Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f797bf6b8 | ||
|
|
d345db927f | ||
|
|
eca7a81f9d | ||
|
|
6f3d7e0f7d | ||
|
|
a8fba73d99 | ||
|
|
669759461d | ||
|
|
38814545c4 | ||
|
|
94c3654240 | ||
|
|
9fa249cc11 | ||
|
|
215c8d0fbb | ||
|
|
3f41eebdf6 | ||
|
|
64e0b2444b | ||
|
|
18fede78f8 | ||
|
|
243d68ab59 | ||
|
|
62c1393f62 | ||
|
|
f0a8299133 | ||
|
|
e36f6da926 | ||
|
|
4a8c2a9fd9 | ||
|
|
248b2e4eca | ||
|
|
1d1ebd2176 | ||
|
|
4252f9a42b | ||
|
|
4fdeedab45 | ||
|
|
866a5be126 | ||
|
|
11d39af934 | ||
|
|
f706531534 | ||
|
|
a839eac4c1 | ||
|
|
581d28e9ce | ||
|
|
2ba39b8174 | ||
|
|
6af55a44c9 | ||
|
|
24badc39d7 | ||
|
|
f5e0baaab6 | ||
|
|
178c84ba60 | ||
|
|
713d40a876 | ||
|
|
9db1964038 | ||
|
|
1ca42055b0 | ||
|
|
c04bda7368 | ||
|
|
1f47843699 | ||
|
|
dca738db82 | ||
|
|
57f364ad0f | ||
|
|
a826153bb5 | ||
|
|
72bd22a707 | ||
|
|
cc73d80dbc | ||
|
|
f0a5b15442 | ||
|
|
eefe5630f4 | ||
|
|
b0ea771e6a | ||
|
|
eb21405a3d | ||
|
|
8ea10ef808 | ||
|
|
ac7da807bd | ||
|
|
3eafc597c6 | ||
|
|
f7a4126718 | ||
|
|
c6cf953ede | ||
|
|
d902202fe9 | ||
|
|
acc80920f9 | ||
|
|
53246af629 | ||
|
|
bd87e94472 | ||
|
|
7ccbb68ffa | ||
|
|
4a7fc7c534 | ||
|
|
f4343ae114 | ||
|
|
0da02dfeb5 | ||
|
|
5f13242cfa | ||
|
|
b492292642 | ||
|
|
ce8ba88b16 | ||
|
|
02b6df5e3b | ||
|
|
6cc4f2759d | ||
|
|
3ea92be722 | ||
|
|
42f8ae0c47 | ||
|
|
148b575767 | ||
|
|
605efacece | ||
|
|
1ccd7749d0 | ||
|
|
b3ba3c8de5 | ||
|
|
4a65b669bd | ||
|
|
aaec443140 | ||
|
|
3cdf1571c5 | ||
|
|
36b934e835 | ||
|
|
5027d0c919 |
@@ -11,6 +11,8 @@ services:
|
|||||||
|
|
||||||
edge-broker:
|
edge-broker:
|
||||||
container_name: "${COMPOSE_PROJECT_NAME:-api}-edge-broker"
|
container_name: "${COMPOSE_PROJECT_NAME:-api}-edge-broker"
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${EDGE_BROKER_CI_PORT:-14300}:4300"
|
||||||
labels:
|
labels:
|
||||||
- "traefik.http.routers.edge-broker-local-ci.rule=PathPrefix(`/api/edge-broker`)"
|
- "traefik.http.routers.edge-broker-local-ci.rule=PathPrefix(`/api/edge-broker`)"
|
||||||
- "traefik.http.routers.edge-broker-local-ci.entrypoints=web"
|
- "traefik.http.routers.edge-broker-local-ci.entrypoints=web"
|
||||||
@@ -80,3 +82,9 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
ci_php_app:
|
ci_php_app:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
ipam:
|
||||||
|
config:
|
||||||
|
- subnet: "${CI_DOCKER_SUBNET:-10.240.0.0/24}"
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
qodana:
|
qodana:
|
||||||
# CI runs on the repository's self-hosted runner pool.
|
# CI runs on the repository's self-hosted runner pool.
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend, docker]
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
pull-requests: read
|
pull-requests: read
|
||||||
|
|||||||
+97
-40
@@ -7,7 +7,7 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
php:
|
php:
|
||||||
name: PHP ${{ matrix.suite }} (required)
|
name: PHP ${{ matrix.suite }} (required)
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend, docker]
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -19,6 +19,20 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Ensure Docker access
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if docker ps >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
test -S /var/run/docker.sock || (echo "Docker socket is not available." >&2; exit 1)
|
||||||
|
if command -v sudo >/dev/null 2>&1; then
|
||||||
|
sudo -n chmod 666 /var/run/docker.sock
|
||||||
|
else
|
||||||
|
chmod 666 /var/run/docker.sock
|
||||||
|
fi
|
||||||
|
docker ps >/dev/null
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
if: ${{ matrix.suite == 'unit' }}
|
if: ${{ matrix.suite == 'unit' }}
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
@@ -44,7 +58,7 @@ jobs:
|
|||||||
|
|
||||||
edge-agent:
|
edge-agent:
|
||||||
name: Edge Agent (required)
|
name: Edge Agent (required)
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -54,8 +68,6 @@ jobs:
|
|||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: services/edge-agent/package-lock.json
|
|
||||||
|
|
||||||
- name: Install native build tools
|
- name: Install native build tools
|
||||||
run: |
|
run: |
|
||||||
@@ -91,12 +103,26 @@ jobs:
|
|||||||
|
|
||||||
edge-broker:
|
edge-broker:
|
||||||
name: Edge Broker (required)
|
name: Edge Broker (required)
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend, docker]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Ensure Docker access
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if docker ps >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
test -S /var/run/docker.sock || (echo "Docker socket is not available." >&2; exit 1)
|
||||||
|
if command -v sudo >/dev/null 2>&1; then
|
||||||
|
sudo -n chmod 666 /var/run/docker.sock
|
||||||
|
else
|
||||||
|
chmod 666 /var/run/docker.sock
|
||||||
|
fi
|
||||||
|
docker ps >/dev/null
|
||||||
|
|
||||||
- name: Materialize CI compose env files
|
- name: Materialize CI compose env files
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -112,8 +138,6 @@ jobs:
|
|||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: services/edge-broker/package-lock.json
|
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
working-directory: services/edge-broker
|
working-directory: services/edge-broker
|
||||||
@@ -125,26 +149,83 @@ jobs:
|
|||||||
|
|
||||||
edge-gateway-backend:
|
edge-gateway-backend:
|
||||||
name: Edge Gateway Backend (required)
|
name: Edge Gateway Backend (required)
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend, docker]
|
||||||
env:
|
env:
|
||||||
COMPOSE_FILE: docker-compose.yml:.github/docker-compose.ci.yml
|
COMPOSE_FILE: docker-compose.yml:.github/docker-compose.ci.yml
|
||||||
COMPOSE_PROJECT_NAME: edge-gateway-backend-${{ github.run_id }}-${{ github.run_attempt }}
|
COMPOSE_PROJECT_NAME: edge-gateway-backend-${{ github.run_id }}-${{ github.run_attempt }}
|
||||||
|
COMPOSE_PROFILES: dev
|
||||||
TRAEFIK_WEB_PORT: "18080"
|
TRAEFIK_WEB_PORT: "18080"
|
||||||
TRAEFIK_WEBSECURE_PORT: "18443"
|
TRAEFIK_WEBSECURE_PORT: "18443"
|
||||||
TRAEFIK_WEBSECURE_STAGING_PORT: "18433"
|
TRAEFIK_WEBSECURE_STAGING_PORT: "18433"
|
||||||
TRAEFIK_METRICS_PORT: "19100"
|
TRAEFIK_METRICS_PORT: "19100"
|
||||||
|
EDGE_BROKER_CI_PORT: "14300"
|
||||||
EDGE_GATEWAY_E2E_BASE_URL: "http://localhost:18080/api"
|
EDGE_GATEWAY_E2E_BASE_URL: "http://localhost:18080/api"
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Ensure Docker access
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if docker ps >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
test -S /var/run/docker.sock || (echo "Docker socket is not available." >&2; exit 1)
|
||||||
|
if command -v sudo >/dev/null 2>&1; then
|
||||||
|
sudo -n chmod 666 /var/run/docker.sock
|
||||||
|
else
|
||||||
|
chmod 666 /var/run/docker.sock
|
||||||
|
fi
|
||||||
|
docker ps >/dev/null
|
||||||
|
|
||||||
|
- name: Allocate CI ports
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
find_free_port() {
|
||||||
|
start="$1"
|
||||||
|
end="$2"
|
||||||
|
port="$start"
|
||||||
|
while [ "$port" -le "$end" ]; do
|
||||||
|
if ! ss -H -ltn "sport = :$port" 2>/dev/null | grep -q .; then
|
||||||
|
echo "$port"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
port=$((port + 1))
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "No free port in range ${start}-${end}." >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
base=$((20000 + (GITHUB_RUN_ID % 20000)))
|
||||||
|
web_port="$(find_free_port "$base" "$((base + 2000))")"
|
||||||
|
websecure_port="$(find_free_port "$((web_port + 1))" "$((web_port + 2000))")"
|
||||||
|
staging_port="$(find_free_port "$((websecure_port + 1))" "$((websecure_port + 2000))")"
|
||||||
|
metrics_port="$(find_free_port "$((staging_port + 1))" "$((staging_port + 2000))")"
|
||||||
|
broker_port="$(find_free_port "$((metrics_port + 1))" "$((metrics_port + 2000))")"
|
||||||
|
checksum="$(printf '%s' "$COMPOSE_PROJECT_NAME" | cksum | awk '{print $1}')"
|
||||||
|
subnet_second=$((64 + ((checksum / 256) % 64)))
|
||||||
|
subnet_third=$((checksum % 256))
|
||||||
|
ci_docker_subnet="10.${subnet_second}.${subnet_third}.0/24"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "TRAEFIK_WEB_PORT=${web_port}"
|
||||||
|
echo "TRAEFIK_WEBSECURE_PORT=${websecure_port}"
|
||||||
|
echo "TRAEFIK_WEBSECURE_STAGING_PORT=${staging_port}"
|
||||||
|
echo "TRAEFIK_METRICS_PORT=${metrics_port}"
|
||||||
|
echo "EDGE_BROKER_CI_PORT=${broker_port}"
|
||||||
|
echo "CI_DOCKER_SUBNET=${ci_docker_subnet}"
|
||||||
|
echo "EDGE_GATEWAY_E2E_BASE_URL=http://localhost:${web_port}/api"
|
||||||
|
echo "EDGE_GATEWAY_E2E_COMPOSE_PROJECT=${COMPOSE_PROJECT_NAME}"
|
||||||
|
} >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: Materialize CI compose env files
|
- name: Materialize CI compose env files
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cp .github/ci.env .env
|
cp .github/ci.env .env
|
||||||
cp .github/ci.env.staging .env.staging
|
cp .github/ci.env.staging .env.staging
|
||||||
printf '\nEDGE_PUBLIC_BROKER_URL=http://edge-broker:4300\n' >> .env
|
printf '\nEDGE_PUBLIC_BROKER_URL=http://edge-broker:4300/edge-broker\n' >> .env
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
@@ -152,7 +233,7 @@ jobs:
|
|||||||
node-version: 22
|
node-version: 22
|
||||||
|
|
||||||
- name: Boot local stack
|
- name: Boot local stack
|
||||||
run: docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml up -d traefik redis mysql-debug edge-broker php1 php2 php3 php4 php5 caddy
|
run: sh scripts/ci-docker-compose-up.sh traefik redis mysql-debug edge-broker php1 php2 php3 php4 php5 caddy
|
||||||
|
|
||||||
- name: Sync PHP app checkout
|
- name: Sync PHP app checkout
|
||||||
run: >
|
run: >
|
||||||
@@ -161,7 +242,7 @@ jobs:
|
|||||||
--exclude='./.phpunit.cache'
|
--exclude='./.phpunit.cache'
|
||||||
--exclude='./build/logs'
|
--exclude='./build/logs'
|
||||||
-C services/nginx/app -cf - .
|
-C services/nginx/app -cf - .
|
||||||
| docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml exec -T php1 tar -C /var/www/html -xf -
|
| docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml exec -T php1 tar --no-same-owner -C /var/www/html -xf -
|
||||||
|
|
||||||
- name: Resolve dependencies
|
- name: Resolve dependencies
|
||||||
run: |
|
run: |
|
||||||
@@ -246,34 +327,10 @@ jobs:
|
|||||||
vendor/bin/pest tests/Integration/EdgeGateway --colors=always"
|
vendor/bin/pest tests/Integration/EdgeGateway --colors=always"
|
||||||
|
|
||||||
- name: Run edge gateway E2E smoke
|
- name: Run edge gateway E2E smoke
|
||||||
run: |
|
env:
|
||||||
set -euo pipefail
|
EDGE_GATEWAY_E2E_COPY_CONFIG: "true"
|
||||||
compose_project="${COMPOSE_PROJECT_NAME:-$(basename "$PWD")}"
|
EDGE_GATEWAY_E2E_SKIP_COMPOSE_UP: "true"
|
||||||
runner="edge-e2e-runner-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
run: node scripts/edge-gateway-e2e.mjs
|
||||||
docker rm -f "$runner" >/dev/null 2>&1 || true
|
|
||||||
trap 'docker rm -f "$runner" >/dev/null 2>&1 || true' EXIT
|
|
||||||
docker create \
|
|
||||||
--name "$runner" \
|
|
||||||
--network "${compose_project}_default" \
|
|
||||||
-e COMPOSE_FILE="$COMPOSE_FILE" \
|
|
||||||
-e COMPOSE_PROJECT_NAME="$compose_project" \
|
|
||||||
-e TRAEFIK_WEB_PORT="${TRAEFIK_WEB_PORT:-18080}" \
|
|
||||||
-e TRAEFIK_WEBSECURE_PORT="${TRAEFIK_WEBSECURE_PORT:-18443}" \
|
|
||||||
-e TRAEFIK_WEBSECURE_STAGING_PORT="${TRAEFIK_WEBSECURE_STAGING_PORT:-18433}" \
|
|
||||||
-e TRAEFIK_METRICS_PORT="${TRAEFIK_METRICS_PORT:-19100}" \
|
|
||||||
-e EDGE_GATEWAY_E2E_BASE_URL="http://caddy" \
|
|
||||||
-e EDGE_GATEWAY_E2E_COMPOSE_PROJECT="$compose_project" \
|
|
||||||
-e EDGE_GATEWAY_E2E_COPY_CONFIG="true" \
|
|
||||||
-e EDGE_GATEWAY_E2E_SKIP_COMPOSE_UP="true" \
|
|
||||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
|
||||||
-w /workspace \
|
|
||||||
node:22-alpine \
|
|
||||||
sh -lc "apk add --no-cache docker-cli docker-cli-compose >/dev/null && node scripts/edge-gateway-e2e.mjs"
|
|
||||||
docker cp . "$runner:/workspace"
|
|
||||||
docker start "$runner" >/dev/null
|
|
||||||
docker logs -f "$runner"
|
|
||||||
exit_code="$(docker wait "$runner")"
|
|
||||||
exit "$exit_code"
|
|
||||||
|
|
||||||
- name: Tear down local stack
|
- name: Tear down local stack
|
||||||
if: always()
|
if: always()
|
||||||
@@ -281,7 +338,7 @@ jobs:
|
|||||||
|
|
||||||
release-manager-gate:
|
release-manager-gate:
|
||||||
name: Release Manager gate
|
name: Release Manager gate
|
||||||
runs-on: [self-hosted, Linux, X64, default]
|
runs-on: [self-hosted, Linux, X64, pleno, backend]
|
||||||
needs: [php, edge-agent, edge-broker, edge-gateway-backend]
|
needs: [php, edge-agent, edge-broker, edge-gateway-backend]
|
||||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -13,4 +13,7 @@
|
|||||||
.env.old
|
.env.old
|
||||||
/.tmp/
|
/.tmp/
|
||||||
/.env.staging
|
/.env.staging
|
||||||
/services/nginx/app/storage/replication-bootstrap.json
|
/services/nginx/app/storage/replication-bootstrap.json
|
||||||
|
/.env_old_2
|
||||||
|
/.openclaw/
|
||||||
|
/services/nginx/app/build/phpstan/
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ COPY . /var/www/html
|
|||||||
|
|
||||||
# Copy Nginx configuration file
|
# Copy Nginx configuration file
|
||||||
COPY nginx.conf /etc/nginx/nginx.conf
|
COPY nginx.conf /etc/nginx/nginx.conf
|
||||||
|
COPY services/php/php-fpm-pool.conf /usr/local/etc/php-fpm.d/zz-pleno-workers.conf
|
||||||
|
|
||||||
# Install Composer
|
# Install Composer
|
||||||
COPY --from=composer:2.6 /usr/bin/composer /usr/bin/composer
|
COPY --from=composer:2.6 /usr/bin/composer /usr/bin/composer
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ RUN set -eux; \
|
|||||||
|
|
||||||
COPY services/nginx/app/ /var/www/html/
|
COPY services/nginx/app/ /var/www/html/
|
||||||
COPY services/php/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
COPY services/php/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||||
|
COPY services/php/php-fpm-pool.conf /usr/local/etc/php-fpm.d/zz-pleno-workers.conf
|
||||||
COPY services/coolify/api/nginx.conf /etc/nginx/nginx.conf
|
COPY services/coolify/api/nginx.conf /etc/nginx/nginx.conf
|
||||||
COPY services/coolify/api/start.sh /usr/local/bin/coolify-api-start
|
COPY services/coolify/api/start.sh /usr/local/bin/coolify-api-start
|
||||||
|
|
||||||
|
|||||||
+132
-3
@@ -7462,7 +7462,7 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
type: object
|
type: object
|
||||||
required: [reg, type, wash_subscription]
|
required: [reg, type]
|
||||||
properties:
|
properties:
|
||||||
reg:
|
reg:
|
||||||
type: string
|
type: string
|
||||||
@@ -7474,6 +7474,8 @@ paths:
|
|||||||
description: Product ID representing the vehicle wash type
|
description: Product ID representing the vehicle wash type
|
||||||
wash_subscription:
|
wash_subscription:
|
||||||
type: boolean
|
type: boolean
|
||||||
|
default: false
|
||||||
|
description: Defaults to false when omitted.
|
||||||
reference:
|
reference:
|
||||||
type: string
|
type: string
|
||||||
maxLength: 255
|
maxLength: 255
|
||||||
@@ -11665,6 +11667,70 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/ModuleConfigUpdateResponse'
|
$ref: '#/components/schemas/ModuleConfigUpdateResponse'
|
||||||
|
|
||||||
|
/slack/config/test:
|
||||||
|
post:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Test Slack customer registration webhook
|
||||||
|
operationId: testSlackCustomerRegistrationWebhook
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack customer registration webhook test completed successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackConfigTestResponse'
|
||||||
|
'400':
|
||||||
|
description: Slack customer registration webhook URL is not configured
|
||||||
|
'502':
|
||||||
|
description: Slack customer registration webhook test failed
|
||||||
|
|
||||||
|
/slack/config/internal-department-goal-progress:
|
||||||
|
get:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Get Slack internal department goal progress config
|
||||||
|
operationId: getSlackInternalDepartmentGoalProgressConfig
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress configuration retrieved successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigResponse'
|
||||||
|
post:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Update Slack internal department goal progress config
|
||||||
|
operationId: updateSlackInternalDepartmentGoalProgressConfig
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigUpdate'
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress configuration updated successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigResponse'
|
||||||
|
|
||||||
|
/slack/config/internal-department-goal-progress/test:
|
||||||
|
post:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Test Slack internal department goal progress webhook
|
||||||
|
operationId: testSlackInternalDepartmentGoalProgressWebhook
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress webhook test completed successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackConfigTestResponse'
|
||||||
|
'400':
|
||||||
|
description: Slack internal department goal progress webhook URL is not configured
|
||||||
|
'502':
|
||||||
|
description: Slack internal department goal progress webhook test failed
|
||||||
|
|
||||||
/backups/config:
|
/backups/config:
|
||||||
get:
|
get:
|
||||||
tags: [Config]
|
tags: [Config]
|
||||||
@@ -15183,12 +15249,59 @@ components:
|
|||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
module: { type: string, enum: [Slack] }
|
module: { type: string, enum: [Slack] }
|
||||||
variable: { type: string, enum: [customer_registration_webhook_url] }
|
variable: { type: string, enum: [customer_registration_webhook_url, internal_department_goal_progress_webhook_url, internal_department_ids] }
|
||||||
type: { type: string, enum: [string] }
|
type: { type: string, enum: [string] }
|
||||||
value:
|
value:
|
||||||
|
oneOf:
|
||||||
|
- type: string
|
||||||
|
example: https://hooks.slack.com/services/...
|
||||||
|
- type: string
|
||||||
|
example: '[1,2,3]'
|
||||||
|
required: [module, variable, type, value]
|
||||||
|
|
||||||
|
SlackConfigTestResult:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
configured: { type: boolean }
|
||||||
|
sent: { type: boolean }
|
||||||
|
message: { type: string }
|
||||||
|
required: [configured, sent, message]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressDepartment:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id: { type: integer }
|
||||||
|
name: { type: string }
|
||||||
|
order_priority: { type: integer }
|
||||||
|
required: [id, name, order_priority]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfig:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
internal_department_goal_progress_webhook_url:
|
||||||
type: string
|
type: string
|
||||||
example: https://hooks.slack.com/services/...
|
example: https://hooks.slack.com/services/...
|
||||||
required: [module, variable, type, value]
|
internal_department_ids:
|
||||||
|
type: array
|
||||||
|
items: { type: integer }
|
||||||
|
example: [1, 2, 3]
|
||||||
|
departments:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressDepartment'
|
||||||
|
required: [internal_department_goal_progress_webhook_url, internal_department_ids, departments]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfigUpdate:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
internal_department_goal_progress_webhook_url:
|
||||||
|
type: string
|
||||||
|
example: https://hooks.slack.com/services/...
|
||||||
|
internal_department_ids:
|
||||||
|
type: array
|
||||||
|
items: { type: integer }
|
||||||
|
example: [1, 2, 3]
|
||||||
|
required: [internal_department_goal_progress_webhook_url, internal_department_ids]
|
||||||
|
|
||||||
BackupsConfigEntry:
|
BackupsConfigEntry:
|
||||||
type: object
|
type: object
|
||||||
@@ -15466,6 +15579,22 @@ components:
|
|||||||
data: { type: array, items: { $ref: '#/components/schemas/SlackConfigEntry' } }
|
data: { type: array, items: { $ref: '#/components/schemas/SlackConfigEntry' } }
|
||||||
required: [data]
|
required: [data]
|
||||||
|
|
||||||
|
SlackConfigTestResponse:
|
||||||
|
allOf:
|
||||||
|
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||||
|
- type: object
|
||||||
|
properties:
|
||||||
|
data: { $ref: '#/components/schemas/SlackConfigTestResult' }
|
||||||
|
required: [data]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfigResponse:
|
||||||
|
allOf:
|
||||||
|
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||||
|
- type: object
|
||||||
|
properties:
|
||||||
|
data: { $ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfig' }
|
||||||
|
required: [data]
|
||||||
|
|
||||||
BackupsConfigListResponse:
|
BackupsConfigListResponse:
|
||||||
allOf:
|
allOf:
|
||||||
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
if [ "$#" -eq 0 ]; then
|
||||||
|
echo "Usage: $0 <service> [service ...]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
compose_files="${CI_DOCKER_COMPOSE_FILES:--f docker-compose.yml -f .github/docker-compose.ci.yml}"
|
||||||
|
lock_file="${CI_DOCKER_LOCK_FILE:-/tmp/pleno-api-ci-docker-compose-up.lock}"
|
||||||
|
max_attempts="${CI_DOCKER_UP_RETRIES:-${PHP_CI_DOCKER_RETRIES:-3}}"
|
||||||
|
export COMPOSE_PROFILES="${COMPOSE_PROFILES:-dev}"
|
||||||
|
|
||||||
|
compose_up() {
|
||||||
|
attempt=1
|
||||||
|
while :; do
|
||||||
|
docker network prune -f >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
if docker compose $compose_files up -d "$@"; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
status="$?"
|
||||||
|
docker compose $compose_files down -v --remove-orphans >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
if [ "$attempt" -ge "$max_attempts" ]; then
|
||||||
|
return "$status"
|
||||||
|
fi
|
||||||
|
|
||||||
|
sleep_seconds=$((attempt * 5))
|
||||||
|
echo "Docker compose up failed with status $status; retrying in ${sleep_seconds}s (attempt $((attempt + 1))/$max_attempts)." >&2
|
||||||
|
sleep "$sleep_seconds"
|
||||||
|
attempt=$((attempt + 1))
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
if command -v flock >/dev/null 2>&1; then
|
||||||
|
(
|
||||||
|
flock 9
|
||||||
|
compose_up "$@"
|
||||||
|
) 9>"$lock_file"
|
||||||
|
else
|
||||||
|
echo "flock is not available; running Docker compose startup without a host lock." >&2
|
||||||
|
compose_up "$@"
|
||||||
|
fi
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import crypto from "node:crypto";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
|
import net from "node:net";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import process from "node:process";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
const DEFAULT_AGENT_PATH = path.join(
|
||||||
|
repoRoot,
|
||||||
|
"services/nginx/app/resources/edge-gateway-agent/agent.php"
|
||||||
|
);
|
||||||
|
const DEFAULT_PHP_IMAGE = "php:8.2-cli-bookworm";
|
||||||
|
const DEFAULT_TIMEOUT_MS = 12000;
|
||||||
|
|
||||||
|
function parseArgs(argv = process.argv.slice(2)) {
|
||||||
|
const options = {
|
||||||
|
agentPath: DEFAULT_AGENT_PATH,
|
||||||
|
phpImage: DEFAULT_PHP_IMAGE,
|
||||||
|
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||||
|
keepTemp: false,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const arg = argv[index];
|
||||||
|
const next = argv[index + 1];
|
||||||
|
|
||||||
|
switch (arg) {
|
||||||
|
case "--agent-path":
|
||||||
|
options.agentPath = path.resolve(String(next || "").trim());
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--php-image":
|
||||||
|
options.phpImage = String(next || "").trim() || DEFAULT_PHP_IMAGE;
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--timeout-ms":
|
||||||
|
options.timeoutMs = Number.parseInt(String(next || ""), 10) || DEFAULT_TIMEOUT_MS;
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--keep-temp":
|
||||||
|
options.keepTemp = true;
|
||||||
|
break;
|
||||||
|
case "--help":
|
||||||
|
case "-h":
|
||||||
|
options.help = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function printUsage() {
|
||||||
|
process.stdout.write(`Usage:
|
||||||
|
node scripts/edge-agent-command-drain-proof.mjs [options]
|
||||||
|
|
||||||
|
Verifies that a broker-connected PHP compose edge agent still drains API-queued
|
||||||
|
SET_RELAY_STATE jobs to the LAN worker /relay/switch endpoint.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--agent-path <path> PHP agent artifact to execute.
|
||||||
|
Default: ${DEFAULT_AGENT_PATH}
|
||||||
|
--php-image <image> Docker PHP image with curl, sqlite3, and pdo_sqlite.
|
||||||
|
Default: ${DEFAULT_PHP_IMAGE}
|
||||||
|
--timeout-ms <ms> Proof timeout. Default: ${DEFAULT_TIMEOUT_MS}
|
||||||
|
--keep-temp Keep the temporary config/runtime directory.
|
||||||
|
--help Show this help text.
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJson(request) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let raw = "";
|
||||||
|
request.setEncoding("utf8");
|
||||||
|
request.on("data", (chunk) => {
|
||||||
|
raw += chunk;
|
||||||
|
});
|
||||||
|
request.on("end", () => {
|
||||||
|
if (raw.trim() === "") {
|
||||||
|
resolve({});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(raw));
|
||||||
|
} catch {
|
||||||
|
resolve({ __invalid: raw });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendJson(response, status, payload) {
|
||||||
|
const body = JSON.stringify(payload);
|
||||||
|
response.writeHead(status, {
|
||||||
|
"content-type": "application/json; charset=utf-8",
|
||||||
|
"content-length": Buffer.byteLength(body),
|
||||||
|
});
|
||||||
|
response.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listen(server) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
server.listen(0, "127.0.0.1", () => resolve(server.address().port));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeServer(server) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
server.close(() => resolve());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function websocketAcceptKey(key) {
|
||||||
|
return crypto
|
||||||
|
.createHash("sha1")
|
||||||
|
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
|
||||||
|
.digest("base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBrokerServer(state) {
|
||||||
|
const sockets = new Set();
|
||||||
|
const server = net.createServer((socket) => {
|
||||||
|
sockets.add(socket);
|
||||||
|
socket.on("close", () => sockets.delete(socket));
|
||||||
|
|
||||||
|
let buffer = "";
|
||||||
|
socket.on("data", (chunk) => {
|
||||||
|
buffer += chunk.toString("binary");
|
||||||
|
if (state.brokerHandshakeSeen || !buffer.includes("\r\n\r\n")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestText = Buffer.from(buffer, "binary").toString("utf8");
|
||||||
|
const key = requestText.match(/Sec-WebSocket-Key:\s*(.+)\r\n/i)?.[1]?.trim();
|
||||||
|
const requestLine = requestText.split("\r\n")[0] || "";
|
||||||
|
if (!requestLine.includes("/ws/agent?")) {
|
||||||
|
state.failure = new Error(`unexpected broker path: ${requestLine}`);
|
||||||
|
}
|
||||||
|
if (!key) {
|
||||||
|
state.failure = new Error("broker handshake missing Sec-WebSocket-Key");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.write([
|
||||||
|
"HTTP/1.1 101 Switching Protocols",
|
||||||
|
"Upgrade: websocket",
|
||||||
|
"Connection: Upgrade",
|
||||||
|
`Sec-WebSocket-Accept: ${websocketAcceptKey(key)}`,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
].join("\r\n"));
|
||||||
|
state.brokerHandshakeSeen = true;
|
||||||
|
buffer = "";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return { server, sockets };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createWorkerServer(state) {
|
||||||
|
return http.createServer(async (request, response) => {
|
||||||
|
const url = new URL(request.url, "http://127.0.0.1");
|
||||||
|
const body = await readJson(request);
|
||||||
|
state.requests.push({ service: "worker", method: request.method, path: url.pathname, body });
|
||||||
|
|
||||||
|
if (request.method === "GET" && url.pathname === "/health") {
|
||||||
|
sendJson(response, 200, { status: "healthy", timestamp: new Date().toISOString() });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/relay/switch") {
|
||||||
|
state.relaySwitchSeen = true;
|
||||||
|
if (body.local_ip !== "10.123.0.31" || body.channel !== 0 || body.on !== true) {
|
||||||
|
state.failure = new Error(`unexpected relay switch payload: ${JSON.stringify(body)}`);
|
||||||
|
}
|
||||||
|
sendJson(response, 200, {
|
||||||
|
online: true,
|
||||||
|
on: true,
|
||||||
|
output: true,
|
||||||
|
raw: { source: "fake-worker" },
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 404, { message: "not found" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createApiServer(state, brokerPort, workerPort) {
|
||||||
|
return http.createServer(async (request, response) => {
|
||||||
|
const url = new URL(request.url, "http://127.0.0.1");
|
||||||
|
const body = await readJson(request);
|
||||||
|
state.requests.push({ service: "api", method: request.method, path: url.pathname, body });
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/heartbeat") {
|
||||||
|
sendJson(response, 200, { data: { ok: true, broker_url: `ws://127.0.0.1:${brokerPort}` } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/selfserve/machine-signal-bindings") {
|
||||||
|
sendJson(response, 200, { data: { monitors: [] } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/commands/poll") {
|
||||||
|
state.commandPollSeen = true;
|
||||||
|
if (body.wait_seconds !== 0) {
|
||||||
|
state.failure = new Error(
|
||||||
|
`broker-connected command poll should be non-blocking, got wait_seconds=${body.wait_seconds}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.commandDelivered) {
|
||||||
|
state.commandDelivered = true;
|
||||||
|
sendJson(response, 200, {
|
||||||
|
data: {
|
||||||
|
id: 77,
|
||||||
|
command_type: "SET_RELAY_STATE",
|
||||||
|
payload: {
|
||||||
|
localIp: "10.123.0.31",
|
||||||
|
channel: 0,
|
||||||
|
on: true,
|
||||||
|
relayId: "relay-proof",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 200, { data: null });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/commands/77/result") {
|
||||||
|
state.resultSeen = true;
|
||||||
|
if (body.ok !== true || body.result?.on !== true || body.result?.raw?.source !== "fake-worker") {
|
||||||
|
state.failure = new Error(`unexpected command result: ${JSON.stringify(body)}`);
|
||||||
|
}
|
||||||
|
sendJson(response, 200, { data: { acknowledged: true } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 404, { message: "not found", path: url.pathname, workerPort });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeConfig(tempDir, apiPort, brokerPort, workerPort) {
|
||||||
|
const containerProofDir = "/proof";
|
||||||
|
const runtimeDir = `${containerProofDir}/runtime`;
|
||||||
|
const config = {
|
||||||
|
apiUrl: `http://127.0.0.1:${apiPort}`,
|
||||||
|
brokerUrl: `ws://127.0.0.1:${brokerPort}`,
|
||||||
|
gatewayId: 42,
|
||||||
|
agentToken: "agent-token",
|
||||||
|
installDir: containerProofDir,
|
||||||
|
runtimeDir,
|
||||||
|
stateDatabasePath: `${runtimeDir}/gateway-state.sqlite`,
|
||||||
|
workerBaseUrl: `http://127.0.0.1:${workerPort}`,
|
||||||
|
heartbeatIntervalSeconds: 60,
|
||||||
|
operationPollTimeoutSeconds: 20,
|
||||||
|
};
|
||||||
|
|
||||||
|
const configPath = path.join(tempDir, "config.json");
|
||||||
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
||||||
|
return { configPath, containerConfigPath: `${containerProofDir}/config.json` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnAgent({ agentPath, phpImage, tempDir, containerConfigPath }) {
|
||||||
|
return spawn("docker", [
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--network",
|
||||||
|
"host",
|
||||||
|
"-v",
|
||||||
|
`${agentPath}:/agent.php:ro`,
|
||||||
|
"-v",
|
||||||
|
`${tempDir}:/proof`,
|
||||||
|
phpImage,
|
||||||
|
"php",
|
||||||
|
"/agent.php",
|
||||||
|
"--config",
|
||||||
|
containerConfigPath,
|
||||||
|
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopChild(child) {
|
||||||
|
if (child.exitCode !== null || child.signalCode !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
const hardKill = setTimeout(() => {
|
||||||
|
if (child.exitCode === null && child.signalCode === null) {
|
||||||
|
child.kill("SIGKILL");
|
||||||
|
}
|
||||||
|
}, 1500);
|
||||||
|
|
||||||
|
await Promise.race([
|
||||||
|
new Promise((resolve) => child.once("exit", resolve)),
|
||||||
|
new Promise((resolve) => setTimeout(resolve, 2200)),
|
||||||
|
]);
|
||||||
|
clearTimeout(hardKill);
|
||||||
|
}
|
||||||
|
|
||||||
|
function evidenceFromState(state, childExited) {
|
||||||
|
return {
|
||||||
|
brokerHandshakeSeen: state.brokerHandshakeSeen,
|
||||||
|
commandPollSeen: state.commandPollSeen,
|
||||||
|
relaySwitchSeen: state.relaySwitchSeen,
|
||||||
|
resultSeen: state.resultSeen,
|
||||||
|
agentStayedRunningUntilProofComplete: !childExited,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runProof(options) {
|
||||||
|
if (process.platform !== "linux") {
|
||||||
|
throw new Error("This proof uses Docker --network host and currently expects Linux.");
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(options.agentPath)) {
|
||||||
|
throw new Error(`Agent artifact not found: ${options.agentPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "edge-agent-command-drain-proof-"));
|
||||||
|
fs.mkdirSync(path.join(tempDir, "runtime"), { recursive: true });
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
brokerHandshakeSeen: false,
|
||||||
|
commandPollSeen: false,
|
||||||
|
relaySwitchSeen: false,
|
||||||
|
resultSeen: false,
|
||||||
|
commandDelivered: false,
|
||||||
|
failure: null,
|
||||||
|
requests: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const broker = createBrokerServer(state);
|
||||||
|
const workerServer = createWorkerServer(state);
|
||||||
|
let apiServer = null;
|
||||||
|
let child = null;
|
||||||
|
let stdout = "";
|
||||||
|
let stderr = "";
|
||||||
|
let childExited = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const brokerPort = await listen(broker.server);
|
||||||
|
const workerPort = await listen(workerServer);
|
||||||
|
apiServer = createApiServer(state, brokerPort, workerPort);
|
||||||
|
const apiPort = await listen(apiServer);
|
||||||
|
const { containerConfigPath } = writeConfig(tempDir, apiPort, brokerPort, workerPort);
|
||||||
|
|
||||||
|
child = spawnAgent({ ...options, tempDir, containerConfigPath });
|
||||||
|
child.stdout.on("data", (chunk) => {
|
||||||
|
stdout += chunk.toString();
|
||||||
|
});
|
||||||
|
child.stderr.on("data", (chunk) => {
|
||||||
|
stderr += chunk.toString();
|
||||||
|
});
|
||||||
|
child.once("exit", () => {
|
||||||
|
childExited = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const deadline = Date.now() + options.timeoutMs;
|
||||||
|
while (Date.now() < deadline && !state.failure && !childExited) {
|
||||||
|
if (state.brokerHandshakeSeen && state.commandPollSeen && state.relaySwitchSeen && state.resultSeen) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
const evidence = evidenceFromState(state, childExited);
|
||||||
|
if (
|
||||||
|
state.failure ||
|
||||||
|
!state.brokerHandshakeSeen ||
|
||||||
|
!state.commandPollSeen ||
|
||||||
|
!state.relaySwitchSeen ||
|
||||||
|
!state.resultSeen
|
||||||
|
) {
|
||||||
|
const error = state.failure || new Error("missing proof evidence");
|
||||||
|
error.evidence = evidence;
|
||||||
|
error.requests = state.requests;
|
||||||
|
error.stdout = stdout.slice(-3000);
|
||||||
|
error.stderr = stderr.slice(-3000);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
evidence,
|
||||||
|
agentPath: options.agentPath,
|
||||||
|
phpImage: options.phpImage,
|
||||||
|
tempDir,
|
||||||
|
requestCount: state.requests.length,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
if (child) {
|
||||||
|
await stopChild(child);
|
||||||
|
}
|
||||||
|
for (const socket of broker.sockets) {
|
||||||
|
socket.destroy();
|
||||||
|
}
|
||||||
|
await Promise.allSettled([
|
||||||
|
closeServer(broker.server),
|
||||||
|
closeServer(workerServer),
|
||||||
|
apiServer ? closeServer(apiServer) : Promise.resolve(),
|
||||||
|
]);
|
||||||
|
if (!options.keepTemp) {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs();
|
||||||
|
if (options.help) {
|
||||||
|
printUsage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await runProof(options);
|
||||||
|
process.stdout.write("PASS broker-connected API command poll triggered local relay switch and posted result\n");
|
||||||
|
process.stdout.write(`${JSON.stringify(result.evidence)}\n`);
|
||||||
|
process.stdout.write(`Agent: ${result.agentPath}\n`);
|
||||||
|
process.stdout.write(`PHP image: ${result.phpImage}\n`);
|
||||||
|
if (options.keepTemp) {
|
||||||
|
process.stdout.write(`Temp dir: ${result.tempDir}\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||||
|
main().catch((error) => {
|
||||||
|
process.stderr.write(`FAIL ${error.message}\n`);
|
||||||
|
if (error.evidence) {
|
||||||
|
process.stderr.write(`Evidence: ${JSON.stringify(error.evidence)}\n`);
|
||||||
|
}
|
||||||
|
if (error.requests) {
|
||||||
|
process.stderr.write(`Requests: ${JSON.stringify(error.requests, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
if (error.stdout) {
|
||||||
|
process.stderr.write(`stdout: ${error.stdout}\n`);
|
||||||
|
}
|
||||||
|
if (error.stderr) {
|
||||||
|
process.stderr.write(`stderr: ${error.stderr}\n`);
|
||||||
|
}
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,619 @@
|
|||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import crypto from "node:crypto";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
|
import net from "node:net";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import process from "node:process";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
const DEFAULT_AGENT_PATH = path.join(
|
||||||
|
repoRoot,
|
||||||
|
"services/nginx/app/resources/edge-gateway-agent/agent.php"
|
||||||
|
);
|
||||||
|
const DEFAULT_WORKER_PATH = path.join(
|
||||||
|
repoRoot,
|
||||||
|
"services/nginx/app/resources/edge-gateway-agent/lan-worker.php"
|
||||||
|
);
|
||||||
|
const DEFAULT_PHP_IMAGE = "php:8.2-cli-bookworm";
|
||||||
|
const DEFAULT_TIMEOUT_MS = 15000;
|
||||||
|
const AGENT_TOKEN = "agent-token";
|
||||||
|
|
||||||
|
function parseArgs(argv = process.argv.slice(2)) {
|
||||||
|
const options = {
|
||||||
|
agentPath: DEFAULT_AGENT_PATH,
|
||||||
|
workerPath: DEFAULT_WORKER_PATH,
|
||||||
|
phpImage: DEFAULT_PHP_IMAGE,
|
||||||
|
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||||
|
keepTemp: false,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const arg = argv[index];
|
||||||
|
const next = argv[index + 1];
|
||||||
|
|
||||||
|
switch (arg) {
|
||||||
|
case "--agent-path":
|
||||||
|
options.agentPath = path.resolve(String(next || "").trim());
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--worker-path":
|
||||||
|
options.workerPath = path.resolve(String(next || "").trim());
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--php-image":
|
||||||
|
options.phpImage = String(next || "").trim() || DEFAULT_PHP_IMAGE;
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--timeout-ms":
|
||||||
|
options.timeoutMs = Number.parseInt(String(next || ""), 10) || DEFAULT_TIMEOUT_MS;
|
||||||
|
index += 1;
|
||||||
|
break;
|
||||||
|
case "--keep-temp":
|
||||||
|
options.keepTemp = true;
|
||||||
|
break;
|
||||||
|
case "--help":
|
||||||
|
case "-h":
|
||||||
|
options.help = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function printUsage() {
|
||||||
|
process.stdout.write(`Usage:
|
||||||
|
node scripts/edge-agent-to-shelly-proof.mjs [options]
|
||||||
|
|
||||||
|
Runs the PHP edge agent and real LAN worker against fake broker, API, and
|
||||||
|
Shelly RPC endpoints. Verifies that a broker-connected SET_RELAY_STATE command
|
||||||
|
drains from the API, reaches the worker, triggers a Shelly-style Switch.Set
|
||||||
|
call, reads Switch.GetStatus, and posts the command result.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--agent-path <path> PHP agent artifact to execute.
|
||||||
|
Default: ${DEFAULT_AGENT_PATH}
|
||||||
|
--worker-path <path> PHP LAN worker artifact to execute.
|
||||||
|
Default: ${DEFAULT_WORKER_PATH}
|
||||||
|
--php-image <image> Docker PHP image with curl, sqlite3, and pdo_sqlite.
|
||||||
|
Default: ${DEFAULT_PHP_IMAGE}
|
||||||
|
--timeout-ms <ms> Proof timeout. Default: ${DEFAULT_TIMEOUT_MS}
|
||||||
|
--keep-temp Keep the temporary config/runtime directory.
|
||||||
|
--help Show this help text.
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJson(request) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let raw = "";
|
||||||
|
request.setEncoding("utf8");
|
||||||
|
request.on("data", (chunk) => {
|
||||||
|
raw += chunk;
|
||||||
|
});
|
||||||
|
request.on("end", () => {
|
||||||
|
if (raw.trim() === "") {
|
||||||
|
resolve({});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(raw));
|
||||||
|
} catch {
|
||||||
|
resolve({ __invalid: raw });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendJson(response, status, payload) {
|
||||||
|
const body = JSON.stringify(payload);
|
||||||
|
response.writeHead(status, {
|
||||||
|
"content-type": "application/json; charset=utf-8",
|
||||||
|
"content-length": Buffer.byteLength(body),
|
||||||
|
});
|
||||||
|
response.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestJson({ method = "GET", port, path: requestPath, body = null, headers = {} }) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const payload = body === null ? null : JSON.stringify(body);
|
||||||
|
const request = http.request({
|
||||||
|
hostname: "127.0.0.1",
|
||||||
|
port,
|
||||||
|
path: requestPath,
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
accept: "application/json",
|
||||||
|
...(payload === null ? {} : {
|
||||||
|
"content-type": "application/json",
|
||||||
|
"content-length": Buffer.byteLength(payload),
|
||||||
|
}),
|
||||||
|
...headers,
|
||||||
|
},
|
||||||
|
timeout: 1000,
|
||||||
|
}, (response) => {
|
||||||
|
let raw = "";
|
||||||
|
response.setEncoding("utf8");
|
||||||
|
response.on("data", (chunk) => {
|
||||||
|
raw += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", () => {
|
||||||
|
let decoded = {};
|
||||||
|
try {
|
||||||
|
decoded = raw.trim() === "" ? {} : JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
decoded = { __invalid: raw };
|
||||||
|
}
|
||||||
|
resolve({ status: response.statusCode || 0, body: decoded });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
request.on("error", reject);
|
||||||
|
request.on("timeout", () => {
|
||||||
|
request.destroy(new Error("request timed out"));
|
||||||
|
});
|
||||||
|
if (payload !== null) {
|
||||||
|
request.write(payload);
|
||||||
|
}
|
||||||
|
request.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function listen(server) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
server.listen(0, "127.0.0.1", () => resolve(server.address().port));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeServer(server) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
server.close(() => resolve());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reservePort() {
|
||||||
|
const server = net.createServer();
|
||||||
|
const port = await new Promise((resolve) => {
|
||||||
|
server.listen(0, "127.0.0.1", () => resolve(server.address().port));
|
||||||
|
});
|
||||||
|
await closeServer(server);
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
function websocketAcceptKey(key) {
|
||||||
|
return crypto
|
||||||
|
.createHash("sha1")
|
||||||
|
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
|
||||||
|
.digest("base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBrokerServer(state) {
|
||||||
|
const sockets = new Set();
|
||||||
|
const server = net.createServer((socket) => {
|
||||||
|
sockets.add(socket);
|
||||||
|
socket.on("close", () => sockets.delete(socket));
|
||||||
|
|
||||||
|
let buffer = "";
|
||||||
|
socket.on("data", (chunk) => {
|
||||||
|
buffer += chunk.toString("binary");
|
||||||
|
if (state.brokerHandshakeSeen || !buffer.includes("\r\n\r\n")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestText = Buffer.from(buffer, "binary").toString("utf8");
|
||||||
|
const key = requestText.match(/Sec-WebSocket-Key:\s*(.+)\r\n/i)?.[1]?.trim();
|
||||||
|
const requestLine = requestText.split("\r\n")[0] || "";
|
||||||
|
if (!requestLine.includes("/ws/agent?")) {
|
||||||
|
state.failure = new Error(`unexpected broker path: ${requestLine}`);
|
||||||
|
}
|
||||||
|
if (!key) {
|
||||||
|
state.failure = new Error("broker handshake missing Sec-WebSocket-Key");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.write([
|
||||||
|
"HTTP/1.1 101 Switching Protocols",
|
||||||
|
"Upgrade: websocket",
|
||||||
|
"Connection: Upgrade",
|
||||||
|
`Sec-WebSocket-Accept: ${websocketAcceptKey(key)}`,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
].join("\r\n"));
|
||||||
|
state.brokerHandshakeSeen = true;
|
||||||
|
buffer = "";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return { server, sockets };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createShellyServer(state) {
|
||||||
|
return http.createServer((request, response) => {
|
||||||
|
const url = new URL(request.url, "http://127.0.0.1");
|
||||||
|
state.requests.push({
|
||||||
|
service: "shelly",
|
||||||
|
method: request.method,
|
||||||
|
path: url.pathname,
|
||||||
|
query: Object.fromEntries(url.searchParams.entries()),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (request.method === "GET" && url.pathname === "/rpc/Switch.Set") {
|
||||||
|
state.shellySwitchSetSeen = true;
|
||||||
|
if (url.searchParams.get("id") !== "0" || url.searchParams.get("on") !== "true") {
|
||||||
|
state.failure = new Error(`unexpected Shelly Switch.Set query: ${url.search}`);
|
||||||
|
}
|
||||||
|
sendJson(response, 200, { was_on: false, output: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "GET" && url.pathname === "/rpc/Switch.GetStatus") {
|
||||||
|
state.shellyStatusSeen = true;
|
||||||
|
if (url.searchParams.get("id") !== "0") {
|
||||||
|
state.failure = new Error(`unexpected Shelly Switch.GetStatus query: ${url.search}`);
|
||||||
|
}
|
||||||
|
sendJson(response, 200, { id: 0, output: true, source: "fake-shelly-rpc" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname.startsWith("/relay/")) {
|
||||||
|
state.failure = new Error(`legacy Shelly endpoint should not be used for generation 2 proof: ${url.pathname}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 404, { message: "not found" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createApiServer(state, brokerPort, shellyAddress) {
|
||||||
|
return http.createServer(async (request, response) => {
|
||||||
|
const url = new URL(request.url, "http://127.0.0.1");
|
||||||
|
const body = await readJson(request);
|
||||||
|
state.requests.push({ service: "api", method: request.method, path: url.pathname, body });
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/heartbeat") {
|
||||||
|
sendJson(response, 200, { data: { ok: true, broker_url: `ws://127.0.0.1:${brokerPort}` } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/selfserve/machine-signal-bindings") {
|
||||||
|
sendJson(response, 200, { data: { monitors: [] } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/commands/poll") {
|
||||||
|
state.commandPollSeen = true;
|
||||||
|
if (body.wait_seconds !== 0) {
|
||||||
|
state.failure = new Error(
|
||||||
|
`broker-connected command poll should be non-blocking, got wait_seconds=${body.wait_seconds}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.commandDelivered) {
|
||||||
|
state.commandDelivered = true;
|
||||||
|
sendJson(response, 200, {
|
||||||
|
data: {
|
||||||
|
id: 77,
|
||||||
|
command_type: "SET_RELAY_STATE",
|
||||||
|
payload: {
|
||||||
|
localIp: shellyAddress,
|
||||||
|
local_ip: shellyAddress,
|
||||||
|
channel: 0,
|
||||||
|
on: true,
|
||||||
|
relayId: "relay-proof",
|
||||||
|
relay_id: "relay-proof",
|
||||||
|
deviceGeneration: 2,
|
||||||
|
device_generation: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 200, { data: null });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method === "POST" && url.pathname === "/edge-agent/gateways/42/commands/77/result") {
|
||||||
|
state.resultSeen = true;
|
||||||
|
if (
|
||||||
|
body.ok !== true ||
|
||||||
|
body.result?.on !== true ||
|
||||||
|
body.result?.output !== true ||
|
||||||
|
body.result?.raw?.source !== "fake-shelly-rpc"
|
||||||
|
) {
|
||||||
|
state.failure = new Error(`unexpected command result: ${JSON.stringify(body)}`);
|
||||||
|
}
|
||||||
|
sendJson(response, 200, { data: { acknowledged: true } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(response, 404, { message: "not found", path: url.pathname });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeConfig(tempDir, apiPort, brokerPort, workerPort) {
|
||||||
|
const containerProofDir = "/proof";
|
||||||
|
const runtimeDir = `${containerProofDir}/runtime`;
|
||||||
|
const config = {
|
||||||
|
apiUrl: `http://127.0.0.1:${apiPort}`,
|
||||||
|
brokerUrl: `ws://127.0.0.1:${brokerPort}`,
|
||||||
|
gatewayId: 42,
|
||||||
|
agentToken: AGENT_TOKEN,
|
||||||
|
installDir: containerProofDir,
|
||||||
|
runtimeDir,
|
||||||
|
stateDatabasePath: `${runtimeDir}/gateway-state.sqlite`,
|
||||||
|
workerBaseUrl: `http://127.0.0.1:${workerPort}`,
|
||||||
|
heartbeatIntervalSeconds: 60,
|
||||||
|
operationPollTimeoutSeconds: 20,
|
||||||
|
};
|
||||||
|
|
||||||
|
const configPath = path.join(tempDir, "config.json");
|
||||||
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
||||||
|
return { containerConfigPath: `${containerProofDir}/config.json` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnWorker({ workerPath, phpImage, workerPort }) {
|
||||||
|
return spawn("docker", [
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--network",
|
||||||
|
"host",
|
||||||
|
"-e",
|
||||||
|
`TRUCKWASH_WORKER_TOKEN=${AGENT_TOKEN}`,
|
||||||
|
"-v",
|
||||||
|
`${workerPath}:/lan-worker.php:ro`,
|
||||||
|
phpImage,
|
||||||
|
"php",
|
||||||
|
"-S",
|
||||||
|
`127.0.0.1:${workerPort}`,
|
||||||
|
"/lan-worker.php",
|
||||||
|
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnAgent({ agentPath, phpImage, tempDir, containerConfigPath }) {
|
||||||
|
return spawn("docker", [
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--network",
|
||||||
|
"host",
|
||||||
|
"-v",
|
||||||
|
`${agentPath}:/agent.php:ro`,
|
||||||
|
"-v",
|
||||||
|
`${tempDir}:/proof`,
|
||||||
|
phpImage,
|
||||||
|
"php",
|
||||||
|
"/agent.php",
|
||||||
|
"--config",
|
||||||
|
containerConfigPath,
|
||||||
|
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForWorker(workerPort, child, timeoutMs) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
let lastError = null;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (child.exitCode !== null || child.signalCode !== null) {
|
||||||
|
throw new Error(`LAN worker exited before becoming healthy: ${child.exitCode ?? child.signalCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await requestJson({ port: workerPort, path: "/health" });
|
||||||
|
if (response.status === 200 && response.body?.service === "lan-worker") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
throw lastError || new Error("LAN worker did not become healthy");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopChild(child) {
|
||||||
|
if (child.exitCode !== null || child.signalCode !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
const hardKill = setTimeout(() => {
|
||||||
|
if (child.exitCode === null && child.signalCode === null) {
|
||||||
|
child.kill("SIGKILL");
|
||||||
|
}
|
||||||
|
}, 1500);
|
||||||
|
|
||||||
|
await Promise.race([
|
||||||
|
new Promise((resolve) => child.once("exit", resolve)),
|
||||||
|
new Promise((resolve) => setTimeout(resolve, 2200)),
|
||||||
|
]);
|
||||||
|
clearTimeout(hardKill);
|
||||||
|
}
|
||||||
|
|
||||||
|
function evidenceFromState(state, agentExited, workerExited) {
|
||||||
|
return {
|
||||||
|
brokerHandshakeSeen: state.brokerHandshakeSeen,
|
||||||
|
commandPollSeen: state.commandPollSeen,
|
||||||
|
shellySwitchSetSeen: state.shellySwitchSetSeen,
|
||||||
|
shellyStatusSeen: state.shellyStatusSeen,
|
||||||
|
resultSeen: state.resultSeen,
|
||||||
|
agentStayedRunningUntilProofComplete: !agentExited,
|
||||||
|
workerStayedRunningUntilProofComplete: !workerExited,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runProof(options) {
|
||||||
|
if (process.platform !== "linux") {
|
||||||
|
throw new Error("This proof uses Docker --network host and currently expects Linux.");
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(options.agentPath)) {
|
||||||
|
throw new Error(`Agent artifact not found: ${options.agentPath}`);
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(options.workerPath)) {
|
||||||
|
throw new Error(`LAN worker artifact not found: ${options.workerPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "edge-agent-to-shelly-proof-"));
|
||||||
|
fs.mkdirSync(path.join(tempDir, "runtime"), { recursive: true });
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
brokerHandshakeSeen: false,
|
||||||
|
commandPollSeen: false,
|
||||||
|
shellySwitchSetSeen: false,
|
||||||
|
shellyStatusSeen: false,
|
||||||
|
resultSeen: false,
|
||||||
|
commandDelivered: false,
|
||||||
|
failure: null,
|
||||||
|
requests: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const broker = createBrokerServer(state);
|
||||||
|
const shellyServer = createShellyServer(state);
|
||||||
|
let apiServer = null;
|
||||||
|
let agent = null;
|
||||||
|
let worker = null;
|
||||||
|
let agentStdout = "";
|
||||||
|
let agentStderr = "";
|
||||||
|
let workerStdout = "";
|
||||||
|
let workerStderr = "";
|
||||||
|
let agentExited = false;
|
||||||
|
let workerExited = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const brokerPort = await listen(broker.server);
|
||||||
|
const shellyPort = await listen(shellyServer);
|
||||||
|
const workerPort = await reservePort();
|
||||||
|
const shellyAddress = `127.0.0.1:${shellyPort}`;
|
||||||
|
apiServer = createApiServer(state, brokerPort, shellyAddress);
|
||||||
|
const apiPort = await listen(apiServer);
|
||||||
|
const { containerConfigPath } = writeConfig(tempDir, apiPort, brokerPort, workerPort);
|
||||||
|
|
||||||
|
worker = spawnWorker({ ...options, workerPort });
|
||||||
|
worker.stdout.on("data", (chunk) => {
|
||||||
|
workerStdout += chunk.toString();
|
||||||
|
});
|
||||||
|
worker.stderr.on("data", (chunk) => {
|
||||||
|
workerStderr += chunk.toString();
|
||||||
|
});
|
||||||
|
worker.once("exit", () => {
|
||||||
|
workerExited = true;
|
||||||
|
});
|
||||||
|
await waitForWorker(workerPort, worker, 5000);
|
||||||
|
|
||||||
|
agent = spawnAgent({ ...options, tempDir, containerConfigPath });
|
||||||
|
agent.stdout.on("data", (chunk) => {
|
||||||
|
agentStdout += chunk.toString();
|
||||||
|
});
|
||||||
|
agent.stderr.on("data", (chunk) => {
|
||||||
|
agentStderr += chunk.toString();
|
||||||
|
});
|
||||||
|
agent.once("exit", () => {
|
||||||
|
agentExited = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const deadline = Date.now() + options.timeoutMs;
|
||||||
|
while (Date.now() < deadline && !state.failure && !agentExited && !workerExited) {
|
||||||
|
if (
|
||||||
|
state.brokerHandshakeSeen &&
|
||||||
|
state.commandPollSeen &&
|
||||||
|
state.shellySwitchSetSeen &&
|
||||||
|
state.shellyStatusSeen &&
|
||||||
|
state.resultSeen
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
const evidence = evidenceFromState(state, agentExited, workerExited);
|
||||||
|
if (
|
||||||
|
state.failure ||
|
||||||
|
!state.brokerHandshakeSeen ||
|
||||||
|
!state.commandPollSeen ||
|
||||||
|
!state.shellySwitchSetSeen ||
|
||||||
|
!state.shellyStatusSeen ||
|
||||||
|
!state.resultSeen
|
||||||
|
) {
|
||||||
|
const error = state.failure || new Error("missing proof evidence");
|
||||||
|
error.evidence = evidence;
|
||||||
|
error.requests = state.requests;
|
||||||
|
error.agentStdout = agentStdout.slice(-3000);
|
||||||
|
error.agentStderr = agentStderr.slice(-3000);
|
||||||
|
error.workerStdout = workerStdout.slice(-3000);
|
||||||
|
error.workerStderr = workerStderr.slice(-3000);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
evidence,
|
||||||
|
agentPath: options.agentPath,
|
||||||
|
workerPath: options.workerPath,
|
||||||
|
phpImage: options.phpImage,
|
||||||
|
tempDir,
|
||||||
|
requestCount: state.requests.length,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
if (agent) {
|
||||||
|
await stopChild(agent);
|
||||||
|
}
|
||||||
|
if (worker) {
|
||||||
|
await stopChild(worker);
|
||||||
|
}
|
||||||
|
for (const socket of broker.sockets) {
|
||||||
|
socket.destroy();
|
||||||
|
}
|
||||||
|
await Promise.allSettled([
|
||||||
|
closeServer(broker.server),
|
||||||
|
closeServer(shellyServer),
|
||||||
|
apiServer ? closeServer(apiServer) : Promise.resolve(),
|
||||||
|
]);
|
||||||
|
if (!options.keepTemp) {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs();
|
||||||
|
if (options.help) {
|
||||||
|
printUsage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await runProof(options);
|
||||||
|
process.stdout.write("PASS broker-connected API command triggered real LAN worker Shelly RPC signal and posted result\n");
|
||||||
|
process.stdout.write(`${JSON.stringify(result.evidence)}\n`);
|
||||||
|
process.stdout.write(`Agent: ${result.agentPath}\n`);
|
||||||
|
process.stdout.write(`LAN worker: ${result.workerPath}\n`);
|
||||||
|
process.stdout.write(`PHP image: ${result.phpImage}\n`);
|
||||||
|
if (options.keepTemp) {
|
||||||
|
process.stdout.write(`Temp dir: ${result.tempDir}\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||||
|
main().catch((error) => {
|
||||||
|
process.stderr.write(`FAIL ${error.message}\n`);
|
||||||
|
if (error.evidence) {
|
||||||
|
process.stderr.write(`Evidence: ${JSON.stringify(error.evidence)}\n`);
|
||||||
|
}
|
||||||
|
if (error.requests) {
|
||||||
|
process.stderr.write(`Requests: ${JSON.stringify(error.requests, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
if (error.agentStdout) {
|
||||||
|
process.stderr.write(`agent stdout: ${error.agentStdout}\n`);
|
||||||
|
}
|
||||||
|
if (error.agentStderr) {
|
||||||
|
process.stderr.write(`agent stderr: ${error.agentStderr}\n`);
|
||||||
|
}
|
||||||
|
if (error.workerStdout) {
|
||||||
|
process.stderr.write(`worker stdout: ${error.workerStdout}\n`);
|
||||||
|
}
|
||||||
|
if (error.workerStderr) {
|
||||||
|
process.stderr.write(`worker stderr: ${error.workerStderr}\n`);
|
||||||
|
}
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
+112
-39
@@ -94,9 +94,23 @@ function directCaddyBaseUrl(baseUrl) {
|
|||||||
return normalizeBaseUrl(url.toString());
|
return normalizeBaseUrl(url.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isLocalHost(hostname) {
|
||||||
|
const normalized = String(hostname || "").toLowerCase().replace(/^\[|\]$/g, "");
|
||||||
|
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
||||||
|
}
|
||||||
|
|
||||||
function resolveBrokerWebSocketUrl(rawUrl, apiBaseUrl) {
|
function resolveBrokerWebSocketUrl(rawUrl, apiBaseUrl) {
|
||||||
const websocketUrl = new URL(String(rawUrl));
|
const websocketUrl = new URL(String(rawUrl));
|
||||||
const apiUrl = new URL(normalizeBaseUrl(apiBaseUrl));
|
const apiUrl = new URL(normalizeBaseUrl(apiBaseUrl));
|
||||||
|
const ciBrokerPort = String(process.env.EDGE_BROKER_CI_PORT || "").trim();
|
||||||
|
|
||||||
|
if (isLocalHost(apiUrl.hostname) && websocketUrl.hostname === "edge-broker" && ciBrokerPort !== "") {
|
||||||
|
websocketUrl.protocol = apiUrl.protocol === "https:" ? "wss:" : "ws:";
|
||||||
|
websocketUrl.hostname = apiUrl.hostname;
|
||||||
|
websocketUrl.port = ciBrokerPort;
|
||||||
|
websocketUrl.pathname = websocketUrl.pathname.replace(/^\/edge-broker(?=\/|$)/, "") || "/";
|
||||||
|
return websocketUrl.toString();
|
||||||
|
}
|
||||||
|
|
||||||
if (apiUrl.hostname === "caddy" && websocketUrl.hostname === "caddy") {
|
if (apiUrl.hostname === "caddy" && websocketUrl.hostname === "caddy") {
|
||||||
websocketUrl.hostname = "edge-broker";
|
websocketUrl.hostname = "edge-broker";
|
||||||
@@ -104,6 +118,18 @@ function resolveBrokerWebSocketUrl(rawUrl, apiBaseUrl) {
|
|||||||
websocketUrl.pathname = websocketUrl.pathname.replace(/^\/edge-broker(?=\/|$)/, "") || "/";
|
websocketUrl.pathname = websocketUrl.pathname.replace(/^\/edge-broker(?=\/|$)/, "") || "/";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isLocalHost(apiUrl.hostname) && ["caddy", "edge-broker"].includes(websocketUrl.hostname)) {
|
||||||
|
const brokerPath = websocketUrl.pathname.replace(/^\/edge-broker(?=\/|$)/, "") || "/";
|
||||||
|
websocketUrl.protocol = apiUrl.protocol === "https:" ? "wss:" : "ws:";
|
||||||
|
websocketUrl.hostname = apiUrl.hostname;
|
||||||
|
websocketUrl.port = apiUrl.port;
|
||||||
|
websocketUrl.pathname = `/api/edge-broker${brokerPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLocalHost(websocketUrl.hostname)) {
|
||||||
|
websocketUrl.pathname = websocketUrl.pathname.replace(/^\/edge-broker(?=\/|$)/, "") || "/";
|
||||||
|
}
|
||||||
|
|
||||||
return websocketUrl.toString();
|
return websocketUrl.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -555,6 +581,38 @@ function summarizeStreamMessages(messages, limit = 12) {
|
|||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function readGatewayDiagnostics({ baseUrl, authToken, gatewayId, containerName }) {
|
||||||
|
const diagnostics = {};
|
||||||
|
|
||||||
|
if (gatewayId !== null && gatewayId > 0 && authToken) {
|
||||||
|
try {
|
||||||
|
const detail = await apiRequest(baseUrl, "GET", `/edge-gateways/${gatewayId}`, {
|
||||||
|
token: authToken,
|
||||||
|
});
|
||||||
|
diagnostics.gateway = {
|
||||||
|
status: detail?.data?.status ?? null,
|
||||||
|
channelStatus: detail?.data?.channel_status ?? null,
|
||||||
|
brokerPresence: detail?.data?.metadata?.broker_presence ?? null,
|
||||||
|
brokerConnected: detail?.data?.metadata?.broker_connected ?? null,
|
||||||
|
brokerLastError: detail?.data?.metadata?.broker_last_error ?? null,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
diagnostics.gatewayError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const logs = await runCommand("docker", ["logs", "--tail", "120", containerName], {
|
||||||
|
allowFailure: true,
|
||||||
|
});
|
||||||
|
diagnostics.containerLogs = String(`${logs.stdout || ""}${logs.stderr || ""}`).trim().split(/\r?\n/).slice(-120);
|
||||||
|
} catch (error) {
|
||||||
|
diagnostics.containerLogError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return diagnostics;
|
||||||
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const scriptPath = fileURLToPath(import.meta.url);
|
const scriptPath = fileURLToPath(import.meta.url);
|
||||||
const rootDir = await resolveRootDir(scriptPath);
|
const rootDir = await resolveRootDir(scriptPath);
|
||||||
@@ -669,22 +727,35 @@ async function main() {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
await waitForCondition(
|
try {
|
||||||
async () => {
|
await waitForCondition(
|
||||||
const detail = await apiRequest(baseUrl, "GET", `/edge-gateways/${gatewayId}`, {
|
async () => {
|
||||||
token: authToken,
|
const detail = await apiRequest(baseUrl, "GET", `/edge-gateways/${gatewayId}`, {
|
||||||
});
|
token: authToken,
|
||||||
|
});
|
||||||
|
|
||||||
return Boolean(
|
return Boolean(
|
||||||
detail?.data?.channel_status?.broker?.connected
|
detail?.data?.channel_status?.broker?.connected
|
||||||
|| detail?.data?.metadata?.broker_connected
|
|| detail?.data?.metadata?.broker_connected
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
timeoutMs: 90_000,
|
timeoutMs: 90_000,
|
||||||
message: "Gateway never established a live broker connection after install.",
|
message: "Gateway never established a live broker connection after install.",
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
const diagnostics = await readGatewayDiagnostics({
|
||||||
|
baseUrl,
|
||||||
|
authToken,
|
||||||
|
gatewayId,
|
||||||
|
containerName,
|
||||||
|
});
|
||||||
|
throw new Error([
|
||||||
|
error instanceof Error ? error.message : String(error),
|
||||||
|
`Broker diagnostics: ${JSON.stringify(diagnostics, null, 2)}`,
|
||||||
|
].join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
const WebSocketImpl = await loadWebSocketImplementation();
|
const WebSocketImpl = await loadWebSocketImplementation();
|
||||||
const streamSession = await apiRequest(baseUrl, "POST", `/edge-gateways/${gatewayId}/stream-session`, {
|
const streamSession = await apiRequest(baseUrl, "POST", `/edge-gateways/${gatewayId}/stream-session`, {
|
||||||
@@ -707,11 +778,14 @@ async function main() {
|
|||||||
{ timeoutMs: 15_000, message: "Gateway stream never became ready." }
|
{ timeoutMs: 15_000, message: "Gateway stream never became ready." }
|
||||||
);
|
);
|
||||||
|
|
||||||
const readyMessage = streamMessages.find((message) => message?.type === "gateway.stream.ready");
|
await waitForSocketMessage(
|
||||||
assert.equal(
|
streamMessages,
|
||||||
Boolean(readyMessage?.connected),
|
(message) => (
|
||||||
true,
|
message?.type === "gateway.stream.ready" && message?.connected === true
|
||||||
"Gateway stream became ready before the broker reported the gateway as connected."
|
) || (
|
||||||
|
message?.type === "presence.changed" && message?.status === "connected"
|
||||||
|
),
|
||||||
|
{ timeoutMs: 45_000, message: "Gateway stream never observed a connected broker presence." }
|
||||||
);
|
);
|
||||||
|
|
||||||
const operationResponse = await apiRequest(baseUrl, "POST", `/edge-gateways/${gatewayId}/operations`, {
|
const operationResponse = await apiRequest(baseUrl, "POST", `/edge-gateways/${gatewayId}/operations`, {
|
||||||
@@ -739,10 +813,24 @@ async function main() {
|
|||||||
assert.ok(operationId > 0, "Operation creation did not return an operation id.");
|
assert.ok(operationId > 0, "Operation creation did not return an operation id.");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await waitForSocketMessage(
|
await waitForCondition(
|
||||||
streamMessages,
|
async () => {
|
||||||
(message) => message?.type === "task.updated" && Number(message?.operationId || 0) === operationId,
|
const operations = await apiRequest(baseUrl, "GET", `/edge-gateways/${gatewayId}/operations`, {
|
||||||
{ timeoutMs: 180_000, message: "Live gateway stream never emitted task.updated for the queued operation." }
|
token: authToken,
|
||||||
|
});
|
||||||
|
|
||||||
|
const operation = Array.isArray(operations?.data)
|
||||||
|
? operations.data.find((item) => Number(item?.id || 0) === operationId)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return operation?.status === "COMPLETED"
|
||||||
|
|| streamMessages.some((message) => (
|
||||||
|
message?.type === "task.updated"
|
||||||
|
&& Number(message?.operationId || 0) === operationId
|
||||||
|
&& message?.operation?.status === "COMPLETED"
|
||||||
|
));
|
||||||
|
},
|
||||||
|
{ timeoutMs: 180_000, message: "Gateway operation never completed through the live agent." }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
let operationSnapshot = null;
|
let operationSnapshot = null;
|
||||||
@@ -765,21 +853,6 @@ async function main() {
|
|||||||
throw new Error(diagnostic);
|
throw new Error(diagnostic);
|
||||||
}
|
}
|
||||||
|
|
||||||
await waitForCondition(
|
|
||||||
async () => {
|
|
||||||
const operations = await apiRequest(baseUrl, "GET", `/edge-gateways/${gatewayId}/operations`, {
|
|
||||||
token: authToken,
|
|
||||||
});
|
|
||||||
|
|
||||||
const operation = Array.isArray(operations?.data)
|
|
||||||
? operations.data.find((item) => Number(item?.id || 0) === operationId)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return operation?.status === "COMPLETED";
|
|
||||||
},
|
|
||||||
{ timeoutMs: 180_000, message: "Gateway operation never completed through the live agent." }
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitForSocketMessage(
|
await waitForSocketMessage(
|
||||||
streamMessages,
|
streamMessages,
|
||||||
(message) => message?.type === "gateway.telemetry" || message?.type === "stats.updated",
|
(message) => message?.type === "gateway.telemetry" || message?.type === "stats.updated",
|
||||||
|
|||||||
+25
-3
@@ -18,6 +18,7 @@ cd "$repo_root"
|
|||||||
compose_files="-f docker-compose.yml -f .github/docker-compose.ci.yml"
|
compose_files="-f docker-compose.yml -f .github/docker-compose.ci.yml"
|
||||||
project_suffix="$(date +%s)-$$"
|
project_suffix="$(date +%s)-$$"
|
||||||
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-php-local-${suite}-${project_suffix}}"
|
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-php-local-${suite}-${project_suffix}}"
|
||||||
|
export COMPOSE_PROFILES="${COMPOSE_PROFILES:-dev}"
|
||||||
|
|
||||||
log_dir=".tmp/ci-logs/$suite"
|
log_dir=".tmp/ci-logs/$suite"
|
||||||
mkdir -p "$log_dir"
|
mkdir -p "$log_dir"
|
||||||
@@ -84,6 +85,17 @@ composer_install() {
|
|||||||
'cd /var/www/html && composer install --no-interaction --prefer-source --no-progress'
|
'cd /var/www/html && composer install --no-interaction --prefer-source --no-progress'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
configure_ci_docker_subnet() {
|
||||||
|
if [ -n "${CI_DOCKER_SUBNET:-}" ]; then
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
checksum="$(printf '%s' "$COMPOSE_PROJECT_NAME" | cksum | awk '{print $1}')"
|
||||||
|
subnet_second=$((64 + ((checksum / 256) % 64)))
|
||||||
|
subnet_third=$((checksum % 256))
|
||||||
|
export CI_DOCKER_SUBNET="10.${subnet_second}.${subnet_third}.0/24"
|
||||||
|
}
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
status="$?"
|
status="$?"
|
||||||
collect_logs "$status"
|
collect_logs "$status"
|
||||||
@@ -103,7 +115,8 @@ cleanup() {
|
|||||||
}
|
}
|
||||||
trap cleanup EXIT INT TERM
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
retry_command "${PHP_CI_DOCKER_RETRIES:-3}" docker compose $compose_files up -d redis mysql-debug php1
|
configure_ci_docker_subnet
|
||||||
|
sh scripts/ci-docker-compose-up.sh redis mysql-debug php1
|
||||||
|
|
||||||
docker compose $compose_files exec -T php1 sh -lc '
|
docker compose $compose_files exec -T php1 sh -lc '
|
||||||
set -eu
|
set -eu
|
||||||
@@ -126,9 +139,18 @@ tar \
|
|||||||
--exclude='./.phpunit.cache' \
|
--exclude='./.phpunit.cache' \
|
||||||
--exclude='./build/logs' \
|
--exclude='./build/logs' \
|
||||||
-C services/nginx/app -cf - . \
|
-C services/nginx/app -cf - . \
|
||||||
| docker compose $compose_files exec -T php1 tar -C /var/www/html -xf -
|
| docker compose $compose_files exec -T php1 tar --no-same-owner -C /var/www/html -xf -
|
||||||
|
|
||||||
|
docker compose $compose_files exec -T php1 sh -lc 'rm -rf /var/www/repo-root && mkdir -p /var/www/repo-root'
|
||||||
|
tar \
|
||||||
|
-cf - \
|
||||||
|
Dockerfile \
|
||||||
|
Dockerfile.coolify-api \
|
||||||
|
services/php/Dockerfile \
|
||||||
|
services/php/php-fpm-pool.conf \
|
||||||
|
| docker compose $compose_files exec -T php1 tar --no-same-owner -C /var/www/repo-root -xf -
|
||||||
|
|
||||||
composer_install
|
composer_install
|
||||||
|
|
||||||
docker compose $compose_files exec -T php1 sh -lc \
|
docker compose $compose_files exec -T php1 sh -lc \
|
||||||
"cd /var/www/html && composer test:ci:$suite"
|
"cd /var/www/html && PLENO_REPO_ROOT_FOR_TESTS=/var/www/repo-root composer test:ci:$suite"
|
||||||
|
|||||||
@@ -1,14 +1,32 @@
|
|||||||
import process from "node:process";
|
import process from "node:process";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
import { pathToFileURL } from "node:url";
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
export const DEFAULT_STAGING_BASE_URL = "https://api.truckwash.io:4433";
|
export const DEFAULT_STAGING_BASE_URL = "https://api.truckwash.io:4433";
|
||||||
|
export const EXPECTED_INSTALL_VERSION = "compose-php-agent-v3";
|
||||||
|
export const REQUIRED_MANIFEST_ARTIFACTS = [
|
||||||
|
"agent.php",
|
||||||
|
"lan-worker.php",
|
||||||
|
"auto-updater.php",
|
||||||
|
"docker-compose.gateway.yml",
|
||||||
|
"Dockerfile.edge-agent",
|
||||||
|
"Dockerfile.lan-worker",
|
||||||
|
"Dockerfile.auto-updater",
|
||||||
|
"gateway-launcher.sh",
|
||||||
|
"truckwash-edge-gateway-stack.service",
|
||||||
|
"truckwash-edge-agent.service",
|
||||||
|
];
|
||||||
export const INSTALLER_SCRIPT_REQUIRED_SNIPPETS = [
|
export const INSTALLER_SCRIPT_REQUIRED_SNIPPETS = [
|
||||||
"/edge-agent/install-token/status",
|
"/edge-agent/install-token/status",
|
||||||
|
"/edge-agent/artifacts/manifest.json",
|
||||||
"report_install_status",
|
"report_install_status",
|
||||||
'begin_install_phase "VERIFY_TOKEN"',
|
'begin_install_phase "VERIFY_TOKEN"',
|
||||||
|
'begin_install_phase "VERIFY_ARTIFACTS"',
|
||||||
'begin_install_phase "WAIT_FOR_CLAIM"',
|
'begin_install_phase "WAIT_FOR_CLAIM"',
|
||||||
'report_install_status "FAILED"',
|
'report_install_status "FAILED"',
|
||||||
|
"verify_manifest_artifact",
|
||||||
|
EXPECTED_INSTALL_VERSION,
|
||||||
];
|
];
|
||||||
|
|
||||||
export function normalizeBaseUrl(url) {
|
export function normalizeBaseUrl(url) {
|
||||||
@@ -55,13 +73,20 @@ export function buildChecks(baseUrl, installToken) {
|
|||||||
name: "Ping",
|
name: "Ping",
|
||||||
url: `${normalizedBaseUrl}/ping`,
|
url: `${normalizedBaseUrl}/ping`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "Artifact manifest",
|
||||||
|
url: `${normalizedBaseUrl}/edge-agent/artifacts/manifest.json`,
|
||||||
|
artifactName: "manifest.json",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "Agent PHP artifact",
|
name: "Agent PHP artifact",
|
||||||
url: `${normalizedBaseUrl}/edge-agent/artifacts/agent.php`,
|
url: `${normalizedBaseUrl}/edge-agent/artifacts/agent.php`,
|
||||||
|
artifactName: "agent.php",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Service unit artifact",
|
name: "Service unit artifact",
|
||||||
url: `${normalizedBaseUrl}/edge-agent/artifacts/truckwash-edge-agent.service`,
|
url: `${normalizedBaseUrl}/edge-agent/artifacts/truckwash-edge-agent.service`,
|
||||||
|
artifactName: "truckwash-edge-agent.service",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Installer script",
|
name: "Installer script",
|
||||||
@@ -70,6 +95,42 @@ export function buildChecks(baseUrl, installToken) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function validateArtifactManifestBody(body) {
|
||||||
|
const manifest = JSON.parse(String(body || ""));
|
||||||
|
if (manifest.version !== EXPECTED_INSTALL_VERSION) {
|
||||||
|
throw new Error(`Artifact manifest version mismatch: expected ${EXPECTED_INSTALL_VERSION}, got ${manifest.version}`);
|
||||||
|
}
|
||||||
|
if (!Array.isArray(manifest.artifacts)) {
|
||||||
|
throw new Error("Artifact manifest is missing artifacts.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const byName = new Map(manifest.artifacts.map((artifact) => [artifact?.name, artifact]));
|
||||||
|
const missingArtifacts = REQUIRED_MANIFEST_ARTIFACTS.filter((artifactName) => !byName.has(artifactName));
|
||||||
|
if (missingArtifacts.length) {
|
||||||
|
throw new Error(`Artifact manifest is missing required artifacts: ${missingArtifacts.join(", ")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return manifest;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateArtifactBodyAgainstManifest(manifest, artifactName, body) {
|
||||||
|
const artifact = manifest?.artifacts?.find((entry) => entry?.name === artifactName);
|
||||||
|
if (!artifact) {
|
||||||
|
throw new Error(`Artifact ${artifactName} is missing from manifest.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = Buffer.isBuffer(body) ? body : Buffer.from(String(body || ""));
|
||||||
|
const sha256 = createHash("sha256").update(buffer).digest("hex");
|
||||||
|
if (sha256 !== artifact.sha256) {
|
||||||
|
throw new Error(`Artifact ${artifactName} hash mismatch: ${sha256} !== ${artifact.sha256}`);
|
||||||
|
}
|
||||||
|
if (buffer.length !== artifact.bytes) {
|
||||||
|
throw new Error(`Artifact ${artifactName} size mismatch: ${buffer.length} !== ${artifact.bytes}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return artifact;
|
||||||
|
}
|
||||||
|
|
||||||
export function validateInstallerScriptBody(body) {
|
export function validateInstallerScriptBody(body) {
|
||||||
const source = String(body || "");
|
const source = String(body || "");
|
||||||
const missingSnippets = INSTALLER_SCRIPT_REQUIRED_SNIPPETS.filter((snippet) => !source.includes(snippet));
|
const missingSnippets = INSTALLER_SCRIPT_REQUIRED_SNIPPETS.filter((snippet) => !source.includes(snippet));
|
||||||
@@ -107,16 +168,17 @@ export async function runSmoke({ baseUrl, installToken }) {
|
|||||||
|
|
||||||
const checks = buildChecks(baseUrl, installToken);
|
const checks = buildChecks(baseUrl, installToken);
|
||||||
const results = [];
|
const results = [];
|
||||||
|
let artifactManifest = null;
|
||||||
|
|
||||||
for (const check of checks) {
|
for (const check of checks) {
|
||||||
process.stdout.write(`[staging-smoke] GET ${check.url}\n`);
|
process.stdout.write(`[staging-smoke] GET ${check.url}\n`);
|
||||||
const response = await fetch(check.url);
|
const response = await fetch(check.url);
|
||||||
const body = await response.text();
|
const body = Buffer.from(await response.arrayBuffer());
|
||||||
const result = {
|
const result = {
|
||||||
...check,
|
...check,
|
||||||
status: response.status,
|
status: response.status,
|
||||||
ok: response.ok,
|
ok: response.ok,
|
||||||
bodyPreview: previewBody(body),
|
bodyPreview: previewBody(body.toString("utf8")),
|
||||||
};
|
};
|
||||||
results.push(result);
|
results.push(result);
|
||||||
|
|
||||||
@@ -127,8 +189,16 @@ export async function runSmoke({ baseUrl, installToken }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (check.name === "Artifact manifest") {
|
||||||
|
artifactManifest = validateArtifactManifestBody(body.toString("utf8"));
|
||||||
|
result.version = artifactManifest.version;
|
||||||
|
result.artifactCount = artifactManifest.artifacts.length;
|
||||||
|
}
|
||||||
|
if (artifactManifest && check.artifactName && check.artifactName !== "manifest.json") {
|
||||||
|
result.verifiedArtifact = validateArtifactBodyAgainstManifest(artifactManifest, check.artifactName, body);
|
||||||
|
}
|
||||||
if (check.name === "Installer script") {
|
if (check.name === "Installer script") {
|
||||||
result.verifiedSnippets = validateInstallerScriptBody(body);
|
result.verifiedSnippets = validateInstallerScriptBody(body.toString("utf8"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,13 @@ import assert from "node:assert/strict";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_STAGING_BASE_URL,
|
DEFAULT_STAGING_BASE_URL,
|
||||||
|
EXPECTED_INSTALL_VERSION,
|
||||||
INSTALLER_SCRIPT_REQUIRED_SNIPPETS,
|
INSTALLER_SCRIPT_REQUIRED_SNIPPETS,
|
||||||
buildChecks,
|
buildChecks,
|
||||||
normalizeBaseUrl,
|
normalizeBaseUrl,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
|
validateArtifactBodyAgainstManifest,
|
||||||
|
validateArtifactManifestBody,
|
||||||
validateInstallerScriptBody,
|
validateInstallerScriptBody,
|
||||||
} from "./staging-edge-gateway-smoke.mjs";
|
} from "./staging-edge-gateway-smoke.mjs";
|
||||||
|
|
||||||
@@ -32,18 +35,58 @@ test("buildChecks targets the public staging endpoints", () => {
|
|||||||
|
|
||||||
assert.deepEqual(checks.map((check) => check.url), [
|
assert.deepEqual(checks.map((check) => check.url), [
|
||||||
"https://api.truckwash.io:4433/ping",
|
"https://api.truckwash.io:4433/ping",
|
||||||
|
"https://api.truckwash.io:4433/edge-agent/artifacts/manifest.json",
|
||||||
"https://api.truckwash.io:4433/edge-agent/artifacts/agent.php",
|
"https://api.truckwash.io:4433/edge-agent/artifacts/agent.php",
|
||||||
"https://api.truckwash.io:4433/edge-agent/artifacts/truckwash-edge-agent.service",
|
"https://api.truckwash.io:4433/edge-agent/artifacts/truckwash-edge-agent.service",
|
||||||
"https://api.truckwash.io:4433/edge-agent/install.sh?token=abc%20123",
|
"https://api.truckwash.io:4433/edge-agent/install.sh?token=abc%20123",
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("validateArtifactManifestBody requires v3 install artifacts", () => {
|
||||||
|
const artifacts = [
|
||||||
|
"agent.php",
|
||||||
|
"lan-worker.php",
|
||||||
|
"auto-updater.php",
|
||||||
|
"docker-compose.gateway.yml",
|
||||||
|
"Dockerfile.edge-agent",
|
||||||
|
"Dockerfile.lan-worker",
|
||||||
|
"Dockerfile.auto-updater",
|
||||||
|
"gateway-launcher.sh",
|
||||||
|
"truckwash-edge-gateway-stack.service",
|
||||||
|
"truckwash-edge-agent.service",
|
||||||
|
].map((name) => ({ name, sha256: "abc", bytes: 1 }));
|
||||||
|
|
||||||
|
const manifest = validateArtifactManifestBody(JSON.stringify({
|
||||||
|
version: EXPECTED_INSTALL_VERSION,
|
||||||
|
artifacts,
|
||||||
|
}));
|
||||||
|
|
||||||
|
assert.equal(manifest.version, EXPECTED_INSTALL_VERSION);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("validateArtifactBodyAgainstManifest verifies size and hash", () => {
|
||||||
|
const body = Buffer.from("hello");
|
||||||
|
const manifest = {
|
||||||
|
artifacts: [{
|
||||||
|
name: "agent.php",
|
||||||
|
sha256: "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
|
||||||
|
bytes: body.length,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.equal(validateArtifactBodyAgainstManifest(manifest, "agent.php", body).name, "agent.php");
|
||||||
|
});
|
||||||
|
|
||||||
test("validateInstallerScriptBody requires install-session reporting wiring", () => {
|
test("validateInstallerScriptBody requires install-session reporting wiring", () => {
|
||||||
const script = `
|
const script = `
|
||||||
INSTALL_STATUS_URL="https://api.truckwash.io:4433/edge-agent/install-token/status"
|
INSTALL_STATUS_URL="https://api.truckwash.io:4433/edge-agent/install-token/status"
|
||||||
|
fetch_http "Download artifact manifest" "https://api.truckwash.io:4433/edge-agent/artifacts/manifest.json"
|
||||||
report_install_status "FAILED"
|
report_install_status "FAILED"
|
||||||
begin_install_phase "VERIFY_TOKEN" "Verifying install token"
|
begin_install_phase "VERIFY_TOKEN" "Verifying install token"
|
||||||
|
begin_install_phase "VERIFY_ARTIFACTS" "Verifying edge gateway artifacts"
|
||||||
begin_install_phase "WAIT_FOR_CLAIM" "Waiting for gateway heartbeat and claim"
|
begin_install_phase "WAIT_FOR_CLAIM" "Waiting for gateway heartbeat and claim"
|
||||||
|
verify_manifest_artifact
|
||||||
|
${EXPECTED_INSTALL_VERSION}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
assert.deepEqual(validateInstallerScriptBody(script), INSTALLER_SCRIPT_REQUIRED_SNIPPETS);
|
assert.deepEqual(validateInstallerScriptBody(script), INSTALLER_SCRIPT_REQUIRED_SNIPPETS);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export const DEFAULT_IMAGE_TAG = "truckwash-edge-agent:test-gateway";
|
|||||||
export const DEFAULT_CONFIG_FILE_NAME = "test-gateway.json";
|
export const DEFAULT_CONFIG_FILE_NAME = "test-gateway.json";
|
||||||
export const DEFAULT_HOST_API_URL = "http://localhost/api";
|
export const DEFAULT_HOST_API_URL = "http://localhost/api";
|
||||||
export const DEFAULT_CONTAINER_API_URL = "http://caddy";
|
export const DEFAULT_CONTAINER_API_URL = "http://caddy";
|
||||||
export const DEFAULT_CONTAINER_BROKER_URL = "http://edge-broker:4300";
|
export const DEFAULT_CONTAINER_BROKER_URL = "ws://edge-broker:4300";
|
||||||
export const DEFAULT_INSTALL_DIR = "/opt/truckwash-edge-agent";
|
export const DEFAULT_INSTALL_DIR = "/opt/truckwash-edge-agent";
|
||||||
export const DEFAULT_RUNTIME_DIR = `${DEFAULT_INSTALL_DIR}/runtime`;
|
export const DEFAULT_RUNTIME_DIR = `${DEFAULT_INSTALL_DIR}/runtime`;
|
||||||
export const DEFAULT_STATE_DATABASE_PATH = `${DEFAULT_RUNTIME_DIR}/gateway-state.sqlite`;
|
export const DEFAULT_STATE_DATABASE_PATH = `${DEFAULT_RUNTIME_DIR}/gateway-state.sqlite`;
|
||||||
@@ -409,14 +409,20 @@ async function startContainer({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (copyConfig) {
|
if (copyConfig) {
|
||||||
await runCommand("docker", [
|
const configFilePath = path.join(configDir, DEFAULT_CONFIG_FILE_NAME);
|
||||||
"cp",
|
await fs.chmod(configFilePath, 0o666).catch(() => {});
|
||||||
path.join(configDir, DEFAULT_CONFIG_FILE_NAME),
|
try {
|
||||||
`${containerName}:${containerConfigPath}`,
|
await runCommand("docker", [
|
||||||
], {
|
"cp",
|
||||||
cwd: rootDir,
|
configFilePath,
|
||||||
stdio: "inherit",
|
`${containerName}:${containerConfigPath}`,
|
||||||
});
|
], {
|
||||||
|
cwd: rootDir,
|
||||||
|
stdio: "inherit",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await fs.chmod(configFilePath, 0o600).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
await runCommand("docker", ["start", containerName], {
|
await runCommand("docker", ["start", containerName], {
|
||||||
cwd: rootDir,
|
cwd: rootDir,
|
||||||
|
|||||||
Vendored
+58
@@ -754,6 +754,60 @@ export async function setRelayState(payload, fetchImpl = fetch) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function mapWithConcurrency(items, limit, mapper) {
|
||||||
|
const results = new Array(items.length);
|
||||||
|
let nextIndex = 0;
|
||||||
|
const workerCount = Math.max(1, Math.min(Number(limit) || 1, items.length || 1));
|
||||||
|
|
||||||
|
await Promise.all(Array.from({ length: workerCount }, async () => {
|
||||||
|
while (nextIndex < items.length) {
|
||||||
|
const index = nextIndex;
|
||||||
|
nextIndex += 1;
|
||||||
|
results[index] = await mapper(items[index], index);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeRelayBatch(command, handler, fetchImpl = fetch) {
|
||||||
|
const commands = Array.isArray(command?.payload?.commands)
|
||||||
|
? command.payload.commands
|
||||||
|
: Array.isArray(command?.commands)
|
||||||
|
? command.commands
|
||||||
|
: [];
|
||||||
|
const concurrency = Math.max(1, Math.min(Number(command?.payload?.concurrency || command?.concurrency || 5), 5));
|
||||||
|
|
||||||
|
const results = await mapWithConcurrency(commands, concurrency, async (entry = {}) => {
|
||||||
|
const target = String(entry.target || entry.relay || "");
|
||||||
|
const relayId = String(entry.relayId || entry.relay_id || "");
|
||||||
|
try {
|
||||||
|
const payload = await handler(entry, fetchImpl);
|
||||||
|
return {
|
||||||
|
target,
|
||||||
|
relayId,
|
||||||
|
relay_id: relayId,
|
||||||
|
ok: true,
|
||||||
|
payload,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
target,
|
||||||
|
relayId,
|
||||||
|
relay_id: relayId,
|
||||||
|
ok: false,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
batchId: command?.payload?.batchId || command?.payload?.batch_id || command?.batchId || command?.batch_id || null,
|
||||||
|
batch_id: command?.payload?.batch_id || command?.payload?.batchId || command?.batch_id || command?.batchId || null,
|
||||||
|
results,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchArtifactBuffer(url, expectedSha256, label, fetchImpl = fetch) {
|
async function fetchArtifactBuffer(url, expectedSha256, label, fetchImpl = fetch) {
|
||||||
if (!url) {
|
if (!url) {
|
||||||
return null;
|
return null;
|
||||||
@@ -1416,6 +1470,10 @@ export async function handleAgentCommand(command, deps = {}) {
|
|||||||
return await getRelayStatus(command.payload || {}, fetchImpl);
|
return await getRelayStatus(command.payload || {}, fetchImpl);
|
||||||
case "SET_RELAY_STATE":
|
case "SET_RELAY_STATE":
|
||||||
return await setRelayState(command.payload || {}, fetchImpl);
|
return await setRelayState(command.payload || {}, fetchImpl);
|
||||||
|
case "BATCH_RELAY_STATUS":
|
||||||
|
return await executeRelayBatch(command, getRelayStatus, fetchImpl);
|
||||||
|
case "BATCH_SET_RELAY_STATE":
|
||||||
|
return await executeRelayBatch(command, setRelayState, fetchImpl);
|
||||||
case "RUN_UPDATE":
|
case "RUN_UPDATE":
|
||||||
return await runUpdate(command.payload || {}, fetchImpl, deps);
|
return await runUpdate(command.payload || {}, fetchImpl, deps);
|
||||||
case "UNINSTALL_AGENT":
|
case "UNINSTALL_AGENT":
|
||||||
|
|||||||
@@ -127,6 +127,39 @@ test("relay status and switch commands support both Shelly RPC and legacy endpoi
|
|||||||
assert.equal(switched.on, false);
|
assert.equal(switched.on, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("batch relay commands return per-relay results without failing the whole batch", async () => {
|
||||||
|
const fakeFetch = async (url) => {
|
||||||
|
const value = String(url);
|
||||||
|
if (value.includes("10.1.0.31")) {
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
async json() {
|
||||||
|
return { output: true };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error("relay offline");
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await handleAgentCommand({
|
||||||
|
commandType: "BATCH_SET_RELAY_STATE",
|
||||||
|
payload: {
|
||||||
|
batch_id: "batch-1",
|
||||||
|
commands: [
|
||||||
|
{ target: "MACHINE", relayId: "relay-machine", localIp: "10.1.0.31", channel: 0, on: true },
|
||||||
|
{ target: "EXIT", relayId: "relay-out", localIp: "10.1.0.32", channel: 0, on: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}, { fetchImpl: fakeFetch });
|
||||||
|
|
||||||
|
assert.equal(result.batch_id, "batch-1");
|
||||||
|
assert.equal(result.results.length, 2);
|
||||||
|
assert.equal(result.results[0].ok, true);
|
||||||
|
assert.equal(result.results[0].target, "MACHINE");
|
||||||
|
assert.equal(result.results[1].ok, false);
|
||||||
|
assert.match(result.results[1].error, /relay offline/);
|
||||||
|
});
|
||||||
|
|
||||||
test("Shelly discovery infers Gen3 from S3 relay model codes when generation is omitted", async () => {
|
test("Shelly discovery infers Gen3 from S3 relay model codes when generation is omitted", async () => {
|
||||||
const inventory = await discoverShellyDevices({ candidateIps: ["192.168.1.2"] }, async (url) => {
|
const inventory = await discoverShellyDevices({ candidateIps: ["192.168.1.2"] }, async (url) => {
|
||||||
assert.equal(String(url), "http://192.168.1.2/shelly");
|
assert.equal(String(url), "http://192.168.1.2/shelly");
|
||||||
|
|||||||
@@ -296,6 +296,12 @@ export function createBrokerServer(options = {}) {
|
|||||||
? async (_gatewayId, payload = {}) => payload
|
? async (_gatewayId, payload = {}) => payload
|
||||||
: async (gatewayId, payload = {}) =>
|
: async (gatewayId, payload = {}) =>
|
||||||
managerRequest(`/edge-agent/internal/gateways/${gatewayId}/logs`, payload));
|
managerRequest(`/edge-agent/internal/gateways/${gatewayId}/logs`, payload));
|
||||||
|
const ingestMachineSignal =
|
||||||
|
options.ingestMachineSignal ||
|
||||||
|
(authMode === "stub"
|
||||||
|
? async (_gatewayId, payload = {}) => payload
|
||||||
|
: async (gatewayId, payload = {}) =>
|
||||||
|
managerRequest(`/edge-agent/internal/gateways/${gatewayId}/selfserve/machine-signal`, payload));
|
||||||
|
|
||||||
const broadcastGatewayEvent = (gatewayId, message) => {
|
const broadcastGatewayEvent = (gatewayId, message) => {
|
||||||
const sessionIds = gatewayStreamSessions.get(String(gatewayId));
|
const sessionIds = gatewayStreamSessions.get(String(gatewayId));
|
||||||
@@ -853,6 +859,11 @@ export function createBrokerServer(options = {}) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (message.type === "MACHINE_SIGNAL") {
|
||||||
|
await ingestMachineSignal(String(ws.gatewayId), message.payload || {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (["SHELL_OUTPUT", "SHELL_OPENED", "SHELL_EXIT"].includes(message.type)) {
|
if (["SHELL_OUTPUT", "SHELL_OPENED", "SHELL_EXIT"].includes(message.type)) {
|
||||||
const sessionRecord = browserShellSessions.get(String(message.sessionId));
|
const sessionRecord = browserShellSessions.get(String(message.sessionId));
|
||||||
if (!sessionRecord) {
|
if (!sessionRecord) {
|
||||||
|
|||||||
@@ -766,6 +766,51 @@ test("broker fans out telemetry, task, log, and presence updates to browser gate
|
|||||||
await broker.close();
|
await broker.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("broker ingests self-serve machine signals from connected agents", async () => {
|
||||||
|
const machineSignals = [];
|
||||||
|
const broker = createBrokerServer({
|
||||||
|
authMode: "stub",
|
||||||
|
validateAgent: async () => ({ id: "701", gateway_id: "701", label: "CPH Edge 01" }),
|
||||||
|
ingestMachineSignal: async (gatewayId, payload) => {
|
||||||
|
machineSignals.push({ gatewayId, payload });
|
||||||
|
return { recorded: true, lane_id: payload.lane_id };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const address = await broker.listen(0);
|
||||||
|
const port = address.port;
|
||||||
|
|
||||||
|
const agent = new WebSocket(`ws://127.0.0.1:${port}/ws/agent?gatewayId=701&token=agent-token`);
|
||||||
|
await new Promise((resolve) => agent.once("open", resolve));
|
||||||
|
|
||||||
|
agent.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "MACHINE_SIGNAL",
|
||||||
|
payload: {
|
||||||
|
lane_id: 3,
|
||||||
|
relay_id: "machine-relay",
|
||||||
|
component: "input",
|
||||||
|
channel: 0,
|
||||||
|
event: "input.toggle_on",
|
||||||
|
state: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => machineSignals.length === 1, { description: "machine signal ingestion" });
|
||||||
|
assert.equal(machineSignals[0].gatewayId, "701");
|
||||||
|
assert.deepEqual(machineSignals[0].payload, {
|
||||||
|
lane_id: 3,
|
||||||
|
relay_id: "machine-relay",
|
||||||
|
component: "input",
|
||||||
|
channel: 0,
|
||||||
|
event: "input.toggle_on",
|
||||||
|
state: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
agent.terminate();
|
||||||
|
await broker.close();
|
||||||
|
});
|
||||||
|
|
||||||
test("broker survives telemetry ingestion failures for stale gateways", async () => {
|
test("broker survives telemetry ingestion failures for stale gateways", async () => {
|
||||||
const broker = createBrokerServer({
|
const broker = createBrokerServer({
|
||||||
authMode: "stub",
|
authMode: "stub",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -12452,3 +12452,875 @@
|
|||||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55074 Closing
|
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55074 Closing
|
||||||
[Tue Jun 2 14:17:06 2026] 127.0.0.1:34490 Accepted
|
[Tue Jun 2 14:17:06 2026] 127.0.0.1:34490 Accepted
|
||||||
[Tue Jun 2 14:17:06 2026] 127.0.0.1:34490 Closing
|
[Tue Jun 2 14:17:06 2026] 127.0.0.1:34490 Closing
|
||||||
|
[Thu Jun 4 05:49:23 2026] PHP 8.2.15 Development Server (http://127.0.0.1:41145) started
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56234 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56234 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56242 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56242 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56250 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56250 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56258 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56258 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56272 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56272 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56278 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56278 Closing
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56288 Accepted
|
||||||
|
[Thu Jun 4 05:49:24 2026] 127.0.0.1:56288 Closing
|
||||||
|
[Thu Jun 4 05:49:46 2026] PHP 8.2.15 Development Server (http://127.0.0.1:45671) started
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37442 Accepted
|
||||||
|
[Thu Jun 4 05:49:47 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37442 Closing
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37444 Accepted
|
||||||
|
[Thu Jun 4 05:49:47 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37444 Closing
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37448 Accepted
|
||||||
|
[Thu Jun 4 05:49:47 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37448 Closing
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37462 Accepted
|
||||||
|
[Thu Jun 4 05:49:47 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:47 2026] 127.0.0.1:37462 Closing
|
||||||
|
[Thu Jun 4 05:49:57 2026] PHP 8.2.15 Development Server (http://127.0.0.1:33783) started
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59700 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59700 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59702 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59702 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59708 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59708 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59722 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59722 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59732 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 05:49:58 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59732 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59738 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59738 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59752 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59752 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59756 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 05:49:58 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59756 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59762 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59762 Closing
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59772 Accepted
|
||||||
|
[Thu Jun 4 05:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:58 2026] 127.0.0.1:59772 Closing
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59784 Accepted
|
||||||
|
[Thu Jun 4 05:49:59 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59784 Closing
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59790 Accepted
|
||||||
|
[Thu Jun 4 05:49:59 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59790 Closing
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59806 Accepted
|
||||||
|
[Thu Jun 4 05:49:59 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59806 Closing
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59810 Accepted
|
||||||
|
[Thu Jun 4 05:49:59 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 05:49:59 2026] 127.0.0.1:59810 Closing
|
||||||
|
[Thu Jun 4 06:06:51 2026] PHP 8.2.15 Development Server (http://127.0.0.1:36081) started
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:34670 Accepted
|
||||||
|
[Thu Jun 4 06:06:51 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:34670 Closing
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:34674 Accepted
|
||||||
|
[Thu Jun 4 06:06:51 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:34674 Closing
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:58440 Accepted
|
||||||
|
[Thu Jun 4 06:06:51 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:58440 Closing
|
||||||
|
[Thu Jun 4 06:06:51 2026] 127.0.0.1:58454 Accepted
|
||||||
|
[Thu Jun 4 06:06:51 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58454 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58466 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:06:52 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58466 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58478 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58478 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58492 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58492 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58502 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:06:52 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58502 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58512 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58512 Closing
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58522 Accepted
|
||||||
|
[Thu Jun 4 06:06:52 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:06:52 2026] 127.0.0.1:58522 Closing
|
||||||
|
[Thu Jun 4 06:07:21 2026] 127.0.0.1:56322 Accepted
|
||||||
|
[Thu Jun 4 06:07:21 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:07:21 2026] 127.0.0.1:56322 Closing
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56336 Accepted
|
||||||
|
[Thu Jun 4 06:07:22 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56336 Closing
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56352 Accepted
|
||||||
|
[Thu Jun 4 06:07:22 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56352 Closing
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56362 Accepted
|
||||||
|
[Thu Jun 4 06:07:22 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56362 Closing
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56374 Accepted
|
||||||
|
[Thu Jun 4 06:07:22 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:07:22 2026] 127.0.0.1:56374 Closing
|
||||||
|
[Thu Jun 4 06:18:18 2026] PHP 8.2.15 Development Server (http://127.0.0.1:45139) started
|
||||||
|
[Thu Jun 4 06:18:18 2026] 127.0.0.1:40632 Accepted
|
||||||
|
[Thu Jun 4 06:18:18 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:18 2026] 127.0.0.1:40632 Closing
|
||||||
|
[Thu Jun 4 06:18:18 2026] 127.0.0.1:40646 Accepted
|
||||||
|
[Thu Jun 4 06:18:18 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40646 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40658 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40658 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40672 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40672 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40674 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:19 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40674 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40684 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40684 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40686 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40686 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40700 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:19 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40700 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40702 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40702 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40714 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40714 Closing
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40722 Accepted
|
||||||
|
[Thu Jun 4 06:18:19 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:19 2026] 127.0.0.1:40722 Closing
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40736 Accepted
|
||||||
|
[Thu Jun 4 06:18:20 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40736 Closing
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40752 Accepted
|
||||||
|
[Thu Jun 4 06:18:20 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40752 Closing
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40760 Accepted
|
||||||
|
[Thu Jun 4 06:18:20 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40760 Closing
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40764 Accepted
|
||||||
|
[Thu Jun 4 06:18:20 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40764 Closing
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40768 Accepted
|
||||||
|
[Thu Jun 4 06:18:20 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:20 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:20 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:18:20 2026] 127.0.0.1:40768 Closing
|
||||||
|
[Thu Jun 4 06:18:21 2026] 127.0.0.1:40774 Accepted
|
||||||
|
[Thu Jun 4 06:18:21 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:18:21 2026] 127.0.0.1:40774 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] PHP 8.2.15 Development Server (http://127.0.0.1:40389) started
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60850 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60850 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60856 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60856 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60858 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60858 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60872 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60872 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60874 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:38 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60874 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60890 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60890 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60904 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60904 Closing
|
||||||
|
[Thu Jun 4 06:31:38 2026] 127.0.0.1:60916 Accepted
|
||||||
|
[Thu Jun 4 06:31:38 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:38 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:38 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60916 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60926 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60926 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60936 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60936 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60946 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60946 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60954 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60954 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60960 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60960 Closing
|
||||||
|
[Thu Jun 4 06:31:39 2026] 127.0.0.1:60964 Accepted
|
||||||
|
[Thu Jun 4 06:31:39 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60964 Closing
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60966 Accepted
|
||||||
|
[Thu Jun 4 06:31:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60966 Closing
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60982 Accepted
|
||||||
|
[Thu Jun 4 06:31:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:40 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:40 2026] Failed to log lane action: Table 'nnks_db_test_clone.module_usage_logs' doesn't exist
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60982 Closing
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60990 Accepted
|
||||||
|
[Thu Jun 4 06:31:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:60990 Closing
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:32770 Accepted
|
||||||
|
[Thu Jun 4 06:31:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Thu Jun 4 06:31:40 2026] 127.0.0.1:32770 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] PHP 8.2.15 Development Server (http://127.0.0.1:44515) started
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34204 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34204 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34210 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34210 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34214 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34214 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34226 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34226 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34228 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34228 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34238 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34238 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34244 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34244 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34260 Accepted
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34260 Closing
|
||||||
|
[Fri Jun 12 12:04:15 2026] 127.0.0.1:34274 Accepted
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34274 Closing
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34280 Accepted
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34280 Closing
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34288 Accepted
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34288 Closing
|
||||||
|
[Fri Jun 12 12:04:16 2026] 127.0.0.1:34290 Accepted
|
||||||
|
[Fri Jun 12 12:04:17 2026] 127.0.0.1:34290 Closing
|
||||||
|
[Fri Jun 12 12:04:17 2026] 127.0.0.1:34296 Accepted
|
||||||
|
[Fri Jun 12 12:04:18 2026] 127.0.0.1:34296 Closing
|
||||||
|
[Fri Jun 12 12:04:18 2026] 127.0.0.1:34304 Accepted
|
||||||
|
[Fri Jun 12 12:04:19 2026] 127.0.0.1:34304 Closing
|
||||||
|
[Fri Jun 12 12:04:19 2026] 127.0.0.1:34314 Accepted
|
||||||
|
[Fri Jun 12 12:04:20 2026] 127.0.0.1:34314 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] PHP 8.2.15 Development Server (http://127.0.0.1:35009) started
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57422 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57422 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57428 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57428 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57444 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57444 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57454 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57454 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57470 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57470 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57472 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57472 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57478 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57478 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57488 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57488 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57496 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57496 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57510 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57510 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57520 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57520 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57522 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57522 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57536 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57536 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57548 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57548 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57550 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57550 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57566 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57566 Closing
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57582 Accepted
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:19:47 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:19:47 2026] 127.0.0.1:57582 Closing
|
||||||
|
[Fri Jun 12 12:23:27 2026] PHP 8.2.15 Development Server (http://127.0.0.1:33981) started
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56426 Accepted
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56426 Closing
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56432 Accepted
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56432 Closing
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56438 Accepted
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:23:27 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:23:27 2026] 127.0.0.1:56438 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] PHP 8.2.15 Development Server (http://127.0.0.1:43643) started
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58744 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58744 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58758 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58758 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58764 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58764 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58774 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58774 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58782 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58782 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58788 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58788 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58804 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58804 Closing
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58818 Accepted
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:31 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:31 2026] 127.0.0.1:58818 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58830 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58830 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58834 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58834 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58838 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58838 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58846 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58846 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58862 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58862 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58872 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58872 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58884 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58884 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58890 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58890 Closing
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58896 Accepted
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:32 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:32 2026] 127.0.0.1:58896 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58898 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58898 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58912 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58912 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58918 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58918 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58932 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58932 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58944 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58944 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58956 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58956 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58962 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58962 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58976 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58976 Closing
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58982 Accepted
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:33 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:33 2026] 127.0.0.1:58982 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:58998 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:58998 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59004 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59004 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59012 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59012 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59028 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59028 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59040 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59040 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59046 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59046 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59052 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59052 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59062 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59062 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59074 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59074 Closing
|
||||||
|
[Fri Jun 12 12:39:34 2026] 127.0.0.1:59078 Accepted
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59078 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59080 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59080 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59090 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59090 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59100 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59100 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59102 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59102 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59106 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59106 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59120 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59120 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59122 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59122 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59136 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59136 Closing
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59144 Accepted
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:35 2026] 127.0.0.1:59144 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59158 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59158 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59162 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59162 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59176 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59176 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59190 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59190 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59202 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59202 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59204 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59204 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59212 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59212 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59222 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59222 Closing
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59224 Accepted
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:36 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:36 2026] 127.0.0.1:59224 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59226 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59226 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59230 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59230 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59232 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59232 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59248 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59248 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59254 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59254 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59270 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59270 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59276 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59276 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59290 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59290 Closing
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59300 Accepted
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:37 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:37 2026] 127.0.0.1:59300 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59316 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59316 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59326 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59326 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59330 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59330 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59332 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59332 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59338 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59338 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59350 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59350 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59356 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59356 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59366 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59366 Closing
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59382 Accepted
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:38 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:38 2026] 127.0.0.1:59382 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59392 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59392 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59408 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59408 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59410 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59410 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59426 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59426 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59430 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59430 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59444 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59444 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59452 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59452 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59458 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59458 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59462 Accepted
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:39 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59462 Closing
|
||||||
|
[Fri Jun 12 12:39:39 2026] 127.0.0.1:59470 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59470 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59484 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59484 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59488 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59488 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59496 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59496 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59512 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59512 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59516 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59516 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59524 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59524 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59526 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59526 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59534 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59534 Closing
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59536 Accepted
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:40 2026] 127.0.0.1:59536 Closing
|
||||||
|
[Fri Jun 12 12:39:41 2026] 127.0.0.1:42172 Accepted
|
||||||
|
[Fri Jun 12 12:39:41 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:39:41 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:39:41 2026] 127.0.0.1:42172 Closing
|
||||||
|
[Fri Jun 12 12:41:48 2026] PHP 8.2.15 Development Server (http://127.0.0.1:45327) started
|
||||||
|
[Fri Jun 12 12:41:48 2026] 127.0.0.1:49112 Accepted
|
||||||
|
[Fri Jun 12 12:41:48 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:41:48 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:41:48 2026] 127.0.0.1:49112 Closing
|
||||||
|
[Fri Jun 12 12:42:48 2026] PHP 8.2.15 Development Server (http://127.0.0.1:44757) started
|
||||||
|
[Fri Jun 12 12:42:48 2026] 127.0.0.1:44444 Accepted
|
||||||
|
[Fri Jun 12 12:42:48 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:42:48 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:42:48 2026] 127.0.0.1:44444 Closing
|
||||||
|
[Fri Jun 12 12:43:43 2026] PHP 8.2.15 Development Server (http://127.0.0.1:43731) started
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40338 Accepted
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40338 Closing
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40354 Accepted
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40354 Closing
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40358 Accepted
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:43:43 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 12:43:43 2026] 127.0.0.1:40358 Closing
|
||||||
|
[Fri Jun 12 12:53:28 2026] PHP 8.2.15 Development Server (http://127.0.0.1:41773) started
|
||||||
|
[Fri Jun 12 12:53:29 2026] 127.0.0.1:59496 Accepted
|
||||||
|
[Fri Jun 12 12:53:29 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:53:29 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:53:29 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 12:53:29 2026] 127.0.0.1:59496 Closing
|
||||||
|
[Fri Jun 12 12:53:29 2026] 127.0.0.1:59506 Accepted
|
||||||
|
[Fri Jun 12 12:53:29 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 12:53:29 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 12:53:29 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 12:53:29 2026] 127.0.0.1:59506 Closing
|
||||||
|
[Fri Jun 12 13:42:40 2026] PHP 8.2.15 Development Server (http://127.0.0.1:45259) started
|
||||||
|
[Fri Jun 12 13:42:40 2026] 127.0.0.1:50638 Accepted
|
||||||
|
[Fri Jun 12 13:42:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:42:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:42:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:42:40 2026] 127.0.0.1:50638 Closing
|
||||||
|
[Fri Jun 12 13:42:40 2026] 127.0.0.1:50644 Accepted
|
||||||
|
[Fri Jun 12 13:42:40 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:42:40 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:42:40 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:42:40 2026] 127.0.0.1:50644 Closing
|
||||||
|
[Fri Jun 12 13:45:11 2026] PHP 8.2.15 Development Server (http://127.0.0.1:43693) started
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:59572 Accepted
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:59572 Closing
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:59578 Accepted
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:59578 Closing
|
||||||
|
[Fri Jun 12 13:45:12 2026] PHP 8.2.15 Development Server (http://127.0.0.1:37353) started
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:37666 Accepted
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:37666 Closing
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:37676 Accepted
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:45:12 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:45:12 2026] 127.0.0.1:37676 Closing
|
||||||
|
[Fri Jun 12 13:49:21 2026] PHP 8.2.15 Development Server (http://127.0.0.1:32781) started
|
||||||
|
[Fri Jun 12 13:49:21 2026] 127.0.0.1:57936 Accepted
|
||||||
|
[Fri Jun 12 13:49:21 2026] 127.0.0.1:57936 Closing
|
||||||
|
[Fri Jun 12 13:49:21 2026] 127.0.0.1:57940 Accepted
|
||||||
|
[Fri Jun 12 13:49:21 2026] 127.0.0.1:57940 Closing
|
||||||
|
[Fri Jun 12 13:49:22 2026] PHP 8.2.15 Development Server (http://127.0.0.1:33723) started
|
||||||
|
[Fri Jun 12 13:49:22 2026] 127.0.0.1:60016 Accepted
|
||||||
|
[Fri Jun 12 13:49:22 2026] 127.0.0.1:60016 Closing
|
||||||
|
[Fri Jun 12 13:49:22 2026] 127.0.0.1:60018 Accepted
|
||||||
|
[Fri Jun 12 13:49:22 2026] 127.0.0.1:60018 Closing
|
||||||
|
[Fri Jun 12 13:49:57 2026] PHP 8.2.15 Development Server (http://127.0.0.1:34549) started
|
||||||
|
[Fri Jun 12 13:49:57 2026] 127.0.0.1:59336 Accepted
|
||||||
|
[Fri Jun 12 13:49:57 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:49:57 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:49:57 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:49:57 2026] 127.0.0.1:59336 Closing
|
||||||
|
[Fri Jun 12 13:49:57 2026] 127.0.0.1:59342 Accepted
|
||||||
|
[Fri Jun 12 13:49:57 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:49:57 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:49:57 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:49:58 2026] 127.0.0.1:59342 Closing
|
||||||
|
[Fri Jun 12 13:49:58 2026] PHP 8.2.15 Development Server (http://127.0.0.1:36181) started
|
||||||
|
[Fri Jun 12 13:49:58 2026] 127.0.0.1:39290 Accepted
|
||||||
|
[Fri Jun 12 13:49:58 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:49:58 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:49:58 2026] 127.0.0.1:39290 Closing
|
||||||
|
[Fri Jun 12 13:49:58 2026] 127.0.0.1:39302 Accepted
|
||||||
|
[Fri Jun 12 13:49:58 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 13:49:58 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 13:49:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 13:49:58 2026] 127.0.0.1:39302 Closing
|
||||||
|
[Fri Jun 12 14:03:34 2026] PHP 8.2.15 Development Server (http://127.0.0.1:40101) started
|
||||||
|
[Fri Jun 12 14:03:34 2026] 127.0.0.1:59406 Accepted
|
||||||
|
[Fri Jun 12 14:03:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:03:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:03:34 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:03:34 2026] 127.0.0.1:59406 Closing
|
||||||
|
[Fri Jun 12 14:03:34 2026] 127.0.0.1:59414 Accepted
|
||||||
|
[Fri Jun 12 14:03:34 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:03:34 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:03:34 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:03:34 2026] 127.0.0.1:59414 Closing
|
||||||
|
[Fri Jun 12 14:03:35 2026] PHP 8.2.15 Development Server (http://127.0.0.1:33543) started
|
||||||
|
[Fri Jun 12 14:03:35 2026] 127.0.0.1:60992 Accepted
|
||||||
|
[Fri Jun 12 14:03:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:03:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:03:35 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:03:35 2026] 127.0.0.1:60992 Closing
|
||||||
|
[Fri Jun 12 14:03:35 2026] 127.0.0.1:60994 Accepted
|
||||||
|
[Fri Jun 12 14:03:35 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:03:35 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:03:35 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:03:35 2026] 127.0.0.1:60994 Closing
|
||||||
|
[Fri Jun 12 14:05:57 2026] PHP 8.2.15 Development Server (http://127.0.0.1:46061) started
|
||||||
|
[Fri Jun 12 14:05:57 2026] 127.0.0.1:38780 Accepted
|
||||||
|
[Fri Jun 12 14:05:57 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:05:57 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:05:57 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:05:57 2026] 127.0.0.1:38780 Closing
|
||||||
|
[Fri Jun 12 14:05:57 2026] 127.0.0.1:38792 Accepted
|
||||||
|
[Fri Jun 12 14:05:57 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:05:57 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:05:57 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:05:57 2026] 127.0.0.1:38792 Closing
|
||||||
|
[Fri Jun 12 14:05:57 2026] PHP 8.2.15 Development Server (http://127.0.0.1:34023) started
|
||||||
|
[Fri Jun 12 14:05:58 2026] 127.0.0.1:59736 Accepted
|
||||||
|
[Fri Jun 12 14:05:58 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:05:58 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:05:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:05:58 2026] 127.0.0.1:59736 Closing
|
||||||
|
[Fri Jun 12 14:05:58 2026] 127.0.0.1:59748 Accepted
|
||||||
|
[Fri Jun 12 14:05:58 2026] [config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.
|
||||||
|
[Fri Jun 12 14:05:58 2026] [config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.
|
||||||
|
[Fri Jun 12 14:05:58 2026] [replication-bootstrap] Could not sync startup failover metadata: Class "replication_bootstrap_config" not found
|
||||||
|
[Fri Jun 12 14:05:58 2026] 127.0.0.1:59748 Closing
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ class cors_policy
|
|||||||
{
|
{
|
||||||
public const ALLOWED_HEADERS = 'Content-Type, Authorization, X-Customer-Number, X-Release-Trace, X-Release-Channel, X-Frontend-Version, Cache-Control, Pragma, *';
|
public const ALLOWED_HEADERS = 'Content-Type, Authorization, X-Customer-Number, X-Release-Trace, X-Release-Channel, X-Frontend-Version, Cache-Control, Pragma, *';
|
||||||
public const ALLOWED_METHODS = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
|
public const ALLOWED_METHODS = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
|
||||||
|
public const EXPOSED_HEADERS = 'Server-Timing';
|
||||||
public const MAX_AGE_SECONDS = '86400';
|
public const MAX_AGE_SECONDS = '86400';
|
||||||
|
|
||||||
private const REQUIRED_ALLOWED_ORIGINS = [
|
private const REQUIRED_ALLOWED_ORIGINS = [
|
||||||
@@ -128,7 +129,9 @@ class cors_policy
|
|||||||
'Access-Control-Allow-Credentials' => 'true',
|
'Access-Control-Allow-Credentials' => 'true',
|
||||||
'Access-Control-Allow-Headers' => self::ALLOWED_HEADERS,
|
'Access-Control-Allow-Headers' => self::ALLOWED_HEADERS,
|
||||||
'Access-Control-Allow-Methods' => self::ALLOWED_METHODS,
|
'Access-Control-Allow-Methods' => self::ALLOWED_METHODS,
|
||||||
|
'Access-Control-Expose-Headers' => self::EXPOSED_HEADERS,
|
||||||
'Access-Control-Max-Age' => self::MAX_AGE_SECONDS,
|
'Access-Control-Max-Age' => self::MAX_AGE_SECONDS,
|
||||||
|
'Timing-Allow-Origin' => $origin,
|
||||||
'Vary' => 'Origin',
|
'Vary' => 'Origin',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -240,7 +240,13 @@ class economic_transfer_executor
|
|||||||
'Queued transfer processed successfully for collected invoice #' . $collected_invoice_id
|
'Queued transfer processed successfully for collected invoice #' . $collected_invoice_id
|
||||||
);
|
);
|
||||||
|
|
||||||
return $collected_order_invoices->asArray();
|
$result = $collected_order_invoices->asArray();
|
||||||
|
$transfer_metrics = $collected_order_invoices->getLastEconomicTransferMetrics();
|
||||||
|
if ($transfer_metrics !== null) {
|
||||||
|
$result['economic_transfer_metrics'] = $transfer_metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ class gateway_shelly_transport implements shelly_transport_i
|
|||||||
return match ($endpoint) {
|
return match ($endpoint) {
|
||||||
'/v2/devices/api/get' => $this->handleGetStates($department_id, $data),
|
'/v2/devices/api/get' => $this->handleGetStates($department_id, $data),
|
||||||
'/v2/devices/api/set/switch' => $this->handleSetSwitch($department_id, $data),
|
'/v2/devices/api/set/switch' => $this->handleSetSwitch($department_id, $data),
|
||||||
|
'/v2/devices/api/batch/get' => $this->handleBatchGetStates($department_id, $data),
|
||||||
|
'/v2/devices/api/batch/set/switch' => $this->handleBatchSetSwitch($department_id, $data),
|
||||||
default => throw new Exception('Unsupported gateway Shelly transport endpoint: ' . $endpoint),
|
default => throw new Exception('Unsupported gateway Shelly transport endpoint: ' . $endpoint),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -95,6 +97,52 @@ class gateway_shelly_transport implements shelly_transport_i
|
|||||||
return [$this->normalizeRelayPayload($logicalRelayId, $status)];
|
return [$this->normalizeRelayPayload($logicalRelayId, $status)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
private function handleBatchGetStates(int $departmentId, array $data): array
|
||||||
|
{
|
||||||
|
$requests = [];
|
||||||
|
foreach ((array)($data['commands'] ?? $data['targets'] ?? []) as $entry) {
|
||||||
|
$command = is_array($entry) ? $entry : ['relay_id' => $entry];
|
||||||
|
$relayId = trim((string)($command['relay_id'] ?? $command['relayId'] ?? $command['id'] ?? ''));
|
||||||
|
if ($relayId === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$requests[] = [
|
||||||
|
'target' => strtoupper(trim((string)($command['target'] ?? $relayId))),
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->manager()->queueRelayStatusBatch($departmentId, $requests, null, $this->localOnly);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
private function handleBatchSetSwitch(int $departmentId, array $data): array
|
||||||
|
{
|
||||||
|
$requests = [];
|
||||||
|
foreach ((array)($data['commands'] ?? []) as $entry) {
|
||||||
|
if (!is_array($entry)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$relayId = trim((string)($entry['relay_id'] ?? $entry['relayId'] ?? $entry['id'] ?? ''));
|
||||||
|
if ($relayId === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$requests[] = [
|
||||||
|
'target' => strtoupper(trim((string)($entry['target'] ?? $relayId))),
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'on' => (bool)($entry['on'] ?? false),
|
||||||
|
'toggle_after' => $entry['toggle_after'] ?? $entry['toggleAfter'] ?? $entry['timer'] ?? null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->manager()->queueRelaySwitchBatch($departmentId, $requests, null, $this->localOnly);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string,mixed> $status
|
* @param array<string,mixed> $status
|
||||||
* @return array<string,mixed>
|
* @return array<string,mixed>
|
||||||
|
|||||||
@@ -10,6 +10,22 @@ use licenseplaterecognizer\licenseplaterecognizer_c;
|
|||||||
|
|
||||||
class licenseplaterecognizer implements licenseplaterecognizer_i
|
class licenseplaterecognizer implements licenseplaterecognizer_i
|
||||||
{
|
{
|
||||||
|
private const DEFAULT_API_URL = 'https://vs4sws0kg4sog4ssw8kwowk4.coolify.truckwash.dk';
|
||||||
|
private const PLATE_READER_CONFIG_JSON = '{"mode":"fast","plates_per_vehicle":1,"zoom_in_vehicles":0}';
|
||||||
|
private const RESULT_CACHE_CONTEXT = '{"config":{"mode":"fast","plates_per_vehicle":1,"zoom_in_vehicles":0},"regions":"dk,de,se,no"}';
|
||||||
|
private const PLATE_READER_REGIONS = 'dk,de,se,no';
|
||||||
|
private const DEFAULT_UPLOAD_FILE_NAME = 'license-plate.jpg';
|
||||||
|
private const RUNTIME_CONFIG_CACHE_TTL_SECONDS = 15;
|
||||||
|
private const RUNTIME_CONFIG_REDIS_CACHE_KEY = 'licenseplaterecognizer:runtime_config:v1';
|
||||||
|
private const RESULT_CACHE_TTL_SECONDS = 10;
|
||||||
|
private const RESULT_CACHE_REDIS_KEY_PREFIX = 'licenseplaterecognizer:result:v1:';
|
||||||
|
private const PLATE_READER_CONNECT_TIMEOUT_MS = 1000;
|
||||||
|
private const PLATE_READER_TOTAL_TIMEOUT_MS = 4500;
|
||||||
|
/**
|
||||||
|
* @var array<string, float>
|
||||||
|
*/
|
||||||
|
private array $last_timings = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The configuration of the module
|
* The configuration of the module
|
||||||
* @var licenseplaterecognizer_c
|
* @var licenseplaterecognizer_c
|
||||||
@@ -19,12 +35,25 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
* API URL
|
* API URL
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private string $api_url = 'https://vs4sws0kg4sog4ssw8kwowk4.coolify.truckwash.dk'; // Default (cloud): 'https://api.platerecognizer.com'; (without /v1/plate-reader/)';
|
private string $api_url;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array{enabled: bool, api_key: string}|null
|
||||||
|
*/
|
||||||
|
private ?array $runtime_config = null;
|
||||||
|
|
||||||
public function __construct()
|
/**
|
||||||
|
* @var array{values: array{enabled: bool, api_key: string}, cached_at: float}|null
|
||||||
|
*/
|
||||||
|
private static ?array $runtime_config_cache = null;
|
||||||
|
|
||||||
|
public function __construct(bool $load_config = true, ?string $api_url = null)
|
||||||
{
|
{
|
||||||
$this->config = new licenseplaterecognizer_c();
|
$this->api_url = self::normalizeApiUrl($api_url ?? self::configuredApiUrl());
|
||||||
|
|
||||||
|
if ($load_config) {
|
||||||
|
$this->config = new licenseplaterecognizer_c();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -33,7 +62,7 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
*/
|
*/
|
||||||
public function requireModuleEnabled(): void
|
public function requireModuleEnabled(): void
|
||||||
{
|
{
|
||||||
if (!(bool)$this->config->enabled->getVariableValue()) {
|
if (!$this->runtimeConfig()['enabled']) {
|
||||||
throw new Exception('licenseplaterecognizer module is not enabled.');
|
throw new Exception('licenseplaterecognizer module is not enabled.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,54 +74,516 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
*/
|
*/
|
||||||
public function licenseplaterecognizer(string $base64_image): array
|
public function licenseplaterecognizer(string $base64_image): array
|
||||||
{
|
{
|
||||||
$image_processor = new image_processor();
|
return $this->recognizePlate(
|
||||||
|
fn () => $this->buildPlateReaderPayload($base64_image),
|
||||||
//ADD PARAMETER IN REQUEST LIKE regions
|
fn () => $this->buildResultCacheKeyFromUploadString($base64_image)
|
||||||
$data = array(
|
|
||||||
'upload' => $base64_image,
|
|
||||||
//'regions' => 'dk' // Optional
|
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Prepare new cURL resource
|
public function licenseplaterecognizerUpload(string $image_data, string $mime_type = 'image/jpeg'): array
|
||||||
//$ch = curl_init('https://api.platerecognizer.com/v1/plate-reader/');
|
{
|
||||||
$ch = curl_init($this->api_url . '/v1/plate-reader/');
|
return $this->recognizePlate(
|
||||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
fn () => $this->buildPlateReaderPayloadFromUpload(
|
||||||
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
|
$this->buildUploadValueFromBytes($image_data, $mime_type)
|
||||||
curl_setopt($ch, CURLOPT_POST, true);
|
),
|
||||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
|
fn () => $this->buildResultCacheKeyFromBytes($image_data)
|
||||||
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Set HTTP Header for POST request
|
public function licenseplaterecognizerUploadUncached(string $image_data, string $mime_type = 'image/jpeg'): array
|
||||||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
{
|
||||||
"Authorization: Token " . $this->config->api_key->getVariableValue()
|
return $this->recognizePlate(
|
||||||
|
fn () => $this->buildPlateReaderPayloadFromUpload(
|
||||||
|
$this->buildUploadValueFromBytes($image_data, $mime_type)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Submit the POST request and close cURL session handle
|
public function licenseplaterecognizerUploadFile(string $image_path, string $mime_type = 'image/jpeg'): array
|
||||||
$result = curl_exec($ch);
|
{
|
||||||
curl_close($ch);
|
return $this->recognizePlate(
|
||||||
// Print the response from the server
|
fn () => $this->buildPlateReaderPayloadFromUpload(
|
||||||
if ($result === false) {
|
$this->buildUploadValueFromFile($image_path, $mime_type)
|
||||||
throw new Exception('Error in API request.');
|
)
|
||||||
}
|
);
|
||||||
|
}
|
||||||
|
|
||||||
$response_data = json_decode($result, true);
|
/**
|
||||||
if (isset($response_data['results']) && count($response_data['results']) > 0) {
|
* @throws Exception
|
||||||
return [
|
*/
|
||||||
'success' => true,
|
private function recognizePlate(callable $payload_factory, ?callable $result_cache_key_factory = null): array
|
||||||
'license_plate_number' => $response_data['results'][0]['plate'] ?? null,
|
{
|
||||||
'confidence' => $response_data['results'][0]['score'] ?? null,
|
$started_at = microtime(true);
|
||||||
'raw_response' => $response_data,
|
$this->last_timings = [];
|
||||||
|
$result_cache = null;
|
||||||
|
$result_cache_key = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$config_started_at = microtime(true);
|
||||||
|
$runtime_config = $this->runtimeConfig();
|
||||||
|
if (!$runtime_config['enabled']) {
|
||||||
|
throw new Exception('licenseplaterecognizer module is not enabled.');
|
||||||
|
}
|
||||||
|
$api_key = $runtime_config['api_key'];
|
||||||
|
$this->last_timings['config'] = $this->elapsedMs($config_started_at);
|
||||||
|
|
||||||
|
if ($result_cache_key_factory !== null) {
|
||||||
|
$cache_started_at = microtime(true);
|
||||||
|
try {
|
||||||
|
$result_cache = $this->resultCacheStore();
|
||||||
|
if ($result_cache !== null) {
|
||||||
|
$result_cache_key = $result_cache_key_factory();
|
||||||
|
if ($result_cache_key !== null) {
|
||||||
|
$cached_result = $this->readRecognitionResultCache($result_cache, $result_cache_key);
|
||||||
|
if ($cached_result !== null) {
|
||||||
|
$this->last_timings['cache_hit'] = 1;
|
||||||
|
return $cached_result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->last_timings['cache_miss'] = 1;
|
||||||
|
} finally {
|
||||||
|
$this->last_timings['cache'] = $this->elapsedMs($cache_started_at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload_started_at = microtime(true);
|
||||||
|
$data = $payload_factory();
|
||||||
|
$this->last_timings['payload'] = $this->elapsedMs($payload_started_at);
|
||||||
|
|
||||||
|
$ch = curl_init($this->api_url . '/v1/plate-reader/');
|
||||||
|
if (!$ch instanceof \CurlHandle) {
|
||||||
|
throw new Exception('Error initializing API request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$curl_options = [
|
||||||
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
|
CURLOPT_POST => true,
|
||||||
|
CURLOPT_POSTFIELDS => $data,
|
||||||
|
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
|
||||||
|
CURLOPT_CONNECTTIMEOUT_MS => self::PLATE_READER_CONNECT_TIMEOUT_MS,
|
||||||
|
CURLOPT_TIMEOUT_MS => self::PLATE_READER_TOTAL_TIMEOUT_MS,
|
||||||
|
CURLOPT_NOSIGNAL => true,
|
||||||
|
CURLOPT_NOPROGRESS => false,
|
||||||
|
CURLOPT_XFERINFOFUNCTION => self::clientDisconnectAbortCallback(),
|
||||||
|
CURLOPT_HTTPHEADER => [
|
||||||
|
"Authorization: Token " . $api_key,
|
||||||
|
'Expect:',
|
||||||
|
],
|
||||||
];
|
];
|
||||||
} else {
|
if (defined('CURLOPT_TCP_NODELAY')) {
|
||||||
return [
|
$curl_options[(int)constant('CURLOPT_TCP_NODELAY')] = true;
|
||||||
|
}
|
||||||
|
curl_setopt_array($ch, $curl_options);
|
||||||
|
|
||||||
|
// Submit the POST request and close cURL session handle
|
||||||
|
$upstream_started_at = microtime(true);
|
||||||
|
$result = curl_exec($ch);
|
||||||
|
$this->last_timings['upstream'] = $this->elapsedMs($upstream_started_at);
|
||||||
|
$this->recordCurlTimings($ch);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
// Print the response from the server
|
||||||
|
if ($result === false) {
|
||||||
|
throw new Exception('Error in API request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$parse_started_at = microtime(true);
|
||||||
|
$response_data = json_decode($result, true);
|
||||||
|
$this->last_timings['parse'] = $this->elapsedMs($parse_started_at);
|
||||||
|
$this->recordResponseTimings($response_data);
|
||||||
|
|
||||||
|
if (isset($response_data['results']) && count($response_data['results']) > 0) {
|
||||||
|
$recognized_result = [
|
||||||
|
'success' => true,
|
||||||
|
'license_plate_number' => $response_data['results'][0]['plate'] ?? null,
|
||||||
|
'confidence' => $response_data['results'][0]['score'] ?? null,
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->writeRecognitionResultCache($result_cache, $result_cache_key, $recognized_result);
|
||||||
|
|
||||||
|
return $recognized_result;
|
||||||
|
}
|
||||||
|
|
||||||
|
$recognized_result = [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => 'No license plate detected.',
|
'message' => 'No license plate detected.',
|
||||||
'raw_response' => $response_data,
|
|
||||||
];
|
];
|
||||||
|
$this->writeRecognitionResultCache($result_cache, $result_cache_key, $recognized_result);
|
||||||
|
|
||||||
|
return $recognized_result;
|
||||||
|
} finally {
|
||||||
|
$this->last_timings['total'] = $this->elapsedMs($started_at);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static function clientDisconnectAbortCallback(): callable
|
||||||
|
{
|
||||||
|
return static function (): int {
|
||||||
|
return connection_aborted() ? 1 : 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getLastTimings(): array
|
||||||
|
{
|
||||||
|
return $this->last_timings;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function elapsedMs(float $started_at): float
|
||||||
|
{
|
||||||
|
return (microtime(true) - $started_at) * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function configuredApiUrl(): string
|
||||||
|
{
|
||||||
|
$configured = getenv('PLATE_RECOGNIZER_API_URL');
|
||||||
|
if ($configured === false || trim((string)$configured) === '') {
|
||||||
|
$configured = $_ENV['PLATE_RECOGNIZER_API_URL'] ?? $_SERVER['PLATE_RECOGNIZER_API_URL'] ?? self::DEFAULT_API_URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string)$configured;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function normalizeApiUrl(string $api_url): string
|
||||||
|
{
|
||||||
|
$api_url = trim($api_url);
|
||||||
|
if ($api_url === '') {
|
||||||
|
return self::DEFAULT_API_URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rtrim($api_url, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recordCurlTimings(\CurlHandle $curl_handle): void
|
||||||
|
{
|
||||||
|
$mapping = [
|
||||||
|
CURLINFO_NAMELOOKUP_TIME => 'upstream_dns',
|
||||||
|
CURLINFO_CONNECT_TIME => 'upstream_connect',
|
||||||
|
CURLINFO_APPCONNECT_TIME => 'upstream_tls',
|
||||||
|
CURLINFO_PRETRANSFER_TIME => 'upstream_pretransfer',
|
||||||
|
CURLINFO_STARTTRANSFER_TIME => 'upstream_ttfb',
|
||||||
|
CURLINFO_TOTAL_TIME => 'upstream_total',
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($mapping as $curl_info_option => $timing_key) {
|
||||||
|
$value = curl_getinfo($curl_handle, $curl_info_option);
|
||||||
|
if (!is_numeric($value)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->last_timings[$timing_key] = max(0, (float)$value * 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recordResponseTimings(mixed $response_data): void
|
||||||
|
{
|
||||||
|
if (!is_array($response_data) || !isset($response_data['processing_time']) || !is_numeric($response_data['processing_time'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->last_timings['upstream_processing'] = max(0, (float)$response_data['processing_time']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildResultCacheKeyFromUploadString(string $base64_image): string
|
||||||
|
{
|
||||||
|
$base64_image = trim($base64_image);
|
||||||
|
if (preg_match('/^data:image\/[a-zA-Z0-9.+-]+;base64,(.*)$/s', $base64_image, $matches) === 1) {
|
||||||
|
$image_data = base64_decode((string)$matches[1], true);
|
||||||
|
if (is_string($image_data)) {
|
||||||
|
return $this->buildResultCacheKeyFromBytes($image_data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->buildResultCacheKeyFromBytes($base64_image);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildResultCacheKeyFromBytes(string $image_data): string
|
||||||
|
{
|
||||||
|
$context = hash_init('sha256');
|
||||||
|
hash_update($context, $this->resultCacheContext());
|
||||||
|
hash_update($context, "\0");
|
||||||
|
hash_update($context, $image_data);
|
||||||
|
|
||||||
|
return self::RESULT_CACHE_REDIS_KEY_PREFIX . hash_final($context);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resultCacheContext(): string
|
||||||
|
{
|
||||||
|
return self::RESULT_CACHE_CONTEXT;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resultCacheStore(): ?object
|
||||||
|
{
|
||||||
|
return $this->runtimeConfigCacheStore();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function readRecognitionResultCache(?object $cache, ?string $key): ?array
|
||||||
|
{
|
||||||
|
if ($cache === null || $key === null || !method_exists($cache, 'get')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cached = $cache->get($key);
|
||||||
|
} catch (\Throwable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_string($cached) || trim($cached) === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($cached, true);
|
||||||
|
if (!is_array($decoded) || !array_key_exists('success', $decoded)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function writeRecognitionResultCache(?object $cache, ?string $key, array $result): void
|
||||||
|
{
|
||||||
|
if ($cache === null || $key === null || !method_exists($cache, 'setEx')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$encoded = json_encode($result, JSON_UNESCAPED_SLASHES);
|
||||||
|
if (is_string($encoded)) {
|
||||||
|
$cache->setEx($key, $encoded, self::RESULT_CACHE_TTL_SECONDS);
|
||||||
|
}
|
||||||
|
} catch (\Throwable) {
|
||||||
|
// Scanner result cache is best-effort; Plate Recognizer remains the source of truth.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function buildPlateReaderPayload(string $base64_image): array
|
||||||
|
{
|
||||||
|
return $this->buildPlateReaderPayloadFromUpload($this->buildUploadValue($base64_image));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function buildPlateReaderPayloadFromUpload(string|\CURLFile|\CURLStringFile $upload): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'upload' => $upload,
|
||||||
|
'config' => self::PLATE_READER_CONFIG_JSON,
|
||||||
|
'regions' => self::PLATE_READER_REGIONS,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildUploadValue(string $base64_image): string|\CURLStringFile
|
||||||
|
{
|
||||||
|
$base64_image = trim($base64_image);
|
||||||
|
if (preg_match('/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.*)$/s', $base64_image, $matches) !== 1) {
|
||||||
|
return $base64_image;
|
||||||
|
}
|
||||||
|
|
||||||
|
$image_data = base64_decode((string)$matches[2], true);
|
||||||
|
if ($image_data === false || !class_exists(\CURLStringFile::class)) {
|
||||||
|
return (string)$matches[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
return new \CURLStringFile($image_data, self::DEFAULT_UPLOAD_FILE_NAME, (string)$matches[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildUploadValueFromBytes(string $image_data, string $mime_type): string|\CURLStringFile
|
||||||
|
{
|
||||||
|
$mime_type = trim($mime_type) !== '' ? trim($mime_type) : 'image/jpeg';
|
||||||
|
if (!str_starts_with($mime_type, 'image/')) {
|
||||||
|
$mime_type = 'image/jpeg';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists(\CURLStringFile::class)) {
|
||||||
|
return $image_data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new \CURLStringFile($image_data, self::DEFAULT_UPLOAD_FILE_NAME, $mime_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
private function buildUploadValueFromFile(string $image_path, string $mime_type): \CURLFile
|
||||||
|
{
|
||||||
|
$image_path = trim($image_path);
|
||||||
|
$mime_type = trim($mime_type) !== '' ? trim($mime_type) : 'image/jpeg';
|
||||||
|
if (!str_starts_with($mime_type, 'image/')) {
|
||||||
|
$mime_type = 'image/jpeg';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($image_path === '' || !is_file($image_path) || !class_exists(\CURLFile::class)) {
|
||||||
|
throw new Exception('Image upload file is invalid.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return new \CURLFile($image_path, $mime_type, self::DEFAULT_UPLOAD_FILE_NAME);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function runtimeConfig(): array
|
||||||
|
{
|
||||||
|
if ($this->runtime_config !== null) {
|
||||||
|
return $this->runtime_config;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->shouldUseSharedRuntimeConfigCache()) {
|
||||||
|
$cached_config = self::getSharedRuntimeConfigCache();
|
||||||
|
if ($cached_config !== null) {
|
||||||
|
$this->runtime_config = $cached_config;
|
||||||
|
|
||||||
|
return $this->runtime_config;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cached_config = $this->readRuntimeConfigCacheStore();
|
||||||
|
if ($cached_config !== null) {
|
||||||
|
self::$runtime_config_cache = [
|
||||||
|
'values' => $cached_config,
|
||||||
|
'cached_at' => microtime(true),
|
||||||
|
];
|
||||||
|
$this->runtime_config = $cached_config;
|
||||||
|
|
||||||
|
return $this->runtime_config;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$values = $this->readRuntimeModuleConfig();
|
||||||
|
|
||||||
|
$this->runtime_config = [
|
||||||
|
'enabled' => $this->parseModuleConfigBool($values['enabled'] ?? false),
|
||||||
|
'api_key' => (string)($values['api_key'] ?? ''),
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($this->shouldUseSharedRuntimeConfigCache()) {
|
||||||
|
self::$runtime_config_cache = [
|
||||||
|
'values' => $this->runtime_config,
|
||||||
|
'cached_at' => microtime(true),
|
||||||
|
];
|
||||||
|
$this->writeRuntimeConfigCacheStore($this->runtime_config);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->runtime_config;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function shouldUseSharedRuntimeConfigCache(): bool
|
||||||
|
{
|
||||||
|
return static::class === self::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getSharedRuntimeConfigCache(): ?array
|
||||||
|
{
|
||||||
|
if (self::$runtime_config_cache === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cache_age_seconds = microtime(true) - self::$runtime_config_cache['cached_at'];
|
||||||
|
if ($cache_age_seconds > self::RUNTIME_CONFIG_CACHE_TTL_SECONDS) {
|
||||||
|
self::$runtime_config_cache = null;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::$runtime_config_cache['values'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function runtimeConfigCacheStore(): ?object
|
||||||
|
{
|
||||||
|
return defined('redis') ? constant('redis') : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function readRuntimeConfigCacheStore(): ?array
|
||||||
|
{
|
||||||
|
$cache = $this->runtimeConfigCacheStore();
|
||||||
|
if ($cache === null || !method_exists($cache, 'get')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cached = $cache->get(self::RUNTIME_CONFIG_REDIS_CACHE_KEY);
|
||||||
|
} catch (\Throwable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_string($cached) || trim($cached) === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($cached, true);
|
||||||
|
if (!is_array($decoded)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!array_key_exists('enabled', $decoded) || !array_key_exists('api_key', $decoded)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'enabled' => $this->parseModuleConfigBool($decoded['enabled']),
|
||||||
|
'api_key' => (string)$decoded['api_key'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{enabled: bool, api_key: string} $config
|
||||||
|
*/
|
||||||
|
private function writeRuntimeConfigCacheStore(array $config): void
|
||||||
|
{
|
||||||
|
$cache = $this->runtimeConfigCacheStore();
|
||||||
|
if ($cache === null || !method_exists($cache, 'setEx')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$encoded = json_encode($config, JSON_UNESCAPED_SLASHES);
|
||||||
|
if (is_string($encoded)) {
|
||||||
|
$cache->setEx(self::RUNTIME_CONFIG_REDIS_CACHE_KEY, $encoded, self::RUNTIME_CONFIG_CACHE_TTL_SECONDS);
|
||||||
|
}
|
||||||
|
} catch (\Throwable) {
|
||||||
|
// Scanner config cache is best-effort; DB remains the source of truth.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function parseModuleConfigBool(mixed $value): bool
|
||||||
|
{
|
||||||
|
if (is_bool($value)) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_numeric($value)) {
|
||||||
|
return (int)$value === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return strtolower(trim((string)$value)) === 'true';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function readRuntimeModuleConfig(): array
|
||||||
|
{
|
||||||
|
global $db;
|
||||||
|
|
||||||
|
if ($db instanceof db) {
|
||||||
|
$module = $db->escape_string('licenseplaterecognizer');
|
||||||
|
$result = $db->query("SELECT variable, value FROM module_config WHERE module = '$module' AND variable IN ('enabled', 'api_key')");
|
||||||
|
$values = [];
|
||||||
|
|
||||||
|
if ($result instanceof \mysqli_result) {
|
||||||
|
while ($row = $result->fetch_assoc()) {
|
||||||
|
$variable = (string)($row['variable'] ?? '');
|
||||||
|
if ($variable !== '') {
|
||||||
|
$values[$variable] = (string)($row['value'] ?? '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $values;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($this->config)) {
|
||||||
|
$this->config = new licenseplaterecognizer_c();
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'enabled' => (string)$this->config->enabled->getVariableValue(),
|
||||||
|
'api_key' => (string)$this->config->api_key->getVariableValue(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @inheritDoc
|
* @inheritDoc
|
||||||
* @throws Exception If the module is not enabled or if there is an error in the API request
|
* @throws Exception If the module is not enabled or if there is an error in the API request
|
||||||
@@ -100,8 +591,8 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
*/
|
*/
|
||||||
public function get_usage(): licenseplaterecognizer_info
|
public function get_usage(): licenseplaterecognizer_info
|
||||||
{
|
{
|
||||||
// Require the module to be enabled
|
|
||||||
$this->requireModuleEnabled();
|
$this->requireModuleEnabled();
|
||||||
|
$api_key = $this->runtimeConfig()['api_key'];
|
||||||
$curl = curl_init();
|
$curl = curl_init();
|
||||||
curl_setopt_array($curl, array(
|
curl_setopt_array($curl, array(
|
||||||
CURLOPT_URL => $this->api_url . '/info/',
|
CURLOPT_URL => $this->api_url . '/info/',
|
||||||
@@ -112,9 +603,9 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
CURLOPT_FOLLOWLOCATION => true,
|
CURLOPT_FOLLOWLOCATION => true,
|
||||||
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
|
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
|
||||||
CURLOPT_CUSTOMREQUEST => 'GET',
|
CURLOPT_CUSTOMREQUEST => 'GET',
|
||||||
CURLOPT_HTTPHEADER => array(
|
CURLOPT_HTTPHEADER => [
|
||||||
'Authorization: Token ' . $this->config->api_key->getVariableValue()
|
'Authorization: Token ' . $api_key,
|
||||||
),
|
],
|
||||||
));
|
));
|
||||||
$response = curl_exec($curl);
|
$response = curl_exec($curl);
|
||||||
curl_close($curl);
|
curl_close($curl);
|
||||||
@@ -124,4 +615,4 @@ class licenseplaterecognizer implements licenseplaterecognizer_i
|
|||||||
}
|
}
|
||||||
return new licenseplaterecognizer_info($response_data);
|
return new licenseplaterecognizer_info($response_data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace classes;
|
||||||
|
|
||||||
|
class limited_backoffice_exception extends \RuntimeException
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
string $message,
|
||||||
|
private readonly int $statusCode = 400,
|
||||||
|
private readonly ?array $payload = null
|
||||||
|
) {
|
||||||
|
parent::__construct($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function statusCode(): int
|
||||||
|
{
|
||||||
|
return $this->statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function payload(): array|string
|
||||||
|
{
|
||||||
|
return $this->payload ?? $this->getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace classes;
|
||||||
|
|
||||||
|
class limited_backoffice_schema_bootstrap
|
||||||
|
{
|
||||||
|
private static bool $initialized = false;
|
||||||
|
|
||||||
|
public static function ensureTables(): void
|
||||||
|
{
|
||||||
|
if (self::$initialized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
global $db;
|
||||||
|
|
||||||
|
if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$db->query(<<<'SQL'
|
||||||
|
CREATE TABLE IF NOT EXISTS `limited_backoffice_employees` (
|
||||||
|
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` INT NOT NULL,
|
||||||
|
`managed_group_id` INT NOT NULL,
|
||||||
|
`role_key` VARCHAR(64) NOT NULL,
|
||||||
|
`department_ids` LONGTEXT NOT NULL,
|
||||||
|
`created_by_user_id` INT NOT NULL,
|
||||||
|
`updated_by_user_id` INT NULL,
|
||||||
|
`deactivated_at` DATETIME NULL,
|
||||||
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uniq_limited_backoffice_employees_user_id` (`user_id`),
|
||||||
|
KEY `idx_limited_backoffice_employees_group_id` (`managed_group_id`),
|
||||||
|
KEY `idx_limited_backoffice_employees_role_key` (`role_key`),
|
||||||
|
KEY `idx_limited_backoffice_employees_deactivated_at` (`deactivated_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
SQL);
|
||||||
|
|
||||||
|
self::$initialized = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -89,7 +89,7 @@ class router
|
|||||||
}
|
}
|
||||||
// Regex
|
// Regex
|
||||||
$route = str_replace('/', '\/', $route);
|
$route = str_replace('/', '\/', $route);
|
||||||
$route = preg_replace('/{[a-zA-Z0-9]+}/', '([a-zA-Z0-9]+)', $route);
|
$route = preg_replace('/{[a-zA-Z0-9_]+}/', '([a-zA-Z0-9]+)', $route);
|
||||||
if (preg_match('/^' . $route . '$/', $this->url)) {
|
if (preg_match('/^' . $route . '$/', $this->url)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -196,11 +196,104 @@ class slack implements notification_i
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a sanitized internal department goal progress test notification to the saved Slack webhook.
|
||||||
|
*
|
||||||
|
* @return array{configured:bool,sent:bool,message:string}
|
||||||
|
*/
|
||||||
|
public function test_internal_department_goal_progress_webhook(): array
|
||||||
|
{
|
||||||
|
$webhook = $this->get_internal_department_goal_progress_webhook_url();
|
||||||
|
if ($webhook === '') {
|
||||||
|
return [
|
||||||
|
'configured' => false,
|
||||||
|
'sent' => false,
|
||||||
|
'message' => 'Slack internal department goal progress webhook URL is not configured.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $this->send_webhook_message(
|
||||||
|
$this->format_internal_department_goal_progress_test(),
|
||||||
|
$webhook
|
||||||
|
);
|
||||||
|
$sent = $this->is_webhook_send_successful($result);
|
||||||
|
|
||||||
|
self::add_log($sent
|
||||||
|
? 'Slack internal department goal progress test webhook sent successfully.'
|
||||||
|
: 'Slack internal department goal progress test webhook failed.'
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'configured' => true,
|
||||||
|
'sent' => $sent,
|
||||||
|
'message' => $sent
|
||||||
|
? 'Slack test message sent successfully.'
|
||||||
|
: 'Slack test message failed.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
protected function get_customer_registration_webhook_url(): string
|
protected function get_customer_registration_webhook_url(): string
|
||||||
{
|
{
|
||||||
return trim((string)$this->getConfig()->customer_registration_webhook_url->getVariableValue());
|
return trim((string)$this->getConfig()->customer_registration_webhook_url->getVariableValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function get_internal_department_goal_progress_webhook_url(): string
|
||||||
|
{
|
||||||
|
return trim((string)$this->getConfig()->internal_department_goal_progress_webhook_url->getVariableValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return int[]
|
||||||
|
*/
|
||||||
|
public function get_internal_department_ids(): array
|
||||||
|
{
|
||||||
|
return $this->getConfig()->internal_department_ids->getDepartmentIds();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int[] $department_ids
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
public function set_internal_department_goal_progress_config(string $webhook_url, array $department_ids): array
|
||||||
|
{
|
||||||
|
$this->getConfig()->internal_department_goal_progress_webhook_url->setVariableValue(trim($webhook_url));
|
||||||
|
$this->getConfig()->internal_department_ids->setVariableValue($department_ids);
|
||||||
|
|
||||||
|
return $this->get_internal_department_goal_progress_config();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_internal_department_goal_progress_config(): array
|
||||||
|
{
|
||||||
|
$departments = (new departments_o())->getFieldsWhere(
|
||||||
|
[
|
||||||
|
'visible' => 1,
|
||||||
|
'archived' => 0,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'id',
|
||||||
|
'name',
|
||||||
|
'order_priority',
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
usort($departments, static function (array $a, array $b): int {
|
||||||
|
return (int)($a['order_priority'] ?? 0) <=> (int)($b['order_priority'] ?? 0)
|
||||||
|
?: (int)($a['id'] ?? 0) <=> (int)($b['id'] ?? 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
'internal_department_goal_progress_webhook_url' => $this->get_internal_department_goal_progress_webhook_url(),
|
||||||
|
'internal_department_ids' => $this->get_internal_department_ids(),
|
||||||
|
'departments' => array_map(static function (array $department): array {
|
||||||
|
return [
|
||||||
|
'id' => (int)$department['id'],
|
||||||
|
'name' => (string)$department['name'],
|
||||||
|
'order_priority' => (int)$department['order_priority'],
|
||||||
|
];
|
||||||
|
}, $departments),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function is_webhook_send_successful(string $result): bool
|
public function is_webhook_send_successful(string $result): bool
|
||||||
{
|
{
|
||||||
return !str_starts_with($result, 'Failed to send message:');
|
return !str_starts_with($result, 'Failed to send message:');
|
||||||
@@ -230,4 +323,10 @@ class slack implements notification_i
|
|||||||
return "*Truck Wash Slack test*\n"
|
return "*Truck Wash Slack test*\n"
|
||||||
. "Customer registration notifications are configured correctly.";
|
. "Customer registration notifications are configured correctly.";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function format_internal_department_goal_progress_test(): string
|
||||||
|
{
|
||||||
|
return "*Truck Wash Slack test*\n"
|
||||||
|
. "Internal department goal progress notifications are configured correctly.";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,10 +12,35 @@ interface licenseplaterecognizer_i extends universal_module_i
|
|||||||
* @return array An array containing the plate number and other relevant information.
|
* @return array An array containing the plate number and other relevant information.
|
||||||
*/
|
*/
|
||||||
public function licenseplaterecognizer(string $base64_image): array;
|
public function licenseplaterecognizer(string $base64_image): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the plate number from raw uploaded image bytes.
|
||||||
|
* @param string $image_data Raw uploaded image bytes.
|
||||||
|
* @param string $mime_type The image MIME type.
|
||||||
|
* @return array An array containing the plate number and other relevant information.
|
||||||
|
*/
|
||||||
|
public function licenseplaterecognizerUpload(string $image_data, string $mime_type = 'image/jpeg'): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the plate number from raw uploaded image bytes without building an exact-result cache key.
|
||||||
|
* @param string $image_data Raw uploaded image bytes.
|
||||||
|
* @param string $mime_type The image MIME type.
|
||||||
|
* @return array An array containing the plate number and other relevant information.
|
||||||
|
*/
|
||||||
|
public function licenseplaterecognizerUploadUncached(string $image_data, string $mime_type = 'image/jpeg'): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the plate number from a PHP upload temp file without copying it into memory.
|
||||||
|
* @param string $image_path The uploaded image temp-file path.
|
||||||
|
* @param string $mime_type The image MIME type.
|
||||||
|
* @return array An array containing the plate number and other relevant information.
|
||||||
|
*/
|
||||||
|
public function licenseplaterecognizerUploadFile(string $image_path, string $mime_type = 'image/jpeg'): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get usage information about the license plate recognizer module.
|
* Get usage information about the license plate recognizer module.
|
||||||
* @returns licenseplaterecognizer_info An object containing usage statistics and information.
|
* @returns licenseplaterecognizer_info An object containing usage statistics and information.
|
||||||
* @see licenseplaterecognizer_info
|
* @see licenseplaterecognizer_info
|
||||||
*/
|
*/
|
||||||
public function get_usage(): licenseplaterecognizer_info;
|
public function get_usage(): licenseplaterecognizer_info;
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-5
@@ -61,19 +61,47 @@ class economic_invoices_draft_endpoint
|
|||||||
* @throws Exception If the request fails
|
* @throws Exception If the request fails
|
||||||
*/
|
*/
|
||||||
public function add_order(int $invoiceDraftId, orders_o $order, string $currency = 'DKK'): void
|
public function add_order(int $invoiceDraftId, orders_o $order, string $currency = 'DKK'): void
|
||||||
|
{
|
||||||
|
$this->add_orders($invoiceDraftId, [$order], $currency);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add many orders to a draft invoice and flush their lines in batches.
|
||||||
|
*
|
||||||
|
* @param orders_o[] $orders
|
||||||
|
* @return array{order_count:int,orders_with_invoice_lines:int,line_count:int,batch_count:int,batch_sizes:array<int,int>}
|
||||||
|
* @throws Exception If the request fails
|
||||||
|
*/
|
||||||
|
public function add_orders(int $invoiceDraftId, array $orders, string $currency = 'DKK', int $line_batch_size = 500): array
|
||||||
{
|
{
|
||||||
$draftInvoice = (new economic())->getInvoiceDraft($invoiceDraftId, strtoupper($currency), true);
|
$draftInvoice = (new economic())->getInvoiceDraft($invoiceDraftId, strtoupper($currency), true);
|
||||||
// Check if the order includes any items that should be included in the invoice
|
$orders_with_invoice_lines = 0;
|
||||||
if ($order->getIncludeInInvoiceCount() > 0) {
|
|
||||||
|
foreach ( $orders as $order ) {
|
||||||
|
if (!$order instanceof orders_o) {
|
||||||
|
throw new Exception('Order payload must contain orders_o instances');
|
||||||
|
}
|
||||||
|
// Check if the order includes any items that should be included in the invoice
|
||||||
|
if ($order->getIncludeInInvoiceCount() <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$orders_with_invoice_lines++;
|
||||||
// Add the transaction header (Timestamp, department, etc.)
|
// Add the transaction header (Timestamp, department, etc.)
|
||||||
$draftInvoice->addNewTransactionHeader($order);
|
$draftInvoice->addNewTransactionHeader($order);
|
||||||
// Add the order lines
|
// Add the order lines
|
||||||
$draftInvoice->addOrderItemLines($order);
|
$draftInvoice->addOrderItemLines($order);
|
||||||
// Add an empty line, so the invoice is not empty
|
// Add an empty line, so the invoice is not empty
|
||||||
$draftInvoice->addTextLine('');
|
$draftInvoice->addTextLine('');
|
||||||
// Save the draft invoice lines
|
|
||||||
$draftInvoice->addLines();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$metrics = $draftInvoice->flushLinesInBatches($line_batch_size);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'order_count' => count($orders),
|
||||||
|
'orders_with_invoice_lines' => $orders_with_invoice_lines,
|
||||||
|
...$metrics,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -151,4 +179,4 @@ class economic_invoices_draft_endpoint
|
|||||||
$draft_invoice->addLines();
|
$draft_invoice->addLines();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ use objects\orders_o;
|
|||||||
|
|
||||||
class economic_invoice_draft
|
class economic_invoice_draft
|
||||||
{
|
{
|
||||||
|
public const DEFAULT_LINE_BATCH_SIZE = 500;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Economic draftInvoiceNumber
|
* The Economic draftInvoiceNumber
|
||||||
* @var int $draft_invoice_number
|
* @var int $draft_invoice_number
|
||||||
@@ -110,13 +112,55 @@ class economic_invoice_draft
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add the lines to the draft invoice
|
* Add the lines to the draft invoice.
|
||||||
* @return void
|
|
||||||
*/
|
*/
|
||||||
public function addLines(): void
|
public function addLines(): void
|
||||||
|
{
|
||||||
|
$this->flushLinesInBatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add queued draft lines using chunked requests.
|
||||||
|
*
|
||||||
|
* @return array{line_count:int,batch_count:int,batch_sizes:array<int,int>}
|
||||||
|
*/
|
||||||
|
public function flushLinesInBatches(int $batch_size = self::DEFAULT_LINE_BATCH_SIZE): array
|
||||||
|
{
|
||||||
|
$lines = array_values($this->draft_lines);
|
||||||
|
$line_count = count($lines);
|
||||||
|
if ($line_count === 0) {
|
||||||
|
return [
|
||||||
|
'line_count' => 0,
|
||||||
|
'batch_count' => 0,
|
||||||
|
'batch_sizes' => [],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$batch_size = max(1, $batch_size);
|
||||||
|
$batch_sizes = [];
|
||||||
|
foreach (array_chunk($lines, $batch_size) as $batch) {
|
||||||
|
$this->sendDraftLines($batch);
|
||||||
|
$batch_sizes[] = count($batch);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->draft_lines = [];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'line_count' => $line_count,
|
||||||
|
'batch_count' => count($batch_sizes),
|
||||||
|
'batch_sizes' => $batch_sizes,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pendingLineCount(): int
|
||||||
|
{
|
||||||
|
return count($this->draft_lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function sendDraftLines(array $draft_lines): object
|
||||||
{
|
{
|
||||||
$economic = new economic();
|
$economic = new economic();
|
||||||
$economic->invoices->draft->add_lines($this->draft_invoice_number, $this->draft_lines);
|
return $economic->invoices->draft->add_lines($this->draft_invoice_number, $draft_lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+44
-3
@@ -6,6 +6,7 @@ use Exception;
|
|||||||
|
|
||||||
class edge_gateway_agent_artifact_locator
|
class edge_gateway_agent_artifact_locator
|
||||||
{
|
{
|
||||||
|
private const EDGE_AGENT_BUILD_ARTIFACT_DIRECTORY = 'build/install';
|
||||||
private const ROUTER_ARTIFACT_DIRECTORY = 'resources/edge-gateway-agent';
|
private const ROUTER_ARTIFACT_DIRECTORY = 'resources/edge-gateway-agent';
|
||||||
private const DEFAULT_MOUNTED_ARTIFACT_DIRECTORY = '/services/edge-agent/php-agent';
|
private const DEFAULT_MOUNTED_ARTIFACT_DIRECTORY = '/services/edge-agent/php-agent';
|
||||||
private const DEFAULT_BAKED_ARTIFACT_DIRECTORY = '/opt/truckwash-edge-agent-artifacts';
|
private const DEFAULT_BAKED_ARTIFACT_DIRECTORY = '/opt/truckwash-edge-agent-artifacts';
|
||||||
@@ -30,6 +31,10 @@ class edge_gateway_agent_artifact_locator
|
|||||||
|
|
||||||
$candidateDirectories[] = self::routerArtifactDirectory($basePath);
|
$candidateDirectories[] = self::routerArtifactDirectory($basePath);
|
||||||
|
|
||||||
|
foreach (self::edgeAgentBuildDirectories($basePath) as $directory) {
|
||||||
|
$candidateDirectories[] = $directory;
|
||||||
|
}
|
||||||
|
|
||||||
$mountedArtifactDirectory = $mountedArtifactDirectory ?? self::mountedArtifactDirectory();
|
$mountedArtifactDirectory = $mountedArtifactDirectory ?? self::mountedArtifactDirectory();
|
||||||
if ($mountedArtifactDirectory !== null) {
|
if ($mountedArtifactDirectory !== null) {
|
||||||
$candidateDirectories[] = self::normalizePath($mountedArtifactDirectory);
|
$candidateDirectories[] = self::normalizePath($mountedArtifactDirectory);
|
||||||
@@ -40,9 +45,9 @@ class edge_gateway_agent_artifact_locator
|
|||||||
$candidateDirectories[] = self::normalizePath($bakedArtifactDirectory);
|
$candidateDirectories[] = self::normalizePath($bakedArtifactDirectory);
|
||||||
}
|
}
|
||||||
|
|
||||||
$candidateDirectories[] = self::normalizePath(dirname($basePath, 3) . DIRECTORY_SEPARATOR . 'services' . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent');
|
foreach (self::legacyPhpAgentDirectories($basePath) as $directory) {
|
||||||
$candidateDirectories[] = self::normalizePath(dirname($basePath, 2) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent');
|
$candidateDirectories[] = $directory;
|
||||||
$candidateDirectories[] = self::normalizePath(dirname($basePath) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent');
|
}
|
||||||
|
|
||||||
$paths = [];
|
$paths = [];
|
||||||
foreach (array_values(array_unique($candidateDirectories)) as $directory) {
|
foreach (array_values(array_unique($candidateDirectories)) as $directory) {
|
||||||
@@ -102,6 +107,42 @@ class edge_gateway_agent_artifact_locator
|
|||||||
return self::normalizePath($basePath . DIRECTORY_SEPARATOR . self::ROUTER_ARTIFACT_DIRECTORY);
|
return self::normalizePath($basePath . DIRECTORY_SEPARATOR . self::ROUTER_ARTIFACT_DIRECTORY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int,string>
|
||||||
|
*/
|
||||||
|
private static function edgeAgentBuildDirectories(string $basePath): array
|
||||||
|
{
|
||||||
|
$relative = str_replace('/', DIRECTORY_SEPARATOR, self::EDGE_AGENT_BUILD_ARTIFACT_DIRECTORY);
|
||||||
|
$directories = [
|
||||||
|
dirname($basePath, 4) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . $relative,
|
||||||
|
dirname($basePath, 3) . DIRECTORY_SEPARATOR . 'services' . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . $relative,
|
||||||
|
dirname($basePath, 2) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . $relative,
|
||||||
|
dirname($basePath) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . $relative,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (DIRECTORY_SEPARATOR === '/') {
|
||||||
|
array_unshift($directories, '/edge-agent/' . self::EDGE_AGENT_BUILD_ARTIFACT_DIRECTORY);
|
||||||
|
$directories[] = '/services/edge-agent/' . self::EDGE_AGENT_BUILD_ARTIFACT_DIRECTORY;
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_unique(array_map(
|
||||||
|
static fn(string $directory): string => self::normalizePath($directory),
|
||||||
|
$directories
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int,string>
|
||||||
|
*/
|
||||||
|
private static function legacyPhpAgentDirectories(string $basePath): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
self::normalizePath(dirname($basePath, 3) . DIRECTORY_SEPARATOR . 'services' . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent'),
|
||||||
|
self::normalizePath(dirname($basePath, 2) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent'),
|
||||||
|
self::normalizePath(dirname($basePath) . DIRECTORY_SEPARATOR . 'edge-agent' . DIRECTORY_SEPARATOR . 'php-agent'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
private static function mountedArtifactDirectory(): ?string
|
private static function mountedArtifactDirectory(): ?string
|
||||||
{
|
{
|
||||||
if (DIRECTORY_SEPARATOR !== '/') {
|
if (DIRECTORY_SEPARATOR !== '/') {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use Exception;
|
|||||||
class edge_gateway_install_service
|
class edge_gateway_install_service
|
||||||
{
|
{
|
||||||
private const ARTIFACTS = [
|
private const ARTIFACTS = [
|
||||||
|
'manifest.json' => 'application/json; charset=utf-8',
|
||||||
'agent.php' => 'application/x-httpd-php; charset=utf-8',
|
'agent.php' => 'application/x-httpd-php; charset=utf-8',
|
||||||
'lan-worker.php' => 'application/x-httpd-php; charset=utf-8',
|
'lan-worker.php' => 'application/x-httpd-php; charset=utf-8',
|
||||||
'auto-updater.php' => 'application/x-httpd-php; charset=utf-8',
|
'auto-updater.php' => 'application/x-httpd-php; charset=utf-8',
|
||||||
@@ -26,7 +27,7 @@ class edge_gateway_install_service
|
|||||||
|
|
||||||
public function buildInstallScript(string $plainToken): string
|
public function buildInstallScript(string $plainToken): string
|
||||||
{
|
{
|
||||||
return $this->manager()->buildInstallScript($plainToken);
|
return $this->normalizeLineEndings($this->manager()->buildInstallScript($plainToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,13 +43,17 @@ class edge_gateway_install_service
|
|||||||
*/
|
*/
|
||||||
public function readArtifact(string $fileName): string
|
public function readArtifact(string $fileName): string
|
||||||
{
|
{
|
||||||
|
if ($fileName === 'manifest.json') {
|
||||||
|
return $this->buildManifest();
|
||||||
|
}
|
||||||
|
|
||||||
$path = $this->artifactPath($fileName);
|
$path = $this->artifactPath($fileName);
|
||||||
$contents = file_get_contents($path);
|
$contents = file_get_contents($path);
|
||||||
if ($contents === false) {
|
if ($contents === false) {
|
||||||
throw new Exception('Unable to read edge agent artifact');
|
throw new Exception('Unable to read edge agent artifact');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $contents;
|
return $this->normalizeLineEndings($contents);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function contentType(string $fileName): string
|
public function contentType(string $fileName): string
|
||||||
@@ -66,15 +71,55 @@ class edge_gateway_install_service
|
|||||||
*/
|
*/
|
||||||
public function artifactPath(string $fileName): string
|
public function artifactPath(string $fileName): string
|
||||||
{
|
{
|
||||||
if (!array_key_exists($fileName, self::ARTIFACTS)) {
|
if (!array_key_exists($fileName, self::ARTIFACTS) || $fileName === 'manifest.json') {
|
||||||
throw new Exception('Unknown edge agent artifact');
|
throw new Exception('Unknown edge agent artifact');
|
||||||
}
|
}
|
||||||
|
|
||||||
return edge_gateway_agent_artifact_locator::resolve($fileName);
|
return edge_gateway_agent_artifact_locator::resolve($fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
private function buildManifest(): string
|
||||||
|
{
|
||||||
|
$artifacts = [];
|
||||||
|
foreach (self::ARTIFACTS as $fileName => $contentType) {
|
||||||
|
if ($fileName === 'manifest.json') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = $this->artifactPath($fileName);
|
||||||
|
$sha256 = hash_file('sha256', $path);
|
||||||
|
$bytes = filesize($path);
|
||||||
|
if ($sha256 === false || $bytes === false) {
|
||||||
|
throw new Exception('Unable to inspect edge agent artifact: ' . $fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
$artifacts[] = [
|
||||||
|
'name' => $fileName,
|
||||||
|
'sha256' => $sha256,
|
||||||
|
'bytes' => $bytes,
|
||||||
|
'content_type' => $contentType,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return json_encode([
|
||||||
|
'schema_version' => 1,
|
||||||
|
'package' => 'truckwash-edge-agent',
|
||||||
|
'version' => edge_gateway_manager::DEFAULT_INSTALL_VERSION,
|
||||||
|
'generated_at' => gmdate('c'),
|
||||||
|
'artifacts' => $artifacts,
|
||||||
|
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
private function manager(): edge_gateway_manager
|
private function manager(): edge_gateway_manager
|
||||||
{
|
{
|
||||||
return $this->manager ?? new edge_gateway_manager();
|
return $this->manager ?? new edge_gateway_manager();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function normalizeLineEndings(string $contents): string
|
||||||
|
{
|
||||||
|
return str_replace(["\r\n", "\r"], "\n", $contents);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -18,8 +18,7 @@ class edge_gateway_schema_bootstrap
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
global $db;
|
$pdo = self::pdo();
|
||||||
|
|
||||||
$queries = [
|
$queries = [
|
||||||
"CREATE TABLE IF NOT EXISTS edge_gateways (
|
"CREATE TABLE IF NOT EXISTS edge_gateways (
|
||||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
@@ -124,6 +123,31 @@ class edge_gateway_schema_bootstrap
|
|||||||
INDEX idx_edge_gateway_command_type (command_type)
|
INDEX idx_edge_gateway_command_type (command_type)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
|
||||||
|
|
||||||
|
"CREATE TABLE IF NOT EXISTS edge_gateway_expected_relay_states (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
gateway_id INT NOT NULL,
|
||||||
|
department_id INT NOT NULL,
|
||||||
|
lane_id INT NOT NULL,
|
||||||
|
role VARCHAR(32) NOT NULL,
|
||||||
|
relay_id VARCHAR(255) NOT NULL,
|
||||||
|
device_id VARCHAR(255) NULL,
|
||||||
|
local_ip VARCHAR(64) NULL,
|
||||||
|
device_type VARCHAR(64) NOT NULL DEFAULT 'UNKNOWN',
|
||||||
|
expected_state TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
updated_at DATETIME NOT NULL,
|
||||||
|
completed_at DATETIME NULL,
|
||||||
|
last_attempted_at DATETIME NULL,
|
||||||
|
last_error TEXT NULL,
|
||||||
|
metadata_json JSON NULL,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
row_updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
deleted_at TIMESTAMP NULL DEFAULT NULL,
|
||||||
|
UNIQUE KEY uniq_edge_gateway_expected_relay_state (gateway_id, lane_id, role),
|
||||||
|
INDEX idx_edge_gateway_expected_relay_gateway (gateway_id),
|
||||||
|
INDEX idx_edge_gateway_expected_relay_department (department_id),
|
||||||
|
INDEX idx_edge_gateway_expected_relay_pending (gateway_id, completed_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
|
||||||
|
|
||||||
"CREATE TABLE IF NOT EXISTS edge_gateway_operations (
|
"CREATE TABLE IF NOT EXISTS edge_gateway_operations (
|
||||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
gateway_id INT NOT NULL,
|
gateway_id INT NOT NULL,
|
||||||
@@ -233,11 +257,18 @@ class edge_gateway_schema_bootstrap
|
|||||||
];
|
];
|
||||||
|
|
||||||
foreach ($queries as $sql) {
|
foreach ($queries as $sql) {
|
||||||
$db->query($sql);
|
$pdo->exec($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
self::ensureColumn('edge_gateway_command_jobs', 'delivery_json', 'JSON NULL AFTER response_json');
|
self::ensureColumn('edge_gateway_command_jobs', 'delivery_json', 'JSON NULL AFTER response_json');
|
||||||
|
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'device_type', "VARCHAR(64) NOT NULL DEFAULT 'UNKNOWN' AFTER local_ip");
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'last_attempted_at', 'DATETIME NULL AFTER completed_at');
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'last_error', 'TEXT NULL AFTER last_attempted_at');
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'metadata_json', 'JSON NULL AFTER last_error');
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'row_updated_at', 'TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP AFTER created_at');
|
||||||
|
self::ensureColumn('edge_gateway_expected_relay_states', 'deleted_at', 'TIMESTAMP NULL DEFAULT NULL AFTER row_updated_at');
|
||||||
|
|
||||||
self::ensureColumn('edge_gateway_relay_bindings', 'fallback_mode', "VARCHAR(32) NOT NULL DEFAULT 'PREFER_LOCAL' AFTER channel");
|
self::ensureColumn('edge_gateway_relay_bindings', 'fallback_mode', "VARCHAR(32) NOT NULL DEFAULT 'PREFER_LOCAL' AFTER channel");
|
||||||
|
|
||||||
self::ensureColumn('edge_gateway_operations', 'type', "VARCHAR(32) NOT NULL DEFAULT 'DISCOVERY' AFTER gateway_id");
|
self::ensureColumn('edge_gateway_operations', 'type', "VARCHAR(32) NOT NULL DEFAULT 'DISCOVERY' AFTER gateway_id");
|
||||||
@@ -304,8 +335,6 @@ class edge_gateway_schema_bootstrap
|
|||||||
|
|
||||||
private static function ensureColumn(string $table, string $column, string $definition): void
|
private static function ensureColumn(string $table, string $column, string $definition): void
|
||||||
{
|
{
|
||||||
global $db;
|
|
||||||
|
|
||||||
if (self::tableHasColumn($table, $column)) {
|
if (self::tableHasColumn($table, $column)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -314,7 +343,7 @@ class edge_gateway_schema_bootstrap
|
|||||||
throw new \RuntimeException('Invalid schema bootstrap identifier');
|
throw new \RuntimeException('Invalid schema bootstrap identifier');
|
||||||
}
|
}
|
||||||
|
|
||||||
$db->query(
|
self::pdo()->exec(
|
||||||
"ALTER TABLE `$table`
|
"ALTER TABLE `$table`
|
||||||
ADD COLUMN `$column` $definition"
|
ADD COLUMN `$column` $definition"
|
||||||
);
|
);
|
||||||
@@ -327,8 +356,6 @@ class edge_gateway_schema_bootstrap
|
|||||||
string $definition,
|
string $definition,
|
||||||
?string $afterColumn = null
|
?string $afterColumn = null
|
||||||
): void {
|
): void {
|
||||||
global $db;
|
|
||||||
|
|
||||||
if (!self::tableHasColumn($table, $from) || self::tableHasColumn($table, $to)) {
|
if (!self::tableHasColumn($table, $from) || self::tableHasColumn($table, $to)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -342,7 +369,7 @@ class edge_gateway_schema_bootstrap
|
|||||||
|
|
||||||
$positionClause = $afterColumn === null ? '' : " AFTER `$afterColumn`";
|
$positionClause = $afterColumn === null ? '' : " AFTER `$afterColumn`";
|
||||||
|
|
||||||
$db->query(
|
self::pdo()->exec(
|
||||||
"ALTER TABLE `$table`
|
"ALTER TABLE `$table`
|
||||||
CHANGE COLUMN `$from` `$to` $definition$positionClause"
|
CHANGE COLUMN `$from` `$to` $definition$positionClause"
|
||||||
);
|
);
|
||||||
@@ -350,38 +377,35 @@ class edge_gateway_schema_bootstrap
|
|||||||
|
|
||||||
private static function tableHasColumn(string $table, string $column): bool
|
private static function tableHasColumn(string $table, string $column): bool
|
||||||
{
|
{
|
||||||
global $db;
|
if (!preg_match('/^[A-Za-z0-9_]+$/', $table) || !preg_match('/^[A-Za-z0-9_]+$/', $column)) {
|
||||||
|
throw new \RuntimeException('Invalid schema bootstrap identifier');
|
||||||
$table = $db->escape_string($table);
|
|
||||||
$column = $db->escape_string($column);
|
|
||||||
$database = $db->escape_string($db->getDatabase());
|
|
||||||
|
|
||||||
$result = $db->query(
|
|
||||||
"SELECT COUNT(*) AS c
|
|
||||||
FROM information_schema.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = '$database'
|
|
||||||
AND TABLE_NAME = '$table'
|
|
||||||
AND COLUMN_NAME = '$column'"
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!$result) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$row = $result->fetch_assoc();
|
$statement = self::pdo()->prepare(
|
||||||
|
"SELECT COUNT(*) AS c
|
||||||
|
FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = :table
|
||||||
|
AND COLUMN_NAME = :column"
|
||||||
|
);
|
||||||
|
$statement->execute([
|
||||||
|
':table' => $table,
|
||||||
|
':column' => $column,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$row = $statement->fetch();
|
||||||
return ((int)($row['c'] ?? 0)) > 0;
|
return ((int)($row['c'] ?? 0)) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static function syncOperationTypeColumns(): void
|
private static function syncOperationTypeColumns(): void
|
||||||
{
|
{
|
||||||
global $db;
|
|
||||||
|
|
||||||
if (!self::tableHasColumn('edge_gateway_operations', 'type')
|
if (!self::tableHasColumn('edge_gateway_operations', 'type')
|
||||||
|| !self::tableHasColumn('edge_gateway_operations', 'operation_type')) {
|
|| !self::tableHasColumn('edge_gateway_operations', 'operation_type')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$db->query(
|
$pdo = self::pdo();
|
||||||
|
$pdo->exec(
|
||||||
"UPDATE edge_gateway_operations
|
"UPDATE edge_gateway_operations
|
||||||
SET type = operation_type
|
SET type = operation_type
|
||||||
WHERE operation_type IS NOT NULL
|
WHERE operation_type IS NOT NULL
|
||||||
@@ -389,7 +413,7 @@ class edge_gateway_schema_bootstrap
|
|||||||
AND (type IS NULL OR type = '' OR type <> operation_type)"
|
AND (type IS NULL OR type = '' OR type <> operation_type)"
|
||||||
);
|
);
|
||||||
|
|
||||||
$db->query(
|
$pdo->exec(
|
||||||
"UPDATE edge_gateway_operations
|
"UPDATE edge_gateway_operations
|
||||||
SET operation_type = type
|
SET operation_type = type
|
||||||
WHERE type IS NOT NULL
|
WHERE type IS NOT NULL
|
||||||
@@ -397,4 +421,88 @@ class edge_gateway_schema_bootstrap
|
|||||||
AND (operation_type IS NULL OR operation_type = '')"
|
AND (operation_type IS NULL OR operation_type = '')"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static function pdo(): \PDO
|
||||||
|
{
|
||||||
|
$envConfig = self::databaseConfigFromEnvironment();
|
||||||
|
if ($envConfig !== null) {
|
||||||
|
return self::connectPdo($envConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists(db::class, false)) {
|
||||||
|
$dbClassPath = __DIR__ . '/../../../classes/db.php';
|
||||||
|
if (is_file($dbClassPath)) {
|
||||||
|
require_once $dbClassPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists(db::class)) {
|
||||||
|
throw new \RuntimeException('Database connection helper is not available.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return db::getPDO();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{host:string,user:string,password:string,database:string,port:int}|null
|
||||||
|
*/
|
||||||
|
private static function databaseConfigFromEnvironment(): ?array
|
||||||
|
{
|
||||||
|
$target = strtolower(self::envString('CONFIG_DB_TARGET') ?: 'live');
|
||||||
|
if ($target !== 'debug') {
|
||||||
|
$target = 'live';
|
||||||
|
}
|
||||||
|
|
||||||
|
$host = self::databaseEnvValue('HOST', $target);
|
||||||
|
$user = self::databaseEnvValue('USER', $target);
|
||||||
|
$database = self::databaseEnvValue('DATABASE', $target);
|
||||||
|
if ($host === '' || $user === '' || $database === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'host' => $host,
|
||||||
|
'user' => $user,
|
||||||
|
'password' => self::databaseEnvValue('PASSWORD', $target),
|
||||||
|
'database' => $database,
|
||||||
|
'port' => (int)(self::databaseEnvValue('PORT', $target) ?: 3306),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function databaseEnvValue(string $key, string $target): string
|
||||||
|
{
|
||||||
|
$liveValue = self::envString('CONFIG_DB_' . $key);
|
||||||
|
$debugValue = self::envString('CONFIG_DB_DEBUG_' . $key);
|
||||||
|
|
||||||
|
if ($target === 'debug' && $debugValue !== '') {
|
||||||
|
return $debugValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $liveValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function envString(string $key): string
|
||||||
|
{
|
||||||
|
$value = getenv($key);
|
||||||
|
if ($value === false || $value === null) {
|
||||||
|
$value = $_ENV[$key] ?? $_SERVER[$key] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return trim((string)$value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{host:string,user:string,password:string,database:string,port:int} $config
|
||||||
|
*/
|
||||||
|
private static function connectPdo(array $config): \PDO
|
||||||
|
{
|
||||||
|
$port = $config['port'] > 0 ? $config['port'] : 3306;
|
||||||
|
$dsn = "mysql:host={$config['host']};port={$port};dbname={$config['database']};charset=utf8mb4";
|
||||||
|
|
||||||
|
return new \PDO($dsn, $config['user'], $config['password'], [
|
||||||
|
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
||||||
|
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
|
||||||
|
\PDO::ATTR_EMULATE_PREPARES => false,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ class edgeGatewaysRoute
|
|||||||
$this->get('/edge-agent/install-token/verify', fn() => $this->handleInstallTokenVerify());
|
$this->get('/edge-agent/install-token/verify', fn() => $this->handleInstallTokenVerify());
|
||||||
$this->post('/edge-agent/install-token/status', fn() => $this->handleAgentInstallTokenStatus());
|
$this->post('/edge-agent/install-token/status', fn() => $this->handleAgentInstallTokenStatus());
|
||||||
$this->get('/edge-agent/install.sh', fn() => $this->renderInstallScript());
|
$this->get('/edge-agent/install.sh', fn() => $this->renderInstallScript());
|
||||||
|
$this->get('/edge-agent/artifacts/manifest.json', fn() => $this->renderArtifact('manifest.json'));
|
||||||
$this->get('/edge-agent/artifacts/agent.php', fn() => $this->renderArtifact('agent.php'));
|
$this->get('/edge-agent/artifacts/agent.php', fn() => $this->renderArtifact('agent.php'));
|
||||||
$this->get('/edge-agent/artifacts/lan-worker.php', fn() => $this->renderArtifact('lan-worker.php'));
|
$this->get('/edge-agent/artifacts/lan-worker.php', fn() => $this->renderArtifact('lan-worker.php'));
|
||||||
$this->get('/edge-agent/artifacts/auto-updater.php', fn() => $this->renderArtifact('auto-updater.php'));
|
$this->get('/edge-agent/artifacts/auto-updater.php', fn() => $this->renderArtifact('auto-updater.php'));
|
||||||
@@ -98,6 +99,8 @@ class edgeGatewaysRoute
|
|||||||
$this->post('/edge-agent/gateways/{id}/operations/{operationId}/complete', fn() => $this->handleAgentOperationComplete());
|
$this->post('/edge-agent/gateways/{id}/operations/{operationId}/complete', fn() => $this->handleAgentOperationComplete());
|
||||||
$this->post('/edge-agent/gateways/{id}/commands/poll', fn() => $this->handleAgentCommandPoll());
|
$this->post('/edge-agent/gateways/{id}/commands/poll', fn() => $this->handleAgentCommandPoll());
|
||||||
$this->post('/edge-agent/gateways/{id}/commands/{jobId}/result', fn() => $this->handleAgentCommandResult());
|
$this->post('/edge-agent/gateways/{id}/commands/{jobId}/result', fn() => $this->handleAgentCommandResult());
|
||||||
|
$this->post('/edge-agent/gateways/{id}/expected-relay-states', fn() => $this->handleAgentExpectedRelayStates());
|
||||||
|
$this->post('/edge-agent/gateways/{id}/relay-state-results', fn() => $this->handleAgentRelayStateResults());
|
||||||
$this->post('/edge-agent/gateways/{id}/presence', fn() => $this->handleAgentPresence());
|
$this->post('/edge-agent/gateways/{id}/presence', fn() => $this->handleAgentPresence());
|
||||||
$this->post('/edge-agent/gateways/{id}/selfserve/machine-signal-bindings', fn() => $this->handleAgentSelfserveMachineSignalBindings());
|
$this->post('/edge-agent/gateways/{id}/selfserve/machine-signal-bindings', fn() => $this->handleAgentSelfserveMachineSignalBindings());
|
||||||
$this->post('/edge-agent/gateways/{id}/selfserve/machine-signal', fn() => $this->handleAgentSelfserveMachineSignal());
|
$this->post('/edge-agent/gateways/{id}/selfserve/machine-signal', fn() => $this->handleAgentSelfserveMachineSignal());
|
||||||
@@ -109,6 +112,7 @@ class edgeGatewaysRoute
|
|||||||
$this->post('/edge-agent/internal/gateways/{id}/operations/{operationId}/events', fn() => $this->handleBrokerOperationEvent());
|
$this->post('/edge-agent/internal/gateways/{id}/operations/{operationId}/events', fn() => $this->handleBrokerOperationEvent());
|
||||||
$this->post('/edge-agent/internal/gateways/{id}/operations/{operationId}/complete', fn() => $this->handleBrokerOperationComplete());
|
$this->post('/edge-agent/internal/gateways/{id}/operations/{operationId}/complete', fn() => $this->handleBrokerOperationComplete());
|
||||||
$this->post('/edge-agent/internal/gateways/{id}/logs', fn() => $this->handleBrokerGatewayLogEntry());
|
$this->post('/edge-agent/internal/gateways/{id}/logs', fn() => $this->handleBrokerGatewayLogEntry());
|
||||||
|
$this->post('/edge-agent/internal/gateways/{id}/selfserve/machine-signal', fn() => $this->handleBrokerSelfserveMachineSignal());
|
||||||
$this->post('/edge-agent/internal/browser-streams/validate', fn() => $this->handleBrokerBrowserStreamValidate());
|
$this->post('/edge-agent/internal/browser-streams/validate', fn() => $this->handleBrokerBrowserStreamValidate());
|
||||||
$this->post('/edge-agent/internal/shell-sessions/validate', fn() => $this->handleBrokerShellSessionValidate());
|
$this->post('/edge-agent/internal/shell-sessions/validate', fn() => $this->handleBrokerShellSessionValidate());
|
||||||
$this->post('/edge-agent/internal/shell-sessions/opened', fn() => $this->handleBrokerShellSessionOpened());
|
$this->post('/edge-agent/internal/shell-sessions/opened', fn() => $this->handleBrokerShellSessionOpened());
|
||||||
@@ -398,7 +402,11 @@ class edgeGatewaysRoute
|
|||||||
$response->error('Missing token', 400);
|
$response->error('Missing token', 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
$response->success($this->install()->verifyInstallToken($token));
|
try {
|
||||||
|
$response->success($this->install()->verifyInstallToken($token));
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$response->error($exception->getMessage(), 400);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function handleAgentInstallTokenStatus(): void
|
private function handleAgentInstallTokenStatus(): void
|
||||||
@@ -407,17 +415,21 @@ class edgeGatewaysRoute
|
|||||||
self::requireParameters(['token', 'status']);
|
self::requireParameters(['token', 'status']);
|
||||||
|
|
||||||
$payload = self::getParametersAsArray();
|
$payload = self::getParametersAsArray();
|
||||||
$response->success($this->registry()->reportInstallTokenStatus(
|
try {
|
||||||
(string)$payload['token'],
|
$response->success($this->registry()->reportInstallTokenStatus(
|
||||||
[
|
(string)$payload['token'],
|
||||||
'status' => (string)$payload['status'],
|
[
|
||||||
'step' => isset($payload['step']) ? (string)$payload['step'] : null,
|
'status' => (string)$payload['status'],
|
||||||
'message' => isset($payload['message']) ? (string)$payload['message'] : null,
|
'step' => isset($payload['step']) ? (string)$payload['step'] : null,
|
||||||
'diagnostics' => isset($payload['diagnostics']) && is_array($payload['diagnostics']) ? (array)$payload['diagnostics'] : [],
|
'message' => isset($payload['message']) ? (string)$payload['message'] : null,
|
||||||
'gateway_id' => isset($payload['gateway_id']) ? (int)$payload['gateway_id'] : null,
|
'diagnostics' => isset($payload['diagnostics']) && is_array($payload['diagnostics']) ? (array)$payload['diagnostics'] : [],
|
||||||
'last_error' => isset($payload['last_error']) ? (string)$payload['last_error'] : null,
|
'gateway_id' => isset($payload['gateway_id']) ? (int)$payload['gateway_id'] : null,
|
||||||
]
|
'last_error' => isset($payload['last_error']) ? (string)$payload['last_error'] : null,
|
||||||
));
|
]
|
||||||
|
));
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$response->error($exception->getMessage(), 400);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function renderArtifact(string $fileName): void
|
private function renderArtifact(string $fileName): void
|
||||||
@@ -439,15 +451,19 @@ class edgeGatewaysRoute
|
|||||||
self::requireParameters(['token']);
|
self::requireParameters(['token']);
|
||||||
$payload = self::getParametersAsArray();
|
$payload = self::getParametersAsArray();
|
||||||
|
|
||||||
$response->success(
|
try {
|
||||||
$this->registry()->claimGateway(
|
$response->success(
|
||||||
(string)$payload['token'],
|
$this->registry()->claimGateway(
|
||||||
trim((string)($payload['hostname'] ?? gethostname() ?: 'unknown-gateway')),
|
(string)$payload['token'],
|
||||||
isset($payload['installed_version']) ? (string)$payload['installed_version'] : null,
|
trim((string)($payload['hostname'] ?? gethostname() ?: 'unknown-gateway')),
|
||||||
isset($payload['metadata']) && is_array($payload['metadata']) ? (array)$payload['metadata'] : []
|
isset($payload['installed_version']) ? (string)$payload['installed_version'] : null,
|
||||||
),
|
isset($payload['metadata']) && is_array($payload['metadata']) ? (array)$payload['metadata'] : []
|
||||||
201
|
),
|
||||||
);
|
201
|
||||||
|
);
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$response->error($exception->getMessage(), 400);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function handleAgentHeartbeat(): void
|
private function handleAgentHeartbeat(): void
|
||||||
@@ -555,6 +571,31 @@ class edgeGatewaysRoute
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function handleAgentExpectedRelayStates(): void
|
||||||
|
{
|
||||||
|
global /** @var response $response */ $response;
|
||||||
|
$gatewayId = (int)$this->fromRoute('id');
|
||||||
|
$payload = self::getParametersAsArray();
|
||||||
|
$response->success($this->manager()->buildExpectedRelayStatesForAgent(
|
||||||
|
$gatewayId,
|
||||||
|
$this->requireAgentToken($payload),
|
||||||
|
isset($payload['wait_seconds']) ? (int)$payload['wait_seconds'] : 0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function handleAgentRelayStateResults(): void
|
||||||
|
{
|
||||||
|
global /** @var response $response */ $response;
|
||||||
|
$gatewayId = (int)$this->fromRoute('id');
|
||||||
|
$payload = self::getParametersAsArray();
|
||||||
|
$results = isset($payload['results']) && is_array($payload['results']) ? (array)$payload['results'] : [];
|
||||||
|
$response->success($this->manager()->recordExpectedRelayStateResults(
|
||||||
|
$gatewayId,
|
||||||
|
$this->requireAgentToken($payload),
|
||||||
|
$results
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
private function handleAgentPresence(): void
|
private function handleAgentPresence(): void
|
||||||
{
|
{
|
||||||
global /** @var response $response */ $response;
|
global /** @var response $response */ $response;
|
||||||
@@ -706,6 +747,21 @@ class edgeGatewaysRoute
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function handleBrokerSelfserveMachineSignal(): void
|
||||||
|
{
|
||||||
|
global /** @var response $response */ $response;
|
||||||
|
$this->requireBrokerSecret();
|
||||||
|
$gatewayId = (int)$this->fromRoute('id');
|
||||||
|
$payload = self::getParametersAsArray();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$result = (new selfserve_machine_signal())->recordBrokerEdgeGatewaySignal($gatewayId, $payload);
|
||||||
|
$response->success($result, !empty($result['recorded']) ? 201 : 202);
|
||||||
|
} catch (\Throwable $exception) {
|
||||||
|
$response->error($exception->getMessage(), 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private function handleBrokerBrowserStreamValidate(): void
|
private function handleBrokerBrowserStreamValidate(): void
|
||||||
{
|
{
|
||||||
global /** @var response $response */ $response;
|
global /** @var response $response */ $response;
|
||||||
|
|||||||
@@ -148,6 +148,25 @@ class selfserve_machine_signal
|
|||||||
$gateway = (new edge_gateway_manager())->authenticateGateway($gatewayId, $agentToken);
|
$gateway = (new edge_gateway_manager())->authenticateGateway($gatewayId, $agentToken);
|
||||||
$departmentId = (int)$gateway->department_id->value();
|
$departmentId = (int)$gateway->department_id->value();
|
||||||
|
|
||||||
|
return $this->recordEdgeGatewaySignalForDepartment($gatewayId, $departmentId, $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $payload
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function recordBrokerEdgeGatewaySignal(int $gatewayId, array $payload): array
|
||||||
|
{
|
||||||
|
$gateway = (new edge_gateway_manager())->getGateway($gatewayId);
|
||||||
|
return $this->recordEdgeGatewaySignalForDepartment($gatewayId, (int)$gateway['department_id'], $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $payload
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
private function recordEdgeGatewaySignalForDepartment(int $gatewayId, int $departmentId, array $payload): array
|
||||||
|
{
|
||||||
return $this->recordCloudShellySignal(
|
return $this->recordCloudShellySignal(
|
||||||
$departmentId,
|
$departmentId,
|
||||||
isset($payload['lane_id']) ? (int)$payload['lane_id'] : null,
|
isset($payload['lane_id']) ? (int)$payload['lane_id'] : null,
|
||||||
|
|||||||
@@ -360,9 +360,13 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
$allowedServices = $this->normalizeServiceNames(
|
$allowedServices = $this->normalizeServiceNames(
|
||||||
is_array($metadata['allowed_services'] ?? null) ? (array)$metadata['allowed_services'] : []
|
is_array($metadata['allowed_services'] ?? null) ? (array)$metadata['allowed_services'] : []
|
||||||
);
|
);
|
||||||
$machineAvailable = array_key_exists('machine_available', $metadata)
|
$machineWashEnabled = $this->isMachineWashEnabled();
|
||||||
|
if (!$machineWashEnabled) {
|
||||||
|
$allowedServices = $this->withoutMachineService($allowedServices);
|
||||||
|
}
|
||||||
|
$machineAvailable = $machineWashEnabled && (array_key_exists('machine_available', $metadata)
|
||||||
? (bool)$metadata['machine_available']
|
? (bool)$metadata['machine_available']
|
||||||
: ($lane->exists() && !empty($lane->relay_machine_id->value()));
|
: ($lane->exists() && !empty($lane->relay_machine_id->value())));
|
||||||
$allVisibleQuestionsAnswered = array_key_exists('all_visible_questions_answered', $metadata)
|
$allVisibleQuestionsAnswered = array_key_exists('all_visible_questions_answered', $metadata)
|
||||||
? (bool)$metadata['all_visible_questions_answered']
|
? (bool)$metadata['all_visible_questions_answered']
|
||||||
: true;
|
: true;
|
||||||
@@ -408,6 +412,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
'events' => $events,
|
'events' => $events,
|
||||||
'allowed_services' => $allowedServices,
|
'allowed_services' => $allowedServices,
|
||||||
'machine_available' => $machineAvailable,
|
'machine_available' => $machineAvailable,
|
||||||
|
'machine_wash_enabled' => $machineWashEnabled,
|
||||||
'all_visible_questions_answered' => $allVisibleQuestionsAnswered,
|
'all_visible_questions_answered' => $allVisibleQuestionsAnswered,
|
||||||
'allowed' => (bool)$session->allowed->value(),
|
'allowed' => (bool)$session->allowed->value(),
|
||||||
'config_version_id' => $metadata['config_version_id'] ?? null,
|
'config_version_id' => $metadata['config_version_id'] ?? null,
|
||||||
@@ -425,7 +430,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
return $this->getSessionSummary((int)$session->id);
|
return $this->getSessionSummary((int)$session->id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null): ?array
|
public function completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null, bool $disableRelays = true): ?array
|
||||||
{
|
{
|
||||||
$session = $reg !== null
|
$session = $reg !== null
|
||||||
? $this->findLatestOpenSession($laneId, selfserve::standardize_registration($reg), $customerNumber)
|
? $this->findLatestOpenSession($laneId, selfserve::standardize_registration($reg), $customerNumber)
|
||||||
@@ -438,7 +443,9 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
if (!$session->markCompletedIfOpen($orderId)) {
|
if (!$session->markCompletedIfOpen($orderId)) {
|
||||||
return $this->getSessionSummary((int)$session->id);
|
return $this->getSessionSummary((int)$session->id);
|
||||||
}
|
}
|
||||||
$this->disableMachineRelayForCompletedWash($laneId);
|
if ($disableRelays) {
|
||||||
|
$this->disableMachineRelayForCompletedWash($laneId);
|
||||||
|
}
|
||||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_COMPLETED, [
|
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_COMPLETED, [
|
||||||
'lane_id' => $laneId,
|
'lane_id' => $laneId,
|
||||||
'reg' => $reg === null ? (string)$session->reg->value() : selfserve::standardize_registration($reg),
|
'reg' => $reg === null ? (string)$session->reg->value() : selfserve::standardize_registration($reg),
|
||||||
@@ -685,7 +692,12 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$machineAvailable = !empty($lane->relay_machine_id->value());
|
$machineWashEnabled = $this->isMachineWashEnabled();
|
||||||
|
if (!$machineWashEnabled) {
|
||||||
|
$allowedServices = $this->withoutMachineService($allowedServices);
|
||||||
|
}
|
||||||
|
|
||||||
|
$machineAvailable = $machineWashEnabled && !empty($lane->relay_machine_id->value());
|
||||||
$allVisibleQuestionsAnswered = true;
|
$allVisibleQuestionsAnswered = true;
|
||||||
foreach ($visibleQuestions as $question) {
|
foreach ($visibleQuestions as $question) {
|
||||||
if ($question['answer'] === null) {
|
if ($question['answer'] === null) {
|
||||||
@@ -724,8 +736,10 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
'tasks' => $visibleTasks,
|
'tasks' => $visibleTasks,
|
||||||
'allowed_services' => $allowedServices,
|
'allowed_services' => $allowedServices,
|
||||||
'machine_available' => $machineAvailable,
|
'machine_available' => $machineAvailable,
|
||||||
|
'machine_wash_enabled' => $machineWashEnabled,
|
||||||
'all_visible_questions_answered' => $allVisibleQuestionsAnswered,
|
'all_visible_questions_answered' => $allVisibleQuestionsAnswered,
|
||||||
'allowed' => $machineAllowed,
|
'allowed' => $machineAllowed,
|
||||||
|
'blocked_reason' => !$machineWashEnabled ? 'Machine wash is disabled globally.' : null,
|
||||||
'config_version_id' => $publishedConfigVersionId === null ? null : (int)$publishedConfigVersionId,
|
'config_version_id' => $publishedConfigVersionId === null ? null : (int)$publishedConfigVersionId,
|
||||||
'config_source' => $configSource,
|
'config_source' => $configSource,
|
||||||
'evaluation_trace' => [
|
'evaluation_trace' => [
|
||||||
@@ -824,6 +838,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
'tasks' => $snapshot['tasks'],
|
'tasks' => $snapshot['tasks'],
|
||||||
'allowed_services' => $snapshot['allowed_services'],
|
'allowed_services' => $snapshot['allowed_services'],
|
||||||
'machine_available' => $snapshot['machine_available'],
|
'machine_available' => $snapshot['machine_available'],
|
||||||
|
'machine_wash_enabled' => $snapshot['machine_wash_enabled'] ?? true,
|
||||||
'all_visible_questions_answered' => $snapshot['all_visible_questions_answered'],
|
'all_visible_questions_answered' => $snapshot['all_visible_questions_answered'],
|
||||||
'allowed' => $snapshot['allowed'],
|
'allowed' => $snapshot['allowed'],
|
||||||
'blocked_reason' => $snapshot['blocked_reason'] ?? null,
|
'blocked_reason' => $snapshot['blocked_reason'] ?? null,
|
||||||
@@ -3308,6 +3323,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
return [
|
return [
|
||||||
'allowed_services' => $snapshot['allowed_services'],
|
'allowed_services' => $snapshot['allowed_services'],
|
||||||
'machine_available' => (bool)$snapshot['machine_available'],
|
'machine_available' => (bool)$snapshot['machine_available'],
|
||||||
|
'machine_wash_enabled' => (bool)($snapshot['machine_wash_enabled'] ?? true),
|
||||||
'all_visible_questions_answered' => (bool)$snapshot['all_visible_questions_answered'],
|
'all_visible_questions_answered' => (bool)$snapshot['all_visible_questions_answered'],
|
||||||
'config_version_id' => $snapshot['config_version_id'] ?? null,
|
'config_version_id' => $snapshot['config_version_id'] ?? null,
|
||||||
'evaluation_trace' => $snapshot['evaluation_trace'] ?? null,
|
'evaluation_trace' => $snapshot['evaluation_trace'] ?? null,
|
||||||
@@ -3606,6 +3622,27 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function isMachineWashEnabled(): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return (new selfserve())->config->machine_wash_enabled->isTrue();
|
||||||
|
} catch (\Throwable) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int,string> $services
|
||||||
|
* @return array<int,string>
|
||||||
|
*/
|
||||||
|
protected function withoutMachineService(array $services): array
|
||||||
|
{
|
||||||
|
return array_values(array_filter(
|
||||||
|
$this->normalizeServiceNames($services),
|
||||||
|
static fn(string $service): bool => $service !== selfserve_lane_services::MACHINE->name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
protected function taskUsesMachineControls(array $task): bool
|
protected function taskUsesMachineControls(array $task): bool
|
||||||
{
|
{
|
||||||
if (in_array(selfserve_lane_services::MACHINE->name, $this->normalizeServiceNames($this->normalizeJsonArray($task['services'] ?? null)), true)) {
|
if (in_array(selfserve_lane_services::MACHINE->name, $this->normalizeServiceNames($this->normalizeJsonArray($task['services'] ?? null)), true)) {
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace modules\selfserve\config;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use traits\module_config_variable;
|
||||||
|
|
||||||
|
class selfserve_machine_wash_enabled_c
|
||||||
|
{
|
||||||
|
use module_config_variable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
self::setupConfigVariable(
|
||||||
|
'selfserve',
|
||||||
|
'machine_wash_enabled',
|
||||||
|
'bool',
|
||||||
|
true,
|
||||||
|
null,
|
||||||
|
'Whether machine wash is available in customer-facing self-serve flows',
|
||||||
|
'1',
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ interface selfserve_wash_flow_i
|
|||||||
|
|
||||||
public function getLatestSessionSummary(int $laneId, string $reg): array;
|
public function getLatestSessionSummary(int $laneId, string $reg): array;
|
||||||
|
|
||||||
public function completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null): ?array;
|
public function completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null, bool $disableRelays = true): ?array;
|
||||||
|
|
||||||
public function forceStopLane(int $laneId, ?int $sessionId = null, bool $bill = false, ?string $reason = null, ?int $userId = null): array;
|
public function forceStopLane(int $laneId, ?int $sessionId = null, bool $bill = false, ?string $reason = null, ?int $userId = null): array;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -439,7 +439,7 @@ Public methods:
|
|||||||
| `recordMachineStartWebhook(int $laneId, ?string $reg = null, array $payload = [])` | The machine button or hardware event fired. | Full session summary after the machine-start event. |
|
| `recordMachineStartWebhook(int $laneId, ?string $reg = null, array $payload = [])` | The machine button or hardware event fired. | Full session summary after the machine-start event. |
|
||||||
| `getSessionSummary(int $sessionId)` | You have a session id already. | Full session summary. |
|
| `getSessionSummary(int $sessionId)` | You have a session id already. | Full session summary. |
|
||||||
| `getLatestSessionSummary(int $laneId, string $reg)` | You want the latest session for a lane and vehicle. | Full session summary. |
|
| `getLatestSessionSummary(int $laneId, string $reg)` | You want the latest session for a lane and vehicle. | Full session summary. |
|
||||||
| `completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null)` | STOP has finished and you want to close the latest open session. | Full summary, or `null` if no open session exists. |
|
| `completeLatestSessionForLane(int $laneId, ?string $reg = null, ?int $customerNumber = null, ?int $orderId = null, bool $disableRelays = true)` | STOP has finished and you want to close the latest open session. Normal STOP passes `false` because it already disabled relays before opening the exit port. | Full summary, or `null` if no open session exists. |
|
||||||
|
|
||||||
Key implementation details:
|
Key implementation details:
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,14 @@
|
|||||||
|
|
||||||
namespace modules\selfserve;
|
namespace modules\selfserve;
|
||||||
require_once WD . '/modules/selfserve/config/selfserve_enabled_c.php';
|
require_once WD . '/modules/selfserve/config/selfserve_enabled_c.php';
|
||||||
|
require_once WD . '/modules/selfserve/config/selfserve_machine_wash_enabled_c.php';
|
||||||
require_once WD . '/modules/selfserve/config/selfserve_minute_product_c.php';
|
require_once WD . '/modules/selfserve/config/selfserve_minute_product_c.php';
|
||||||
require_once WD . '/modules/selfserve/config/selfserve_machine_wash_minutes_included_c.php';
|
require_once WD . '/modules/selfserve/config/selfserve_machine_wash_minutes_included_c.php';
|
||||||
require_once WD . '/modules/selfserve/config/selfserve_dynamic_image_size_c.php';
|
require_once WD . '/modules/selfserve/config/selfserve_dynamic_image_size_c.php';
|
||||||
|
|
||||||
use modules\selfserve\config\selfserve_dynamic_image_size_c;
|
use modules\selfserve\config\selfserve_dynamic_image_size_c;
|
||||||
use modules\selfserve\config\selfserve_enabled_c;
|
use modules\selfserve\config\selfserve_enabled_c;
|
||||||
|
use modules\selfserve\config\selfserve_machine_wash_enabled_c;
|
||||||
use modules\selfserve\config\selfserve_machine_wash_minutes_included_c;
|
use modules\selfserve\config\selfserve_machine_wash_minutes_included_c;
|
||||||
use modules\selfserve\config\selfserve_minute_product_c;
|
use modules\selfserve\config\selfserve_minute_product_c;
|
||||||
use traits\module_config_t;
|
use traits\module_config_t;
|
||||||
@@ -21,6 +23,11 @@ class selfserve_c
|
|||||||
* @var selfserve_enabled_c $enabled
|
* @var selfserve_enabled_c $enabled
|
||||||
*/
|
*/
|
||||||
public selfserve_enabled_c $enabled;
|
public selfserve_enabled_c $enabled;
|
||||||
|
/**
|
||||||
|
* Whether machine wash is available in customer-facing self-serve flows
|
||||||
|
* @var selfserve_machine_wash_enabled_c $machine_wash_enabled
|
||||||
|
*/
|
||||||
|
public selfserve_machine_wash_enabled_c $machine_wash_enabled;
|
||||||
/**
|
/**
|
||||||
* The product ID used for minute-based self-serve billing
|
* The product ID used for minute-based self-serve billing
|
||||||
* @var selfserve_minute_product_c $minute_product
|
* @var selfserve_minute_product_c $minute_product
|
||||||
@@ -42,11 +49,13 @@ class selfserve_c
|
|||||||
$this->setupConfig('selfserve');
|
$this->setupConfig('selfserve');
|
||||||
$this->allowUpdate([
|
$this->allowUpdate([
|
||||||
selfserve_enabled_c::class,
|
selfserve_enabled_c::class,
|
||||||
|
selfserve_machine_wash_enabled_c::class,
|
||||||
selfserve_minute_product_c::class,
|
selfserve_minute_product_c::class,
|
||||||
selfserve_machine_wash_minutes_included_c::class,
|
selfserve_machine_wash_minutes_included_c::class,
|
||||||
selfserve_dynamic_image_size_c::class
|
selfserve_dynamic_image_size_c::class
|
||||||
]);
|
]);
|
||||||
$this->enabled = new selfserve_enabled_c();
|
$this->enabled = new selfserve_enabled_c();
|
||||||
|
$this->machine_wash_enabled = new selfserve_machine_wash_enabled_c();
|
||||||
$this->minute_product = new selfserve_minute_product_c();
|
$this->minute_product = new selfserve_minute_product_c();
|
||||||
$this->machine_wash_minutes_included = new selfserve_machine_wash_minutes_included_c();
|
$this->machine_wash_minutes_included = new selfserve_machine_wash_minutes_included_c();
|
||||||
$this->dynamic_image_size = new selfserve_dynamic_image_size_c();
|
$this->dynamic_image_size = new selfserve_dynamic_image_size_c();
|
||||||
|
|||||||
@@ -538,7 +538,8 @@ trait selfserve_lane_command_t
|
|||||||
$this->id,
|
$this->id,
|
||||||
$this->getLicensePlate() ?: null,
|
$this->getLicensePlate() ?: null,
|
||||||
$this->getCustomerNumber() ?: null,
|
$this->getCustomerNumber() ?: null,
|
||||||
method_exists($this, 'getLastInvoiceOrderId') ? $this->getLastInvoiceOrderId() : null
|
method_exists($this, 'getLastInvoiceOrderId') ? $this->getLastInvoiceOrderId() : null,
|
||||||
|
false
|
||||||
);
|
);
|
||||||
} catch (\Throwable) {
|
} catch (\Throwable) {
|
||||||
// Session completion must not block STOP flow.
|
// Session completion must not block STOP flow.
|
||||||
|
|||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace slack\config;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use traits\module_config_variable;
|
||||||
|
|
||||||
|
class slack_internal_department_goal_progress_webhook_url_c
|
||||||
|
{
|
||||||
|
use module_config_variable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
self::setupConfigVariable(
|
||||||
|
'Slack',
|
||||||
|
'internal_department_goal_progress_webhook_url',
|
||||||
|
'string',
|
||||||
|
false,
|
||||||
|
null,
|
||||||
|
'Slack webhook URL used for internal department goal progress notifications',
|
||||||
|
'https://hooks.slack.com/services/...',
|
||||||
|
true,
|
||||||
|
''
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace slack\config;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use traits\module_config_variable;
|
||||||
|
|
||||||
|
class slack_internal_department_ids_c
|
||||||
|
{
|
||||||
|
use module_config_variable {
|
||||||
|
setVariableValue as private traitSetVariableValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
self::setupConfigVariable(
|
||||||
|
'Slack',
|
||||||
|
'internal_department_ids',
|
||||||
|
'string',
|
||||||
|
false,
|
||||||
|
null,
|
||||||
|
'JSON encoded department IDs considered internal departments for Slack goal progress notifications',
|
||||||
|
'[1,2,3]',
|
||||||
|
false,
|
||||||
|
'[]'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getDepartmentIds(): array
|
||||||
|
{
|
||||||
|
return self::normalizeDepartmentIds($this->getVariableValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function setVariableValue(mixed $value): void
|
||||||
|
{
|
||||||
|
$this->traitSetVariableValue(json_encode(
|
||||||
|
self::normalizeDepartmentIds($value),
|
||||||
|
JSON_THROW_ON_ERROR
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function normalizeDepartmentIds(mixed $value): array
|
||||||
|
{
|
||||||
|
if (is_string($value)) {
|
||||||
|
$decoded = json_decode($value, true);
|
||||||
|
if (is_array($decoded)) {
|
||||||
|
$value = $decoded;
|
||||||
|
} else {
|
||||||
|
$value = array_filter(array_map('trim', explode(',', $value)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_array($value)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$departmentIds = [];
|
||||||
|
foreach ($value as $departmentId) {
|
||||||
|
$departmentId = (int)$departmentId;
|
||||||
|
if ($departmentId > 0) {
|
||||||
|
$departmentIds[] = $departmentId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$departmentIds = array_values(array_unique($departmentIds));
|
||||||
|
sort($departmentIds);
|
||||||
|
|
||||||
|
return $departmentIds;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,8 +3,12 @@
|
|||||||
namespace slack;
|
namespace slack;
|
||||||
|
|
||||||
require_once WD . '/modules/slack/config/slack_customer_registration_webhook_url_c.php';
|
require_once WD . '/modules/slack/config/slack_customer_registration_webhook_url_c.php';
|
||||||
|
require_once WD . '/modules/slack/config/slack_internal_department_goal_progress_webhook_url_c.php';
|
||||||
|
require_once WD . '/modules/slack/config/slack_internal_department_ids_c.php';
|
||||||
|
|
||||||
use slack\config\slack_customer_registration_webhook_url_c;
|
use slack\config\slack_customer_registration_webhook_url_c;
|
||||||
|
use slack\config\slack_internal_department_goal_progress_webhook_url_c;
|
||||||
|
use slack\config\slack_internal_department_ids_c;
|
||||||
use traits\module_config_t;
|
use traits\module_config_t;
|
||||||
|
|
||||||
class slack_c
|
class slack_c
|
||||||
@@ -12,14 +16,20 @@ class slack_c
|
|||||||
use module_config_t;
|
use module_config_t;
|
||||||
|
|
||||||
public slack_customer_registration_webhook_url_c $customer_registration_webhook_url;
|
public slack_customer_registration_webhook_url_c $customer_registration_webhook_url;
|
||||||
|
public slack_internal_department_goal_progress_webhook_url_c $internal_department_goal_progress_webhook_url;
|
||||||
|
public slack_internal_department_ids_c $internal_department_ids;
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->setupConfig('Slack');
|
$this->setupConfig('Slack');
|
||||||
$this->allowUpdate([
|
$this->allowUpdate([
|
||||||
slack_customer_registration_webhook_url_c::class,
|
slack_customer_registration_webhook_url_c::class,
|
||||||
|
slack_internal_department_goal_progress_webhook_url_c::class,
|
||||||
|
slack_internal_department_ids_c::class,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->customer_registration_webhook_url = new slack_customer_registration_webhook_url_c();
|
$this->customer_registration_webhook_url = new slack_customer_registration_webhook_url_c();
|
||||||
|
$this->internal_department_goal_progress_webhook_url = new slack_internal_department_goal_progress_webhook_url_c();
|
||||||
|
$this->internal_department_ids = new slack_internal_department_ids_c();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ class collected_order_invoices_o extends db
|
|||||||
public object_property $updated_at;
|
public object_property $updated_at;
|
||||||
public object_property $closed_at;
|
public object_property $closed_at;
|
||||||
public int $economic_wash_subscription_user_id = 1857;
|
public int $economic_wash_subscription_user_id = 1857;
|
||||||
|
private ?array $last_economic_transfer_metrics = null;
|
||||||
/**
|
/**
|
||||||
* The processor types
|
* The processor types
|
||||||
*
|
*
|
||||||
@@ -712,6 +713,7 @@ class collected_order_invoices_o extends db
|
|||||||
*/
|
*/
|
||||||
public function addInvoicesToDraft(bool $skip_check = false): self
|
public function addInvoicesToDraft(bool $skip_check = false): self
|
||||||
{
|
{
|
||||||
|
$this->last_economic_transfer_metrics = null;
|
||||||
// Require the invoice collection to be selected
|
// Require the invoice collection to be selected
|
||||||
self::requireSelected();
|
self::requireSelected();
|
||||||
// Require the invoice collection to be open
|
// Require the invoice collection to be open
|
||||||
@@ -736,10 +738,20 @@ class collected_order_invoices_o extends db
|
|||||||
usort($orders, function ($a, $b) {
|
usort($orders, function ($a, $b) {
|
||||||
return strtotime($a['created_at']) - strtotime($b['created_at']);
|
return strtotime($a['created_at']) - strtotime($b['created_at']);
|
||||||
});
|
});
|
||||||
// Add the invoices to the invoice draft
|
// Add the invoice lines to the draft in one accumulated batch path.
|
||||||
|
$order_objects = [];
|
||||||
foreach ( $orders as $order ) {
|
foreach ( $orders as $order ) {
|
||||||
self::addInvoiceToDraft($order['id'], true, $draft_id, $currency);
|
$order_object = new orders_o();
|
||||||
|
$order_object->select((int)$order['id']);
|
||||||
|
$order_object->requireSelected();
|
||||||
|
$order_objects[] = $order_object;
|
||||||
}
|
}
|
||||||
|
$metrics = (new economic())->invoices->draft->add_orders($draft_id, $order_objects, $currency);
|
||||||
|
$this->last_economic_transfer_metrics = [
|
||||||
|
'draft_invoice_id' => $draft_id,
|
||||||
|
'currency' => (string)$currency,
|
||||||
|
...$metrics,
|
||||||
|
];
|
||||||
// If the customer has the onlyTankCleaning attribute, add the environmental fee & oil fees to the invoice draft
|
// If the customer has the onlyTankCleaning attribute, add the environmental fee & oil fees to the invoice draft
|
||||||
self::addEnvironmentalAndOilFeesToDraft($draft_id, $currency);
|
self::addEnvironmentalAndOilFeesToDraft($draft_id, $currency);
|
||||||
// Object changed
|
// Object changed
|
||||||
@@ -748,6 +760,11 @@ class collected_order_invoices_o extends db
|
|||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getLastEconomicTransferMetrics(): ?array
|
||||||
|
{
|
||||||
|
return $this->last_economic_transfer_metrics;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add the environmental fee & oil fees to the invoice draft, if the customer has the onlyTankCleaning attribute
|
* Add the environmental fee & oil fees to the invoice draft, if the customer has the onlyTankCleaning attribute
|
||||||
* @param int $draft_id The invoice draft id
|
* @param int $draft_id The invoice draft id
|
||||||
|
|||||||
@@ -18,13 +18,18 @@ class customer_password_reset_keys_o extends db
|
|||||||
public object_property $updated_at;
|
public object_property $updated_at;
|
||||||
public object_property $deleted_at;
|
public object_property $deleted_at;
|
||||||
const TOKEN_LENGTH = 32;
|
const TOKEN_LENGTH = 32;
|
||||||
const TOKEN_EXPIRY_SECONDS = 3600; // 1 hour
|
const TOKEN_EXPIRY_SECONDS = 72 * 60 * 60; // 72 hours
|
||||||
|
|
||||||
public function structure(): void
|
public function structure(): void
|
||||||
{
|
{
|
||||||
$this->setTable('customer_password_reset_keys');
|
$this->setTable('customer_password_reset_keys');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function validTokenWhereClause(): string
|
||||||
|
{
|
||||||
|
return "deleted_at IS NULL AND created_at >= DATE_SUB(NOW(), INTERVAL " . self::TOKEN_EXPIRY_SECONDS . " SECOND)";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a new customer reset key
|
* Add a new customer reset key
|
||||||
@@ -65,9 +70,8 @@ class customer_password_reset_keys_o extends db
|
|||||||
if (strlen($token) !== self::TOKEN_LENGTH) {
|
if (strlen($token) !== self::TOKEN_LENGTH) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
// Query the database for a valid token
|
// Query the database for a valid token using the same clock that writes created_at.
|
||||||
$current_time = date('Y-m-d H:i:s');
|
$sql = "SELECT id FROM $this->table WHERE token = '" . $db->escape_string($token) . "' AND " . $this->validTokenWhereClause() . " LIMIT 1";
|
||||||
$sql = "SELECT id FROM $this->table WHERE token = '" . $db->escape_string($token) . "' AND deleted_at IS NULL AND created_at >= DATE_SUB('$current_time', INTERVAL " . self::TOKEN_EXPIRY_SECONDS . " SECOND) LIMIT 1";
|
|
||||||
$result = $db->query($sql);
|
$result = $db->query($sql);
|
||||||
if ($result->num_rows === 0) {
|
if ($result->num_rows === 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -85,13 +89,11 @@ class customer_password_reset_keys_o extends db
|
|||||||
*/
|
*/
|
||||||
public function isValidToken(): bool
|
public function isValidToken(): bool
|
||||||
{
|
{
|
||||||
|
global $db;
|
||||||
self::requireSelected();
|
self::requireSelected();
|
||||||
$created_at = strtotime($this->created_at->value());
|
$sql = "SELECT id FROM $this->table WHERE id = " . (int)$this->id . " AND " . $this->validTokenWhereClause() . " LIMIT 1";
|
||||||
$current_time = time();
|
$result = $db->query($sql);
|
||||||
return (
|
return $result->num_rows > 0;
|
||||||
($current_time - $created_at) <= self::TOKEN_EXPIRY_SECONDS) &&
|
|
||||||
($this->deleted_at->value() === null
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -140,4 +142,4 @@ class customer_password_reset_keys_o extends db
|
|||||||
{
|
{
|
||||||
//TODO: Add cache invalidation
|
//TODO: Add cache invalidation
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -718,7 +718,7 @@ class departments_o extends db
|
|||||||
* @return null|array
|
* @return null|array
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
public function sendSlackInternalStatisticNotification(string $date_start, string $date_end, array $department_ids, array $product_ids = [
|
public function sendSlackInternalStatisticNotification(string $date_start, string $date_end, array $department_ids = [], array $product_ids = [
|
||||||
25,
|
25,
|
||||||
[23, 24], // Used to merge two products into one percentage (Spot Free)
|
[23, 24], // Used to merge two products into one percentage (Spot Free)
|
||||||
22,
|
22,
|
||||||
@@ -727,6 +727,11 @@ class departments_o extends db
|
|||||||
26
|
26
|
||||||
], bool $return_as_array = false): null|array
|
], bool $return_as_array = false): null|array
|
||||||
{
|
{
|
||||||
|
$slack = new slack();
|
||||||
|
if (empty($department_ids)) {
|
||||||
|
$department_ids = $slack->get_internal_department_ids();
|
||||||
|
}
|
||||||
|
|
||||||
if (empty($department_ids)) {
|
if (empty($department_ids)) {
|
||||||
throw new Exception('No department ids provided for the Slack internal statistic notification.');
|
throw new Exception('No department ids provided for the Slack internal statistic notification.');
|
||||||
}
|
}
|
||||||
@@ -847,9 +852,11 @@ class departments_o extends db
|
|||||||
$array_of_results['daily_management'][] = $tmp;
|
$array_of_results['daily_management'][] = $tmp;
|
||||||
|
|
||||||
// Send the message to the internal Slack webhook
|
// Send the message to the internal Slack webhook
|
||||||
$slack = new slack();
|
|
||||||
if (!$return_as_array) {
|
if (!$return_as_array) {
|
||||||
$slack->send_webhook_message($tmp, (new departments_o())->select(10)->slack_webhook->value());
|
$webhook = $slack->get_internal_department_goal_progress_webhook_url();
|
||||||
|
if ($webhook !== '') {
|
||||||
|
$slack->send_webhook_message($tmp, $webhook);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Send a department-specific message for each internal department with the percentage of addons sold
|
// Send a department-specific message for each internal department with the percentage of addons sold
|
||||||
foreach ( $department_ids as $department_id ) {
|
foreach ( $department_ids as $department_id ) {
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace objects;
|
||||||
|
|
||||||
|
use classes\db;
|
||||||
|
use classes\edge_gateway_schema_bootstrap;
|
||||||
|
use classes\object_property;
|
||||||
|
use traits\db_object_t;
|
||||||
|
|
||||||
|
class edge_gateway_expected_relay_states_o extends db
|
||||||
|
{
|
||||||
|
use db_object_t;
|
||||||
|
|
||||||
|
public object_property $gateway_id;
|
||||||
|
public object_property $department_id;
|
||||||
|
public object_property $lane_id;
|
||||||
|
public object_property $role;
|
||||||
|
public object_property $relay_id;
|
||||||
|
public object_property $device_id;
|
||||||
|
public object_property $local_ip;
|
||||||
|
public object_property $device_type;
|
||||||
|
public object_property $expected_state;
|
||||||
|
public object_property $updated_at;
|
||||||
|
public object_property $completed_at;
|
||||||
|
public object_property $last_attempted_at;
|
||||||
|
public object_property $last_error;
|
||||||
|
public object_property $metadata_json;
|
||||||
|
public object_property $created_at;
|
||||||
|
public object_property $row_updated_at;
|
||||||
|
public object_property $deleted_at;
|
||||||
|
|
||||||
|
public function structure(): void
|
||||||
|
{
|
||||||
|
edge_gateway_schema_bootstrap::ensureTables();
|
||||||
|
$this->setTable('edge_gateway_expected_relay_states');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getObjectProperties(): void
|
||||||
|
{
|
||||||
|
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
|
||||||
|
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
|
||||||
|
$this->lane_id = new object_property($this->table, $this->id, 'lane_id', 'int', false);
|
||||||
|
$this->role = new object_property($this->table, $this->id, 'role', 'string', false);
|
||||||
|
$this->relay_id = new object_property($this->table, $this->id, 'relay_id', 'string', false);
|
||||||
|
$this->device_id = new object_property($this->table, $this->id, 'device_id', 'string', false);
|
||||||
|
$this->local_ip = new object_property($this->table, $this->id, 'local_ip', 'string', false);
|
||||||
|
$this->device_type = new object_property($this->table, $this->id, 'device_type', 'string', false);
|
||||||
|
$this->expected_state = new object_property($this->table, $this->id, 'expected_state', 'bool', false);
|
||||||
|
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'string', false);
|
||||||
|
$this->completed_at = new object_property($this->table, $this->id, 'completed_at', 'string', false);
|
||||||
|
$this->last_attempted_at = new object_property($this->table, $this->id, 'last_attempted_at', 'string', false);
|
||||||
|
$this->last_error = new object_property($this->table, $this->id, 'last_error', 'text', false);
|
||||||
|
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
|
||||||
|
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
|
||||||
|
$this->row_updated_at = new object_property($this->table, $this->id, 'row_updated_at', 'timestamp', false);
|
||||||
|
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function objectChanged(): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function asArray(): array
|
||||||
|
{
|
||||||
|
$this->requireSelected();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => (int)$this->id,
|
||||||
|
'gateway_id' => (int)$this->gateway_id->value(),
|
||||||
|
'department_id' => (int)$this->department_id->value(),
|
||||||
|
'lane_id' => (int)$this->lane_id->value(),
|
||||||
|
'role' => (string)$this->role->value(),
|
||||||
|
'relay_id' => (string)$this->relay_id->value(),
|
||||||
|
'device_id' => $this->device_id->value() === null ? null : (string)$this->device_id->value(),
|
||||||
|
'local_ip' => $this->local_ip->value() === null ? null : (string)$this->local_ip->value(),
|
||||||
|
'device_type' => (string)$this->device_type->value(),
|
||||||
|
'state' => (bool)$this->expected_state->value(),
|
||||||
|
'updated' => (string)$this->updated_at->value(),
|
||||||
|
'completed' => $this->completed_at->value() === null ? null : (string)$this->completed_at->value(),
|
||||||
|
'last_attempted_at' => $this->last_attempted_at->value() === null ? null : (string)$this->last_attempted_at->value(),
|
||||||
|
'last_error' => $this->last_error->value() === null ? null : (string)$this->last_error->value(),
|
||||||
|
'metadata' => (array)($this->metadata_json->value() ?? []),
|
||||||
|
'created_at' => (string)$this->created_at->value(),
|
||||||
|
'row_updated_at' => $this->row_updated_at->value() === null ? null : (string)$this->row_updated_at->value(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,11 +23,11 @@ class subuser_grants_o extends db
|
|||||||
public object_property $deleted_at;
|
public object_property $deleted_at;
|
||||||
const defaultPermissions = [
|
const defaultPermissions = [
|
||||||
'VEHICLES_LIST',
|
'VEHICLES_LIST',
|
||||||
|
'SELFSERVE_LIST',
|
||||||
'SELFSERVE_ADD',
|
'SELFSERVE_ADD',
|
||||||
'BOOKINGS_LIST',
|
'BOOKINGS_LIST',
|
||||||
'BOOKINGS_ADD',
|
'BOOKINGS_ADD',
|
||||||
'BOOKINGS_EDIT',
|
'ORDERS_LIST',
|
||||||
'BOOKINGS_DELETE',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function normalizePermissionsValue(mixed $raw): array
|
public static function normalizePermissionsValue(mixed $raw): array
|
||||||
|
|||||||
@@ -171,6 +171,7 @@ class subusers_o extends db
|
|||||||
return $this;
|
return $this;
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
$response->error($e->getMessage());
|
$response->error($e->getMessage());
|
||||||
|
throw $e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,9 +218,16 @@ class subusers_o extends db
|
|||||||
throw new RandomException('Error generating random bytes for setup token', 0, $e);
|
throw new RandomException('Error generating random bytes for setup token', 0, $e);
|
||||||
}
|
}
|
||||||
$cache_key = 'setup_token:' . $token;
|
$cache_key = 'setup_token:' . $token;
|
||||||
$cashe_object_id = 'subuser_setup_token';
|
$reverse_cache_key = 'setup_token_for_subuser:' . (int)$this->id;
|
||||||
$this->cache($cache_key, $this->id, $cashe_object_id);
|
$cache_object_id = 'subuser_setup_token';
|
||||||
$this->setCachedExpiration($cache_key, 24 * 60 * 60, $cashe_object_id); // Set the cache expiration to 24 hours
|
$existingToken = $this->getCached($reverse_cache_key, $cache_object_id);
|
||||||
|
if (is_string($existingToken) && $existingToken !== '') {
|
||||||
|
$this->deleteCached('setup_token:' . $existingToken, $cache_object_id);
|
||||||
|
}
|
||||||
|
$this->cache($cache_key, $this->id, $cache_object_id);
|
||||||
|
$this->setCachedExpiration($cache_key, 24 * 60 * 60, $cache_object_id); // Set the cache expiration to 24 hours
|
||||||
|
$this->cache($reverse_cache_key, $token, $cache_object_id);
|
||||||
|
$this->setCachedExpiration($reverse_cache_key, 24 * 60 * 60, $cache_object_id);
|
||||||
return $token;
|
return $token;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,8 +268,16 @@ class subusers_o extends db
|
|||||||
public function invalidateSetupToken(string $token): void
|
public function invalidateSetupToken(string $token): void
|
||||||
{
|
{
|
||||||
$object_id = 'subuser_setup_token';
|
$object_id = 'subuser_setup_token';
|
||||||
|
$subuser_id = $this->getSubuserIdBySetupToken($token);
|
||||||
$cache_key = 'setup_token:' . $token;
|
$cache_key = 'setup_token:' . $token;
|
||||||
$this->deleteCached($cache_key, $object_id);
|
$this->deleteCached($cache_key, $object_id);
|
||||||
|
if ($subuser_id !== null) {
|
||||||
|
$reverse_cache_key = 'setup_token_for_subuser:' . (int)$subuser_id;
|
||||||
|
$currentToken = $this->getCached($reverse_cache_key, $object_id);
|
||||||
|
if ((string)$currentToken === $token) {
|
||||||
|
$this->deleteCached($reverse_cache_key, $object_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -7462,7 +7462,7 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
type: object
|
type: object
|
||||||
required: [reg, type, wash_subscription]
|
required: [reg, type]
|
||||||
properties:
|
properties:
|
||||||
reg:
|
reg:
|
||||||
type: string
|
type: string
|
||||||
@@ -7474,6 +7474,8 @@ paths:
|
|||||||
description: Product ID representing the vehicle wash type
|
description: Product ID representing the vehicle wash type
|
||||||
wash_subscription:
|
wash_subscription:
|
||||||
type: boolean
|
type: boolean
|
||||||
|
default: false
|
||||||
|
description: Defaults to false when omitted.
|
||||||
reference:
|
reference:
|
||||||
type: string
|
type: string
|
||||||
maxLength: 255
|
maxLength: 255
|
||||||
@@ -11682,6 +11684,53 @@ paths:
|
|||||||
'502':
|
'502':
|
||||||
description: Slack customer registration webhook test failed
|
description: Slack customer registration webhook test failed
|
||||||
|
|
||||||
|
/slack/config/internal-department-goal-progress:
|
||||||
|
get:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Get Slack internal department goal progress config
|
||||||
|
operationId: getSlackInternalDepartmentGoalProgressConfig
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress configuration retrieved successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigResponse'
|
||||||
|
post:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Update Slack internal department goal progress config
|
||||||
|
operationId: updateSlackInternalDepartmentGoalProgressConfig
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigUpdate'
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress configuration updated successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfigResponse'
|
||||||
|
|
||||||
|
/slack/config/internal-department-goal-progress/test:
|
||||||
|
post:
|
||||||
|
tags: [Config]
|
||||||
|
summary: Test Slack internal department goal progress webhook
|
||||||
|
operationId: testSlackInternalDepartmentGoalProgressWebhook
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Slack internal department goal progress webhook test completed successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SlackConfigTestResponse'
|
||||||
|
'400':
|
||||||
|
description: Slack internal department goal progress webhook URL is not configured
|
||||||
|
'502':
|
||||||
|
description: Slack internal department goal progress webhook test failed
|
||||||
|
|
||||||
/backups/config:
|
/backups/config:
|
||||||
get:
|
get:
|
||||||
tags: [Config]
|
tags: [Config]
|
||||||
@@ -12474,6 +12523,40 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema: {}
|
schema: {}
|
||||||
|
|
||||||
|
/superuser/departments/{id}/overview:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- Departments
|
||||||
|
summary: Get superuser department overview
|
||||||
|
description: Returns the selected department metadata and operational overview metrics for a superuser without requiring scoped department access.
|
||||||
|
operationId: getSuperuserDepartmentOverview
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema: {type: integer}
|
||||||
|
- name: date
|
||||||
|
in: query
|
||||||
|
required: true
|
||||||
|
schema: {type: string}
|
||||||
|
- name: date_to
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
schema: {type: string}
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Superuser department overview loaded successfully
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/SuperuserDepartmentOverviewResponse'
|
||||||
|
'400':
|
||||||
|
$ref: '#/components/responses/BadRequest'
|
||||||
|
'403':
|
||||||
|
$ref: '#/components/responses/Forbidden'
|
||||||
|
'404':
|
||||||
|
$ref: '#/components/responses/NotFound'
|
||||||
|
|
||||||
/superuser/department/branding:
|
/superuser/department/branding:
|
||||||
put:
|
put:
|
||||||
tags:
|
tags:
|
||||||
@@ -15200,11 +15283,14 @@ components:
|
|||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
module: { type: string, enum: [Slack] }
|
module: { type: string, enum: [Slack] }
|
||||||
variable: { type: string, enum: [customer_registration_webhook_url] }
|
variable: { type: string, enum: [customer_registration_webhook_url, internal_department_goal_progress_webhook_url, internal_department_ids] }
|
||||||
type: { type: string, enum: [string] }
|
type: { type: string, enum: [string] }
|
||||||
value:
|
value:
|
||||||
type: string
|
oneOf:
|
||||||
example: https://hooks.slack.com/services/...
|
- type: string
|
||||||
|
example: https://hooks.slack.com/services/...
|
||||||
|
- type: string
|
||||||
|
example: '[1,2,3]'
|
||||||
required: [module, variable, type, value]
|
required: [module, variable, type, value]
|
||||||
|
|
||||||
SlackConfigTestResult:
|
SlackConfigTestResult:
|
||||||
@@ -15215,6 +15301,42 @@ components:
|
|||||||
message: { type: string }
|
message: { type: string }
|
||||||
required: [configured, sent, message]
|
required: [configured, sent, message]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressDepartment:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id: { type: integer }
|
||||||
|
name: { type: string }
|
||||||
|
order_priority: { type: integer }
|
||||||
|
required: [id, name, order_priority]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfig:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
internal_department_goal_progress_webhook_url:
|
||||||
|
type: string
|
||||||
|
example: https://hooks.slack.com/services/...
|
||||||
|
internal_department_ids:
|
||||||
|
type: array
|
||||||
|
items: { type: integer }
|
||||||
|
example: [1, 2, 3]
|
||||||
|
departments:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: '#/components/schemas/SlackInternalDepartmentGoalProgressDepartment'
|
||||||
|
required: [internal_department_goal_progress_webhook_url, internal_department_ids, departments]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfigUpdate:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
internal_department_goal_progress_webhook_url:
|
||||||
|
type: string
|
||||||
|
example: https://hooks.slack.com/services/...
|
||||||
|
internal_department_ids:
|
||||||
|
type: array
|
||||||
|
items: { type: integer }
|
||||||
|
example: [1, 2, 3]
|
||||||
|
required: [internal_department_goal_progress_webhook_url, internal_department_ids]
|
||||||
|
|
||||||
BackupsConfigEntry:
|
BackupsConfigEntry:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
@@ -15499,6 +15621,14 @@ components:
|
|||||||
data: { $ref: '#/components/schemas/SlackConfigTestResult' }
|
data: { $ref: '#/components/schemas/SlackConfigTestResult' }
|
||||||
required: [data]
|
required: [data]
|
||||||
|
|
||||||
|
SlackInternalDepartmentGoalProgressConfigResponse:
|
||||||
|
allOf:
|
||||||
|
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||||
|
- type: object
|
||||||
|
properties:
|
||||||
|
data: { $ref: '#/components/schemas/SlackInternalDepartmentGoalProgressConfig' }
|
||||||
|
required: [data]
|
||||||
|
|
||||||
BackupsConfigListResponse:
|
BackupsConfigListResponse:
|
||||||
allOf:
|
allOf:
|
||||||
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||||
@@ -21454,6 +21584,21 @@ components:
|
|||||||
data:
|
data:
|
||||||
$ref: '#/components/schemas/DepartmentDailyReportOverviewPayload'
|
$ref: '#/components/schemas/DepartmentDailyReportOverviewPayload'
|
||||||
|
|
||||||
|
SuperuserDepartmentOverviewPayload:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
department:
|
||||||
|
$ref: '#/components/schemas/Department'
|
||||||
|
overview:
|
||||||
|
$ref: '#/components/schemas/DepartmentDailyReportOverviewPayload'
|
||||||
|
|
||||||
|
SuperuserDepartmentOverviewResponse:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
success: { type: boolean, example: true }
|
||||||
|
data:
|
||||||
|
$ref: '#/components/schemas/SuperuserDepartmentOverviewPayload'
|
||||||
|
|
||||||
DepartmentDailyReportTransactionCountPayload:
|
DepartmentDailyReportTransactionCountPayload:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
|
|||||||
@@ -3,9 +3,8 @@ FROM ${BASE_IMAGE}
|
|||||||
|
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y --no-install-recommends bash ca-certificates curl docker.io docker-compose libcurl4-openssl-dev libsqlite3-dev; \
|
apt-get install -y --no-install-recommends bash ca-certificates curl docker.io docker-compose; \
|
||||||
docker-php-ext-install -j"$(nproc)" curl sqlite3 pdo_sqlite; \
|
php -r 'foreach (["curl", "sqlite3", "pdo_sqlite"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'; \
|
||||||
php -r 'foreach (["curl", "sqlite3"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'; \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
COPY auto-updater.php /usr/local/bin/auto-updater.php
|
COPY auto-updater.php /usr/local/bin/auto-updater.php
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
ARG BASE_IMAGE=php:8.2-cli-bookworm
|
ARG BASE_IMAGE=php:8.2-cli-bookworm
|
||||||
FROM ${BASE_IMAGE}
|
FROM ${BASE_IMAGE}
|
||||||
|
|
||||||
RUN set -eux; \
|
RUN php -r 'foreach (["curl", "sqlite3", "pdo_sqlite"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'
|
||||||
apt-get update; \
|
|
||||||
apt-get install -y --no-install-recommends libcurl4-openssl-dev libsqlite3-dev; \
|
|
||||||
docker-php-ext-install -j"$(nproc)" curl sqlite3 pdo_sqlite; \
|
|
||||||
php -r 'foreach (["curl", "sqlite3"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'; \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
WORKDIR /opt/truckwash-edge-agent
|
WORKDIR /opt/truckwash-edge-agent
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
ARG BASE_IMAGE=php:8.2-cli-bookworm
|
ARG BASE_IMAGE=php:8.2-cli-bookworm
|
||||||
FROM ${BASE_IMAGE}
|
FROM ${BASE_IMAGE}
|
||||||
|
|
||||||
RUN set -eux; \
|
RUN php -r 'foreach (["curl", "sqlite3", "pdo_sqlite"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'
|
||||||
apt-get update; \
|
|
||||||
apt-get install -y --no-install-recommends libcurl4-openssl-dev libsqlite3-dev; \
|
|
||||||
docker-php-ext-install -j"$(nproc)" curl sqlite3 pdo_sqlite; \
|
|
||||||
php -r 'foreach (["curl", "sqlite3"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing PHP extension: {$extension}\n"); exit(1); } }'; \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
WORKDIR /opt/truckwash-edge-agent
|
WORKDIR /opt/truckwash-edge-agent
|
||||||
|
|
||||||
|
|||||||
@@ -727,11 +727,20 @@ final class BrokerWebSocketClient
|
|||||||
throw new RuntimeException('Invalid broker websocket URL: ' . $socketUrl);
|
throw new RuntimeException('Invalid broker websocket URL: ' . $socketUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$host = (string)$parts['host'];
|
||||||
|
$path = (string)($parts['path'] ?? '/');
|
||||||
|
if ($host === 'edge-broker' && ($path === '/edge-broker' || str_starts_with($path, '/edge-broker/'))) {
|
||||||
|
$path = substr($path, strlen('/edge-broker'));
|
||||||
|
if ($path === '') {
|
||||||
|
$path = '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'scheme' => strtolower((string)($parts['scheme'] ?? 'ws')),
|
'scheme' => strtolower((string)($parts['scheme'] ?? 'ws')),
|
||||||
'host' => (string)$parts['host'],
|
'host' => $host,
|
||||||
'port' => (int)($parts['port'] ?? (((string)($parts['scheme'] ?? 'ws')) === 'wss' ? 443 : 80)),
|
'port' => (int)($parts['port'] ?? (((string)($parts['scheme'] ?? 'ws')) === 'wss' ? 443 : 80)),
|
||||||
'path' => (string)($parts['path'] ?? '/')
|
'path' => $path
|
||||||
. (isset($parts['query']) && trim((string)$parts['query']) !== '' ? '?' . $parts['query'] : ''),
|
. (isset($parts['query']) && trim((string)$parts['query']) !== '' ? '?' . $parts['query'] : ''),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -997,9 +1006,16 @@ final class TruckwashEdgeAgent
|
|||||||
private const DEFAULT_WORKER_BASE_URL = 'http://lan-worker:8090';
|
private const DEFAULT_WORKER_BASE_URL = 'http://lan-worker:8090';
|
||||||
private const DEFAULT_UPDATE_WINDOW = '02:00-04:00';
|
private const DEFAULT_UPDATE_WINDOW = '02:00-04:00';
|
||||||
private const OPERATION_COMPLETE_TIMEOUT_SECONDS = 120;
|
private const OPERATION_COMPLETE_TIMEOUT_SECONDS = 120;
|
||||||
|
private const OUTBOX_REPLAY_BATCH_LIMIT = 3;
|
||||||
|
private const OUTBOX_REPLAY_TIMEOUT_SECONDS = 3;
|
||||||
|
private const OUTBOX_OPERATION_COMPLETE_REPLAY_TIMEOUT_SECONDS = 10;
|
||||||
|
private const OUTBOX_REPLAY_FAILURE_COOLDOWN_SECONDS = 15;
|
||||||
|
private const MACHINE_SIGNAL_TIMEOUT_SECONDS = 3;
|
||||||
private const BROKER_MESSAGE_PUMP_LIMIT = 12;
|
private const BROKER_MESSAGE_PUMP_LIMIT = 12;
|
||||||
|
private const BROKER_CONNECTED_COMMAND_POLL_INTERVAL_SECONDS = 1;
|
||||||
private const LOOP_STALE_AFTER_SECONDS = 30;
|
private const LOOP_STALE_AFTER_SECONDS = 30;
|
||||||
private const CONTROL_PLANE_SYNC_STALE_AFTER_SECONDS = 90;
|
private const CONTROL_PLANE_SYNC_STALE_AFTER_SECONDS = 90;
|
||||||
|
private const MAX_RELAY_TOGGLE_AFTER_SECONDS = 5;
|
||||||
|
|
||||||
private AgentConfig $config;
|
private AgentConfig $config;
|
||||||
private HttpJsonClient $http;
|
private HttpJsonClient $http;
|
||||||
@@ -1017,7 +1033,9 @@ final class TruckwashEdgeAgent
|
|||||||
private string $stagedUpdatePath;
|
private string $stagedUpdatePath;
|
||||||
private int $lastHeartbeatAt = 0;
|
private int $lastHeartbeatAt = 0;
|
||||||
private int $lastMachineSignalPollAt = 0;
|
private int $lastMachineSignalPollAt = 0;
|
||||||
|
private int $lastBrokerConnectedCommandPollAt = 0;
|
||||||
private int $lastMachineSignalMonitorRefreshAt = 0;
|
private int $lastMachineSignalMonitorRefreshAt = 0;
|
||||||
|
private int $lastOutboxFailureAt = 0;
|
||||||
private ?array $lastControlPlaneResponse = null;
|
private ?array $lastControlPlaneResponse = null;
|
||||||
private string $agentInstanceId;
|
private string $agentInstanceId;
|
||||||
|
|
||||||
@@ -1061,7 +1079,6 @@ final class TruckwashEdgeAgent
|
|||||||
$this->reloadConfigFromDisk();
|
$this->reloadConfigFromDisk();
|
||||||
$this->ensureClaimed();
|
$this->ensureClaimed();
|
||||||
$this->configureBrokerClient();
|
$this->configureBrokerClient();
|
||||||
$this->flushOutbox();
|
|
||||||
$this->pumpBrokerTransport();
|
$this->pumpBrokerTransport();
|
||||||
$this->heartbeat();
|
$this->heartbeat();
|
||||||
$this->pollMachineStartSignals();
|
$this->pollMachineStartSignals();
|
||||||
@@ -1069,12 +1086,13 @@ final class TruckwashEdgeAgent
|
|||||||
$this->pumpBrokerTransport();
|
$this->pumpBrokerTransport();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
$brokerConnected = $this->isBrokerConnected();
|
||||||
$processedManagementOperation = false;
|
$processedManagementOperation = false;
|
||||||
if (!$this->isBrokerConnected()) {
|
if (!$brokerConnected) {
|
||||||
$processedManagementOperation = $this->processManagementOperation();
|
$processedManagementOperation = $this->processManagementOperation();
|
||||||
}
|
}
|
||||||
if (!$processedManagementOperation && !$this->isBrokerConnected()) {
|
if (!$processedManagementOperation && $this->shouldPollApiCommandQueue($brokerConnected)) {
|
||||||
$this->processCommandQueue();
|
$this->processCommandQueue($brokerConnected ? 0 : null);
|
||||||
}
|
}
|
||||||
$this->pumpBrokerTransport();
|
$this->pumpBrokerTransport();
|
||||||
$this->flushOutbox();
|
$this->flushOutbox();
|
||||||
@@ -1093,7 +1111,7 @@ final class TruckwashEdgeAgent
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$installedVersion = (string)$this->config->get('installedVersion', 'compose-php-agent-v2');
|
$installedVersion = (string)$this->config->get('installedVersion', 'compose-php-agent-v3');
|
||||||
try {
|
try {
|
||||||
$response = $this->http->post('/edge-agent/claim', [
|
$response = $this->http->post('/edge-agent/claim', [
|
||||||
'token' => (string)$this->config->get('installToken'),
|
'token' => (string)$this->config->get('installToken'),
|
||||||
@@ -1249,10 +1267,10 @@ final class TruckwashEdgeAgent
|
|||||||
'agent_token' => (string)$this->config->get('agentToken'),
|
'agent_token' => (string)$this->config->get('agentToken'),
|
||||||
'status' => 'ONLINE',
|
'status' => 'ONLINE',
|
||||||
'hostname' => gethostname() ?: 'truckwash-edge',
|
'hostname' => gethostname() ?: 'truckwash-edge',
|
||||||
'installed_version' => (string)$this->config->get('installedVersion', 'compose-php-agent-v2'),
|
'installed_version' => (string)$this->config->get('installedVersion', 'compose-php-agent-v3'),
|
||||||
'target_version' => (string)$this->config->get(
|
'target_version' => (string)$this->config->get(
|
||||||
'targetVersion',
|
'targetVersion',
|
||||||
$this->config->get('installedVersion', 'compose-php-agent-v2')
|
$this->config->get('installedVersion', 'compose-php-agent-v3')
|
||||||
),
|
),
|
||||||
'metadata' => array_merge([
|
'metadata' => array_merge([
|
||||||
'agent_instance_id' => $this->agentInstanceId,
|
'agent_instance_id' => $this->agentInstanceId,
|
||||||
@@ -1356,7 +1374,8 @@ final class TruckwashEdgeAgent
|
|||||||
$this->sendControlPlaneEvent(
|
$this->sendControlPlaneEvent(
|
||||||
'/edge-agent/gateways/' . $gatewayId . '/selfserve/machine-signal',
|
'/edge-agent/gateways/' . $gatewayId . '/selfserve/machine-signal',
|
||||||
$payload,
|
$payload,
|
||||||
'machine_signal'
|
'machine_signal',
|
||||||
|
self::MACHINE_SIGNAL_TIMEOUT_SECONDS
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1464,14 +1483,29 @@ final class TruckwashEdgeAgent
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function processCommandQueue(): void
|
private function shouldPollApiCommandQueue(bool $brokerConnected): bool
|
||||||
|
{
|
||||||
|
if (!$brokerConnected) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$now = time();
|
||||||
|
if (($now - $this->lastBrokerConnectedCommandPollAt) < self::BROKER_CONNECTED_COMMAND_POLL_INTERVAL_SECONDS) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->lastBrokerConnectedCommandPollAt = $now;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function processCommandQueue(?int $waitSecondsOverride = null): void
|
||||||
{
|
{
|
||||||
$gatewayId = (int)$this->config->get('gatewayId');
|
$gatewayId = (int)$this->config->get('gatewayId');
|
||||||
if ($gatewayId <= 0) {
|
if ($gatewayId <= 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$waitSeconds = (int)$this->config->get('operationPollTimeoutSeconds', 20);
|
$waitSeconds = $waitSecondsOverride ?? (int)$this->config->get('operationPollTimeoutSeconds', 20);
|
||||||
try {
|
try {
|
||||||
$response = $this->http->post('/edge-agent/gateways/' . $gatewayId . '/commands/poll', [
|
$response = $this->http->post('/edge-agent/gateways/' . $gatewayId . '/commands/poll', [
|
||||||
'agent_token' => (string)$this->config->get('agentToken'),
|
'agent_token' => (string)$this->config->get('agentToken'),
|
||||||
@@ -1948,7 +1982,7 @@ final class TruckwashEdgeAgent
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'applied' => false,
|
'applied' => false,
|
||||||
'installed_version' => (string)$this->config->get('installedVersion', 'compose-php-agent-v2'),
|
'installed_version' => (string)$this->config->get('installedVersion', 'compose-php-agent-v3'),
|
||||||
'staged_version' => $targetVersion,
|
'staged_version' => $targetVersion,
|
||||||
'target_version' => $targetVersion,
|
'target_version' => $targetVersion,
|
||||||
'staged_at' => $stagedAt,
|
'staged_at' => $stagedAt,
|
||||||
@@ -2010,26 +2044,156 @@ final class TruckwashEdgeAgent
|
|||||||
$localIp = (string)($request['localIp'] ?? $request['local_ip'] ?? '');
|
$localIp = (string)($request['localIp'] ?? $request['local_ip'] ?? '');
|
||||||
$channel = (int)($request['channel'] ?? 0);
|
$channel = (int)($request['channel'] ?? 0);
|
||||||
$on = (bool)($request['on'] ?? false);
|
$on = (bool)($request['on'] ?? false);
|
||||||
|
$toggleAfter = $this->resolveRelayToggleAfterSeconds($request);
|
||||||
|
$deviceGeneration = $this->resolveShellyCommandGeneration($request);
|
||||||
|
$workerPayload = [
|
||||||
|
'local_ip' => $localIp,
|
||||||
|
'channel' => $channel,
|
||||||
|
'on' => $on,
|
||||||
|
];
|
||||||
|
if ($toggleAfter !== null) {
|
||||||
|
$workerPayload['toggle_after'] = $toggleAfter;
|
||||||
|
$workerPayload['toggleAfter'] = $toggleAfter;
|
||||||
|
}
|
||||||
|
if ($deviceGeneration !== null) {
|
||||||
|
$workerPayload['device_generation'] = $deviceGeneration;
|
||||||
|
$workerPayload['deviceGeneration'] = $deviceGeneration;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return $this->workerHttp->post('/relay/switch', [
|
return $this->workerHttp->post('/relay/switch', $workerPayload, 8) ?? [];
|
||||||
'local_ip' => $localIp,
|
|
||||||
'channel' => $channel,
|
|
||||||
'on' => $on,
|
|
||||||
], 8) ?? [];
|
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
$rpcUrl = sprintf('http://%s/rpc/Switch.Set?id=%d&on=%s', $localIp, $channel, $on ? 'true' : 'false');
|
$timerQuery = $toggleAfter === null ? '' : '&toggle_after=' . rawurlencode((string)$toggleAfter);
|
||||||
|
$legacyTimerQuery = $toggleAfter === null ? '' : '&timer=' . rawurlencode((string)$toggleAfter);
|
||||||
|
$runRpcSwitch = fn(): array => $this->http->getJson(
|
||||||
|
sprintf('http://%s/rpc/Switch.Set?id=%d&on=%s%s', $localIp, $channel, $on ? 'true' : 'false', $timerQuery),
|
||||||
|
8
|
||||||
|
);
|
||||||
|
$runLegacySwitch = fn(): array => $this->http->getJson(
|
||||||
|
sprintf('http://%s/relay/%d?turn=%s%s', $localIp, $channel, $on ? 'on' : 'off', $legacyTimerQuery),
|
||||||
|
8
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($toggleAfter !== null) {
|
||||||
|
$attempts = $deviceGeneration === 1
|
||||||
|
? [$runLegacySwitch, $runRpcSwitch]
|
||||||
|
: [$runRpcSwitch, $runLegacySwitch];
|
||||||
|
$lastError = null;
|
||||||
|
foreach ($attempts as $attempt) {
|
||||||
|
try {
|
||||||
|
$attempt();
|
||||||
|
return $this->fetchShellyState($localIp, $channel);
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
$lastError = $throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw $lastError ?? new RuntimeException('Unable to switch relay');
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->http->getJson($rpcUrl, 8);
|
$runRpcSwitch();
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
$legacyUrl = sprintf('http://%s/relay/%d?turn=%s', $localIp, $channel, $on ? 'on' : 'off');
|
$runLegacySwitch();
|
||||||
$this->http->getJson($legacyUrl, 8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->fetchShellyState($localIp, $channel);
|
return $this->fetchShellyState($localIp, $channel);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function resolveRelayToggleAfterSeconds(array $request): ?int
|
||||||
|
{
|
||||||
|
$configured = $request['toggleAfter'] ?? $request['toggle_after'] ?? $request['timer'] ?? null;
|
||||||
|
if (!is_int($configured) && !is_float($configured) && !(is_string($configured) && is_numeric(trim($configured)))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$seconds = (int)floor((float)$configured);
|
||||||
|
if ($seconds <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return min($seconds, self::MAX_RELAY_TOGGLE_AFTER_SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizeShellyDeviceGeneration(mixed $value): ?int
|
||||||
|
{
|
||||||
|
if (is_int($value) || is_float($value) || (is_string($value) && is_numeric(trim($value)))) {
|
||||||
|
$generation = (int)$value;
|
||||||
|
return $generation > 0 ? $generation : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function inferShellyDeviceGenerationFromString(mixed $value): ?int
|
||||||
|
{
|
||||||
|
$normalized = trim((string)$value);
|
||||||
|
if ($normalized === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\bgen(?:eration)?\s*([1-9]\d*)\b/i', $normalized, $explicit) === 1) {
|
||||||
|
return (int)$explicit[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
$upper = strtoupper($normalized);
|
||||||
|
if (preg_match('/\bS([3-9])(?:[A-Z0-9]+)?-[A-Z0-9-]+\b/', $upper, $series) === 1) {
|
||||||
|
return (int)$series[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\b(?:SHELLY\s+)?(?:PLUS|PRO)\b/i', $normalized) === 1 || preg_match('/\bSP[A-Z0-9]+-[A-Z0-9-]+\b/', $upper) === 1) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\bSH[A-Z0-9]+-?[A-Z0-9-]*\b/', $upper) === 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolveShellyCommandGeneration(array $request): ?int
|
||||||
|
{
|
||||||
|
foreach ([
|
||||||
|
$request['gen'] ?? null,
|
||||||
|
$request['generation'] ?? null,
|
||||||
|
$request['deviceGeneration'] ?? null,
|
||||||
|
$request['device_generation'] ?? null,
|
||||||
|
is_array($request['capabilities'] ?? null) ? ($request['capabilities']['generation'] ?? null) : null,
|
||||||
|
] as $candidate) {
|
||||||
|
$generation = $this->normalizeShellyDeviceGeneration($candidate);
|
||||||
|
if ($generation !== null) {
|
||||||
|
return $generation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
$request['model'] ?? null,
|
||||||
|
$request['deviceModel'] ?? null,
|
||||||
|
$request['device_model'] ?? null,
|
||||||
|
$request['type'] ?? null,
|
||||||
|
$request['deviceType'] ?? null,
|
||||||
|
$request['device_type'] ?? null,
|
||||||
|
$request['app'] ?? null,
|
||||||
|
$request['name'] ?? null,
|
||||||
|
$request['deviceName'] ?? null,
|
||||||
|
$request['device_name'] ?? null,
|
||||||
|
$request['deviceId'] ?? null,
|
||||||
|
$request['device_id'] ?? null,
|
||||||
|
$request['relayId'] ?? null,
|
||||||
|
$request['relay_id'] ?? null,
|
||||||
|
$request['mac'] ?? null,
|
||||||
|
] as $candidate) {
|
||||||
|
$generation = $this->inferShellyDeviceGenerationFromString($candidate);
|
||||||
|
if ($generation !== null) {
|
||||||
|
return $generation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
private function downloadToFileAtomic(string $url, string $path, string $expectedSha256 = ''): array
|
private function downloadToFileAtomic(string $url, string $path, string $expectedSha256 = ''): array
|
||||||
{
|
{
|
||||||
$directory = dirname($path);
|
$directory = dirname($path);
|
||||||
@@ -2321,12 +2485,14 @@ final class TruckwashEdgeAgent
|
|||||||
|
|
||||||
private function flushOutbox(): void
|
private function flushOutbox(): void
|
||||||
{
|
{
|
||||||
$items = $this->stateStore->queuedItems(25);
|
if ($this->shouldSkipOutboxReplay()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$items = $this->stateStore->queuedItems(self::OUTBOX_REPLAY_BATCH_LIMIT);
|
||||||
foreach ($items as $item) {
|
foreach ($items as $item) {
|
||||||
try {
|
try {
|
||||||
$timeoutSeconds = (string)($item['type'] ?? '') === 'operation_complete'
|
$timeoutSeconds = $this->outboxReplayTimeoutSeconds((string)($item['type'] ?? ''));
|
||||||
? self::OPERATION_COMPLETE_TIMEOUT_SECONDS
|
|
||||||
: 20;
|
|
||||||
$endpoint = (string)$item['endpoint'];
|
$endpoint = (string)$item['endpoint'];
|
||||||
$payload = is_array($item['payload'] ?? null) ? (array)$item['payload'] : [];
|
$payload = is_array($item['payload'] ?? null) ? (array)$item['payload'] : [];
|
||||||
$brokerDispatch = $this->dispatchBrokerControlPlaneEvent($endpoint, $payload);
|
$brokerDispatch = $this->dispatchBrokerControlPlaneEvent($endpoint, $payload);
|
||||||
@@ -2334,8 +2500,10 @@ final class TruckwashEdgeAgent
|
|||||||
$this->http->post($endpoint, $payload, $timeoutSeconds);
|
$this->http->post($endpoint, $payload, $timeoutSeconds);
|
||||||
}
|
}
|
||||||
$this->stateStore->removeOutboxItem((int)$item['id']);
|
$this->stateStore->removeOutboxItem((int)$item['id']);
|
||||||
|
$this->lastOutboxFailureAt = 0;
|
||||||
$this->recordSuccessfulSync();
|
$this->recordSuccessfulSync();
|
||||||
} catch (Throwable $throwable) {
|
} catch (Throwable $throwable) {
|
||||||
|
$this->lastOutboxFailureAt = time();
|
||||||
$this->recordTransportFailure(
|
$this->recordTransportFailure(
|
||||||
'Outbox replay blocked on ' . (string)$item['type'] . ' for ' . (string)$item['endpoint'],
|
'Outbox replay blocked on ' . (string)$item['type'] . ' for ' . (string)$item['endpoint'],
|
||||||
$throwable
|
$throwable
|
||||||
@@ -2345,6 +2513,19 @@ final class TruckwashEdgeAgent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function shouldSkipOutboxReplay(): bool
|
||||||
|
{
|
||||||
|
return $this->lastOutboxFailureAt > 0
|
||||||
|
&& (time() - $this->lastOutboxFailureAt) < self::OUTBOX_REPLAY_FAILURE_COOLDOWN_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function outboxReplayTimeoutSeconds(string $type): int
|
||||||
|
{
|
||||||
|
return $type === 'operation_complete'
|
||||||
|
? self::OUTBOX_OPERATION_COMPLETE_REPLAY_TIMEOUT_SECONDS
|
||||||
|
: self::OUTBOX_REPLAY_TIMEOUT_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
private function probeWorkerHealth(): array
|
private function probeWorkerHealth(): array
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
@@ -2433,7 +2614,7 @@ final class TruckwashEdgeAgent
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function sendControlPlaneEvent(string $endpoint, array $payload, string $type): bool
|
private function sendControlPlaneEvent(string $endpoint, array $payload, string $type, int $timeoutSeconds = 20): bool
|
||||||
{
|
{
|
||||||
$this->lastControlPlaneResponse = null;
|
$this->lastControlPlaneResponse = null;
|
||||||
$brokerDispatch = $this->dispatchBrokerControlPlaneEvent($endpoint, $payload);
|
$brokerDispatch = $this->dispatchBrokerControlPlaneEvent($endpoint, $payload);
|
||||||
@@ -2442,7 +2623,7 @@ final class TruckwashEdgeAgent
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$response = $this->http->post($endpoint, $payload, 20);
|
$response = $this->http->post($endpoint, $payload, $timeoutSeconds);
|
||||||
$this->lastControlPlaneResponse = is_array($response) ? $response : null;
|
$this->lastControlPlaneResponse = is_array($response) ? $response : null;
|
||||||
$this->recordSuccessfulSync();
|
$this->recordSuccessfulSync();
|
||||||
return true;
|
return true;
|
||||||
@@ -2477,7 +2658,9 @@ final class TruckwashEdgeAgent
|
|||||||
}
|
}
|
||||||
|
|
||||||
$current = trim((string)$this->config->get('brokerUrl'));
|
$current = trim((string)$this->config->get('brokerUrl'));
|
||||||
if (rtrim($current, '/') === rtrim($brokerUrl, '/')) {
|
$currentNormalized = $this->normalizeBrokerUrlForComparison($current);
|
||||||
|
$nextNormalized = $this->normalizeBrokerUrlForComparison($brokerUrl);
|
||||||
|
if ($currentNormalized !== null && $currentNormalized === $nextNormalized) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2487,6 +2670,38 @@ final class TruckwashEdgeAgent
|
|||||||
$this->logger->info('Updated broker URL from control plane heartbeat response.');
|
$this->logger->info('Updated broker URL from control plane heartbeat response.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function normalizeBrokerUrlForComparison(?string $value): ?string
|
||||||
|
{
|
||||||
|
$trimmed = rtrim(trim((string)($value ?? '')), '/');
|
||||||
|
if ($trimmed === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($trimmed, 'https://')) {
|
||||||
|
$trimmed = 'wss://' . substr($trimmed, 8);
|
||||||
|
} elseif (str_starts_with($trimmed, 'http://')) {
|
||||||
|
$trimmed = 'ws://' . substr($trimmed, 7);
|
||||||
|
} elseif (!str_starts_with($trimmed, 'ws://') && !str_starts_with($trimmed, 'wss://')) {
|
||||||
|
$trimmed = 'ws://' . $trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts = parse_url($trimmed);
|
||||||
|
if (!is_array($parts) || empty($parts['host'])) {
|
||||||
|
return strtolower($trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
$scheme = strtolower((string)($parts['scheme'] ?? 'ws'));
|
||||||
|
$host = strtolower((string)$parts['host']);
|
||||||
|
$port = isset($parts['port']) ? (int)$parts['port'] : ($scheme === 'wss' ? 443 : 80);
|
||||||
|
$path = rtrim((string)($parts['path'] ?? ''), '/');
|
||||||
|
if ($host === 'edge-broker' && ($path === '/edge-broker' || str_starts_with($path, '/edge-broker/'))) {
|
||||||
|
$path = rtrim(substr($path, strlen('/edge-broker')), '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
$isDefaultPort = ($scheme === 'wss' && $port === 443) || ($scheme !== 'wss' && $port === 80);
|
||||||
|
return $scheme . '://' . $host . ($isDefaultPort ? '' : ':' . $port) . ($path === '' ? '' : $path);
|
||||||
|
}
|
||||||
|
|
||||||
private function shouldPersistControlPlaneEventOverHttp(string $endpoint): bool
|
private function shouldPersistControlPlaneEventOverHttp(string $endpoint): bool
|
||||||
{
|
{
|
||||||
return preg_match('#/edge-agent/gateways/\d+/heartbeat$#', $endpoint) === 1;
|
return preg_match('#/edge-agent/gateways/\d+/heartbeat$#', $endpoint) === 1;
|
||||||
@@ -2796,6 +3011,13 @@ final class TruckwashEdgeAgent
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (preg_match('#/edge-agent/gateways/\d+/selfserve/machine-signal$#', $endpoint)) {
|
||||||
|
return $this->sendBrokerMessage([
|
||||||
|
'type' => 'MACHINE_SIGNAL',
|
||||||
|
'payload' => $this->stripAgentAuthentication($payload),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2890,7 +3112,10 @@ final class TruckwashEdgeAgent
|
|||||||
{
|
{
|
||||||
$reloaded = AgentConfig::load($this->config->path);
|
$reloaded = AgentConfig::load($this->config->path);
|
||||||
$this->config = $reloaded;
|
$this->config = $reloaded;
|
||||||
$this->workerHttp = new HttpJsonClient((string)$this->config->get('workerBaseUrl', self::DEFAULT_WORKER_BASE_URL));
|
$this->workerHttp = new HttpJsonClient(
|
||||||
|
(string)$this->config->get('workerBaseUrl', self::DEFAULT_WORKER_BASE_URL),
|
||||||
|
$this->workerAuthorizationHeaders()
|
||||||
|
);
|
||||||
$this->configureBrokerClient();
|
$this->configureBrokerClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ services:
|
|||||||
test:
|
test:
|
||||||
[
|
[
|
||||||
"CMD-SHELL",
|
"CMD-SHELL",
|
||||||
"php -r '$$path=\"/opt/truckwash-edge-agent/runtime/control-plane-status.json\"; if (!is_file($$path)) { exit(1); } $$data=json_decode((string)file_get_contents($$path), true); if (!is_array($$data)) { exit(1); } $$loopAt=strtotime((string)($$data[\"last_loop_at\"] ?? \"\")); $$syncAt=strtotime((string)($$data[\"last_successful_sync_at\"] ?? $$data[\"started_at\"] ?? \"\")); if ($$loopAt === false || $$syncAt === false) { exit(1); } $$now=time(); exit((($$now - $$loopAt) <= 30 && ($$now - $$syncAt) <= 90) ? 0 : 1);'",
|
"php -r '$$path=\"/opt/truckwash-edge-agent/runtime/control-plane-status.json\"; if (!is_file($$path)) { exit(1); } $$data=json_decode((string)file_get_contents($$path), true); if (!is_array($$data)) { exit(1); } $$loopAt=strtotime((string)($$data[\"last_loop_at\"] ?? $$data[\"started_at\"] ?? \"\")); if ($$loopAt === false) { exit(1); } $$now=time(); exit(($$now - $$loopAt) <= 120 ? 0 : 1);'",
|
||||||
]
|
]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
|
|||||||
@@ -31,14 +31,17 @@ compose_cmd() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
print_compose_diagnostics() {
|
print_compose_diagnostics() {
|
||||||
log "docker ps --format '{{.Names}} {{.Status}}'"
|
local compose_project_name
|
||||||
docker ps --format '{{.Names}} {{.Status}}' || true
|
compose_project_name="$(config_value composeProjectName 'truckwash-edge-gateway')"
|
||||||
|
|
||||||
log "compose ps"
|
log "docker ps -a --format '{{.Names}} {{.Status}} {{.Ports}}'"
|
||||||
compose_cmd -f "$COMPOSE_FILE" ps || true
|
docker ps -a --format '{{.Names}} {{.Status}} {{.Ports}}' || true
|
||||||
|
|
||||||
log "compose logs --tail=80"
|
log "compose ps -a --no-trunc"
|
||||||
compose_cmd -f "$COMPOSE_FILE" logs --tail=80 || true
|
COMPOSE_PROJECT_NAME="$compose_project_name" compose_cmd -f "$COMPOSE_FILE" ps -a --no-trunc || true
|
||||||
|
|
||||||
|
log "compose logs --no-color --no-log-prefix --tail=120"
|
||||||
|
COMPOSE_PROJECT_NAME="$compose_project_name" compose_cmd -f "$COMPOSE_FILE" logs --no-color --no-log-prefix --tail=120 || true
|
||||||
}
|
}
|
||||||
|
|
||||||
config_value() {
|
config_value() {
|
||||||
@@ -61,6 +64,32 @@ config_value() {
|
|||||||
' "$CONFIG_PATH" "$key" "$fallback"
|
' "$CONFIG_PATH" "$key" "$fallback"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
staged_update_value() {
|
||||||
|
local key="$1"
|
||||||
|
local fallback="${2:-}"
|
||||||
|
php -r '
|
||||||
|
$path = $argv[1];
|
||||||
|
$key = $argv[2];
|
||||||
|
$fallback = $argv[3];
|
||||||
|
if (!is_file($path)) {
|
||||||
|
echo $fallback;
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
$decoded = json_decode((string)file_get_contents($path), true);
|
||||||
|
if (!is_array($decoded) || !array_key_exists($key, $decoded) || $decoded[$key] === null || $decoded[$key] === "") {
|
||||||
|
echo $fallback;
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
echo is_scalar($decoded[$key]) ? (string)$decoded[$key] : json_encode($decoded[$key], JSON_UNESCAPED_SLASHES);
|
||||||
|
' "$STAGED_UPDATE_PATH" "$key" "$fallback"
|
||||||
|
}
|
||||||
|
|
||||||
|
staged_update_is_applied() {
|
||||||
|
local status
|
||||||
|
status="$(staged_update_value status '')"
|
||||||
|
[ "$status" = "APPLIED" ]
|
||||||
|
}
|
||||||
|
|
||||||
ensure_dirs() {
|
ensure_dirs() {
|
||||||
mkdir -p "$RUNTIME_DIR" "$RUNTIME_DIR/backups"
|
mkdir -p "$RUNTIME_DIR" "$RUNTIME_DIR/backups"
|
||||||
}
|
}
|
||||||
@@ -103,7 +132,10 @@ ensure_stack_env() {
|
|||||||
|
|
||||||
within_update_window() {
|
within_update_window() {
|
||||||
local window
|
local window
|
||||||
window="$(config_value updateWindow '02:00-04:00')"
|
window="$(staged_update_value update_window '')"
|
||||||
|
if [ -z "$window" ]; then
|
||||||
|
window="$(config_value updateWindow '02:00-04:00')"
|
||||||
|
fi
|
||||||
php -r '
|
php -r '
|
||||||
$window = $argv[1];
|
$window = $argv[1];
|
||||||
[$start, $end] = array_pad(explode("-", $window, 2), 2, "");
|
[$start, $end] = array_pad(explode("-", $window, 2), 2, "");
|
||||||
@@ -283,6 +315,10 @@ case "$ACTION" in
|
|||||||
reconcile_stack
|
reconcile_stack
|
||||||
;;
|
;;
|
||||||
reconcile)
|
reconcile)
|
||||||
|
if [ -f "$STAGED_UPDATE_PATH" ] && staged_update_is_applied; then
|
||||||
|
log "Staged update already applied; nothing to reconcile"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
if [ -f "$STAGED_UPDATE_PATH" ] && ! within_update_window; then
|
if [ -f "$STAGED_UPDATE_PATH" ] && ! within_update_window; then
|
||||||
log "Update is staged but outside the maintenance window; keeping current stack running"
|
log "Update is staged but outside the maintenance window; keeping current stack running"
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
const WORKER_MAX_RELAY_TOGGLE_AFTER_SECONDS = 5;
|
||||||
|
|
||||||
function worker_json_response(int $status, array $payload): void
|
function worker_json_response(int $status, array $payload): void
|
||||||
{
|
{
|
||||||
http_response_code($status);
|
http_response_code($status);
|
||||||
@@ -156,17 +158,173 @@ function worker_fetch_shelly_input_state(string $localIp, int $channel): ?array
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function worker_switch_shelly_state(string $localIp, int $channel, bool $on): array
|
function worker_normalize_shelly_device_generation(mixed $value): ?int
|
||||||
{
|
{
|
||||||
|
if (is_int($value) || is_float($value) || (is_string($value) && is_numeric(trim($value)))) {
|
||||||
|
$generation = (int)$value;
|
||||||
|
return $generation > 0 ? $generation : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker_infer_shelly_device_generation_from_string(mixed $value): ?int
|
||||||
|
{
|
||||||
|
$normalized = trim((string)$value);
|
||||||
|
if ($normalized === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\bgen(?:eration)?\s*([1-9]\d*)\b/i', $normalized, $explicit) === 1) {
|
||||||
|
return (int)$explicit[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
$upper = strtoupper($normalized);
|
||||||
|
if (preg_match('/\bS([3-9])(?:[A-Z0-9]+)?-[A-Z0-9-]+\b/', $upper, $series) === 1) {
|
||||||
|
return (int)$series[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\b(?:SHELLY\s+)?(?:PLUS|PRO)\b/i', $normalized) === 1 || preg_match('/\bSP[A-Z0-9]+-[A-Z0-9-]+\b/', $upper) === 1) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\bSH[A-Z0-9]+-?[A-Z0-9-]*\b/', $upper) === 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker_resolve_shelly_command_generation(array $command): ?int
|
||||||
|
{
|
||||||
|
foreach ([
|
||||||
|
$command['gen'] ?? null,
|
||||||
|
$command['generation'] ?? null,
|
||||||
|
$command['deviceGeneration'] ?? null,
|
||||||
|
$command['device_generation'] ?? null,
|
||||||
|
is_array($command['capabilities'] ?? null) ? ($command['capabilities']['generation'] ?? null) : null,
|
||||||
|
] as $candidate) {
|
||||||
|
$generation = worker_normalize_shelly_device_generation($candidate);
|
||||||
|
if ($generation !== null) {
|
||||||
|
return $generation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
$command['model'] ?? null,
|
||||||
|
$command['deviceModel'] ?? null,
|
||||||
|
$command['device_model'] ?? null,
|
||||||
|
$command['type'] ?? null,
|
||||||
|
$command['deviceType'] ?? null,
|
||||||
|
$command['device_type'] ?? null,
|
||||||
|
$command['app'] ?? null,
|
||||||
|
$command['name'] ?? null,
|
||||||
|
$command['deviceName'] ?? null,
|
||||||
|
$command['device_name'] ?? null,
|
||||||
|
$command['deviceId'] ?? null,
|
||||||
|
$command['device_id'] ?? null,
|
||||||
|
$command['relayId'] ?? null,
|
||||||
|
$command['relay_id'] ?? null,
|
||||||
|
$command['mac'] ?? null,
|
||||||
|
] as $candidate) {
|
||||||
|
$generation = worker_infer_shelly_device_generation_from_string($candidate);
|
||||||
|
if ($generation !== null) {
|
||||||
|
return $generation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker_resolve_relay_toggle_after_seconds(array $command): ?int
|
||||||
|
{
|
||||||
|
$configured = $command['toggleAfter'] ?? $command['toggle_after'] ?? $command['timer'] ?? null;
|
||||||
|
if (!is_int($configured) && !is_float($configured) && !(is_string($configured) && is_numeric(trim($configured)))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$seconds = (int)floor((float)$configured);
|
||||||
|
if ($seconds <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return min($seconds, WORKER_MAX_RELAY_TOGGLE_AFTER_SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker_switch_shelly_state(string $localIp, int $channel, bool $on, array $command = []): array
|
||||||
|
{
|
||||||
|
if ($localIp === '') {
|
||||||
|
throw new RuntimeException('Missing Shelly IP address');
|
||||||
|
}
|
||||||
|
|
||||||
|
$toggleAfter = worker_resolve_relay_toggle_after_seconds($command);
|
||||||
|
$timerQuery = $toggleAfter === null ? '' : '&toggle_after=' . rawurlencode((string)$toggleAfter);
|
||||||
|
$legacyTimerQuery = $toggleAfter === null ? '' : '&timer=' . rawurlencode((string)$toggleAfter);
|
||||||
|
$runRpcSwitch = static fn(): array => worker_http_get_json(
|
||||||
|
sprintf('http://%s/rpc/Switch.Set?id=%d&on=%s%s', $localIp, $channel, $on ? 'true' : 'false', $timerQuery)
|
||||||
|
);
|
||||||
|
$runLegacySwitch = static fn(): array => worker_http_get_json(
|
||||||
|
sprintf('http://%s/relay/%d?turn=%s%s', $localIp, $channel, $on ? 'on' : 'off', $legacyTimerQuery)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($toggleAfter !== null) {
|
||||||
|
$attempts = worker_resolve_shelly_command_generation($command) === 1
|
||||||
|
? [$runLegacySwitch, $runRpcSwitch]
|
||||||
|
: [$runRpcSwitch, $runLegacySwitch];
|
||||||
|
$lastError = null;
|
||||||
|
foreach ($attempts as $attempt) {
|
||||||
|
try {
|
||||||
|
$attempt();
|
||||||
|
return worker_fetch_shelly_state($localIp, $channel);
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
$lastError = $throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw $lastError ?? new RuntimeException('Unable to switch relay');
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
worker_http_get_json(sprintf('http://%s/rpc/Switch.Set?id=%d&on=%s', $localIp, $channel, $on ? 'true' : 'false'));
|
$runRpcSwitch();
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
worker_http_get_json(sprintf('http://%s/relay/%d?turn=%s', $localIp, $channel, $on ? 'on' : 'off'));
|
$runLegacySwitch();
|
||||||
}
|
}
|
||||||
|
|
||||||
return worker_fetch_shelly_state($localIp, $channel);
|
return worker_fetch_shelly_state($localIp, $channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function worker_normalize_relay_commands(array $body): array
|
||||||
|
{
|
||||||
|
$commands = $body['commands'] ?? [];
|
||||||
|
return is_array($commands) ? array_values($commands) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker_relay_command_result(array $command, callable $handler): array
|
||||||
|
{
|
||||||
|
$target = trim((string)($command['target'] ?? $command['relay'] ?? ''));
|
||||||
|
$relayId = trim((string)($command['relayId'] ?? $command['relay_id'] ?? ''));
|
||||||
|
|
||||||
|
try {
|
||||||
|
$localIp = trim((string)($command['local_ip'] ?? $command['localIp'] ?? ''));
|
||||||
|
$channel = (int)($command['channel'] ?? 0);
|
||||||
|
return [
|
||||||
|
'target' => $target,
|
||||||
|
'relayId' => $relayId,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'ok' => true,
|
||||||
|
'payload' => $handler($localIp, $channel, $command),
|
||||||
|
];
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
return [
|
||||||
|
'target' => $target,
|
||||||
|
'relayId' => $relayId,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'ok' => false,
|
||||||
|
'error' => $throwable->getMessage(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||||
$path = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?? '/');
|
$path = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?? '/');
|
||||||
$body = worker_read_json_body();
|
$body = worker_read_json_body();
|
||||||
@@ -244,7 +402,50 @@ try {
|
|||||||
$localIp = trim((string)($body['local_ip'] ?? $body['localIp'] ?? ''));
|
$localIp = trim((string)($body['local_ip'] ?? $body['localIp'] ?? ''));
|
||||||
$channel = (int)($body['channel'] ?? 0);
|
$channel = (int)($body['channel'] ?? 0);
|
||||||
$on = (bool)($body['on'] ?? false);
|
$on = (bool)($body['on'] ?? false);
|
||||||
worker_json_response(200, worker_switch_shelly_state($localIp, $channel, $on));
|
worker_json_response(200, worker_switch_shelly_state($localIp, $channel, $on, $body));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($method === 'POST' && $path === '/relay/batch-status') {
|
||||||
|
if (!worker_require_authorization()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = array_map(
|
||||||
|
fn(array $command): array => worker_relay_command_result(
|
||||||
|
$command,
|
||||||
|
fn(string $localIp, int $channel): array => worker_fetch_shelly_state($localIp, $channel)
|
||||||
|
),
|
||||||
|
worker_normalize_relay_commands($body)
|
||||||
|
);
|
||||||
|
worker_json_response(200, [
|
||||||
|
'batch_id' => $body['batch_id'] ?? $body['batchId'] ?? null,
|
||||||
|
'results' => $results,
|
||||||
|
]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($method === 'POST' && $path === '/relay/batch-switch') {
|
||||||
|
if (!worker_require_authorization()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = array_map(
|
||||||
|
fn(array $command): array => worker_relay_command_result(
|
||||||
|
$command,
|
||||||
|
fn(string $localIp, int $channel, array $entry): array => worker_switch_shelly_state(
|
||||||
|
$localIp,
|
||||||
|
$channel,
|
||||||
|
(bool)($entry['on'] ?? false),
|
||||||
|
$entry
|
||||||
|
)
|
||||||
|
),
|
||||||
|
worker_normalize_relay_commands($body)
|
||||||
|
);
|
||||||
|
worker_json_response(200, [
|
||||||
|
'batch_id' => $body['batch_id'] ?? $body['batchId'] ?? null,
|
||||||
|
'results' => $results,
|
||||||
|
]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,72 @@ class authRoute
|
|||||||
{
|
{
|
||||||
use route_t;
|
use route_t;
|
||||||
|
|
||||||
|
private function passkeyChallengePrincipalCacheKey(string $challengeToken): string
|
||||||
|
{
|
||||||
|
return 'passkey_challenge_principal:' . $challengeToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function setPasskeyChallengePrincipal(string $challengeToken, string $principalType): void
|
||||||
|
{
|
||||||
|
if (!defined('redis')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
constant('redis')->setEx($this->passkeyChallengePrincipalCacheKey($challengeToken), $principalType, 5 * 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getPasskeyChallengePrincipal(string $challengeToken): string
|
||||||
|
{
|
||||||
|
if (!defined('redis')) {
|
||||||
|
return 'discoverable';
|
||||||
|
}
|
||||||
|
$principalType = constant('redis')->get($this->passkeyChallengePrincipalCacheKey($challengeToken));
|
||||||
|
return is_string($principalType) && in_array($principalType, ['user', 'subuser'], true)
|
||||||
|
? $principalType
|
||||||
|
: 'discoverable';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function clearPasskeyChallengePrincipal(string $challengeToken): void
|
||||||
|
{
|
||||||
|
if (!defined('redis')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
constant('redis')->delete($this->passkeyChallengePrincipalCacheKey($challengeToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function passkeyAllowCredentials(int $userId, bool $isSubuser): array
|
||||||
|
{
|
||||||
|
if ($userId <= 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$passkeys = new passkeys_o();
|
||||||
|
$passkeys->setAdditionalWhereClause(
|
||||||
|
'`user_id` = ' . (int)$userId . ' AND `is_subuser` = ' . ($isSubuser ? '1' : '0')
|
||||||
|
);
|
||||||
|
$list = $passkeys->listObjectsWithPaginationIfSet(function ($o) {
|
||||||
|
$transports = null;
|
||||||
|
if (isset($o['transports'])) {
|
||||||
|
$decoded = json_decode($o['transports'], true);
|
||||||
|
$transports = is_array($decoded) ? $decoded : null;
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
'type' => 'public-key',
|
||||||
|
'id' => $o['credential_id'] ?? null,
|
||||||
|
'transports' => $transports,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isset($list['items']) && is_array($list['items'])) {
|
||||||
|
$list = $list['items'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return is_array($list)
|
||||||
|
? array_values(array_filter($list, function ($item) {
|
||||||
|
return isset($item['id']) && is_string($item['id']) && strlen($item['id']) > 0;
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
public function run(): void
|
public function run(): void
|
||||||
{
|
{
|
||||||
$this->post('/auth/login', function () {
|
$this->post('/auth/login', function () {
|
||||||
@@ -570,7 +636,8 @@ class authRoute
|
|||||||
$reset_link = "https://truckwash.io/auth/password-reset/" . $token;
|
$reset_link = "https://truckwash.io/auth/password-reset/" . $token;
|
||||||
|
|
||||||
$subject = 'Adgangskode nulstilling';
|
$subject = 'Adgangskode nulstilling';
|
||||||
$message = "Du har anmodet om at nulstille din adgangskode. Klik på linket herunder for at fortsætte:<br><br><a href='$reset_link'>$reset_link</a><br><br>Linket er gyldigt i 1 time.";
|
$valid_hours = (int)(customer_password_reset_keys_o::TOKEN_EXPIRY_SECONDS / 3600);
|
||||||
|
$message = "Du har anmodet om at nulstille din adgangskode. Klik på linket herunder for at fortsætte:<br><br><a href='$reset_link'>$reset_link</a><br><br>Linket er gyldigt i $valid_hours timer.";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$email->sendEmail($email_address, $user->display_name->value() ?? 'Kunde', $subject, $message, null);
|
$email->sendEmail($email_address, $user->display_name->value() ?? 'Kunde', $subject, $message, null);
|
||||||
@@ -624,11 +691,53 @@ class authRoute
|
|||||||
global $response;
|
global $response;
|
||||||
$this->requireRecaptcha();
|
$this->requireRecaptcha();
|
||||||
|
|
||||||
|
$principal_type = strtolower(trim((string)(self::getParameter('principal_type') ?? self::getParameter('user_type') ?? '')));
|
||||||
|
if ($principal_type === '') {
|
||||||
|
$principal_type = self::getParameter('customer_number') !== null ? 'user' : 'discoverable';
|
||||||
|
}
|
||||||
|
if (!in_array($principal_type, ['user', 'subuser', 'discoverable'], true)) {
|
||||||
|
$response->error('Invalid principal_type', 400);
|
||||||
|
}
|
||||||
|
|
||||||
$customer_number = self::getParameter('customer_number');
|
$customer_number = self::getParameter('customer_number');
|
||||||
$user_id = 0;
|
$user_id = 0;
|
||||||
$allowCredentials = [];
|
$allowCredentials = [];
|
||||||
|
|
||||||
if ($customer_number !== null) {
|
if ($principal_type === 'subuser') {
|
||||||
|
$subuser = null;
|
||||||
|
if (self::isParametersSet(['subuser_id'])) {
|
||||||
|
$subuser_id = (int)self::getParameter('subuser_id');
|
||||||
|
self::requireType($subuser_id, $this->type_int());
|
||||||
|
self::requireMinValue($subuser_id, 1);
|
||||||
|
$candidate = (new subusers_o())->select($subuser_id);
|
||||||
|
if ($candidate->exists()) {
|
||||||
|
$candidate->getObjectProperties();
|
||||||
|
$subuser = $candidate;
|
||||||
|
}
|
||||||
|
} elseif (self::isParametersSet(['username'])) {
|
||||||
|
$username = (string)self::getParameter('username');
|
||||||
|
self::requireType($username, $this->type_string());
|
||||||
|
self::requireMinLength('username', 3);
|
||||||
|
self::requireMaxLength('username', 255);
|
||||||
|
$subuser = (new subusers_o())->getSubuserByUsername($username);
|
||||||
|
} elseif (self::isParametersSet(['phone_country_code', 'phone'])) {
|
||||||
|
$phone_country_code = (int)self::getParameter('phone_country_code');
|
||||||
|
$phone = (int)self::getParameter('phone');
|
||||||
|
self::requireType($phone_country_code, $this->type_int());
|
||||||
|
self::requireMinLength('phone_country_code', 1);
|
||||||
|
self::requireMaxLength('phone_country_code', 3);
|
||||||
|
self::requireType($phone, $this->type_int());
|
||||||
|
self::requireMinLength('phone', 4);
|
||||||
|
self::requireMaxLength('phone', 15);
|
||||||
|
$subuser = (new subusers_o())->getSubuserByPhone($phone_country_code, $phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($subuser !== null) {
|
||||||
|
$user_id = (int)$subuser->id;
|
||||||
|
$allowCredentials = $this->passkeyAllowCredentials($user_id, true);
|
||||||
|
}
|
||||||
|
} elseif ($customer_number !== null) {
|
||||||
|
$principal_type = 'user';
|
||||||
$customer_number = (int)$customer_number;
|
$customer_number = (int)$customer_number;
|
||||||
self::requireType($customer_number, $this->type_int());
|
self::requireType($customer_number, $this->type_int());
|
||||||
self::requireMinValue($customer_number, 1);
|
self::requireMinValue($customer_number, 1);
|
||||||
@@ -638,33 +747,7 @@ class authRoute
|
|||||||
|
|
||||||
if ($user->exists()) {
|
if ($user->exists()) {
|
||||||
$user_id = (int)$user->id;
|
$user_id = (int)$user->id;
|
||||||
|
$allowCredentials = $this->passkeyAllowCredentials($user_id, false);
|
||||||
// Load passkeys for this user (non-subuser)
|
|
||||||
$passkeys = new passkeys_o();
|
|
||||||
$passkeys->setAdditionalWhereClause('`user_id` = ' . (int)$user_id . ' AND `is_subuser` = 0');
|
|
||||||
$list = $passkeys->listObjectsWithPaginationIfSet(function ($o) {
|
|
||||||
$transports = null;
|
|
||||||
if (isset($o['transports'])) {
|
|
||||||
$decoded = json_decode($o['transports'], true);
|
|
||||||
$transports = is_array($decoded) ? $decoded : null;
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
'type' => 'public-key',
|
|
||||||
'id' => $o['credential_id'] ?? null,
|
|
||||||
'transports' => $transports,
|
|
||||||
];
|
|
||||||
});
|
|
||||||
|
|
||||||
// Ensure we return a simple array of credentials (without pagination wrapper)
|
|
||||||
if (isset($list['items']) && is_array($list['items'])) {
|
|
||||||
$allowCredentials = array_values(array_filter($list['items'], function ($item) {
|
|
||||||
return isset($item['id']) && is_string($item['id']) && strlen($item['id']) > 0;
|
|
||||||
}));
|
|
||||||
} elseif (is_array($list)) {
|
|
||||||
$allowCredentials = array_values(array_filter($list, function ($item) {
|
|
||||||
return isset($item['id']) && is_string($item['id']) && strlen($item['id']) > 0;
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -681,6 +764,10 @@ class authRoute
|
|||||||
|
|
||||||
// Create an ephemeral token to bind the challenge to the (potential) user
|
// Create an ephemeral token to bind the challenge to the (potential) user
|
||||||
(new tokens_o())->create($user_id, $challenge_token, 'PASSKEY_CHALLENGE');
|
(new tokens_o())->create($user_id, $challenge_token, 'PASSKEY_CHALLENGE');
|
||||||
|
$this->setPasskeyChallengePrincipal(
|
||||||
|
$challenge_token,
|
||||||
|
$principal_type === 'subuser' ? 'subuser' : ($principal_type === 'user' ? 'user' : 'discoverable')
|
||||||
|
);
|
||||||
|
|
||||||
$logDetails = $customer_number ? 'Issued passkey challenge for customer ' . $customer_number : 'Issued passkey challenge (discoverable)';
|
$logDetails = $customer_number ? 'Issued passkey challenge for customer ' . $customer_number : 'Issued passkey challenge (discoverable)';
|
||||||
(new logs_o())->add('auth', 'global', 1, $user_id, 'AUTH_PASSKEY_CHALLENGE', $logDetails);
|
(new logs_o())->add('auth', 'global', 1, $user_id, 'AUTH_PASSKEY_CHALLENGE', $logDetails);
|
||||||
@@ -732,6 +819,7 @@ class authRoute
|
|||||||
if ($token_type !== 'PASSKEY_CHALLENGE') {
|
if ($token_type !== 'PASSKEY_CHALLENGE') {
|
||||||
$response->error('Invalid token type', 401);
|
$response->error('Invalid token type', 401);
|
||||||
}
|
}
|
||||||
|
$challengePrincipalType = $this->getPasskeyChallengePrincipal($challenge_token);
|
||||||
|
|
||||||
// Determine rpId/host
|
// Determine rpId/host
|
||||||
$host = parse_url((string)($_SERVER['HTTP_ORIGIN'] ?? ''), PHP_URL_HOST) ?: ($_SERVER['SERVER_NAME'] ?? 'localhost');
|
$host = parse_url((string)($_SERVER['HTTP_ORIGIN'] ?? ''), PHP_URL_HOST) ?: ($_SERVER['SERVER_NAME'] ?? 'localhost');
|
||||||
@@ -767,7 +855,17 @@ class authRoute
|
|||||||
// Success → issue session token accordingly and delete the challenge token
|
// Success → issue session token accordingly and delete the challenge token
|
||||||
$issued_to_user_id = (int)$passkey->user_id->value();
|
$issued_to_user_id = (int)$passkey->user_id->value();
|
||||||
$is_subuser = (bool)$passkey->is_subuser->value();
|
$is_subuser = (bool)$passkey->is_subuser->value();
|
||||||
|
if (
|
||||||
|
($challengePrincipalType === 'subuser' && !$is_subuser)
|
||||||
|
|| ($challengePrincipalType === 'user' && $is_subuser)
|
||||||
|
) {
|
||||||
|
(new logs_o())->add('auth', 'global', 1, $user_id_hint, 'AUTH_PASSKEY_VERIFY_FAILURE', 'Credential principal mismatch');
|
||||||
|
$token_o->delete($challenge_token);
|
||||||
|
$this->clearPasskeyChallengePrincipal($challenge_token);
|
||||||
|
$response->error('Invalid credential', 401);
|
||||||
|
}
|
||||||
$token_o->delete($challenge_token);
|
$token_o->delete($challenge_token);
|
||||||
|
$this->clearPasskeyChallengePrincipal($challenge_token);
|
||||||
|
|
||||||
(new logs_o())->add('auth', 'global', 1, $issued_to_user_id, 'AUTH_PASSKEY_VERIFY_SUCCESS', 'Passkey assertion accepted');
|
(new logs_o())->add('auth', 'global', 1, $issued_to_user_id, 'AUTH_PASSKEY_VERIFY_SUCCESS', 'Passkey assertion accepted');
|
||||||
|
|
||||||
|
|||||||
@@ -812,6 +812,53 @@ class departmentDailyReportsRoute
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
$this->get('/superuser/departments/{id}/overview', function () {
|
||||||
|
global $response;
|
||||||
|
$this->requirePermission('superuser_fetch_department');
|
||||||
|
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
(new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_DEPARTMENT_OVERVIEW', 'No user found, or invalid session');
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$department_id_param = (string)($this->fromRoute('id') ?? '');
|
||||||
|
if (!ctype_digit($department_id_param) || (int)$department_id_param <= 0) {
|
||||||
|
$response->error('Parameter id must be a positive integer', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self::requireParameters([
|
||||||
|
'date',
|
||||||
|
]);
|
||||||
|
|
||||||
|
self::validateDateLocally();
|
||||||
|
$date_to = $this->getDate_to();
|
||||||
|
$department_id = (int)$department_id_param;
|
||||||
|
$department = (new departments_o())->select($department_id);
|
||||||
|
|
||||||
|
if (!$department->exists()) {
|
||||||
|
$response->error('Department not found', 404);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
(new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_DEPARTMENT_OVERVIEW', 'Successfully loaded superuser department overview');
|
||||||
|
|
||||||
|
$response->success([
|
||||||
|
'department' => $department->asArray(['slack_webhook' => false]),
|
||||||
|
'overview' => $this->buildDailyReportOverview(
|
||||||
|
[$department_id],
|
||||||
|
(string)self::getParameter('date'),
|
||||||
|
$date_to
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
[
|
||||||
|
'superuser_fetch_department' => 'Get the superuser department overview'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
$this->get('/departments/daily-reports/overview', function () {
|
$this->get('/departments/daily-reports/overview', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$this->requirePermission('list_department_daily_reports');
|
$this->requirePermission('list_department_daily_reports');
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use classes\authentication;
|
|||||||
use classes\response;
|
use classes\response;
|
||||||
use classes\selfserve;
|
use classes\selfserve;
|
||||||
use modules\selfserve\classes\selfserve_wash_flow;
|
use modules\selfserve\classes\selfserve_wash_flow;
|
||||||
|
use modules\subusers\helpers\subusers_permission_node_key;
|
||||||
use objects\customer_vehicles_o;
|
use objects\customer_vehicles_o;
|
||||||
use objects\department_lanes_o;
|
use objects\department_lanes_o;
|
||||||
use objects\department_selfserve_tasks_o;
|
use objects\department_selfserve_tasks_o;
|
||||||
@@ -118,17 +119,19 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
*/
|
*/
|
||||||
$this->get('/department/selfserve/vehicle/allowed', function () {
|
$this->get('/department/selfserve/vehicle/allowed', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$user = (new authentication())->get_user();
|
[$user, $actor_id] = $this->getAuthenticatedSelfServePrincipal();
|
||||||
if (!$user) {
|
$own_permission = self::definePermission('list_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_LIST);
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$has_global = $user->hasPermission('list_department_selfserve_vehicle_conditions');
|
$has_global = $user !== null && $this->hasPermission('list_department_selfserve_vehicle_conditions');
|
||||||
$has_own = $user->hasPermission('list_own_department_selfserve_vehicle_conditions');
|
$has_own = $this->hasPermission($own_permission);
|
||||||
if (!$has_global && !$has_own) {
|
if (!$has_global && !$has_own) {
|
||||||
$response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
|
$response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($user === null && !$has_own) {
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
self::requireParameters(['lane_id', 'reg']);
|
self::requireParameters(['lane_id', 'reg']);
|
||||||
$lane_id = (int)self::getParameter('lane_id');
|
$lane_id = (int)self::getParameter('lane_id');
|
||||||
$reg = selfserve::standardize_registration((string)self::getParameter('reg'));
|
$reg = selfserve::standardize_registration((string)self::getParameter('reg'));
|
||||||
@@ -147,7 +150,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
(new logs_o())->add('department_selfserve_vehicle_conditions', (int)$lane->department->value(), 1, $user->id, 'CHECK_VEHICLE_ALLOWED', 'User checked self-serve eligibility for lane ' . $lane_id . ' and vehicle ' . $reg);
|
(new logs_o())->add('department_selfserve_vehicle_conditions', (int)$lane->department->value(), 1, $actor_id, 'CHECK_VEHICLE_ALLOWED', 'User checked self-serve eligibility for lane ' . $lane_id . ' and vehicle ' . $reg);
|
||||||
$response->success($flow->previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id));
|
$response->success($flow->previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id));
|
||||||
}, [
|
}, [
|
||||||
'list_department_selfserve_vehicle_conditions' => 'Check whether self-serve is allowed for a specific vehicle',
|
'list_department_selfserve_vehicle_conditions' => 'Check whether self-serve is allowed for a specific vehicle',
|
||||||
@@ -159,17 +162,19 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
*/
|
*/
|
||||||
$this->get('/department/selfserve/washes/summary', function () {
|
$this->get('/department/selfserve/washes/summary', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$user = (new authentication())->get_user();
|
[$user] = $this->getAuthenticatedSelfServePrincipal();
|
||||||
if (!$user) {
|
$own_permission = self::definePermission('list_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_LIST);
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$has_global = $user->hasPermission('list_department_selfserve_vehicle_conditions');
|
$has_global = $user !== null && $this->hasPermission('list_department_selfserve_vehicle_conditions');
|
||||||
$has_own = $user->hasPermission('list_own_department_selfserve_vehicle_conditions');
|
$has_own = $this->hasPermission($own_permission);
|
||||||
if (!$has_global && !$has_own) {
|
if (!$has_global && !$has_own) {
|
||||||
$response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
|
$response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($user === null && !$has_own) {
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
$flow = $this->getWashFlow();
|
$flow = $this->getWashFlow();
|
||||||
$vehicle_type_id = $this->resolveVehicleTypeIdFromQuery();
|
$vehicle_type_id = $this->resolveVehicleTypeIdFromQuery();
|
||||||
try {
|
try {
|
||||||
@@ -236,18 +241,20 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
*/
|
*/
|
||||||
$this->post('/department/selfserve/vehicle/conditions', function () {
|
$this->post('/department/selfserve/vehicle/conditions', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$user = (new authentication())->get_user();
|
[$user, $actor_id] = $this->getAuthenticatedSelfServePrincipal();
|
||||||
if (!$user) {
|
$own_permission = self::definePermission('add_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_ADD);
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$has_global = $user->hasPermission('add_department_selfserve_vehicle_conditions');
|
$has_global = $user !== null && $this->hasPermission('add_department_selfserve_vehicle_conditions');
|
||||||
$has_own = $user->hasPermission('add_own_department_selfserve_vehicle_conditions');
|
$has_own = $this->hasPermission($own_permission);
|
||||||
|
|
||||||
if (!$has_global && !$has_own) {
|
if (!$has_global && !$has_own) {
|
||||||
$response->forbidden(['add_department_selfserve_vehicle_conditions', 'add_own_department_selfserve_vehicle_conditions']);
|
$response->forbidden(['add_department_selfserve_vehicle_conditions', 'add_own_department_selfserve_vehicle_conditions']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($user === null && !$has_own) {
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
$department = (int)$response->getRequestParameter('department');
|
$department = (int)$response->getRequestParameter('department');
|
||||||
$lane = (int)$response->getRequestParameter('lane');
|
$lane = (int)$response->getRequestParameter('lane');
|
||||||
$reg = selfserve::standardize_registration((string)$response->getRequestParameter('reg'));
|
$reg = selfserve::standardize_registration((string)$response->getRequestParameter('reg'));
|
||||||
@@ -275,7 +282,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
$condition_o = new department_selfserve_vehicle_conditions_o();
|
$condition_o = new department_selfserve_vehicle_conditions_o();
|
||||||
$condition_o->add($department, $lane, $reg, $question, $value, $customer_id);
|
$condition_o->add($department, $lane, $reg, $question, $value, $customer_id);
|
||||||
$summary = $this->getWashFlow()->synchronizeSession($lane, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state);
|
$summary = $this->getWashFlow()->synchronizeSession($lane, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state);
|
||||||
(new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $user->id, 'ADD_VEHICLE_CONDITION', 'User added department self-serve vehicle condition ' . $condition_o->id);
|
(new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $actor_id, 'ADD_VEHICLE_CONDITION', 'User added department self-serve vehicle condition ' . $condition_o->id);
|
||||||
$response->success([
|
$response->success([
|
||||||
'condition' => $condition_o->asArray(),
|
'condition' => $condition_o->asArray(),
|
||||||
'selfserve' => $summary,
|
'selfserve' => $summary,
|
||||||
@@ -455,6 +462,24 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
return new selfserve_wash_flow();
|
return new selfserve_wash_flow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function getAuthenticatedSelfServePrincipal(): array
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
$auth = new authentication();
|
||||||
|
$user = $auth->get_user();
|
||||||
|
if ($user !== false) {
|
||||||
|
return [$user, (int)$user->id];
|
||||||
|
}
|
||||||
|
|
||||||
|
$subuser = $auth->get_subuser();
|
||||||
|
if ($subuser !== false) {
|
||||||
|
return [null, (int)$subuser->id];
|
||||||
|
}
|
||||||
|
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
private function resolveVehicleTypeIdFromQuery(): ?int
|
private function resolveVehicleTypeIdFromQuery(): ?int
|
||||||
{
|
{
|
||||||
$rawVehicleType = null;
|
$rawVehicleType = null;
|
||||||
@@ -549,7 +574,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
}
|
}
|
||||||
|
|
||||||
private function assertLaneAccess(
|
private function assertLaneAccess(
|
||||||
object $user,
|
?object $user,
|
||||||
int $laneId,
|
int $laneId,
|
||||||
bool $hasGlobalPermission = true,
|
bool $hasGlobalPermission = true,
|
||||||
bool $hasOwnPermission = false,
|
bool $hasOwnPermission = false,
|
||||||
@@ -563,7 +588,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
$response->error('Department lane not found', 404);
|
$response->error('Department lane not found', 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($hasGlobalPermission && $this->userHasLaneDepartmentAccess($user, $lane)) {
|
if ($hasGlobalPermission && $user !== null && $this->userHasLaneDepartmentAccess($user, $lane)) {
|
||||||
return $lane;
|
return $lane;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -604,16 +629,17 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function summaryBelongsToCustomer(object $user, array $summary): bool
|
private function summaryBelongsToCustomer(?object $user, array $summary): bool
|
||||||
{
|
{
|
||||||
|
$customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
|
||||||
$session_customer_number = $summary['session']['customer_number'] ?? null;
|
$session_customer_number = $summary['session']['customer_number'] ?? null;
|
||||||
if ($session_customer_number !== null && (int)$session_customer_number === (int)$user->customer_number->value()) {
|
if ($session_customer_number !== null && (int)$session_customer_number === $customer_number) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$reg = (string)($summary['session']['reg'] ?? '');
|
$reg = (string)($summary['session']['reg'] ?? '');
|
||||||
$vehicle_o = (new customer_vehicles_o())->selectByPlate($reg);
|
$vehicle_o = (new customer_vehicles_o())->selectByPlate($reg);
|
||||||
return $vehicle_o->exists() && (int)$vehicle_o->customer_id->value() === (int)$user->customer_number->value();
|
return $vehicle_o->exists() && (int)$vehicle_o->customer_id->value() === $customer_number;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function summaryDepartmentId(array $summary): int
|
private function summaryDepartmentId(array $summary): int
|
||||||
@@ -636,11 +662,15 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
return in_array($lane_department, $authorized_department_ids, true);
|
return in_array($lane_department, $authorized_department_ids, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function requireAuthenticatedCustomerNumber(object $user, string $elevatedPermission): int
|
private function requireAuthenticatedCustomerNumber(?object $user, string $elevatedPermission): int
|
||||||
{
|
{
|
||||||
global $response;
|
global $response;
|
||||||
|
|
||||||
$customer_number = (int)$user->customer_number->value();
|
$customer_number = $this->resolveEffectiveCustomerNumber();
|
||||||
|
if ($customer_number === null && $user !== null && isset($user->customer_number)) {
|
||||||
|
$customer_number = (int)$user->customer_number->value();
|
||||||
|
}
|
||||||
|
$customer_number = (int)$customer_number;
|
||||||
if ($customer_number <= 0) {
|
if ($customer_number <= 0) {
|
||||||
$response->forbidden([$elevatedPermission]);
|
$response->forbidden([$elevatedPermission]);
|
||||||
}
|
}
|
||||||
@@ -649,7 +679,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
}
|
}
|
||||||
|
|
||||||
private function assertSummaryAccess(
|
private function assertSummaryAccess(
|
||||||
object $user,
|
?object $user,
|
||||||
array $summary,
|
array $summary,
|
||||||
bool $hasGlobalPermission,
|
bool $hasGlobalPermission,
|
||||||
bool $hasOwnPermission,
|
bool $hasOwnPermission,
|
||||||
@@ -658,7 +688,7 @@ class departmentSelfserveVehicleConditionsRoute
|
|||||||
{
|
{
|
||||||
global $response;
|
global $response;
|
||||||
|
|
||||||
if ($hasGlobalPermission && $this->userHasSummaryDepartmentAccess($user, $summary)) {
|
if ($hasGlobalPermission && $user !== null && $this->userHasSummaryDepartmentAccess($user, $summary)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -526,7 +526,7 @@ class departmentsRoute
|
|||||||
'results' => $departments_o->sendSlackInternalStatisticNotification(
|
'results' => $departments_o->sendSlackInternalStatisticNotification(
|
||||||
$week_monday,
|
$week_monday,
|
||||||
$week_sunday,
|
$week_sunday,
|
||||||
[1, 2, 3, 4, 5, 6, 7],
|
[],
|
||||||
// Default value
|
// Default value
|
||||||
[
|
[
|
||||||
25,
|
25,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace routes;
|
|||||||
|
|
||||||
use classes\authentication;
|
use classes\authentication;
|
||||||
use classes\recaptcha;
|
use classes\recaptcha;
|
||||||
|
use classes\selfserve;
|
||||||
use classes\virkdata;
|
use classes\virkdata;
|
||||||
use objects\department_lanes_o;
|
use objects\department_lanes_o;
|
||||||
use objects\departments_o;
|
use objects\departments_o;
|
||||||
@@ -53,31 +54,57 @@ class guestRoute
|
|||||||
$this->get('/guest/departments', function () {
|
$this->get('/guest/departments', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$departments = (new departments_o());
|
$departments = (new departments_o());
|
||||||
|
try {
|
||||||
|
$self_serve_module_enabled = (bool)(new selfserve())->config->enabled->getVariableValue();
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$self_serve_module_enabled = false;
|
||||||
|
}
|
||||||
// Check if the department lane status is requested to be included
|
// Check if the department lane status is requested to be included
|
||||||
$include_lane_status = false;
|
$include_lane_status = false;
|
||||||
if (self::isParametersSet(['include_lanes']) && self::getParameter('include_lanes')) {
|
if (self::isParametersSet(['include_lanes']) && self::getParameter('include_lanes')) {
|
||||||
$include_lane_status = true;
|
$include_lane_status = true;
|
||||||
}
|
}
|
||||||
$response->success($departments->listObjectsWithPaginationIfSet(function ($department_array) use ($departments, $include_lane_status) {
|
$response->success($departments->listObjectsWithPaginationIfSet(function ($department_array) use ($departments, $include_lane_status, $self_serve_module_enabled) {
|
||||||
$additional_data = [];
|
$additional_data = [];
|
||||||
// If including lane status, fetch it
|
// If including lane status, fetch it
|
||||||
if ($include_lane_status) {
|
if ($include_lane_status) {
|
||||||
$department = $departments->select((int)$department_array['id']);
|
$department = $departments->select((int)$department_array['id']);
|
||||||
// Include the status of self-serve in the department (disabled, when staffed hours)
|
// Include the status of self-serve in the department (disabled, when staffed hours)
|
||||||
$additional_data['self_serve_enabled'] = (bool)$department->getSelfServeEnabled();
|
$department_self_serve_enabled = (bool)$department->getSelfServeEnabled();
|
||||||
|
$additional_data['self_serve_enabled'] = $department_self_serve_enabled;
|
||||||
|
$additional_data['self_serve_module_enabled'] = $self_serve_module_enabled;
|
||||||
$additional_data['lanes'] = array_map(
|
$additional_data['lanes'] = array_map(
|
||||||
/**
|
/**
|
||||||
* @param department_lanes_o $lane
|
* @param department_lanes_o $lane
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
function (department_lanes_o $lane) {
|
function (department_lanes_o $lane) use ($department_self_serve_enabled, $self_serve_module_enabled) {
|
||||||
|
$status = (string)$lane->getLaneStatus()->name;
|
||||||
|
$lane_self_serve_enabled = $lane->isSelfServeEnabled();
|
||||||
|
$self_serve_available = $self_serve_module_enabled
|
||||||
|
&& $department_self_serve_enabled
|
||||||
|
&& $lane_self_serve_enabled
|
||||||
|
&& strtoupper(trim($status)) === 'AVAILABLE';
|
||||||
|
$self_serve_unavailable_reason = null;
|
||||||
|
if (!$self_serve_module_enabled) {
|
||||||
|
$self_serve_unavailable_reason = 'self_serve_module_disabled';
|
||||||
|
} elseif (!$department_self_serve_enabled) {
|
||||||
|
$self_serve_unavailable_reason = 'department_self_serve_disabled';
|
||||||
|
} elseif (!$lane_self_serve_enabled) {
|
||||||
|
$self_serve_unavailable_reason = 'lane_self_serve_disabled';
|
||||||
|
} elseif (strtoupper(trim($status)) !== 'AVAILABLE') {
|
||||||
|
$self_serve_unavailable_reason = 'lane_status_' . strtolower($status);
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => (int)$lane->id,
|
'id' => (int)$lane->id,
|
||||||
'name' => (string)$lane->name->value(),
|
'name' => (string)$lane->name->value(),
|
||||||
'status' => (string)$lane->getLaneStatus()->name,
|
'status' => $status,
|
||||||
'products' => $lane->getSelfServeLaneProducts(),
|
'products' => $lane->getSelfServeLaneProducts(),
|
||||||
'selfserve_enabled' => $lane->isSelfServeEnabled(),
|
'selfserve_enabled' => $lane_self_serve_enabled,
|
||||||
'machine_available' => $lane->isSelfServeEnabled() && !empty($lane->relay_machine_id->value()),
|
'selfserve_available' => $self_serve_available,
|
||||||
|
'selfserve_unavailable_reason' => $self_serve_unavailable_reason,
|
||||||
|
'machine_available' => $self_serve_available && !empty($lane->relay_machine_id->value()),
|
||||||
'dynamic_image_id' => $lane->dynamic_image_id->value() ? (int)$lane->dynamic_image_id->value() : null,
|
'dynamic_image_id' => $lane->dynamic_image_id->value() ? (int)$lane->dynamic_image_id->value() : null,
|
||||||
];
|
];
|
||||||
}, $department->getLanes());
|
}, $department->getLanes());
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace routes;
|
||||||
|
|
||||||
|
use classes\authentication;
|
||||||
|
use classes\limited_backoffice_exception;
|
||||||
|
use classes\limited_backoffice_service;
|
||||||
|
use traits\route_t;
|
||||||
|
|
||||||
|
class limitedBackofficeRoute
|
||||||
|
{
|
||||||
|
use route_t;
|
||||||
|
|
||||||
|
public function run(): void
|
||||||
|
{
|
||||||
|
$this->get('/limited-backoffice/departments', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
return $service->departmentsForUser($user);
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->get('/limited-backoffice/departments/{departmentId}/prices', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$departmentId = $this->routePositiveInt('departmentId');
|
||||||
|
return $service->getDepartmentPrices($user, $departmentId);
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->put('/limited-backoffice/departments/{departmentId}/prices', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_PRICES);
|
||||||
|
$departmentId = $this->routePositiveInt('departmentId');
|
||||||
|
return $service->updateDepartmentPrices($user, $departmentId, $this->requestPayload());
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_PRICES => 'Manage limited backoffice department prices',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->get('/limited-backoffice/roles', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES);
|
||||||
|
return $service->rolePresets();
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES => 'Manage limited backoffice employees',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->get('/limited-backoffice/employees', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES);
|
||||||
|
$includeInactive = strtolower((string)($this->fromQuery('include_inactive') ?? 'false')) === 'true';
|
||||||
|
return $service->employeesForUser($user, $includeInactive);
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES => 'Manage limited backoffice employees',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->post('/limited-backoffice/employees', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES);
|
||||||
|
return $service->createEmployee($user, $this->requestPayload());
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES => 'Manage limited backoffice employees',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->put('/limited-backoffice/employees/{employeeId}', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES);
|
||||||
|
return $service->updateEmployee($user, $this->routePositiveInt('employeeId'), $this->requestPayload());
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES => 'Manage limited backoffice employees',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->delete('/limited-backoffice/employees/{employeeId}', function () {
|
||||||
|
$this->withLimitedBackoffice(function (limited_backoffice_service $service, $user): array {
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_ACCESS);
|
||||||
|
$this->requirePermission(limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES);
|
||||||
|
return $service->deactivateEmployee($user, $this->routePositiveInt('employeeId'));
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS => 'Access the limited backoffice',
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES => 'Manage limited backoffice employees',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function withLimitedBackoffice(callable $callback): void
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$response->success($callback(new limited_backoffice_service(), $user));
|
||||||
|
} catch (limited_backoffice_exception $exception) {
|
||||||
|
$response->error($exception->payload(), $exception->statusCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function requestPayload(): array
|
||||||
|
{
|
||||||
|
$payload = json_decode(file_get_contents('php://input'), true);
|
||||||
|
return is_array($payload) ? $payload : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function routePositiveInt(string $name): int
|
||||||
|
{
|
||||||
|
$value = $this->fromRoute($name);
|
||||||
|
if (!is_string($value) || !ctype_digit($value) || (int)$value <= 0) {
|
||||||
|
throw new limited_backoffice_exception('Invalid route parameter.', 400);
|
||||||
|
}
|
||||||
|
return (int)$value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -250,6 +250,89 @@ class moduleConfigRoute
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** Slack internal department goal progress config > TEST */
|
||||||
|
$this->post('/slack/config/internal-department-goal-progress/test', function () {
|
||||||
|
global $response;
|
||||||
|
$this->requirePermission('slack_config');
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, 0, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG_TEST', 'No user found, or invalid session');
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = (new slack())->test_internal_department_goal_progress_webhook();
|
||||||
|
if (($result['configured'] ?? false) !== true) {
|
||||||
|
(new logs_o())->add('slack_config', 'global', 0, $user->id, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG_TEST', 'Slack internal department goal progress webhook URL is not configured');
|
||||||
|
$response->error($result['message'] ?? 'Slack internal department goal progress webhook URL is not configured.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($result['sent'] ?? false) !== true) {
|
||||||
|
(new logs_o())->add('slack_config', 'global', 0, $user->id, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG_TEST', 'Slack internal department goal progress test webhook failed');
|
||||||
|
$response->error($result['message'] ?? 'Slack test message failed.', 502);
|
||||||
|
}
|
||||||
|
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, $user->id, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG_TEST', 'Successfully tested Slack internal department goal progress webhook');
|
||||||
|
$response->success($result);
|
||||||
|
},
|
||||||
|
[
|
||||||
|
'slack_config' => 'Test Slack internal department goal progress config'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Slack internal department goal progress config > GET */
|
||||||
|
$this->get('/slack/config/internal-department-goal-progress', function () {
|
||||||
|
global $response;
|
||||||
|
$this->requirePermission('slack_config');
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, 0, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG', 'No user found, or invalid session');
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, $user->id, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG', 'Successfully fetched Slack internal department goal progress config');
|
||||||
|
$response->success(
|
||||||
|
(new slack())->get_internal_department_goal_progress_config()
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[
|
||||||
|
'slack_config' => 'Get Slack internal department goal progress config'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Slack internal department goal progress config > POST */
|
||||||
|
$this->post('/slack/config/internal-department-goal-progress', function () {
|
||||||
|
global $response;
|
||||||
|
$this->requirePermission('slack_config');
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, 0, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG', 'No user found, or invalid session');
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$webhook_url = $response->getRequestParameter('internal_department_goal_progress_webhook_url')
|
||||||
|
?? $response->getRequestParameter('webhook_url')
|
||||||
|
?? '';
|
||||||
|
$department_ids = $response->getRequestParameter('internal_department_ids')
|
||||||
|
?? $response->getRequestParameter('department_ids')
|
||||||
|
?? [];
|
||||||
|
|
||||||
|
if (!is_array($department_ids)) {
|
||||||
|
$department_ids = array_filter(array_map('trim', explode(',', (string)$department_ids)));
|
||||||
|
}
|
||||||
|
|
||||||
|
(new logs_o())->add('slack_config', 'global', 1, $user->id, 'SLACK_INTERNAL_DEPARTMENT_GOAL_PROGRESS_CONFIG', 'Successfully updated Slack internal department goal progress config');
|
||||||
|
$response->success(
|
||||||
|
(new slack())->set_internal_department_goal_progress_config(
|
||||||
|
(string)$webhook_url,
|
||||||
|
$department_ids
|
||||||
|
)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[
|
||||||
|
'slack_config' => 'Update Slack internal department goal progress config'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
$this->get('/backups/config', function () {
|
$this->get('/backups/config', function () {
|
||||||
global $response;
|
global $response;
|
||||||
$this->requirePermission('backups_config');
|
$this->requirePermission('backups_config');
|
||||||
|
|||||||
@@ -2,21 +2,35 @@
|
|||||||
|
|
||||||
namespace routes;
|
namespace routes;
|
||||||
|
|
||||||
use classes\authentication;
|
|
||||||
use classes\image_processor;
|
|
||||||
use classes\licenseplaterecognizer;
|
use classes\licenseplaterecognizer;
|
||||||
use classes\openai;
|
|
||||||
use classes\response;
|
use classes\response;
|
||||||
use classes\router;
|
|
||||||
use classes\upload_store;
|
|
||||||
use Exception;
|
|
||||||
use objects\logs_o;
|
|
||||||
use traits\route_t;
|
use traits\route_t;
|
||||||
|
|
||||||
class moduleScannerRoute
|
class moduleScannerRoute
|
||||||
{
|
{
|
||||||
use route_t;
|
use route_t;
|
||||||
|
|
||||||
|
private const LPR_IMAGE_UPLOAD_FIELD = 'image';
|
||||||
|
private const LPR_IMAGE_UPLOAD_MAX_BYTES = 4194304;
|
||||||
|
private const LPR_CLIENT_CAPTURE_MS_FIELD = 'client_capture_ms';
|
||||||
|
private const LPR_CLIENT_CAPTURE_MAX_MS = 10000;
|
||||||
|
private const LPR_CLIENT_DRAW_MS_FIELD = 'client_draw_ms';
|
||||||
|
private const LPR_CLIENT_ENCODE_MS_FIELD = 'client_encode_ms';
|
||||||
|
private const LPR_CLIENT_FRAME_WIDTH_FIELD = 'client_frame_width';
|
||||||
|
private const LPR_CLIENT_FRAME_HEIGHT_FIELD = 'client_frame_height';
|
||||||
|
private const LPR_CLIENT_FRAME_BYTES_FIELD = 'client_frame_bytes';
|
||||||
|
private const LPR_CLIENT_FRAME_MAX_DIMENSION = 4096;
|
||||||
|
private const LPR_CLIENT_PREFLIGHT_MS_FIELD = 'client_preflight_ms';
|
||||||
|
private const LPR_CLIENT_VISUAL_FINGERPRINT_MS_FIELD = 'client_visual_fingerprint_ms';
|
||||||
|
private const LPR_CLIENT_CAPTURE_MS_HEADER = 'HTTP_X_LPR_CLIENT_CAPTURE_MS';
|
||||||
|
private const LPR_CLIENT_DRAW_MS_HEADER = 'HTTP_X_LPR_CLIENT_DRAW_MS';
|
||||||
|
private const LPR_CLIENT_ENCODE_MS_HEADER = 'HTTP_X_LPR_CLIENT_ENCODE_MS';
|
||||||
|
private const LPR_CLIENT_FRAME_WIDTH_HEADER = 'HTTP_X_LPR_CLIENT_FRAME_WIDTH';
|
||||||
|
private const LPR_CLIENT_FRAME_HEIGHT_HEADER = 'HTTP_X_LPR_CLIENT_FRAME_HEIGHT';
|
||||||
|
private const LPR_CLIENT_FRAME_BYTES_HEADER = 'HTTP_X_LPR_CLIENT_FRAME_BYTES';
|
||||||
|
private const LPR_CLIENT_PREFLIGHT_MS_HEADER = 'HTTP_X_LPR_CLIENT_PREFLIGHT_MS';
|
||||||
|
private const LPR_CLIENT_VISUAL_FINGERPRINT_MS_HEADER = 'HTTP_X_LPR_CLIENT_VISUAL_FINGERPRINT_MS';
|
||||||
|
|
||||||
public function run(): void
|
public function run(): void
|
||||||
{
|
{
|
||||||
global /** @var response $response */
|
global /** @var response $response */
|
||||||
@@ -24,27 +38,43 @@ class moduleScannerRoute
|
|||||||
/** Modules > Scanner > License Plate Recognition > POST */
|
/** Modules > Scanner > License Plate Recognition > POST */
|
||||||
$this->post('/modules/scanner/lpr', function () {
|
$this->post('/modules/scanner/lpr', function () {
|
||||||
global $response;
|
global $response;
|
||||||
self::requireParameters(['base64_image']);
|
$route_started_at = microtime(true);
|
||||||
$base64_image = self::getParameter('base64_image');
|
$image_upload = self::getLPRImageUpload();
|
||||||
|
$raw_image_upload = $image_upload === null ? self::getLPRRawImageUpload() : null;
|
||||||
|
$client_timings = self::getLPRClientTimings();
|
||||||
|
$base64_image = null;
|
||||||
//self::requirePermission('modules_scanner_lpr');
|
//self::requirePermission('modules_scanner_lpr');
|
||||||
if (empty($base64_image)) {
|
if ($image_upload === null && $raw_image_upload === null) {
|
||||||
$response->error('Base64 image is required.');}
|
$base64_image = self::getParameter('base64_image');
|
||||||
$uploads = new upload_store();
|
if (!is_string($base64_image) || trim($base64_image) === '') {
|
||||||
$object_name = $uploads->storeTempImageFromBase64(
|
$response->error('Image is required.');
|
||||||
$base64_image
|
}
|
||||||
);
|
}
|
||||||
//echo $object_name;
|
$recognizer = new licenseplaterecognizer(false);
|
||||||
//echo "License Plate Recognition result:\n";
|
try {
|
||||||
// Uncomment the line below to use the actual license plate recognizer.
|
if ($image_upload !== null) {
|
||||||
$lpr_result = (new licenseplaterecognizer())->licenseplaterecognizer($base64_image);
|
$lpr_result = $recognizer->licenseplaterecognizerUploadFile($image_upload['path'], $image_upload['mime_type']);
|
||||||
|
} elseif ($raw_image_upload !== null) {
|
||||||
|
$lpr_result = $recognizer->licenseplaterecognizerUploadUncached($raw_image_upload['data'], $raw_image_upload['mime_type']);
|
||||||
|
} else {
|
||||||
|
$lpr_result = $recognizer->licenseplaterecognizer((string)$base64_image);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
self::sendLPRServerTiming(array_merge($client_timings, $recognizer->getLastTimings()), $route_started_at);
|
||||||
|
}
|
||||||
if ($lpr_result['success']) {
|
if ($lpr_result['success']) {
|
||||||
// Set the LICENSE_PLATE_NUMBER to uppercase and remove spaces.
|
// Set the LICENSE_PLATE_NUMBER to uppercase and remove spaces.
|
||||||
$lpr_result['license_plate_number'] = strtoupper(str_replace(' ', '', $lpr_result['license_plate_number']));
|
$lpr_result['license_plate_number'] = strtoupper(str_replace(' ', '', $lpr_result['license_plate_number']));
|
||||||
// Make sure the scanned plate is more than 3 characters long.
|
// Make sure the scanned plate is more than 3 characters long.
|
||||||
$scannedPlateIsTooShort = strlen($lpr_result['license_plate_number']) <= 3;
|
$scannedPlateIsTooShort = strlen($lpr_result['license_plate_number']) <= 3;
|
||||||
// If the confidence is below 90%, consider it a failure.
|
// If the confidence is below 90%, treat it as a recoverable scanner miss.
|
||||||
if (isset($lpr_result['confidence']) && $lpr_result['confidence'] < 0.9 && !$scannedPlateIsTooShort) {
|
if (isset($lpr_result['confidence']) && $lpr_result['confidence'] < 0.9 && !$scannedPlateIsTooShort) {
|
||||||
throw new Exception('License plate recognition confidence too low. Score: ' . $lpr_result['confidence'] . ' Plate: ' . $lpr_result['license_plate_number'] . ' Raw: ' . json_encode($lpr_result['raw_response']));
|
$response->response(false, [
|
||||||
|
'message' => 'License plate recognition confidence too low.',
|
||||||
|
'reason' => 'low_confidence_license_plate',
|
||||||
|
'confidence' => $lpr_result['confidence'],
|
||||||
|
'license_plate_number' => $lpr_result['license_plate_number'],
|
||||||
|
], 200);
|
||||||
}
|
}
|
||||||
// Success
|
// Success
|
||||||
$response->success(['success' => true, 'license_plate_number' => $lpr_result['license_plate_number']]);
|
$response->success(['success' => true, 'license_plate_number' => $lpr_result['license_plate_number']]);
|
||||||
@@ -54,25 +84,296 @@ class moduleScannerRoute
|
|||||||
'reason' => 'no_license_plate_detected',
|
'reason' => 'no_license_plate_detected',
|
||||||
], 200);
|
], 200);
|
||||||
}
|
}
|
||||||
exit;
|
|
||||||
// For future use with OpenAI.
|
|
||||||
$openai = new openai();
|
|
||||||
$registration_numbers_debug = [
|
|
||||||
'EC21233',
|
|
||||||
'EC21234',
|
|
||||||
'EC21235',
|
|
||||||
];
|
|
||||||
$random_index = rand(0, count($registration_numbers_debug) - 1);
|
|
||||||
$object_name = $registration_numbers_debug[$random_index];
|
|
||||||
// Attempt to recognize the license plate number from the image.
|
|
||||||
|
|
||||||
//Debug: TODO: Remove this.
|
|
||||||
$response->success(['success' => true, 'license_plate_number' => $object_name]);
|
|
||||||
$response->success($openai->lpr($object_name));
|
|
||||||
},
|
},
|
||||||
[
|
[
|
||||||
'modules_scanner_lpr' => 'License Plate Recognition',
|
'modules_scanner_lpr' => 'License Plate Recognition',
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static function getLPRImageUpload(): ?array
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
if (!isset($_FILES[self::LPR_IMAGE_UPLOAD_FIELD]) || !is_array($_FILES[self::LPR_IMAGE_UPLOAD_FIELD])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$file = $_FILES[self::LPR_IMAGE_UPLOAD_FIELD];
|
||||||
|
if (is_array($file['error'] ?? null)) {
|
||||||
|
$response->error('Only one image can be uploaded.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$upload_error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
|
||||||
|
if ($upload_error === UPLOAD_ERR_NO_FILE) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($upload_error !== UPLOAD_ERR_OK) {
|
||||||
|
$response->error('Image upload failed.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$size = (int)($file['size'] ?? 0);
|
||||||
|
if ($size <= 0) {
|
||||||
|
$response->error('Image upload is empty.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($size > self::LPR_IMAGE_UPLOAD_MAX_BYTES) {
|
||||||
|
$response->error('Image upload is too large.', 413);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tmp_name = (string)($file['tmp_name'] ?? '');
|
||||||
|
if ($tmp_name === '' || !is_uploaded_file($tmp_name)) {
|
||||||
|
$response->error('Image upload is invalid.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_readable($tmp_name)) {
|
||||||
|
$response->error('Image upload could not be read.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$mime_type = self::detectLPRImageMimeType($file, $tmp_name);
|
||||||
|
if (!str_starts_with($mime_type, 'image/')) {
|
||||||
|
$response->error('Image upload must be an image.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'path' => $tmp_name,
|
||||||
|
'mime_type' => $mime_type,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getLPRRawImageUpload(): ?array
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
$mime_type = self::getRequestContentType();
|
||||||
|
if (!str_starts_with($mime_type, 'image/')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$content_length = isset($_SERVER['CONTENT_LENGTH']) && is_numeric($_SERVER['CONTENT_LENGTH'])
|
||||||
|
? (int)$_SERVER['CONTENT_LENGTH']
|
||||||
|
: null;
|
||||||
|
if ($content_length !== null && $content_length > self::LPR_IMAGE_UPLOAD_MAX_BYTES) {
|
||||||
|
$response->error('Image upload is too large.', 413);
|
||||||
|
}
|
||||||
|
|
||||||
|
$image_data = file_get_contents('php://input');
|
||||||
|
if (!is_string($image_data) || $image_data === '') {
|
||||||
|
$response->error('Image upload is empty.', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strlen($image_data) > self::LPR_IMAGE_UPLOAD_MAX_BYTES) {
|
||||||
|
$response->error('Image upload is too large.', 413);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'data' => $image_data,
|
||||||
|
'mime_type' => $mime_type,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getRequestContentType(): string
|
||||||
|
{
|
||||||
|
$content_type = (string)($_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '');
|
||||||
|
$content_type = strtolower(trim(explode(';', $content_type, 2)[0] ?? ''));
|
||||||
|
|
||||||
|
return $content_type;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function detectLPRImageMimeType(array $file, string $tmp_name): string
|
||||||
|
{
|
||||||
|
$mime_type = trim((string)($file['type'] ?? ''));
|
||||||
|
if ($mime_type !== '') {
|
||||||
|
return $mime_type;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (class_exists(\finfo::class)) {
|
||||||
|
$finfo = new \finfo(FILEINFO_MIME_TYPE);
|
||||||
|
$detected = $finfo->file($tmp_name);
|
||||||
|
if (is_string($detected) && $detected !== '') {
|
||||||
|
return $detected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'image/jpeg';
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getLPRClientTimings(): array
|
||||||
|
{
|
||||||
|
$timings = [];
|
||||||
|
$client_capture_ms = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_CAPTURE_MS_FIELD,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MS_HEADER,
|
||||||
|
0,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MAX_MS
|
||||||
|
);
|
||||||
|
if ($client_capture_ms !== null) {
|
||||||
|
$timings['client_capture'] = $client_capture_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_preflight_ms = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_PREFLIGHT_MS_FIELD,
|
||||||
|
self::LPR_CLIENT_PREFLIGHT_MS_HEADER,
|
||||||
|
0,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MAX_MS
|
||||||
|
);
|
||||||
|
if ($client_preflight_ms !== null) {
|
||||||
|
$timings['client_preflight'] = $client_preflight_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_draw_ms = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_DRAW_MS_FIELD,
|
||||||
|
self::LPR_CLIENT_DRAW_MS_HEADER,
|
||||||
|
0,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MAX_MS
|
||||||
|
);
|
||||||
|
if ($client_draw_ms !== null) {
|
||||||
|
$timings['client_draw'] = $client_draw_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_encode_ms = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_ENCODE_MS_FIELD,
|
||||||
|
self::LPR_CLIENT_ENCODE_MS_HEADER,
|
||||||
|
0,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MAX_MS
|
||||||
|
);
|
||||||
|
if ($client_encode_ms !== null) {
|
||||||
|
$timings['client_encode'] = $client_encode_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_visual_fingerprint_ms = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_VISUAL_FINGERPRINT_MS_FIELD,
|
||||||
|
self::LPR_CLIENT_VISUAL_FINGERPRINT_MS_HEADER,
|
||||||
|
0,
|
||||||
|
self::LPR_CLIENT_CAPTURE_MAX_MS
|
||||||
|
);
|
||||||
|
if ($client_visual_fingerprint_ms !== null) {
|
||||||
|
$timings['client_visual_fingerprint'] = $client_visual_fingerprint_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_frame_width = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_FRAME_WIDTH_FIELD,
|
||||||
|
self::LPR_CLIENT_FRAME_WIDTH_HEADER,
|
||||||
|
1,
|
||||||
|
self::LPR_CLIENT_FRAME_MAX_DIMENSION
|
||||||
|
);
|
||||||
|
if ($client_frame_width !== null) {
|
||||||
|
$timings['client_frame_width'] = $client_frame_width;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_frame_height = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_FRAME_HEIGHT_FIELD,
|
||||||
|
self::LPR_CLIENT_FRAME_HEIGHT_HEADER,
|
||||||
|
1,
|
||||||
|
self::LPR_CLIENT_FRAME_MAX_DIMENSION
|
||||||
|
);
|
||||||
|
if ($client_frame_height !== null) {
|
||||||
|
$timings['client_frame_height'] = $client_frame_height;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client_frame_bytes = self::getNumericClientField(
|
||||||
|
self::LPR_CLIENT_FRAME_BYTES_FIELD,
|
||||||
|
self::LPR_CLIENT_FRAME_BYTES_HEADER,
|
||||||
|
1,
|
||||||
|
self::LPR_IMAGE_UPLOAD_MAX_BYTES
|
||||||
|
);
|
||||||
|
if ($client_frame_bytes !== null) {
|
||||||
|
$timings['client_frame_bytes'] = $client_frame_bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $timings;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getNumericClientField(string $field, string $server_header, float $min, float $max): ?float
|
||||||
|
{
|
||||||
|
$value = $_GET[$field] ?? null;
|
||||||
|
if ($value === null) {
|
||||||
|
$value = $_POST[$field] ?? null;
|
||||||
|
}
|
||||||
|
if ($value === null) {
|
||||||
|
$value = $_SERVER[$server_header] ?? null;
|
||||||
|
}
|
||||||
|
if (is_array($value) || !is_numeric($value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = (float)$value;
|
||||||
|
if ($value < $min || $value > $max) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function sendLPRServerTiming(array $timings, float $route_started_at): void
|
||||||
|
{
|
||||||
|
if (headers_sent()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts = [];
|
||||||
|
$timings['route_total'] = max(0, (microtime(true) - $route_started_at) * 1000);
|
||||||
|
$timings['local'] = self::getLPRLocalDuration($timings);
|
||||||
|
if (isset($_SERVER['REQUEST_TIME_FLOAT']) && is_numeric($_SERVER['REQUEST_TIME_FLOAT'])) {
|
||||||
|
$timings['request_total'] = max(0, (microtime(true) - (float)$_SERVER['REQUEST_TIME_FLOAT']) * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
'client_capture',
|
||||||
|
'client_preflight',
|
||||||
|
'client_visual_fingerprint',
|
||||||
|
'client_draw',
|
||||||
|
'client_encode',
|
||||||
|
'client_frame_width',
|
||||||
|
'client_frame_height',
|
||||||
|
'client_frame_bytes',
|
||||||
|
'config',
|
||||||
|
'cache',
|
||||||
|
'cache_hit',
|
||||||
|
'cache_miss',
|
||||||
|
'local',
|
||||||
|
'payload',
|
||||||
|
'upstream_dns',
|
||||||
|
'upstream_connect',
|
||||||
|
'upstream_tls',
|
||||||
|
'upstream_pretransfer',
|
||||||
|
'upstream_ttfb',
|
||||||
|
'upstream_total',
|
||||||
|
'upstream_processing',
|
||||||
|
'upstream',
|
||||||
|
'parse',
|
||||||
|
'total',
|
||||||
|
] as $name) {
|
||||||
|
if (!isset($timings[$name]) || !is_numeric($timings[$name])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts[] = sprintf('lpr_%s;dur=%.3F', $name, (float)$timings[$name]);
|
||||||
|
}
|
||||||
|
foreach (['route_total', 'request_total'] as $name) {
|
||||||
|
if (!isset($timings[$name]) || !is_numeric($timings[$name])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts[] = sprintf('lpr_%s;dur=%.3F', $name, (float)$timings[$name]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($parts !== []) {
|
||||||
|
header('Server-Timing: ' . implode(', ', $parts));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function getLPRLocalDuration(array $timings): float
|
||||||
|
{
|
||||||
|
$upstream = null;
|
||||||
|
foreach (['upstream', 'upstream_total'] as $name) {
|
||||||
|
if (isset($timings[$name]) && is_numeric($timings[$name])) {
|
||||||
|
$upstream = max(0, (float)$timings[$name]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return max(0, (float)$timings['route_total'] - ($upstream ?? 0));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace routes;
|
namespace routes;
|
||||||
|
|
||||||
use classes\authentication;
|
use classes\authentication;
|
||||||
|
use classes\edge_gateway_manager;
|
||||||
use classes\email;
|
use classes\email;
|
||||||
use classes\response;
|
use classes\response;
|
||||||
use classes\router;
|
use classes\router;
|
||||||
@@ -14,11 +15,14 @@ use modules\selfserve\classes\selfserve_wash_flow;
|
|||||||
use modules\selfserve\helpers\selfserve_lane_command;
|
use modules\selfserve\helpers\selfserve_lane_command;
|
||||||
use modules\selfserve\helpers\selfserve_lane_port;
|
use modules\selfserve\helpers\selfserve_lane_port;
|
||||||
use modules\selfserve\helpers\selfserve_lane_relay;
|
use modules\selfserve\helpers\selfserve_lane_relay;
|
||||||
|
use modules\selfserve\helpers\selfserve_lane_services;
|
||||||
use modules\selfserve\helpers\selfserve_lane_state;
|
use modules\selfserve\helpers\selfserve_lane_state;
|
||||||
use modules\selfserve\helpers\selfserve_lane_status;
|
use modules\selfserve\helpers\selfserve_lane_status;
|
||||||
use modules\selfserve\helpers\selfserve_wash_session_status;
|
use modules\selfserve\helpers\selfserve_wash_session_status;
|
||||||
|
use modules\subusers\helpers\subusers_permission_node_key;
|
||||||
use objects\department_lanes_o;
|
use objects\department_lanes_o;
|
||||||
use objects\departments_o;
|
use objects\departments_o;
|
||||||
|
use objects\edge_gateway_relay_bindings_o;
|
||||||
use objects\logs_o;
|
use objects\logs_o;
|
||||||
use objects\orders_o;
|
use objects\orders_o;
|
||||||
use objects\customer_vehicles_o;
|
use objects\customer_vehicles_o;
|
||||||
@@ -715,6 +719,12 @@ class moduleSelfServeRoute
|
|||||||
// Merge services (if any)
|
// Merge services (if any)
|
||||||
$merge_services((array)$t->services->value());
|
$merge_services((array)$t->services->value());
|
||||||
}
|
}
|
||||||
|
if (!$this->isMachineWashEnabled()) {
|
||||||
|
$allowed_services = array_values(array_filter(
|
||||||
|
$allowed_services,
|
||||||
|
static fn(string $service): bool => $service !== selfserve_lane_services::MACHINE->name
|
||||||
|
));
|
||||||
|
}
|
||||||
// Persist on lane cache (overwrites previous allowed services)
|
// Persist on lane cache (overwrites previous allowed services)
|
||||||
try {
|
try {
|
||||||
$relay_sync = $lane->setAllowedServicesFromVisibleTasks($allowed_services);
|
$relay_sync = $lane->setAllowedServicesFromVisibleTasks($allowed_services);
|
||||||
@@ -755,15 +765,23 @@ class moduleSelfServeRoute
|
|||||||
$lane = $selfserve->lane($lane_id);
|
$lane = $selfserve->lane($lane_id);
|
||||||
try {
|
try {
|
||||||
$this->applyShellyTransportOverride($lane);
|
$this->applyShellyTransportOverride($lane);
|
||||||
$lane->open($gate, $toggle_after);
|
$queued_gate_command = null;
|
||||||
|
if ($this->requestedShellyTransportOverride() === 'local') {
|
||||||
|
$queued_gate_command = $this->queueLocalLaneGateOpen($lane, $gate, $toggle_after);
|
||||||
|
} else {
|
||||||
|
$lane->open($gate, $toggle_after);
|
||||||
|
}
|
||||||
|
|
||||||
$response->success([
|
$response->success([
|
||||||
'lane_id' => $lane_id,
|
'lane_id' => $lane_id,
|
||||||
'gate' => $gate->name,
|
'gate' => $gate->name,
|
||||||
'opened' => true,
|
'opened' => true,
|
||||||
|
'queued' => $queued_gate_command !== null,
|
||||||
|
'batch' => $queued_gate_command,
|
||||||
'toggle_after' => $toggle_after,
|
'toggle_after' => $toggle_after,
|
||||||
'state' => $lane->getLaneState()->name,
|
'state' => $lane->getLaneState()->name,
|
||||||
'transport' => $this->requestedShellyTransportOverride(),
|
'transport' => $this->requestedShellyTransportOverride(),
|
||||||
]);
|
], $queued_gate_command !== null ? 202 : 200);
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
error_log('Failed to open self-serve lane gate ' . $gate->name . ' for lane ' . $lane_id . ': ' . $e->getMessage());
|
error_log('Failed to open self-serve lane gate ' . $gate->name . ' for lane ' . $lane_id . ': ' . $e->getMessage());
|
||||||
$response->error('Failed to open ' . strtolower($gate->name) . ' gate.', 400);
|
$response->error('Failed to open ' . strtolower($gate->name) . ' gate.', 400);
|
||||||
@@ -772,6 +790,83 @@ class moduleSelfServeRoute
|
|||||||
'modules_selfserve_lane_gate_open' => 'Open ENTRANCE or EXIT gate for a self-serve lane'
|
'modules_selfserve_lane_gate_open' => 'Open ENTRANCE or EXIT gate for a self-serve lane'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
/** Modules > Self Serve > Lane > Hardware > Batch status */
|
||||||
|
$this->post('/modules/self-serve/lane/hardware/batch/status', function () {
|
||||||
|
global $response;
|
||||||
|
$selfserve = new selfserve();
|
||||||
|
self::requireParameters(['lane_id']);
|
||||||
|
$lane_id = (int)$this->getParameter('lane_id');
|
||||||
|
self::requireType($lane_id, self::type_int());
|
||||||
|
self::requireMinValue($lane_id, 1);
|
||||||
|
|
||||||
|
$lane = $selfserve->lane($lane_id);
|
||||||
|
try {
|
||||||
|
$this->applyShellyTransportOverride($lane);
|
||||||
|
$targets = self::isParametersSet(['targets']) ? (array)$this->getParameter('targets') : [
|
||||||
|
'MACHINE',
|
||||||
|
'PROGRAM_PICKER',
|
||||||
|
'CLEANER',
|
||||||
|
'ENTRANCE',
|
||||||
|
'EXIT',
|
||||||
|
];
|
||||||
|
$requests = $this->buildLaneHardwareBatchRequests($lane, $targets, false);
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
$result = (new edge_gateway_manager())->queueRelayStatusBatch(
|
||||||
|
$this->departmentIdForLane($lane),
|
||||||
|
$requests,
|
||||||
|
$user instanceof users_o ? (int)$user->id : null,
|
||||||
|
$this->requestedShellyTransportOverride() === 'local'
|
||||||
|
);
|
||||||
|
$response->success($result, 202);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$response->error('Failed to queue lane hardware status batch: ' . $e->getMessage(), 400);
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
'modules_selfserve_lane_relay_machine_status_view' => 'Queue self-serve lane hardware status batch'
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** Modules > Self Serve > Lane > Hardware > Batch set/open */
|
||||||
|
$this->post('/modules/self-serve/lane/hardware/batch/set', function () {
|
||||||
|
global $response;
|
||||||
|
$selfserve = new selfserve();
|
||||||
|
self::requireParameters(['lane_id', 'commands']);
|
||||||
|
$lane_id = (int)$this->getParameter('lane_id');
|
||||||
|
self::requireType($lane_id, self::type_int());
|
||||||
|
self::requireMinValue($lane_id, 1);
|
||||||
|
|
||||||
|
$commands = (array)$this->getParameter('commands');
|
||||||
|
$lane = $selfserve->lane($lane_id);
|
||||||
|
try {
|
||||||
|
$this->applyShellyTransportOverride($lane);
|
||||||
|
$requests = $this->buildLaneHardwareBatchRequests($lane, $commands, true);
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
$result = (new edge_gateway_manager())->queueRelaySwitchBatch(
|
||||||
|
$this->departmentIdForLane($lane),
|
||||||
|
$requests,
|
||||||
|
$user instanceof users_o ? (int)$user->id : null,
|
||||||
|
$this->requestedShellyTransportOverride() === 'local'
|
||||||
|
);
|
||||||
|
$response->success($result, 202);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$response->error('Failed to queue lane hardware command batch: ' . $e->getMessage(), 400);
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
'modules_selfserve_lane_relay_machine_status_set' => 'Queue self-serve lane hardware command batch'
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** Modules > Self Serve > Lane > Hardware > Batch poll */
|
||||||
|
$this->get('/modules/self-serve/lane/hardware/batch/{batch_id}', function () {
|
||||||
|
global $response;
|
||||||
|
self::requirePermission('modules_selfserve_lane_relay_machine_status_view');
|
||||||
|
try {
|
||||||
|
$response->success((new edge_gateway_manager())->relayBatchStatus((string)$this->fromRoute('batch_id')));
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$response->error('Failed to get lane hardware batch status: ' . $e->getMessage(), 400);
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
'modules_selfserve_lane_relay_machine_status_view' => 'Poll self-serve lane hardware batch'
|
||||||
|
]);
|
||||||
|
|
||||||
/** Modules > Self Serve > Lane > Relay > MACHINE_PROGRAM_PICKER status */
|
/** Modules > Self Serve > Lane > Relay > MACHINE_PROGRAM_PICKER status */
|
||||||
$this->get('/modules/self-serve/lane/relay/machine_program_picker/status', function () {
|
$this->get('/modules/self-serve/lane/relay/machine_program_picker/status', function () {
|
||||||
global $response;
|
global $response;
|
||||||
@@ -1330,8 +1425,7 @@ class moduleSelfServeRoute
|
|||||||
{
|
{
|
||||||
global $response;
|
global $response;
|
||||||
|
|
||||||
$user = (new authentication())->get_user();
|
if (!$this->hasAuthenticatedUserOrSubuser()) {
|
||||||
if (!$user) {
|
|
||||||
$response->error('Authentication failed. Invalid or missing token.', 401);
|
$response->error('Authentication failed. Invalid or missing token.', 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1344,7 +1438,7 @@ class moduleSelfServeRoute
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self::hasPermission('list_own_department_selfserve_vehicle_conditions')) {
|
if (self::hasPermission($this->customerSelfServePermission())) {
|
||||||
$customer_number = $this->resolveEffectiveCustomerNumber();
|
$customer_number = $this->resolveEffectiveCustomerNumber();
|
||||||
if ($customer_number !== null && $customer_number > 0) {
|
if ($customer_number !== null && $customer_number > 0) {
|
||||||
return (int)$customer_number;
|
return (int)$customer_number;
|
||||||
@@ -1353,7 +1447,7 @@ class moduleSelfServeRoute
|
|||||||
|
|
||||||
$this->emitForbidden([
|
$this->emitForbidden([
|
||||||
'modules_selfserve_lane_wash_in_progress_view',
|
'modules_selfserve_lane_wash_in_progress_view',
|
||||||
'list_own_department_selfserve_vehicle_conditions',
|
$this->customerSelfServePermission(),
|
||||||
]);
|
]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -1412,13 +1506,12 @@ class moduleSelfServeRoute
|
|||||||
{
|
{
|
||||||
global $response;
|
global $response;
|
||||||
|
|
||||||
$user = (new authentication())->get_user();
|
if (!$this->hasAuthenticatedUserOrSubuser()) {
|
||||||
if (!$user) {
|
|
||||||
$response->error('Authentication failed. Invalid or missing token.', 401);
|
$response->error('Authentication failed. Invalid or missing token.', 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!self::hasPermission(self::CUSTOMER_SELFSERVE_PERMISSION)) {
|
if (!self::hasPermission($this->customerSelfServePermission())) {
|
||||||
$this->emitForbidden([self::CUSTOMER_SELFSERVE_PERMISSION]);
|
$this->emitForbidden([$this->customerSelfServePermission()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$customer_number = $this->resolveEffectiveCustomerNumber();
|
$customer_number = $this->resolveEffectiveCustomerNumber();
|
||||||
@@ -1429,6 +1522,17 @@ class moduleSelfServeRoute
|
|||||||
return (int)$customer_number;
|
return (int)$customer_number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function customerSelfServePermission(): \classes\permission_node
|
||||||
|
{
|
||||||
|
return self::definePermission(self::CUSTOMER_SELFSERVE_PERMISSION, subusers_permission_node_key::SELFSERVE_LIST);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasAuthenticatedUserOrSubuser(): bool
|
||||||
|
{
|
||||||
|
$auth = new authentication();
|
||||||
|
return $auth->get_user() !== false || $auth->get_subuser() !== false;
|
||||||
|
}
|
||||||
|
|
||||||
private function findLatestActiveSelfServeSessionForCustomer(int $customer_number): selfserve_wash_sessions_o
|
private function findLatestActiveSelfServeSessionForCustomer(int $customer_number): selfserve_wash_sessions_o
|
||||||
{
|
{
|
||||||
if ($customer_number <= 0) {
|
if ($customer_number <= 0) {
|
||||||
@@ -1624,6 +1728,305 @@ class moduleSelfServeRoute
|
|||||||
return $payload;
|
return $payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string,mixed>
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
private function queueLocalLaneGateOpen(selfserve_lane $lane, selfserve_lane_port $gate, int $toggleAfter): array
|
||||||
|
{
|
||||||
|
$requests = $this->buildLaneHardwareBatchRequests($lane, [[
|
||||||
|
'target' => $gate->name,
|
||||||
|
'action' => 'OPEN',
|
||||||
|
'toggle_after' => $toggleAfter,
|
||||||
|
]], true);
|
||||||
|
$user = (new authentication())->get_user();
|
||||||
|
|
||||||
|
return (new edge_gateway_manager())->queueRelaySwitchBatch(
|
||||||
|
$this->departmentIdForLane($lane),
|
||||||
|
$requests,
|
||||||
|
$user instanceof users_o ? (int)$user->id : null,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int,mixed> $items
|
||||||
|
* @return array<int,array<string,mixed>>
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
private function buildLaneHardwareBatchRequests(selfserve_lane $lane, array $items, bool $mutation): array
|
||||||
|
{
|
||||||
|
if (empty($lane->department_lane)) {
|
||||||
|
throw new \Exception("Department lane object not found for lane ID {$lane->id}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$requests = [];
|
||||||
|
$seen = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$command = is_array($item) ? $item : ['target' => $item];
|
||||||
|
$target = strtoupper(trim((string)($command['target'] ?? $command['relay'] ?? '')));
|
||||||
|
if ($target === '') {
|
||||||
|
throw new \Exception('Lane hardware batch commands require a target');
|
||||||
|
}
|
||||||
|
if (isset($seen[$target])) {
|
||||||
|
throw new \Exception('Duplicate lane hardware target: ' . $target);
|
||||||
|
}
|
||||||
|
$seen[$target] = true;
|
||||||
|
|
||||||
|
$relayId = $this->relayIdForLaneHardwareTarget($lane, $target);
|
||||||
|
if ($relayId === '') {
|
||||||
|
throw new \Exception('No relay is configured for lane hardware target ' . $target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($mutation) {
|
||||||
|
$this->requireLaneHardwareMutationPermission($target);
|
||||||
|
} else {
|
||||||
|
$this->requireLaneHardwareStatusPermission($target);
|
||||||
|
}
|
||||||
|
|
||||||
|
$request = [
|
||||||
|
'target' => $target,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'relayId' => $relayId,
|
||||||
|
'lane_id' => (int)$lane->id,
|
||||||
|
'laneId' => (int)$lane->id,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($mutation) {
|
||||||
|
if (in_array($target, ['ENTRANCE', 'EXIT'], true)) {
|
||||||
|
$action = strtoupper(trim((string)($command['action'] ?? 'OPEN')));
|
||||||
|
if ($action !== 'OPEN') {
|
||||||
|
throw new \Exception($target . ' only supports action=OPEN');
|
||||||
|
}
|
||||||
|
$request['on'] = true;
|
||||||
|
$request['toggle_after'] = $this->normalizeBatchToggleAfter(
|
||||||
|
$command['toggle_after'] ?? $command['toggleAfter'] ?? $command['timer'] ?? 1,
|
||||||
|
self::MAX_GATE_OPEN_TOGGLE_AFTER_SECONDS
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
if (!array_key_exists('on', $command)) {
|
||||||
|
throw new \Exception($target . ' relay commands require an on boolean');
|
||||||
|
}
|
||||||
|
$on = is_bool($command['on'])
|
||||||
|
? $command['on']
|
||||||
|
: filter_var($command['on'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||||
|
if ($on === null) {
|
||||||
|
throw new \Exception('Invalid on value for ' . $target . '. Expected boolean true/false.');
|
||||||
|
}
|
||||||
|
$request['on'] = (bool)$on;
|
||||||
|
if (isset($command['toggle_after']) || isset($command['toggleAfter']) || isset($command['timer'])) {
|
||||||
|
$request['toggle_after'] = $this->normalizeBatchToggleAfter(
|
||||||
|
$command['toggle_after'] ?? $command['toggleAfter'] ?? $command['timer'],
|
||||||
|
86400
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$requests[] = $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($requests === []) {
|
||||||
|
throw new \Exception('At least one lane hardware target is required');
|
||||||
|
}
|
||||||
|
if (count($requests) > 5) {
|
||||||
|
throw new \Exception('Lane hardware batches are limited to five targets');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $requests;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function relayIdForLaneHardwareTarget(selfserve_lane $lane, string $target): string
|
||||||
|
{
|
||||||
|
$relayId = trim((string)match ($target) {
|
||||||
|
'MACHINE' => $lane->department_lane->relay_machine_id->value(),
|
||||||
|
'PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER' => $lane->department_lane->relay_machine_program_picker_id->value(),
|
||||||
|
'CLEANER', 'MACHINE_CLEANER' => $lane->department_lane->relay_machine_cleaner_id->value(),
|
||||||
|
'ENTRANCE' => $lane->department_lane->relay_in_id->value(),
|
||||||
|
'EXIT' => $lane->department_lane->relay_out_id->value(),
|
||||||
|
default => throw new \Exception('Unsupported lane hardware target: ' . $target),
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($relayId !== '') {
|
||||||
|
return $relayId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->edgeGatewayRelayIdForLaneHardwareTarget($lane, $target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function edgeGatewayRelayIdForLaneHardwareTarget(selfserve_lane $lane, string $target): string
|
||||||
|
{
|
||||||
|
$departmentId = $this->departmentIdForLane($lane);
|
||||||
|
if ($departmentId <= 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = (new edge_gateway_relay_bindings_o())->getFieldsWhere([
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'deleted_at' => null,
|
||||||
|
], ['id']);
|
||||||
|
|
||||||
|
$laneScoped = [];
|
||||||
|
$unscoped = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$binding = (new edge_gateway_relay_bindings_o())->select((int)$row['id']);
|
||||||
|
if (!$binding->exists()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = $binding->asArray();
|
||||||
|
if (!$this->edgeGatewayBindingMatchesHardwareTarget($payload, $target)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->edgeGatewayBindingMatchesLane($payload, (int)$lane->id, $target)) {
|
||||||
|
$laneScoped[] = (string)$payload['relay_id'];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->edgeGatewayBindingHasConsumers($payload)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$unscoped[] = (string)$payload['relay_id'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$candidates = $laneScoped !== [] ? array_values(array_unique($laneScoped)) : array_values(array_unique($unscoped));
|
||||||
|
if (count($candidates) === 1) {
|
||||||
|
return $candidates[0];
|
||||||
|
}
|
||||||
|
if (count($candidates) > 1) {
|
||||||
|
throw new \Exception('Multiple edge gateway relay bindings match lane hardware target ' . $target);
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $binding
|
||||||
|
*/
|
||||||
|
private function edgeGatewayBindingMatchesHardwareTarget(array $binding, string $target): bool
|
||||||
|
{
|
||||||
|
$accepted = match ($target) {
|
||||||
|
'MACHINE' => ['MACHINE'],
|
||||||
|
'PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER' => ['PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER'],
|
||||||
|
'CLEANER', 'MACHINE_CLEANER' => ['CLEANER', 'MACHINE_CLEANER'],
|
||||||
|
'ENTRANCE' => ['ENTRANCE', 'ENTRY'],
|
||||||
|
'EXIT' => ['EXIT'],
|
||||||
|
default => [],
|
||||||
|
};
|
||||||
|
if ($accepted === []) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$metadata = isset($binding['metadata']) && is_array($binding['metadata']) ? (array)$binding['metadata'] : [];
|
||||||
|
$values = [
|
||||||
|
$binding['role'] ?? null,
|
||||||
|
$binding['service'] ?? null,
|
||||||
|
$binding['slot'] ?? null,
|
||||||
|
$metadata['role'] ?? null,
|
||||||
|
$metadata['relay_role'] ?? null,
|
||||||
|
$metadata['service'] ?? null,
|
||||||
|
$metadata['slot'] ?? null,
|
||||||
|
];
|
||||||
|
foreach ((array)($binding['services'] ?? $metadata['services'] ?? []) as $service) {
|
||||||
|
$values[] = $service;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($values as $value) {
|
||||||
|
if (in_array($this->normalizeLaneHardwareTargetRole($value), $accepted, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $binding
|
||||||
|
*/
|
||||||
|
private function edgeGatewayBindingMatchesLane(array $binding, int $laneId, string $target): bool
|
||||||
|
{
|
||||||
|
$targetRoles = match ($target) {
|
||||||
|
'MACHINE' => ['MACHINE'],
|
||||||
|
'PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER' => ['PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER'],
|
||||||
|
'CLEANER', 'MACHINE_CLEANER' => ['CLEANER', 'MACHINE_CLEANER'],
|
||||||
|
'ENTRANCE' => ['ENTRANCE', 'ENTRY'],
|
||||||
|
'EXIT' => ['EXIT'],
|
||||||
|
default => [],
|
||||||
|
};
|
||||||
|
$metadata = isset($binding['metadata']) && is_array($binding['metadata']) ? (array)$binding['metadata'] : [];
|
||||||
|
$consumers = $binding['consumer_contexts'] ?? $binding['consumers'] ?? $metadata['consumer_contexts'] ?? $metadata['consumers'] ?? [];
|
||||||
|
if (!is_array($consumers)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($consumers as $consumer) {
|
||||||
|
if (!is_array($consumer)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (strtolower(trim((string)($consumer['type'] ?? ''))) !== 'lane') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((int)($consumer['id'] ?? 0) !== $laneId) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$slot = $this->normalizeLaneHardwareTargetRole($consumer['slot'] ?? '');
|
||||||
|
if ($slot === '' || in_array($slot, $targetRoles, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $binding
|
||||||
|
*/
|
||||||
|
private function edgeGatewayBindingHasConsumers(array $binding): bool
|
||||||
|
{
|
||||||
|
$metadata = isset($binding['metadata']) && is_array($binding['metadata']) ? (array)$binding['metadata'] : [];
|
||||||
|
$consumers = $binding['consumer_contexts'] ?? $binding['consumers'] ?? $metadata['consumer_contexts'] ?? $metadata['consumers'] ?? [];
|
||||||
|
return is_array($consumers) && $consumers !== [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizeLaneHardwareTargetRole(mixed $value): string
|
||||||
|
{
|
||||||
|
return strtoupper(str_replace(['-', ' '], '_', trim((string)($value ?? ''))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function requireLaneHardwareStatusPermission(string $target): void
|
||||||
|
{
|
||||||
|
match ($target) {
|
||||||
|
'MACHINE' => self::requirePermission('modules_selfserve_lane_relay_machine_status_view'),
|
||||||
|
'PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER' => self::requirePermission('modules_selfserve_lane_relay_machine_program_picker_status_view'),
|
||||||
|
'CLEANER', 'MACHINE_CLEANER' => self::requirePermission('modules_selfserve_lane_relay_machine_cleaner_status_view'),
|
||||||
|
'ENTRANCE', 'EXIT' => self::requirePermission('modules_selfserve_lane_gate_open'),
|
||||||
|
default => throw new \Exception('Unsupported lane hardware target: ' . $target),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function requireLaneHardwareMutationPermission(string $target): void
|
||||||
|
{
|
||||||
|
match ($target) {
|
||||||
|
'MACHINE' => self::requirePermission('modules_selfserve_lane_relay_machine_status_set'),
|
||||||
|
'PROGRAM_PICKER', 'MACHINE_PROGRAM_PICKER' => self::requirePermission('modules_selfserve_lane_relay_machine_program_picker_status_set'),
|
||||||
|
'CLEANER', 'MACHINE_CLEANER' => self::requirePermission('modules_selfserve_lane_relay_machine_cleaner_status_set'),
|
||||||
|
'ENTRANCE', 'EXIT' => self::requirePermission('modules_selfserve_lane_gate_open'),
|
||||||
|
default => throw new \Exception('Unsupported lane hardware target: ' . $target),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizeBatchToggleAfter(mixed $value, int $max): int
|
||||||
|
{
|
||||||
|
$seconds = (int)$value;
|
||||||
|
if ($seconds <= 0) {
|
||||||
|
throw new \Exception('toggle_after must be greater than zero');
|
||||||
|
}
|
||||||
|
|
||||||
|
return min($seconds, $max);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws \Exception
|
* @throws \Exception
|
||||||
*/
|
*/
|
||||||
@@ -1685,7 +2088,7 @@ class moduleSelfServeRoute
|
|||||||
|
|
||||||
$missing_permissions = $department_id > 0 ? ['department_access_' . $department_id] : [];
|
$missing_permissions = $department_id > 0 ? ['department_access_' . $department_id] : [];
|
||||||
if ($allow_customer_self_serve) {
|
if ($allow_customer_self_serve) {
|
||||||
$missing_permissions[] = self::CUSTOMER_SELFSERVE_PERMISSION;
|
$missing_permissions[] = $this->customerSelfServePermission();
|
||||||
}
|
}
|
||||||
$this->emitForbidden($missing_permissions);
|
$this->emitForbidden($missing_permissions);
|
||||||
}
|
}
|
||||||
@@ -1729,7 +2132,7 @@ class moduleSelfServeRoute
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->emitForbidden([...$elevated_permissions, self::CUSTOMER_SELFSERVE_PERMISSION]);
|
$this->emitForbidden([...$elevated_permissions, $this->customerSelfServePermission()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function requireSelfServeLaneCommandPermission(
|
private function requireSelfServeLaneCommandPermission(
|
||||||
@@ -1760,7 +2163,7 @@ class moduleSelfServeRoute
|
|||||||
|
|
||||||
$this->emitForbidden(
|
$this->emitForbidden(
|
||||||
$allow_customer_self_serve
|
$allow_customer_self_serve
|
||||||
? [...$elevated_permissions, self::CUSTOMER_SELFSERVE_PERMISSION]
|
? [...$elevated_permissions, $this->customerSelfServePermission()]
|
||||||
: $elevated_permissions
|
: $elevated_permissions
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1791,28 +2194,37 @@ class moduleSelfServeRoute
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->emitForbidden([...$elevated_permissions, self::CUSTOMER_SELFSERVE_PERMISSION]);
|
$this->emitForbidden([...$elevated_permissions, $this->customerSelfServePermission()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function isSelfServeModuleEnabled(): bool
|
protected function isSelfServeModuleEnabled(): bool
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return (bool)(new selfserve())->config->enabled->getVariableValue();
|
return (new selfserve())->config->enabled->isTrue();
|
||||||
} catch (\Throwable) {
|
} catch (\Throwable) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function isMachineWashEnabled(): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return (new selfserve())->config->machine_wash_enabled->isTrue();
|
||||||
|
} catch (\Throwable) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected function canCustomerUseSelfServeLane(selfserve_lane $lane, int $customer_number): bool
|
protected function canCustomerUseSelfServeLane(selfserve_lane $lane, int $customer_number): bool
|
||||||
{
|
{
|
||||||
return $customer_number > 0
|
return $customer_number > 0
|
||||||
&& $this->hasPermission(self::CUSTOMER_SELFSERVE_PERMISSION)
|
&& $this->hasPermission($this->customerSelfServePermission())
|
||||||
&& $this->isLaneSelfServeOperationallyEnabled($lane);
|
&& $this->isLaneSelfServeOperationallyEnabled($lane);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function canCustomerUseActiveSelfServeLane(selfserve_lane $lane, int $customer_number): bool
|
protected function canCustomerUseActiveSelfServeLane(selfserve_lane $lane, int $customer_number): bool
|
||||||
{
|
{
|
||||||
if ($customer_number <= 0 || !$this->hasPermission(self::CUSTOMER_SELFSERVE_PERMISSION)) {
|
if ($customer_number <= 0 || !$this->hasPermission($this->customerSelfServePermission())) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1859,7 +2271,7 @@ class moduleSelfServeRoute
|
|||||||
|
|
||||||
protected function canCustomerUseActiveSelfServeLaneSession(selfserve_lane $lane, int $customer_number): bool
|
protected function canCustomerUseActiveSelfServeLaneSession(selfserve_lane $lane, int $customer_number): bool
|
||||||
{
|
{
|
||||||
if ($customer_number <= 0 || !$this->hasPermission(self::CUSTOMER_SELFSERVE_PERMISSION)) {
|
if ($customer_number <= 0 || !$this->hasPermission($this->customerSelfServePermission())) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,21 +11,48 @@ class passkeysRoute
|
|||||||
{
|
{
|
||||||
use route_t;
|
use route_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{principal:object,user_id:int,is_subuser:bool}
|
||||||
|
*/
|
||||||
|
private function resolvePasskeyPrincipal(string $classicUserPermission): array
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
$auth = new authentication();
|
||||||
|
$subuser = $auth->get_subuser();
|
||||||
|
if ($subuser !== false) {
|
||||||
|
return [
|
||||||
|
'principal' => $subuser,
|
||||||
|
'user_id' => (int)$subuser->id,
|
||||||
|
'is_subuser' => true,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
self::requirePermission($classicUserPermission);
|
||||||
|
$user = $auth->get_user();
|
||||||
|
if (!$user) {
|
||||||
|
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_AUTH', 'User not logged in');
|
||||||
|
$response->error('Invalid session', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'principal' => $user,
|
||||||
|
'user_id' => (int)$user->id,
|
||||||
|
'is_subuser' => false,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function run(): void
|
public function run(): void
|
||||||
{
|
{
|
||||||
// List passkeys for current authenticated user
|
// List passkeys for current authenticated user
|
||||||
$this->get('/account/security/passkeys', function () {
|
$this->get('/account/security/passkeys', function () {
|
||||||
global $response;
|
global $response;
|
||||||
self::requirePermission('user_security_passkeys_list');
|
$principal = $this->resolvePasskeyPrincipal('user_security_passkeys_list');
|
||||||
$user = (new authentication())->get_user();
|
|
||||||
if (!$user) {
|
|
||||||
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_LIST', 'User not logged in');
|
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$passkeys = new passkeys_o();
|
$passkeys = new passkeys_o();
|
||||||
// Restrict to current user (customer) and non-subuser records
|
$passkeys->setAdditionalWhereClause(
|
||||||
$passkeys->setAdditionalWhereClause('`user_id` = ' . (int)$user->id . ' AND `is_subuser` = 0');
|
'`user_id` = ' . (int)$principal['user_id'] . ' AND `is_subuser` = ' . ($principal['is_subuser'] ? '1' : '0')
|
||||||
|
);
|
||||||
$list = $passkeys->listObjectsWithPaginationIfSet(function ($o) {
|
$list = $passkeys->listObjectsWithPaginationIfSet(function ($o) {
|
||||||
// $o is an associative array from the database
|
// $o is an associative array from the database
|
||||||
$transports = null;
|
$transports = null;
|
||||||
@@ -45,7 +72,7 @@ class passkeysRoute
|
|||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
(new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_LIST', 'Listed passkeys');
|
(new logs_o())->add('user_security', 'global', 1, $principal['user_id'], 'USER_SECURITY_PASSKEYS_LIST', 'Listed passkeys');
|
||||||
$response->success($list);
|
$response->success($list);
|
||||||
}, [
|
}, [
|
||||||
'user_security_passkeys_list' => 'List passkeys for the authenticated user',
|
'user_security_passkeys_list' => 'List passkeys for the authenticated user',
|
||||||
@@ -54,12 +81,7 @@ class passkeysRoute
|
|||||||
// Create/add a passkey (store after client-side WebAuthn attestation)
|
// Create/add a passkey (store after client-side WebAuthn attestation)
|
||||||
$this->post('/account/security/passkeys', function () {
|
$this->post('/account/security/passkeys', function () {
|
||||||
global $response;
|
global $response;
|
||||||
self::requirePermission('user_security_passkeys_create');
|
$principal = $this->resolvePasskeyPrincipal('user_security_passkeys_create');
|
||||||
$user = (new authentication())->get_user();
|
|
||||||
if (!$user) {
|
|
||||||
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_CREATE', 'User not logged in');
|
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
self::requireParameters(['credential_id', 'public_key', 'algorithm', 'transports']);
|
self::requireParameters(['credential_id', 'public_key', 'algorithm', 'transports']);
|
||||||
|
|
||||||
@@ -100,9 +122,9 @@ class passkeysRoute
|
|||||||
}
|
}
|
||||||
|
|
||||||
$obj = new passkeys_o();
|
$obj = new passkeys_o();
|
||||||
$obj->add((int)$user->id, false, $credential_id, $public_key, $algorithm, (array)$transports, $name);
|
$obj->add((int)$principal['user_id'], (bool)$principal['is_subuser'], $credential_id, $public_key, $algorithm, (array)$transports, $name);
|
||||||
|
|
||||||
(new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_CREATE', 'Created passkey: ' . $obj->id);
|
(new logs_o())->add('user_security', 'global', 1, $principal['user_id'], 'USER_SECURITY_PASSKEYS_CREATE', 'Created passkey: ' . $obj->id);
|
||||||
$response->success(['id' => $obj->id]);
|
$response->success(['id' => $obj->id]);
|
||||||
}, [
|
}, [
|
||||||
'user_security_passkeys_create' => 'Create/add a new passkey for the authenticated user',
|
'user_security_passkeys_create' => 'Create/add a new passkey for the authenticated user',
|
||||||
@@ -111,12 +133,7 @@ class passkeysRoute
|
|||||||
// Rename a passkey
|
// Rename a passkey
|
||||||
$this->patch('/account/security/passkeys/{id}', function () {
|
$this->patch('/account/security/passkeys/{id}', function () {
|
||||||
global $response;
|
global $response;
|
||||||
self::requirePermission('user_security_passkeys_rename');
|
$principal = $this->resolvePasskeyPrincipal('user_security_passkeys_rename');
|
||||||
$user = (new authentication())->get_user();
|
|
||||||
if (!$user) {
|
|
||||||
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_RENAME', 'User not logged in');
|
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$id = (int)self::fromRoute('id');
|
$id = (int)self::fromRoute('id');
|
||||||
self::requireParameterIntPositive($id, 'id');
|
self::requireParameterIntPositive($id, 'id');
|
||||||
@@ -127,13 +144,17 @@ class passkeysRoute
|
|||||||
self::requireMaxLength('name', 255);
|
self::requireMaxLength('name', 255);
|
||||||
|
|
||||||
$obj = (new passkeys_o())->select($id);
|
$obj = (new passkeys_o())->select($id);
|
||||||
if (!$obj->exists() || (int)$obj->user_id->value() !== (int)$user->id || (int)$obj->is_subuser->value() !== 0) {
|
if (
|
||||||
(new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_PASSKEYS_RENAME', 'Passkey not found or not owned');
|
!$obj->exists()
|
||||||
|
|| (int)$obj->user_id->value() !== (int)$principal['user_id']
|
||||||
|
|| (bool)$obj->is_subuser->value() !== (bool)$principal['is_subuser']
|
||||||
|
) {
|
||||||
|
(new logs_o())->add('user_security', 'global', 0, $principal['user_id'], 'USER_SECURITY_PASSKEYS_RENAME', 'Passkey not found or not owned');
|
||||||
$response->error('Not found', 404);
|
$response->error('Not found', 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
$obj->update(['name' => $name]);
|
$obj->update(['name' => $name]);
|
||||||
(new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_RENAME', 'Renamed passkey ' . $id);
|
(new logs_o())->add('user_security', 'global', 1, $principal['user_id'], 'USER_SECURITY_PASSKEYS_RENAME', 'Renamed passkey ' . $id);
|
||||||
$response->success(['message' => 'Renamed', 'id' => $id]);
|
$response->success(['message' => 'Renamed', 'id' => $id]);
|
||||||
}, [
|
}, [
|
||||||
'user_security_passkeys_rename' => 'Rename a passkey that belongs to the authenticated user',
|
'user_security_passkeys_rename' => 'Rename a passkey that belongs to the authenticated user',
|
||||||
@@ -142,24 +163,23 @@ class passkeysRoute
|
|||||||
// Delete a passkey (soft delete)
|
// Delete a passkey (soft delete)
|
||||||
$this->delete('/account/security/passkeys/{id}', function () {
|
$this->delete('/account/security/passkeys/{id}', function () {
|
||||||
global $response;
|
global $response;
|
||||||
self::requirePermission('user_security_passkeys_delete');
|
$principal = $this->resolvePasskeyPrincipal('user_security_passkeys_delete');
|
||||||
$user = (new authentication())->get_user();
|
|
||||||
if (!$user) {
|
|
||||||
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_DELETE', 'User not logged in');
|
|
||||||
$response->error('Invalid session', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$id = (int)self::fromRoute('id');
|
$id = (int)self::fromRoute('id');
|
||||||
self::requireParameterIntPositive($id, 'id');
|
self::requireParameterIntPositive($id, 'id');
|
||||||
|
|
||||||
$obj = (new passkeys_o())->select($id);
|
$obj = (new passkeys_o())->select($id);
|
||||||
if (!$obj->exists() || (int)$obj->user_id->value() !== (int)$user->id || (int)$obj->is_subuser->value() !== 0) {
|
if (
|
||||||
(new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_PASSKEYS_DELETE', 'Passkey not found or not owned');
|
!$obj->exists()
|
||||||
|
|| (int)$obj->user_id->value() !== (int)$principal['user_id']
|
||||||
|
|| (bool)$obj->is_subuser->value() !== (bool)$principal['is_subuser']
|
||||||
|
) {
|
||||||
|
(new logs_o())->add('user_security', 'global', 0, $principal['user_id'], 'USER_SECURITY_PASSKEYS_DELETE', 'Passkey not found or not owned');
|
||||||
$response->error('Not found', 404);
|
$response->error('Not found', 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
$obj->delete();
|
$obj->delete();
|
||||||
(new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_DELETE', 'Deleted passkey ' . $id);
|
(new logs_o())->add('user_security', 'global', 1, $principal['user_id'], 'USER_SECURITY_PASSKEYS_DELETE', 'Deleted passkey ' . $id);
|
||||||
$response->success(['message' => 'Deleted', 'id' => $id]);
|
$response->success(['message' => 'Deleted', 'id' => $id]);
|
||||||
}, [
|
}, [
|
||||||
'user_security_passkeys_delete' => 'Delete a passkey that belongs to the authenticated user',
|
'user_security_passkeys_delete' => 'Delete a passkey that belongs to the authenticated user',
|
||||||
|
|||||||
@@ -231,7 +231,57 @@ class subusersRoute
|
|||||||
|
|
||||||
private function buildSetupLink(string $token): string
|
private function buildSetupLink(string $token): string
|
||||||
{
|
{
|
||||||
return 'https://truckwash.io/complete-registration?token=' . $token;
|
$frontendBaseUrl = trim((string)(
|
||||||
|
getenv('FRONTEND_URL')
|
||||||
|
?: getenv('APP_URL')
|
||||||
|
?: ($_SERVER['FRONTEND_URL'] ?? '')
|
||||||
|
?: ($_SERVER['APP_URL'] ?? '')
|
||||||
|
?: 'https://truckwash.io'
|
||||||
|
));
|
||||||
|
$frontendBaseUrl = rtrim($frontendBaseUrl !== '' ? $frontendBaseUrl : 'https://truckwash.io', '/');
|
||||||
|
return $frontendBaseUrl . '/complete-registration?token=' . rawurlencode($token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function clientThrottleIp(): string
|
||||||
|
{
|
||||||
|
$remoteAddress = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));
|
||||||
|
return $remoteAddress !== '' ? $remoteAddress : 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recordThrottleAttempt(string $scope, string $identifier, int $limit, int $windowSeconds): ?string
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
|
||||||
|
if (!defined('redis')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$safeScope = preg_replace('/[^a-z0-9:_-]/i', '_', $scope);
|
||||||
|
$key = 'subusers_route_throttle:' . $safeScope . ':' . hash(
|
||||||
|
'sha256',
|
||||||
|
$this->clientThrottleIp() . ':' . $identifier
|
||||||
|
);
|
||||||
|
$redis = constant('redis');
|
||||||
|
$attempts = (int)($redis->get($key) ?? '0');
|
||||||
|
if ($attempts >= $limit) {
|
||||||
|
$response->error('Too many attempts. Please wait and try again.', 429);
|
||||||
|
}
|
||||||
|
$redis->setEx($key, (string)($attempts + 1), $windowSeconds);
|
||||||
|
return $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function clearThrottleAttempt(?string $key): void
|
||||||
|
{
|
||||||
|
if ($key === null || !defined('redis')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
constant('redis')->delete($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function subuserAuthFailure(): void
|
||||||
|
{
|
||||||
|
global $response;
|
||||||
|
$response->error('Invalid credentials', 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function issueSetupInvite(subusers_o $subuser): array
|
private function issueSetupInvite(subusers_o $subuser): array
|
||||||
@@ -272,7 +322,7 @@ class subusersRoute
|
|||||||
$delivery = [
|
$delivery = [
|
||||||
'channel' => 'sms',
|
'channel' => 'sms',
|
||||||
'status' => 'failed',
|
'status' => 'failed',
|
||||||
'message' => $exception->getMessage(),
|
'message' => 'Invite delivery failed.',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,7 +380,7 @@ class subusersRoute
|
|||||||
'subuser' => $subuser->id,
|
'subuser' => $subuser->id,
|
||||||
'enabled' => 1,
|
'enabled' => 1,
|
||||||
'deleted_at' => null,
|
'deleted_at' => null,
|
||||||
], ['permissions', 'billing_customer_number']);
|
], ['id', 'permissions', 'billing_customer_number']);
|
||||||
$customerNames = $this->resolveCustomerNames(array_map(
|
$customerNames = $this->resolveCustomerNames(array_map(
|
||||||
static fn (array $grant): int => (int)($grant['billing_customer_number'] ?? 0),
|
static fn (array $grant): int => (int)($grant['billing_customer_number'] ?? 0),
|
||||||
$grants
|
$grants
|
||||||
@@ -346,6 +396,7 @@ class subusersRoute
|
|||||||
'grants' => array_map(function ($grant) use ($customerNames) {
|
'grants' => array_map(function ($grant) use ($customerNames) {
|
||||||
$customerNumber = (int)$grant['billing_customer_number'];
|
$customerNumber = (int)$grant['billing_customer_number'];
|
||||||
return [
|
return [
|
||||||
|
'grant_id' => isset($grant['id']) ? (int)$grant['id'] : null,
|
||||||
'name' => $this->resolveCustomerName($customerNumber, $customerNames),
|
'name' => $this->resolveCustomerName($customerNumber, $customerNames),
|
||||||
'billing_customer_number' => $customerNumber,
|
'billing_customer_number' => $customerNumber,
|
||||||
'permissions' => subuser_grants_o::normalizePermissionsValue($grant['permissions'] ?? null),
|
'permissions' => subuser_grants_o::normalizePermissionsValue($grant['permissions'] ?? null),
|
||||||
@@ -762,28 +813,9 @@ class subusersRoute
|
|||||||
self::requireType($note, self::type_string());
|
self::requireType($note, self::type_string());
|
||||||
self::requireMaxLength('note', 65535);
|
self::requireMaxLength('note', 65535);
|
||||||
}
|
}
|
||||||
$permissions = null;
|
$permissions = self::isParametersSet(['permissions'])
|
||||||
if (self::isParametersSet(['permissions'])) {
|
? $this->parsePermissionsPayload(self::getParameter('permissions'), [])
|
||||||
$raw = self::getParameter('permissions');
|
: null;
|
||||||
// Expect array (already parsed) or JSON string
|
|
||||||
if (is_string($raw)) {
|
|
||||||
$decoded = json_decode($raw, true);
|
|
||||||
if (!is_array($decoded)) {
|
|
||||||
$response->error('Invalid permissions payload', 400);
|
|
||||||
}
|
|
||||||
$permissions = $decoded;
|
|
||||||
} elseif (is_array($raw)) {
|
|
||||||
$permissions = $raw;
|
|
||||||
} else {
|
|
||||||
$response->error('Invalid permissions type', 400);
|
|
||||||
}
|
|
||||||
// Validate each permission is a known key
|
|
||||||
foreach ($permissions as $perm) {
|
|
||||||
if (!is_string($perm) || subusers_permission_node_key::tryFrom($perm) === null) {
|
|
||||||
$response->error('Unknown permission key: ' . (string)$perm, 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
$grant = (new subuser_grants_o())->add($customer_number, $subuser_id, (bool)$enabled, $note, $permissions);
|
$grant = (new subuser_grants_o())->add($customer_number, $subuser_id, (bool)$enabled, $note, $permissions);
|
||||||
$response->success(['grant' => $grant->asArray()]);
|
$response->success(['grant' => $grant->asArray()]);
|
||||||
@@ -834,25 +866,7 @@ class subusersRoute
|
|||||||
$grant->note->set($note);
|
$grant->note->set($note);
|
||||||
}
|
}
|
||||||
if (self::isParametersSet(['permissions'])) {
|
if (self::isParametersSet(['permissions'])) {
|
||||||
$raw = self::getParameter('permissions');
|
$permissions = $this->parsePermissionsPayload(self::getParameter('permissions'), []);
|
||||||
// Expect array (already parsed) or JSON string
|
|
||||||
if (is_string($raw)) {
|
|
||||||
$decoded = json_decode($raw, true);
|
|
||||||
if (!is_array($decoded)) {
|
|
||||||
$response->error('Invalid permissions payload', 400);
|
|
||||||
}
|
|
||||||
$permissions = $decoded;
|
|
||||||
} elseif (is_array($raw)) {
|
|
||||||
$permissions = $raw;
|
|
||||||
} else {
|
|
||||||
$response->error('Invalid permissions type', 400);
|
|
||||||
}
|
|
||||||
// Validate each permission is a known key
|
|
||||||
foreach ($permissions as $perm) {
|
|
||||||
if (!is_string($perm) || subusers_permission_node_key::tryFrom($perm) === null) {
|
|
||||||
$response->error('Unknown permission key: ' . (string)$perm, 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$grant->permissions->set($permissions);
|
$grant->permissions->set($permissions);
|
||||||
}
|
}
|
||||||
$response->success($grant->asArray());
|
$response->success($grant->asArray());
|
||||||
@@ -866,6 +880,14 @@ class subusersRoute
|
|||||||
|
|
||||||
$this->get('/subusers/permission-nodes', function () {
|
$this->get('/subusers/permission-nodes', function () {
|
||||||
global $response;
|
global $response;
|
||||||
|
$canUseGlobalManagement = self::hasPermission('manage_subuser_grants')
|
||||||
|
|| self::hasPermission('list_subusers')
|
||||||
|
|| self::hasPermission('add_subusers')
|
||||||
|
|| self::hasPermission('edit_subusers');
|
||||||
|
if (!$canUseGlobalManagement) {
|
||||||
|
$this->requireManagedCustomerScope(subusers_permission_node_key::SUBUSERS_LIST);
|
||||||
|
}
|
||||||
|
|
||||||
// Build groups
|
// Build groups
|
||||||
$groups = [
|
$groups = [
|
||||||
new subusers_permission_nodes_bookings(),
|
new subusers_permission_nodes_bookings(),
|
||||||
@@ -893,7 +915,13 @@ class subusersRoute
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
$response->success($out);
|
$response->success($out);
|
||||||
}, []);
|
}, [
|
||||||
|
'list_own_subusers' => 'List chauffeur permission nodes for own customer. Subusers require node: SUBUSERS_LIST and X-Customer-Number header.',
|
||||||
|
'manage_subuser_grants' => 'List chauffeur permission nodes for administrative grant management.',
|
||||||
|
'list_subusers' => 'List chauffeur permission nodes for superuser management.',
|
||||||
|
'add_subusers' => 'List chauffeur permission nodes while inviting chauffeurs.',
|
||||||
|
'edit_subusers' => 'List chauffeur permission nodes while editing chauffeur grants.',
|
||||||
|
]);
|
||||||
|
|
||||||
$this->post('/subusers', function () {
|
$this->post('/subusers', function () {
|
||||||
global /** @var response $response */
|
global /** @var response $response */
|
||||||
@@ -948,15 +976,7 @@ class subusersRoute
|
|||||||
(int)$phone_country_code,
|
(int)$phone_country_code,
|
||||||
(int)$phone
|
(int)$phone
|
||||||
);
|
);
|
||||||
// Send an SMS with a link to complete the registration process.
|
$invite = $this->issueSetupInvite($subuser);
|
||||||
$gatewayAPI = new gatewayapi();
|
|
||||||
if ($gatewayAPI->isEnabled()) {
|
|
||||||
$token = $subuser->generateSetupToken();
|
|
||||||
$link = 'https://truckwash.io/complete-registration?token=' . $token;
|
|
||||||
$message = 'Tak for din oprettelse af chaufførkonto hos Truck Wash! Klik på linket for at fuldføre registreringen: ' . $link;
|
|
||||||
$phone_number_array = [(string)$phone_country_code . (string)$phone];
|
|
||||||
$gatewayAPI->send($phone_number_array, $message);
|
|
||||||
}
|
|
||||||
// Add the grant request
|
// Add the grant request
|
||||||
$subuser_grants_o = new subuser_grants_o();
|
$subuser_grants_o = new subuser_grants_o();
|
||||||
try {
|
try {
|
||||||
@@ -964,7 +984,7 @@ class subusersRoute
|
|||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
$response->error('Failed to add subuser grant', 500);
|
$response->error('Failed to add subuser grant', 500);
|
||||||
}
|
}
|
||||||
$response->success(['cvr' => $cvr, 'customer_number' => $results[0]->customerNumber]);
|
$response->success(['cvr' => $cvr, 'customer_number' => $results[0]->customerNumber, 'invite' => $invite]);
|
||||||
// Code for creating a new subuser would go here
|
// Code for creating a new subuser would go here
|
||||||
});
|
});
|
||||||
$this->get('/subusers/setup', function () {
|
$this->get('/subusers/setup', function () {
|
||||||
@@ -972,11 +992,13 @@ class subusersRoute
|
|||||||
global $response;
|
global $response;
|
||||||
self::requireParameters(['token']);
|
self::requireParameters(['token']);
|
||||||
$token = self::getParameter('token');
|
$token = self::getParameter('token');
|
||||||
|
$setupThrottleKey = $this->recordThrottleAttempt('setup_token', 'token-validation', 20, 15 * 60);
|
||||||
// Get the subuser with the setup token
|
// Get the subuser with the setup token
|
||||||
$subuser = (new subusers_o())->getSubuserBySetupToken($token);
|
$subuser = (new subusers_o())->getSubuserBySetupToken($token);
|
||||||
if ($subuser === null) {
|
if ($subuser === null) {
|
||||||
$response->error('Invalid or expired token', 400);
|
$response->error('Invalid or expired token', 400);
|
||||||
}
|
}
|
||||||
|
$this->clearThrottleAttempt($setupThrottleKey);
|
||||||
$response->success(['message' => 'Token is valid', 'subuser_id' => $subuser->id]);
|
$response->success(['message' => 'Token is valid', 'subuser_id' => $subuser->id]);
|
||||||
});
|
});
|
||||||
$this->post('/subusers/setup', function () {
|
$this->post('/subusers/setup', function () {
|
||||||
@@ -986,6 +1008,7 @@ class subusersRoute
|
|||||||
$token = (string)self::getParameter('token');
|
$token = (string)self::getParameter('token');
|
||||||
$password = (string)self::getParameter('password');
|
$password = (string)self::getParameter('password');
|
||||||
$name = (string)self::getParameter('name');
|
$name = (string)self::getParameter('name');
|
||||||
|
$setupThrottleKey = $this->recordThrottleAttempt('setup_complete', 'token-complete', 20, 15 * 60);
|
||||||
$this->requireSubuserPasswordPolicy($password);
|
$this->requireSubuserPasswordPolicy($password);
|
||||||
self::requireType($name, self::type_string());
|
self::requireType($name, self::type_string());
|
||||||
self::requireMinLength('name', 3);
|
self::requireMinLength('name', 3);
|
||||||
@@ -1017,18 +1040,24 @@ class subusersRoute
|
|||||||
if ($subuser === null) {
|
if ($subuser === null) {
|
||||||
$response->error('Invalid or expired token', 400);
|
$response->error('Invalid or expired token', 400);
|
||||||
}
|
}
|
||||||
|
$this->assertSubuserIdentifiersAvailable(
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
$username,
|
||||||
|
$email,
|
||||||
|
(int)$subuser->id
|
||||||
|
);
|
||||||
// Set the password for the subuser
|
// Set the password for the subuser
|
||||||
try {
|
try {
|
||||||
$subuser->setPassword($password);
|
$subuser->update([
|
||||||
if (!empty($username) || !empty($email) || !empty($name)) {
|
'password' => password_hash($password, PASSWORD_DEFAULT),
|
||||||
$subuser->update([
|
'name' => $name,
|
||||||
...(!empty($username) ? ['username' => $username] : []),
|
...(!empty($username) ? ['username' => $username] : []),
|
||||||
...(!empty($email) ? ['email' => $email] : []),
|
...(!empty($email) ? ['email' => $email] : []),
|
||||||
...(!empty($name) ? ['name' => $name] : []),
|
]);
|
||||||
]);
|
|
||||||
}
|
|
||||||
// Invalidate the setup token
|
// Invalidate the setup token
|
||||||
$subuser->invalidateSetupToken($token);
|
$subuser->invalidateSetupToken($token);
|
||||||
|
$this->clearThrottleAttempt($setupThrottleKey);
|
||||||
$response->success(['message' => 'Complete registration successful']);
|
$response->success(['message' => 'Complete registration successful']);
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
$response->error($e->getMessage(), 400);
|
$response->error($e->getMessage(), 400);
|
||||||
@@ -1067,23 +1096,34 @@ class subusersRoute
|
|||||||
} else {
|
} else {
|
||||||
$response->error('You must provide either phone_country_code & phone, subuser_id or username', 400);
|
$response->error('You must provide either phone_country_code & phone, subuser_id or username', 400);
|
||||||
}
|
}
|
||||||
|
$identifier = $username !== null
|
||||||
|
? 'username:' . strtolower($username)
|
||||||
|
: ($subuser_id !== null
|
||||||
|
? 'id:' . (string)$subuser_id
|
||||||
|
: 'phone:' . (string)$phone_country_code . ':' . (string)$phone);
|
||||||
|
$authThrottleKey = $this->recordThrottleAttempt('auth_password', $identifier, 10, 15 * 60);
|
||||||
// Get the subuser based on the provided username type
|
// Get the subuser based on the provided username type
|
||||||
$subuser = null;
|
$subuser = null;
|
||||||
if ($phone_country_code !== null && $phone !== null) {
|
if ($phone_country_code !== null && $phone !== null) {
|
||||||
$subuser = (new subusers_o())->getSubuserByPhone($phone_country_code, $phone);
|
$subuser = (new subusers_o())->getSubuserByPhone($phone_country_code, $phone);
|
||||||
} elseif ($subuser_id !== null) {
|
} elseif ($subuser_id !== null) {
|
||||||
$subuser = (new subusers_o())->select($subuser_id);
|
$candidate = (new subusers_o())->select($subuser_id);
|
||||||
|
if ($candidate->exists()) {
|
||||||
|
$candidate->getObjectProperties();
|
||||||
|
$subuser = $candidate;
|
||||||
|
}
|
||||||
} elseif ($username !== null) {
|
} elseif ($username !== null) {
|
||||||
$subuser = (new subusers_o())->getSubuserByUsername($username);
|
$subuser = (new subusers_o())->getSubuserByUsername($username);
|
||||||
}
|
}
|
||||||
if ($subuser === null) {
|
if ($subuser === null) {
|
||||||
$response->error('Subuser not found', 404);
|
$this->subuserAuthFailure();
|
||||||
}
|
}
|
||||||
self::requireParameters(['password']);
|
self::requireParameters(['password']);
|
||||||
$password = (string)self::getParameter('password');
|
$password = (string)self::getParameter('password');
|
||||||
$this->requireSubuserPasswordPolicy($password);
|
|
||||||
try {
|
try {
|
||||||
if (password_verify($password, $subuser->password->value())) {
|
$passwordHash = $subuser->password->value();
|
||||||
|
if (is_string($passwordHash) && $passwordHash !== '' && password_verify($password, $passwordHash)) {
|
||||||
|
$this->clearThrottleAttempt($authThrottleKey);
|
||||||
if ($subuser->isTwoFactorEnabled()) {
|
if ($subuser->isTwoFactorEnabled()) {
|
||||||
$token = (new authentication())->create_2fa_token($subuser->id, '2FA_VERIFICATION_SUBUSER');
|
$token = (new authentication())->create_2fa_token($subuser->id, '2FA_VERIFICATION_SUBUSER');
|
||||||
$response->success(['2fa_required' => true, '2fa_token' => $token]);
|
$response->success(['2fa_required' => true, '2fa_token' => $token]);
|
||||||
@@ -1092,7 +1132,7 @@ class subusersRoute
|
|||||||
$session = $subuser->generateSession();
|
$session = $subuser->generateSession();
|
||||||
$response->success(['session' => $session]);
|
$response->success(['session' => $session]);
|
||||||
} else {
|
} else {
|
||||||
$response->error('Invalid password', 400);
|
$this->subuserAuthFailure();
|
||||||
}
|
}
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
$response->error($e->getMessage(), 500);
|
$response->error($e->getMessage(), 500);
|
||||||
@@ -1363,15 +1403,7 @@ class subusersRoute
|
|||||||
(int)$phone
|
(int)$phone
|
||||||
);
|
);
|
||||||
|
|
||||||
// Optionally send SMS with setup link
|
$invite = $this->issueSetupInvite($subuser);
|
||||||
$gatewayAPI = new gatewayapi();
|
|
||||||
if ($gatewayAPI->isEnabled()) {
|
|
||||||
$token = $subuser->generateSetupToken();
|
|
||||||
$link = 'https://truckwash.io/complete-registration?token=' . $token;
|
|
||||||
$message = 'Tak for din oprettelse af chaufførkonto hos Truck Wash! Klik på linket for at fuldføre registreringen: ' . $link;
|
|
||||||
$phone_number_array = [(string)$phone_country_code . (string)$phone];
|
|
||||||
$gatewayAPI->send($phone_number_array, $message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a pending grant request for the company
|
// Create a pending grant request for the company
|
||||||
$subuser_grants_o = new subuser_grants_o();
|
$subuser_grants_o = new subuser_grants_o();
|
||||||
@@ -1381,7 +1413,7 @@ class subusersRoute
|
|||||||
$response->error('Failed to add subuser grant', 500);
|
$response->error('Failed to add subuser grant', 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
$response->success(['cvr' => $cvr, 'customer_number' => $results[0]->customerNumber]);
|
$response->success(['cvr' => $cvr, 'customer_number' => $results[0]->customerNumber, 'invite' => $invite]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,7 +132,6 @@ class vehiclesRoute
|
|||||||
self::requireParameters([
|
self::requireParameters([
|
||||||
'type',
|
'type',
|
||||||
'reg',
|
'reg',
|
||||||
'wash_subscription',
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Determine target customer
|
// Determine target customer
|
||||||
@@ -165,11 +164,14 @@ class vehiclesRoute
|
|||||||
// Validate the parameters
|
// Validate the parameters
|
||||||
self::requireType(self::getParameter('reg'), self::type_string());
|
self::requireType(self::getParameter('reg'), self::type_string());
|
||||||
self::requireType(self::getParameter('type'), self::type_int());
|
self::requireType(self::getParameter('type'), self::type_int());
|
||||||
self::requireType(self::getParameter('wash_subscription'), self::type_bool());
|
$subscription = false;
|
||||||
|
if (self::isParametersSet(['wash_subscription'])) {
|
||||||
|
self::requireType(self::getParameter('wash_subscription'), self::type_bool());
|
||||||
|
$subscription = (bool)self::getParameter('wash_subscription');
|
||||||
|
}
|
||||||
// Get the parameters
|
// Get the parameters
|
||||||
$reg = (string)self::getParameter('reg');
|
$reg = (string)self::getParameter('reg');
|
||||||
$type = (int)self::getParameter('type');
|
$type = (int)self::getParameter('type');
|
||||||
$subscription = (bool)self::getParameter('wash_subscription');
|
|
||||||
$reg = trim($reg);
|
$reg = trim($reg);
|
||||||
|
|
||||||
// Create a new vehicle
|
// Create a new vehicle
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ class workerRoute
|
|||||||
// The time should be from 00:00:00 of the start date to 23:59:59 of the end date
|
// The time should be from 00:00:00 of the start date to 23:59:59 of the end date
|
||||||
$date_end = date('Y-m-d 23:59:59', strtotime("-1 days")); // Yesterday (Sunday) at 23:59:59
|
$date_end = date('Y-m-d 23:59:59', strtotime("-1 days")); // Yesterday (Sunday) at 23:59:59
|
||||||
$date_start = date('Y-m-d 00:00:00', strtotime("-$days days")); // $days ago at 00:00:00
|
$date_start = date('Y-m-d 00:00:00', strtotime("-$days days")); // $days ago at 00:00:00
|
||||||
$department->sendSlackInternalStatisticNotification($date_start, $date_end, [1,2,3,4,5,6,7]);
|
$department->sendSlackInternalStatisticNotification($date_start, $date_end);
|
||||||
$response->success(['message' => 'Test message sent to Slack (not really, this is a placeholder).' ]);
|
$response->success(['message' => 'Test message sent to Slack (not really, this is a placeholder).' ]);
|
||||||
exit;
|
exit;
|
||||||
// Configuration
|
// Configuration
|
||||||
|
|||||||
@@ -200,6 +200,66 @@ it('logs out and invalidates cached subuser sessions', function (): void {
|
|||||||
->assertMessage('Unauthorized');
|
->assertMessage('Unauthorized');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('scopes passkey challenges to the requested principal type', function (): void {
|
||||||
|
api_test_covers('POST /auth/passkey/challenge', 'auth');
|
||||||
|
|
||||||
|
api_fixtures()->setModuleConfig('reCAPTCHA', 'enabled', 'false');
|
||||||
|
$user = api_fixtures()->createUser([
|
||||||
|
'display_name' => 'Passkey Customer',
|
||||||
|
]);
|
||||||
|
$subuser = api_fixtures()->createSubuser([
|
||||||
|
'username' => 'passkey-driver',
|
||||||
|
]);
|
||||||
|
api_fixtures()->createPasskey([
|
||||||
|
'user_id' => (int)$user['id'],
|
||||||
|
'is_subuser' => false,
|
||||||
|
'credential_id' => 'customer-passkey-credential',
|
||||||
|
]);
|
||||||
|
api_fixtures()->createPasskey([
|
||||||
|
'user_id' => (int)$subuser['id'],
|
||||||
|
'is_subuser' => true,
|
||||||
|
'credential_id' => 'subuser-passkey-credential',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$subuserChallenge = api_client()->post('/auth/passkey/challenge', [
|
||||||
|
'principal_type' => 'subuser',
|
||||||
|
'username' => 'passkey-driver',
|
||||||
|
]);
|
||||||
|
$userChallenge = api_client()->post('/auth/passkey/challenge', [
|
||||||
|
'principal_type' => 'user',
|
||||||
|
'customer_number' => (int)$user['customer_number'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$subuserChallenge
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
$userChallenge
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$subuserCredentials = $subuserChallenge->data()['publicKey']['allowCredentials'] ?? [];
|
||||||
|
$userCredentials = $userChallenge->data()['publicKey']['allowCredentials'] ?? [];
|
||||||
|
|
||||||
|
$subuserCredentialIds = array_column($subuserCredentials, 'id');
|
||||||
|
$userCredentialIds = array_column($userCredentials, 'id');
|
||||||
|
|
||||||
|
expect($subuserCredentialIds)->toContain('subuser-passkey-credential');
|
||||||
|
expect($subuserCredentialIds)->not->toContain('customer-passkey-credential');
|
||||||
|
expect($userCredentialIds)->toContain('customer-passkey-credential');
|
||||||
|
expect($userCredentialIds)->not->toContain('subuser-passkey-credential');
|
||||||
|
|
||||||
|
$subuserChallengeToken = (string)($subuserChallenge->data()['challenge_token'] ?? '');
|
||||||
|
$userChallengeToken = (string)($userChallenge->data()['challenge_token'] ?? '');
|
||||||
|
if ($subuserChallengeToken !== '') {
|
||||||
|
api_fixtures()->cleanupDeleteWhere('tokens', ['token' => $subuserChallengeToken]);
|
||||||
|
}
|
||||||
|
if ($userChallengeToken !== '') {
|
||||||
|
api_fixtures()->cleanupDeleteWhere('tokens', ['token' => $userChallengeToken]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects invalid logout tokens', function (): void {
|
it('rejects invalid logout tokens', function (): void {
|
||||||
api_test_covers('GET /auth/logout', 'auth');
|
api_test_covers('GET /auth/logout', 'auth');
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,15 @@ it('serves installer artifacts and recovers gateway runtime status after fresh h
|
|||||||
->and($artifact->body)
|
->and($artifact->body)
|
||||||
->toContain('<?php');
|
->toContain('<?php');
|
||||||
|
|
||||||
|
$manifest = api_client()->get('/edge-agent/artifacts/manifest.json');
|
||||||
|
expect($manifest->status)->toBe(200);
|
||||||
|
$manifestPayload = json_decode($manifest->body, true);
|
||||||
|
expect($manifestPayload)->toBeArray()
|
||||||
|
->and($manifestPayload['version'] ?? null)->toBe(edge_gateway_manager::DEFAULT_INSTALL_VERSION);
|
||||||
|
$manifestArtifacts = array_column((array)($manifestPayload['artifacts'] ?? []), null, 'name');
|
||||||
|
expect($manifestArtifacts)->toHaveKey('agent.php')
|
||||||
|
->and($manifestArtifacts['agent.php']['sha256'] ?? null)->toBe(hash('sha256', $artifact->body));
|
||||||
|
|
||||||
$claimResponse = api_client()->post('/edge-agent/claim', [
|
$claimResponse = api_client()->post('/edge-agent/claim', [
|
||||||
'token' => (string)$installToken['token'],
|
'token' => (string)$installToken['token'],
|
||||||
'hostname' => 'edge-agent-api',
|
'hostname' => 'edge-agent-api',
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
usesApiSuite();
|
||||||
|
|
||||||
|
it('serves whole-department expected relay states and records successful physical completion only', function (): void {
|
||||||
|
$scenario = api_fixtures()->createSelfServeScenario([
|
||||||
|
'department' => [
|
||||||
|
'name' => 'Edge Expected State Department',
|
||||||
|
],
|
||||||
|
'relay_ids' => [
|
||||||
|
'entry' => 'expected-entry',
|
||||||
|
'exit' => 'expected-exit',
|
||||||
|
'machine' => 'expected-machine',
|
||||||
|
'program_picker' => 'expected-program',
|
||||||
|
'cleaner' => 'expected-cleaner',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
$departmentId = (int)$scenario['department']['id'];
|
||||||
|
$laneId = (int)$scenario['lane']['id'];
|
||||||
|
api_fixtures()->setDepartmentShellyTransportMode($departmentId, 'gateway');
|
||||||
|
$session = api_fixtures()->createEdgeOperatorSession($departmentId, [
|
||||||
|
'modules_selfserve_lane_relay_machine_status_set',
|
||||||
|
'modules_selfserve_lane_relay_machine_cleaner_status_set',
|
||||||
|
]);
|
||||||
|
$gateway = api_fixtures()->createClaimedEdgeGateway([
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'label' => 'Expected State Gateway',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$relayIps = [
|
||||||
|
'expected-entry' => '10.41.0.11',
|
||||||
|
'expected-exit' => '10.41.0.12',
|
||||||
|
'expected-machine' => '10.41.0.13',
|
||||||
|
'expected-program' => '10.41.0.14',
|
||||||
|
'expected-cleaner' => '10.41.0.15',
|
||||||
|
];
|
||||||
|
foreach ($relayIps as $relayId => $ip) {
|
||||||
|
api_fixtures()->createEdgeRelayBinding([
|
||||||
|
'gateway_id' => (int)$gateway['id'],
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'device_id' => 'device-' . $relayId,
|
||||||
|
'local_ip' => $ip,
|
||||||
|
'metadata' => [
|
||||||
|
'device_type' => 'SHELLY_SWITCH',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$queueResponse = api_client()->post('/modules/self-serve/lane/hardware/batch/set', [
|
||||||
|
'lane_id' => $laneId,
|
||||||
|
'transport' => 'gateway',
|
||||||
|
'commands' => [
|
||||||
|
['target' => 'MACHINE', 'on' => true],
|
||||||
|
['target' => 'CLEANER', 'on' => false],
|
||||||
|
],
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$queueResponse
|
||||||
|
->assertStatus(202)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$expectedResponse = api_client()->post('/edge-agent/gateways/' . (int)$gateway['id'] . '/expected-relay-states', [
|
||||||
|
'agent_token' => (string)$gateway['agent_token'],
|
||||||
|
'wait_seconds' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$expectedResponse
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$lanes = $expectedResponse->data()['lanes'] ?? [];
|
||||||
|
expect($lanes)->toHaveKey((string)$laneId);
|
||||||
|
$laneStates = $lanes[(string)$laneId];
|
||||||
|
|
||||||
|
expect(array_keys($laneStates))->toBe([
|
||||||
|
'ENTRANCE_GATE',
|
||||||
|
'EXIT_GATE',
|
||||||
|
'MACHINE',
|
||||||
|
'PROGRAM_PICKER',
|
||||||
|
'CLEANER',
|
||||||
|
])
|
||||||
|
->and($laneStates['MACHINE']['device'])->toBe([
|
||||||
|
'ip' => '10.41.0.13',
|
||||||
|
'id' => 'device-expected-machine',
|
||||||
|
'type' => 'SHELLY_SWITCH',
|
||||||
|
])
|
||||||
|
->and($laneStates['MACHINE']['state'])->toBeTrue()
|
||||||
|
->and($laneStates['MACHINE']['completed'])->toBeNull()
|
||||||
|
->and($laneStates['CLEANER']['state'])->toBeFalse()
|
||||||
|
->and($laneStates['CLEANER']['completed'])->toBeNull()
|
||||||
|
->and($laneStates['ENTRANCE_GATE']['completed'])->not->toBeNull();
|
||||||
|
expect($expectedResponse->data())->toHaveKey('CLEANER')
|
||||||
|
->and($expectedResponse->data()['MACHINE']['device'] ?? null)->toBe($laneStates['MACHINE']['device'])
|
||||||
|
->and($expectedResponse->data()['CLEANER']['completed'])->toBeNull();
|
||||||
|
|
||||||
|
$machineUpdated = (string)$laneStates['MACHINE']['updated'];
|
||||||
|
$cleanerUpdated = (string)$laneStates['CLEANER']['updated'];
|
||||||
|
|
||||||
|
$resultResponse = api_client()->post('/edge-agent/gateways/' . (int)$gateway['id'] . '/relay-state-results', [
|
||||||
|
'agent_token' => (string)$gateway['agent_token'],
|
||||||
|
'results' => [
|
||||||
|
[
|
||||||
|
'lane_id' => $laneId,
|
||||||
|
'role' => 'MACHINE',
|
||||||
|
'state' => true,
|
||||||
|
'updated' => $machineUpdated,
|
||||||
|
'ok' => true,
|
||||||
|
'completed' => '2026-07-01T09:10:00+00:00',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'lane_id' => $laneId,
|
||||||
|
'role' => 'CLEANER',
|
||||||
|
'state' => false,
|
||||||
|
'updated' => $cleanerUpdated,
|
||||||
|
'ok' => false,
|
||||||
|
'skipped' => true,
|
||||||
|
'error' => 'Relay offline',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$resultResponse
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($resultResponse->data()['summary'] ?? [])
|
||||||
|
->toHaveKey('completed', 1)
|
||||||
|
->toHaveKey('skipped', 1)
|
||||||
|
->toHaveKey('failed', 0);
|
||||||
|
|
||||||
|
$afterResult = api_client()->post('/edge-agent/gateways/' . (int)$gateway['id'] . '/expected-relay-states', [
|
||||||
|
'agent_token' => (string)$gateway['agent_token'],
|
||||||
|
'wait_seconds' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$afterResult
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$afterLaneStates = $afterResult->data()['lanes'][(string)$laneId] ?? [];
|
||||||
|
expect($afterLaneStates['MACHINE']['completed'] ?? null)->not->toBeNull()
|
||||||
|
->and($afterLaneStates['CLEANER']['completed'] ?? null)->toBeNull()
|
||||||
|
->and($afterLaneStates['CLEANER']['last_error'] ?? null)->toBe('Relay offline');
|
||||||
|
|
||||||
|
$staleResponse = api_client()->post('/edge-agent/gateways/' . (int)$gateway['id'] . '/relay-state-results', [
|
||||||
|
'agent_token' => (string)$gateway['agent_token'],
|
||||||
|
'results' => [[
|
||||||
|
'lane_id' => $laneId,
|
||||||
|
'role' => 'CLEANER',
|
||||||
|
'state' => false,
|
||||||
|
'updated' => '2000-01-01 00:00:00',
|
||||||
|
'ok' => true,
|
||||||
|
'completed' => '2026-07-01T09:11:00+00:00',
|
||||||
|
]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$staleResponse
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($staleResponse->data()['summary']['stale'] ?? null)->toBe(1)
|
||||||
|
->and($staleResponse->data()['rejected'][0]['reason'] ?? null)->toBe('STALE_STATE');
|
||||||
|
});
|
||||||
@@ -0,0 +1,691 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use classes\limited_backoffice_service;
|
||||||
|
|
||||||
|
usesApiSuite();
|
||||||
|
|
||||||
|
function limited_backoffice_manager_session(array $departmentIds, array $extraPermissions = []): array
|
||||||
|
{
|
||||||
|
$permissions = [
|
||||||
|
limited_backoffice_service::PERMISSION_ACCESS,
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_PRICES,
|
||||||
|
limited_backoffice_service::PERMISSION_MANAGE_EMPLOYEES,
|
||||||
|
];
|
||||||
|
foreach ($departmentIds as $departmentId) {
|
||||||
|
$permissions[] = 'department_access_' . (int)$departmentId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return api_fixtures()->createUserSession(array_values(array_unique(array_merge($permissions, $extraPermissions))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function limited_backoffice_price_insert(int $departmentId, int $productId, int $price): void
|
||||||
|
{
|
||||||
|
$statement = api_test_runtime()->db()->prepare(
|
||||||
|
'INSERT INTO `product_department_prices` (`department_id`, `product_id`, `price`)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
ON DUPLICATE KEY UPDATE `price` = VALUES(`price`)'
|
||||||
|
);
|
||||||
|
$statement->bind_param('iii', $departmentId, $productId, $price);
|
||||||
|
$statement->execute();
|
||||||
|
$statement->close();
|
||||||
|
|
||||||
|
api_fixtures()->cleanupDeleteWhere('product_department_prices', [
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'product_id' => $productId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function limited_backoffice_price_value(int $departmentId, int $productId): ?int
|
||||||
|
{
|
||||||
|
$row = api_test_runtime()->queryOne(
|
||||||
|
'SELECT `price` FROM `product_department_prices` WHERE `department_id` = ' . $departmentId .
|
||||||
|
' AND `product_id` = ' . $productId . ' LIMIT 1'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $row === null ? null : (int)$row['price'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function limited_backoffice_cleanup_created_employee(int $employeeId): void
|
||||||
|
{
|
||||||
|
$row = api_test_runtime()->queryOne(
|
||||||
|
'SELECT `managed_group_id` FROM `limited_backoffice_employees` WHERE `user_id` = ' . $employeeId . ' LIMIT 1'
|
||||||
|
);
|
||||||
|
$groupId = (int)($row['managed_group_id'] ?? 0);
|
||||||
|
|
||||||
|
api_fixtures()->cleanupDeleteWhere('limited_backoffice_employees', ['user_id' => $employeeId]);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('tokens', ['user_id' => $employeeId]);
|
||||||
|
api_fixtures()->cleanupDeleteById('users', $employeeId);
|
||||||
|
if ($groupId > 0) {
|
||||||
|
api_fixtures()->cleanupDeleteWhere('groups_permissions', ['group_id' => $groupId]);
|
||||||
|
api_fixtures()->cleanupDeleteById('groups', $groupId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function limited_backoffice_without_users_deleted_at(callable $callback): void
|
||||||
|
{
|
||||||
|
$db = api_test_runtime()->db();
|
||||||
|
$column = $db->query("SHOW COLUMNS FROM `users` LIKE 'deleted_at'");
|
||||||
|
if ($column === false) {
|
||||||
|
throw new RuntimeException('Unable to inspect users.deleted_at test column.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$hadColumn = (int)$column->num_rows > 0;
|
||||||
|
if ($hadColumn) {
|
||||||
|
$db->query('ALTER TABLE `users` DROP COLUMN `deleted_at`');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$callback();
|
||||||
|
} finally {
|
||||||
|
if ($hadColumn) {
|
||||||
|
$db->query('ALTER TABLE `users` ADD COLUMN `deleted_at` DATETIME NULL');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function limited_backoffice_without_department_prices_updated_at(callable $callback): void
|
||||||
|
{
|
||||||
|
$db = api_test_runtime()->db();
|
||||||
|
$column = $db->query("SHOW COLUMNS FROM `product_department_prices` LIKE 'updated_at'");
|
||||||
|
if ($column === false) {
|
||||||
|
throw new RuntimeException('Unable to inspect product_department_prices.updated_at test column.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$hadColumn = (int)$column->num_rows > 0;
|
||||||
|
if ($hadColumn) {
|
||||||
|
$db->query('ALTER TABLE `product_department_prices` DROP COLUMN `updated_at`');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$callback();
|
||||||
|
} finally {
|
||||||
|
if ($hadColumn) {
|
||||||
|
$db->query(
|
||||||
|
'ALTER TABLE `product_department_prices`
|
||||||
|
ADD COLUMN `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
AFTER `created_at`'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('lists and updates explicit prices only for assigned departments', function (): void {
|
||||||
|
api_test_covers('GET /limited-backoffice/departments', 'happy');
|
||||||
|
api_test_covers('GET /limited-backoffice/departments/{departmentId}/prices', 'happy');
|
||||||
|
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'happy');
|
||||||
|
|
||||||
|
$productDeletedAtColumn = api_test_runtime()->db()->query("SHOW COLUMNS FROM `products` LIKE 'deleted_at'");
|
||||||
|
expect($productDeletedAtColumn)->not->toBeFalse();
|
||||||
|
expect((int)$productDeletedAtColumn->num_rows)->toBe(0);
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Prices Own']);
|
||||||
|
$otherDepartment = api_fixtures()->createDepartment(['name' => 'Limited Prices Other']);
|
||||||
|
$category = api_fixtures()->createCategory(['name' => 'Limited Washes']);
|
||||||
|
$product = api_fixtures()->createProduct([
|
||||||
|
'name' => 'Limited Wash Product',
|
||||||
|
'category' => $category['id'],
|
||||||
|
'price' => 98765,
|
||||||
|
]);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$otherDepartment['id'], (int)$category['id']);
|
||||||
|
limited_backoffice_price_insert((int)$department['id'], (int)$product['id'], 1234);
|
||||||
|
limited_backoffice_price_insert((int)$otherDepartment['id'], (int)$product['id'], 4321);
|
||||||
|
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
$departments = api_client()->get('/limited-backoffice/departments', $session['headers']);
|
||||||
|
$departments
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect(array_column($departments->data(), 'id'))
|
||||||
|
->toContain((int)$department['id'])
|
||||||
|
->not->toContain((int)$otherDepartment['id']);
|
||||||
|
|
||||||
|
$prices = api_client()->get('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', $session['headers']);
|
||||||
|
$prices
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($prices->body)->not->toContain('98765');
|
||||||
|
expect($prices->data()['categories'][0]['products'][0])
|
||||||
|
->toMatchArray([
|
||||||
|
'id' => (int)$product['id'],
|
||||||
|
'name' => 'Limited Wash Product',
|
||||||
|
'price' => 1234,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$updated = api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$product['id'], 'price' => '2222'],
|
||||||
|
],
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$updated
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$product['id']))->toBe(2222);
|
||||||
|
expect(limited_backoffice_price_value((int)$otherDepartment['id'], (int)$product['id']))->toBe(4321);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates department prices when the price table has no updated_at column', function (): void {
|
||||||
|
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'schema compatibility');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Prices Legacy Schema']);
|
||||||
|
$category = api_fixtures()->createCategory(['name' => 'Limited Prices Legacy Category']);
|
||||||
|
$products = [
|
||||||
|
api_fixtures()->createProduct(['name' => 'Legacy Price One', 'category' => $category['id']]),
|
||||||
|
api_fixtures()->createProduct(['name' => 'Legacy Price Two', 'category' => $category['id']]),
|
||||||
|
api_fixtures()->createProduct(['name' => 'Legacy Price Three', 'category' => $category['id']]),
|
||||||
|
];
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||||
|
|
||||||
|
foreach ($products as $index => $product) {
|
||||||
|
limited_backoffice_price_insert((int)$department['id'], (int)$product['id'], 100 + $index);
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
limited_backoffice_without_department_prices_updated_at(function () use ($department, $products, $session): void {
|
||||||
|
$updated = api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$products[0]['id'], 'price' => '999999'],
|
||||||
|
['product_id' => (int)$products[1]['id'], 'price' => '999999'],
|
||||||
|
['product_id' => (int)$products[2]['id'], 'price' => '99999'],
|
||||||
|
],
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$updated
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[0]['id']))->toBe(999999);
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[1]['id']))->toBe(999999);
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[2]['id']))->toBe(99999);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects cross-department price access, body spoofing, and outside products', function (): void {
|
||||||
|
api_test_covers('GET /limited-backoffice/departments/{departmentId}/prices', 'auth');
|
||||||
|
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'auth');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Scope Own']);
|
||||||
|
$otherDepartment = api_fixtures()->createDepartment(['name' => 'Limited Scope Other']);
|
||||||
|
$category = api_fixtures()->createCategory(['name' => 'Limited Scope Category']);
|
||||||
|
$otherCategory = api_fixtures()->createCategory(['name' => 'Limited Scope Other Category']);
|
||||||
|
$product = api_fixtures()->createProduct(['category' => $category['id']]);
|
||||||
|
$outsideProduct = api_fixtures()->createProduct(['category' => $otherCategory['id']]);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$otherDepartment['id'], (int)$otherCategory['id']);
|
||||||
|
limited_backoffice_price_insert((int)$department['id'], (int)$product['id'], 100);
|
||||||
|
limited_backoffice_price_insert((int)$otherDepartment['id'], (int)$outsideProduct['id'], 200);
|
||||||
|
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
api_client()->get('/limited-backoffice/departments/' . (int)$otherDepartment['id'] . '/prices', $session['headers'])
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMissingPermissions(['department_access_' . (int)$otherDepartment['id']]);
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'department_id' => (int)$otherDepartment['id'],
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$product['id'], 'price' => 111],
|
||||||
|
],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Department ID in body does not match the route.');
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$product['id'], 'price' => 111],
|
||||||
|
['product_id' => (int)$outsideProduct['id'], 'price' => 111],
|
||||||
|
],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Product is not available for this department.');
|
||||||
|
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$product['id']))->toBe(100);
|
||||||
|
expect(limited_backoffice_price_value((int)$otherDepartment['id'], (int)$outsideProduct['id']))->toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails price setup gaps without exposing product defaults', function (): void {
|
||||||
|
api_test_covers('GET /limited-backoffice/departments/{departmentId}/prices', 'failure');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Setup Gap']);
|
||||||
|
$category = api_fixtures()->createCategory(['name' => 'Limited Setup Gap Category']);
|
||||||
|
$product = api_fixtures()->createProduct([
|
||||||
|
'name' => 'Setup Gap Product',
|
||||||
|
'category' => $category['id'],
|
||||||
|
'price' => 87654,
|
||||||
|
]);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||||
|
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
$response = api_client()->get('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', $session['headers']);
|
||||||
|
$response
|
||||||
|
->assertStatus(409)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Department price setup is incomplete.');
|
||||||
|
|
||||||
|
expect($response->body)->not->toContain('87654');
|
||||||
|
expect($response->data()['missing_products'][0]['id'] ?? null)->toBe((int)$product['id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid price batches and leaves existing prices unchanged', function (): void {
|
||||||
|
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'validation');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Invalid Prices']);
|
||||||
|
$category = api_fixtures()->createCategory(['name' => 'Limited Invalid Prices Category']);
|
||||||
|
$firstProduct = api_fixtures()->createProduct(['category' => $category['id']]);
|
||||||
|
$secondProduct = api_fixtures()->createProduct(['category' => $category['id']]);
|
||||||
|
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||||
|
limited_backoffice_price_insert((int)$department['id'], (int)$firstProduct['id'], 100);
|
||||||
|
limited_backoffice_price_insert((int)$department['id'], (int)$secondProduct['id'], 200);
|
||||||
|
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
foreach ([null, '', 'abc', -1] as $invalidPrice) {
|
||||||
|
api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$firstProduct['id'], 'price' => 999],
|
||||||
|
['product_id' => (int)$secondProduct['id'], 'price' => $invalidPrice],
|
||||||
|
],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false);
|
||||||
|
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$firstProduct['id']))->toBe(100);
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$secondProduct['id']))->toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||||
|
'prices' => [
|
||||||
|
['product_id' => (int)$firstProduct['id'], 'price' => 999],
|
||||||
|
],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Price is required for every department product.');
|
||||||
|
|
||||||
|
expect(limited_backoffice_price_value((int)$department['id'], (int)$firstProduct['id']))->toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates updates lists and deactivates scoped employees without exposing raw permissions', function (): void {
|
||||||
|
limited_backoffice_without_users_deleted_at(function (): void {
|
||||||
|
api_test_covers('GET /limited-backoffice/roles', 'happy');
|
||||||
|
api_test_covers('GET /limited-backoffice/employees', 'happy');
|
||||||
|
api_test_covers('POST /limited-backoffice/employees', 'happy');
|
||||||
|
api_test_covers('PUT /limited-backoffice/employees/{employeeId}', 'happy');
|
||||||
|
api_test_covers('DELETE /limited-backoffice/employees/{employeeId}', 'happy');
|
||||||
|
|
||||||
|
$usersDeletedAtColumn = api_test_runtime()->db()->query("SHOW COLUMNS FROM `users` LIKE 'deleted_at'");
|
||||||
|
expect($usersDeletedAtColumn)->not->toBeFalse();
|
||||||
|
expect((int)$usersDeletedAtColumn->num_rows)->toBe(0);
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee Department']);
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
$roles = api_client()->get('/limited-backoffice/roles', $session['headers']);
|
||||||
|
$roles
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect(array_column($roles->data(), 'key'))->toBe(['viewer', 'cashier', 'booking_coordinator', 'operations_lead', 'department_admin']);
|
||||||
|
$rolesByKey = array_column($roles->data(), null, 'key');
|
||||||
|
expect($rolesByKey['viewer']['permission_groups'] ?? null)->toBe([
|
||||||
|
[
|
||||||
|
'key' => 'account',
|
||||||
|
'capabilities' => ['sign_in', 'view_own_permissions'],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
$departmentAdminGroups = array_column($rolesByKey['department_admin']['permission_groups'] ?? [], 'capabilities', 'key');
|
||||||
|
expect($departmentAdminGroups['limited_backoffice'] ?? null)->toBe([
|
||||||
|
'open_limited_backoffice',
|
||||||
|
'manage_department_prices',
|
||||||
|
'manage_employee_access',
|
||||||
|
]);
|
||||||
|
expect($roles->body)->not->toContain('department_access_');
|
||||||
|
$rolePayload = $roles->data();
|
||||||
|
$rolePayloadStrings = [];
|
||||||
|
array_walk_recursive($rolePayload, static function ($value) use (&$rolePayloadStrings): void {
|
||||||
|
if (is_string($value)) {
|
||||||
|
$rolePayloadStrings[] = $value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
foreach ([
|
||||||
|
'list_orders',
|
||||||
|
'add_order',
|
||||||
|
'edit_order',
|
||||||
|
'delete_order',
|
||||||
|
'list_order_items',
|
||||||
|
'add_order_items',
|
||||||
|
'edit_order_items',
|
||||||
|
'delete_order_items',
|
||||||
|
'charge_order',
|
||||||
|
'list_bookings',
|
||||||
|
'list_own_bookings',
|
||||||
|
'edit_bookings',
|
||||||
|
'add_booking',
|
||||||
|
'complete_bookings',
|
||||||
|
'resend_booking_confirmations',
|
||||||
|
'department_timebookings_entries_get',
|
||||||
|
'department_timebookings_entries_post',
|
||||||
|
'department_timebookings_entries_put',
|
||||||
|
'statistics_orders_new',
|
||||||
|
'statistics_bookings_new',
|
||||||
|
'limited_backoffice_access',
|
||||||
|
'limited_backoffice_prices_manage',
|
||||||
|
'limited_backoffice_employees_manage',
|
||||||
|
] as $rawPermission) {
|
||||||
|
expect($rolePayloadStrings)->not->toContain($rawPermission);
|
||||||
|
}
|
||||||
|
|
||||||
|
$created = api_client()->post('/limited-backoffice/employees', [
|
||||||
|
'display_name' => 'Limited Cashier',
|
||||||
|
'email' => 'limited-cashier@example.test',
|
||||||
|
'phone_country_code' => 45,
|
||||||
|
'phone' => 12345678,
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'cashier',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$created
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||||
|
expect($employeeId)->toBeGreaterThan(0);
|
||||||
|
limited_backoffice_cleanup_created_employee($employeeId);
|
||||||
|
expect($created->data()['email'] ?? null)->toBe('limited-cashier@example.test');
|
||||||
|
expect($created->data()['phone_country_code'] ?? null)->toBe(45);
|
||||||
|
expect($created->data()['phone'] ?? null)->toBe(12345678);
|
||||||
|
expect($created->body)->not->toContain('department_access_');
|
||||||
|
expect($created->body)->not->toContain('permissions');
|
||||||
|
|
||||||
|
$groupRow = api_test_runtime()->queryOne(
|
||||||
|
'SELECT `managed_group_id` FROM `limited_backoffice_employees` WHERE `user_id` = ' . $employeeId . ' LIMIT 1'
|
||||||
|
);
|
||||||
|
$groupId = (int)($groupRow['managed_group_id'] ?? 0);
|
||||||
|
$permissionRows = api_test_runtime()->db()->query(
|
||||||
|
'SELECT `permission` FROM `groups_permissions` WHERE `group_id` = ' . $groupId
|
||||||
|
)->fetch_all(MYSQLI_ASSOC);
|
||||||
|
$permissions = array_column($permissionRows, 'permission');
|
||||||
|
expect($permissions)
|
||||||
|
->toContain('department_access_' . (int)$department['id'])
|
||||||
|
->toContain('add_order')
|
||||||
|
->not->toContain('superuser');
|
||||||
|
|
||||||
|
$updated = api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||||
|
'display_name' => 'Limited Lead',
|
||||||
|
'email' => 'limited-lead@example.test',
|
||||||
|
'phone_country_code' => 358,
|
||||||
|
'phone' => 87654321,
|
||||||
|
'role_key' => 'operations_lead',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
], $session['headers']);
|
||||||
|
$updated
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($updated->data()['display_name'] ?? null)->toBe('Limited Lead');
|
||||||
|
expect($updated->data()['email'] ?? null)->toBe('limited-lead@example.test');
|
||||||
|
expect($updated->data()['phone_country_code'] ?? null)->toBe(358);
|
||||||
|
expect($updated->data()['phone'] ?? null)->toBe(87654321);
|
||||||
|
expect($updated->data()['role']['key'] ?? null)->toBe('operations_lead');
|
||||||
|
|
||||||
|
$list = api_client()->get('/limited-backoffice/employees', $session['headers']);
|
||||||
|
$ids = array_column($list->data(), 'id');
|
||||||
|
expect($ids)->toContain($employeeId);
|
||||||
|
$listedEmployee = null;
|
||||||
|
foreach ($list->data() as $employee) {
|
||||||
|
if ((int)($employee['id'] ?? 0) === $employeeId) {
|
||||||
|
$listedEmployee = $employee;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect($listedEmployee)->not->toBeNull();
|
||||||
|
expect($listedEmployee['email'] ?? null)->toBe('limited-lead@example.test');
|
||||||
|
expect($listedEmployee['phone_country_code'] ?? null)->toBe(358);
|
||||||
|
expect($listedEmployee['phone'] ?? null)->toBe(87654321);
|
||||||
|
expect($list->body)->not->toContain('department_access_');
|
||||||
|
|
||||||
|
$deactivated = api_client()->delete('/limited-backoffice/employees/' . $employeeId, null, $session['headers']);
|
||||||
|
$deactivated
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($deactivated->data()['active'] ?? true)->toBeFalse();
|
||||||
|
$userRow = api_test_runtime()->queryOne('SELECT `password`, `group_id` FROM `users` WHERE `id` = ' . $employeeId);
|
||||||
|
expect($userRow)->not->toBeNull();
|
||||||
|
expect(array_key_exists('password', $userRow ?? []))->toBeTrue();
|
||||||
|
expect($userRow['password'])->toBeNull();
|
||||||
|
expect((int)($userRow['group_id'] ?? -1))->toBe(0);
|
||||||
|
$employeeRow = api_test_runtime()->queryOne(
|
||||||
|
'SELECT `deactivated_at` FROM `limited_backoffice_employees` WHERE `user_id` = ' . $employeeId . ' LIMIT 1'
|
||||||
|
);
|
||||||
|
expect($employeeRow['deactivated_at'] ?? null)->not->toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts employees without optional phone details', function (): void {
|
||||||
|
api_test_covers('POST /limited-backoffice/employees', 'happy');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee No Phone']);
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
$created = api_client()->post('/limited-backoffice/employees', [
|
||||||
|
'display_name' => 'Limited No Phone',
|
||||||
|
'email' => 'limited-no-phone@example.test',
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'viewer',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$created
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||||
|
expect($employeeId)->toBeGreaterThan(0);
|
||||||
|
limited_backoffice_cleanup_created_employee($employeeId);
|
||||||
|
expect(array_key_exists('phone_country_code', $created->data()))->toBeTrue();
|
||||||
|
expect(array_key_exists('phone', $created->data()))->toBeTrue();
|
||||||
|
expect($created->data()['phone_country_code'])->toBeNull();
|
||||||
|
expect($created->data()['phone'])->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects employee scopes roles raw permissions self edits superusers and shared groups', function (): void {
|
||||||
|
api_test_covers('POST /limited-backoffice/employees', 'validation');
|
||||||
|
api_test_covers('PUT /limited-backoffice/employees/{employeeId}', 'validation');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee Own']);
|
||||||
|
$otherDepartment = api_fixtures()->createDepartment(['name' => 'Limited Employee Other']);
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
'display_name' => 'Outside Employee',
|
||||||
|
'email' => 'outside@example.test',
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'cashier',
|
||||||
|
'department_ids' => [(int)$otherDepartment['id']],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMissingPermissions(['department_access_' . (int)$otherDepartment['id']]);
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
'display_name' => 'Raw Employee',
|
||||||
|
'email' => 'raw@example.test',
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'cashier',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
'permissions' => ['superuser'],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Raw permission and group assignment is not allowed.');
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
'display_name' => 'Unknown Role Employee',
|
||||||
|
'email' => 'unknown-role@example.test',
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'superuser',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Unknown role.');
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/employees/' . (int)$session['user']['id'], [
|
||||||
|
'display_name' => 'Self Edit',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Managers cannot edit themselves.');
|
||||||
|
|
||||||
|
$superuser = api_fixtures()->createUser(['group_id' => 1]);
|
||||||
|
api_test_runtime()->db()->query(
|
||||||
|
'INSERT INTO `limited_backoffice_employees`
|
||||||
|
(`user_id`, `managed_group_id`, `role_key`, `department_ids`, `created_by_user_id`)
|
||||||
|
VALUES (' . (int)$superuser['id'] . ", 1, 'department_admin', '[" . (int)$department['id'] . "]', " . (int)$session['user']['id'] . ')'
|
||||||
|
);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('limited_backoffice_employees', ['user_id' => (int)$superuser['id']]);
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/employees/' . (int)$superuser['id'], [
|
||||||
|
'display_name' => 'Edited Superuser',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Cannot manage superuser accounts.');
|
||||||
|
|
||||||
|
$sharedGroup = api_fixtures()->createGroup();
|
||||||
|
$firstSharedUser = api_fixtures()->createUser(['group_id' => $sharedGroup['id']]);
|
||||||
|
api_fixtures()->createUser(['group_id' => $sharedGroup['id']]);
|
||||||
|
$departmentJson = '[' . (int)$department['id'] . ']';
|
||||||
|
api_test_runtime()->db()->query(
|
||||||
|
'INSERT INTO `limited_backoffice_employees`
|
||||||
|
(`user_id`, `managed_group_id`, `role_key`, `department_ids`, `created_by_user_id`)
|
||||||
|
VALUES (' . (int)$firstSharedUser['id'] . ', ' . (int)$sharedGroup['id'] . ", 'viewer', '" . $departmentJson . "', " . (int)$session['user']['id'] . ')'
|
||||||
|
);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('limited_backoffice_employees', ['user_id' => (int)$firstSharedUser['id']]);
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/employees/' . (int)$firstSharedUser['id'], [
|
||||||
|
'display_name' => 'Edited Shared Group',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Cannot manage shared groups.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid limited backoffice employee contact details', function (): void {
|
||||||
|
api_test_covers('POST /limited-backoffice/employees', 'validation');
|
||||||
|
api_test_covers('PUT /limited-backoffice/employees/{employeeId}', 'validation');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee Contact Validation']);
|
||||||
|
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||||
|
$basePayload = [
|
||||||
|
'display_name' => 'Contact Employee',
|
||||||
|
'email' => 'contact@example.test',
|
||||||
|
'password' => 'Secret123!',
|
||||||
|
'role_key' => 'viewer',
|
||||||
|
'department_ids' => [(int)$department['id']],
|
||||||
|
];
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', array_diff_key($basePayload, ['email' => true]), $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Email is required.');
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
...$basePayload,
|
||||||
|
'email' => 'not-an-email',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Email must be a valid email address.');
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
...$basePayload,
|
||||||
|
'phone_country_code' => 45,
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Phone country code and phone number must be provided together.');
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
...$basePayload,
|
||||||
|
'phone_country_code' => 1,
|
||||||
|
'phone' => 12345678,
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Phone country code is not supported.');
|
||||||
|
|
||||||
|
api_client()->post('/limited-backoffice/employees', [
|
||||||
|
...$basePayload,
|
||||||
|
'phone_country_code' => 45,
|
||||||
|
'phone' => '12ab',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Phone values must contain digits only.');
|
||||||
|
|
||||||
|
$created = api_client()->post('/limited-backoffice/employees', $basePayload, $session['headers'])
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||||
|
expect($employeeId)->toBeGreaterThan(0);
|
||||||
|
limited_backoffice_cleanup_created_employee($employeeId);
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||||
|
'email' => '',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Email is required.');
|
||||||
|
|
||||||
|
api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||||
|
'phone_country_code' => 45,
|
||||||
|
'phone' => '123',
|
||||||
|
], $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Phone number must be 4-15 digits.');
|
||||||
|
});
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Tests\Support\Api\ApiServer;
|
||||||
|
|
||||||
|
usesApiSuite();
|
||||||
|
|
||||||
|
it('rejects scanner LPR requests without an image before contacting Plate Recognizer', function (): void {
|
||||||
|
api_test_covers('POST /modules/scanner/lpr', 'failure');
|
||||||
|
|
||||||
|
$response = api_client()->post('/modules/scanner/lpr', []);
|
||||||
|
|
||||||
|
$response->assertStatus(400)->assertSuccess(false)->assertMessage('Image is required.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts multipart scanner images and forwards them to Plate Recognizer as a temp-file upload', function (): void {
|
||||||
|
api_test_covers('POST /modules/scanner/lpr', 'happy');
|
||||||
|
|
||||||
|
if (trim((string)getenv('API_TEST_BASE_URL')) !== '') {
|
||||||
|
$this->markTestSkipped('This scanner LPR test requires the self-started API server so PLATE_RECOGNIZER_API_URL can be isolated.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$fakePlateRecognizer = ScannerLprFakePlateRecognizerServer::start();
|
||||||
|
$previousPlateRecognizerUrl = scanner_lpr_api_get_env('PLATE_RECOGNIZER_API_URL');
|
||||||
|
scanner_lpr_api_set_env('PLATE_RECOGNIZER_API_URL', $fakePlateRecognizer->url());
|
||||||
|
api_test_runtime()->restartServer();
|
||||||
|
|
||||||
|
$imagePath = tempnam(sys_get_temp_dir(), 'scanner-lpr-api-');
|
||||||
|
expect($imagePath)->not->toBeFalse();
|
||||||
|
file_put_contents($imagePath, 'jpeg-camera-bytes');
|
||||||
|
|
||||||
|
try {
|
||||||
|
api_fixtures()->setModuleConfig('licenseplaterecognizer', 'enabled', 'true', 'bool');
|
||||||
|
api_fixtures()->setModuleConfig('licenseplaterecognizer', 'api_key', 'scanner-api-test-key', 'string');
|
||||||
|
api_test_runtime()->redis()?->del(['licenseplaterecognizer:runtime_config:v1']);
|
||||||
|
|
||||||
|
$response = api_client()->postMultipart('/modules/scanner/lpr', [
|
||||||
|
'client_capture_ms' => '12.345',
|
||||||
|
'client_frame_width' => '300',
|
||||||
|
'client_frame_height' => '225',
|
||||||
|
'client_frame_bytes' => (string)strlen('jpeg-camera-bytes'),
|
||||||
|
], [
|
||||||
|
'image' => [
|
||||||
|
'path' => $imagePath,
|
||||||
|
'mime' => 'image/jpeg',
|
||||||
|
'name' => 'camera-frame.jpg',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertStatus(200)->assertSuccess();
|
||||||
|
expect($response->data())->toMatchArray([
|
||||||
|
'success' => true,
|
||||||
|
'license_plate_number' => 'AB12345',
|
||||||
|
]);
|
||||||
|
expect($response->headers['server-timing'] ?? '')
|
||||||
|
->toContain('lpr_client_capture')
|
||||||
|
->toContain('lpr_client_frame_width')
|
||||||
|
->toContain('lpr_client_frame_height')
|
||||||
|
->toContain('lpr_client_frame_bytes')
|
||||||
|
->toContain('lpr_local')
|
||||||
|
->toContain('lpr_payload')
|
||||||
|
->toContain('lpr_upstream_dns')
|
||||||
|
->toContain('lpr_upstream_connect')
|
||||||
|
->toContain('lpr_upstream')
|
||||||
|
->toContain('lpr_upstream_total')
|
||||||
|
->toContain('lpr_upstream_processing')
|
||||||
|
->toContain('lpr_total')
|
||||||
|
->toContain('lpr_route_total')
|
||||||
|
->toContain('lpr_request_total');
|
||||||
|
|
||||||
|
$capture = $fakePlateRecognizer->capture();
|
||||||
|
expect($capture['method'] ?? null)->toBe('POST');
|
||||||
|
expect($capture['authorization'] ?? null)->toBe('Token scanner-api-test-key');
|
||||||
|
expect($capture['expect'] ?? null)->toBeNull();
|
||||||
|
expect(json_decode((string)($capture['post']['config'] ?? ''), true))->toBe([
|
||||||
|
'mode' => 'fast',
|
||||||
|
'plates_per_vehicle' => 1,
|
||||||
|
'zoom_in_vehicles' => 0,
|
||||||
|
]);
|
||||||
|
expect($capture['post']['regions'] ?? null)->toBe('dk,de,se,no');
|
||||||
|
expect($capture['post']['client_capture_ms'] ?? null)->toBeNull();
|
||||||
|
expect($capture['post']['client_frame_width'] ?? null)->toBeNull();
|
||||||
|
expect($capture['post']['client_frame_height'] ?? null)->toBeNull();
|
||||||
|
expect($capture['post']['client_frame_bytes'] ?? null)->toBeNull();
|
||||||
|
expect($capture['files']['upload'] ?? [])->toMatchArray([
|
||||||
|
'name' => 'license-plate.jpg',
|
||||||
|
'type' => 'image/jpeg',
|
||||||
|
'size' => strlen('jpeg-camera-bytes'),
|
||||||
|
'error' => UPLOAD_ERR_OK,
|
||||||
|
'contents' => base64_encode('jpeg-camera-bytes'),
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
@unlink($imagePath);
|
||||||
|
$fakePlateRecognizer->stop();
|
||||||
|
scanner_lpr_api_set_env('PLATE_RECOGNIZER_API_URL', $previousPlateRecognizerUrl);
|
||||||
|
api_test_runtime()->restartServer();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
final class ScannerLprFakePlateRecognizerServer
|
||||||
|
{
|
||||||
|
private mixed $process = null;
|
||||||
|
|
||||||
|
private function __construct(
|
||||||
|
private readonly string $directory,
|
||||||
|
private readonly string $capturePath,
|
||||||
|
private readonly int $port,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function start(): self
|
||||||
|
{
|
||||||
|
$directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'scanner-lpr-fake-' . bin2hex(random_bytes(6));
|
||||||
|
if (!mkdir($directory, 0777, true) && !is_dir($directory)) {
|
||||||
|
throw new RuntimeException('Unable to create fake Plate Recognizer directory.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$capturePath = $directory . DIRECTORY_SEPARATOR . 'capture.json';
|
||||||
|
$routerPath = $directory . DIRECTORY_SEPARATOR . 'router.php';
|
||||||
|
file_put_contents($routerPath, <<<'PHP'
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$path = parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/';
|
||||||
|
if ($path === '/health') {
|
||||||
|
header('Content-Type: text/plain');
|
||||||
|
echo 'ok';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($path !== '/v1/plate-reader/') {
|
||||||
|
http_response_code(404);
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
echo json_encode(['error' => 'not found']);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$upload = $_FILES['upload'] ?? [];
|
||||||
|
$tmpName = is_array($upload) ? (string)($upload['tmp_name'] ?? '') : '';
|
||||||
|
$capture = [
|
||||||
|
'method' => $_SERVER['REQUEST_METHOD'] ?? null,
|
||||||
|
'authorization' => $_SERVER['HTTP_AUTHORIZATION'] ?? null,
|
||||||
|
'expect' => $_SERVER['HTTP_EXPECT'] ?? null,
|
||||||
|
'post' => $_POST,
|
||||||
|
'files' => [
|
||||||
|
'upload' => [
|
||||||
|
'name' => is_array($upload) ? ($upload['name'] ?? null) : null,
|
||||||
|
'type' => is_array($upload) ? ($upload['type'] ?? null) : null,
|
||||||
|
'size' => is_array($upload) ? ($upload['size'] ?? null) : null,
|
||||||
|
'error' => is_array($upload) ? ($upload['error'] ?? null) : null,
|
||||||
|
'contents' => $tmpName !== '' && is_file($tmpName) ? base64_encode((string)file_get_contents($tmpName)) : null,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
file_put_contents((string)getenv('SCANNER_LPR_FAKE_CAPTURE_PATH'), json_encode($capture, JSON_UNESCAPED_SLASHES));
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
echo json_encode([
|
||||||
|
'processing_time' => 58.184,
|
||||||
|
'results' => [['plate' => 'ab12345', 'score' => 0.98]],
|
||||||
|
], JSON_UNESCAPED_SLASHES);
|
||||||
|
PHP);
|
||||||
|
|
||||||
|
$port = ApiServer::findAvailablePort('127.0.0.1');
|
||||||
|
$server = new self($directory, $capturePath, $port);
|
||||||
|
$server->startProcess($routerPath);
|
||||||
|
$server->waitUntilReady();
|
||||||
|
|
||||||
|
return $server;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function url(): string
|
||||||
|
{
|
||||||
|
return sprintf('http://127.0.0.1:%d', $this->port);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function capture(): array
|
||||||
|
{
|
||||||
|
$contents = is_file($this->capturePath) ? file_get_contents($this->capturePath) : false;
|
||||||
|
expect($contents)->not->toBeFalse();
|
||||||
|
|
||||||
|
$decoded = json_decode((string)$contents, true);
|
||||||
|
expect($decoded)->toBeArray();
|
||||||
|
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stop(): void
|
||||||
|
{
|
||||||
|
if (is_resource($this->process)) {
|
||||||
|
proc_terminate($this->process);
|
||||||
|
usleep(250000);
|
||||||
|
$status = proc_get_status($this->process);
|
||||||
|
if (($status['running'] ?? false) && function_exists('posix_kill')) {
|
||||||
|
@posix_kill((int)$status['pid'], 9);
|
||||||
|
}
|
||||||
|
proc_close($this->process);
|
||||||
|
$this->process = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->removeDirectory($this->directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function startProcess(string $routerPath): void
|
||||||
|
{
|
||||||
|
$command = sprintf(
|
||||||
|
'%s -S %s %s',
|
||||||
|
escapeshellarg((string)(PHP_BINARY ?: 'php')),
|
||||||
|
escapeshellarg('127.0.0.1:' . $this->port),
|
||||||
|
escapeshellarg($routerPath),
|
||||||
|
);
|
||||||
|
$environment = array_merge(getenv() ?: [], [
|
||||||
|
'SCANNER_LPR_FAKE_CAPTURE_PATH' => $this->capturePath,
|
||||||
|
]);
|
||||||
|
$descriptorSpec = [
|
||||||
|
0 => ['pipe', 'r'],
|
||||||
|
1 => ['file', $this->directory . DIRECTORY_SEPARATOR . 'stdout.log', 'a'],
|
||||||
|
2 => ['file', $this->directory . DIRECTORY_SEPARATOR . 'stderr.log', 'a'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->process = proc_open($command, $descriptorSpec, $pipes, $this->directory, $environment);
|
||||||
|
if (!is_resource($this->process)) {
|
||||||
|
throw new RuntimeException('Unable to start fake Plate Recognizer server.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($pipes[0]) && is_resource($pipes[0])) {
|
||||||
|
fclose($pipes[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function waitUntilReady(): void
|
||||||
|
{
|
||||||
|
$deadline = microtime(true) + 5;
|
||||||
|
$lastError = 'Timed out waiting for fake Plate Recognizer.';
|
||||||
|
|
||||||
|
while (microtime(true) < $deadline) {
|
||||||
|
$curl = curl_init($this->url() . '/health');
|
||||||
|
if ($curl === false) {
|
||||||
|
throw new RuntimeException('Unable to initialize fake Plate Recognizer health check.');
|
||||||
|
}
|
||||||
|
|
||||||
|
curl_setopt_array($curl, [
|
||||||
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
|
CURLOPT_CONNECTTIMEOUT_MS => 250,
|
||||||
|
CURLOPT_TIMEOUT_MS => 500,
|
||||||
|
]);
|
||||||
|
$body = curl_exec($curl);
|
||||||
|
$status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
|
||||||
|
if ($body === false) {
|
||||||
|
$lastError = curl_error($curl);
|
||||||
|
}
|
||||||
|
curl_close($curl);
|
||||||
|
|
||||||
|
if ($status === 200 && $body === 'ok') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
usleep(100000);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new RuntimeException($lastError);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function removeDirectory(string $directory): void
|
||||||
|
{
|
||||||
|
if (!is_dir($directory)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $path) {
|
||||||
|
if (is_file($path)) {
|
||||||
|
@unlink($path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@rmdir($directory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanner_lpr_api_get_env(string $key): ?string
|
||||||
|
{
|
||||||
|
$value = getenv($key);
|
||||||
|
|
||||||
|
return $value === false ? null : (string)$value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanner_lpr_api_set_env(string $key, ?string $value): void
|
||||||
|
{
|
||||||
|
if ($value === null) {
|
||||||
|
putenv($key);
|
||||||
|
unset($_ENV[$key], $_SERVER[$key]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
putenv($key . '=' . $value);
|
||||||
|
$_ENV[$key] = $value;
|
||||||
|
$_SERVER[$key] = $value;
|
||||||
|
}
|
||||||
@@ -264,6 +264,55 @@ it('derives allowed services from published v2 config task snapshots when no ses
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps questions visible but disables machine services and tasks when machine wash is globally disabled', function (): void {
|
||||||
|
$group = api_fixtures()->createGroup([], [
|
||||||
|
'list_own_department_selfserve_vehicle_conditions',
|
||||||
|
]);
|
||||||
|
$scenario = api_fixtures()->createSelfServeScenario([
|
||||||
|
'customer' => ['group_id' => $group['id']],
|
||||||
|
'department_selfserve_enabled' => true,
|
||||||
|
'lane_selfserve_enabled' => true,
|
||||||
|
'machine_wash_enabled' => false,
|
||||||
|
]);
|
||||||
|
$headers = api_fixtures()->bearerHeaders(
|
||||||
|
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||||
|
);
|
||||||
|
$laneId = (int)$scenario['lane']['id'];
|
||||||
|
$reg = (string)$scenario['vehicle']['reg'];
|
||||||
|
$productId = (int)$scenario['product']['id'];
|
||||||
|
$machineTaskId = (int)$scenario['tasks'][1]['id'];
|
||||||
|
|
||||||
|
$allowedResponse = api_client()
|
||||||
|
->get(
|
||||||
|
'/department/selfserve/vehicle/allowed?lane_id=' . $laneId
|
||||||
|
. '®=' . urlencode($reg)
|
||||||
|
. '&vehicle_type=' . $productId,
|
||||||
|
$headers
|
||||||
|
)
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertSuccess(true);
|
||||||
|
|
||||||
|
expect($allowedResponse->data()['questions'] ?? [])->not->toBeEmpty()
|
||||||
|
->and($allowedResponse->data()['allowed_services'] ?? [])->not->toContain('MACHINE')
|
||||||
|
->and($allowedResponse->data()['machine_available'] ?? null)->toBeFalse()
|
||||||
|
->and($allowedResponse->data()['machine_wash_enabled'] ?? null)->toBeFalse()
|
||||||
|
->and($allowedResponse->data()['allowed'] ?? null)->toBeFalse();
|
||||||
|
|
||||||
|
foreach ($allowedResponse->data()['tasks'] ?? [] as $task) {
|
||||||
|
expect($task['services'] ?? [])->not->toContain('MACHINE');
|
||||||
|
}
|
||||||
|
|
||||||
|
$serviceResponse = api_client()
|
||||||
|
->post('/modules/self-serve/lane/services/allowed', [
|
||||||
|
'lane_id' => $laneId,
|
||||||
|
'task_ids' => [$machineTaskId],
|
||||||
|
], $headers)
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertSuccess(true);
|
||||||
|
|
||||||
|
expect($serviceResponse->data()['allowed_services'] ?? [])->not->toContain('MACHINE');
|
||||||
|
});
|
||||||
|
|
||||||
it('keeps long generated task descriptions when refreshing vehicle eligibility snapshots', function (): void {
|
it('keeps long generated task descriptions when refreshing vehicle eligibility snapshots', function (): void {
|
||||||
$group = api_fixtures()->createGroup([], [
|
$group = api_fixtures()->createGroup([], [
|
||||||
'list_own_department_selfserve_vehicle_conditions',
|
'list_own_department_selfserve_vehicle_conditions',
|
||||||
|
|||||||
@@ -44,11 +44,13 @@ it('lists subusers when an existing grant has legacy zero permissions', function
|
|||||||
expect($matchingSubusers[0]['permissions'] ?? null)->toBe([]);
|
expect($matchingSubusers[0]['permissions'] ?? null)->toBe([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses the same password policy for subuser setup and password auth', function (): void {
|
it('enforces the password policy for setup without rejecting legacy valid passwords at login', function (): void {
|
||||||
api_test_covers('POST /subusers/setup', 'failure');
|
api_test_covers('POST /subusers/setup', 'failure');
|
||||||
api_test_covers('POST /subusers/auth/password', 'failure');
|
api_test_covers('POST /subusers/auth/password', 'happy');
|
||||||
|
|
||||||
$subuser = api_fixtures()->createSubuser();
|
$subuser = api_fixtures()->createSubuser([
|
||||||
|
'password_plaintext' => 'invalidpassword',
|
||||||
|
]);
|
||||||
|
|
||||||
$setupResponse = api_client()->post('/subusers/setup', [
|
$setupResponse = api_client()->post('/subusers/setup', [
|
||||||
'token' => 'policy-test-token',
|
'token' => 'policy-test-token',
|
||||||
@@ -68,10 +70,114 @@ it('uses the same password policy for subuser setup and password auth', function
|
|||||||
->assertMessage(SUBUSER_PASSWORD_POLICY_MESSAGE);
|
->assertMessage(SUBUSER_PASSWORD_POLICY_MESSAGE);
|
||||||
|
|
||||||
$authResponse
|
$authResponse
|
||||||
->assertStatus(400)
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($authResponse->data()['session'] ?? null)->toBeString();
|
||||||
|
(new \objects\subusers_o())->invalidateSessionToken((string)$authResponse->data()['session']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns a generic error for invalid subuser credentials', function (): void {
|
||||||
|
api_test_covers('POST /subusers/auth/password', 'failure');
|
||||||
|
|
||||||
|
$response = api_client()->post('/subusers/auth/password', [
|
||||||
|
'subuser_id' => 999999999,
|
||||||
|
'password' => 'whatever',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(401)
|
||||||
->assertEnvelope()
|
->assertEnvelope()
|
||||||
->assertSuccess(false)
|
->assertSuccess(false)
|
||||||
->assertMessage(SUBUSER_PASSWORD_POLICY_MESSAGE);
|
->assertMessage('Invalid credentials');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires subuser management access before exposing permission nodes', function (): void {
|
||||||
|
api_test_covers('GET /subusers/permission-nodes', 'auth');
|
||||||
|
|
||||||
|
$unauthenticated = api_client()->get('/subusers/permission-nodes');
|
||||||
|
$unauthenticated
|
||||||
|
->assertStatus(401)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false);
|
||||||
|
|
||||||
|
$session = api_fixtures()->createUserSession(['list_own_subusers']);
|
||||||
|
$authorized = api_client()->get('/subusers/permission-nodes', $session['headers']);
|
||||||
|
$authorized
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
expect($authorized->data())->toBeArray()->not->toBeEmpty();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects customer subuser listing without own-scope permission', function (): void {
|
||||||
|
api_test_covers('GET /subusers', 'auth');
|
||||||
|
|
||||||
|
$session = api_fixtures()->createUserSession(['user']);
|
||||||
|
$response = api_client()->get('/subusers?page=1&limit=5', $session['headers']);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replaces older setup tokens when a new setup token is generated', function (): void {
|
||||||
|
$subuser = api_fixtures()->createSubuser([
|
||||||
|
'password_plaintext' => null,
|
||||||
|
'name' => 'Pending Setup Driver',
|
||||||
|
]);
|
||||||
|
$subuserObject = (new \objects\subusers_o())->select((int)$subuser['id']);
|
||||||
|
$subuserObject->getObjectProperties();
|
||||||
|
|
||||||
|
$firstToken = $subuserObject->generateSetupToken();
|
||||||
|
$secondToken = $subuserObject->generateSetupToken();
|
||||||
|
|
||||||
|
try {
|
||||||
|
expect((new \objects\subusers_o())->getSubuserBySetupToken($firstToken))->toBeNull();
|
||||||
|
expect((new \objects\subusers_o())->getSubuserBySetupToken($secondToken))->not->toBeNull();
|
||||||
|
} finally {
|
||||||
|
(new \objects\subusers_o())->invalidateSetupToken($secondToken);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates setup identifiers before setting the driver password', function (): void {
|
||||||
|
api_test_covers('POST /subusers/setup', 'failure');
|
||||||
|
|
||||||
|
$existing = api_fixtures()->createSubuser([
|
||||||
|
'username' => 'existing-driver-setup',
|
||||||
|
]);
|
||||||
|
$pending = api_fixtures()->createSubuser([
|
||||||
|
'password_plaintext' => null,
|
||||||
|
'username' => 'pending-driver-setup',
|
||||||
|
'name' => 'Pending Driver',
|
||||||
|
]);
|
||||||
|
$pendingObject = (new \objects\subusers_o())->select((int)$pending['id']);
|
||||||
|
$pendingObject->getObjectProperties();
|
||||||
|
$token = $pendingObject->generateSetupToken();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = api_client()->post('/subusers/setup', [
|
||||||
|
'token' => $token,
|
||||||
|
'name' => 'Pending Driver',
|
||||||
|
'username' => $existing['username'],
|
||||||
|
'password' => 'ValidPass123',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Account already exists with this username');
|
||||||
|
|
||||||
|
$row = api_fixtures()->fetchRowById('subusers', (int)$pending['id']);
|
||||||
|
expect($row['password'] ?? null)->toBeNull();
|
||||||
|
expect((new \objects\subusers_o())->getSubuserBySetupToken($token))->not->toBeNull();
|
||||||
|
} finally {
|
||||||
|
(new \objects\subusers_o())->invalidateSetupToken($token);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('lists chauffeur grants across customers for superusers', function (): void {
|
it('lists chauffeur grants across customers for superusers', function (): void {
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
usesApiSuite();
|
||||||
|
|
||||||
|
it('loads a single department overview for superusers without department scoped access', function (): void {
|
||||||
|
api_test_covers('GET /superuser/departments/{id}/overview', 'happy');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment([
|
||||||
|
'name' => 'Overview Department ' . uniqid('', false),
|
||||||
|
'description' => 'Department overview fixture',
|
||||||
|
'economic_department_id' => 42,
|
||||||
|
'visible' => 1,
|
||||||
|
]);
|
||||||
|
$departmentRow = api_fixtures()->fetchRowById('departments', (int)$department['id']);
|
||||||
|
$session = api_fixtures()->createUserSession([
|
||||||
|
'superuser_fetch_department',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = api_client()->get(
|
||||||
|
'/superuser/departments/' . $department['id'] . '/overview?date=2026-07-06&date_to=2026-07-06',
|
||||||
|
$session['headers']
|
||||||
|
);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$payload = $response->data();
|
||||||
|
|
||||||
|
expect($payload)->toBeArray();
|
||||||
|
expect($payload['department'])
|
||||||
|
->toBeArray()
|
||||||
|
->toHaveKey('id', (int)$department['id'])
|
||||||
|
->toHaveKey('name', $departmentRow['name'])
|
||||||
|
->toHaveKey('description', 'Department overview fixture')
|
||||||
|
->toHaveKey('economic_department_id', 42);
|
||||||
|
|
||||||
|
expect($payload['overview'])
|
||||||
|
->toBeArray()
|
||||||
|
->toHaveKey('department_ids', [(int)$department['id']])
|
||||||
|
->toHaveKey('date', '2026-07-06')
|
||||||
|
->toHaveKey('date_to', '2026-07-06');
|
||||||
|
|
||||||
|
expect($payload['overview']['metrics'])
|
||||||
|
->toBeArray()
|
||||||
|
->toHaveKeys([
|
||||||
|
'bookings',
|
||||||
|
'complaints',
|
||||||
|
'night_washes',
|
||||||
|
'revenue',
|
||||||
|
'washes',
|
||||||
|
'products_sold',
|
||||||
|
'transactions',
|
||||||
|
'water_usage',
|
||||||
|
'overtime',
|
||||||
|
]);
|
||||||
|
expect($payload['overview']['metrics']['revenue']['state'])->toBe('ready');
|
||||||
|
expect($payload['overview']['metrics']['revenue']['value'])->toBe(0);
|
||||||
|
expect($payload['overview']['products'])->toBeArray();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects superuser department overview requests without permission or valid input', function (): void {
|
||||||
|
api_test_covers('GET /superuser/departments/{id}/overview', 'auth');
|
||||||
|
api_test_covers('GET /superuser/departments/{id}/overview', 'failure');
|
||||||
|
|
||||||
|
$department = api_fixtures()->createDepartment();
|
||||||
|
$unauthorizedSession = api_fixtures()->createUserSession([]);
|
||||||
|
|
||||||
|
api_client()->get(
|
||||||
|
'/superuser/departments/' . $department['id'] . '/overview?date=2026-07-06',
|
||||||
|
$unauthorizedSession['headers']
|
||||||
|
)
|
||||||
|
->assertStatus(403)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMissingPermissions(['superuser_fetch_department']);
|
||||||
|
|
||||||
|
$session = api_fixtures()->createUserSession(['superuser_fetch_department']);
|
||||||
|
|
||||||
|
api_client()->get('/superuser/departments/bad/overview?date=2026-07-06', $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Parameter id must be a positive integer');
|
||||||
|
|
||||||
|
api_client()->get('/superuser/departments/' . $department['id'] . '/overview', $session['headers'])
|
||||||
|
->assertStatus(400)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Missing required parameters: date');
|
||||||
|
|
||||||
|
api_client()->get('/superuser/departments/99999999/overview?date=2026-07-06', $session['headers'])
|
||||||
|
->assertStatus(404)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess(false)
|
||||||
|
->assertMessage('Department not found');
|
||||||
|
});
|
||||||
@@ -4,6 +4,106 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
usesApiSuite();
|
usesApiSuite();
|
||||||
|
|
||||||
|
it('defaults wash subscriptions to false when a customer creates a vehicle without the field', function (): void {
|
||||||
|
api_test_covers('POST /vehicles', 'happy');
|
||||||
|
|
||||||
|
$session = api_fixtures()->createUserSession(['add_vehicle']);
|
||||||
|
|
||||||
|
$response = api_client()->post('/vehicles', [
|
||||||
|
'type' => 53,
|
||||||
|
'reg' => 'DEFAULTOWN',
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$vehicleId = (int)($response->data()['id'] ?? 0);
|
||||||
|
expect($vehicleId)->toBeGreaterThan(0);
|
||||||
|
|
||||||
|
$row = api_fixtures()->fetchRowById('customer_vehicles', $vehicleId);
|
||||||
|
expect($row)->not->toBeNull();
|
||||||
|
expect((int)$row['customer_id'])->toBe((int)$session['user']['customer_number']);
|
||||||
|
expect((int)$row['wash_subscription'])->toBe(0);
|
||||||
|
expect($response->data())->toMatchArray([
|
||||||
|
'id' => $vehicleId,
|
||||||
|
'customer_id' => (int)$session['user']['customer_number'],
|
||||||
|
'reg' => 'DEFAULTOWN',
|
||||||
|
'wash_subscription' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
api_fixtures()->cleanupDeleteById('customer_vehicles', $vehicleId);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('customer_vehicle_subscription_versions', ['vehicle_id' => $vehicleId]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults wash subscriptions to false when a superuser creates a vehicle for another customer without the field', function (): void {
|
||||||
|
api_test_covers('POST /vehicles', 'happy');
|
||||||
|
|
||||||
|
$targetCustomer = api_fixtures()->createUser(['display_name' => 'Vehicle Default Target Customer']);
|
||||||
|
$session = api_fixtures()->createUserSession(['add_vehicle_other']);
|
||||||
|
|
||||||
|
$response = api_client()->post('/vehicles', [
|
||||||
|
'customer_id' => $targetCustomer['customer_number'],
|
||||||
|
'type' => 53,
|
||||||
|
'reg' => 'DEFAULTSU',
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$vehicleId = (int)($response->data()['id'] ?? 0);
|
||||||
|
expect($vehicleId)->toBeGreaterThan(0);
|
||||||
|
|
||||||
|
$row = api_fixtures()->fetchRowById('customer_vehicles', $vehicleId);
|
||||||
|
expect($row)->not->toBeNull();
|
||||||
|
expect((int)$row['customer_id'])->toBe((int)$targetCustomer['customer_number']);
|
||||||
|
expect((int)$row['wash_subscription'])->toBe(0);
|
||||||
|
expect($response->data())->toMatchArray([
|
||||||
|
'id' => $vehicleId,
|
||||||
|
'customer_id' => (int)$targetCustomer['customer_number'],
|
||||||
|
'reg' => 'DEFAULTSU',
|
||||||
|
'wash_subscription' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
api_fixtures()->cleanupDeleteById('customer_vehicles', $vehicleId);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('customer_vehicle_subscription_versions', ['vehicle_id' => $vehicleId]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still honors an explicit wash subscription true value on vehicle create', function (): void {
|
||||||
|
api_test_covers('POST /vehicles', 'happy');
|
||||||
|
|
||||||
|
$session = api_fixtures()->createUserSession(['add_vehicle']);
|
||||||
|
|
||||||
|
$response = api_client()->post('/vehicles', [
|
||||||
|
'type' => 53,
|
||||||
|
'reg' => 'EXPLICITON',
|
||||||
|
'wash_subscription' => true,
|
||||||
|
], $session['headers']);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertStatus(200)
|
||||||
|
->assertEnvelope()
|
||||||
|
->assertSuccess();
|
||||||
|
|
||||||
|
$vehicleId = (int)($response->data()['id'] ?? 0);
|
||||||
|
expect($vehicleId)->toBeGreaterThan(0);
|
||||||
|
|
||||||
|
$row = api_fixtures()->fetchRowById('customer_vehicles', $vehicleId);
|
||||||
|
expect($row)->not->toBeNull();
|
||||||
|
expect((int)$row['wash_subscription'])->toBe(1);
|
||||||
|
expect($response->data())->toMatchArray([
|
||||||
|
'id' => $vehicleId,
|
||||||
|
'reg' => 'EXPLICITON',
|
||||||
|
'wash_subscription' => true,
|
||||||
|
]);
|
||||||
|
|
||||||
|
api_fixtures()->cleanupDeleteById('customer_vehicles', $vehicleId);
|
||||||
|
api_fixtures()->cleanupDeleteWhere('customer_vehicle_subscription_versions', ['vehicle_id' => $vehicleId]);
|
||||||
|
});
|
||||||
|
|
||||||
it('returns the newest vehicle last_order_id that still has order items', function (): void {
|
it('returns the newest vehicle last_order_id that still has order items', function (): void {
|
||||||
api_test_covers('GET /vehicles', 'happy');
|
api_test_covers('GET /vehicles', 'happy');
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ return [
|
|||||||
'GET /branding',
|
'GET /branding',
|
||||||
'POST /branding',
|
'POST /branding',
|
||||||
'PUT /branding',
|
'PUT /branding',
|
||||||
|
'GET /superuser/departments/{id}/overview',
|
||||||
'PUT /superuser/department/branding',
|
'PUT /superuser/department/branding',
|
||||||
'POST /bird/voice/calls/webhook/inbound',
|
'POST /bird/voice/calls/webhook/inbound',
|
||||||
],
|
],
|
||||||
@@ -26,6 +27,7 @@ return [
|
|||||||
'GET /ping',
|
'GET /ping',
|
||||||
'PUT /order',
|
'PUT /order',
|
||||||
'GET /orders/reference-suggestions',
|
'GET /orders/reference-suggestions',
|
||||||
|
'POST /modules/scanner/lpr',
|
||||||
],
|
],
|
||||||
'happy_only_operations' => [
|
'happy_only_operations' => [
|
||||||
'GET /ping',
|
'GET /ping',
|
||||||
|
|||||||
@@ -24,6 +24,28 @@ final class ApiClient
|
|||||||
return $this->request('POST', $path, $payload, $headers);
|
return $this->request('POST', $path, $payload, $headers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, scalar|null> $fields
|
||||||
|
* @param array<string, string|array{path:string,mime?:string,name?:string}> $files
|
||||||
|
* @param array<string, string> $headers
|
||||||
|
*/
|
||||||
|
public function postMultipart(string $path, array $fields = [], array $files = [], array $headers = []): ApiResponse
|
||||||
|
{
|
||||||
|
$postFields = [];
|
||||||
|
foreach ($fields as $name => $value) {
|
||||||
|
$postFields[$name] = $value === null ? '' : (string)$value;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($files as $name => $file) {
|
||||||
|
$filePath = is_array($file) ? (string)$file['path'] : (string)$file;
|
||||||
|
$mime = is_array($file) ? (string)($file['mime'] ?? 'application/octet-stream') : 'application/octet-stream';
|
||||||
|
$filename = is_array($file) ? (string)($file['name'] ?? basename($filePath)) : basename($filePath);
|
||||||
|
$postFields[$name] = new \CURLFile($filePath, $mime, $filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->requestMultipart('POST', $path, $postFields, $headers);
|
||||||
|
}
|
||||||
|
|
||||||
public function put(string $path, ?array $payload = null, array $headers = []): ApiResponse
|
public function put(string $path, ?array $payload = null, array $headers = []): ApiResponse
|
||||||
{
|
{
|
||||||
return $this->request('PUT', $path, $payload, $headers);
|
return $this->request('PUT', $path, $payload, $headers);
|
||||||
@@ -102,4 +124,61 @@ final class ApiClient
|
|||||||
|
|
||||||
return new ApiResponse($status, $responseHeaders, $decoded, (string)$body);
|
return new ApiResponse($status, $responseHeaders, $decoded, (string)$body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string|\CURLFile> $postFields
|
||||||
|
* @param array<string, string> $headers
|
||||||
|
*/
|
||||||
|
private function requestMultipart(string $method, string $path, array $postFields, array $headers = []): ApiResponse
|
||||||
|
{
|
||||||
|
$curl = curl_init();
|
||||||
|
if ($curl === false) {
|
||||||
|
throw new RuntimeException('Unable to initialize cURL for API tests.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$timeoutSeconds = (int)(getenv('API_TEST_REQUEST_TIMEOUT') ?: self::DEFAULT_TIMEOUT_SECONDS);
|
||||||
|
if ($timeoutSeconds <= 0) {
|
||||||
|
$timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$responseHeaders = [];
|
||||||
|
$normalizedHeaders = [];
|
||||||
|
foreach ($headers as $name => $value) {
|
||||||
|
$normalizedHeaders[] = $name . ': ' . $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
curl_setopt_array($curl, [
|
||||||
|
CURLOPT_URL => rtrim($this->baseUrl, '/') . $path,
|
||||||
|
CURLOPT_CUSTOMREQUEST => $method,
|
||||||
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
|
CURLOPT_HEADER => false,
|
||||||
|
CURLOPT_HTTPHEADER => $normalizedHeaders,
|
||||||
|
CURLOPT_CONNECTTIMEOUT => $timeoutSeconds,
|
||||||
|
CURLOPT_TIMEOUT => $timeoutSeconds,
|
||||||
|
CURLOPT_POSTFIELDS => $postFields,
|
||||||
|
CURLOPT_HEADERFUNCTION => static function ($curlHandle, string $headerLine) use (&$responseHeaders): int {
|
||||||
|
$length = strlen($headerLine);
|
||||||
|
$parts = explode(':', $headerLine, 2);
|
||||||
|
if (count($parts) === 2) {
|
||||||
|
$responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $length;
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
$body = curl_exec($curl);
|
||||||
|
if ($body === false) {
|
||||||
|
$error = curl_error($curl);
|
||||||
|
curl_close($curl);
|
||||||
|
throw new RuntimeException('API multipart request failed: ' . $error);
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
|
||||||
|
curl_close($curl);
|
||||||
|
|
||||||
|
$decoded = json_decode($body, true);
|
||||||
|
|
||||||
|
return new ApiResponse($status, $responseHeaders, $decoded, (string)$body);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -175,6 +175,32 @@ final class ApiFixtures
|
|||||||
$this->cleanup->add(fn() => $this->deleteById('department_variables', $variableId));
|
$this->cleanup->add(fn() => $this->deleteById('department_variables', $variableId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function setDepartmentShellyTransportMode(int $departmentId, string $mode): void
|
||||||
|
{
|
||||||
|
if ($departmentId <= 0) {
|
||||||
|
throw new RuntimeException('Department Shelly transport fixtures require a positive department id.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$mode = strtolower(trim($mode));
|
||||||
|
if (!in_array($mode, ['cloud', 'gateway'], true)) {
|
||||||
|
throw new RuntimeException('Invalid Shelly transport fixture mode.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$conditions = [
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'variable' => 'shelly_transport_mode',
|
||||||
|
];
|
||||||
|
$this->deleteWhereIfPossible('department_variables', $conditions);
|
||||||
|
$this->cleanupDeleteWhere('department_variables', $conditions);
|
||||||
|
|
||||||
|
$variableId = $this->insertRowWithExistingColumns('department_variables', [
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'variable' => 'shelly_transport_mode',
|
||||||
|
'value' => $mode,
|
||||||
|
]);
|
||||||
|
$this->cleanup->add(fn() => $this->deleteById('department_variables', $variableId));
|
||||||
|
}
|
||||||
|
|
||||||
public function setLaneSelfServeEnabled(int $laneId, bool $enabled): void
|
public function setLaneSelfServeEnabled(int $laneId, bool $enabled): void
|
||||||
{
|
{
|
||||||
if ($laneId <= 0) {
|
if ($laneId <= 0) {
|
||||||
@@ -544,6 +570,11 @@ final class ApiFixtures
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->setModuleConfig('selfserve', 'enabled', 'true');
|
$this->setModuleConfig('selfserve', 'enabled', 'true');
|
||||||
|
$this->setModuleConfig(
|
||||||
|
'selfserve',
|
||||||
|
'machine_wash_enabled',
|
||||||
|
(bool)($overrides['machine_wash_enabled'] ?? true) ? 'true' : 'false'
|
||||||
|
);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'department' => $department,
|
'department' => $department,
|
||||||
@@ -885,14 +916,16 @@ final class ApiFixtures
|
|||||||
public function createSubuser(array $attributes = []): array
|
public function createSubuser(array $attributes = []): array
|
||||||
{
|
{
|
||||||
$username = (string)($attributes['username'] ?? ('api-subuser-' . strtolower($this->uniqueSuffix())));
|
$username = (string)($attributes['username'] ?? ('api-subuser-' . strtolower($this->uniqueSuffix())));
|
||||||
$passwordPlaintext = (string)($attributes['password_plaintext'] ?? 'Secret123!');
|
$passwordPlaintext = array_key_exists('password_plaintext', $attributes)
|
||||||
|
? $attributes['password_plaintext']
|
||||||
|
: 'Secret123!';
|
||||||
$name = (string)($attributes['name'] ?? 'API Subuser');
|
$name = (string)($attributes['name'] ?? 'API Subuser');
|
||||||
$email = (string)($attributes['email'] ?? ($username . '@example.test'));
|
$email = (string)($attributes['email'] ?? ($username . '@example.test'));
|
||||||
$now = $this->now();
|
$now = $this->now();
|
||||||
|
|
||||||
$subuserId = $this->insertRow('subusers', [
|
$subuserId = $this->insertRow('subusers', [
|
||||||
'username' => $username,
|
'username' => $username,
|
||||||
'password' => password_hash($passwordPlaintext, PASSWORD_DEFAULT),
|
'password' => $passwordPlaintext === null ? null : password_hash((string)$passwordPlaintext, PASSWORD_DEFAULT),
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'email' => $email,
|
'email' => $email,
|
||||||
'phone_country_code' => 45,
|
'phone_country_code' => 45,
|
||||||
@@ -1033,6 +1066,42 @@ final class ApiFixtures
|
|||||||
return $token;
|
return $token;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $attributes
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function createPasskey(array $attributes): array
|
||||||
|
{
|
||||||
|
$userId = (int)($attributes['user_id'] ?? 0);
|
||||||
|
if ($userId <= 0) {
|
||||||
|
throw new RuntimeException('Passkey fixtures require user_id.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$credentialId = (string)($attributes['credential_id'] ?? ('credential-' . strtolower($this->uniqueSuffix())));
|
||||||
|
$passkeyId = $this->insertRow('passkeys', [
|
||||||
|
'user_id' => $userId,
|
||||||
|
'is_subuser' => !empty($attributes['is_subuser']) ? 1 : 0,
|
||||||
|
'credential_id' => $credentialId,
|
||||||
|
'public_key' => $attributes['public_key'] ?? str_repeat('A', 64),
|
||||||
|
'algorithm' => $attributes['algorithm'] ?? 'ES256',
|
||||||
|
'transports' => json_encode($attributes['transports'] ?? ['internal'], JSON_UNESCAPED_SLASHES),
|
||||||
|
'sign_count' => (int)($attributes['sign_count'] ?? 0),
|
||||||
|
'backup_state' => json_encode($attributes['backup_state'] ?? new \stdClass(), JSON_UNESCAPED_SLASHES),
|
||||||
|
'name' => $attributes['name'] ?? 'API test passkey',
|
||||||
|
'created_at' => $attributes['created_at'] ?? $this->now(),
|
||||||
|
'updated_at' => $attributes['updated_at'] ?? $this->now(),
|
||||||
|
'deleted_at' => $attributes['deleted_at'] ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->cleanup->add(fn() => $this->deleteById('passkeys', $passkeyId));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $passkeyId,
|
||||||
|
'credential_id' => $credentialId,
|
||||||
|
'user_id' => $userId,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function addCustomerAttribute(int $userId, string $attribute): int
|
public function addCustomerAttribute(int $userId, string $attribute): int
|
||||||
{
|
{
|
||||||
$attributeId = $this->insertRow('customer_attributes', [
|
$attributeId = $this->insertRow('customer_attributes', [
|
||||||
@@ -1258,6 +1327,10 @@ final class ApiFixtures
|
|||||||
*/
|
*/
|
||||||
public function createClaimedEdgeGateway(array $attributes): array
|
public function createClaimedEdgeGateway(array $attributes): array
|
||||||
{
|
{
|
||||||
|
if (class_exists(\classes\edge_gateway_schema_bootstrap::class)) {
|
||||||
|
\classes\edge_gateway_schema_bootstrap::ensureTables();
|
||||||
|
}
|
||||||
|
|
||||||
$departmentId = (int)($attributes['department_id'] ?? 0);
|
$departmentId = (int)($attributes['department_id'] ?? 0);
|
||||||
if ($departmentId <= 0) {
|
if ($departmentId <= 0) {
|
||||||
throw new RuntimeException('Claimed edge gateways require department_id.');
|
throw new RuntimeException('Claimed edge gateways require department_id.');
|
||||||
@@ -1312,6 +1385,7 @@ final class ApiFixtures
|
|||||||
$this->deleteWhere('edge_gateway_operation_events', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_operation_events', ['gateway_id' => $gatewayId]);
|
||||||
$this->deleteWhere('edge_gateway_operations', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_operations', ['gateway_id' => $gatewayId]);
|
||||||
$this->deleteWhere('edge_gateway_command_jobs', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_command_jobs', ['gateway_id' => $gatewayId]);
|
||||||
|
$this->deleteWhere('edge_gateway_expected_relay_states', ['gateway_id' => $gatewayId]);
|
||||||
$this->deleteWhere('edge_gateway_device_inventory', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_device_inventory', ['gateway_id' => $gatewayId]);
|
||||||
$this->deleteWhere('edge_gateway_relay_bindings', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_relay_bindings', ['gateway_id' => $gatewayId]);
|
||||||
$this->deleteWhere('edge_gateway_log_entries', ['gateway_id' => $gatewayId]);
|
$this->deleteWhere('edge_gateway_log_entries', ['gateway_id' => $gatewayId]);
|
||||||
@@ -1329,6 +1403,52 @@ final class ApiFixtures
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $attributes
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function createEdgeRelayBinding(array $attributes): array
|
||||||
|
{
|
||||||
|
if (class_exists(\classes\edge_gateway_schema_bootstrap::class)) {
|
||||||
|
\classes\edge_gateway_schema_bootstrap::ensureTables();
|
||||||
|
}
|
||||||
|
|
||||||
|
$gatewayId = (int)($attributes['gateway_id'] ?? 0);
|
||||||
|
$departmentId = (int)($attributes['department_id'] ?? 0);
|
||||||
|
$relayId = trim((string)($attributes['relay_id'] ?? ''));
|
||||||
|
if ($gatewayId <= 0 || $departmentId <= 0 || $relayId === '') {
|
||||||
|
throw new RuntimeException('Edge relay bindings require gateway_id, department_id, and relay_id.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$bindingId = $this->insertRow('edge_gateway_relay_bindings', [
|
||||||
|
'gateway_id' => $gatewayId,
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
'device_id' => (string)($attributes['device_id'] ?? $relayId),
|
||||||
|
'local_ip' => $attributes['local_ip'] ?? '10.31.0.' . max(2, $gatewayId % 250),
|
||||||
|
'channel' => $attributes['channel'] ?? 0,
|
||||||
|
'fallback_mode' => (string)($attributes['fallback_mode'] ?? 'LOCAL_ONLY'),
|
||||||
|
'binding_source' => (string)($attributes['binding_source'] ?? 'TEST'),
|
||||||
|
'approved_by' => $attributes['approved_by'] ?? null,
|
||||||
|
'approved_at' => $attributes['approved_at'] ?? $this->now(),
|
||||||
|
'metadata_json' => isset($attributes['metadata']) && is_array($attributes['metadata'])
|
||||||
|
? (array)$attributes['metadata']
|
||||||
|
: ['device_type' => 'SHELLY_SWITCH'],
|
||||||
|
'created_at' => $attributes['created_at'] ?? $this->now(),
|
||||||
|
'updated_at' => $attributes['updated_at'] ?? $this->now(),
|
||||||
|
'deleted_at' => $attributes['deleted_at'] ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->cleanup->add(fn() => $this->deleteById('edge_gateway_relay_bindings', $bindingId));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $bindingId,
|
||||||
|
'gateway_id' => $gatewayId,
|
||||||
|
'department_id' => $departmentId,
|
||||||
|
'relay_id' => $relayId,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $attributes
|
* @param array<string, mixed> $attributes
|
||||||
* @return array<string, mixed>
|
* @return array<string, mixed>
|
||||||
@@ -1628,6 +1748,7 @@ final class ApiFixtures
|
|||||||
$this->deleteWhereIfPossible('tokens', ['user_id' => $userId]);
|
$this->deleteWhereIfPossible('tokens', ['user_id' => $userId]);
|
||||||
$this->deleteWhereIfPossible('user_key_value_pairs', ['user_id' => $userId]);
|
$this->deleteWhereIfPossible('user_key_value_pairs', ['user_id' => $userId]);
|
||||||
$this->deleteWhereIfPossible('price_overrides', ['user_id' => $userId]);
|
$this->deleteWhereIfPossible('price_overrides', ['user_id' => $userId]);
|
||||||
|
$this->deleteWhereIfPossible('limited_backoffice_employees', ['user_id' => $userId]);
|
||||||
$this->deleteWhereIfPossible('customer_default_department', ['customer_number' => $customerNumber]);
|
$this->deleteWhereIfPossible('customer_default_department', ['customer_number' => $customerNumber]);
|
||||||
$this->deleteWhereIfPossible('customer_fixed_pricing', ['customer_number' => $customerNumber]);
|
$this->deleteWhereIfPossible('customer_fixed_pricing', ['customer_number' => $customerNumber]);
|
||||||
$this->deleteWhereIfPossible('customer_fixed_pricing_versions', ['customer_number' => $customerNumber]);
|
$this->deleteWhereIfPossible('customer_fixed_pricing_versions', ['customer_number' => $customerNumber]);
|
||||||
|
|||||||
@@ -111,6 +111,46 @@ CREATE TABLE IF NOT EXISTS `department_variables` (
|
|||||||
KEY `idx_department_variables_department_id` (`department_id`),
|
KEY `idx_department_variables_department_id` (`department_id`),
|
||||||
KEY `idx_department_variables_variable` (`variable`)
|
KEY `idx_department_variables_variable` (`variable`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
SQL,
|
||||||
|
'department_daily_reports' => <<<'SQL'
|
||||||
|
CREATE TABLE IF NOT EXISTS `department_daily_reports` (
|
||||||
|
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
`department_id` INT NOT NULL,
|
||||||
|
`water_usage` INT NOT NULL DEFAULT 0,
|
||||||
|
`water_usage_morning` INT NOT NULL DEFAULT 0,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`filled_by` INT NOT NULL DEFAULT 0,
|
||||||
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_department_daily_reports_department_id` (`department_id`),
|
||||||
|
KEY `idx_department_daily_reports_created_at` (`created_at`),
|
||||||
|
KEY `idx_department_daily_reports_department_created_at` (`department_id`, `created_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
SQL,
|
||||||
|
'department_time_bookings_opening_hours' => <<<'SQL'
|
||||||
|
CREATE TABLE IF NOT EXISTS `department_time_bookings_opening_hours` (
|
||||||
|
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
`department` INT NOT NULL,
|
||||||
|
`monday_start` TIME NULL,
|
||||||
|
`monday_end` TIME NULL,
|
||||||
|
`tuesday_start` TIME NULL,
|
||||||
|
`tuesday_end` TIME NULL,
|
||||||
|
`wednesday_start` TIME NULL,
|
||||||
|
`wednesday_end` TIME NULL,
|
||||||
|
`thursday_start` TIME NULL,
|
||||||
|
`thursday_end` TIME NULL,
|
||||||
|
`friday_start` TIME NULL,
|
||||||
|
`friday_end` TIME NULL,
|
||||||
|
`saturday_start` TIME NULL,
|
||||||
|
`saturday_end` TIME NULL,
|
||||||
|
`sunday_start` TIME NULL,
|
||||||
|
`sunday_end` TIME NULL,
|
||||||
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_department_time_bookings_opening_hours_department` (`department`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
SQL,
|
SQL,
|
||||||
'department_gates' => <<<'SQL'
|
'department_gates' => <<<'SQL'
|
||||||
CREATE TABLE IF NOT EXISTS `department_gates` (
|
CREATE TABLE IF NOT EXISTS `department_gates` (
|
||||||
@@ -396,10 +436,8 @@ CREATE TABLE IF NOT EXISTS `products` (
|
|||||||
`max_quantity_per_order` INT NULL,
|
`max_quantity_per_order` INT NULL,
|
||||||
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
`deleted_at` DATETIME NULL,
|
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
KEY `idx_products_category` (`category`),
|
KEY `idx_products_category` (`category`)
|
||||||
KEY `idx_products_deleted_at` (`deleted_at`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
SQL,
|
SQL,
|
||||||
'department_categories' => <<<'SQL'
|
'department_categories' => <<<'SQL'
|
||||||
@@ -426,6 +464,25 @@ CREATE TABLE IF NOT EXISTS `product_department_prices` (
|
|||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `uniq_product_department_prices_lookup` (`department_id`, `product_id`)
|
UNIQUE KEY `uniq_product_department_prices_lookup` (`department_id`, `product_id`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
SQL,
|
||||||
|
'limited_backoffice_employees' => <<<'SQL'
|
||||||
|
CREATE TABLE IF NOT EXISTS `limited_backoffice_employees` (
|
||||||
|
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` INT NOT NULL,
|
||||||
|
`managed_group_id` INT NOT NULL,
|
||||||
|
`role_key` VARCHAR(64) NOT NULL,
|
||||||
|
`department_ids` LONGTEXT NOT NULL,
|
||||||
|
`created_by_user_id` INT NOT NULL,
|
||||||
|
`updated_by_user_id` INT NULL,
|
||||||
|
`deactivated_at` DATETIME NULL,
|
||||||
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uniq_limited_backoffice_employees_user_id` (`user_id`),
|
||||||
|
KEY `idx_limited_backoffice_employees_group_id` (`managed_group_id`),
|
||||||
|
KEY `idx_limited_backoffice_employees_role_key` (`role_key`),
|
||||||
|
KEY `idx_limited_backoffice_employees_deactivated_at` (`deactivated_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
SQL,
|
SQL,
|
||||||
'collected_order_invoices' => <<<'SQL'
|
'collected_order_invoices' => <<<'SQL'
|
||||||
CREATE TABLE IF NOT EXISTS `collected_order_invoices` (
|
CREATE TABLE IF NOT EXISTS `collected_order_invoices` (
|
||||||
@@ -649,6 +706,26 @@ CREATE TABLE IF NOT EXISTS `tokens` (
|
|||||||
KEY `idx_tokens_user_id` (`user_id`),
|
KEY `idx_tokens_user_id` (`user_id`),
|
||||||
KEY `idx_tokens_type` (`type`)
|
KEY `idx_tokens_type` (`type`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
SQL,
|
||||||
|
'passkeys' => <<<'SQL'
|
||||||
|
CREATE TABLE IF NOT EXISTS `passkeys` (
|
||||||
|
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` INT NOT NULL,
|
||||||
|
`is_subuser` TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
`credential_id` VARCHAR(4096) NOT NULL,
|
||||||
|
`public_key` TEXT NOT NULL,
|
||||||
|
`algorithm` VARCHAR(32) NOT NULL,
|
||||||
|
`transports` JSON NULL,
|
||||||
|
`sign_count` INT NOT NULL DEFAULT 0,
|
||||||
|
`backup_state` JSON NULL,
|
||||||
|
`name` VARCHAR(255) NULL,
|
||||||
|
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
`deleted_at` DATETIME NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_passkeys_user` (`user_id`, `is_subuser`),
|
||||||
|
KEY `idx_passkeys_deleted_at` (`deleted_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
SQL,
|
SQL,
|
||||||
'customer_attributes' => <<<'SQL'
|
'customer_attributes' => <<<'SQL'
|
||||||
CREATE TABLE IF NOT EXISTS `customer_attributes` (
|
CREATE TABLE IF NOT EXISTS `customer_attributes` (
|
||||||
|
|||||||
@@ -81,6 +81,21 @@ final class ApiTestRuntime
|
|||||||
return new ApiClient($this->baseUrl);
|
return new ApiClient($this->baseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function restartServer(): void
|
||||||
|
{
|
||||||
|
if ($this->usesExternalBaseUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->server !== null) {
|
||||||
|
$this->server->stop();
|
||||||
|
$this->server = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->baseUrl = self::DEFAULT_BASE_URL;
|
||||||
|
$this->internalServerPort = null;
|
||||||
|
}
|
||||||
|
|
||||||
public function fixtures(): ApiFixtures
|
public function fixtures(): ApiFixtures
|
||||||
{
|
{
|
||||||
if ($this->fixtures === null) {
|
if ($this->fixtures === null) {
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use objects\customer_password_reset_keys_o;
|
||||||
|
|
||||||
|
app_require('objects/customer_password_reset_keys_o.php');
|
||||||
|
|
||||||
|
if (!class_exists('PasswordResetTokenExpiryFakeResult')) {
|
||||||
|
class PasswordResetTokenExpiryFakeResult
|
||||||
|
{
|
||||||
|
public int $num_rows;
|
||||||
|
|
||||||
|
public function __construct(private readonly array $rows)
|
||||||
|
{
|
||||||
|
$this->num_rows = count($rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetch_assoc(): ?array
|
||||||
|
{
|
||||||
|
return $this->rows[0] ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists('PasswordResetTokenExpiryFakeDb')) {
|
||||||
|
class PasswordResetTokenExpiryFakeDb
|
||||||
|
{
|
||||||
|
public array $queries = [];
|
||||||
|
|
||||||
|
public function __construct(private readonly array $results)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function escape_string(string $string): string
|
||||||
|
{
|
||||||
|
return addslashes($string);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function query(string $sql): PasswordResetTokenExpiryFakeResult
|
||||||
|
{
|
||||||
|
$this->queries[] = $sql;
|
||||||
|
|
||||||
|
return $this->results[count($this->queries) - 1] ?? new PasswordResetTokenExpiryFakeResult([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists('PasswordResetTokenExpiryProbe')) {
|
||||||
|
class PasswordResetTokenExpiryProbe extends customer_password_reset_keys_o
|
||||||
|
{
|
||||||
|
public function getObjectProperties(): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function forceSelectedId(int $id): void
|
||||||
|
{
|
||||||
|
$this->id = $id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(function (): void {
|
||||||
|
$this->previousDb = $GLOBALS['db'] ?? null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function (): void {
|
||||||
|
if ($this->previousDb !== null) {
|
||||||
|
$GLOBALS['db'] = $this->previousDb;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($GLOBALS['db']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps password reset tokens valid for 72 hours', function (): void {
|
||||||
|
expect(customer_password_reset_keys_o::TOKEN_EXPIRY_SECONDS)->toBe(72 * 60 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('looks up reset tokens using the database 72 hour validity window', function (): void {
|
||||||
|
$GLOBALS['db'] = new PasswordResetTokenExpiryFakeDb([
|
||||||
|
new PasswordResetTokenExpiryFakeResult([['id' => 42]]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$token = str_repeat('a', customer_password_reset_keys_o::TOKEN_LENGTH);
|
||||||
|
$probe = new PasswordResetTokenExpiryProbe();
|
||||||
|
|
||||||
|
$found = $probe->findValidByToken($token);
|
||||||
|
|
||||||
|
expect($found)->toBe($probe)
|
||||||
|
->and($probe->id)->toBe(42)
|
||||||
|
->and($GLOBALS['db']->queries[0])->toContain('created_at >= DATE_SUB(NOW(), INTERVAL 259200 SECOND)')
|
||||||
|
->and($GLOBALS['db']->queries[0])->not->toContain("DATE_SUB('");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the same database 72 hour window for the selected token guard', function (): void {
|
||||||
|
$GLOBALS['db'] = new PasswordResetTokenExpiryFakeDb([
|
||||||
|
new PasswordResetTokenExpiryFakeResult([['id' => 42]]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$probe = new PasswordResetTokenExpiryProbe();
|
||||||
|
$probe->forceSelectedId(42);
|
||||||
|
|
||||||
|
expect($probe->isValidToken())->toBeTrue()
|
||||||
|
->and($GLOBALS['db']->queries[0])->toContain('id = 42')
|
||||||
|
->and($GLOBALS['db']->queries[0])->toContain('created_at >= DATE_SUB(NOW(), INTERVAL 259200 SECOND)');
|
||||||
|
});
|
||||||
+3
@@ -31,8 +31,11 @@ it('documents the daily report overview endpoint and reusable schemas in openapi
|
|||||||
$content = department_daily_reports_openapi_content_or_skip();
|
$content = department_daily_reports_openapi_content_or_skip();
|
||||||
|
|
||||||
expect($content)->toContain('/departments/daily-reports/overview:');
|
expect($content)->toContain('/departments/daily-reports/overview:');
|
||||||
|
expect($content)->toContain('/superuser/departments/{id}/overview:');
|
||||||
expect($content)->toContain('operationId: getDailyReportOverview');
|
expect($content)->toContain('operationId: getDailyReportOverview');
|
||||||
|
expect($content)->toContain('operationId: getSuperuserDepartmentOverview');
|
||||||
expect($content)->toContain('DepartmentDailyReportOverviewResponse:');
|
expect($content)->toContain('DepartmentDailyReportOverviewResponse:');
|
||||||
|
expect($content)->toContain('SuperuserDepartmentOverviewResponse:');
|
||||||
expect($content)->toContain('DepartmentDailyReportMetric:');
|
expect($content)->toContain('DepartmentDailyReportMetric:');
|
||||||
expect($content)->toContain('DepartmentDailyReportProductTile:');
|
expect($content)->toContain('DepartmentDailyReportProductTile:');
|
||||||
expect($content)->toContain('- name: department_ids');
|
expect($content)->toContain('- name: department_ids');
|
||||||
|
|||||||
@@ -342,6 +342,8 @@ it('wires the overview route to batched repository methods and overview path', f
|
|||||||
$objectContent = (string)file_get_contents(app_path('objects/department_daily_reports_o.php'));
|
$objectContent = (string)file_get_contents(app_path('objects/department_daily_reports_o.php'));
|
||||||
|
|
||||||
expect($routeContent)->toContain('/departments/daily-reports/overview');
|
expect($routeContent)->toContain('/departments/daily-reports/overview');
|
||||||
|
expect($routeContent)->toContain('/superuser/departments/{id}/overview');
|
||||||
|
expect($routeContent)->toContain('superuser_fetch_department');
|
||||||
expect($routeContent)->toContain('/departments/daily-reports/complaints');
|
expect($routeContent)->toContain('/departments/daily-reports/complaints');
|
||||||
expect($routeContent)->toContain('outsideHoursStatisticsService');
|
expect($routeContent)->toContain('outsideHoursStatisticsService');
|
||||||
expect($routeContent)->toContain('dailyReportComplaintsRepository');
|
expect($routeContent)->toContain('dailyReportComplaintsRepository');
|
||||||
|
|||||||
@@ -30,7 +30,9 @@ it('builds credential-safe normal CORS response headers for allowed origins', fu
|
|||||||
expect($headers['Access-Control-Allow-Methods'])->toContain('PATCH');
|
expect($headers['Access-Control-Allow-Methods'])->toContain('PATCH');
|
||||||
expect($headers['Access-Control-Allow-Headers'])->toContain('X-Release-Trace');
|
expect($headers['Access-Control-Allow-Headers'])->toContain('X-Release-Trace');
|
||||||
expect($headers['Access-Control-Allow-Headers'])->toContain('Cache-Control');
|
expect($headers['Access-Control-Allow-Headers'])->toContain('Cache-Control');
|
||||||
|
expect($headers['Access-Control-Expose-Headers'])->toContain('Server-Timing');
|
||||||
expect($headers['Access-Control-Max-Age'])->toBe('86400');
|
expect($headers['Access-Control-Max-Age'])->toBe('86400');
|
||||||
|
expect($headers['Timing-Allow-Origin'])->toBe('http://localhost:5173');
|
||||||
expect($headers['Vary'])->toBe('Origin');
|
expect($headers['Vary'])->toBe('Origin');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -52,6 +54,8 @@ it('builds preflight CORS response headers for api-v2 release URLs', function ()
|
|||||||
expect($preflight['status'])->toBe(200);
|
expect($preflight['status'])->toBe(200);
|
||||||
expect($preflight['headers']['Access-Control-Allow-Origin'])->toBe('https://api-v2.truckwash.io');
|
expect($preflight['headers']['Access-Control-Allow-Origin'])->toBe('https://api-v2.truckwash.io');
|
||||||
expect($preflight['headers']['Content-Type'])->toBe('application/json');
|
expect($preflight['headers']['Content-Type'])->toBe('application/json');
|
||||||
|
expect($preflight['headers']['Access-Control-Expose-Headers'])->toContain('Server-Timing');
|
||||||
|
expect($preflight['headers']['Timing-Allow-Origin'])->toBe('https://api-v2.truckwash.io');
|
||||||
expect($preflight['body'])->toBe('');
|
expect($preflight['body'])->toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -71,4 +75,5 @@ it('reflects the request origin for wildcard CORS instead of sending credentiale
|
|||||||
expect($headers['Access-Control-Allow-Origin'])->toBe('https://partner.example.test');
|
expect($headers['Access-Control-Allow-Origin'])->toBe('https://partner.example.test');
|
||||||
expect($headers['Access-Control-Allow-Credentials'])->toBe('true');
|
expect($headers['Access-Control-Allow-Credentials'])->toBe('true');
|
||||||
expect($headers['Access-Control-Allow-Origin'])->not->toBe('*');
|
expect($headers['Access-Control-Allow-Origin'])->not->toBe('*');
|
||||||
|
expect($headers['Timing-Allow-Origin'])->toBe('https://partner.example.test');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
function phpFpmWorkerConfigRepoRoot(): string
|
||||||
|
{
|
||||||
|
$configuredRoot = getenv('PLENO_REPO_ROOT_FOR_TESTS');
|
||||||
|
if (is_string($configuredRoot) && $configuredRoot !== '') {
|
||||||
|
return rtrim($configuredRoot, DIRECTORY_SEPARATOR);
|
||||||
|
}
|
||||||
|
|
||||||
|
$appRoot = defined('WD') ? WD : dirname(__DIR__, 3);
|
||||||
|
|
||||||
|
return dirname($appRoot, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
function phpFpmWorkerConfigRepoPath(string $relative): string
|
||||||
|
{
|
||||||
|
return phpFpmWorkerConfigRepoRoot() . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relative);
|
||||||
|
}
|
||||||
|
|
||||||
|
function phpFpmWorkerConfigValue(string $poolConfig, string $key): ?int
|
||||||
|
{
|
||||||
|
if (!preg_match('/^' . preg_quote($key, '/') . '\s*=\s*(\d+)\s*$/m', $poolConfig, $matches)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int)$matches[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
it('configures PHP-FPM with multiple warm request workers', function (): void {
|
||||||
|
$poolPath = phpFpmWorkerConfigRepoPath('services/php/php-fpm-pool.conf');
|
||||||
|
expect(is_file($poolPath))->toBeTrue();
|
||||||
|
|
||||||
|
$poolConfig = (string)file_get_contents($poolPath);
|
||||||
|
|
||||||
|
expect($poolConfig)->toContain('[www]')
|
||||||
|
->and($poolConfig)->toContain('pm = dynamic')
|
||||||
|
->and(phpFpmWorkerConfigValue($poolConfig, 'pm.max_children'))->toBeGreaterThanOrEqual(8)
|
||||||
|
->and(phpFpmWorkerConfigValue($poolConfig, 'pm.start_servers'))->toBeGreaterThanOrEqual(4)
|
||||||
|
->and(phpFpmWorkerConfigValue($poolConfig, 'pm.min_spare_servers'))->toBeGreaterThanOrEqual(4)
|
||||||
|
->and(phpFpmWorkerConfigValue($poolConfig, 'pm.max_spare_servers'))->toBeGreaterThanOrEqual(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('copies the worker pool config into every API PHP image', function (): void {
|
||||||
|
$copyInstruction = 'COPY services/php/php-fpm-pool.conf /usr/local/etc/php-fpm.d/zz-pleno-workers.conf';
|
||||||
|
$dockerfiles = [
|
||||||
|
phpFpmWorkerConfigRepoPath('Dockerfile'),
|
||||||
|
phpFpmWorkerConfigRepoPath('Dockerfile.coolify-api'),
|
||||||
|
phpFpmWorkerConfigRepoPath('services/php/Dockerfile'),
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($dockerfiles as $dockerfile) {
|
||||||
|
expect(is_file($dockerfile))->toBeTrue();
|
||||||
|
expect((string)file_get_contents($dockerfile))->toContain($copyInstruction);
|
||||||
|
}
|
||||||
|
});
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
it('routes collected invoice draft line uploads through the multi-order batch endpoint', function (): void {
|
||||||
|
$content = file_get_contents(dirname(__DIR__, 3) . '/objects/collected_order_invoices_o.php');
|
||||||
|
|
||||||
|
expect($content)->not->toBeFalse();
|
||||||
|
$content = (string)$content;
|
||||||
|
|
||||||
|
$start = strpos($content, 'public function addInvoicesToDraft');
|
||||||
|
$end = strpos($content, 'public function getLastEconomicTransferMetrics');
|
||||||
|
expect($start)->not->toBeFalse();
|
||||||
|
expect($end)->not->toBeFalse();
|
||||||
|
expect($end)->toBeGreaterThan($start);
|
||||||
|
|
||||||
|
$methodBlock = substr($content, (int)$start, (int)$end - (int)$start);
|
||||||
|
expect($methodBlock)->toContain('$order_objects = [];')
|
||||||
|
->and($methodBlock)->toContain('$metrics = (new economic())->invoices->draft->add_orders($draft_id, $order_objects, $currency);')
|
||||||
|
->and($methodBlock)->toContain('...$metrics')
|
||||||
|
->and($methodBlock)->not->toContain('self::addInvoiceToDraft($order[\'id\'], true, $draft_id, $currency);');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps single-order draft uploads as a wrapper around the batch endpoint', function (): void {
|
||||||
|
$content = file_get_contents(dirname(__DIR__, 3) . '/modules/economic/endpoints/invoices/draft/economic_invoices_draft_endpoint.php');
|
||||||
|
|
||||||
|
expect($content)->not->toBeFalse();
|
||||||
|
$content = (string)$content;
|
||||||
|
|
||||||
|
$singleStart = strpos($content, 'public function add_order');
|
||||||
|
$singleEnd = strpos($content, 'public function add_orders');
|
||||||
|
expect($singleStart)->not->toBeFalse();
|
||||||
|
expect($singleEnd)->not->toBeFalse();
|
||||||
|
expect($singleEnd)->toBeGreaterThan($singleStart);
|
||||||
|
|
||||||
|
$singleBlock = substr($content, (int)$singleStart, (int)$singleEnd - (int)$singleStart);
|
||||||
|
expect($singleBlock)->toContain('$this->add_orders($invoiceDraftId, [$order], $currency);');
|
||||||
|
|
||||||
|
$batchBlock = substr($content, (int)$singleEnd);
|
||||||
|
expect($batchBlock)->toContain('$draftInvoice->flushLinesInBatches($line_batch_size);')
|
||||||
|
->and($batchBlock)->toContain("'orders_with_invoice_lines' => \$orders_with_invoice_lines");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes collected invoice batch transfer metrics in queue results when available', function (): void {
|
||||||
|
$content = file_get_contents(dirname(__DIR__, 3) . '/classes/economic_transfer_executor.php');
|
||||||
|
|
||||||
|
expect($content)->not->toBeFalse();
|
||||||
|
$content = (string)$content;
|
||||||
|
|
||||||
|
expect($content)->toContain('$transfer_metrics = $collected_order_invoices->getLastEconomicTransferMetrics();')
|
||||||
|
->and($content)->toContain("\$result['economic_transfer_metrics'] = \$transfer_metrics;");
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use helpers\economic_invoice_draft;
|
||||||
|
|
||||||
|
if (!class_exists('EconomicInvoiceDraftBatchingProbe')) {
|
||||||
|
class EconomicInvoiceDraftBatchingProbe extends economic_invoice_draft
|
||||||
|
{
|
||||||
|
public array $sentBatches = [];
|
||||||
|
|
||||||
|
protected function sendDraftLines(array $draft_lines): object
|
||||||
|
{
|
||||||
|
$this->sentBatches[] = $draft_lines;
|
||||||
|
return (object)['lines' => $draft_lines];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!class_exists('EconomicInvoiceDraftFailingBatchingProbe')) {
|
||||||
|
class EconomicInvoiceDraftFailingBatchingProbe extends EconomicInvoiceDraftBatchingProbe
|
||||||
|
{
|
||||||
|
public int $failOnBatch = 1;
|
||||||
|
|
||||||
|
protected function sendDraftLines(array $draft_lines): object
|
||||||
|
{
|
||||||
|
if (count($this->sentBatches) + 1 === $this->failOnBatch) {
|
||||||
|
throw new RuntimeException('Simulated e-conomic line batch failure');
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::sendDraftLines($draft_lines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('does not call e-conomic when flushing an empty draft line buffer', function (): void {
|
||||||
|
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||||
|
|
||||||
|
$metrics = $draft->flushLinesInBatches();
|
||||||
|
|
||||||
|
expect($metrics)->toBe([
|
||||||
|
'line_count' => 0,
|
||||||
|
'batch_count' => 0,
|
||||||
|
'batch_sizes' => [],
|
||||||
|
])->and($draft->sentBatches)->toBe([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flushes a small draft line buffer in one request and clears pending lines', function (): void {
|
||||||
|
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||||
|
$draft->addTextLine('line-0');
|
||||||
|
$draft->addTextLine('line-1');
|
||||||
|
$draft->addTextLine('line-2');
|
||||||
|
|
||||||
|
$metrics = $draft->flushLinesInBatches(500);
|
||||||
|
|
||||||
|
expect($metrics)->toBe([
|
||||||
|
'line_count' => 3,
|
||||||
|
'batch_count' => 1,
|
||||||
|
'batch_sizes' => [3],
|
||||||
|
])->and($draft->sentBatches)->toHaveCount(1)
|
||||||
|
->and($draft->sentBatches[0][0]['description'])->toBe('line-0')
|
||||||
|
->and($draft->sentBatches[0][2]['description'])->toBe('line-2')
|
||||||
|
->and($draft->pendingLineCount())->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('chunks large draft line buffers while preserving line order', function (): void {
|
||||||
|
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||||
|
for ($i = 0; $i < 1201; $i++) {
|
||||||
|
$draft->addTextLine('line-' . $i);
|
||||||
|
}
|
||||||
|
|
||||||
|
$metrics = $draft->flushLinesInBatches(500);
|
||||||
|
|
||||||
|
expect($metrics)->toBe([
|
||||||
|
'line_count' => 1201,
|
||||||
|
'batch_count' => 3,
|
||||||
|
'batch_sizes' => [500, 500, 201],
|
||||||
|
])->and($draft->sentBatches)->toHaveCount(3)
|
||||||
|
->and($draft->sentBatches[0][0]['description'])->toBe('line-0')
|
||||||
|
->and($draft->sentBatches[1][0]['description'])->toBe('line-500')
|
||||||
|
->and($draft->sentBatches[2][200]['description'])->toBe('line-1200')
|
||||||
|
->and($draft->pendingLineCount())->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bubbles line batch failures and keeps pending lines available', function (): void {
|
||||||
|
$draft = new EconomicInvoiceDraftFailingBatchingProbe(123, 'DKK', true);
|
||||||
|
$draft->addTextLine('line-0');
|
||||||
|
|
||||||
|
expect(fn () => $draft->flushLinesInBatches(500))
|
||||||
|
->toThrow(RuntimeException::class, 'Simulated e-conomic line batch failure');
|
||||||
|
|
||||||
|
expect($draft->sentBatches)->toBe([])
|
||||||
|
->and($draft->pendingLineCount())->toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use classes\router;
|
||||||
|
|
||||||
|
it('matches dynamic route parameter names containing underscores', function (): void {
|
||||||
|
$_SERVER['REQUEST_URI'] = '/modules/self-serve/lane/hardware/batch/916cdba1981e52f3dc728ea06fc39cf0';
|
||||||
|
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||||
|
|
||||||
|
$router = new router();
|
||||||
|
$matcher = new ReflectionMethod(router::class, 'doesRouteMatchCurrent');
|
||||||
|
|
||||||
|
expect($matcher->invoke(
|
||||||
|
$router,
|
||||||
|
'/modules/self-serve/lane/hardware/batch/{batch_id}'
|
||||||
|
))->toBeTrue();
|
||||||
|
});
|
||||||
@@ -0,0 +1,449 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use classes\licenseplaterecognizer;
|
||||||
|
|
||||||
|
class scanner_test_license_plate_recognizer extends licenseplaterecognizer
|
||||||
|
{
|
||||||
|
public int $config_reads = 0;
|
||||||
|
|
||||||
|
public function __construct(private readonly array $config_values)
|
||||||
|
{
|
||||||
|
parent::__construct(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exposedRuntimeConfig(): array
|
||||||
|
{
|
||||||
|
return $this->runtimeConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function readRuntimeModuleConfig(): array
|
||||||
|
{
|
||||||
|
$this->config_reads++;
|
||||||
|
|
||||||
|
return $this->config_values;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class scanner_test_shared_cache_license_plate_recognizer extends licenseplaterecognizer
|
||||||
|
{
|
||||||
|
public static int $config_reads = 0;
|
||||||
|
public static array $config_values = [];
|
||||||
|
public static ?scanner_test_runtime_config_cache_store $cache_store = null;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exposedRuntimeConfig(): array
|
||||||
|
{
|
||||||
|
return $this->runtimeConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function shouldUseSharedRuntimeConfigCache(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function readRuntimeModuleConfig(): array
|
||||||
|
{
|
||||||
|
self::$config_reads++;
|
||||||
|
|
||||||
|
return self::$config_values;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function runtimeConfigCacheStore(): ?object
|
||||||
|
{
|
||||||
|
return self::$cache_store;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class scanner_test_runtime_config_cache_store
|
||||||
|
{
|
||||||
|
public array $store = [];
|
||||||
|
public array $set_ex_calls = [];
|
||||||
|
|
||||||
|
public function get(string $key): ?string
|
||||||
|
{
|
||||||
|
return $this->store[$key] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setEx(string $key, string $value, int $expiration): void
|
||||||
|
{
|
||||||
|
$this->store[$key] = $value;
|
||||||
|
$this->set_ex_calls[] = [
|
||||||
|
'key' => $key,
|
||||||
|
'value' => $value,
|
||||||
|
'expiration' => $expiration,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset_license_plate_recognizer_runtime_config_cache(): void
|
||||||
|
{
|
||||||
|
$cacheProperty = new ReflectionProperty(licenseplaterecognizer::class, 'runtime_config_cache');
|
||||||
|
$cacheProperty->setValue(null, null);
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_reads = 0;
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [];
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$cache_store = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(function (): void {
|
||||||
|
reset_license_plate_recognizer_runtime_config_cache();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function (): void {
|
||||||
|
reset_license_plate_recognizer_runtime_config_cache();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends data URI images to Plate Recognizer as multipart bytes with fast mode enabled', function (): void {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$method = $reflection->getMethod('buildPlateReaderPayload');
|
||||||
|
|
||||||
|
$payload = $method->invoke($recognizer, 'data:image/jpeg;base64,' . base64_encode('jpeg-bytes'));
|
||||||
|
|
||||||
|
expect($payload['upload'])->toBeInstanceOf(CURLStringFile::class);
|
||||||
|
expect($payload['upload']->data)->toBe('jpeg-bytes');
|
||||||
|
expect($payload['upload']->postname)->toBe('license-plate.jpg');
|
||||||
|
expect($payload['upload']->mime)->toBe('image/jpeg');
|
||||||
|
expect(json_decode($payload['config'], true))->toBe([
|
||||||
|
'mode' => 'fast',
|
||||||
|
'plates_per_vehicle' => 1,
|
||||||
|
'zoom_in_vehicles' => 0,
|
||||||
|
]);
|
||||||
|
expect($payload['regions'])->toBe('dk,de,se,no');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses precomputed Plate Reader config strings on the scanner payload hot path', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('PLATE_READER_CONFIG_JSON');
|
||||||
|
expect($source)->toContain('RESULT_CACHE_CONTEXT');
|
||||||
|
expect($source)->toContain("'config' => self::PLATE_READER_CONFIG_JSON");
|
||||||
|
expect($source)->toContain('return self::RESULT_CACHE_CONTEXT;');
|
||||||
|
expect($source)->not->toContain("'config' => json_encode(self::PLATE_READER_CONFIG");
|
||||||
|
expect($source)->not->toContain("return json_encode([\n 'config' => self::PLATE_READER_CONFIG");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps already raw base64 upload data unchanged', function (): void {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$method = $reflection->getMethod('buildPlateReaderPayload');
|
||||||
|
|
||||||
|
$payload = $method->invoke($recognizer, 'abc123');
|
||||||
|
|
||||||
|
expect($payload['upload'])->toBe('abc123');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not retain raw upstream Plate Recognizer responses in compact scanner results', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->not->toContain("'raw_response' => \$response_data");
|
||||||
|
expect($source)->toContain("'license_plate_number' => \$response_data['results'][0]['plate'] ?? null");
|
||||||
|
expect($source)->toContain("'confidence' => \$response_data['results'][0]['score'] ?? null");
|
||||||
|
expect($source)->toContain("'message' => 'No license plate detected.'");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends multipart route image bytes to Plate Recognizer without base64 wrapping', function (): void {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$uploadMethod = $reflection->getMethod('buildUploadValueFromBytes');
|
||||||
|
$payloadMethod = $reflection->getMethod('buildPlateReaderPayloadFromUpload');
|
||||||
|
|
||||||
|
$upload = $uploadMethod->invoke($recognizer, 'jpeg-bytes', 'image/jpeg');
|
||||||
|
$payload = $payloadMethod->invoke($recognizer, $upload);
|
||||||
|
|
||||||
|
expect($payload['upload'])->toBeInstanceOf(CURLStringFile::class);
|
||||||
|
expect($payload['upload']->data)->toBe('jpeg-bytes');
|
||||||
|
expect($payload['upload']->postname)->toBe('license-plate.jpg');
|
||||||
|
expect($payload['upload']->mime)->toBe('image/jpeg');
|
||||||
|
expect(json_decode($payload['config'], true))->toBe([
|
||||||
|
'mode' => 'fast',
|
||||||
|
'plates_per_vehicle' => 1,
|
||||||
|
'zoom_in_vehicles' => 0,
|
||||||
|
]);
|
||||||
|
expect($payload['regions'])->toBe('dk,de,se,no');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends multipart route upload files to Plate Recognizer without reading bytes into PHP memory', function (): void {
|
||||||
|
$path = tempnam(sys_get_temp_dir(), 'lpr-upload-');
|
||||||
|
expect($path)->not->toBeFalse();
|
||||||
|
file_put_contents($path, 'jpeg-bytes');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$uploadMethod = $reflection->getMethod('buildUploadValueFromFile');
|
||||||
|
$payloadMethod = $reflection->getMethod('buildPlateReaderPayloadFromUpload');
|
||||||
|
|
||||||
|
$upload = $uploadMethod->invoke($recognizer, $path, 'image/jpeg');
|
||||||
|
$payload = $payloadMethod->invoke($recognizer, $upload);
|
||||||
|
|
||||||
|
expect($payload['upload'])->toBeInstanceOf(CURLFile::class);
|
||||||
|
expect($payload['upload']->getFilename())->toBe($path);
|
||||||
|
expect($payload['upload']->getPostFilename())->toBe('license-plate.jpg');
|
||||||
|
expect($payload['upload']->getMimeType())->toBe('image/jpeg');
|
||||||
|
expect(json_decode($payload['config'], true))->toBe([
|
||||||
|
'mode' => 'fast',
|
||||||
|
'plates_per_vehicle' => 1,
|
||||||
|
'zoom_in_vehicles' => 0,
|
||||||
|
]);
|
||||||
|
expect($payload['regions'])->toBe('dk,de,se,no');
|
||||||
|
} finally {
|
||||||
|
@unlink($path);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records Plate Recognizer processing time from the upstream response', function (): void {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$method = $reflection->getMethod('recordResponseTimings');
|
||||||
|
|
||||||
|
$method->invoke($recognizer, [
|
||||||
|
'processing_time' => 58.184,
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($recognizer->getLastTimings())->toHaveKey('upstream_processing', 58.184);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can skip config object setup and cache runtime config for scanner requests', function (): void {
|
||||||
|
$recognizer = new scanner_test_license_plate_recognizer([
|
||||||
|
'enabled' => 'true',
|
||||||
|
'api_key' => 'test-key',
|
||||||
|
]);
|
||||||
|
$configProperty = new ReflectionProperty(licenseplaterecognizer::class, 'config');
|
||||||
|
|
||||||
|
expect($configProperty->isInitialized($recognizer))->toBeFalse();
|
||||||
|
expect($recognizer->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'test-key',
|
||||||
|
]);
|
||||||
|
expect($recognizer->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'test-key',
|
||||||
|
]);
|
||||||
|
expect($recognizer->config_reads)->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads runtime config once in the scanner recognition hot path', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('$runtime_config = $this->runtimeConfig();');
|
||||||
|
expect($source)->toContain('$api_key = $runtime_config[\'api_key\'];');
|
||||||
|
expect($source)->not->toContain('$this->requireModuleEnabled();' . "\n " . '$api_key = $this->runtimeConfig()[\'api_key\'];');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shares runtime config briefly across scanner recognizer instances', function (): void {
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [
|
||||||
|
'enabled' => 'true',
|
||||||
|
'api_key' => 'cached-key',
|
||||||
|
];
|
||||||
|
|
||||||
|
$first = new scanner_test_shared_cache_license_plate_recognizer();
|
||||||
|
expect($first->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'cached-key',
|
||||||
|
]);
|
||||||
|
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [
|
||||||
|
'enabled' => 'false',
|
||||||
|
'api_key' => 'new-key',
|
||||||
|
];
|
||||||
|
|
||||||
|
$second = new scanner_test_shared_cache_license_plate_recognizer();
|
||||||
|
expect($second->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'cached-key',
|
||||||
|
]);
|
||||||
|
expect(scanner_test_shared_cache_license_plate_recognizer::$config_reads)->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refreshes the shared runtime config cache after the short scanner ttl', function (): void {
|
||||||
|
$cacheProperty = new ReflectionProperty(licenseplaterecognizer::class, 'runtime_config_cache');
|
||||||
|
$cacheProperty->setValue(null, [
|
||||||
|
'values' => [
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'stale-key',
|
||||||
|
],
|
||||||
|
'cached_at' => microtime(true) - 20,
|
||||||
|
]);
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [
|
||||||
|
'enabled' => 'false',
|
||||||
|
'api_key' => 'fresh-key',
|
||||||
|
];
|
||||||
|
|
||||||
|
$recognizer = new scanner_test_shared_cache_license_plate_recognizer();
|
||||||
|
|
||||||
|
expect($recognizer->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => false,
|
||||||
|
'api_key' => 'fresh-key',
|
||||||
|
]);
|
||||||
|
expect(scanner_test_shared_cache_license_plate_recognizer::$config_reads)->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses Redis-backed runtime config cache across scanner requests when available', function (): void {
|
||||||
|
$cache = new scanner_test_runtime_config_cache_store();
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$cache_store = $cache;
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [
|
||||||
|
'enabled' => 'true',
|
||||||
|
'api_key' => 'redis-key',
|
||||||
|
];
|
||||||
|
|
||||||
|
$first = new scanner_test_shared_cache_license_plate_recognizer();
|
||||||
|
expect($first->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'redis-key',
|
||||||
|
]);
|
||||||
|
expect(scanner_test_shared_cache_license_plate_recognizer::$config_reads)->toBe(1);
|
||||||
|
expect($cache->set_ex_calls)->toHaveCount(1);
|
||||||
|
expect($cache->set_ex_calls[0]['expiration'])->toBe(15);
|
||||||
|
|
||||||
|
$cacheProperty = new ReflectionProperty(licenseplaterecognizer::class, 'runtime_config_cache');
|
||||||
|
$cacheProperty->setValue(null, null);
|
||||||
|
scanner_test_shared_cache_license_plate_recognizer::$config_values = [
|
||||||
|
'enabled' => 'false',
|
||||||
|
'api_key' => 'db-should-not-be-read',
|
||||||
|
];
|
||||||
|
|
||||||
|
$second = new scanner_test_shared_cache_license_plate_recognizer();
|
||||||
|
|
||||||
|
expect($second->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => true,
|
||||||
|
'api_key' => 'redis-key',
|
||||||
|
]);
|
||||||
|
expect(scanner_test_shared_cache_license_plate_recognizer::$config_reads)->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats false runtime config values as disabled', function (): void {
|
||||||
|
$recognizer = new scanner_test_license_plate_recognizer([
|
||||||
|
'enabled' => 'false',
|
||||||
|
'api_key' => 'test-key',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($recognizer->exposedRuntimeConfig())->toBe([
|
||||||
|
'enabled' => false,
|
||||||
|
'api_key' => 'test-key',
|
||||||
|
]);
|
||||||
|
expect(fn () => $recognizer->requireModuleEnabled())
|
||||||
|
->toThrow(Exception::class, 'licenseplaterecognizer module is not enabled.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can point Plate Recognizer calls at a local measurement upstream', function (): void {
|
||||||
|
$recognizer = new licenseplaterecognizer(false, 'http://127.0.0.1:18081/');
|
||||||
|
$apiUrlProperty = new ReflectionProperty(licenseplaterecognizer::class, 'api_url');
|
||||||
|
|
||||||
|
expect($apiUrlProperty->getValue($recognizer))->toBe('http://127.0.0.1:18081');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables curl expect continue waits for large multipart uploads', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain("'Expect:'");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables tcp write coalescing on scanner Plate Recognizer requests when curl supports it', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('$curl_options = [');
|
||||||
|
expect($source)->toContain("defined('CURLOPT_TCP_NODELAY')");
|
||||||
|
expect($source)->toContain("\$curl_options[(int)constant('CURLOPT_TCP_NODELAY')] = true;");
|
||||||
|
expect($source)->toContain('curl_setopt_array($ch, $curl_options);');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not capture outgoing curl headers on the scanner hot path', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->not->toContain('CURLINFO_HEADER_OUT');
|
||||||
|
expect($source)->toContain('curl_setopt_array($ch');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records only selected curl timing fields on the scanner hot path', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('$this->recordCurlTimings($ch);');
|
||||||
|
expect($source)->not->toContain('$curl_info = curl_getinfo($ch);');
|
||||||
|
expect($source)->toContain('CURLINFO_NAMELOOKUP_TIME');
|
||||||
|
expect($source)->toContain('CURLINFO_TOTAL_TIME');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aborts upstream recognition transfers when the HTTP client disconnects', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('CURLOPT_NOPROGRESS');
|
||||||
|
expect($source)->toContain('CURLOPT_XFERINFOFUNCTION');
|
||||||
|
expect($source)->toContain('connection_aborted() ? 1 : 0');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bounds Plate Recognizer scanner uploads with conservative curl timeouts', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('PLATE_READER_CONNECT_TIMEOUT_MS = 1000');
|
||||||
|
expect($source)->toContain('PLATE_READER_TOTAL_TIMEOUT_MS = 4500');
|
||||||
|
expect($source)->toContain('CURLOPT_CONNECTTIMEOUT_MS => self::PLATE_READER_CONNECT_TIMEOUT_MS');
|
||||||
|
expect($source)->toContain('CURLOPT_TIMEOUT_MS => self::PLATE_READER_TOTAL_TIMEOUT_MS');
|
||||||
|
expect($source)->toContain('CURLOPT_NOSIGNAL => true');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses a short exact-image result cache before calling Plate Recognizer', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('RESULT_CACHE_TTL_SECONDS = 10');
|
||||||
|
expect($source)->toContain('RESULT_CACHE_REDIS_KEY_PREFIX');
|
||||||
|
expect($source)->toContain('$cached_result = $this->readRecognitionResultCache($result_cache, $result_cache_key);');
|
||||||
|
expect($source)->toContain('return $cached_result;');
|
||||||
|
expect($source)->toContain('$this->writeRecognitionResultCache($result_cache, $result_cache_key, $recognized_result);');
|
||||||
|
expect($source)->toContain('$this->last_timings[\'cache\']');
|
||||||
|
expect($source)->toContain('$this->last_timings[\'cache_hit\'] = 1;');
|
||||||
|
expect($source)->toContain('$this->last_timings[\'cache_miss\'] = 1;');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not hash multipart upload temp files for result-cache misses', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('public function licenseplaterecognizerUploadFile');
|
||||||
|
expect($source)->toContain('return $this->recognizePlate(');
|
||||||
|
expect($source)->toContain('$this->buildUploadValueFromFile($image_path, $mime_type)');
|
||||||
|
expect($source)->not->toContain('buildResultCacheKeyFromFile');
|
||||||
|
expect($source)->not->toContain('hash_update_file($context, $image_path)');
|
||||||
|
expect($source)->not->toContain('file_get_contents($image_path');
|
||||||
|
expect($source)->not->toContain('hash_update($context, $chunk)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not hash raw scanner body bytes on the live camera upload path', function (): void {
|
||||||
|
$source = file_get_contents(app_path('classes/licenseplaterecognizer.php'));
|
||||||
|
$route = file_get_contents(app_path('routes/moduleScannerRoute.php'));
|
||||||
|
|
||||||
|
expect($source)->not->toBeFalse();
|
||||||
|
expect($route)->not->toBeFalse();
|
||||||
|
expect($source)->toContain('public function licenseplaterecognizerUploadUncached');
|
||||||
|
expect($source)->toContain('fn () => $this->buildPlateReaderPayloadFromUpload(');
|
||||||
|
expect($route)->toContain('licenseplaterecognizerUploadUncached($raw_image_upload');
|
||||||
|
expect($route)->not->toContain('licenseplaterecognizerUpload($raw_image_upload');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds stable result cache keys from equivalent in-memory image bytes', function (): void {
|
||||||
|
$reflection = new ReflectionClass(licenseplaterecognizer::class);
|
||||||
|
$recognizer = $reflection->newInstanceWithoutConstructor();
|
||||||
|
$bytesMethod = $reflection->getMethod('buildResultCacheKeyFromBytes');
|
||||||
|
$uploadStringMethod = $reflection->getMethod('buildResultCacheKeyFromUploadString');
|
||||||
|
|
||||||
|
$bytesKey = $bytesMethod->invoke($recognizer, 'jpeg-bytes');
|
||||||
|
$dataUriKey = $uploadStringMethod->invoke($recognizer, 'data:image/jpeg;base64,' . base64_encode('jpeg-bytes'));
|
||||||
|
$differentKey = $bytesMethod->invoke($recognizer, 'other-jpeg-bytes');
|
||||||
|
|
||||||
|
expect($dataUriKey)->toBe($bytesKey);
|
||||||
|
expect($differentKey)->not->toBe($bytesKey);
|
||||||
|
expect($bytesKey)->toStartWith('licenseplaterecognizer:result:v1:');
|
||||||
|
});
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use routes\moduleScannerRoute;
|
||||||
|
|
||||||
|
app_require('routes/moduleScannerRoute.php');
|
||||||
|
|
||||||
it('returns no-plate LPR results without a failed HTTP status', function (): void {
|
it('returns no-plate LPR results without a failed HTTP status', function (): void {
|
||||||
$route = file_get_contents(app_path('routes/moduleScannerRoute.php'));
|
$route = file_get_contents(app_path('routes/moduleScannerRoute.php'));
|
||||||
|
|
||||||
@@ -8,3 +12,124 @@ it('returns no-plate LPR results without a failed HTTP status', function (): voi
|
|||||||
expect($route)->toContain('], 200);');
|
expect($route)->toContain('], 200);');
|
||||||
expect($route)->not->toContain("throw new Exception('License plate extraction failed.')");
|
expect($route)->not->toContain("throw new Exception('License plate extraction failed.')");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('returns low-confidence LPR results without a failed HTTP status', function (): void {
|
||||||
|
$route = file_get_contents(app_path('routes/moduleScannerRoute.php'));
|
||||||
|
|
||||||
|
expect($route)->not->toBeFalse();
|
||||||
|
expect($route)->toContain("'reason' => 'low_confidence_license_plate'");
|
||||||
|
expect($route)->toContain("'message' => 'License plate recognition confidence too low.'");
|
||||||
|
expect($route)->toContain("'confidence' => \$lpr_result['confidence']");
|
||||||
|
expect($route)->not->toContain('License plate recognition confidence too low. Score:');
|
||||||
|
expect($route)->not->toContain('use Exception;');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not store scanner images before LPR recognition', function (): void {
|
||||||
|
$route = file_get_contents(app_path('routes/moduleScannerRoute.php'));
|
||||||
|
|
||||||
|
expect($route)->not->toBeFalse();
|
||||||
|
expect($route)->toContain('new licenseplaterecognizer(false)');
|
||||||
|
expect($route)->toContain('getLPRImageUpload()');
|
||||||
|
expect($route)->toContain('getLPRRawImageUpload()');
|
||||||
|
expect($route)->toContain('$base64_image = null;');
|
||||||
|
expect($route)->toContain('if ($image_upload === null && $raw_image_upload === null)');
|
||||||
|
expect($route)->toContain('licenseplaterecognizerUploadFile($image_upload');
|
||||||
|
expect($route)->toContain('licenseplaterecognizerUploadUncached($raw_image_upload');
|
||||||
|
expect($route)->toContain("'path' => \$tmp_name");
|
||||||
|
expect($route)->toContain("'data' => \$image_data");
|
||||||
|
expect($route)->toContain("file_get_contents('php://input')");
|
||||||
|
expect($route)->toContain("str_starts_with(\$mime_type, 'image/')");
|
||||||
|
expect($route)->toContain('$recognizer->licenseplaterecognizer((string)$base64_image)');
|
||||||
|
expect($route)->toContain('$route_started_at = microtime(true);');
|
||||||
|
expect($route)->toContain('$client_timings = self::getLPRClientTimings();');
|
||||||
|
expect($route)->toContain('array_merge($client_timings, $recognizer->getLastTimings())');
|
||||||
|
expect($route)->toContain("header('Server-Timing: '");
|
||||||
|
expect($route)->toContain("'client_capture'");
|
||||||
|
expect($route)->toContain("'client_preflight'");
|
||||||
|
expect($route)->toContain("'client_visual_fingerprint'");
|
||||||
|
expect($route)->toContain("'client_draw'");
|
||||||
|
expect($route)->toContain("'client_encode'");
|
||||||
|
expect($route)->toContain("'client_frame_width'");
|
||||||
|
expect($route)->toContain("'client_frame_height'");
|
||||||
|
expect($route)->toContain("'client_frame_bytes'");
|
||||||
|
expect($route)->toContain("'cache'");
|
||||||
|
expect($route)->toContain("'cache_hit'");
|
||||||
|
expect($route)->toContain("'cache_miss'");
|
||||||
|
expect($route)->toContain("\$timings['local'] = self::getLPRLocalDuration(\$timings);");
|
||||||
|
expect($route)->toContain("'local'");
|
||||||
|
expect($route)->toContain("'upstream_dns'");
|
||||||
|
expect($route)->toContain("'upstream_connect'");
|
||||||
|
expect($route)->toContain("'upstream_tls'");
|
||||||
|
expect($route)->toContain("'upstream_pretransfer'");
|
||||||
|
expect($route)->toContain("'upstream_ttfb'");
|
||||||
|
expect($route)->toContain("'upstream_total'");
|
||||||
|
expect($route)->toContain("'upstream_processing'");
|
||||||
|
expect($route)->toContain("'route_total'");
|
||||||
|
expect($route)->toContain("'request_total'");
|
||||||
|
expect($route)->toContain('HTTP_X_LPR_CLIENT_CAPTURE_MS');
|
||||||
|
expect($route)->toContain('HTTP_X_LPR_CLIENT_FRAME_BYTES');
|
||||||
|
expect($route)->toContain('$value = $_GET[$field] ?? null;');
|
||||||
|
expect($route)->toContain("isset(\$_SERVER['REQUEST_TIME_FLOAT'])");
|
||||||
|
expect($route)->not->toContain("requireParameters(['base64_image'])");
|
||||||
|
expect($route)->not->toContain('file_get_contents($tmp_name)');
|
||||||
|
expect($route)->not->toContain('storeTempImageFromBase64');
|
||||||
|
expect($route)->not->toContain('new upload_store');
|
||||||
|
expect($route)->not->toContain('new openai');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads raw scanner client timing metadata from request query parameters', function (): void {
|
||||||
|
$previousGet = $_GET;
|
||||||
|
$previousPost = $_POST;
|
||||||
|
$headerNames = [
|
||||||
|
'HTTP_X_LPR_CLIENT_CAPTURE_MS',
|
||||||
|
'HTTP_X_LPR_CLIENT_PREFLIGHT_MS',
|
||||||
|
'HTTP_X_LPR_CLIENT_DRAW_MS',
|
||||||
|
'HTTP_X_LPR_CLIENT_ENCODE_MS',
|
||||||
|
'HTTP_X_LPR_CLIENT_VISUAL_FINGERPRINT_MS',
|
||||||
|
'HTTP_X_LPR_CLIENT_FRAME_WIDTH',
|
||||||
|
'HTTP_X_LPR_CLIENT_FRAME_HEIGHT',
|
||||||
|
'HTTP_X_LPR_CLIENT_FRAME_BYTES',
|
||||||
|
];
|
||||||
|
$previousHeaders = [];
|
||||||
|
foreach ($headerNames as $headerName) {
|
||||||
|
$previousHeaders[$headerName] = $_SERVER[$headerName] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$_GET = [
|
||||||
|
'client_capture_ms' => '12.345',
|
||||||
|
'client_preflight_ms' => '1.500',
|
||||||
|
'client_draw_ms' => '2.250',
|
||||||
|
'client_encode_ms' => '8.500',
|
||||||
|
'client_visual_fingerprint_ms' => '0.750',
|
||||||
|
'client_frame_width' => '384',
|
||||||
|
'client_frame_height' => '216',
|
||||||
|
'client_frame_bytes' => '12345',
|
||||||
|
];
|
||||||
|
$_POST = [];
|
||||||
|
|
||||||
|
$reflection = new ReflectionClass(moduleScannerRoute::class);
|
||||||
|
$method = $reflection->getMethod('getLPRClientTimings');
|
||||||
|
|
||||||
|
expect($method->invoke(null))->toMatchArray([
|
||||||
|
'client_capture' => 12.345,
|
||||||
|
'client_preflight' => 1.5,
|
||||||
|
'client_draw' => 2.25,
|
||||||
|
'client_encode' => 8.5,
|
||||||
|
'client_visual_fingerprint' => 0.75,
|
||||||
|
'client_frame_width' => 384.0,
|
||||||
|
'client_frame_height' => 216.0,
|
||||||
|
'client_frame_bytes' => 12345.0,
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
$_GET = $previousGet;
|
||||||
|
$_POST = $previousPost;
|
||||||
|
foreach ($previousHeaders as $headerName => $previousValue) {
|
||||||
|
if ($previousValue === null) {
|
||||||
|
unset($_SERVER[$headerName]);
|
||||||
|
} else {
|
||||||
|
$_SERVER[$headerName] = $previousValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
it('services broker transport before replaying queued outbox items', function (): void {
|
||||||
|
$agentSource = (string)file_get_contents(app_path('resources/edge-gateway-agent/agent.php'));
|
||||||
|
$runOffset = strpos($agentSource, 'public function run(): void');
|
||||||
|
expect($runOffset)->not->toBeFalse();
|
||||||
|
|
||||||
|
$loopSource = substr($agentSource, (int)$runOffset, 1800);
|
||||||
|
$configureOffset = strpos($loopSource, '$this->configureBrokerClient();');
|
||||||
|
$pumpOffset = strpos($loopSource, '$this->pumpBrokerTransport();');
|
||||||
|
$flushOffset = strpos($loopSource, '$this->flushOutbox();');
|
||||||
|
|
||||||
|
expect($configureOffset)->not->toBeFalse()
|
||||||
|
->and($pumpOffset)->not->toBeFalse()
|
||||||
|
->and($flushOffset)->not->toBeFalse()
|
||||||
|
->and((int)$configureOffset)->toBeLessThan((int)$pumpOffset)
|
||||||
|
->and((int)$pumpOffset)->toBeLessThan((int)$flushOffset);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bounds stale outbox replay so it cannot monopolize the gateway loop', function (): void {
|
||||||
|
$agentSource = (string)file_get_contents(app_path('resources/edge-gateway-agent/agent.php'));
|
||||||
|
|
||||||
|
expect($agentSource)->toContain('private const OUTBOX_REPLAY_BATCH_LIMIT = 3;')
|
||||||
|
->and($agentSource)->toContain('private const OUTBOX_REPLAY_TIMEOUT_SECONDS = 3;')
|
||||||
|
->and($agentSource)->toContain('private const OUTBOX_OPERATION_COMPLETE_REPLAY_TIMEOUT_SECONDS = 10;')
|
||||||
|
->and($agentSource)->toContain('private const OUTBOX_REPLAY_FAILURE_COOLDOWN_SECONDS = 15;')
|
||||||
|
->and($agentSource)->toContain('private int $lastOutboxFailureAt = 0;')
|
||||||
|
->and($agentSource)->toContain('$this->stateStore->queuedItems(self::OUTBOX_REPLAY_BATCH_LIMIT)')
|
||||||
|
->and($agentSource)->toContain('private function shouldSkipOutboxReplay(): bool')
|
||||||
|
->and($agentSource)->toContain('$this->lastOutboxFailureAt = time();')
|
||||||
|
->and($agentSource)->toContain('? self::OUTBOX_OPERATION_COMPLETE_REPLAY_TIMEOUT_SECONDS')
|
||||||
|
->and($agentSource)->toContain(': self::OUTBOX_REPLAY_TIMEOUT_SECONDS;');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps draining API command jobs while broker transport is connected', function (): void {
|
||||||
|
$agentSource = (string)file_get_contents(app_path('resources/edge-gateway-agent/agent.php'));
|
||||||
|
$runOffset = strpos($agentSource, 'public function run(): void');
|
||||||
|
expect($runOffset)->not->toBeFalse();
|
||||||
|
|
||||||
|
$loopSource = substr($agentSource, (int)$runOffset, 1900);
|
||||||
|
|
||||||
|
expect($agentSource)->toContain('private const BROKER_CONNECTED_COMMAND_POLL_INTERVAL_SECONDS = 1;')
|
||||||
|
->and($agentSource)->toContain('private int $lastBrokerConnectedCommandPollAt = 0;')
|
||||||
|
->and($agentSource)->toContain('private function shouldPollApiCommandQueue(bool $brokerConnected): bool')
|
||||||
|
->and($agentSource)->toContain('private function processCommandQueue(?int $waitSecondsOverride = null): void')
|
||||||
|
->and($loopSource)->toContain('$brokerConnected = $this->isBrokerConnected();')
|
||||||
|
->and($loopSource)->toContain('if (!$brokerConnected) {')
|
||||||
|
->and($loopSource)->toContain('$processedManagementOperation = $this->processManagementOperation();')
|
||||||
|
->and($loopSource)->toContain('$this->processCommandQueue($brokerConnected ? 0 : null);');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses a short control-plane timeout for self-serve machine signals before queueing', function (): void {
|
||||||
|
$agentSource = (string)file_get_contents(app_path('resources/edge-gateway-agent/agent.php'));
|
||||||
|
|
||||||
|
expect($agentSource)->toContain('private const MACHINE_SIGNAL_TIMEOUT_SECONDS = 3;')
|
||||||
|
->and($agentSource)->toContain('private function sendControlPlaneEvent(string $endpoint, array $payload, string $type, int $timeoutSeconds = 20): bool')
|
||||||
|
->and($agentSource)->toContain("'machine_signal',\n self::MACHINE_SIGNAL_TIMEOUT_SECONDS");
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user