Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0de0e9d6b | ||
|
|
574b263a54 | ||
|
|
36ff5bb438 | ||
|
|
1beca924fc | ||
|
|
d605eca574 | ||
|
|
cea469c95a | ||
|
|
7e85c74e60 | ||
|
|
67d62eff70 | ||
|
|
8ebbd52a99 | ||
|
|
6d6cc501db | ||
|
|
ce999afbb3 | ||
|
|
cb34b030c8 | ||
|
|
e26034dfae | ||
|
|
0aad41fd0f | ||
|
|
5c67fe419f | ||
|
|
aca8be51dc | ||
|
|
fb1f0883e1 | ||
|
|
6446eb2e36 | ||
|
|
a1224ec2f4 | ||
|
|
07441c4ed1 | ||
|
|
cd100f1180 | ||
|
|
4fc66c72b8 | ||
|
|
a3ea5fee83 | ||
|
|
ef8d97c821 | ||
|
|
327a77edf4 | ||
|
|
d8abc8f87d | ||
|
|
325b35beb7 | ||
|
|
49364864d2 | ||
|
|
a19178a042 | ||
|
|
91d3332d4e | ||
|
|
bedbf21c29 | ||
|
|
75c19bcce4 | ||
|
|
458fe7399d | ||
|
|
2b6a8eedcc | ||
|
|
c0ed107f75 | ||
|
|
30dceff0b5 | ||
|
|
716929bd7b | ||
|
|
3d221f3379 | ||
|
|
6f1c160fbb | ||
|
|
9694695f00 | ||
|
|
1d43221b4d | ||
|
|
33b7c3e51a | ||
|
|
1e64bd63b8 | ||
|
|
bcbc2481c3 | ||
|
|
8288a1069c | ||
|
|
1b99523366 |
@@ -9,7 +9,7 @@ on:
|
||||
|
||||
jobs:
|
||||
assign-task:
|
||||
runs-on: [self-hosted, Linux, X64, default]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
|
||||
@@ -164,7 +164,30 @@ jobs:
|
||||
| docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml exec -T php1 tar -C /var/www/html -xf -
|
||||
|
||||
- name: Resolve dependencies
|
||||
run: docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml exec -T php1 sh -lc "cd /var/www/html && composer install --no-interaction --prefer-dist --no-progress"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
composer_install() {
|
||||
install_mode="$1"
|
||||
max_attempts="$2"
|
||||
attempt=1
|
||||
while :; do
|
||||
if docker compose -f docker-compose.yml -f .github/docker-compose.ci.yml exec -T php1 sh -lc "cd /var/www/html && composer install --no-interaction ${install_mode} --no-progress"; then
|
||||
return 0
|
||||
fi
|
||||
if [ "$attempt" -ge "$max_attempts" ]; then
|
||||
return 1
|
||||
fi
|
||||
sleep_seconds=$((attempt * 5))
|
||||
echo "composer install ${install_mode} failed; retrying in ${sleep_seconds}s (attempt $((attempt + 1))/${max_attempts})" >&2
|
||||
sleep "$sleep_seconds"
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
}
|
||||
|
||||
composer_install --prefer-dist 3 || {
|
||||
echo "Composer dist install failed; retrying with --prefer-source." >&2
|
||||
composer_install --prefer-source 2
|
||||
}
|
||||
|
||||
- name: Verify edge gateway test files
|
||||
run: >
|
||||
@@ -279,7 +302,7 @@ jobs:
|
||||
-X POST "$RELEASE_MANAGER_GATE_URL" \
|
||||
-H "Authorization: Bearer $RELEASE_MANAGER_GATE_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data "{\"channel_slug\":\"stable\",\"app\":\"api\",\"repository\":\"$RELEASE_REPOSITORY\",\"branch\":\"$RELEASE_BRANCH\",\"expected_commit\":\"$RELEASE_EXPECTED_COMMIT\",\"workflow_url\":\"$RELEASE_WORKFLOW_URL\",\"auto_sync\":true,\"wait_timeout_seconds\":300,\"poll_interval_seconds\":10,\"required_checks\":[]}")"
|
||||
--data "{\"channel_slug\":\"stable\",\"app\":\"api\",\"repository\":\"$RELEASE_REPOSITORY\",\"branch\":\"$RELEASE_BRANCH\",\"expected_commit\":\"$RELEASE_EXPECTED_COMMIT\",\"workflow_url\":\"$RELEASE_WORKFLOW_URL\",\"auto_sync\":true,\"wait_timeout_seconds\":300,\"poll_interval_seconds\":10,\"required_checks\":[\"api_gateway\"]}")"
|
||||
response_body="$(cat "$response_file")"
|
||||
rm -f "$response_file"
|
||||
|
||||
|
||||
Binary file not shown.
@@ -3,6 +3,8 @@ services:
|
||||
traefik:
|
||||
image: traefik:2.11
|
||||
container_name: traefik
|
||||
group_add:
|
||||
- "${DOCKER_SOCKET_GID:-65534}"
|
||||
ports:
|
||||
- "${TRAEFIK_WEB_PORT:-80}:80"
|
||||
- "${TRAEFIK_WEBSECURE_PORT:-443}:443"
|
||||
@@ -102,6 +104,7 @@ services:
|
||||
image: mysql:8.4
|
||||
container_name: mysql-debug
|
||||
profiles: [dev]
|
||||
command: ["mysqld", "--innodb-use-native-aio=0"]
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${CONFIG_DB_DEBUG_PASSWORD:?CONFIG_DB_DEBUG_PASSWORD is required for mysql-debug}
|
||||
MYSQL_DATABASE: ${CONFIG_DB_DEBUG_DATABASE:-nnks_db_debug}
|
||||
|
||||
@@ -3357,6 +3357,9 @@
|
||||
},
|
||||
"email_notifications_enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"superuser_new_customer_email_notifications_enabled": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12955,6 +12958,54 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/slack/config": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Config"
|
||||
],
|
||||
"summary": "Get Slack config",
|
||||
"operationId": "getSlackConfig",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Slack configuration retrieved successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SlackConfigListResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Config"
|
||||
],
|
||||
"summary": "Update Slack config",
|
||||
"operationId": "updateSlackConfig",
|
||||
"requestBody": {
|
||||
"required": false,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Slack configuration updated successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ModuleConfigUpdateResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/backups/config": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -15496,6 +15547,39 @@
|
||||
"value"
|
||||
]
|
||||
},
|
||||
"SlackConfigEntry": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"module": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Slack"
|
||||
]
|
||||
},
|
||||
"variable": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"customer_registration_webhook_url"
|
||||
]
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"example": "https://hooks.slack.com/services/..."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"module",
|
||||
"variable",
|
||||
"type",
|
||||
"value"
|
||||
]
|
||||
},
|
||||
"BackupsConfigEntry": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -16240,6 +16324,27 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"SlackConfigListResponse": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/ModuleConfigEnvelopeBase"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/SlackConfigEntry"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"BackupsConfigListResponse": {
|
||||
"allOf": [
|
||||
{
|
||||
|
||||
+2921
-199
File diff suppressed because it is too large
Load Diff
+132545
File diff suppressed because one or more lines are too long
+17
-2
@@ -68,6 +68,22 @@ retry_command() {
|
||||
done
|
||||
}
|
||||
|
||||
composer_install() {
|
||||
dist_attempts="${PHP_CI_COMPOSER_RETRIES:-3}"
|
||||
source_attempts="${PHP_CI_COMPOSER_SOURCE_RETRIES:-2}"
|
||||
|
||||
if retry_command "$dist_attempts" \
|
||||
docker compose $compose_files exec -T php1 sh -lc \
|
||||
'cd /var/www/html && composer install --no-interaction --prefer-dist --no-progress'; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Composer dist install failed after ${dist_attempts} attempts; retrying with --prefer-source." >&2
|
||||
retry_command "$source_attempts" \
|
||||
docker compose $compose_files exec -T php1 sh -lc \
|
||||
'cd /var/www/html && composer install --no-interaction --prefer-source --no-progress'
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
status="$?"
|
||||
collect_logs "$status"
|
||||
@@ -112,8 +128,7 @@ tar \
|
||||
-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 sh -lc \
|
||||
'cd /var/www/html && composer install --no-interaction --prefer-dist --no-progress'
|
||||
composer_install
|
||||
|
||||
docker compose $compose_files exec -T php1 sh -lc \
|
||||
"cd /var/www/html && composer test:ci:$suite"
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -12204,3 +12204,251 @@
|
||||
[Tue May 26 09:31:07 2026] 127.0.0.1:38284 Closing
|
||||
[Tue May 26 09:31:08 2026] 127.0.0.1:38290 Accepted
|
||||
[Tue May 26 09:31:12 2026] 127.0.0.1:38290 Closing
|
||||
[Tue Jun 2 12:55:52 2026] PHP 8.2.15 Development Server (http://127.0.0.1:45377) started
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52720 Accepted
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52720 Closing
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52734 Accepted
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52734 Closing
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52742 Accepted
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52742 Closing
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52750 Accepted
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52750 Closing
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52766 Accepted
|
||||
[Tue Jun 2 12:55:52 2026] 127.0.0.1:52766 Closing
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52770 Accepted
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52770 Closing
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52784 Accepted
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52784 Closing
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52792 Accepted
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52792 Closing
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52802 Accepted
|
||||
[Tue Jun 2 12:55:53 2026] 127.0.0.1:52802 Closing
|
||||
[Tue Jun 2 12:59:15 2026] PHP 8.2.15 Development Server (http://127.0.0.1:42651) started
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41826 Accepted
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41826 Closing
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41842 Accepted
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41842 Closing
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41850 Accepted
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41850 Closing
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41860 Accepted
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41860 Closing
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41874 Accepted
|
||||
[Tue Jun 2 12:59:15 2026] 127.0.0.1:41874 Closing
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41884 Accepted
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41884 Closing
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41894 Accepted
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41894 Closing
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41902 Accepted
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41902 Closing
|
||||
[Tue Jun 2 12:59:16 2026] 127.0.0.1:41916 Accepted
|
||||
[Tue Jun 2 12:59:37 2026] 127.0.0.1:41916 Closing
|
||||
[Tue Jun 2 13:02:13 2026] PHP 8.2.15 Development Server (http://127.0.0.1:38777) started
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37238 Accepted
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37238 Closing
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37252 Accepted
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37252 Closing
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37256 Accepted
|
||||
[Tue Jun 2 13:02:13 2026] 127.0.0.1:37256 Closing
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35516 Accepted
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35516 Closing
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35518 Accepted
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35518 Closing
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35528 Accepted
|
||||
[Tue Jun 2 13:02:15 2026] 127.0.0.1:35528 Closing
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35544 Accepted
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35544 Closing
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35552 Accepted
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35552 Closing
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35568 Accepted
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35568 Closing
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35582 Accepted
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35582 Closing
|
||||
[Tue Jun 2 13:02:16 2026] 127.0.0.1:35586 Accepted
|
||||
[Tue Jun 2 13:02:17 2026] 127.0.0.1:35586 Closing
|
||||
[Tue Jun 2 13:02:17 2026] 127.0.0.1:35588 Accepted
|
||||
[Tue Jun 2 13:02:17 2026] 127.0.0.1:35588 Closing
|
||||
[Tue Jun 2 13:02:19 2026] 127.0.0.1:35596 Accepted
|
||||
[Tue Jun 2 13:02:20 2026] 127.0.0.1:35596 Closing
|
||||
[Tue Jun 2 13:02:20 2026] 127.0.0.1:35600 Accepted
|
||||
[Tue Jun 2 13:02:20 2026] 127.0.0.1:35600 Closing
|
||||
[Tue Jun 2 13:02:20 2026] 127.0.0.1:35612 Accepted
|
||||
[Tue Jun 2 13:02:20 2026] 127.0.0.1:35612 Closing
|
||||
[Tue Jun 2 13:02:46 2026] PHP 8.2.15 Development Server (http://127.0.0.1:39573) started
|
||||
[Tue Jun 2 13:02:46 2026] 127.0.0.1:43488 Accepted
|
||||
[Tue Jun 2 13:02:46 2026] 127.0.0.1:43488 Closing
|
||||
[Tue Jun 2 13:02:46 2026] 127.0.0.1:43494 Accepted
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43494 Closing
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43502 Accepted
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43502 Closing
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43504 Accepted
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43504 Closing
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43516 Accepted
|
||||
[Tue Jun 2 13:02:47 2026] 127.0.0.1:43516 Closing
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43530 Accepted
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43530 Closing
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43540 Accepted
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43540 Closing
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43550 Accepted
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43550 Closing
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43562 Accepted
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43562 Closing
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43578 Accepted
|
||||
[Tue Jun 2 13:02:53 2026] 127.0.0.1:43578 Closing
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51950 Accepted
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51950 Closing
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51952 Accepted
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51952 Closing
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51964 Accepted
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51964 Closing
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51978 Accepted
|
||||
[Tue Jun 2 13:02:54 2026] 127.0.0.1:51978 Closing
|
||||
[Tue Jun 2 13:02:55 2026] 127.0.0.1:51994 Accepted
|
||||
[Tue Jun 2 13:02:55 2026] 127.0.0.1:51994 Closing
|
||||
[Tue Jun 2 13:25:35 2026] PHP 8.2.15 Development Server (http://127.0.0.1:40811) started
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43736 Accepted
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43736 Closing
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43740 Accepted
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43740 Closing
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43754 Accepted
|
||||
[Tue Jun 2 13:25:35 2026] 127.0.0.1:43754 Closing
|
||||
[Tue Jun 2 13:25:36 2026] 127.0.0.1:43768 Accepted
|
||||
[Tue Jun 2 13:25:36 2026] 127.0.0.1:43768 Closing
|
||||
[Tue Jun 2 13:25:36 2026] 127.0.0.1:43776 Accepted
|
||||
[Tue Jun 2 13:25:36 2026] 127.0.0.1:43776 Closing
|
||||
[Tue Jun 2 13:25:52 2026] 127.0.0.1:57442 Accepted
|
||||
[Tue Jun 2 13:25:52 2026] 127.0.0.1:57442 Closing
|
||||
[Tue Jun 2 13:25:52 2026] 127.0.0.1:57452 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57452 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57460 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57460 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57472 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57472 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57486 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57486 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57492 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57492 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57508 Accepted
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57508 Closing
|
||||
[Tue Jun 2 13:25:53 2026] 127.0.0.1:57522 Accepted
|
||||
[Tue Jun 2 13:25:54 2026] 127.0.0.1:57522 Closing
|
||||
[Tue Jun 2 13:25:54 2026] 127.0.0.1:60940 Accepted
|
||||
[Tue Jun 2 13:25:54 2026] 127.0.0.1:60940 Closing
|
||||
[Tue Jun 2 13:25:54 2026] 127.0.0.1:60950 Accepted
|
||||
[Tue Jun 2 13:25:54 2026] 127.0.0.1:60950 Closing
|
||||
[Tue Jun 2 13:44:42 2026] PHP 8.2.15 Development Server (http://127.0.0.1:37125) started
|
||||
[Tue Jun 2 13:44:42 2026] 127.0.0.1:45382 Accepted
|
||||
[Tue Jun 2 13:44:42 2026] 127.0.0.1:45382 Closing
|
||||
[Tue Jun 2 13:44:42 2026] 127.0.0.1:45388 Accepted
|
||||
[Tue Jun 2 13:44:42 2026] 127.0.0.1:45388 Closing
|
||||
[Tue Jun 2 13:44:42 2026] 127.0.0.1:45398 Accepted
|
||||
[Tue Jun 2 13:44:43 2026] 127.0.0.1:45398 Closing
|
||||
[Tue Jun 2 13:44:43 2026] 127.0.0.1:45410 Accepted
|
||||
[Tue Jun 2 13:44:46 2026] 127.0.0.1:45410 Closing
|
||||
[Tue Jun 2 13:44:46 2026] 127.0.0.1:53928 Accepted
|
||||
[Tue Jun 2 13:44:46 2026] 127.0.0.1:53928 Closing
|
||||
[Tue Jun 2 13:44:51 2026] PHP 8.2.15 Development Server (http://127.0.0.1:34643) started
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46776 Accepted
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46776 Closing
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46782 Accepted
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46782 Closing
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46796 Accepted
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46796 Closing
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46806 Accepted
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46806 Closing
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46816 Accepted
|
||||
[Tue Jun 2 13:44:51 2026] 127.0.0.1:46816 Closing
|
||||
[Tue Jun 2 13:44:52 2026] 127.0.0.1:46824 Accepted
|
||||
[Tue Jun 2 13:44:52 2026] 127.0.0.1:46824 Closing
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46836 Accepted
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46836 Closing
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46846 Accepted
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46846 Closing
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46848 Accepted
|
||||
[Tue Jun 2 13:44:53 2026] 127.0.0.1:46848 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45254 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45254 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45264 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45264 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45276 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45276 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45282 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45282 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45288 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45288 Closing
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45296 Accepted
|
||||
[Tue Jun 2 13:44:54 2026] 127.0.0.1:45296 Closing
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45312 Accepted
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45312 Closing
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45314 Accepted
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45314 Closing
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45328 Accepted
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45328 Closing
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45330 Accepted
|
||||
[Tue Jun 2 13:44:55 2026] 127.0.0.1:45330 Closing
|
||||
[Tue Jun 2 14:14:22 2026] PHP 8.2.15 Development Server (http://127.0.0.1:41283) started
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54804 Accepted
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54804 Closing
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54812 Accepted
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54812 Closing
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54816 Accepted
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54816 Closing
|
||||
[Tue Jun 2 14:14:22 2026] 127.0.0.1:54826 Accepted
|
||||
[Tue Jun 2 14:14:23 2026] 127.0.0.1:54826 Closing
|
||||
[Tue Jun 2 14:14:23 2026] 127.0.0.1:54828 Accepted
|
||||
[Tue Jun 2 14:14:25 2026] 127.0.0.1:54828 Closing
|
||||
[Tue Jun 2 14:14:25 2026] 127.0.0.1:45644 Accepted
|
||||
[Tue Jun 2 14:14:25 2026] 127.0.0.1:45644 Closing
|
||||
[Tue Jun 2 14:14:42 2026] PHP 8.2.15 Development Server (http://127.0.0.1:40157) started
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46410 Accepted
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46410 Closing
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46414 Accepted
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46414 Closing
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46424 Accepted
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46424 Closing
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46440 Accepted
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46440 Closing
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46442 Accepted
|
||||
[Tue Jun 2 14:14:42 2026] 127.0.0.1:46442 Closing
|
||||
[Tue Jun 2 14:14:43 2026] 127.0.0.1:46458 Accepted
|
||||
[Tue Jun 2 14:14:43 2026] 127.0.0.1:46458 Closing
|
||||
[Tue Jun 2 14:16:10 2026] PHP 8.2.15 Development Server (http://127.0.0.1:38915) started
|
||||
[Tue Jun 2 14:16:10 2026] 127.0.0.1:54470 Accepted
|
||||
[Tue Jun 2 14:16:10 2026] 127.0.0.1:54470 Closing
|
||||
[Tue Jun 2 14:16:10 2026] 127.0.0.1:54482 Accepted
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54482 Closing
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54492 Accepted
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54492 Closing
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54498 Accepted
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54498 Closing
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54508 Accepted
|
||||
[Tue Jun 2 14:16:11 2026] 127.0.0.1:54508 Closing
|
||||
[Tue Jun 2 14:16:24 2026] 127.0.0.1:48044 Accepted
|
||||
[Tue Jun 2 14:16:24 2026] 127.0.0.1:48044 Closing
|
||||
[Tue Jun 2 14:16:25 2026] 127.0.0.1:48060 Accepted
|
||||
[Tue Jun 2 14:16:25 2026] 127.0.0.1:48060 Closing
|
||||
[Tue Jun 2 14:16:27 2026] 127.0.0.1:48072 Accepted
|
||||
[Tue Jun 2 14:16:27 2026] 127.0.0.1:48072 Closing
|
||||
[Tue Jun 2 14:16:27 2026] 127.0.0.1:48088 Accepted
|
||||
[Tue Jun 2 14:16:28 2026] 127.0.0.1:48088 Closing
|
||||
[Tue Jun 2 14:16:28 2026] 127.0.0.1:48094 Accepted
|
||||
[Tue Jun 2 14:16:28 2026] 127.0.0.1:48094 Closing
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55000 Accepted
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55000 Closing
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55006 Accepted
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55006 Closing
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55016 Accepted
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55016 Closing
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55018 Accepted
|
||||
[Tue Jun 2 14:16:34 2026] 127.0.0.1:55018 Closing
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55022 Accepted
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55022 Closing
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55032 Accepted
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55032 Closing
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55048 Accepted
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55048 Closing
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55060 Accepted
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55060 Closing
|
||||
[Tue Jun 2 14:16:35 2026] 127.0.0.1:55074 Accepted
|
||||
[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 Closing
|
||||
|
||||
@@ -133,8 +133,14 @@ class attachments implements attachments_i
|
||||
protected function fetchAttachmentRows(string $type, array $object_ids, array $options = []): array
|
||||
{
|
||||
$options = $this->normalizeAttachmentOptions($options);
|
||||
$rawType = trim($type, '`');
|
||||
$objectTypes = array_values(array_unique([
|
||||
$rawType,
|
||||
'`' . $rawType . '`',
|
||||
]));
|
||||
|
||||
return (new object_attachments_o())->getFieldsWhereIn([
|
||||
'object_type' => $type,
|
||||
'object_type' => $objectTypes,
|
||||
'object_id' => $object_ids,
|
||||
'deleted_at' => null
|
||||
], $options);
|
||||
|
||||
@@ -121,6 +121,16 @@ class coolify_api_client
|
||||
]);
|
||||
}
|
||||
|
||||
public function listApplicationEnvs(string $uuid): array
|
||||
{
|
||||
return $this->request('GET', '/applications/' . rawurlencode($uuid) . '/envs');
|
||||
}
|
||||
|
||||
public function deleteApplicationEnv(string $uuid, string $envUuid): array
|
||||
{
|
||||
return $this->request('DELETE', '/applications/' . rawurlencode($uuid) . '/envs/' . rawurlencode($envUuid));
|
||||
}
|
||||
|
||||
private static function bulkEnvData(array $env): array
|
||||
{
|
||||
$data = [];
|
||||
@@ -159,6 +169,11 @@ class coolify_api_client
|
||||
return $this->request('GET', '/applications/' . rawurlencode($uuid) . '/restart');
|
||||
}
|
||||
|
||||
public function stopApplication(string $uuid): array
|
||||
{
|
||||
return $this->request('GET', '/applications/' . rawurlencode($uuid) . '/stop');
|
||||
}
|
||||
|
||||
public function deleteService(string $uuid): array
|
||||
{
|
||||
return $this->request('DELETE', '/services/' . rawurlencode($uuid));
|
||||
|
||||
@@ -25,6 +25,9 @@ class cors_policy
|
||||
'https://localhost:4433',
|
||||
'https://twdev.jeppeb.dk',
|
||||
'http://localhost:5173',
|
||||
'http://localhost:5174',
|
||||
'http://127.0.0.1:5173',
|
||||
'http://127.0.0.1:5174',
|
||||
];
|
||||
|
||||
public static function normalizeOrigin(?string $value): string
|
||||
|
||||
@@ -128,13 +128,13 @@ use Psr\Http\Client\ClientExceptionInterface;
|
||||
private function sendEmailMailerSend(string $to, string $recipient_name, string $subject, string $message, string $html = null, string $references = null, array $attachments = []): void
|
||||
{
|
||||
if (self::isFakeDeliveryEnabled()) {
|
||||
self::$fake_deliveries[] = [
|
||||
self::recordFakeDelivery([
|
||||
'to' => $to,
|
||||
'recipient_name' => $recipient_name,
|
||||
'subject' => $subject,
|
||||
'message' => $message,
|
||||
'html' => $html,
|
||||
];
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -225,6 +225,72 @@ use Psr\Http\Client\ClientExceptionInterface;
|
||||
public static function resetFakeDeliveries(): void
|
||||
{
|
||||
self::$fake_deliveries = [];
|
||||
$path = self::getFakeDeliveriesPath();
|
||||
if ($path !== null && is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
public static function syncFakeDeliveries(): void
|
||||
{
|
||||
$path = self::getFakeDeliveriesPath();
|
||||
if ($path === null || !is_file($path)) {
|
||||
self::$fake_deliveries = [];
|
||||
return;
|
||||
}
|
||||
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
if ($lines === false) {
|
||||
self::$fake_deliveries = [];
|
||||
return;
|
||||
}
|
||||
|
||||
$deliveries = [];
|
||||
foreach ($lines as $line) {
|
||||
$delivery = json_decode($line, true);
|
||||
if (is_array($delivery)) {
|
||||
$deliveries[] = $delivery;
|
||||
}
|
||||
}
|
||||
|
||||
self::$fake_deliveries = $deliveries;
|
||||
}
|
||||
|
||||
private static function recordFakeDelivery(array $delivery): void
|
||||
{
|
||||
self::$fake_deliveries[] = $delivery;
|
||||
|
||||
$path = self::getFakeDeliveriesPath();
|
||||
if ($path === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$directory = dirname($path);
|
||||
if (!is_dir($directory)) {
|
||||
mkdir($directory, 0777, true);
|
||||
}
|
||||
|
||||
file_put_contents($path, json_encode($delivery, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
|
||||
private static function getFakeDeliveriesPath(): ?string
|
||||
{
|
||||
if (!self::isFakeDeliveryEnabled()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$configuredPath = trim((string)(getenv('EMAIL_FAKE_DELIVERIES_PATH') ?: ''));
|
||||
if ($configuredPath !== '') {
|
||||
return $configuredPath;
|
||||
}
|
||||
|
||||
if (getenv('RUN_API_TESTS') !== '1') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR)
|
||||
. DIRECTORY_SEPARATOR
|
||||
. 'truckwash-email-fake-deliveries-' . md5((string)getcwd()) . '.jsonl';
|
||||
}
|
||||
|
||||
private static function isFakeDeliveryEnabled(): bool
|
||||
@@ -511,4 +577,47 @@ use Psr\Http\Client\ClientExceptionInterface;
|
||||
$this->attachments
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function sendNewCustomerRegistrationNotifications(int $customer_number): void
|
||||
{
|
||||
$customer = (new users_o())->getUserByCustomerNumber($customer_number);
|
||||
if (!$customer->exists()) {
|
||||
throw new Exception('Customer not found with customer number: ' . $customer_number);
|
||||
}
|
||||
|
||||
$customerName = $customer->getCustomerName((int)$customer->customer_number->value()) ?: 'Unknown customer';
|
||||
$safeCustomerName = htmlspecialchars($customerName, ENT_QUOTES, 'UTF-8');
|
||||
$safeCustomerNumber = (int)$customer->customer_number->value();
|
||||
$customerUrl = 'https://truckwash.io/superuser/users?search=' . $safeCustomerNumber;
|
||||
$message = "
|
||||
<p>A new customer has registered on truckwash.io.</p>
|
||||
<p>
|
||||
<strong>Customer number:</strong> $safeCustomerNumber<br>
|
||||
<strong>Customer name:</strong> $safeCustomerName
|
||||
</p>
|
||||
<p><a href='$customerUrl'>Open customer in Superuser</a></p>
|
||||
";
|
||||
|
||||
foreach ((new users_o())->getSuperuserNewCustomerEmailNotificationRecipients() as $recipient) {
|
||||
$recipientEmail = trim((string)($recipient['email'] ?? ''));
|
||||
if ($recipientEmail === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$recipientName = trim((string)($recipient['display_name'] ?? ''));
|
||||
if ($recipientName === '') {
|
||||
$recipientName = $recipientEmail;
|
||||
}
|
||||
|
||||
$this->sendEmail(
|
||||
$recipientEmail,
|
||||
$recipientName,
|
||||
'New customer registered on Truck Wash',
|
||||
$message,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +47,12 @@ class pdf_store implements minio_pdfs_i
|
||||
*/
|
||||
public function download(string $file): string
|
||||
{
|
||||
if ($this->shouldUseLocalTestStorage()) {
|
||||
return $this->getLocalTestObjectPath($file);
|
||||
}
|
||||
|
||||
$path = '/tmp/' . $file;
|
||||
$result = self::getS3Client()->getObject([
|
||||
self::getS3Client()->getObject([
|
||||
'Bucket' => self::getBucket(),
|
||||
'Key' => $file,
|
||||
'SaveAs' => $path
|
||||
|
||||
@@ -1434,6 +1434,8 @@ class release_manager
|
||||
];
|
||||
}
|
||||
|
||||
$expectedCommit = self::normalizeCommitSha((string)($gateInput['expected_commit'] ?? ''));
|
||||
$enforceExpectedCommit = $expectedCommit !== '' && !$this->releaseGateAutoSyncRequested($gateInput);
|
||||
$checked = [];
|
||||
try {
|
||||
foreach ($gateInput['api_ping_paths'] as $path) {
|
||||
@@ -1442,9 +1444,19 @@ class release_manager
|
||||
if (array_key_exists('success', $payload) && $payload['success'] !== true) {
|
||||
throw new RuntimeException(sprintf('%s returned success=false.', $path));
|
||||
}
|
||||
$actualCommit = $this->releaseGateApiPayloadCommitSha($payload);
|
||||
if ($enforceExpectedCommit && !$this->releaseGateCommitMatches($actualCommit, $expectedCommit)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'%s returned commit %s, expected %s.',
|
||||
$path,
|
||||
$actualCommit !== '' ? $actualCommit : 'unknown',
|
||||
$expectedCommit
|
||||
));
|
||||
}
|
||||
$checked[] = [
|
||||
'path' => $path,
|
||||
'status' => $json['status'],
|
||||
'commit_sha' => $actualCommit !== '' ? $actualCommit : null,
|
||||
];
|
||||
}
|
||||
} catch (Throwable $throwable) {
|
||||
@@ -1471,10 +1483,24 @@ class release_manager
|
||||
'context' => [
|
||||
'api_base_url' => $apiBaseUrl,
|
||||
'checked' => $checked,
|
||||
'expected_commit' => $expectedCommit !== '' ? $expectedCommit : null,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function releaseGateApiPayloadCommitSha(array $payload): string
|
||||
{
|
||||
$data = is_array($payload['data'] ?? null) ? $payload['data'] : $payload;
|
||||
foreach (['api_commit_sha', 'backend_version', 'commit_sha', 'version'] as $key) {
|
||||
$commit = self::normalizeCommitSha((string)($data[$key] ?? ''));
|
||||
if ($commit !== '') {
|
||||
return $commit;
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
private function releaseGateFetchJson(string $baseUrl, string $path): array
|
||||
{
|
||||
$result = $this->releaseGateFetch($this->releaseGateJoinUrl($baseUrl, $path));
|
||||
@@ -2066,11 +2092,7 @@ class release_manager
|
||||
|
||||
$eventId = (int)$event['id'];
|
||||
if (!$this->acquireReleaseAutoSyncLock($eventId)) {
|
||||
return [
|
||||
'step_status' => 'passed',
|
||||
'message' => 'Automatic container update is already being processed for this commit.',
|
||||
'auto_sync_event' => $this->publicReleaseAutoSyncEvent($event),
|
||||
];
|
||||
return $this->waitForReleaseAutoSyncEventResult($eventId, $channelId, $app, $commitSha, $gateInput);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -2152,6 +2174,67 @@ class release_manager
|
||||
}
|
||||
}
|
||||
|
||||
private function waitForReleaseAutoSyncEventResult(int $eventId, int $channelId, string $app, string $commitSha, array $gateInput): array
|
||||
{
|
||||
$timeout = max(0, min(300, (int)($gateInput['wait_timeout_seconds'] ?? 300)));
|
||||
$pollInterval = max(1, min(60, (int)($gateInput['poll_interval_seconds'] ?? 10)));
|
||||
$deadline = time() + $timeout;
|
||||
$attempts = 0;
|
||||
$lastStatus = 'unknown';
|
||||
|
||||
do {
|
||||
$attempts++;
|
||||
$event = $this->releaseAutoSyncEventById($eventId);
|
||||
if ($event === null) {
|
||||
throw new RuntimeException('Automatic container update disappeared while another request was processing it.');
|
||||
}
|
||||
|
||||
$lastStatus = (string)($event['status'] ?? 'unknown');
|
||||
if (in_array($lastStatus, ['promoted', 'deployed'], true)) {
|
||||
$deployment = null;
|
||||
$deploymentId = $this->nullablePositiveInt($event['deployment_id'] ?? null);
|
||||
if ($deploymentId !== null) {
|
||||
$deployment = $this->getDeployment($deploymentId);
|
||||
}
|
||||
$deployment ??= $this->currentDeploymentForChannelApp($channelId, $app);
|
||||
if ($deployment !== null && $this->releaseGateCommitMatches((string)($deployment['commit_sha'] ?? ''), $commitSha)) {
|
||||
return [
|
||||
'step_status' => 'passed',
|
||||
'message' => sprintf('%s container update completed by an in-flight request at %s.', strtoupper($app), substr($commitSha, 0, 12)),
|
||||
'deployment' => $this->publicDeployment($deployment),
|
||||
'auto_sync_event' => $this->publicReleaseAutoSyncEvent($event),
|
||||
'attempts' => $attempts,
|
||||
];
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'Automatic container update completed for event %d but the active %s deployment does not match %s.',
|
||||
$eventId,
|
||||
strtoupper($app),
|
||||
$commitSha
|
||||
));
|
||||
}
|
||||
|
||||
if ($lastStatus === 'failed') {
|
||||
$message = trim((string)($event['error_message'] ?? 'Automatic container update failed in another request.'));
|
||||
throw new RuntimeException($message !== '' ? $message : 'Automatic container update failed in another request.');
|
||||
}
|
||||
|
||||
if (time() >= $deadline) {
|
||||
break;
|
||||
}
|
||||
|
||||
sleep($pollInterval);
|
||||
} while (true);
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'Automatic container update is already being processed for event %d but did not finish within %d seconds; last status was %s.',
|
||||
$eventId,
|
||||
$timeout,
|
||||
$lastStatus
|
||||
));
|
||||
}
|
||||
|
||||
private function upsertReleaseAutoSyncEvent(array $input): array
|
||||
{
|
||||
$channelId = (int)$input['channel_id'];
|
||||
@@ -6232,6 +6315,7 @@ class release_manager
|
||||
}
|
||||
|
||||
$deployment = $client->deployResource($serviceUuid, $this->releaseCoolifyForceRebuild($context));
|
||||
$previousApplications = $this->stopCoolifyPreviousApplications($client, $context, $serviceUuid);
|
||||
return [
|
||||
'service_uuid' => $serviceUuid,
|
||||
'resource_type' => $resourceType,
|
||||
@@ -6241,9 +6325,76 @@ class release_manager
|
||||
'updated' => self::redactPayload($update ?? []),
|
||||
'runtime_env' => $runtimeEnvUpdate,
|
||||
'deployment' => self::redactPayload($deployment),
|
||||
'previous_applications' => self::redactPayload($previousApplications),
|
||||
];
|
||||
}
|
||||
|
||||
private function stopCoolifyPreviousApplications(coolify_api_client $client, array $context, string $activeUuid): array
|
||||
{
|
||||
$stopped = [];
|
||||
foreach ($this->releaseCoolifyPreviousApplicationUuids($context, $activeUuid) as $uuid) {
|
||||
try {
|
||||
$stopped[] = [
|
||||
'uuid' => $uuid,
|
||||
'status' => 'stop_requested',
|
||||
'result' => $client->stopApplication($uuid),
|
||||
];
|
||||
} catch (Throwable $throwable) {
|
||||
$stopped[] = [
|
||||
'uuid' => $uuid,
|
||||
'status' => 'warning',
|
||||
'error' => $throwable->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $stopped;
|
||||
}
|
||||
|
||||
private function releaseCoolifyPreviousApplicationUuids(array $context, string $activeUuid): array
|
||||
{
|
||||
$values = [];
|
||||
foreach ([
|
||||
'coolify_previous_application_uuid',
|
||||
'coolify_previous_artifact_app_uuid',
|
||||
'coolify_previous_artifact_application_uuid',
|
||||
'previous_application_uuid',
|
||||
'previous_app_uuid',
|
||||
] as $key) {
|
||||
if (is_scalar($context[$key] ?? null)) {
|
||||
$values[] = (string)$context[$key];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'coolify_previous_application_uuids',
|
||||
'coolify_previous_artifact_app_uuids',
|
||||
'previous_application_uuids',
|
||||
'previous_app_uuids',
|
||||
] as $key) {
|
||||
if (!is_array($context[$key] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($context[$key] as $value) {
|
||||
if (is_scalar($value)) {
|
||||
$values[] = (string)$value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$activeUuid = trim($activeUuid);
|
||||
$uuids = [];
|
||||
foreach ($values as $value) {
|
||||
$uuid = trim((string)$value);
|
||||
if ($uuid === '' || $uuid === $activeUuid || in_array($uuid, $uuids, true)) {
|
||||
continue;
|
||||
}
|
||||
$uuids[] = $uuid;
|
||||
}
|
||||
|
||||
return $uuids;
|
||||
}
|
||||
|
||||
private function updateCoolifyReleaseRuntimeEnv(coolify_api_client $client, string $resourceUuid, string $resourceType, array $target, array $context): ?array
|
||||
{
|
||||
$env = $this->releaseCoolifyRuntimeEnv($target, $context);
|
||||
@@ -6252,6 +6403,7 @@ class release_manager
|
||||
}
|
||||
|
||||
if ($resourceType === 'application') {
|
||||
$this->deleteCoolifyGeneratedCommitEnvs($client, $resourceUuid, $target, $context);
|
||||
$client->updateApplicationEnvsBulk($resourceUuid, $env);
|
||||
} else {
|
||||
$client->updateServiceEnvsBulk($resourceUuid, $env);
|
||||
@@ -6264,12 +6416,45 @@ class release_manager
|
||||
];
|
||||
}
|
||||
|
||||
private function deleteCoolifyGeneratedCommitEnvs(coolify_api_client $client, string $resourceUuid, array $target, array $context): void
|
||||
{
|
||||
$keys = $this->releaseCoolifyGeneratedCommitEnvKeys($target, $context);
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$rows = $this->payloadRows($client->listApplicationEnvs($resourceUuid));
|
||||
} catch (Throwable) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$key = trim((string)($row['key'] ?? $row['name'] ?? ''));
|
||||
$uuid = trim((string)($row['uuid'] ?? $row['id'] ?? ''));
|
||||
if ($key === '' || $uuid === '' || !in_array($key, $keys, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$client->deleteApplicationEnv($resourceUuid, $uuid);
|
||||
} catch (Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function releaseCoolifyRuntimeEnv(array $target, array $context): array
|
||||
{
|
||||
$contextEnv = $this->releaseCoolifyContextEnv($context);
|
||||
$env = $contextEnv;
|
||||
$app = strtolower(trim((string)($target['app'] ?? '')));
|
||||
$deploymentCommitSha = self::normalizeCommitSha($this->releaseCoolifyGitCommitSha($target, $context));
|
||||
|
||||
if ($app !== 'api') {
|
||||
$this->applyReleaseCoolifyCommitRuntimeEnv($env, $app, $deploymentCommitSha);
|
||||
return $env;
|
||||
}
|
||||
|
||||
@@ -6291,21 +6476,37 @@ class release_manager
|
||||
$this->appendRuntimeEnvValue($env, $key, $value);
|
||||
}
|
||||
|
||||
$deploymentCommitSha = self::normalizeCommitSha($this->releaseCoolifyGitCommitSha($target, $context));
|
||||
if ($deploymentCommitSha !== '') {
|
||||
foreach (['API_COMMIT_SHA', 'COMMIT_SHA'] as $key) {
|
||||
if (!array_key_exists($key, $contextEnv)) {
|
||||
$env[$key] = $deploymentCommitSha;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$env = array_replace($env, $contextEnv);
|
||||
$env['USE_ENV'] = trim((string)($env['USE_ENV'] ?? '')) !== '' ? $env['USE_ENV'] : 'true';
|
||||
$env['CORS'] = cors_policy::withRequiredOrigins((string)($env['CORS'] ?? ''));
|
||||
$this->applyReleaseCoolifyCommitRuntimeEnv($env, $app, $deploymentCommitSha);
|
||||
return $this->normalizeCoolifyRuntimeEnv($env);
|
||||
}
|
||||
|
||||
private function applyReleaseCoolifyCommitRuntimeEnv(array &$env, string $app, string $deploymentCommitSha): void
|
||||
{
|
||||
if ($deploymentCommitSha === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($this->releaseCoolifyGeneratedCommitEnvKeys(['app' => $app], []) as $key) {
|
||||
$env[$key] = $deploymentCommitSha;
|
||||
}
|
||||
}
|
||||
|
||||
private function releaseCoolifyGeneratedCommitEnvKeys(array $target, array $context): array
|
||||
{
|
||||
$app = strtolower(trim((string)($target['app'] ?? $context['app'] ?? '')));
|
||||
if ($app === 'frontend') {
|
||||
return ['SOURCE_COMMIT', 'RELEASE_COMMIT_SHA', 'COMMIT_SHA', 'GITHUB_SHA', 'VITE_COMMIT_HASH'];
|
||||
}
|
||||
if ($app === 'api') {
|
||||
return ['API_COMMIT_SHA', 'COMMIT_SHA', 'GITHUB_SHA', 'RELEASE_COMMIT_SHA'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private function releaseCoolifyContextEnv(array $context): array
|
||||
{
|
||||
$env = [];
|
||||
@@ -7013,6 +7214,13 @@ class release_manager
|
||||
|
||||
private function releaseCoolifyGitCommitSha(array $target, array $context): string
|
||||
{
|
||||
foreach (['commit_sha', 'commit'] as $key) {
|
||||
$value = trim((string)($target[$key] ?? ''));
|
||||
if ($value !== '') {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'coolify_git_commit_sha',
|
||||
'git_commit_sha',
|
||||
@@ -8928,7 +9136,7 @@ class release_manager
|
||||
if (array_keys($payload) === range(0, count($payload) - 1)) {
|
||||
return $payload;
|
||||
}
|
||||
foreach (['data', 'services', 'projects', 'servers', 'github_apps', 'results'] as $key) {
|
||||
foreach (['data', 'services', 'projects', 'servers', 'github_apps', 'envs', 'environment_variables', 'results'] as $key) {
|
||||
if (is_array($payload[$key] ?? null)) {
|
||||
return $this->payloadRows($payload[$key]);
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ class selfserve_schema_bootstrap
|
||||
session_id INT NOT NULL,
|
||||
task_id INT NULL,
|
||||
task_text VARCHAR(255) NOT NULL,
|
||||
description VARCHAR(255) NULL,
|
||||
description TEXT NULL,
|
||||
services JSON NULL,
|
||||
buttons JSON NULL,
|
||||
dynamic_image_id INT NULL,
|
||||
@@ -197,6 +197,18 @@ class selfserve_schema_bootstrap
|
||||
'gate_ref_id',
|
||||
'ALTER TABLE department_selfserve_tasks ADD COLUMN gate_ref_id INT NULL AFTER gate_type'
|
||||
);
|
||||
self::ensureColumnDataType(
|
||||
'department_selfserve_tasks',
|
||||
'description',
|
||||
['text', 'mediumtext', 'longtext'],
|
||||
'ALTER TABLE department_selfserve_tasks MODIFY COLUMN description TEXT NULL AFTER task'
|
||||
);
|
||||
self::ensureColumnDataType(
|
||||
'selfserve_wash_session_tasks',
|
||||
'description',
|
||||
['text', 'mediumtext', 'longtext'],
|
||||
'ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text'
|
||||
);
|
||||
self::ensureColumn(
|
||||
'selfserve_wash_session_tasks',
|
||||
'dynamic_images_vehicle_type',
|
||||
@@ -239,4 +251,49 @@ class selfserve_schema_bootstrap
|
||||
}
|
||||
$db->query($alterSql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,string> $acceptedDataTypes
|
||||
*/
|
||||
public static function ensureColumnDataType(string $table, string $column, array $acceptedDataTypes, string $alterSql): void
|
||||
{
|
||||
global $db;
|
||||
|
||||
$columnInfo = self::columnInfo($table, $column);
|
||||
if ($columnInfo === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$dataType = strtolower((string)($columnInfo['DATA_TYPE'] ?? ''));
|
||||
$acceptedDataTypes = array_map(static fn(string $type): string => strtolower($type), $acceptedDataTypes);
|
||||
if (in_array($dataType, $acceptedDataTypes, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$db->query($alterSql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public static function columnInfo(string $table, string $column): ?array
|
||||
{
|
||||
global $db;
|
||||
$table = $db->escape_string($table);
|
||||
$column = $db->escape_string($column);
|
||||
$database = $db->escape_string($db->getDatabase());
|
||||
|
||||
$sql = "SELECT DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = '$database'
|
||||
AND TABLE_NAME = '$table'
|
||||
AND COLUMN_NAME = '$column'
|
||||
LIMIT 1";
|
||||
$result = $db->query($sql);
|
||||
if (!$result) {
|
||||
return null;
|
||||
}
|
||||
$row = $result->fetch_assoc();
|
||||
return is_array($row) ? $row : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ class shelly implements shelly_i
|
||||
private const SHELLY_RATE_LIMIT_WAIT_TIMEOUT_SECONDS = 20;
|
||||
private const SHELLY_RATE_LIMIT_WINDOW_MILLISECONDS = 2000;
|
||||
private const SHELLY_RATE_LIMIT_GATE_KEY = 'shelly_cloud_rate_limit_gate';
|
||||
private const SHELLY_CONNECT_TIMEOUT_SECONDS = 2;
|
||||
private const SHELLY_REQUEST_TIMEOUT_SECONDS = 5;
|
||||
/**
|
||||
* @var array<int,array<string,mixed>>
|
||||
*/
|
||||
@@ -178,6 +180,9 @@ class shelly implements shelly_i
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::SHELLY_CONNECT_TIMEOUT_SECONDS);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, self::SHELLY_REQUEST_TIMEOUT_SECONDS);
|
||||
curl_setopt($ch, CURLOPT_NOSIGNAL, true);
|
||||
// Execute the request
|
||||
$response = curl_exec($ch);
|
||||
// Get the status code
|
||||
@@ -224,6 +229,9 @@ class shelly implements shelly_i
|
||||
);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_HTTPGET, true);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::SHELLY_CONNECT_TIMEOUT_SECONDS);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, self::SHELLY_REQUEST_TIMEOUT_SECONDS);
|
||||
curl_setopt($ch, CURLOPT_NOSIGNAL, true);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
|
||||
@@ -6,13 +6,25 @@ use GuzzleHttp\Client;
|
||||
use interfaces\notification_i;
|
||||
use objects\departments_o;
|
||||
use objects\users_o;
|
||||
use slack\slack_c;
|
||||
use traits\notification_t;
|
||||
|
||||
require_once WD . '/modules/slack/slack_c.php';
|
||||
|
||||
class slack implements notification_i
|
||||
{
|
||||
use notification_t;
|
||||
|
||||
private ?slack_c $config = null;
|
||||
|
||||
public function getConfig(): slack_c
|
||||
{
|
||||
if ($this->config === null) {
|
||||
$this->config = new slack_c();
|
||||
}
|
||||
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
@@ -132,4 +144,38 @@ class slack implements notification_i
|
||||
// Send the message to the slack webhook
|
||||
self::add_log(self::send_webhook_message($string, $SLACK_DEFAULT_WEBHOOK));
|
||||
}
|
||||
}
|
||||
|
||||
public function send_customer_registration_notification(int $customer_number): self
|
||||
{
|
||||
$webhook = trim((string)$this->getConfig()->customer_registration_webhook_url->getVariableValue());
|
||||
if ($webhook === '') {
|
||||
return $this;
|
||||
}
|
||||
|
||||
self::add_log(self::send_webhook_message(
|
||||
$this->format_customer_registration($customer_number),
|
||||
$webhook
|
||||
));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function format_customer_registration(int $customer_number): string
|
||||
{
|
||||
$customer = (new users_o())->getUserByCustomerNumber($customer_number);
|
||||
$customerName = $customer->exists()
|
||||
? $customer->getCustomerName((int)$customer->customer_number->value())
|
||||
: '';
|
||||
$customerName = trim((string)$customerName);
|
||||
if ($customerName === '') {
|
||||
$customerName = 'Unknown customer';
|
||||
}
|
||||
|
||||
$safeCustomerNumber = (int)$customer_number;
|
||||
$customerUrl = 'https://truckwash.io/superuser/users?search=' . $safeCustomerNumber;
|
||||
|
||||
return "*New customer registered on Truck Wash*\n"
|
||||
. "Customer: $customerName ($safeCustomerNumber)\n"
|
||||
. "Open in Superuser: $customerUrl";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
{
|
||||
"scripts": {
|
||||
"test": "composer test:unit",
|
||||
"analyse": "vendor/bin/phpstan analyse --configuration=phpstan.neon.dist --memory-limit=1G --no-progress",
|
||||
"static": "@analyse",
|
||||
"rector:dry-run": "@php -d error_reporting=0 -d display_errors=0 -d log_errors=0 vendor/bin/rector process --dry-run --config rector.php",
|
||||
"rector:fix": "@php -d error_reporting=0 -d display_errors=0 -d log_errors=0 vendor/bin/rector process --config rector.php",
|
||||
"test:unit": "vendor/bin/pest --testsuite=Unit --colors=always",
|
||||
"test:integration": "vendor/bin/pest --testsuite=Integration --colors=always",
|
||||
"test:api": [
|
||||
|
||||
@@ -19,6 +19,8 @@ use classes\slack as Slack;
|
||||
use classes\email as Email;
|
||||
use classes\gatewayapi as GatewayAPI;
|
||||
use dynamicimages\images\machine_1;
|
||||
use modules\selfserve\config\selfserve_dynamic_image_size_c;
|
||||
use modules\selfserve\selfserve_c;
|
||||
use goals\classes\goals_criteria;
|
||||
use goals\services\goals_progress_alert_renderer;
|
||||
use goals\helpers\goals_criteria_progress_alert_destination as Dest;
|
||||
@@ -33,6 +35,8 @@ use objects\users_o;
|
||||
use routes\moduleWeatherAPIRoute;
|
||||
|
||||
require_once __DIR__ . '/../classes/economic_transfer_executor.php';
|
||||
|
||||
const DYNAMIC_IMAGE_RELEVANT_MAX_WIDTH = 1600;
|
||||
require_once __DIR__ . '/../classes/economic_transfer_queue_schema_bootstrap.php';
|
||||
require_once __DIR__ . '/../classes/economic_transfer_queue.php';
|
||||
require_once __DIR__ . '/../classes/workfeed_employee_name_formatter.php';
|
||||
@@ -930,6 +934,7 @@ function buildDynamicImageCacheKey(array $variant): string
|
||||
'current_step' => (int)($variant['current_step'] ?? 0),
|
||||
'only_current_step' => (bool)($variant['only_current_step'] ?? false),
|
||||
'vehicle_type' => $variant['vehicle_type'] ?? null,
|
||||
'dynamic_image_size' => getSelfServeDynamicImageSizeModeForCron(),
|
||||
];
|
||||
|
||||
$json = json_encode($cacheParams);
|
||||
@@ -962,16 +967,11 @@ function renderDynamicImageVariant(int $dynamicImageId, ?array $buttons, int $cu
|
||||
$image->current_step = max(0, $currentStep);
|
||||
$image->only_generate_current_step = $onlyCurrentStep;
|
||||
$image->setup();
|
||||
if (getSelfServeDynamicImageSizeModeForCron() === selfserve_dynamic_image_size_c::SIZE_RELEVANT) {
|
||||
$image->resizeToMaxWidth(DYNAMIC_IMAGE_RELEVANT_MAX_WIDTH);
|
||||
}
|
||||
|
||||
$dataUri = $image->exportAsBase64('png');
|
||||
if (!preg_match('/^data:image\/png;base64,(.*)$/', $dataUri, $matches)) {
|
||||
return null;
|
||||
}
|
||||
$imageData = base64_decode($matches[1], true);
|
||||
if ($imageData === false) {
|
||||
return null;
|
||||
}
|
||||
return $imageData;
|
||||
return $image->exportBinary('png');
|
||||
} catch (Throwable $e) {
|
||||
warn('PreRenderDynamicImagesCron: render failed for dynamic_image_id=' . $dynamicImageId . ': ' . $e->getMessage());
|
||||
return null;
|
||||
@@ -985,6 +985,19 @@ function renderDynamicImageVariant(int $dynamicImageId, ?array $buttons, int $cu
|
||||
}
|
||||
}
|
||||
|
||||
function getSelfServeDynamicImageSizeModeForCron(): string
|
||||
{
|
||||
try {
|
||||
$mode = (string)(new selfserve_c())->dynamic_image_size->getVariableValue();
|
||||
} catch (Throwable) {
|
||||
return selfserve_dynamic_image_size_c::SIZE_ORIGINAL;
|
||||
}
|
||||
|
||||
return in_array($mode, [selfserve_dynamic_image_size_c::SIZE_ORIGINAL, selfserve_dynamic_image_size_c::SIZE_RELEVANT], true)
|
||||
? $mode
|
||||
: selfserve_dynamic_image_size_c::SIZE_ORIGINAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return array<int|string>
|
||||
|
||||
@@ -86,6 +86,14 @@ interface dynamicimages_image_i
|
||||
*/
|
||||
public function exportAsBase64(?string $format = null, int $quality = 90): string;
|
||||
|
||||
/**
|
||||
* Export the composed image as binary image data.
|
||||
* @param string|null $format Optional target format (e.g. 'png', 'jpeg')
|
||||
* @param int $quality Quality for lossy formats (0-100)
|
||||
* @return string binary image data
|
||||
*/
|
||||
public function exportBinary(?string $format = null, int $quality = 90): string;
|
||||
|
||||
/**
|
||||
* Directly serve the composed image to the client with proper headers.
|
||||
* Convenience wrapper for outputting binary image data.
|
||||
@@ -94,4 +102,4 @@ interface dynamicimages_image_i
|
||||
* @param int $quality Quality for lossy formats (0-100)
|
||||
*/
|
||||
public function servePicture(?string $format = null, int $quality = 90): void;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,6 +226,20 @@ trait dynamicimages_image_t
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function resizeToMaxWidth(int $maxWidth): dynamicimages_image_i
|
||||
{
|
||||
$this->assertCanvasInitialized();
|
||||
if ($maxWidth <= 0) {
|
||||
throw new \InvalidArgumentException('Resize max width must be a positive integer.');
|
||||
}
|
||||
if ($this->canvasWidth === null || $this->canvasHeight === null || $this->canvasWidth <= $maxWidth) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$height = (int)round($this->canvasHeight * ($maxWidth / $this->canvasWidth));
|
||||
return $this->resize($maxWidth, max(1, $height));
|
||||
}
|
||||
|
||||
public function crop(int $width, int $height, int $x, int $y): dynamicimages_image_i
|
||||
{
|
||||
$this->assertCanvasInitialized();
|
||||
@@ -307,20 +321,8 @@ trait dynamicimages_image_t
|
||||
*/
|
||||
public function exportAsBase64(?string $format = null, int $quality = 90): string
|
||||
{
|
||||
// If a canvas is initialized, export that as PNG by default
|
||||
if ($this->image instanceof \Imagick) {
|
||||
$img = clone $this->image;
|
||||
$img->setImageFormat('png');
|
||||
// Quality influences compression for PNG differently; keep as hint
|
||||
if ($format !== null && strtolower($format) !== 'png') {
|
||||
// For now we only support PNG for composed images as requested
|
||||
}
|
||||
// Strip metadata to reduce size
|
||||
$img->stripImage();
|
||||
$blob = $img->getImageBlob();
|
||||
$img->clear();
|
||||
$img->destroy();
|
||||
return 'data:image/png;base64,' . base64_encode($blob);
|
||||
return 'data:image/png;base64,' . base64_encode($this->exportBinary($format, $quality));
|
||||
}
|
||||
|
||||
// Fallback: export first asset as-is
|
||||
@@ -341,6 +343,40 @@ trait dynamicimages_image_t
|
||||
return 'data:' . $mime . ';base64,' . base64_encode($data);
|
||||
}
|
||||
|
||||
public function exportBinary(?string $format = null, int $quality = 90): string
|
||||
{
|
||||
// If a canvas is initialized, export that as PNG by default
|
||||
if ($this->image instanceof \Imagick) {
|
||||
$img = clone $this->image;
|
||||
$img->setImageFormat('png');
|
||||
// Quality influences compression for PNG differently; keep as hint
|
||||
if ($format !== null && strtolower($format) !== 'png') {
|
||||
// For now we only support PNG for composed images as requested
|
||||
}
|
||||
// Strip metadata to reduce size
|
||||
$img->stripImage();
|
||||
$blob = $img->getImageBlob();
|
||||
$img->clear();
|
||||
$img->destroy();
|
||||
return $blob;
|
||||
}
|
||||
|
||||
// Fallback: export first asset as-is
|
||||
if (empty($this->assets)) {
|
||||
throw new \RuntimeException('No assets available to export.');
|
||||
}
|
||||
$asset = $this->assets[0];
|
||||
$path = $asset->getPath();
|
||||
if (!is_readable($path)) {
|
||||
throw new \RuntimeException('Asset is not readable: ' . $path);
|
||||
}
|
||||
$data = file_get_contents($path);
|
||||
if ($data === false) {
|
||||
throw new \RuntimeException('Failed to read asset: ' . $path);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getAsset(string $asset_name): ?dynamicimages_asset
|
||||
{
|
||||
foreach ($this->assets as $asset) {
|
||||
@@ -357,22 +393,18 @@ trait dynamicimages_image_t
|
||||
*/
|
||||
public function outputImage(?string $format = null, int $quality = 90): void
|
||||
{
|
||||
$dataUri = $this->exportAsBase64($format, $quality);
|
||||
// Extract mime type and base64 data
|
||||
if (preg_match('/^data:(image\/[a-zA-Z0-9+.-]+);base64,(.*)$/', $dataUri, $matches)) {
|
||||
$mimeType = $matches[1];
|
||||
$base64Data = $matches[2];
|
||||
// Decode base64 data
|
||||
$imageData = base64_decode($base64Data);
|
||||
if ($imageData !== false) {
|
||||
// Send appropriate headers
|
||||
header('Content-Type: ' . $mimeType);
|
||||
header('Content-Length: ' . strlen($imageData));
|
||||
// Output the image data
|
||||
echo $imageData;
|
||||
exit;
|
||||
}
|
||||
$mimeType = 'image/png';
|
||||
if (!$this->image instanceof \Imagick && !empty($this->assets)) {
|
||||
$asset = $this->assets[0];
|
||||
$path = $asset->getPath();
|
||||
$imgInfo = is_readable($path) ? @getimagesize($path) : false;
|
||||
$mimeType = is_array($imgInfo) && isset($imgInfo['mime']) ? $imgInfo['mime'] : 'application/octet-stream';
|
||||
}
|
||||
$imageData = $this->exportBinary($format, $quality);
|
||||
header('Content-Type: ' . $mimeType);
|
||||
header('Content-Length: ' . strlen($imageData));
|
||||
echo $imageData;
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -382,4 +414,4 @@ trait dynamicimages_image_t
|
||||
{
|
||||
$this->outputImage($format, $quality);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ class selfserve_lane_command_arguments
|
||||
public ?string $license_plate = null;
|
||||
public ?int $customer_number = null;
|
||||
public ?int $subuser_id = null;
|
||||
public ?string $wash_mode = null;
|
||||
public bool $defer_relay_side_effects = false;
|
||||
|
||||
/**
|
||||
@@ -32,6 +33,22 @@ class selfserve_lane_command_arguments
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setWashMode(?string $wash_mode): self
|
||||
{
|
||||
$normalized = strtolower(trim((string)$wash_mode));
|
||||
if ($wash_mode === null || $normalized === '') {
|
||||
$this->wash_mode = null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (!in_array($normalized, ['manual', 'machine'], true)) {
|
||||
throw new \InvalidArgumentException('Invalid wash type: ' . $wash_mode);
|
||||
}
|
||||
|
||||
$this->wash_mode = $normalized;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setDeferRelaySideEffects(bool $defer_relay_side_effects): self
|
||||
{
|
||||
$this->defer_relay_side_effects = $defer_relay_side_effects;
|
||||
@@ -50,6 +67,12 @@ class selfserve_lane_command_arguments
|
||||
if (array_key_exists('subuser_id', $params)) {
|
||||
$this->setSubuserId($params['subuser_id'] === null ? null : (int)$params['subuser_id']);
|
||||
}
|
||||
if (array_key_exists('wash_type', $params)) {
|
||||
$this->setWashMode($params['wash_type'] === null ? null : (string)$params['wash_type']);
|
||||
}
|
||||
if (array_key_exists('wash_mode', $params)) {
|
||||
$this->setWashMode($params['wash_mode'] === null ? null : (string)$params['wash_mode']);
|
||||
}
|
||||
if (array_key_exists('defer_relay_side_effects', $params)) {
|
||||
$this->setDeferRelaySideEffects(filter_var(
|
||||
$params['defer_relay_side_effects'],
|
||||
|
||||
@@ -103,49 +103,79 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
public function synchronizeSession(int $laneId, string $reg, ?int $customerNumber = null, bool $activateMachine = true, ?int $vehicleTypeIdOverride = null, bool $syncRelayState = true, array $options = []): array
|
||||
{
|
||||
$snapshot = $this->buildEligibilitySnapshot($laneId, $reg, $customerNumber, $vehicleTypeIdOverride, $options);
|
||||
$session = $this->findLatestOpenSession($laneId, $snapshot['reg'], $snapshot['customer_number']);
|
||||
$mutationResult = $this->withSessionMutationLock(
|
||||
$laneId,
|
||||
$snapshot['reg'],
|
||||
$snapshot['customer_number'],
|
||||
function () use ($laneId, $snapshot, $options): array {
|
||||
$session = $this->findLatestOpenSession($laneId, $snapshot['reg'], $snapshot['customer_number']);
|
||||
$createSession = (bool)($options['create_session'] ?? true);
|
||||
|
||||
if (($snapshot['evaluation_trace']['disabled_lane'] ?? false) === true) {
|
||||
return $session->exists()
|
||||
? $this->getSessionSummary((int)$session->id)
|
||||
: $this->formatBlockedSessionSummary($snapshot);
|
||||
if (($snapshot['evaluation_trace']['disabled_lane'] ?? false) === true) {
|
||||
return [
|
||||
'session' => $session,
|
||||
'response' => $session->exists()
|
||||
? $this->getSessionSummary((int)$session->id)
|
||||
: $this->formatBlockedSessionSummary($snapshot),
|
||||
];
|
||||
}
|
||||
|
||||
if (!$session->exists() && !$createSession) {
|
||||
return [
|
||||
'session' => $session,
|
||||
'response' => $this->formatSnapshotResponse($snapshot, null),
|
||||
];
|
||||
}
|
||||
|
||||
if (!$session->exists()) {
|
||||
$session = (new selfserve_wash_sessions_o())->add(
|
||||
$laneId,
|
||||
(int)$snapshot['lane']['department'],
|
||||
$snapshot['machine_type']['id'] ?? null,
|
||||
$snapshot['customer_number'],
|
||||
$snapshot['reg'],
|
||||
$snapshot['vehicle']['id'] ?? null,
|
||||
$snapshot['vehicle']['type'] ?? null,
|
||||
$this->deriveBaseStatus($snapshot),
|
||||
(bool)$snapshot['allowed'],
|
||||
$this->buildSessionMetadata($snapshot),
|
||||
);
|
||||
} else {
|
||||
$session->machine_type_id->set($snapshot['machine_type']['id'] ?? null);
|
||||
$session->customer_number->set($snapshot['customer_number']);
|
||||
$session->vehicle_id->set($snapshot['vehicle']['id'] ?? null);
|
||||
$session->vehicle_type_id->set($snapshot['vehicle_type_id']);
|
||||
$session->reg->set($snapshot['reg']);
|
||||
$session->allowed->set((bool)$snapshot['allowed']);
|
||||
$session->metadata_json->set($this->buildSessionMetadata($snapshot));
|
||||
$session->updateStatus($this->deriveCurrentStatus($snapshot, $session));
|
||||
}
|
||||
|
||||
$this->syncSessionAnswers((int)$session->id, $snapshot['questions']);
|
||||
$this->syncSessionTasks((int)$session->id, $snapshot['tasks']);
|
||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_SYNCED, [
|
||||
'allowed' => (bool)$snapshot['allowed'],
|
||||
'all_visible_questions_answered' => (bool)$snapshot['all_visible_questions_answered'],
|
||||
'allowed_services' => $snapshot['allowed_services'],
|
||||
'task_ids' => array_map(static fn(array $task): int => (int)$task['id'], $snapshot['tasks']),
|
||||
]);
|
||||
|
||||
return [
|
||||
'session' => $session,
|
||||
'response' => null,
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
$session = $mutationResult['session'];
|
||||
if ($mutationResult['response'] !== null) {
|
||||
return $mutationResult['response'];
|
||||
}
|
||||
|
||||
if (!$session->exists()) {
|
||||
$session = (new selfserve_wash_sessions_o())->add(
|
||||
$laneId,
|
||||
(int)$snapshot['lane']['department'],
|
||||
$snapshot['machine_type']['id'] ?? null,
|
||||
$snapshot['customer_number'],
|
||||
$snapshot['reg'],
|
||||
$snapshot['vehicle']['id'] ?? null,
|
||||
$snapshot['vehicle']['type'] ?? null,
|
||||
$this->deriveBaseStatus($snapshot),
|
||||
(bool)$snapshot['allowed'],
|
||||
$this->buildSessionMetadata($snapshot),
|
||||
);
|
||||
} else {
|
||||
$session->machine_type_id->set($snapshot['machine_type']['id'] ?? null);
|
||||
$session->customer_number->set($snapshot['customer_number']);
|
||||
$session->vehicle_id->set($snapshot['vehicle']['id'] ?? null);
|
||||
$session->vehicle_type_id->set($snapshot['vehicle_type_id']);
|
||||
$session->reg->set($snapshot['reg']);
|
||||
$session->allowed->set((bool)$snapshot['allowed']);
|
||||
$session->metadata_json->set($this->buildSessionMetadata($snapshot));
|
||||
$session->updateStatus($this->deriveCurrentStatus($snapshot, $session));
|
||||
}
|
||||
|
||||
$this->syncSessionAnswers((int)$session->id, $snapshot['questions']);
|
||||
$this->syncSessionTasks((int)$session->id, $snapshot['tasks']);
|
||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_SYNCED, [
|
||||
'allowed' => (bool)$snapshot['allowed'],
|
||||
'all_visible_questions_answered' => (bool)$snapshot['all_visible_questions_answered'],
|
||||
'allowed_services' => $snapshot['allowed_services'],
|
||||
'task_ids' => array_map(static fn(array $task): int => (int)$task['id'], $snapshot['tasks']),
|
||||
]);
|
||||
|
||||
if ($syncRelayState) {
|
||||
$this->syncMachineRelayFromVisibleServices($snapshot, $session, $activateMachine);
|
||||
if ($session->exists()) {
|
||||
$this->syncMachineRelayFromVisibleServices($snapshot, $session, $activateMachine);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->getSessionSummary((int)$session->id);
|
||||
@@ -405,7 +435,9 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
return null;
|
||||
}
|
||||
|
||||
$session->markCompleted($orderId);
|
||||
if (!$session->markCompletedIfOpen($orderId)) {
|
||||
return $this->getSessionSummary((int)$session->id);
|
||||
}
|
||||
$this->disableMachineRelayForCompletedWash($laneId);
|
||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_COMPLETED, [
|
||||
'lane_id' => $laneId,
|
||||
@@ -450,9 +482,12 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
'runtime_before_reset' => $runtimeSnapshot,
|
||||
'forced_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
$session->markForceStopped($orderId, $eventPayload);
|
||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_FORCE_STOPPED, $eventPayload);
|
||||
$summary = $this->getSessionSummary((int)$session->id);
|
||||
if (!$session->markForceStoppedIfOpen($orderId, $eventPayload)) {
|
||||
$summary = $this->getSessionSummary((int)$session->id);
|
||||
} else {
|
||||
$this->logSessionEvent((int)$session->id, selfserve_wash_event_type::SESSION_FORCE_STOPPED, $eventPayload);
|
||||
$summary = $this->getSessionSummary((int)$session->id);
|
||||
}
|
||||
}
|
||||
|
||||
$lane->execute(selfserve_lane_command::RESET, new selfserve_lane_command_arguments());
|
||||
@@ -2962,7 +2997,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
|
||||
return array_values(array_filter($questions, static function (array $question) use ($departmentId, $laneId, $vehicleTypeId): bool {
|
||||
return (int)($question['department'] ?? 0) === $departmentId
|
||||
&& (int)($question['lane'] ?? 0) === $laneId
|
||||
&& ((int)($question['lane'] ?? 0) === 0 || (int)($question['lane'] ?? 0) === $laneId)
|
||||
&& (int)($question['product'] ?? 0) === $vehicleTypeId;
|
||||
}));
|
||||
}
|
||||
@@ -3005,7 +3040,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
return array_values(array_filter($conditions, static function (array $condition) use ($departmentId, $laneId, $vehicleTypeId): bool {
|
||||
return (int)($condition['machine_type_id'] ?? 0) === 0
|
||||
&& (int)($condition['department'] ?? 0) === $departmentId
|
||||
&& (int)($condition['lane'] ?? 0) === $laneId
|
||||
&& ((int)($condition['lane'] ?? 0) === 0 || (int)($condition['lane'] ?? 0) === $laneId)
|
||||
&& (int)($condition['product'] ?? 0) === $vehicleTypeId;
|
||||
}));
|
||||
}
|
||||
@@ -3049,7 +3084,7 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
return array_values(array_filter($tasks, static function (array $task) use ($departmentId, $laneId, $vehicleTypeId): bool {
|
||||
return (int)($task['machine_type_id'] ?? 0) === 0
|
||||
&& (int)($task['department'] ?? 0) === $departmentId
|
||||
&& (int)($task['lane'] ?? 0) === $laneId
|
||||
&& ((int)($task['lane'] ?? 0) === 0 || (int)($task['lane'] ?? 0) === $laneId)
|
||||
&& (int)($task['product'] ?? 0) === $vehicleTypeId;
|
||||
}));
|
||||
}
|
||||
@@ -3188,6 +3223,86 @@ class selfserve_wash_flow implements selfserve_wash_flow_i
|
||||
(new selfserve_wash_session_events_o())->add($sessionId, $eventType, $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable():array<string,mixed> $callback
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
protected function withSessionMutationLock(int $laneId, string $reg, ?int $customerNumber, callable $callback): array
|
||||
{
|
||||
$lockKey = $this->sessionMutationLockKey($laneId, $reg, $customerNumber);
|
||||
$lock = $this->acquireSessionMutationLock($lockKey);
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
$this->releaseSessionMutationLock($lock);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{driver:string,key:string,token:?string}
|
||||
*/
|
||||
protected function acquireSessionMutationLock(string $lockKey): array
|
||||
{
|
||||
if (defined('redis') && method_exists(redis, 'set_if_absent_with_expiration')) {
|
||||
$token = bin2hex(random_bytes(16));
|
||||
if (!redis->set_if_absent_with_expiration($lockKey, $token, 15)) {
|
||||
throw new \RuntimeException('Self-serve wash session is busy. Try again.');
|
||||
}
|
||||
|
||||
return [
|
||||
'driver' => 'redis',
|
||||
'key' => $lockKey,
|
||||
'token' => $token,
|
||||
];
|
||||
}
|
||||
|
||||
global $db;
|
||||
$result = $db->query("SELECT GET_LOCK('" . $db->escape_string($lockKey) . "', 5) AS acquired");
|
||||
$row = $db->fetch_assoc($result);
|
||||
if ((int)($row['acquired'] ?? 0) !== 1) {
|
||||
throw new \RuntimeException('Self-serve wash session is busy. Try again.');
|
||||
}
|
||||
|
||||
return [
|
||||
'driver' => 'mysql',
|
||||
'key' => $lockKey,
|
||||
'token' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{driver:string,key:string,token:?string} $lock
|
||||
*/
|
||||
protected function releaseSessionMutationLock(array $lock): void
|
||||
{
|
||||
try {
|
||||
if ($lock['driver'] === 'redis' && defined('redis')) {
|
||||
if (method_exists(redis, 'get') && redis->get($lock['key']) !== $lock['token']) {
|
||||
return;
|
||||
}
|
||||
if (method_exists(redis, 'delete')) {
|
||||
redis->delete($lock['key']);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ($lock['driver'] === 'mysql') {
|
||||
global $db;
|
||||
$db->query("SELECT RELEASE_LOCK('" . $db->escape_string($lock['key']) . "')");
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Locks have TTLs or connection scope; release failures must not mask API results.
|
||||
}
|
||||
}
|
||||
|
||||
protected function sessionMutationLockKey(int $laneId, string $reg, ?int $customerNumber): string
|
||||
{
|
||||
return 'selfserve_session_mutation:' . (int)$laneId . ':' . sha1(
|
||||
selfserve::standardize_registration($reg) . ':' . ($customerNumber === null ? 'anon' : (string)(int)$customerNumber)
|
||||
);
|
||||
}
|
||||
|
||||
protected function buildSessionMetadata(array $snapshot): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace modules\selfserve\config;
|
||||
|
||||
use Exception;
|
||||
use traits\module_config_variable;
|
||||
|
||||
class selfserve_dynamic_image_size_c
|
||||
{
|
||||
use module_config_variable;
|
||||
|
||||
public const SIZE_ORIGINAL = 'original';
|
||||
public const SIZE_RELEVANT = 'relevant';
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
self::setupConfigVariable(
|
||||
'selfserve',
|
||||
'dynamic_image_size',
|
||||
'string',
|
||||
true,
|
||||
[self::SIZE_ORIGINAL, self::SIZE_RELEVANT],
|
||||
'Whether self-serve dynamic images are served in the original rendered size or resized to the relevant terminal size',
|
||||
self::SIZE_RELEVANT,
|
||||
false,
|
||||
self::SIZE_ORIGINAL
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ namespace modules\selfserve;
|
||||
require_once WD . '/modules/selfserve/config/selfserve_enabled_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_dynamic_image_size_c.php';
|
||||
|
||||
use modules\selfserve\config\selfserve_dynamic_image_size_c;
|
||||
use modules\selfserve\config\selfserve_enabled_c;
|
||||
use modules\selfserve\config\selfserve_machine_wash_minutes_included_c;
|
||||
use modules\selfserve\config\selfserve_minute_product_c;
|
||||
@@ -29,6 +31,11 @@ class selfserve_c
|
||||
* @var selfserve_machine_wash_minutes_included_c $machine_wash_minutes_included
|
||||
*/
|
||||
public selfserve_machine_wash_minutes_included_c $machine_wash_minutes_included;
|
||||
/**
|
||||
* Dynamic image output size mode for self-serve terminals
|
||||
* @var selfserve_dynamic_image_size_c $dynamic_image_size
|
||||
*/
|
||||
public selfserve_dynamic_image_size_c $dynamic_image_size;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -36,10 +43,12 @@ class selfserve_c
|
||||
$this->allowUpdate([
|
||||
selfserve_enabled_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
|
||||
]);
|
||||
$this->enabled = new selfserve_enabled_c();
|
||||
$this->minute_product = new selfserve_minute_product_c();
|
||||
$this->machine_wash_minutes_included = new selfserve_machine_wash_minutes_included_c();
|
||||
$this->dynamic_image_size = new selfserve_dynamic_image_size_c();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,13 +171,12 @@ trait selfserve_lane_command_t
|
||||
* Ensure machine relay is ON when a wash starts, when it is allowed by configuration.
|
||||
* If machine relay is not configured, this is a no-op.
|
||||
*/
|
||||
protected function setMachineRelayStatusForWashStart(): void
|
||||
protected function setMachineRelayStatusForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
if (!$this->isRelayConfigured(selfserve_lane_relay::MACHINE)) {
|
||||
return;
|
||||
}
|
||||
$active_wash = new selfserve_wash_flow();
|
||||
if ($active_wash->isMachineAllowedToStartWash($this->id)) {
|
||||
if ($this->isMachineWashSelectedAndAvailableForStart($arguments)) {
|
||||
try {
|
||||
$this->setMachineRelayStatusHard(true);
|
||||
} catch (\Throwable) {
|
||||
@@ -193,6 +192,116 @@ trait selfserve_lane_command_t
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the program picker relay aligned with the selected wash mode at START.
|
||||
* It is ON only when the customer explicitly selected machine wash.
|
||||
*/
|
||||
protected function setProgramPickerRelayStatusForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
if (!$this->isRelayConfigured(selfserve_lane_relay::MACHINE_PROGRAM_PICKER)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$shouldEnable = $this->isExplicitMachineWashModeSelectedForStart($arguments)
|
||||
&& $this->isMachineWashSelectedAndAvailableForStart($arguments);
|
||||
$this->setMachineProgramPickerRelayStatusHard($shouldEnable);
|
||||
} catch (\Throwable) {
|
||||
// Best effort only; wash start must continue.
|
||||
}
|
||||
}
|
||||
|
||||
protected function setProgramPickerRelayStatusFromSelectedServiceForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
if (!$this->isRelayConfigured(selfserve_lane_relay::MACHINE_PROGRAM_PICKER)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->setMachineProgramPickerRelayStatusHard($this->shouldEnableProgramPickerRelayForWashStart($arguments));
|
||||
} catch (\Throwable) {
|
||||
// Best effort only; wash start must continue.
|
||||
}
|
||||
}
|
||||
|
||||
protected function isMachineWashSelectedAndAvailableForStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
if (!$this->shouldEnableSelectedMachineServiceForWashStart($arguments)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$reg = method_exists($this, 'getLicensePlate') ? trim((string)$this->getLicensePlate()) : '';
|
||||
if ($reg === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$customerNumber = method_exists($this, 'getCustomerNumber') ? (int)$this->getCustomerNumber() : null;
|
||||
$snapshot = (new selfserve_wash_flow())->previewVehicleEligibility(
|
||||
(int)$this->id,
|
||||
$reg,
|
||||
$customerNumber !== null && $customerNumber > 0 ? $customerNumber : null
|
||||
);
|
||||
|
||||
return (bool)($snapshot['allowed'] ?? false);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function shouldEnableSelectedMachineServiceForWashStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
if (!$this->isMachineWashModeSelectedForStart($arguments)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isMachineServiceSelectedForWashStart();
|
||||
}
|
||||
|
||||
protected function shouldEnableProgramPickerRelayForWashStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
return $this->isExplicitMachineWashModeSelectedForStart($arguments)
|
||||
&& $this->isMachineServiceSelectedForWashStart();
|
||||
}
|
||||
|
||||
protected function isExplicitMachineWashModeSelectedForStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
return $arguments !== null && $arguments->wash_mode === selfserve_studio_actions::MODE_MACHINE;
|
||||
}
|
||||
|
||||
protected function isMachineWashModeSelectedForStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
if ($arguments !== null && $arguments->wash_mode === selfserve_studio_actions::MODE_MANUAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($arguments !== null && $arguments->wash_mode === selfserve_studio_actions::MODE_MACHINE) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->isMachineServiceSelectedForWashStart();
|
||||
}
|
||||
|
||||
protected function isMachineServiceSelectedForWashStart(): bool
|
||||
{
|
||||
try {
|
||||
if (method_exists($this, 'getLaneCache') && defined(self::class . '::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES')) {
|
||||
$services = $this->getLaneCache((int)$this->id, self::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES);
|
||||
if (is_array($services)) {
|
||||
foreach ($services as $service) {
|
||||
if (strtoupper((string)$service) === 'MACHINE') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Fall through to fail-closed when the selected service cache is unavailable.
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function openEntrancePortForWashStart(): void
|
||||
{
|
||||
try {
|
||||
@@ -274,30 +383,26 @@ trait selfserve_lane_command_t
|
||||
protected function runRelaySideEffectsForWashStart(selfserve_lane_command_arguments $arguments): void
|
||||
{
|
||||
if ($arguments->defer_relay_side_effects) {
|
||||
$this->setProgramPickerRelayStatusFromSelectedServiceForWashStart($arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure cleaner relay is enabled whenever wash starts.
|
||||
$this->turnOnCleanerRelayForWashStart();
|
||||
// Ensure the machine relay is ON when a wash starts, when it is allowed.
|
||||
$this->setMachineRelayStatusForWashStart();
|
||||
$this->setProgramPickerRelayStatusForWashStart($arguments);
|
||||
$this->setMachineRelayStatusForWashStart($arguments);
|
||||
}
|
||||
|
||||
protected function resolveSelfServeActionWashModeForStart(): string
|
||||
protected function resolveSelfServeActionWashModeForStart(?selfserve_lane_command_arguments $arguments = null): string
|
||||
{
|
||||
try {
|
||||
if (method_exists($this, 'getLaneCache') && defined(self::class . '::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES')) {
|
||||
$services = $this->getLaneCache((int)$this->id, self::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES);
|
||||
if (is_array($services)) {
|
||||
foreach ($services as $service) {
|
||||
if (strtoupper((string)$service) === 'MACHINE') {
|
||||
return selfserve_studio_actions::MODE_MACHINE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Fall through to manual mode when the cached service set is unavailable.
|
||||
if ($arguments !== null && in_array($arguments->wash_mode, [
|
||||
selfserve_studio_actions::MODE_MANUAL,
|
||||
selfserve_studio_actions::MODE_MACHINE,
|
||||
], true)) {
|
||||
return $arguments->wash_mode;
|
||||
}
|
||||
|
||||
if ($this->isMachineServiceSelectedForWashStart()) {
|
||||
return selfserve_studio_actions::MODE_MACHINE;
|
||||
}
|
||||
|
||||
return selfserve_studio_actions::MODE_MANUAL;
|
||||
@@ -382,14 +487,16 @@ trait selfserve_lane_command_t
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable relays after STOP in deterministic order:
|
||||
* Disable relays before opening exit gates in deterministic order:
|
||||
* 1. Cleaner relay
|
||||
* 2. Machine relay
|
||||
* 2. Program picker relay
|
||||
* 3. Machine relay
|
||||
*/
|
||||
protected function turnOffRelaysAfterStop(): void
|
||||
{
|
||||
$relays = [
|
||||
selfserve_lane_relay::MACHINE_CLEANER,
|
||||
selfserve_lane_relay::MACHINE_PROGRAM_PICKER,
|
||||
selfserve_lane_relay::MACHINE,
|
||||
];
|
||||
|
||||
@@ -563,8 +670,17 @@ trait selfserve_lane_command_t
|
||||
// Set the customer number and license plate
|
||||
$this->setCustomerNumber($customer_number);
|
||||
$this->setLicensePlate($license_plate);
|
||||
// Mark the lane occupied before any physical entrance relay side effects.
|
||||
// Mark the lane occupied before any physical relay or gate side effects.
|
||||
$this->setLaneStatus(selfserve_lane_status::OCCUPIED);
|
||||
$this->runRelaySideEffectsForWashStart($arguments);
|
||||
$this->runPublishedStudioActions(
|
||||
selfserve_studio_actions::EVENT_WASH_START_COMMAND,
|
||||
$this->resolveSelfServeActionWashModeForStart($arguments),
|
||||
[
|
||||
'customer_number' => (int)$customer_number,
|
||||
'reg' => $license_plate,
|
||||
]
|
||||
);
|
||||
try {
|
||||
// Gateway timeouts are ambiguous because the relay may already have received
|
||||
// the pulse, so openEntrancePortForWashStart() reports them and continues.
|
||||
@@ -580,15 +696,6 @@ trait selfserve_lane_command_t
|
||||
$this->setLaneState(selfserve_lane_state::IN_WASH);
|
||||
// Start the wash timer
|
||||
$this->setWashStartTime(time());
|
||||
$this->runPublishedStudioActions(
|
||||
selfserve_studio_actions::EVENT_WASH_START_COMMAND,
|
||||
$this->resolveSelfServeActionWashModeForStart(),
|
||||
[
|
||||
'customer_number' => (int)$customer_number,
|
||||
'reg' => $license_plate,
|
||||
]
|
||||
);
|
||||
$this->runRelaySideEffectsForWashStart($arguments);
|
||||
// Log the lane start event
|
||||
$this->logLaneAction(selfserve_lane_log_action::START_WASH);
|
||||
} finally {
|
||||
@@ -604,6 +711,8 @@ trait selfserve_lane_command_t
|
||||
}
|
||||
// Snapshot the physical machine ON signal before session completion/reset.
|
||||
$machine_start_triggered = $this->hasMachineStartSignalForStop();
|
||||
// Turn off relays before any configured or default exit gate opens.
|
||||
$this->turnOffRelaysAfterStop();
|
||||
$this->runPublishedStudioActions(
|
||||
selfserve_studio_actions::EVENT_WASH_STOP_COMMAND,
|
||||
$machine_start_triggered ? selfserve_studio_actions::MODE_MACHINE : selfserve_studio_actions::MODE_MANUAL,
|
||||
@@ -616,8 +725,6 @@ trait selfserve_lane_command_t
|
||||
// Open the exit port. Gateway timeouts are ambiguous because
|
||||
// the relay may already have received the pulse.
|
||||
$this->openExitPortForWashStop();
|
||||
// Turn off relays in deterministic order after STOP
|
||||
$this->turnOffRelaysAfterStop();
|
||||
// Log the lane stop event
|
||||
$this->logLaneAction(selfserve_lane_log_action::STOP_WASH);
|
||||
// Invoice the customer
|
||||
|
||||
@@ -12,6 +12,7 @@ use modules\selfserve\helpers\selfserve_lane_relay;
|
||||
use modules\selfserve\helpers\selfserve_lane_services;
|
||||
use modules\selfserve\helpers\selfserve_lane_status;
|
||||
use modules\shelly\helpers\shelly_request_body_get_states;
|
||||
use objects\selfserve_wash_sessions_o;
|
||||
|
||||
trait selfserve_lane_relay_controller_t
|
||||
{
|
||||
@@ -917,7 +918,38 @@ trait selfserve_lane_relay_controller_t
|
||||
}
|
||||
}
|
||||
|
||||
return $this->sendRelaySwitchCommand($relay, true, $duration);
|
||||
$result = $this->sendRelaySwitchCommand($relay, true, $duration);
|
||||
if ($result && $relay === selfserve_lane_relay::MACHINE) {
|
||||
$this->markLatestSelfServeSessionRelayEnabledForLane();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected function markLatestSelfServeSessionRelayEnabledForLane(): void
|
||||
{
|
||||
try {
|
||||
$customerNumber = (int)$this->getCustomerNumber();
|
||||
$session = (new selfserve_wash_sessions_o())->selectLatestOpenByLane(
|
||||
(int)$this->id,
|
||||
$customerNumber > 0 ? $customerNumber : null
|
||||
);
|
||||
if (!$session->exists() && $customerNumber > 0) {
|
||||
$session = (new selfserve_wash_sessions_o())->selectLatestOpenByLane((int)$this->id);
|
||||
}
|
||||
if (!$session->exists() || (bool)$session->machine_relay_enabled->value() === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$session->markRelayEnabled();
|
||||
} catch (\Throwable $e) {
|
||||
error_log(
|
||||
'Failed to synchronize self-serve machine relay session state for lane '
|
||||
. (int)$this->id
|
||||
. ': '
|
||||
. $e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace slack\config;
|
||||
|
||||
use Exception;
|
||||
use traits\module_config_variable;
|
||||
|
||||
class slack_customer_registration_webhook_url_c
|
||||
{
|
||||
use module_config_variable;
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
self::setupConfigVariable(
|
||||
'Slack',
|
||||
'customer_registration_webhook_url',
|
||||
'string',
|
||||
false,
|
||||
null,
|
||||
'Slack webhook URL used for successful customer registration notifications',
|
||||
'https://hooks.slack.com/services/...',
|
||||
true,
|
||||
''
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace slack;
|
||||
|
||||
require_once WD . '/modules/slack/config/slack_customer_registration_webhook_url_c.php';
|
||||
|
||||
use slack\config\slack_customer_registration_webhook_url_c;
|
||||
use traits\module_config_t;
|
||||
|
||||
class slack_c
|
||||
{
|
||||
use module_config_t;
|
||||
|
||||
public slack_customer_registration_webhook_url_c $customer_registration_webhook_url;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->setupConfig('Slack');
|
||||
$this->allowUpdate([
|
||||
slack_customer_registration_webhook_url_c::class,
|
||||
]);
|
||||
|
||||
$this->customer_registration_webhook_url = new slack_customer_registration_webhook_url_c();
|
||||
}
|
||||
}
|
||||
@@ -606,6 +606,76 @@ class collected_order_invoices_o extends db
|
||||
self::deleteCached('asArray', $this->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move this invoice collection and all attached orders to another customer.
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
* @throws Exception
|
||||
*/
|
||||
public function moveToCustomer(int $target_customer_number): array
|
||||
{
|
||||
global $db;
|
||||
|
||||
self::requireSelected();
|
||||
self::requireValidCustomer((string)$target_customer_number);
|
||||
|
||||
if ($target_customer_number <= 0) {
|
||||
throw new Exception('Target customer number must be greater than zero');
|
||||
}
|
||||
|
||||
if (!empty($this->external_id->value()) || $this->booked_invoice_id->value() !== null) {
|
||||
throw new Exception('Invoice collections with an external or booked invoice cannot be moved');
|
||||
}
|
||||
|
||||
$source_customer_number = (int)$this->customer_number->value();
|
||||
if ($source_customer_number === $target_customer_number) {
|
||||
return [
|
||||
'invoice_collection_id' => (int)$this->id,
|
||||
'source_customer_number' => $source_customer_number,
|
||||
'target_customer_number' => $target_customer_number,
|
||||
'moved_order_ids' => [],
|
||||
'moved_order_count' => 0,
|
||||
'changed' => false,
|
||||
];
|
||||
}
|
||||
|
||||
$invoice_collection_id = (int)$this->id;
|
||||
$result = $db->query("SELECT id FROM orders WHERE invoice_collection_id = {$invoice_collection_id}");
|
||||
$order_ids = array_map(
|
||||
static fn(array $row): int => (int)$row['id'],
|
||||
$db->fetch_all($result)
|
||||
);
|
||||
|
||||
$db->conn()->begin_transaction();
|
||||
try {
|
||||
$this->customer_number->set($target_customer_number);
|
||||
|
||||
foreach ( $order_ids as $order_id ) {
|
||||
$order = (new orders_o())->select($order_id);
|
||||
if (!$order->exists()) {
|
||||
continue;
|
||||
}
|
||||
$order->customer_id->set($target_customer_number);
|
||||
$order->objectChanged();
|
||||
}
|
||||
|
||||
$this->objectChanged();
|
||||
$db->conn()->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->conn()->rollback();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return [
|
||||
'invoice_collection_id' => $invoice_collection_id,
|
||||
'source_customer_number' => $source_customer_number,
|
||||
'target_customer_number' => $target_customer_number,
|
||||
'moved_order_ids' => $order_ids,
|
||||
'moved_order_count' => count($order_ids),
|
||||
'changed' => true,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the external id of the invoice collection
|
||||
* @throws Exception If the request was not successful
|
||||
|
||||
@@ -7,6 +7,7 @@ use classes\object_property;
|
||||
use classes\selfserve;
|
||||
use classes\selfserve_schema_bootstrap;
|
||||
use Exception;
|
||||
use modules\selfserve\classes\selfserve_config_versioning;
|
||||
use traits\db_object_t;
|
||||
|
||||
class department_lanes_o extends db
|
||||
@@ -324,9 +325,52 @@ class department_lanes_o extends db
|
||||
public function getSelfServeLaneProducts(): array
|
||||
{
|
||||
self::requireSelected();
|
||||
$publishedProducts = $this->getPublishedSelfServeLaneProducts();
|
||||
if ($publishedProducts !== []) {
|
||||
return $publishedProducts;
|
||||
}
|
||||
|
||||
return department_selfserve_tasks_o::getLaneProducts((int)$this->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private function getPublishedSelfServeLaneProducts(): array
|
||||
{
|
||||
try {
|
||||
$published = (new selfserve_config_versioning())->getPublishedV2Config((int)$this->department->value());
|
||||
} catch (\Throwable) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$config = is_array($published['config'] ?? null) ? $published['config'] : null;
|
||||
if ($config === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$laneId = (int)$this->id;
|
||||
$products = [];
|
||||
foreach ((array)($config['tasks'] ?? []) as $task) {
|
||||
if (!is_array($task)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$taskLane = (int)($task['lane'] ?? 0);
|
||||
if ($taskLane !== 0 && $taskLane !== $laneId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$productId = (int)($task['product'] ?? 0);
|
||||
if ($productId > 0 && !in_array($productId, $products, true)) {
|
||||
$products[] = $productId;
|
||||
}
|
||||
}
|
||||
|
||||
sort($products, SORT_NUMERIC);
|
||||
return $products;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return department_lanes_o[] An array of department lane objects for the specified department
|
||||
|
||||
@@ -158,6 +158,18 @@ class selfserve_wash_sessions_o extends db
|
||||
}
|
||||
|
||||
public function markCompleted(?int $orderId = null): void
|
||||
{
|
||||
if (!$this->closeIfOpen(selfserve_wash_session_status::COMPLETED, $orderId)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public function markCompletedIfOpen(?int $orderId = null): bool
|
||||
{
|
||||
return $this->closeIfOpen(selfserve_wash_session_status::COMPLETED, $orderId);
|
||||
}
|
||||
|
||||
private function markCompletedInMemory(?int $orderId = null): void
|
||||
{
|
||||
$this->completed_at->set(date('Y-m-d H:i:s'));
|
||||
if ($orderId !== null) {
|
||||
@@ -167,6 +179,18 @@ class selfserve_wash_sessions_o extends db
|
||||
}
|
||||
|
||||
public function markForceStopped(?int $orderId = null, ?array $metadata = null): void
|
||||
{
|
||||
if (!$this->closeIfOpen(selfserve_wash_session_status::FORCE_STOPPED, $orderId, $metadata)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public function markForceStoppedIfOpen(?int $orderId = null, ?array $metadata = null): bool
|
||||
{
|
||||
return $this->closeIfOpen(selfserve_wash_session_status::FORCE_STOPPED, $orderId, $metadata);
|
||||
}
|
||||
|
||||
private function markForceStoppedInMemory(?int $orderId = null, ?array $metadata = null): void
|
||||
{
|
||||
$this->completed_at->set(date('Y-m-d H:i:s'));
|
||||
if ($orderId !== null) {
|
||||
@@ -181,6 +205,53 @@ class selfserve_wash_sessions_o extends db
|
||||
$this->status->set(selfserve_wash_session_status::FORCE_STOPPED->value);
|
||||
}
|
||||
|
||||
private function closeIfOpen(selfserve_wash_session_status $status, ?int $orderId = null, ?array $metadata = null): bool
|
||||
{
|
||||
if (!$this->isPersistedSession()) {
|
||||
if ($status === selfserve_wash_session_status::COMPLETED) {
|
||||
$this->markCompletedInMemory($orderId);
|
||||
} else {
|
||||
$this->markForceStoppedInMemory($orderId, $metadata);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
global $db;
|
||||
|
||||
$updates = [
|
||||
"`completed_at` = NOW()",
|
||||
"`status` = '" . $db->escape_string($status->value) . "'",
|
||||
];
|
||||
|
||||
if ($orderId !== null) {
|
||||
$updates[] = "`order_id` = " . (int)$orderId;
|
||||
}
|
||||
|
||||
if ($metadata !== null) {
|
||||
$existing = $this->metadata_json->value();
|
||||
$existing = is_array($existing) ? $existing : [];
|
||||
$existing['force_stop'] = $metadata;
|
||||
$updates[] = "`metadata_json` = '" . $db->escape_string(json_encode($existing, JSON_THROW_ON_ERROR)) . "'";
|
||||
}
|
||||
|
||||
$terminalStatuses = self::terminalStatusSqlList();
|
||||
$db->query(
|
||||
"UPDATE `selfserve_wash_sessions` SET " . implode(', ', $updates) .
|
||||
" WHERE `id` = " . (int)$this->id .
|
||||
" AND `completed_at` IS NULL" .
|
||||
" AND UPPER(TRIM(`status`)) NOT IN ($terminalStatuses)"
|
||||
);
|
||||
|
||||
$changed = $db->conn()->affected_rows > 0;
|
||||
$this->select((int)$this->id);
|
||||
return $changed;
|
||||
}
|
||||
|
||||
private function isPersistedSession(): bool
|
||||
{
|
||||
return isset($this->id) && (int)$this->id > 0 && $this->exists();
|
||||
}
|
||||
|
||||
public function selectLatestOpenByLane(int $laneId, ?int $customerNumber = null): self
|
||||
{
|
||||
$filters = [
|
||||
|
||||
@@ -18,6 +18,8 @@ class users_o extends db
|
||||
{
|
||||
use db_object_t;
|
||||
|
||||
public const KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS = 'superuser_new_customer_email_notifications_enabled';
|
||||
|
||||
public object_property $customer_number;
|
||||
public object_property $display_name;
|
||||
public object_property $group_id;
|
||||
@@ -436,6 +438,7 @@ class users_o extends db
|
||||
'sms_notifications_enabled' => (bool)$this->sms_notifications_enabled->value(),
|
||||
'email_notifications_enabled' => (bool)$this->email_notifications_enabled->value(),
|
||||
'wash_certificate_email' => $this->wash_certificate_email->value(),
|
||||
self::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => $this->isSuperuserNewCustomerEmailNotificationsEnabled(),
|
||||
],
|
||||
'created_at' => $this->created_at->value(),
|
||||
'updated_at' => $this->updated_at->value(),
|
||||
@@ -831,6 +834,53 @@ class users_o extends db
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isSuperuserNewCustomerEmailNotificationsEnabled(): bool
|
||||
{
|
||||
self::requireSelected();
|
||||
$value = $this->keys->setUser($this->id)->getValue(self::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS);
|
||||
return in_array(strtolower((string)$value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
public function setSuperuserNewCustomerEmailNotificationsEnabled(bool $enabled): void
|
||||
{
|
||||
self::requireSelected();
|
||||
$this->keys->setUser($this->id)->setValue(
|
||||
self::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS,
|
||||
$enabled ? '1' : '0'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{id:int, customer_number:int, display_name:string|null, email:string}>
|
||||
*/
|
||||
public function getSuperuserNewCustomerEmailNotificationRecipients(): array
|
||||
{
|
||||
global $db;
|
||||
|
||||
$key = $db->escape_string(self::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS);
|
||||
$sql = "
|
||||
SELECT DISTINCT
|
||||
u.id,
|
||||
u.customer_number,
|
||||
u.display_name,
|
||||
u.email
|
||||
FROM users u
|
||||
INNER JOIN user_key_value_pairs kv
|
||||
ON kv.user_id = u.id
|
||||
AND kv.var = '$key'
|
||||
AND LOWER(kv.val) IN ('1', 'true', 'yes', 'on')
|
||||
LEFT JOIN groups_permissions gp
|
||||
ON gp.group_id = u.group_id
|
||||
AND gp.permission = 'superuser'
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND u.email IS NOT NULL
|
||||
AND u.email <> ''
|
||||
AND (u.group_id = 1 OR gp.id IS NOT NULL)
|
||||
";
|
||||
|
||||
return $db->fetch_all($db->query($sql));
|
||||
}
|
||||
|
||||
public function setOpenInvoiceDraft(int $draftInvoiceNumber): void
|
||||
{
|
||||
// Set the open invoice draft (key = 'open_invoice_draft')
|
||||
|
||||
@@ -3043,6 +3043,7 @@ paths:
|
||||
wash_certificate_email: {type: string}
|
||||
sms_notifications_enabled: {type: boolean}
|
||||
email_notifications_enabled: {type: boolean}
|
||||
superuser_new_customer_email_notifications_enabled: {type: boolean}
|
||||
responses:
|
||||
'200':
|
||||
description: Success
|
||||
@@ -6265,6 +6266,33 @@ paths:
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
'403': { $ref: '#/components/responses/Forbidden' }
|
||||
|
||||
/order-bookings/completion-confirmation/resend:
|
||||
post:
|
||||
tags:
|
||||
- Bookings
|
||||
summary: Resend order booking completion confirmation
|
||||
description: Resends the customer completion confirmation email with the wash certificate for a completed order booking. Requires `complete_bookings` and access to the booking's department.
|
||||
operationId: resendOrderBookingCompletionConfirmation
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [id]
|
||||
properties:
|
||||
id: {type: integer}
|
||||
responses:
|
||||
'200':
|
||||
description: Completion confirmation resent successfully
|
||||
content:
|
||||
application/json:
|
||||
schema: {}
|
||||
'400': { $ref: '#/components/responses/BadRequest' }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
'403': { $ref: '#/components/responses/Forbidden' }
|
||||
'409': { $ref: '#/components/responses/Conflict' }
|
||||
|
||||
/order-bookings/complete:
|
||||
post:
|
||||
tags:
|
||||
@@ -9420,6 +9448,14 @@ paths:
|
||||
license_plate:
|
||||
type: string
|
||||
description: Required for START command
|
||||
wash_type:
|
||||
type: string
|
||||
enum: [Manual, Machine]
|
||||
description: Optional customer-selected wash type for START. When provided, Manual and Machine start actions use this explicit choice instead of inferring mode from allowed services.
|
||||
wash_mode:
|
||||
type: string
|
||||
enum: [manual, machine]
|
||||
description: Lowercase alias for wash_type accepted by backend clients.
|
||||
customer_number:
|
||||
type: integer
|
||||
description: Required for START and RESERVE commands. The authenticated customer's number is applied server-side when omitted by user clients.
|
||||
@@ -11600,6 +11636,35 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ModuleConfigTestResponse'
|
||||
|
||||
/slack/config:
|
||||
get:
|
||||
tags: [Config]
|
||||
summary: Get Slack config
|
||||
operationId: getSlackConfig
|
||||
responses:
|
||||
'200':
|
||||
description: Slack configuration retrieved successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SlackConfigListResponse'
|
||||
post:
|
||||
tags: [Config]
|
||||
summary: Update Slack config
|
||||
operationId: updateSlackConfig
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema: {}
|
||||
responses:
|
||||
'200':
|
||||
description: Slack configuration updated successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ModuleConfigUpdateResponse'
|
||||
|
||||
/backups/config:
|
||||
get:
|
||||
tags: [Config]
|
||||
@@ -15114,6 +15179,17 @@ components:
|
||||
- type: integer
|
||||
required: [module, variable, type, value]
|
||||
|
||||
SlackConfigEntry:
|
||||
type: object
|
||||
properties:
|
||||
module: { type: string, enum: [Slack] }
|
||||
variable: { type: string, enum: [customer_registration_webhook_url] }
|
||||
type: { type: string, enum: [string] }
|
||||
value:
|
||||
type: string
|
||||
example: https://hooks.slack.com/services/...
|
||||
required: [module, variable, type, value]
|
||||
|
||||
BackupsConfigEntry:
|
||||
type: object
|
||||
properties:
|
||||
@@ -15382,6 +15458,14 @@ components:
|
||||
data: { type: array, items: { $ref: '#/components/schemas/EmailConfigEntry' } }
|
||||
required: [data]
|
||||
|
||||
SlackConfigListResponse:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||
- type: object
|
||||
properties:
|
||||
data: { type: array, items: { $ref: '#/components/schemas/SlackConfigEntry' } }
|
||||
required: [data]
|
||||
|
||||
BackupsConfigListResponse:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ModuleConfigEnvelopeBase'
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
parameters:
|
||||
level: 0
|
||||
paths:
|
||||
- classes
|
||||
- interfaces
|
||||
- traits
|
||||
- objects
|
||||
- modules
|
||||
- routes
|
||||
- statistics
|
||||
- tests/Unit
|
||||
- tests/Integration
|
||||
- tests/Api
|
||||
bootstrapFiles:
|
||||
- vendor/autoload.php
|
||||
tmpDir: build/phpstan
|
||||
excludePaths:
|
||||
analyse:
|
||||
- vendor
|
||||
- build
|
||||
- .phpunit.cache
|
||||
- modules/*/vendor
|
||||
- modules/*/vendor/*
|
||||
- tests/Legacy
|
||||
reportUnmatchedIgnoredErrors: false
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Rector\Config\RectorConfig;
|
||||
|
||||
return RectorConfig::configure()
|
||||
->withPaths([
|
||||
__DIR__ . '/classes',
|
||||
__DIR__ . '/interfaces',
|
||||
__DIR__ . '/traits',
|
||||
__DIR__ . '/objects',
|
||||
__DIR__ . '/modules',
|
||||
__DIR__ . '/routes',
|
||||
__DIR__ . '/statistics',
|
||||
__DIR__ . '/tests/Unit',
|
||||
__DIR__ . '/tests/Integration',
|
||||
__DIR__ . '/tests/Api',
|
||||
])
|
||||
->withBootstrapFiles([
|
||||
__DIR__ . '/vendor/autoload.php',
|
||||
])
|
||||
->withSkip([
|
||||
__DIR__ . '/build',
|
||||
__DIR__ . '/vendor',
|
||||
__DIR__ . '/.phpunit.cache',
|
||||
__DIR__ . '/modules/*/vendor',
|
||||
__DIR__ . '/modules/*/vendor/*',
|
||||
__DIR__ . '/tests/Legacy',
|
||||
])
|
||||
->withPreparedSets(
|
||||
codeQuality: true,
|
||||
codingStyle: true,
|
||||
phpunitCodeQuality: true,
|
||||
);
|
||||
@@ -398,12 +398,18 @@ class InvoicingPeriodRoute
|
||||
$limit = min(500, $limit);
|
||||
}
|
||||
|
||||
$allowedFlagTabs = ['all' => true, 'red' => true, 'yellow' => true, 'none' => true, 'filters' => true];
|
||||
$flagTab = trim((string)($parameters['flagTab'] ?? 'all'));
|
||||
if ($flagTab === '' || !isset($allowedFlagTabs[$flagTab])) {
|
||||
$flagTab = 'all';
|
||||
}
|
||||
|
||||
return [
|
||||
'periodView' => $periodView,
|
||||
'page' => $page,
|
||||
'limit' => $limit,
|
||||
'search' => trim((string)($parameters['search'] ?? '')),
|
||||
'flagTab' => trim((string)($parameters['flagTab'] ?? 'all')),
|
||||
'flagTab' => $flagTab,
|
||||
'includeRequiresAction' => self::parsePeriodBooleanOption(
|
||||
$parameters['includeRequiresAction'] ?? null,
|
||||
true
|
||||
@@ -506,25 +512,11 @@ class InvoicingPeriodRoute
|
||||
$types[$viewName] = array_values(array_filter(
|
||||
is_array($entries) ? $entries : [],
|
||||
static function (array $customer) use ($flagTab): bool {
|
||||
$hasManual = false;
|
||||
$hasAutomatic = false;
|
||||
if (is_array($customer['flags'] ?? null)) {
|
||||
foreach ($customer['flags'] as $flag) {
|
||||
if (!empty($flag['order_id']) || !empty($flag['invoice_collection_id'])) {
|
||||
continue;
|
||||
}
|
||||
if ($flag['is_manual'] ?? ($flag['source'] ?? '') === 'manual') {
|
||||
$hasManual = true;
|
||||
} else {
|
||||
$hasAutomatic = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$tab = 'none';
|
||||
if ($hasManual) {
|
||||
$flagCounts = self::getActivePeriodFlagCounts($customer);
|
||||
if ($flagCounts['manual'] > 0) {
|
||||
$tab = 'red';
|
||||
} elseif ($hasAutomatic) {
|
||||
} elseif ($flagCounts['automatic'] > 0) {
|
||||
$tab = 'yellow';
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use classes\economic;
|
||||
use classes\email;
|
||||
use classes\release_manager;
|
||||
use classes\recaptcha;
|
||||
use classes\slack;
|
||||
use classes\totp;
|
||||
use classes\virkdata;
|
||||
use classes\webauthn;
|
||||
@@ -810,6 +811,24 @@ class authRoute
|
||||
//$email->sendWelcomeEmailToCustomer($customerNumber, (string)$infoEmail); - Disabled, requested by Christian.
|
||||
$email->sendWelcomeEmailToCustomer($customerNumber, $jimmyEmail);
|
||||
$email->sendWelcomeEmailToCustomer($customerNumber, $invoiceEmail);
|
||||
|
||||
try {
|
||||
$email->sendNewCustomerRegistrationNotifications($customerNumber);
|
||||
} catch (Exception $exception) {
|
||||
$this->logRegisterCvrIssue('AUTH_REGISTER_CVR_SUPERUSER_NOTIFICATION_FAILED', [
|
||||
'customerNumber' => $customerNumber,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
(new slack())->send_customer_registration_notification($customerNumber);
|
||||
} catch (Exception $exception) {
|
||||
$this->logRegisterCvrIssue('AUTH_REGISTER_CVR_SLACK_NOTIFICATION_FAILED', [
|
||||
'customerNumber' => $customerNumber,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function logRegisterCvrIssue(string $action, array $context): void
|
||||
|
||||
@@ -6,6 +6,8 @@ use classes\authentication;
|
||||
use classes\response;
|
||||
use classes\shelly_relay_inventory;
|
||||
use dynamicimages\images\machine_1;
|
||||
use modules\selfserve\config\selfserve_dynamic_image_size_c;
|
||||
use modules\selfserve\selfserve_c;
|
||||
use objects\categories_o;
|
||||
use objects\department_lanes_o;
|
||||
use objects\department_selfserve_tasks_o;
|
||||
@@ -16,6 +18,8 @@ class departmentLanesRoute
|
||||
{
|
||||
use route_t;
|
||||
|
||||
private const RELEVANT_DYNAMIC_IMAGE_MAX_WIDTH = 1600;
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->get('/department/lanes/status-toggles', function () {
|
||||
@@ -219,6 +223,7 @@ class departmentLanesRoute
|
||||
$response->error('No dynamic image configured for this lane', 404);
|
||||
}
|
||||
$dynamic_image_id = (int)$dynamic_image_id;
|
||||
$dynamic_image_size = self::getSelfServeDynamicImageSizeMode();
|
||||
|
||||
// Parse optional params
|
||||
$buttons = null;
|
||||
@@ -266,27 +271,21 @@ class departmentLanesRoute
|
||||
// Cache check
|
||||
$cacheKey = null;
|
||||
if (defined('redis')) {
|
||||
// Cache only the default image variant to avoid unbounded cache key growth
|
||||
// from request-controlled parameters (buttons/current_step/etc.).
|
||||
$isDefaultVariant = $buttons === null
|
||||
&& $current_step === 0
|
||||
&& !(bool)$only_current_step
|
||||
&& $vehicle_type === null;
|
||||
|
||||
if ($isDefaultVariant) {
|
||||
$cacheParams = [
|
||||
'department' => $department_id,
|
||||
'lane' => $lane_id,
|
||||
'dynamic_image_id' => $dynamic_image_id,
|
||||
];
|
||||
$cacheKey = 'dynamic_image:' . md5(json_encode($cacheParams));
|
||||
$cachedImage = redis->get($cacheKey);
|
||||
if ($cachedImage) {
|
||||
header('Content-Type: image/png');
|
||||
header('Content-Length: ' . strlen($cachedImage));
|
||||
echo $cachedImage;
|
||||
exit;
|
||||
}
|
||||
$cacheKey = self::buildDynamicImageCacheKey([
|
||||
'dynamic_image_id' => $dynamic_image_id,
|
||||
'buttons' => $buttons,
|
||||
'current_step' => $current_step,
|
||||
'only_current_step' => $only_current_step,
|
||||
'vehicle_type' => $vehicle_type,
|
||||
'dynamic_image_size' => $dynamic_image_size,
|
||||
'thumb_position' => $thumb_position,
|
||||
]);
|
||||
$cachedImage = $cacheKey === null ? false : redis->get($cacheKey);
|
||||
if ($cachedImage) {
|
||||
header('Content-Type: image/png');
|
||||
header('Content-Length: ' . strlen($cachedImage));
|
||||
echo $cachedImage;
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,20 +312,17 @@ class departmentLanesRoute
|
||||
// Compose and serve the image
|
||||
try {
|
||||
$image->setup();
|
||||
if ($dynamic_image_size === selfserve_dynamic_image_size_c::SIZE_RELEVANT) {
|
||||
$image->resizeToMaxWidth(self::RELEVANT_DYNAMIC_IMAGE_MAX_WIDTH);
|
||||
}
|
||||
|
||||
// If caching is enabled, we need to capture the output or use export
|
||||
if ($cacheKey && defined('redis')) {
|
||||
$dataUri = $image->exportAsBase64('png');
|
||||
if (preg_match('/^data:image\/png;base64,(.*)$/', $dataUri, $matches)) {
|
||||
$imageData = base64_decode($matches[1]);
|
||||
if ($imageData !== false) {
|
||||
redis->setEx($cacheKey, $imageData, 86400); // Cache for 24 hours
|
||||
header('Content-Type: image/png');
|
||||
header('Content-Length: ' . strlen($imageData));
|
||||
echo $imageData;
|
||||
exit;
|
||||
}
|
||||
}
|
||||
$imageData = $image->exportBinary('png');
|
||||
redis->setEx($cacheKey, $imageData, 86400); // Cache for 24 hours
|
||||
header('Content-Type: image/png');
|
||||
header('Content-Length: ' . strlen($imageData));
|
||||
echo $imageData;
|
||||
exit;
|
||||
}
|
||||
|
||||
$image->servePicture('png');
|
||||
@@ -527,4 +523,47 @@ class departmentLanesRoute
|
||||
|
||||
$field->set($normalized);
|
||||
}
|
||||
|
||||
private static function getSelfServeDynamicImageSizeMode(): string
|
||||
{
|
||||
try {
|
||||
$mode = (string)(new selfserve_c())->dynamic_image_size->getVariableValue();
|
||||
} catch (\Throwable) {
|
||||
return selfserve_dynamic_image_size_c::SIZE_ORIGINAL;
|
||||
}
|
||||
|
||||
return in_array($mode, [selfserve_dynamic_image_size_c::SIZE_ORIGINAL, selfserve_dynamic_image_size_c::SIZE_RELEVANT], true)
|
||||
? $mode
|
||||
: selfserve_dynamic_image_size_c::SIZE_ORIGINAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* dynamic_image_id:int,
|
||||
* buttons:array<int|string>|null,
|
||||
* current_step:int,
|
||||
* only_current_step:bool,
|
||||
* vehicle_type:int|null,
|
||||
* dynamic_image_size:string,
|
||||
* thumb_position:int|null
|
||||
* } $variant
|
||||
*/
|
||||
private static function buildDynamicImageCacheKey(array $variant): ?string
|
||||
{
|
||||
$cacheParams = [
|
||||
'dynamic_image_id' => (int)$variant['dynamic_image_id'],
|
||||
'buttons' => $variant['buttons'],
|
||||
'current_step' => (int)$variant['current_step'],
|
||||
'only_current_step' => (bool)$variant['only_current_step'],
|
||||
'vehicle_type' => $variant['vehicle_type'],
|
||||
'dynamic_image_size' => (string)$variant['dynamic_image_size'],
|
||||
];
|
||||
|
||||
if ($variant['thumb_position'] !== null) {
|
||||
$cacheParams['thumb_position'] = (int)$variant['thumb_position'];
|
||||
}
|
||||
|
||||
$json = json_encode($cacheParams);
|
||||
return $json === false ? null : 'dynamic_image:' . md5($json);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ use objects\customer_vehicles_o;
|
||||
use objects\department_lanes_o;
|
||||
use objects\department_selfserve_tasks_o;
|
||||
use objects\department_selfserve_vehicle_conditions_o;
|
||||
use objects\departments_o;
|
||||
use objects\logs_o;
|
||||
use objects\selfserve_wash_sessions_o;
|
||||
use traits\route_t;
|
||||
|
||||
class departmentSelfserveVehicleConditionsRoute
|
||||
@@ -131,16 +133,18 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
$lane_id = (int)self::getParameter('lane_id');
|
||||
$reg = selfserve::standardize_registration((string)self::getParameter('reg'));
|
||||
|
||||
$lane = $this->assertLaneAccess($user, $lane_id);
|
||||
$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);
|
||||
$customer_number = null;
|
||||
if (!$has_global && $has_own) {
|
||||
if ($has_own && (!$has_global || !$this->userHasLaneDepartmentAccess($user, $lane))) {
|
||||
$customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
|
||||
}
|
||||
$vehicle_type_id = $this->resolveVehicleTypeIdFromQuery();
|
||||
$flow = $this->getWashFlow();
|
||||
|
||||
if ($vehicle_type_id !== null) {
|
||||
$flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false);
|
||||
$flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [
|
||||
'create_session' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
(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);
|
||||
@@ -171,10 +175,10 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
try {
|
||||
if (self::isParametersSet(['session_id'])) {
|
||||
$summary = $flow->getSessionSummary((int)self::getParameter('session_id'));
|
||||
$this->assertSummaryAccess($user, $summary, $has_global, 'list_department_selfserve_vehicle_conditions');
|
||||
$this->assertSummaryAccess($user, $summary, $has_global, $has_own, 'list_department_selfserve_vehicle_conditions');
|
||||
|
||||
if ($this->shouldRefreshSummaryForVehicleType($summary, $vehicle_type_id)) {
|
||||
$summary = $flow->synchronizeSession(
|
||||
$refreshed_summary = $flow->synchronizeSession(
|
||||
(int)($summary['session']['lane_id'] ?? 0),
|
||||
(string)($summary['session']['reg'] ?? ''),
|
||||
isset($summary['session']['customer_number']) && $summary['session']['customer_number'] !== null
|
||||
@@ -182,8 +186,12 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
: null,
|
||||
false,
|
||||
$vehicle_type_id,
|
||||
false
|
||||
false,
|
||||
['create_session' => false]
|
||||
);
|
||||
if (!empty($refreshed_summary['session']['id'])) {
|
||||
$summary = $refreshed_summary;
|
||||
}
|
||||
}
|
||||
|
||||
$response->success($summary);
|
||||
@@ -193,18 +201,27 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
$lane_id = (int)self::getParameter('lane_id');
|
||||
$reg = selfserve::standardize_registration((string)self::getParameter('reg'));
|
||||
|
||||
$this->assertLaneAccess($user, $lane_id);
|
||||
$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);
|
||||
$customer_number = null;
|
||||
if (!$has_global && $has_own) {
|
||||
if ($has_own && (!$has_global || !$this->userHasLaneDepartmentAccess($user, $lane))) {
|
||||
$customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
|
||||
}
|
||||
|
||||
if ($vehicle_type_id !== null) {
|
||||
$summary = $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false);
|
||||
$summary = $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [
|
||||
'create_session' => false,
|
||||
]);
|
||||
if (empty($summary['session']['id'])) {
|
||||
try {
|
||||
$summary = $flow->getLatestSessionSummary($lane_id, $reg);
|
||||
} catch (\RuntimeException) {
|
||||
// Keep the read-only snapshot when no previous wash exists.
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$summary = $flow->getLatestSessionSummary($lane_id, $reg);
|
||||
}
|
||||
$this->assertSummaryAccess($user, $summary, $has_global, 'list_department_selfserve_vehicle_conditions');
|
||||
$this->assertSummaryAccess($user, $summary, $has_global, $has_own, 'list_department_selfserve_vehicle_conditions');
|
||||
$response->success($summary);
|
||||
} catch (\RuntimeException $e) {
|
||||
$response->error($e->getMessage(), 404);
|
||||
@@ -490,6 +507,10 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
}
|
||||
|
||||
$session = is_array($summary['session'] ?? null) ? $summary['session'] : [];
|
||||
if (($session['completed_at'] ?? null) !== null || selfserve_wash_sessions_o::isTerminalStatus($session['status'] ?? null)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sessionVehicleTypeId = isset($session['vehicle_type_id']) && $session['vehicle_type_id'] !== null
|
||||
? (int)$session['vehicle_type_id']
|
||||
: null;
|
||||
@@ -527,7 +548,13 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
return $default;
|
||||
}
|
||||
|
||||
private function assertLaneAccess(object $user, int $laneId): department_lanes_o
|
||||
private function assertLaneAccess(
|
||||
object $user,
|
||||
int $laneId,
|
||||
bool $hasGlobalPermission = true,
|
||||
bool $hasOwnPermission = false,
|
||||
string $elevatedPermission = 'list_department_selfserve_vehicle_conditions'
|
||||
): department_lanes_o
|
||||
{
|
||||
global $response;
|
||||
|
||||
@@ -536,17 +563,77 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
$response->error('Department lane not found', 404);
|
||||
}
|
||||
|
||||
if ($hasGlobalPermission && $this->userHasLaneDepartmentAccess($user, $lane)) {
|
||||
return $lane;
|
||||
}
|
||||
|
||||
if ($hasOwnPermission && $this->isCustomerSelfServeLaneEnabled($lane)) {
|
||||
return $lane;
|
||||
}
|
||||
|
||||
if ($hasGlobalPermission) {
|
||||
$lane_department_id = (int)$lane->department->value();
|
||||
$this->forbidDepartmentAccess($lane_department_id);
|
||||
}
|
||||
|
||||
$response->forbidden([$elevatedPermission]);
|
||||
}
|
||||
|
||||
private function userHasLaneDepartmentAccess(object $user, department_lanes_o $lane): bool
|
||||
{
|
||||
$lane_department_id = (int)$lane->department->value();
|
||||
$authorized_department_ids = array_values(array_filter(
|
||||
array_map('intval', (array)$user->getGroup()->getDepartments()),
|
||||
static fn(int $department_id): bool => $department_id > 0
|
||||
));
|
||||
|
||||
if (!in_array($lane_department_id, $authorized_department_ids, true)) {
|
||||
$this->forbidDepartmentAccess($lane_department_id);
|
||||
return in_array($lane_department_id, $authorized_department_ids, true);
|
||||
}
|
||||
|
||||
private function isCustomerSelfServeLaneEnabled(department_lanes_o $lane): bool
|
||||
{
|
||||
try {
|
||||
if (!$lane->isSelfServeEnabled()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$department = (new departments_o())->select((int)$lane->department->value());
|
||||
return $department->exists() && $department->getSelfServeEnabled();
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function summaryBelongsToCustomer(object $user, array $summary): bool
|
||||
{
|
||||
$session_customer_number = $summary['session']['customer_number'] ?? null;
|
||||
if ($session_customer_number !== null && (int)$session_customer_number === (int)$user->customer_number->value()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $lane;
|
||||
$reg = (string)($summary['session']['reg'] ?? '');
|
||||
$vehicle_o = (new customer_vehicles_o())->selectByPlate($reg);
|
||||
return $vehicle_o->exists() && (int)$vehicle_o->customer_id->value() === (int)$user->customer_number->value();
|
||||
}
|
||||
|
||||
private function summaryDepartmentId(array $summary): int
|
||||
{
|
||||
return (int)($summary['lane']['department'] ?? $summary['session']['department_id'] ?? 0);
|
||||
}
|
||||
|
||||
private function userHasSummaryDepartmentAccess(object $user, array $summary): bool
|
||||
{
|
||||
$lane_department = $this->summaryDepartmentId($summary);
|
||||
if ($lane_department <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$authorized_department_ids = array_values(array_filter(
|
||||
array_map('intval', (array)$user->getGroup()->getDepartments()),
|
||||
static fn(int $department_id): bool => $department_id > 0
|
||||
));
|
||||
|
||||
return in_array($lane_department, $authorized_department_ids, true);
|
||||
}
|
||||
|
||||
private function requireAuthenticatedCustomerNumber(object $user, string $elevatedPermission): int
|
||||
@@ -561,28 +648,26 @@ class departmentSelfserveVehicleConditionsRoute
|
||||
return $customer_number;
|
||||
}
|
||||
|
||||
private function assertSummaryAccess(object $user, array $summary, bool $hasGlobalPermission, string $elevatedPermission): void
|
||||
private function assertSummaryAccess(
|
||||
object $user,
|
||||
array $summary,
|
||||
bool $hasGlobalPermission,
|
||||
bool $hasOwnPermission,
|
||||
string $elevatedPermission
|
||||
): void
|
||||
{
|
||||
global $response;
|
||||
|
||||
if ($hasGlobalPermission && $this->userHasSummaryDepartmentAccess($user, $summary)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($hasOwnPermission && $this->summaryBelongsToCustomer($user, $summary)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($hasGlobalPermission) {
|
||||
$authorized_department_ids = $user->getGroup()->getDepartments();
|
||||
$lane_department = (int)($summary['lane']['department'] ?? 0);
|
||||
if (!in_array($lane_department, $authorized_department_ids, true)) {
|
||||
$this->forbidDepartmentAccess($lane_department);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
$session_customer_number = $summary['session']['customer_number'] ?? null;
|
||||
if ($session_customer_number !== null && (int)$session_customer_number === (int)$user->customer_number->value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reg = (string)($summary['session']['reg'] ?? '');
|
||||
$vehicle_o = (new customer_vehicles_o())->selectByPlate($reg);
|
||||
if ($vehicle_o->exists() && (int)$vehicle_o->customer_id->value() === (int)$user->customer_number->value()) {
|
||||
return;
|
||||
$this->forbidDepartmentAccess($this->summaryDepartmentId($summary));
|
||||
}
|
||||
|
||||
$response->forbidden([$elevatedPermission]);
|
||||
|
||||
@@ -12,6 +12,7 @@ use classes\n8n;
|
||||
use classes\recaptcha;
|
||||
use classes\response;
|
||||
use classes\router;
|
||||
use classes\slack;
|
||||
use classes\stripe;
|
||||
use classes\weatherapi;
|
||||
use classes\workfeed;
|
||||
@@ -180,6 +181,46 @@ class moduleConfigRoute
|
||||
]
|
||||
);
|
||||
|
||||
/** Slack config > GET */
|
||||
$this->get('/slack/config', function () {
|
||||
global $response;
|
||||
$this->requirePermission('slack_config');
|
||||
$user = (new authentication())->get_user();
|
||||
if ($user) {
|
||||
(new logs_o())->add('slack_config', 'global', 1, $user->id, 'SLACK_CONFIG', 'Successfully fetched Slack config');
|
||||
$response->success(
|
||||
(new slack())->getConfig()->getConfigRequest()
|
||||
);
|
||||
} else {
|
||||
(new logs_o())->add('slack_config', 'global', 1, 0, 'SLACK_CONFIG', 'No user found, or invalid session');
|
||||
$response->error('Invalid session', 400);
|
||||
}
|
||||
},
|
||||
[
|
||||
'slack_config' => 'Get Slack config'
|
||||
]
|
||||
);
|
||||
|
||||
/** Slack config > POST */
|
||||
$this->post('/slack/config', function () {
|
||||
global $response;
|
||||
$this->requirePermission('slack_config');
|
||||
$user = (new authentication())->get_user();
|
||||
if ($user) {
|
||||
(new logs_o())->add('slack_config', 'global', 1, $user->id, 'SLACK_CONFIG', 'Successfully updated Slack config');
|
||||
$response->success(
|
||||
(new slack())->getConfig()->postConfigRequest()
|
||||
);
|
||||
} else {
|
||||
(new logs_o())->add('slack_config', 'global', 1, 0, 'SLACK_CONFIG', 'No user found, or invalid session');
|
||||
$response->error('Invalid session', 400);
|
||||
}
|
||||
},
|
||||
[
|
||||
'slack_config' => 'Update Slack config'
|
||||
]
|
||||
);
|
||||
|
||||
$this->get('/backups/config', function () {
|
||||
global $response;
|
||||
$this->requirePermission('backups_config');
|
||||
|
||||
@@ -8,6 +8,7 @@ use classes\response;
|
||||
use classes\router;
|
||||
use classes\selfserve;
|
||||
use classes\stripe;
|
||||
use modules\selfserve\classes\selfserve_config_versioning;
|
||||
use modules\selfserve\classes\selfserve_lane;
|
||||
use modules\selfserve\classes\selfserve_wash_flow;
|
||||
use modules\selfserve\helpers\selfserve_lane_command;
|
||||
@@ -22,6 +23,7 @@ use objects\logs_o;
|
||||
use objects\orders_o;
|
||||
use objects\customer_vehicles_o;
|
||||
use objects\selfserve_wash_sessions_o;
|
||||
use objects\selfserve_wash_session_tasks_o;
|
||||
use objects\stripe_module_customers_o;
|
||||
use objects\users_o;
|
||||
use traits\route_t;
|
||||
@@ -567,6 +569,30 @@ class moduleSelfServeRoute
|
||||
'subuser_id' => $subuser === false ? null : (int)$subuser->id,
|
||||
]);
|
||||
$lane->execute($command, $args);
|
||||
if ($command === selfserve_lane_command::START) {
|
||||
try {
|
||||
$license_plate = selfserve::standardize_registration(
|
||||
(string)($args->license_plate ?: $lane->getLicensePlate())
|
||||
);
|
||||
if ($license_plate !== '') {
|
||||
(new selfserve_wash_flow())->synchronizeSession(
|
||||
$lane_id,
|
||||
$license_plate,
|
||||
$customer_number > 0 ? $customer_number : null,
|
||||
false,
|
||||
null,
|
||||
false
|
||||
);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log(
|
||||
'Failed to persist self-serve START session for lane '
|
||||
. $lane_id
|
||||
. ': '
|
||||
. $e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
$response->success([
|
||||
'id' => $lane->id,
|
||||
'status' => $lane->getLaneStatus()->name,
|
||||
@@ -630,23 +656,64 @@ class moduleSelfServeRoute
|
||||
// Build allowed services from provided tasks
|
||||
$lane = $selfserve->lane($lane_id);
|
||||
$customer_number = $this->resolveEffectiveCustomerNumber();
|
||||
self::requirePermission('modules_selfserve_lane_services_set_allowed');
|
||||
$this->requireSelfServeLaneAccess(
|
||||
$lane,
|
||||
$customer_number === null ? 0 : (int)$customer_number,
|
||||
['modules_selfserve_lane_services_set_allowed'],
|
||||
false
|
||||
);
|
||||
$session_task_services = [];
|
||||
$latest_session = (new selfserve_wash_sessions_o())->selectLatestOpenByLane(
|
||||
$lane_id,
|
||||
$customer_number === null || (int)$customer_number <= 0 ? null : (int)$customer_number
|
||||
);
|
||||
if (!$latest_session->exists() && $customer_number !== null && (int)$customer_number > 0) {
|
||||
$latest_session = (new selfserve_wash_sessions_o())->selectLatestOpenByLane($lane_id);
|
||||
}
|
||||
if ($latest_session->exists()) {
|
||||
foreach ((new selfserve_wash_session_tasks_o())->listBySession((int)$latest_session->id) as $session_task) {
|
||||
$task_id = (int)($session_task['task_id'] ?? 0);
|
||||
if ($task_id > 0) {
|
||||
$services = $session_task['services'] ?? [];
|
||||
if (is_string($services)) {
|
||||
$decoded_services = json_decode($services, true);
|
||||
$services = json_last_error() === JSON_ERROR_NONE && is_array($decoded_services)
|
||||
? $decoded_services
|
||||
: [];
|
||||
}
|
||||
$session_task_services[$task_id] = is_array($services) ? $services : [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$allowed_services = [];
|
||||
foreach ($task_ids as $tid) {
|
||||
if ($tid <= 0) continue;
|
||||
$t = new \objects\department_selfserve_tasks_o();
|
||||
$t->select($tid);
|
||||
if (!$t->exists()) continue; // ignore unknown ids
|
||||
// Validate the task belongs to the same lane
|
||||
if ((int)$t->lane->value() !== $lane_id) continue;
|
||||
// Merge services (if any)
|
||||
$services = (array)$t->services->value();
|
||||
$published_config_task_services = $this->publishedConfigTaskServicesForLane($lane, $task_ids);
|
||||
$merge_services = static function (array $services) use (&$allowed_services): void {
|
||||
foreach ($services as $srv) {
|
||||
$name = strtoupper((string)$srv);
|
||||
if (!in_array($name, $allowed_services, true)) {
|
||||
$allowed_services[] = $name;
|
||||
}
|
||||
}
|
||||
};
|
||||
foreach ($task_ids as $tid) {
|
||||
if ($tid <= 0) continue;
|
||||
if (array_key_exists($tid, $session_task_services)) {
|
||||
$merge_services($session_task_services[$tid]);
|
||||
continue;
|
||||
}
|
||||
if (array_key_exists($tid, $published_config_task_services)) {
|
||||
$merge_services($published_config_task_services[$tid]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$t = new \objects\department_selfserve_tasks_o();
|
||||
$t->select($tid);
|
||||
if (!$t->exists()) continue; // ignore unknown ids
|
||||
// Validate the task belongs to the same lane
|
||||
if ((int)$t->lane->value() !== $lane_id) continue;
|
||||
// Merge services (if any)
|
||||
$merge_services((array)$t->services->value());
|
||||
}
|
||||
// Persist on lane cache (overwrites previous allowed services)
|
||||
try {
|
||||
@@ -1603,9 +1670,13 @@ class moduleSelfServeRoute
|
||||
}
|
||||
|
||||
if ($allow_customer_self_serve) {
|
||||
$customer_allowed = $requires_active_wash
|
||||
? $this->canCustomerUseActiveOperationalSelfServeLane($lane, $customer_number, $allow_department_active_wash)
|
||||
: $this->canCustomerUseSelfServeLane($lane, $customer_number);
|
||||
if ($requires_active_wash && $allow_department_active_wash) {
|
||||
$customer_allowed = $this->canCustomerUsePropertyGateForLane($lane, $customer_number);
|
||||
} else {
|
||||
$customer_allowed = $requires_active_wash
|
||||
? $this->canCustomerUseActiveOperationalSelfServeLane($lane, $customer_number, false)
|
||||
: $this->canCustomerUseSelfServeLane($lane, $customer_number);
|
||||
}
|
||||
|
||||
if ($customer_allowed) {
|
||||
return;
|
||||
@@ -1760,7 +1831,17 @@ class moduleSelfServeRoute
|
||||
|
||||
protected function canCustomerUsePropertyGateForLane(selfserve_lane $lane, int $customer_number): bool
|
||||
{
|
||||
return $this->canCustomerUseActiveOperationalSelfServeLane($lane, $customer_number, true);
|
||||
if ($this->canCustomerUseActiveOperationalSelfServeLane($lane, $customer_number, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($customer_number <= 0 || !$this->isOwnCustomerContext($customer_number)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$department_id = $this->departmentIdForLane($lane);
|
||||
return $department_id > 0
|
||||
&& $this->customerHasActiveSelfServeWashInDepartment($department_id, $customer_number);
|
||||
}
|
||||
|
||||
protected function canCustomerUseActiveOperationalSelfServeLane(
|
||||
@@ -1899,6 +1980,59 @@ class moduleSelfServeRoute
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,int> $task_ids
|
||||
* @return array<int,array<int,string>>
|
||||
*/
|
||||
private function publishedConfigTaskServicesForLane(selfserve_lane $lane, array $task_ids): array
|
||||
{
|
||||
$department_id = $this->departmentIdForLane($lane);
|
||||
if ($department_id <= 0 || $task_ids === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$published = (new selfserve_config_versioning())->getPublishedConfig($department_id);
|
||||
$config = is_array($published) ? (array)($published['config'] ?? []) : [];
|
||||
$tasks = is_array($config['tasks'] ?? null) ? $config['tasks'] : [];
|
||||
if ($tasks === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$requested_task_ids = array_fill_keys(array_map(static fn($task_id): int => (int)$task_id, $task_ids), true);
|
||||
$services_by_task_id = [];
|
||||
foreach ($tasks as $task) {
|
||||
if (!is_array($task)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$task_id = (int)($task['id'] ?? $task['task_id'] ?? 0);
|
||||
if ($task_id <= 0 || !isset($requested_task_ids[$task_id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$task_department_id = (int)($task['department'] ?? $task['department_id'] ?? 0);
|
||||
if ($task_department_id !== 0 && $task_department_id !== $department_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$task_lane_id = (int)($task['lane'] ?? $task['lane_id'] ?? 0);
|
||||
if ($task_lane_id !== 0 && $task_lane_id !== (int)$lane->id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$services = $task['services'] ?? [];
|
||||
if (is_string($services)) {
|
||||
$decoded = json_decode($services, true);
|
||||
$services = json_last_error() === JSON_ERROR_NONE && is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
$services_by_task_id[$task_id] = is_array($services) ? $services : [];
|
||||
}
|
||||
|
||||
return $services_by_task_id;
|
||||
}
|
||||
|
||||
private function requestedShellyTransportOverride(): ?string
|
||||
{
|
||||
$transport = null;
|
||||
|
||||
@@ -392,6 +392,37 @@ class orderBookingRoute
|
||||
]
|
||||
);
|
||||
|
||||
$this->post('/order-bookings/completion-confirmation/resend', function () {
|
||||
global $response;
|
||||
|
||||
$object = self::getTargetObject();
|
||||
if (!$object || !$object->exists()) {
|
||||
$response->error('Order booking does not exist.', 400);
|
||||
}
|
||||
|
||||
self::requirePermission('complete_bookings');
|
||||
self::requireDepartmentAccess((int)$object->department->value());
|
||||
|
||||
if (!$object->hasTransaction()) {
|
||||
$response->error('Order booking has not been completed yet.', 409);
|
||||
}
|
||||
|
||||
if (!$object->getOrder()->hasWashCertificateAttached()) {
|
||||
$response->error('Order booking completion confirmation is not available yet.', 409);
|
||||
}
|
||||
|
||||
(new email())->sendWashCertificateEmailToCustomer($object);
|
||||
|
||||
$response->success([
|
||||
'message' => 'Completion confirmation resent successfully.',
|
||||
'booking' => $object->asArray(),
|
||||
]);
|
||||
},
|
||||
[
|
||||
'complete_bookings' => 'Permission for department admins to resend order booking completion confirmation emails.'
|
||||
]
|
||||
);
|
||||
|
||||
$this->post('/order-bookings/complete', function () {
|
||||
// Require the user to be logged in
|
||||
global $response;
|
||||
|
||||
@@ -496,6 +496,49 @@ class orderInvoicesRoute
|
||||
]
|
||||
);
|
||||
|
||||
/** Collected order invoices > Move to customer > POST */
|
||||
$this->post('/collected-invoices/move-to-customer', function () {
|
||||
global $response;
|
||||
self::requirePermission('move_collected_invoice_customer');
|
||||
$user = (new authentication())->get_user();
|
||||
if (!$user) {
|
||||
(new logs_o())->add('orderInvoices', 'global', 0, 0, 'MOVE_COLLECTED_INVOICE_CUSTOMER', 'User tried to move a collected order invoice without a valid session');
|
||||
$response->error('Invalid session', 400);
|
||||
}
|
||||
|
||||
self::requireParameters(['id', 'customer_number']);
|
||||
self::requireType((int)self::getParameter('id'), self::type_int());
|
||||
self::requireType((int)self::getParameter('customer_number'), self::type_int());
|
||||
self::requireMinValue((int)self::getParameter('id'), 1);
|
||||
self::requireMinValue((int)self::getParameter('customer_number'), 1);
|
||||
self::requireMaxValue((int)self::getParameter('customer_number'), 999999999);
|
||||
|
||||
$collected_order_invoices = (new collected_order_invoices_o())->select((int)self::getParameter('id'));
|
||||
$collected_order_invoices->requireSelected();
|
||||
|
||||
try {
|
||||
$move_result = $collected_order_invoices->moveToCustomer((int)self::getParameter('customer_number'));
|
||||
} catch (\Throwable $e) {
|
||||
$response->error($e->getMessage(), 400);
|
||||
}
|
||||
|
||||
(new logs_o())->add(
|
||||
'orderInvoices',
|
||||
'global',
|
||||
1,
|
||||
$user->id,
|
||||
'MOVE_COLLECTED_INVOICE_CUSTOMER',
|
||||
'User moved collected order invoice #' . (int)$collected_order_invoices->id . ' to customer #' . (int)self::getParameter('customer_number')
|
||||
);
|
||||
|
||||
$response->add_meta('move', $move_result);
|
||||
$response->success($collected_order_invoices->asArray());
|
||||
},
|
||||
[
|
||||
'move_collected_invoice_customer' => 'Move a collected order invoice and its orders to another customer. This is a superuser-only route.'
|
||||
]
|
||||
);
|
||||
|
||||
/** Collected order invoices > Split > POST */
|
||||
$this->post('/collected-invoices/split', function () {
|
||||
global $response;
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace routes;
|
||||
|
||||
use classes\authentication;
|
||||
use objects\logs_o;
|
||||
use objects\users_o;
|
||||
use traits\route_t;
|
||||
|
||||
class userNotificationsRoute
|
||||
@@ -28,6 +29,9 @@ class userNotificationsRoute
|
||||
$wash_certificate_email = self::isParametersSet(['wash_certificate_email']) ? (string)self::getParameter('wash_certificate_email') : null;
|
||||
$sms_notifications_enabled = self::isParametersSet(['sms_notifications_enabled']) ? (bool)self::getParameter('sms_notifications_enabled') : null;
|
||||
$email_notifications_enabled = self::isParametersSet(['email_notifications_enabled']) ? (bool)self::getParameter('email_notifications_enabled') : null;
|
||||
$superuser_new_customer_email_notifications_enabled = self::isParametersSet([users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS])
|
||||
? (bool)self::getParameter(users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS)
|
||||
: null;
|
||||
/**
|
||||
* Wash Certificate Email
|
||||
*/
|
||||
@@ -55,6 +59,22 @@ class userNotificationsRoute
|
||||
self::requireType($email_notifications_enabled, self::type_bool());
|
||||
$user->email_notifications_enabled->set($email_notifications_enabled ? 1 : 0);
|
||||
}
|
||||
/**
|
||||
* Superuser New Customer Email Notifications Enabled
|
||||
*/
|
||||
if ($superuser_new_customer_email_notifications_enabled !== null) {
|
||||
self::requirePermission('superuser');
|
||||
self::requireType($superuser_new_customer_email_notifications_enabled, self::type_bool());
|
||||
$user->setSuperuserNewCustomerEmailNotificationsEnabled($superuser_new_customer_email_notifications_enabled);
|
||||
}
|
||||
$token = str_replace('Bearer ', '', (string)($_SERVER['HTTP_AUTHORIZATION'] ?? ''));
|
||||
if ($token !== '') {
|
||||
try {
|
||||
redis->clear_auth_session($token);
|
||||
} catch (\Throwable) {
|
||||
// Session cache invalidation is best-effort; the persistent update above is authoritative.
|
||||
}
|
||||
}
|
||||
// Log the update
|
||||
(new logs_o())->add('user_notifications', 'global', 0, $user->id, 'USER_NOTIFICATIONS_UPDATE', 'User notification settings updated');
|
||||
// Return success
|
||||
@@ -65,4 +85,4 @@ class userNotificationsRoute
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
usesApiSuite();
|
||||
|
||||
function moved_invoice_collection_customer_number(int $invoiceCollectionId): int
|
||||
{
|
||||
$row = api_test_runtime()->queryOne('SELECT customer_number FROM collected_order_invoices WHERE id = ' . $invoiceCollectionId . ' LIMIT 1');
|
||||
return (int)($row['customer_number'] ?? 0);
|
||||
}
|
||||
|
||||
function moved_order_customer_number(int $orderId): int
|
||||
{
|
||||
$row = api_test_runtime()->queryOne('SELECT customer_id FROM orders WHERE id = ' . $orderId . ' LIMIT 1');
|
||||
return (int)($row['customer_id'] ?? 0);
|
||||
}
|
||||
|
||||
it('moves a collected invoice collection and all attached orders to another customer', function (): void {
|
||||
api_test_covers('POST /collected-invoices/move-to-customer', 'happy');
|
||||
|
||||
$sourceCustomer = api_fixtures()->createUser(['display_name' => 'Move Source Customer']);
|
||||
$targetCustomer = api_fixtures()->createUser(['display_name' => 'Move Target Customer']);
|
||||
$department = api_fixtures()->createDepartment();
|
||||
$invoiceCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $sourceCustomer['customer_number'],
|
||||
]);
|
||||
$firstOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $sourceCustomer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $invoiceCollection['id'],
|
||||
]);
|
||||
$secondOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $sourceCustomer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $invoiceCollection['id'],
|
||||
]);
|
||||
$session = api_fixtures()->createUserSession(['move_collected_invoice_customer']);
|
||||
|
||||
$response = api_client()->post('/collected-invoices/move-to-customer', [
|
||||
'id' => $invoiceCollection['id'],
|
||||
'customer_number' => $targetCustomer['customer_number'],
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$payload = $response->data();
|
||||
$moveMeta = $response->meta()['move'] ?? [];
|
||||
|
||||
expect($payload['id'] ?? null)->toBe((int)$invoiceCollection['id'])
|
||||
->and($payload['customer_number'] ?? null)->toBe((int)$targetCustomer['customer_number'])
|
||||
->and($moveMeta['source_customer_number'] ?? null)->toBe((int)$sourceCustomer['customer_number'])
|
||||
->and($moveMeta['target_customer_number'] ?? null)->toBe((int)$targetCustomer['customer_number'])
|
||||
->and($moveMeta['moved_order_count'] ?? null)->toBe(2)
|
||||
->and(moved_invoice_collection_customer_number((int)$invoiceCollection['id']))->toBe((int)$targetCustomer['customer_number'])
|
||||
->and(moved_order_customer_number((int)$firstOrder['id']))->toBe((int)$targetCustomer['customer_number'])
|
||||
->and(moved_order_customer_number((int)$secondOrder['id']))->toBe((int)$targetCustomer['customer_number']);
|
||||
});
|
||||
|
||||
it('rejects moving a collection that already has an external invoice reference', function (): void {
|
||||
api_test_covers('POST /collected-invoices/move-to-customer', 'external-guard');
|
||||
|
||||
$sourceCustomer = api_fixtures()->createUser(['display_name' => 'Move External Source Customer']);
|
||||
$targetCustomer = api_fixtures()->createUser(['display_name' => 'Move External Target Customer']);
|
||||
$department = api_fixtures()->createDepartment();
|
||||
$invoiceCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $sourceCustomer['customer_number'],
|
||||
'external_id' => 'external-invoice-123',
|
||||
]);
|
||||
$order = api_fixtures()->createOrder([
|
||||
'customer_id' => $sourceCustomer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $invoiceCollection['id'],
|
||||
]);
|
||||
$session = api_fixtures()->createUserSession(['move_collected_invoice_customer']);
|
||||
|
||||
$response = api_client()->post('/collected-invoices/move-to-customer', [
|
||||
'id' => $invoiceCollection['id'],
|
||||
'customer_number' => $targetCustomer['customer_number'],
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false);
|
||||
|
||||
expect($response->data()['message'] ?? '')->toContain('external or booked invoice')
|
||||
->and(moved_invoice_collection_customer_number((int)$invoiceCollection['id']))->toBe((int)$sourceCustomer['customer_number'])
|
||||
->and(moved_order_customer_number((int)$order['id']))->toBe((int)$sourceCustomer['customer_number']);
|
||||
});
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use classes\email;
|
||||
use classes\pdf_store;
|
||||
|
||||
putenv('EMAIL_FAKE_MODE=1');
|
||||
|
||||
usesApiSuite();
|
||||
@@ -76,3 +79,97 @@ it('requires department access when resending order booking confirmations', func
|
||||
->assertSuccess(false)
|
||||
->assertMissingPermissions(['department_access_' . $department['id']]);
|
||||
});
|
||||
|
||||
it('allows department admins to resend order booking completion confirmations', function (): void {
|
||||
email::resetFakeDeliveries();
|
||||
|
||||
$customer = api_fixtures()->createUser([
|
||||
'display_name' => 'Resend Completion Confirmation Customer',
|
||||
'email' => 'resend-completion-confirmation@example.test',
|
||||
]);
|
||||
$department = api_fixtures()->createDepartment([
|
||||
'name' => 'Resend Completion Confirmation Department',
|
||||
]);
|
||||
$cashier = api_fixtures()->createUser([
|
||||
'display_name' => 'Resend Completion Confirmation Cashier',
|
||||
]);
|
||||
$order = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'cashier_id' => $cashier['id'],
|
||||
'department_id' => $department['id'],
|
||||
]);
|
||||
$booking = api_fixtures()->createOrderBooking([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
'department' => $department['id'],
|
||||
'reference' => 'RESEND-COMPLETION',
|
||||
'reg_1' => 'DONE1',
|
||||
'order_id' => $order['id'],
|
||||
]);
|
||||
api_fixtures()->createOrderAttachment([
|
||||
'order_id' => $order['id'],
|
||||
'content' => json_encode([
|
||||
'document' => 'completion-confirmation-test.pdf',
|
||||
'other' => 'wash_certificate',
|
||||
], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
(new pdf_store())->createObject('completion-confirmation-test.pdf', '%PDF-1.4 test completion confirmation');
|
||||
$session = api_fixtures()->createUserSession([
|
||||
'complete_bookings',
|
||||
'department_access_' . $department['id'],
|
||||
]);
|
||||
|
||||
$response = api_client()->post('/order-bookings/completion-confirmation/resend', [
|
||||
'id' => $booking['id'],
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
expect($response->data())
|
||||
->toBeArray()
|
||||
->toHaveKey('message', 'Completion confirmation resent successfully.')
|
||||
->toHaveKey('booking')
|
||||
->and($response->data()['booking'])
|
||||
->toBeArray()
|
||||
->and($response->data()['booking']['id'] ?? null)
|
||||
->toBe($booking['id'])
|
||||
->and(email::$fake_deliveries)
|
||||
->toHaveCount(1)
|
||||
->and(email::$fake_deliveries[0]['to'] ?? null)
|
||||
->toBe('resend-completion-confirmation@example.test')
|
||||
->and(email::$fake_deliveries[0]['subject'] ?? '')
|
||||
->toContain('RESEND-COMPLETION');
|
||||
});
|
||||
|
||||
it('requires department access when resending order booking completion confirmations', function (): void {
|
||||
$customer = api_fixtures()->createUser([
|
||||
'display_name' => 'Resend Completion Confirmation Foreign Customer',
|
||||
]);
|
||||
$department = api_fixtures()->createDepartment([
|
||||
'name' => 'Resend Completion Confirmation Foreign Department',
|
||||
]);
|
||||
$order = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
]);
|
||||
$booking = api_fixtures()->createOrderBooking([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
'department' => $department['id'],
|
||||
'order_id' => $order['id'],
|
||||
]);
|
||||
$session = api_fixtures()->createUserSession([
|
||||
'complete_bookings',
|
||||
]);
|
||||
|
||||
$response = api_client()->post('/order-bookings/completion-confirmation/resend', [
|
||||
'id' => $booking['id'],
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(403)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMissingPermissions(['department_access_' . $department['id']]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
<?php
|
||||
|
||||
usesApiSuite();
|
||||
|
||||
function selfserve_customer_start_ensure_legacy_redis_constant(): void
|
||||
{
|
||||
if (defined('redis')) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $REDIS_CONFIG;
|
||||
|
||||
$REDIS_CONFIG = [
|
||||
'host' => getenv('REDIS_CONFIG_HOST') ?: getenv('REDIS_CONFIG_DEBUG_HOST') ?: 'redis',
|
||||
'user' => getenv('REDIS_CONFIG_USER') ?: getenv('REDIS_CONFIG_DEBUG_USER') ?: 'default',
|
||||
'database' => getenv('REDIS_CONFIG_DATABASE') ?: getenv('REDIS_CONFIG_DEBUG_DATABASE') ?: '0',
|
||||
'password' => getenv('REDIS_CONFIG_PASSWORD') ?: getenv('REDIS_CONFIG_DEBUG_PASSWORD') ?: '',
|
||||
'port' => getenv('REDIS_CONFIG_PORT') ?: getenv('REDIS_CONFIG_DEBUG_PORT') ?: '6379',
|
||||
];
|
||||
|
||||
define('redis', (new \classes\redis())->connect());
|
||||
}
|
||||
|
||||
function selfserve_customer_start_make_available(int $laneId): void
|
||||
{
|
||||
selfserve_customer_start_ensure_legacy_redis_constant();
|
||||
|
||||
$lane = (new \classes\selfserve())->lane($laneId);
|
||||
$lane->setLaneStatus(\modules\selfserve\helpers\selfserve_lane_status::AVAILABLE);
|
||||
$lane->setLaneState(\modules\selfserve\helpers\selfserve_lane_state::IDLE);
|
||||
$lane->setCustomerNumber(0);
|
||||
$lane->setLicensePlate('');
|
||||
$lane->setWashStartTime(0);
|
||||
}
|
||||
|
||||
it('allows the customer self-serve start sequence without department access', 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,
|
||||
]);
|
||||
$headers = api_fixtures()->bearerHeaders(
|
||||
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||
);
|
||||
$laneId = (int)$scenario['lane']['id'];
|
||||
$reg = (string)$scenario['vehicle']['reg'];
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
|
||||
api_client()
|
||||
->get('/department/selfserve/vehicle/allowed?lane_id=' . $laneId . '®=' . urlencode($reg), $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$summaryResponse = api_client()
|
||||
->get('/department/selfserve/washes/summary?lane_id=' . $laneId . '®=' . urlencode($reg), $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($summaryResponse->data()['session']['customer_number'] ?? null)
|
||||
->toBe((int)$scenario['customer']['customer_number']);
|
||||
|
||||
api_client()
|
||||
->post('/modules/self-serve/lane/services/allowed', [
|
||||
'lane_id' => $laneId,
|
||||
'task_ids' => [(int)$scenario['tasks'][1]['id']],
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$startResponse = api_client()
|
||||
->post('/modules/self-serve/lane/command', [
|
||||
'lane_id' => $laneId,
|
||||
'command' => 'START',
|
||||
'license_plate' => $reg,
|
||||
'wash_type' => 'Manual',
|
||||
'defer_relay_side_effects' => true,
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($startResponse->data()['status'] ?? null)->toBe('OCCUPIED')
|
||||
->and($startResponse->data()['customer_number'] ?? null)
|
||||
->toBe((int)$scenario['customer']['customer_number']);
|
||||
});
|
||||
|
||||
it('marks the active customer session relay-enabled after machine relay enable', function (): void {
|
||||
$group = api_fixtures()->createGroup([], [
|
||||
'list_own_department_selfserve_vehicle_conditions',
|
||||
'modules_selfserve_lane_relay_enable_machine',
|
||||
]);
|
||||
$scenario = api_fixtures()->createSelfServeScenario([
|
||||
'customer' => ['group_id' => $group['id']],
|
||||
'department_selfserve_enabled' => true,
|
||||
'lane_selfserve_enabled' => true,
|
||||
'session' => [
|
||||
'status' => 'READY_FOR_MACHINE_START',
|
||||
'machine_relay_enabled' => 0,
|
||||
'machine_relay_enabled_at' => null,
|
||||
'machine_start_triggered' => 0,
|
||||
'machine_start_triggered_at' => null,
|
||||
'wash_started_at' => null,
|
||||
],
|
||||
]);
|
||||
$headers = api_fixtures()->bearerHeaders(
|
||||
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||
);
|
||||
$laneId = (int)$scenario['lane']['id'];
|
||||
$reg = (string)$scenario['vehicle']['reg'];
|
||||
$machineTaskId = (int)$scenario['tasks'][1]['id'];
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
|
||||
api_client()
|
||||
->get('/department/selfserve/vehicle/allowed?lane_id=' . $laneId . '®=' . urlencode($reg), $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
api_client()
|
||||
->post('/modules/self-serve/lane/services/allowed', [
|
||||
'lane_id' => $laneId,
|
||||
'task_ids' => [$machineTaskId],
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
api_client()
|
||||
->post('/modules/self-serve/lane/command', [
|
||||
'lane_id' => $laneId,
|
||||
'command' => 'START',
|
||||
'license_plate' => $reg,
|
||||
'wash_type' => 'Machine',
|
||||
'defer_relay_side_effects' => true,
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
api_client()
|
||||
->post('/modules/self-serve/lane/relay/machine/enable', [
|
||||
'lane_id' => $laneId,
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$activeResponse = api_client()
|
||||
->get('/modules/self-serve/lane/wash/my-active-wash', $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($activeResponse->data()['session']['status'] ?? null)->toBe('MACHINE_RELAY_ENABLED')
|
||||
->and($activeResponse->data()['session']['machine_relay_enabled'] ?? null)->toBeTrue()
|
||||
->and($activeResponse->data()['session']['machine_start_triggered'] ?? null)->toBeFalse();
|
||||
});
|
||||
|
||||
it('derives allowed services from v2 session task snapshots when task rows are not legacy records', 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,
|
||||
]);
|
||||
$headers = api_fixtures()->bearerHeaders(
|
||||
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||
);
|
||||
$laneId = (int)$scenario['lane']['id'];
|
||||
$v2TaskId = 900000 + $laneId;
|
||||
|
||||
$sessionTask = (new \objects\selfserve_wash_session_tasks_o())->addSnapshot(
|
||||
(int)$scenario['session']['id'],
|
||||
$v2TaskId,
|
||||
'V2 path editor machine task',
|
||||
'Task exists only in the session snapshot.',
|
||||
['MACHINE', 'PROGRAM_PICKER'],
|
||||
['program_picker', 6, 'start'],
|
||||
(int)$scenario['product']['id'],
|
||||
);
|
||||
|
||||
try {
|
||||
$response = api_client()
|
||||
->post('/modules/self-serve/lane/services/allowed', [
|
||||
'lane_id' => $laneId,
|
||||
'task_ids' => [$v2TaskId],
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($response->data()['allowed_services'] ?? [])->toBe([
|
||||
'MACHINE',
|
||||
'PROGRAM_PICKER',
|
||||
]);
|
||||
} finally {
|
||||
$sessionTask->delete();
|
||||
}
|
||||
});
|
||||
|
||||
it('derives allowed services from published v2 config task snapshots when no session exists yet', 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,
|
||||
'session' => [
|
||||
'status' => 'COMPLETED',
|
||||
'completed_at' => date('Y-m-d H:i:s'),
|
||||
'wash_started_at' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
]);
|
||||
$headers = api_fixtures()->bearerHeaders(
|
||||
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||
);
|
||||
$laneId = (int)$scenario['lane']['id'];
|
||||
$departmentId = (int)$scenario['department']['id'];
|
||||
$productId = (int)$scenario['product']['id'];
|
||||
$v2TaskId = 910000 + $laneId;
|
||||
|
||||
$configVersion = (new \objects\selfserve_config_versions_o())->add(
|
||||
$departmentId,
|
||||
\modules\selfserve\classes\selfserve_config_versioning::STATUS_PUBLISHED,
|
||||
1,
|
||||
[
|
||||
'schema_version' => 2,
|
||||
'tasks' => [
|
||||
[
|
||||
'id' => $v2TaskId,
|
||||
'department' => $departmentId,
|
||||
'lane' => $laneId,
|
||||
'product' => $productId,
|
||||
'machine_type_id' => 0,
|
||||
'task' => 'Published v2 machine task',
|
||||
'description' => 'Task exists only in the published config snapshot.',
|
||||
'order_priority' => 10,
|
||||
'services' => ['MACHINE', 'PROGRAM_PICKER'],
|
||||
],
|
||||
],
|
||||
],
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
date('Y-m-d H:i:s'),
|
||||
);
|
||||
|
||||
try {
|
||||
$response = api_client()
|
||||
->post('/modules/self-serve/lane/services/allowed', [
|
||||
'lane_id' => $laneId,
|
||||
'task_ids' => [$v2TaskId],
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($response->data()['allowed_services'] ?? [])->toBe([
|
||||
'MACHINE',
|
||||
'PROGRAM_PICKER',
|
||||
]);
|
||||
} finally {
|
||||
$configVersion->delete();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps long generated task descriptions when refreshing vehicle eligibility snapshots', 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,
|
||||
]);
|
||||
$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'];
|
||||
$taskId = (int)$scenario['tasks'][1]['id'];
|
||||
$longDescription = str_repeat('Hvis ja - vaelg tagboerste program (#6) og lift program (#2) / ', 6);
|
||||
|
||||
$statement = api_test_runtime()->db()->prepare(
|
||||
'UPDATE department_selfserve_tasks SET description = ? WHERE id = ?'
|
||||
);
|
||||
$statement->bind_param('si', $longDescription, $taskId);
|
||||
$statement->execute();
|
||||
|
||||
api_client()
|
||||
->get(
|
||||
'/department/selfserve/vehicle/allowed?lane_id=' . $laneId
|
||||
. '®=' . urlencode($reg)
|
||||
. '&vehicle_type=' . $productId,
|
||||
$headers
|
||||
)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$sessionTask = api_test_runtime()->queryOne(
|
||||
'SELECT description FROM selfserve_wash_session_tasks'
|
||||
. ' WHERE session_id = ' . (int)$scenario['session']['id']
|
||||
. ' AND task_id = ' . $taskId
|
||||
. ' LIMIT 1'
|
||||
);
|
||||
|
||||
expect($sessionTask['description'] ?? null)->toBe($longDescription);
|
||||
});
|
||||
|
||||
it('does not create an active wash preview session from read-only eligibility checks', 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,
|
||||
]);
|
||||
$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'];
|
||||
$sessionId = (int)$scenario['session']['id'];
|
||||
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_events WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_tasks WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_answers WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_sessions WHERE id = ' . $sessionId
|
||||
);
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
|
||||
api_client()
|
||||
->get(
|
||||
'/department/selfserve/vehicle/allowed?lane_id=' . $laneId
|
||||
. '®=' . urlencode($reg)
|
||||
. '&vehicle_type=' . $productId,
|
||||
$headers
|
||||
)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$openSession = api_test_runtime()->queryOne(
|
||||
'SELECT id FROM selfserve_wash_sessions'
|
||||
. ' WHERE lane_id = ' . $laneId
|
||||
. ' AND reg = "' . api_test_runtime()->db()->real_escape_string($reg) . '"'
|
||||
. ' AND completed_at IS NULL'
|
||||
. ' AND deleted_at IS NULL'
|
||||
. ' LIMIT 1'
|
||||
);
|
||||
|
||||
expect($openSession)->toBeNull();
|
||||
});
|
||||
|
||||
it('creates a durable wash session from customer start after read-only eligibility', 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,
|
||||
]);
|
||||
$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'];
|
||||
$sessionId = (int)$scenario['session']['id'];
|
||||
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_events WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_tasks WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_session_answers WHERE session_id = ' . $sessionId
|
||||
);
|
||||
api_test_runtime()->db()->query(
|
||||
'DELETE FROM selfserve_wash_sessions WHERE id = ' . $sessionId
|
||||
);
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
|
||||
api_client()
|
||||
->get(
|
||||
'/department/selfserve/vehicle/allowed?lane_id=' . $laneId
|
||||
. '®=' . urlencode($reg)
|
||||
. '&vehicle_type=' . $productId,
|
||||
$headers
|
||||
)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
api_client()
|
||||
->post('/modules/self-serve/lane/command', [
|
||||
'lane_id' => $laneId,
|
||||
'command' => 'START',
|
||||
'license_plate' => $reg,
|
||||
'defer_relay_side_effects' => true,
|
||||
], $headers)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
$openSession = api_test_runtime()->queryOne(
|
||||
'SELECT id, status, customer_number FROM selfserve_wash_sessions'
|
||||
. ' WHERE lane_id = ' . $laneId
|
||||
. ' AND reg = "' . api_test_runtime()->db()->real_escape_string($reg) . '"'
|
||||
. ' AND completed_at IS NULL'
|
||||
. ' AND deleted_at IS NULL'
|
||||
. ' ORDER BY id DESC LIMIT 1'
|
||||
);
|
||||
|
||||
expect($openSession)->not->toBeNull()
|
||||
->and((int)$openSession['customer_number'])->toBe((int)$scenario['customer']['customer_number'])
|
||||
->and($openSession['status'])->toBe('READY_FOR_MACHINE_START');
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
});
|
||||
|
||||
it('refreshes an active wash summary with vehicle type without a namespace error', 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,
|
||||
'session' => [
|
||||
'status' => 'MACHINE_RELAY_ENABLED',
|
||||
'machine_relay_enabled' => 1,
|
||||
'machine_relay_enabled_at' => date('Y-m-d H:i:s'),
|
||||
'completed_at' => null,
|
||||
],
|
||||
]);
|
||||
$headers = api_fixtures()->bearerHeaders(
|
||||
api_fixtures()->createAuthToken((int)$scenario['customer']['id'])
|
||||
);
|
||||
$sessionId = (int)$scenario['session']['id'];
|
||||
$productId = (int)$scenario['product']['id'];
|
||||
|
||||
$summaryResponse = api_client()
|
||||
->get(
|
||||
'/department/selfserve/washes/summary?session_id=' . $sessionId
|
||||
. '&vehicle_type=' . $productId,
|
||||
$headers
|
||||
)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($summaryResponse->data()['session']['id'] ?? null)->toBe($sessionId)
|
||||
->and($summaryResponse->data()['session']['status'] ?? null)->toBe('MACHINE_RELAY_ENABLED');
|
||||
});
|
||||
|
||||
it('does not create a replacement session when refreshing a completed summary with vehicle type', 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,
|
||||
'session' => [
|
||||
'status' => 'COMPLETED',
|
||||
'completed_at' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
]);
|
||||
$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'];
|
||||
$sessionId = (int)$scenario['session']['id'];
|
||||
|
||||
selfserve_customer_start_make_available($laneId);
|
||||
|
||||
$summaryResponse = api_client()
|
||||
->get(
|
||||
'/department/selfserve/washes/summary?lane_id=' . $laneId
|
||||
. '®=' . urlencode($reg)
|
||||
. '&vehicle_type=' . $productId,
|
||||
$headers
|
||||
)
|
||||
->assertStatus(200)
|
||||
->assertSuccess(true);
|
||||
|
||||
expect($summaryResponse->data()['session']['id'] ?? null)->toBe($sessionId)
|
||||
->and($summaryResponse->data()['session']['status'] ?? null)->toBe('COMPLETED');
|
||||
|
||||
$openSession = api_test_runtime()->queryOne(
|
||||
'SELECT id FROM selfserve_wash_sessions'
|
||||
. ' WHERE lane_id = ' . $laneId
|
||||
. ' AND reg = "' . api_test_runtime()->db()->real_escape_string($reg) . '"'
|
||||
. ' AND completed_at IS NULL'
|
||||
. ' AND deleted_at IS NULL'
|
||||
. ' LIMIT 1'
|
||||
);
|
||||
|
||||
expect($openSession)->toBeNull();
|
||||
});
|
||||
@@ -64,6 +64,7 @@ it('allows customer self-serve permission to execute START without department ac
|
||||
'lane_id' => (int)$scenario['lane']['id'],
|
||||
'command' => 'START',
|
||||
'license_plate' => (string)$scenario['vehicle']['reg'],
|
||||
'wash_type' => 'Manual',
|
||||
'defer_relay_side_effects' => true,
|
||||
], api_fixtures()->bearerHeaders($token));
|
||||
|
||||
@@ -170,6 +171,7 @@ it('still allows elevated operators with department access to execute lane comma
|
||||
'lane_id' => (int)$scenario['lane']['id'],
|
||||
'command' => 'START',
|
||||
'license_plate' => 'OP' . (int)$scenario['lane']['id'],
|
||||
'wash_type' => 'Manual',
|
||||
'defer_relay_side_effects' => true,
|
||||
], $session['headers']);
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use classes\email;
|
||||
use objects\users_o;
|
||||
|
||||
putenv('EMAIL_FAKE_MODE=1');
|
||||
|
||||
usesApiSuite();
|
||||
|
||||
beforeEach(function (): void {
|
||||
email::resetFakeDeliveries();
|
||||
});
|
||||
|
||||
it('persists superuser new customer notification preferences and includes them in session payloads', function (): void {
|
||||
api_test_covers('PUT /account/notifications', 'happy');
|
||||
|
||||
$session = api_fixtures()->createUserSession([
|
||||
'user_notifications_update',
|
||||
'superuser',
|
||||
]);
|
||||
|
||||
$response = api_client()->put('/account/notifications', [
|
||||
users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$key = api_test_runtime()->db()->real_escape_string(users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS);
|
||||
$storedPreference = api_test_runtime()->queryOne(
|
||||
"SELECT val FROM user_key_value_pairs WHERE user_id = " . (int)$session['user']['id'] . " AND var = '$key'"
|
||||
);
|
||||
|
||||
expect($storedPreference)
|
||||
->toBeArray()
|
||||
->toHaveKey('val', '1');
|
||||
|
||||
$sessionResponse = api_client()->get('/auth/session', $session['headers']);
|
||||
|
||||
$sessionResponse
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
expect($sessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
|
||||
->toBeTrue();
|
||||
});
|
||||
|
||||
it('invalidates cached session payloads after notification preferences change', function (): void {
|
||||
api_test_covers('PUT /account/notifications', 'cache');
|
||||
|
||||
$permissions = [
|
||||
'fetch_session',
|
||||
'user_notifications_update',
|
||||
'superuser',
|
||||
];
|
||||
$session = api_fixtures()->createUserSession($permissions);
|
||||
api_fixtures()->cacheAuthSessionForUser($session['user'], $session['token'], $permissions, [
|
||||
'notifications' => [
|
||||
users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => false,
|
||||
],
|
||||
]);
|
||||
|
||||
$cachedSessionResponse = api_client()->get('/auth/session', $session['headers']);
|
||||
|
||||
$cachedSessionResponse
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
expect($cachedSessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
|
||||
->toBeFalse();
|
||||
|
||||
$response = api_client()->put('/account/notifications', [
|
||||
users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$sessionResponse = api_client()->get('/auth/session', $session['headers']);
|
||||
|
||||
$sessionResponse
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
expect($sessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
|
||||
->toBeTrue();
|
||||
});
|
||||
|
||||
it('requires superuser permission before saving superuser new customer notification preferences', function (): void {
|
||||
api_test_covers('PUT /account/notifications', 'auth');
|
||||
|
||||
$session = api_fixtures()->createUserSession([
|
||||
'user_notifications_update',
|
||||
]);
|
||||
|
||||
$response = api_client()->put('/account/notifications', [
|
||||
users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(403)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMissingPermissions(['superuser']);
|
||||
});
|
||||
|
||||
it('sends new customer registration notifications only to opted-in superusers', function (): void {
|
||||
api_test_covers('POST /auth/register/cvr', 'notification');
|
||||
|
||||
api_fixtures()->setModuleConfig('Email', 'mailersend_enabled', 'true', 'bool');
|
||||
|
||||
$customer = api_fixtures()->createUser([
|
||||
'display_name' => 'Newly Registered Customer',
|
||||
]);
|
||||
$enabledSuperuser = api_fixtures()->createUser([
|
||||
'display_name' => 'Enabled Superuser',
|
||||
'email' => 'enabled-superuser@example.test',
|
||||
], ['superuser']);
|
||||
$regularUser = api_fixtures()->createUser([
|
||||
'display_name' => 'Enabled Regular User',
|
||||
'email' => 'enabled-regular@example.test',
|
||||
]);
|
||||
$disabledSuperuser = api_fixtures()->createUser([
|
||||
'display_name' => 'Disabled Superuser',
|
||||
'email' => 'disabled-superuser@example.test',
|
||||
], ['superuser']);
|
||||
|
||||
(new users_o())
|
||||
->select((int)$enabledSuperuser['id'])
|
||||
->setSuperuserNewCustomerEmailNotificationsEnabled(true);
|
||||
(new users_o())
|
||||
->select((int)$regularUser['id'])
|
||||
->setSuperuserNewCustomerEmailNotificationsEnabled(true);
|
||||
(new users_o())
|
||||
->select((int)$disabledSuperuser['id'])
|
||||
->setSuperuserNewCustomerEmailNotificationsEnabled(false);
|
||||
|
||||
(new email())->sendNewCustomerRegistrationNotifications((int)$customer['customer_number']);
|
||||
|
||||
expect(email::$fake_deliveries)
|
||||
->toHaveCount(1)
|
||||
->and(email::$fake_deliveries[0]['to'] ?? null)
|
||||
->toBe('enabled-superuser@example.test')
|
||||
->and(email::$fake_deliveries[0]['subject'] ?? null)
|
||||
->toBe('New customer registered on Truck Wash')
|
||||
->and(email::$fake_deliveries[0]['html'] ?? '')
|
||||
->toContain((string)$customer['customer_number']);
|
||||
});
|
||||
@@ -96,6 +96,10 @@ final class ApiClient
|
||||
|
||||
$decoded = json_decode($body, true);
|
||||
|
||||
if (getenv('EMAIL_FAKE_MODE') === '1' && class_exists(\classes\email::class)) {
|
||||
\classes\email::syncFakeDeliveries();
|
||||
}
|
||||
|
||||
return new ApiResponse($status, $responseHeaders, $decoded, (string)$body);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1141,6 +1141,7 @@ final class ApiFixtures
|
||||
'sms_notifications_enabled' => false,
|
||||
'email_notifications_enabled' => false,
|
||||
'wash_certificate_email' => null,
|
||||
'superuser_new_customer_email_notifications_enabled' => false,
|
||||
],
|
||||
'created_at' => $this->now(),
|
||||
'updated_at' => $this->now(),
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
it('wires the order booking completion confirmation resend endpoint', function (): void {
|
||||
$routeFile = app_path('routes/orderBookingRoute.php');
|
||||
|
||||
expect(is_file($routeFile))->toBeTrue();
|
||||
|
||||
$routeCode = preg_replace('/\s+/', ' ', (string)file_get_contents($routeFile));
|
||||
|
||||
expect($routeCode)
|
||||
->toContain("$" . "this->post('/order-bookings/completion-confirmation/resend', function () {")
|
||||
->toContain("self::requirePermission('complete_bookings');")
|
||||
->toContain('self::requireDepartmentAccess((int)$object->department->value());')
|
||||
->toContain('(new email())->sendWashCertificateEmailToCustomer($object);')
|
||||
->toContain("'Completion confirmation resent successfully.'");
|
||||
});
|
||||
@@ -38,6 +38,36 @@ namespace {
|
||||
expect($content)->toContain("switch (\$dynamic_image_id)");
|
||||
});
|
||||
|
||||
it('uses the selfserve dynamic image size config for route output and cache keys', function (): void {
|
||||
$route = file_get_contents(app_path('routes/departmentLanesRoute.php'));
|
||||
$config = file_get_contents(app_path('modules/selfserve/config/selfserve_dynamic_image_size_c.php'));
|
||||
$moduleConfig = file_get_contents(app_path('modules/selfserve/selfserve_c.php'));
|
||||
$imageTrait = file_get_contents(app_path('modules/dynamicimages/traits/dynamicimages_image_t.php'));
|
||||
|
||||
expect($route)->not->toBeFalse();
|
||||
expect($config)->not->toBeFalse();
|
||||
expect($moduleConfig)->not->toBeFalse();
|
||||
expect($imageTrait)->not->toBeFalse();
|
||||
expect($config)->toContain("self::SIZE_ORIGINAL");
|
||||
expect($config)->toContain("self::SIZE_RELEVANT");
|
||||
expect($config)->toContain("[self::SIZE_ORIGINAL, self::SIZE_RELEVANT]");
|
||||
expect($config)->toContain("'dynamic_image_size'");
|
||||
expect($moduleConfig)->toContain("selfserve_dynamic_image_size_c::class");
|
||||
expect($moduleConfig)->toContain('public selfserve_dynamic_image_size_c $dynamic_image_size;');
|
||||
expect($route)->toContain('$dynamic_image_size = self::getSelfServeDynamicImageSizeMode();');
|
||||
expect($route)->toContain("'dynamic_image_size' => \$dynamic_image_size");
|
||||
expect($route)->toContain('self::buildDynamicImageCacheKey');
|
||||
expect($route)->toContain("'thumb_position' => \$thumb_position");
|
||||
expect($route)->toContain("'buttons' => \$buttons");
|
||||
expect($route)->toContain("'current_step' => \$current_step");
|
||||
expect($route)->toContain("'only_current_step' => \$only_current_step");
|
||||
expect($route)->toContain("'vehicle_type' => \$vehicle_type");
|
||||
expect($route)->toContain("resizeToMaxWidth(self::RELEVANT_DYNAMIC_IMAGE_MAX_WIDTH)");
|
||||
expect($imageTrait)->toContain('function resizeToMaxWidth(int $maxWidth)');
|
||||
expect($imageTrait)->toContain('function exportBinary(?string $format = null, int $quality = 90): string');
|
||||
expect($route)->toContain("\$imageData = \$image->exportBinary('png');");
|
||||
});
|
||||
|
||||
it('accepts ordered dynamic image button tokens including program picker reset start and zero', function (): void {
|
||||
expect(department_selfserve_tasks_o::normalizeButtonsInput('["program_picker","reset",0,2,"start",5]'))->toBe([
|
||||
'program_picker',
|
||||
|
||||
@@ -13,4 +13,8 @@ it('registers dynamic image pre-render cron task and related helpers', function
|
||||
expect($content)->toContain('normalizeButtonsInput');
|
||||
expect($content)->toContain('dynamic_image:');
|
||||
expect($content)->toContain('machine_1');
|
||||
expect($content)->toContain('getSelfServeDynamicImageSizeModeForCron');
|
||||
expect($content)->toContain("'dynamic_image_size' => getSelfServeDynamicImageSizeModeForCron()");
|
||||
expect($content)->toContain('resizeToMaxWidth(DYNAMIC_IMAGE_RELEVANT_MAX_WIDTH)');
|
||||
expect($content)->toContain("\$image->exportBinary('png')");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
app_require('classes/email.php');
|
||||
|
||||
use classes\email;
|
||||
|
||||
it('syncs fake email deliveries written by another process', function (): void {
|
||||
$previousFakeMode = getenv('EMAIL_FAKE_MODE');
|
||||
$previousFakePath = getenv('EMAIL_FAKE_DELIVERIES_PATH');
|
||||
$path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'truckwash-fake-email-sync-' . bin2hex(random_bytes(4)) . '.jsonl';
|
||||
|
||||
putenv('EMAIL_FAKE_MODE=1');
|
||||
putenv('EMAIL_FAKE_DELIVERIES_PATH=' . $path);
|
||||
email::resetFakeDeliveries();
|
||||
|
||||
try {
|
||||
file_put_contents($path, json_encode([
|
||||
'to' => 'customer@example.test',
|
||||
'recipient_name' => 'Customer',
|
||||
'subject' => 'Subject',
|
||||
'message' => '',
|
||||
'html' => '<p>Body</p>',
|
||||
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL);
|
||||
|
||||
email::syncFakeDeliveries();
|
||||
|
||||
expect(email::$fake_deliveries)
|
||||
->toHaveCount(1)
|
||||
->and(email::$fake_deliveries[0]['to'] ?? null)
|
||||
->toBe('customer@example.test')
|
||||
->and(email::$fake_deliveries[0]['subject'] ?? null)
|
||||
->toBe('Subject');
|
||||
} finally {
|
||||
email::resetFakeDeliveries();
|
||||
if (is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
if ($previousFakeMode === false) {
|
||||
putenv('EMAIL_FAKE_MODE');
|
||||
} else {
|
||||
putenv('EMAIL_FAKE_MODE=' . $previousFakeMode);
|
||||
}
|
||||
if ($previousFakePath === false) {
|
||||
putenv('EMAIL_FAKE_DELIVERIES_PATH');
|
||||
} else {
|
||||
putenv('EMAIL_FAKE_DELIVERIES_PATH=' . $previousFakePath);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -34,6 +34,14 @@ it('builds credential-safe normal CORS response headers for allowed origins', fu
|
||||
expect($headers['Vary'])->toBe('Origin');
|
||||
});
|
||||
|
||||
it('allows the fallback Vite localhost dev origin used after port 5173 is busy', function (): void {
|
||||
$preflight = cors_policy::preflightResponse('http://localhost:5174', 'https://truckwash.io');
|
||||
|
||||
expect($preflight['allowed'])->toBeTrue();
|
||||
expect($preflight['status'])->toBe(200);
|
||||
expect($preflight['headers']['Access-Control-Allow-Origin'])->toBe('http://localhost:5174');
|
||||
});
|
||||
|
||||
it('builds preflight CORS response headers for api-v2 release URLs', function (): void {
|
||||
$preflight = cors_policy::preflightResponse(
|
||||
'https://api-v2.truckwash.io/master/api',
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
it('wires collected invoice customer moves through the dedicated route and permission', function (): void {
|
||||
$routeContent = file_get_contents(app_path('routes/orderInvoicesRoute.php'));
|
||||
$objectContent = file_get_contents(app_path('objects/collected_order_invoices_o.php'));
|
||||
|
||||
expect($routeContent)->not->toBeFalse()
|
||||
->and($routeContent)->toContain("\$this->post('/collected-invoices/move-to-customer'")
|
||||
->and($routeContent)->toContain("self::requirePermission('move_collected_invoice_customer')")
|
||||
->and($routeContent)->toContain('$collected_order_invoices->moveToCustomer')
|
||||
->and($routeContent)->toContain("\$response->add_meta('move', \$move_result)")
|
||||
->and($objectContent)->not->toBeFalse()
|
||||
->and($objectContent)->toContain('public function moveToCustomer(int $target_customer_number): array')
|
||||
->and($objectContent)->toContain('Invoice collections with an external or booked invoice cannot be moved')
|
||||
->and($objectContent)->toContain('SELECT id FROM orders WHERE invoice_collection_id = {$invoice_collection_id}')
|
||||
->and($objectContent)->toContain('$order->customer_id->set($target_customer_number)')
|
||||
->and($objectContent)->toContain('$this->customer_number->set($target_customer_number)')
|
||||
->and($objectContent)->toContain('$db->conn()->begin_transaction()');
|
||||
});
|
||||
@@ -113,6 +113,7 @@ it('normalizes period pagination options and clamps invalid page and limit value
|
||||
'search' => ' Nordic ',
|
||||
'includeRequiresAction' => '0',
|
||||
'includeBooked' => 'false',
|
||||
'flagTab' => 'invalid-tab',
|
||||
]]);
|
||||
|
||||
expect($options)->toBe([
|
||||
@@ -141,10 +142,12 @@ it('normalizes period pagination options and clamps invalid page and limit value
|
||||
'periodView' => 'invoice_per_order',
|
||||
'page' => '3',
|
||||
'limit' => '0',
|
||||
'flagTab' => 'yellow',
|
||||
]]))->toMatchArray([
|
||||
'periodView' => 'invoice_per_order',
|
||||
'page' => 3,
|
||||
'limit' => 100,
|
||||
'flagTab' => 'yellow',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -387,3 +390,79 @@ it('applies requires-action and booked visibility filters before counting and sl
|
||||
expect($result['period']['type_counts']['all']['total'])->toBe(1);
|
||||
expect($result['period']['types']['all'][0]['customer_number'])->toBe(3003);
|
||||
});
|
||||
|
||||
it('filters period flag tabs using active customer-scoped flag counts', function (): void {
|
||||
$period = [
|
||||
'dateFrom' => '2026-04-01 00:00:00',
|
||||
'dateTo' => '2026-04-30 23:59:59',
|
||||
'types' => [
|
||||
'all' => [
|
||||
invoicing_period_customer_card(4001, 'Yellow Order Flag', [
|
||||
invoicing_period_transaction(['customer_number' => 4001, 'id' => 41]),
|
||||
], false, [
|
||||
'flags' => [
|
||||
[
|
||||
'source' => 'automatic',
|
||||
'status' => 'active',
|
||||
'target_type' => 'order',
|
||||
'order_id' => 41,
|
||||
],
|
||||
],
|
||||
]),
|
||||
invoicing_period_customer_card(4002, 'Ignored Manual Flag', [
|
||||
invoicing_period_transaction(['customer_number' => 4002, 'id' => 42]),
|
||||
], false, [
|
||||
'flags' => [
|
||||
[
|
||||
'source' => 'manual',
|
||||
'status' => 'ignored',
|
||||
'target_type' => 'customer',
|
||||
],
|
||||
],
|
||||
]),
|
||||
invoicing_period_customer_card(4003, 'Red Customer Flag', [
|
||||
invoicing_period_transaction(['customer_number' => 4003, 'id' => 43]),
|
||||
], false, [
|
||||
'flags' => [
|
||||
[
|
||||
'source' => 'manual',
|
||||
'status' => 'active',
|
||||
'target_type' => 'customer',
|
||||
],
|
||||
],
|
||||
]),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$yellowResult = invoicing_period_pagination_invoke('applyPeriodPagination', [$period, [
|
||||
'periodView' => 'all',
|
||||
'page' => 1,
|
||||
'limit' => 25,
|
||||
'search' => '',
|
||||
'flagTab' => 'yellow',
|
||||
'includeRequiresAction' => true,
|
||||
'includeBooked' => true,
|
||||
]]);
|
||||
|
||||
expect($yellowResult['pagination']['total'])->toBe(1);
|
||||
expect(array_column($yellowResult['period']['types']['all'], 'customer_number'))->toBe([4001]);
|
||||
|
||||
$noneResult = invoicing_period_pagination_invoke('applyPeriodPagination', [$period, [
|
||||
'periodView' => 'all',
|
||||
'page' => 1,
|
||||
'limit' => 25,
|
||||
'search' => '',
|
||||
'flagTab' => 'none',
|
||||
'includeRequiresAction' => true,
|
||||
'includeBooked' => true,
|
||||
]]);
|
||||
|
||||
expect($noneResult['pagination']['total'])->toBe(1);
|
||||
expect(array_column($noneResult['period']['types']['all'], 'customer_number'))->toBe([4002]);
|
||||
expect($noneResult['period']['type_counts']['all'])->toMatchArray([
|
||||
'manual_flags' => 1,
|
||||
'automatic_flags' => 1,
|
||||
'total' => 3,
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -2,9 +2,33 @@
|
||||
|
||||
app_require('classes/release_manager.php');
|
||||
app_require('classes/release_manager_schema_bootstrap.php');
|
||||
app_require('classes/coolify_api_client.php');
|
||||
|
||||
use classes\coolify_api_client;
|
||||
use classes\release_manager;
|
||||
|
||||
class ReleaseManagerCoolifyEnvFake extends coolify_api_client
|
||||
{
|
||||
public array $envRows;
|
||||
public array $deleted = [];
|
||||
|
||||
public function __construct(array $envRows)
|
||||
{
|
||||
$this->envRows = $envRows;
|
||||
}
|
||||
|
||||
public function listApplicationEnvs(string $uuid): array
|
||||
{
|
||||
return $this->envRows;
|
||||
}
|
||||
|
||||
public function deleteApplicationEnv(string $uuid, string $envUuid): array
|
||||
{
|
||||
$this->deleted[] = [$uuid, $envUuid];
|
||||
return ['message' => 'deleted'];
|
||||
}
|
||||
}
|
||||
|
||||
it('redacts sensitive release timeline payload fields recursively', function (): void {
|
||||
$payload = [
|
||||
'Authorization' => 'Bearer secret-token',
|
||||
@@ -140,6 +164,26 @@ it('requires non-empty release gate checks before auto-sync can proceed', functi
|
||||
]);
|
||||
});
|
||||
|
||||
it('extracts API ping commit metadata for release gate verification', function (): void {
|
||||
$manager = new release_manager();
|
||||
$method = new ReflectionMethod(release_manager::class, 'releaseGateApiPayloadCommitSha');
|
||||
$method->setAccessible(true);
|
||||
|
||||
expect($method->invoke($manager, [
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'message' => 'pong',
|
||||
'api_commit_sha' => '327a77edf48069c14cb592f298924b0ea1aaf208',
|
||||
],
|
||||
]))->toBe('327a77edf48069c14cb592f298924b0ea1aaf208')
|
||||
->and($method->invoke($manager, [
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'backend_version' => '75c19bcce44fe3f0657d84b45dbc1c89f29332b4',
|
||||
],
|
||||
]))->toBe('75c19bcce44fe3f0657d84b45dbc1c89f29332b4');
|
||||
});
|
||||
|
||||
it('normalizes GitHub repository identifiers for private repository access checks', function (): void {
|
||||
expect(release_manager::normalizeGithubRepositoryName('truckwash/backend-php'))->toBe('truckwash/backend-php');
|
||||
expect(release_manager::normalizeGithubRepositoryName('https://github.com/truckwash/front-end-vue.git'))->toBe('truckwash/front-end-vue');
|
||||
@@ -588,7 +632,7 @@ it('resolves backend commit sha from API runtime environment in priority order',
|
||||
}
|
||||
});
|
||||
|
||||
it('injects selected API commit into Coolify runtime env unless explicitly set', function (): void {
|
||||
it('forces selected API commit into generated Coolify runtime env keys', function (): void {
|
||||
$manager = new release_manager();
|
||||
$runtimeEnv = new ReflectionMethod(release_manager::class, 'releaseCoolifyRuntimeEnv');
|
||||
$runtimeEnv->setAccessible(true);
|
||||
@@ -601,12 +645,52 @@ it('injects selected API commit into Coolify runtime env unless explicitly set',
|
||||
'commit_sha' => $selectedCommit,
|
||||
], [
|
||||
'coolify_env' => [
|
||||
'API_COMMIT_SHA' => $explicitCommit,
|
||||
'COMMIT_SHA' => $explicitCommit,
|
||||
'GITHUB_SHA' => $explicitCommit,
|
||||
'RELEASE_COMMIT_SHA' => $explicitCommit,
|
||||
],
|
||||
]);
|
||||
|
||||
expect($env['API_COMMIT_SHA'])->toBe($selectedCommit);
|
||||
expect($env['COMMIT_SHA'])->toBe($explicitCommit);
|
||||
expect($env['COMMIT_SHA'])->toBe($selectedCommit);
|
||||
expect($env['GITHUB_SHA'])->toBe($selectedCommit);
|
||||
expect($env['RELEASE_COMMIT_SHA'])->toBe($selectedCommit);
|
||||
});
|
||||
|
||||
it('uses the selected deployment commit before stale Coolify context commits', function (): void {
|
||||
$manager = new release_manager();
|
||||
$gitCommitSha = new ReflectionMethod(release_manager::class, 'releaseCoolifyGitCommitSha');
|
||||
$gitCommitSha->setAccessible(true);
|
||||
|
||||
$selectedCommit = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||
$staleCommit = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
|
||||
|
||||
expect($gitCommitSha->invoke($manager, [
|
||||
'commit_sha' => $selectedCommit,
|
||||
], [
|
||||
'coolify_git_commit_sha' => $staleCommit,
|
||||
'git_commit_sha' => $staleCommit,
|
||||
]))->toBe($selectedCommit);
|
||||
});
|
||||
|
||||
it('injects selected frontend commit into Coolify runtime env for manifest builds', function (): void {
|
||||
$manager = new release_manager();
|
||||
$runtimeEnv = new ReflectionMethod(release_manager::class, 'releaseCoolifyRuntimeEnv');
|
||||
$runtimeEnv->setAccessible(true);
|
||||
|
||||
$selectedCommit = '3333333333333333333333333333333333333333';
|
||||
|
||||
$env = $runtimeEnv->invoke($manager, [
|
||||
'app' => 'frontend',
|
||||
'commit_sha' => $selectedCommit,
|
||||
], []);
|
||||
|
||||
expect($env['SOURCE_COMMIT'])->toBe($selectedCommit);
|
||||
expect($env['RELEASE_COMMIT_SHA'])->toBe($selectedCommit);
|
||||
expect($env['COMMIT_SHA'])->toBe($selectedCommit);
|
||||
expect($env['GITHUB_SHA'])->toBe($selectedCommit);
|
||||
expect($env['VITE_COMMIT_HASH'])->toBe($selectedCommit);
|
||||
});
|
||||
|
||||
it('keeps beta API runtime environment on production database target', function (): void {
|
||||
@@ -971,6 +1055,7 @@ it('defines release manager schema, routes, permissions, and system-status integ
|
||||
expect($manager)->toContain('createService');
|
||||
expect($manager)->toContain('updateService');
|
||||
expect(file_get_contents(app_path('classes/coolify_api_client.php')))->toContain('updateApplicationEnvsBulk');
|
||||
expect(file_get_contents(app_path('classes/coolify_api_client.php')))->toContain('stopApplication');
|
||||
expect($manager)->toContain('channel_presets');
|
||||
expect($manager)->toContain('target_presets');
|
||||
|
||||
@@ -1361,6 +1446,57 @@ it('resolves release deployment endpoints from manual overrides, URLs, health ch
|
||||
]))->toBe('https://gateway.example.test/beta/frontend');
|
||||
});
|
||||
|
||||
it('collects previous Coolify application UUIDs for stale route cleanup', function (): void {
|
||||
$manager = new release_manager();
|
||||
$previousApplications = new ReflectionMethod(release_manager::class, 'releaseCoolifyPreviousApplicationUuids');
|
||||
$previousApplications->setAccessible(true);
|
||||
|
||||
expect($previousApplications->invoke($manager, [
|
||||
'coolify_previous_artifact_app_uuid' => 'old-artifact-app',
|
||||
'coolify_previous_application_uuid' => 'old-application',
|
||||
'coolify_previous_application_uuids' => [
|
||||
'old-application',
|
||||
'active-application',
|
||||
'other-old-application',
|
||||
'',
|
||||
],
|
||||
], 'active-application'))->toBe([
|
||||
'old-application',
|
||||
'old-artifact-app',
|
||||
'other-old-application',
|
||||
]);
|
||||
});
|
||||
|
||||
it('deletes only generated API commit env rows before Coolify application env updates', function (): void {
|
||||
$manager = new release_manager();
|
||||
$deleteCommitEnvs = new ReflectionMethod(release_manager::class, 'deleteCoolifyGeneratedCommitEnvs');
|
||||
$deleteCommitEnvs->setAccessible(true);
|
||||
$client = new ReleaseManagerCoolifyEnvFake([
|
||||
['uuid' => 'api-commit', 'key' => 'API_COMMIT_SHA'],
|
||||
['uuid' => 'commit', 'key' => 'COMMIT_SHA'],
|
||||
['uuid' => 'github', 'key' => 'GITHUB_SHA'],
|
||||
['uuid' => 'release', 'key' => 'RELEASE_COMMIT_SHA'],
|
||||
['uuid' => 'frontend-source', 'key' => 'SOURCE_COMMIT'],
|
||||
['uuid' => 'secret', 'key' => 'CONFIG_DB_PASSWORD'],
|
||||
]);
|
||||
|
||||
$deleteCommitEnvs->invoke($manager, $client, 'application-uuid', ['app' => 'api'], []);
|
||||
|
||||
expect($client->deleted)->toBe([
|
||||
['application-uuid', 'api-commit'],
|
||||
['application-uuid', 'commit'],
|
||||
['application-uuid', 'github'],
|
||||
['application-uuid', 'release'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('waits for an in-flight automatic sync instead of passing the retry immediately', function (): void {
|
||||
$manager = file_get_contents(app_path('classes/release_manager.php'));
|
||||
|
||||
expect($manager)->toContain('return $this->waitForReleaseAutoSyncEventResult($eventId, $channelId, $app, $commitSha, $gateInput);')
|
||||
->and($manager)->toContain('Automatic container update is already being processed for event %d but did not finish');
|
||||
});
|
||||
|
||||
it('redacts GitHub access metadata from public release versions', function (): void {
|
||||
$manager = new release_manager();
|
||||
$publicVersion = new ReflectionMethod(release_manager::class, 'publicVersion');
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
app_require('traits/module_config_variable_t.php');
|
||||
|
||||
use traits\module_config_variable;
|
||||
|
||||
function selfserve_module_config_database_config(): array
|
||||
{
|
||||
$subject = new class {
|
||||
use module_config_variable;
|
||||
};
|
||||
|
||||
$method = new ReflectionMethod($subject::class, 'readDatabaseConfigFromEnvironment');
|
||||
$method->setAccessible(true);
|
||||
|
||||
return $method->invoke(null);
|
||||
}
|
||||
|
||||
function selfserve_module_config_with_env(array $values, callable $callback): mixed
|
||||
{
|
||||
$keys = [
|
||||
'CONFIG_DB_TARGET',
|
||||
'CONFIG_DB_HOST',
|
||||
'CONFIG_DB_USER',
|
||||
'CONFIG_DB_PASSWORD',
|
||||
'CONFIG_DB_DATABASE',
|
||||
'CONFIG_DB_PORT',
|
||||
'CONFIG_DB_SSL_MODE',
|
||||
'CONFIG_DB_DEBUG_HOST',
|
||||
'CONFIG_DB_DEBUG_USER',
|
||||
'CONFIG_DB_DEBUG_PASSWORD',
|
||||
'CONFIG_DB_DEBUG_DATABASE',
|
||||
'CONFIG_DB_DEBUG_PORT',
|
||||
'CONFIG_DB_DEBUG_SSL_MODE',
|
||||
];
|
||||
$previous = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$previous[$key] = [
|
||||
'env' => getenv($key),
|
||||
'has_env' => array_key_exists($key, $_ENV),
|
||||
'super_env' => $_ENV[$key] ?? null,
|
||||
'has_server' => array_key_exists($key, $_SERVER),
|
||||
'server' => $_SERVER[$key] ?? null,
|
||||
];
|
||||
putenv($key);
|
||||
unset($_ENV[$key], $_SERVER[$key]);
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($values as $key => $value) {
|
||||
putenv($key . '=' . (string)$value);
|
||||
$_ENV[$key] = (string)$value;
|
||||
$_SERVER[$key] = (string)$value;
|
||||
}
|
||||
|
||||
return $callback();
|
||||
} finally {
|
||||
foreach ($previous as $key => $state) {
|
||||
$state['env'] === false
|
||||
? putenv($key)
|
||||
: putenv($key . '=' . $state['env']);
|
||||
|
||||
if ($state['has_env']) {
|
||||
$_ENV[$key] = $state['super_env'];
|
||||
} else {
|
||||
unset($_ENV[$key]);
|
||||
}
|
||||
|
||||
if ($state['has_server']) {
|
||||
$_SERVER[$key] = $state['server'];
|
||||
} else {
|
||||
unset($_SERVER[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('reads debug database configuration when the debug target is selected', function (): void {
|
||||
$config = selfserve_module_config_with_env([
|
||||
'CONFIG_DB_TARGET' => 'debug',
|
||||
'CONFIG_DB_HOST' => '',
|
||||
'CONFIG_DB_USER' => '',
|
||||
'CONFIG_DB_PASSWORD' => '',
|
||||
'CONFIG_DB_DATABASE' => '',
|
||||
'CONFIG_DB_PORT' => '',
|
||||
'CONFIG_DB_SSL_MODE' => '',
|
||||
'CONFIG_DB_DEBUG_HOST' => 'mysql-debug',
|
||||
'CONFIG_DB_DEBUG_USER' => 'root',
|
||||
'CONFIG_DB_DEBUG_PASSWORD' => 'debug_root_password',
|
||||
'CONFIG_DB_DEBUG_DATABASE' => 'nnks_db_debug',
|
||||
'CONFIG_DB_DEBUG_PORT' => '3306',
|
||||
'CONFIG_DB_DEBUG_SSL_MODE' => 'DISABLED',
|
||||
], static fn(): array => selfserve_module_config_database_config());
|
||||
|
||||
expect($config)->toMatchArray([
|
||||
'host' => 'mysql-debug',
|
||||
'user' => 'root',
|
||||
'password' => 'debug_root_password',
|
||||
'database' => 'nnks_db_debug',
|
||||
'port' => 3306,
|
||||
'ssl_mode' => 'DISABLED',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps live database configuration as the default target', function (): void {
|
||||
$config = selfserve_module_config_with_env([
|
||||
'CONFIG_DB_HOST' => 'live-db',
|
||||
'CONFIG_DB_USER' => 'live-user',
|
||||
'CONFIG_DB_PASSWORD' => 'live-password',
|
||||
'CONFIG_DB_DATABASE' => 'live-database',
|
||||
'CONFIG_DB_PORT' => '3307',
|
||||
'CONFIG_DB_SSL_MODE' => 'REQUIRED',
|
||||
'CONFIG_DB_DEBUG_HOST' => 'mysql-debug',
|
||||
'CONFIG_DB_DEBUG_USER' => 'root',
|
||||
'CONFIG_DB_DEBUG_PASSWORD' => 'debug_root_password',
|
||||
'CONFIG_DB_DEBUG_DATABASE' => 'nnks_db_debug',
|
||||
'CONFIG_DB_DEBUG_PORT' => '3306',
|
||||
'CONFIG_DB_DEBUG_SSL_MODE' => 'DISABLED',
|
||||
], static fn(): array => selfserve_module_config_database_config());
|
||||
|
||||
expect($config)->toMatchArray([
|
||||
'host' => 'live-db',
|
||||
'user' => 'live-user',
|
||||
'password' => 'live-password',
|
||||
'database' => 'live-database',
|
||||
'port' => 3307,
|
||||
'ssl_mode' => 'REQUIRED',
|
||||
]);
|
||||
});
|
||||
@@ -43,16 +43,17 @@ function selfserve_eligibility_method_block(string $route, string $signature): s
|
||||
it('authorizes customer eligibility preview lanes before returning task attachments', function (): void {
|
||||
$route = selfserve_eligibility_route_source();
|
||||
$allowedBlock = selfserve_eligibility_route_block($route, 'get', '/department/selfserve/vehicle/allowed');
|
||||
$assertBlock = selfserve_eligibility_method_block($route, 'private function assertLaneAccess(object $user, int $laneId): department_lanes_o');
|
||||
$assertBlock = selfserve_eligibility_method_block($route, 'private function assertLaneAccess(');
|
||||
|
||||
expect($allowedBlock)->toContain('$lane = $this->assertLaneAccess($user, $lane_id);')
|
||||
expect($allowedBlock)->toContain('$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);')
|
||||
->and($allowedBlock)->toContain('previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id)')
|
||||
->and(strpos($allowedBlock, '$lane = $this->assertLaneAccess($user, $lane_id);'))
|
||||
->and(strpos($allowedBlock, '$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);'))
|
||||
->toBeLessThan(strpos($allowedBlock, 'previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id)'));
|
||||
|
||||
expect($assertBlock)->toContain('$authorized_department_ids = array_values(array_filter(')
|
||||
->and($assertBlock)->toContain('array_map(\'intval\', (array)$user->getGroup()->getDepartments())')
|
||||
->and($assertBlock)->toContain('if (!in_array($lane_department_id, $authorized_department_ids, true))')
|
||||
expect($assertBlock)->toContain('bool $hasGlobalPermission = true')
|
||||
->and($assertBlock)->toContain('bool $hasOwnPermission = false')
|
||||
->and($assertBlock)->toContain('if ($hasGlobalPermission && $this->userHasLaneDepartmentAccess($user, $lane))')
|
||||
->and($assertBlock)->toContain('if ($hasOwnPermission && $this->isCustomerSelfServeLaneEnabled($lane))')
|
||||
->and($assertBlock)->toContain('$this->forbidDepartmentAccess($lane_department_id);')
|
||||
->and($assertBlock)->not->toContain('if ($hasGlobalPermission)');
|
||||
->and($assertBlock)->toContain('$response->forbidden([$elevatedPermission]);');
|
||||
});
|
||||
|
||||
@@ -21,7 +21,10 @@ class SelfserveLaneStartEntranceTimeoutHarness
|
||||
public ?\Throwable $reportedTimeout = null;
|
||||
public ?selfserve_lane_state $laneState = null;
|
||||
public int $cleanerRelayCalls = 0;
|
||||
public int $programPickerRelayCalls = 0;
|
||||
public int $machineRelayCalls = 0;
|
||||
/** @var array<int,string> */
|
||||
public array $relayEvents = [];
|
||||
|
||||
public function open(selfserve_lane_port $port, ?int $toggle_after_seconds = null): bool
|
||||
{
|
||||
@@ -47,11 +50,28 @@ class SelfserveLaneStartEntranceTimeoutHarness
|
||||
protected function turnOnCleanerRelayForWashStart(): void
|
||||
{
|
||||
$this->cleanerRelayCalls++;
|
||||
$this->relayEvents[] = 'cleaner:on';
|
||||
}
|
||||
|
||||
protected function setMachineRelayStatusForWashStart(): void
|
||||
protected function setProgramPickerRelayStatusFromSelectedServiceForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
unset($arguments);
|
||||
$this->programPickerRelayCalls++;
|
||||
$this->relayEvents[] = 'program_picker:selected_service';
|
||||
}
|
||||
|
||||
protected function setProgramPickerRelayStatusForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
unset($arguments);
|
||||
$this->programPickerRelayCalls++;
|
||||
$this->relayEvents[] = 'program_picker:eligibility_sync';
|
||||
}
|
||||
|
||||
protected function setMachineRelayStatusForWashStart(?selfserve_lane_command_arguments $arguments = null): void
|
||||
{
|
||||
unset($arguments);
|
||||
$this->machineRelayCalls++;
|
||||
$this->relayEvents[] = 'machine:sync';
|
||||
}
|
||||
|
||||
public function runEntranceOpenForStart(): void
|
||||
@@ -90,28 +110,54 @@ it('parses deferred relay side effects on start command arguments', function ():
|
||||
$arguments = (new selfserve_lane_command_arguments())->setParameters([
|
||||
'license_plate' => 'ab12345',
|
||||
'customer_number' => 12345679,
|
||||
'wash_type' => 'Manual',
|
||||
'defer_relay_side_effects' => true,
|
||||
]);
|
||||
|
||||
expect($arguments->license_plate)->toBe('AB12345');
|
||||
expect($arguments->customer_number)->toBe(12345679);
|
||||
expect($arguments->wash_mode)->toBe('manual');
|
||||
expect($arguments->defer_relay_side_effects)->toBeTrue();
|
||||
});
|
||||
|
||||
it('skips cleaner and machine relay side effects when start asks to defer them', function (): void {
|
||||
it('parses wash mode aliases on start command arguments', function (): void {
|
||||
$arguments = (new selfserve_lane_command_arguments())->setParameters([
|
||||
'wash_mode' => 'machine',
|
||||
]);
|
||||
|
||||
expect($arguments->wash_mode)->toBe('machine');
|
||||
});
|
||||
|
||||
it('rejects invalid wash types on start command arguments', function (): void {
|
||||
expect(fn() => (new selfserve_lane_command_arguments())->setParameters([
|
||||
'wash_type' => 'automatic',
|
||||
]))->toThrow(\InvalidArgumentException::class, 'Invalid wash type: automatic');
|
||||
});
|
||||
|
||||
it('only syncs program picker from selected service when start asks to defer machine side effects', function (): void {
|
||||
$lane = new SelfserveLaneStartEntranceTimeoutHarness();
|
||||
|
||||
$lane->runStartRelaySideEffects(true);
|
||||
|
||||
expect($lane->cleanerRelayCalls)->toBe(0);
|
||||
expect($lane->programPickerRelayCalls)->toBe(1);
|
||||
expect($lane->machineRelayCalls)->toBe(0);
|
||||
expect($lane->relayEvents)->toBe([
|
||||
'program_picker:selected_service',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps cleaner and machine relay side effects for normal start commands', function (): void {
|
||||
it('keeps cleaner, program picker and machine relay side effects in order for normal start commands', function (): void {
|
||||
$lane = new SelfserveLaneStartEntranceTimeoutHarness();
|
||||
|
||||
$lane->runStartRelaySideEffects(false);
|
||||
|
||||
expect($lane->cleanerRelayCalls)->toBe(1);
|
||||
expect($lane->programPickerRelayCalls)->toBe(1);
|
||||
expect($lane->machineRelayCalls)->toBe(1);
|
||||
expect($lane->relayEvents)->toBe([
|
||||
'cleaner:on',
|
||||
'program_picker:eligibility_sync',
|
||||
'machine:sync',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -63,6 +63,8 @@ class SelfserveLaneStopFlowHarness
|
||||
public array $openedPorts = [];
|
||||
/** @var selfserve_lane_relay[] */
|
||||
public array $turnedOffRelays = [];
|
||||
/** @var array<int,string> */
|
||||
public array $events = [];
|
||||
|
||||
private selfserve_lane_status $laneStatus;
|
||||
private selfserve_lane_mode $laneMode;
|
||||
@@ -182,6 +184,7 @@ class SelfserveLaneStopFlowHarness
|
||||
public function open(selfserve_lane_port $port): bool
|
||||
{
|
||||
$this->openedPorts[] = $port;
|
||||
$this->events[] = 'open:' . $port->name;
|
||||
if ($this->openThrowable !== null) {
|
||||
throw $this->openThrowable;
|
||||
}
|
||||
@@ -192,6 +195,7 @@ class SelfserveLaneStopFlowHarness
|
||||
public function turnOffRelay(selfserve_lane_relay $relay): bool
|
||||
{
|
||||
$this->turnedOffRelays[] = $relay;
|
||||
$this->events[] = 'relay:' . $relay->name . ':off';
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -199,6 +203,7 @@ class SelfserveLaneStopFlowHarness
|
||||
{
|
||||
if ($on === false) {
|
||||
$this->turnedOffRelays[] = $relay;
|
||||
$this->events[] = 'relay:' . $relay->name . ':off';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -229,7 +234,7 @@ class SelfserveLaneStopFlowHarness
|
||||
}
|
||||
}
|
||||
|
||||
it('adds vehicle type product on STOP when the physical machine ON signal was recorded, then turns off cleaner and machine relays', function (): void {
|
||||
it('adds vehicle type product on STOP when the physical machine ON signal was recorded, after turning relays off before exit', function (): void {
|
||||
$lane = new SelfserveLaneStopFlowHarness(machineStartTriggered: true);
|
||||
$args = (new selfserve_lane_command_arguments())->setCustomerNumber(1234);
|
||||
|
||||
@@ -243,8 +248,15 @@ it('adds vehicle type product on STOP when the physical machine ON signal was re
|
||||
expect($lane->openedPorts)->toBe([selfserve_lane_port::EXIT]);
|
||||
expect($lane->turnedOffRelays)->toBe([
|
||||
selfserve_lane_relay::MACHINE_CLEANER,
|
||||
selfserve_lane_relay::MACHINE_PROGRAM_PICKER,
|
||||
selfserve_lane_relay::MACHINE,
|
||||
]);
|
||||
expect($lane->events)->toBe([
|
||||
'relay:MACHINE_CLEANER:off',
|
||||
'relay:MACHINE_PROGRAM_PICKER:off',
|
||||
'relay:MACHINE:off',
|
||||
'open:EXIT',
|
||||
]);
|
||||
expect($lane->getLaneStatus())->toBe(selfserve_lane_status::AVAILABLE);
|
||||
});
|
||||
|
||||
@@ -266,8 +278,14 @@ it('skips vehicle type product add when no physical machine ON signal was record
|
||||
expect($lane->lastVehicleTypeProductDecision)->toBeFalse();
|
||||
expect($lane->programSelectorStatusReads)->toBe(0);
|
||||
expect($lane->turnedOffRelays)->toBe([
|
||||
selfserve_lane_relay::MACHINE_PROGRAM_PICKER,
|
||||
selfserve_lane_relay::MACHINE,
|
||||
]);
|
||||
expect($lane->events)->toBe([
|
||||
'relay:MACHINE_PROGRAM_PICKER:off',
|
||||
'relay:MACHINE:off',
|
||||
'open:EXIT',
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not use selector relay online status as machine-wash billing evidence', function (): void {
|
||||
@@ -301,8 +319,15 @@ it('continues STOP when exit relay dispatch times out ambiguously', function ():
|
||||
expect($lane->vehicleTypeProductAddCalls)->toBe(1);
|
||||
expect($lane->turnedOffRelays)->toBe([
|
||||
selfserve_lane_relay::MACHINE_CLEANER,
|
||||
selfserve_lane_relay::MACHINE_PROGRAM_PICKER,
|
||||
selfserve_lane_relay::MACHINE,
|
||||
]);
|
||||
expect($lane->events)->toBe([
|
||||
'relay:MACHINE_CLEANER:off',
|
||||
'relay:MACHINE_PROGRAM_PICKER:off',
|
||||
'relay:MACHINE:off',
|
||||
'open:EXIT',
|
||||
]);
|
||||
expect($lane->getLaneStatus())->toBe(selfserve_lane_status::AVAILABLE);
|
||||
});
|
||||
|
||||
|
||||
@@ -138,6 +138,8 @@ it('documents property gate lane commands and sanitized gate failure responses',
|
||||
|
||||
expect($commandPathBlock)->toContain('OPEN_PROPERTY_ACCESS_GATE');
|
||||
expect($commandPathBlock)->toContain('OPEN_PROPERTY_EXIT_GATE');
|
||||
expect($commandPathBlock)->toContain('wash_type:');
|
||||
expect($commandPathBlock)->toContain('wash_mode:');
|
||||
expect($commandPathBlock)->toContain('Command execution failed');
|
||||
expect($commandPathBlock)->toContain('Failed to execute command: Failed to open property access gate.');
|
||||
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
app_require('modules/selfserve/traits/selfserve_lane_command_t.php');
|
||||
app_require('modules/selfserve/classes/selfserve_lane_command_arguments.php');
|
||||
app_require('modules/selfserve/helpers/selfserve_lane_relay.php');
|
||||
|
||||
use modules\selfserve\classes\selfserve_lane_command_arguments;
|
||||
use modules\selfserve\traits\selfserve_lane_command_t;
|
||||
|
||||
class SelfserveProgramPickerSelectionValueFake
|
||||
{
|
||||
public function __construct(private readonly string $value) {}
|
||||
|
||||
public function value(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
}
|
||||
|
||||
class SelfserveProgramPickerSelectionDepartmentLaneFake
|
||||
{
|
||||
public SelfserveProgramPickerSelectionValueFake $relay_machine_id;
|
||||
public SelfserveProgramPickerSelectionValueFake $relay_machine_program_picker_id;
|
||||
public SelfserveProgramPickerSelectionValueFake $relay_machine_cleaner_id;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->relay_machine_id = new SelfserveProgramPickerSelectionValueFake('relay-machine');
|
||||
$this->relay_machine_program_picker_id = new SelfserveProgramPickerSelectionValueFake('relay-program-picker');
|
||||
$this->relay_machine_cleaner_id = new SelfserveProgramPickerSelectionValueFake('relay-cleaner');
|
||||
}
|
||||
}
|
||||
|
||||
class SelfserveProgramPickerSelectionHarness
|
||||
{
|
||||
use selfserve_lane_command_t;
|
||||
|
||||
public const CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES = 'allowed_services';
|
||||
|
||||
public int $id = 881;
|
||||
public object $department_lane;
|
||||
public int $licensePlateReads = 0;
|
||||
public int $customerNumberReads = 0;
|
||||
public int $availabilityChecks = 0;
|
||||
public bool $machineAvailable = true;
|
||||
/** @var array<int,bool> */
|
||||
public array $programPickerWrites = [];
|
||||
/** @var array<string,mixed> */
|
||||
private array $laneCache = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->department_lane = new SelfserveProgramPickerSelectionDepartmentLaneFake();
|
||||
}
|
||||
|
||||
public function getLaneCache(int $lane_id, string $key): mixed
|
||||
{
|
||||
return $this->laneCache[$key . '_' . $lane_id] ?? null;
|
||||
}
|
||||
|
||||
public function setSelectedServices(array $services): void
|
||||
{
|
||||
$this->laneCache[self::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES . '_' . $this->id] = $services;
|
||||
}
|
||||
|
||||
public function getLicensePlate(): string
|
||||
{
|
||||
$this->licensePlateReads++;
|
||||
return 'AB12345';
|
||||
}
|
||||
|
||||
public function getCustomerNumber(): int
|
||||
{
|
||||
$this->customerNumberReads++;
|
||||
return 12345678;
|
||||
}
|
||||
|
||||
public function setMachineProgramPickerRelayStatusHard(bool $on): bool
|
||||
{
|
||||
$this->programPickerWrites[] = $on;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function runDeferredStartRelaySideEffects(?string $washType = null): void
|
||||
{
|
||||
$arguments = (new selfserve_lane_command_arguments())
|
||||
->setDeferRelaySideEffects(true)
|
||||
->setWashMode($washType);
|
||||
$this->runRelaySideEffectsForWashStart($arguments);
|
||||
}
|
||||
|
||||
public function runNormalStartProgramPickerRelay(?string $washType = null): void
|
||||
{
|
||||
$arguments = (new selfserve_lane_command_arguments())->setWashMode($washType);
|
||||
$this->setProgramPickerRelayStatusForWashStart($arguments);
|
||||
}
|
||||
|
||||
public function resolveStartWashMode(?string $washType = null): string
|
||||
{
|
||||
$arguments = (new selfserve_lane_command_arguments())->setWashMode($washType);
|
||||
return $this->resolveSelfServeActionWashModeForStart($arguments);
|
||||
}
|
||||
|
||||
protected function isMachineWashSelectedAndAvailableForStart(?selfserve_lane_command_arguments $arguments = null): bool
|
||||
{
|
||||
unset($arguments);
|
||||
$this->availabilityChecks++;
|
||||
return $this->machineAvailable;
|
||||
}
|
||||
}
|
||||
|
||||
it('turns off the program picker on deferred start when the frontend selected manual wash', function (): void {
|
||||
$lane = new SelfserveProgramPickerSelectionHarness();
|
||||
$lane->setSelectedServices([]);
|
||||
|
||||
$lane->runDeferredStartRelaySideEffects('Manual');
|
||||
|
||||
expect($lane->programPickerWrites)->toBe([false]);
|
||||
});
|
||||
|
||||
it('does not let backend machine eligibility override a frontend manual wash selection', function (): void {
|
||||
$lane = new SelfserveProgramPickerSelectionHarness();
|
||||
$lane->setSelectedServices(['MACHINE']);
|
||||
|
||||
$lane->runDeferredStartRelaySideEffects('Manual');
|
||||
|
||||
expect($lane->licensePlateReads)->toBe(0)
|
||||
->and($lane->customerNumberReads)->toBe(0)
|
||||
->and($lane->programPickerWrites)->toBe([false])
|
||||
->and($lane->resolveStartWashMode('Manual'))->toBe('manual');
|
||||
});
|
||||
|
||||
it('does not infer program picker enablement from machine service without a customer machine selection', function (): void {
|
||||
$lane = new SelfserveProgramPickerSelectionHarness();
|
||||
$lane->setSelectedServices(['MACHINE']);
|
||||
|
||||
$lane->runDeferredStartRelaySideEffects();
|
||||
$lane->runNormalStartProgramPickerRelay();
|
||||
|
||||
expect($lane->programPickerWrites)->toBe([false, false])
|
||||
->and($lane->availabilityChecks)->toBe(0);
|
||||
});
|
||||
|
||||
it('keeps normal start program picker off when the customer selected manual wash', function (): void {
|
||||
$lane = new SelfserveProgramPickerSelectionHarness();
|
||||
$lane->setSelectedServices(['MACHINE']);
|
||||
|
||||
$lane->runNormalStartProgramPickerRelay('Manual');
|
||||
|
||||
expect($lane->programPickerWrites)->toBe([false])
|
||||
->and($lane->availabilityChecks)->toBe(0);
|
||||
});
|
||||
|
||||
it('honors a frontend machine wash selection when machine service is selected', function (): void {
|
||||
$lane = new SelfserveProgramPickerSelectionHarness();
|
||||
$lane->setSelectedServices(['MACHINE']);
|
||||
|
||||
$lane->runDeferredStartRelaySideEffects('Machine');
|
||||
$lane->runNormalStartProgramPickerRelay('Machine');
|
||||
|
||||
expect($lane->programPickerWrites)->toBe([true, true])
|
||||
->and($lane->availabilityChecks)->toBe(1)
|
||||
->and($lane->resolveStartWashMode('Machine'))->toBe('machine');
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
app_require('modules/selfserve/classes/selfserve_wash_flow.php');
|
||||
|
||||
use modules\selfserve\classes\selfserve_wash_flow;
|
||||
|
||||
class SelfservePublishedConfigLaneWildcardHarness extends selfserve_wash_flow
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function questionsFor(int $departmentId, int $laneId, int $vehicleTypeId, array $config): array
|
||||
{
|
||||
return $this->loadQuestions($departmentId, $laneId, $vehicleTypeId, $config);
|
||||
}
|
||||
|
||||
public function conditionsFor(int $departmentId, int $laneId, int $vehicleTypeId, array $config): array
|
||||
{
|
||||
return $this->loadConditions($departmentId, $laneId, $vehicleTypeId, null, $config);
|
||||
}
|
||||
|
||||
public function tasksFor(int $departmentId, int $laneId, int $vehicleTypeId, array $config): array
|
||||
{
|
||||
return $this->loadTasks($departmentId, $laneId, $vehicleTypeId, null, $config);
|
||||
}
|
||||
}
|
||||
|
||||
it('applies department product rows with lane zero to all lanes in published v2 configs', function (): void {
|
||||
$flow = new SelfservePublishedConfigLaneWildcardHarness();
|
||||
$config = [
|
||||
'schema_version' => 2,
|
||||
'questions' => [
|
||||
['id' => 1, 'department' => 6, 'lane' => 0, 'product' => 1, 'question' => 'Wildcard question'],
|
||||
['id' => 2, 'department' => 6, 'lane' => 99, 'product' => 1, 'question' => 'Other lane question'],
|
||||
],
|
||||
'conditions' => [
|
||||
['id' => 11, 'department' => 6, 'lane' => 0, 'product' => 1, 'machine_type_id' => null, 'expression' => ['type' => 'predicate', 'subject_type' => 'question', 'subject_id' => 1, 'operator' => 'IS_TRUE']],
|
||||
['id' => 12, 'department' => 6, 'lane' => 99, 'product' => 1, 'machine_type_id' => null, 'expression' => ['type' => 'predicate', 'subject_type' => 'question', 'subject_id' => 2, 'operator' => 'IS_TRUE']],
|
||||
],
|
||||
'tasks' => [
|
||||
['id' => 21, 'department' => 6, 'lane' => 0, 'product' => 1, 'machine_type_id' => null, 'task' => 'Wildcard task', 'services' => ['MACHINE'], 'buttons' => [], 'gate_type' => 'ALWAYS', 'gate_ref_id' => null],
|
||||
['id' => 22, 'department' => 6, 'lane' => 99, 'product' => 1, 'machine_type_id' => null, 'task' => 'Other lane task', 'services' => ['MACHINE'], 'buttons' => [], 'gate_type' => 'ALWAYS', 'gate_ref_id' => null],
|
||||
],
|
||||
];
|
||||
|
||||
expect(array_column($flow->questionsFor(6, 12, 1, $config), 'id'))->toBe([1]);
|
||||
expect(array_column($flow->conditionsFor(6, 12, 1, $config), 'id'))->toBe([11]);
|
||||
expect(array_column($flow->tasksFor(6, 12, 1, $config), 'id'))->toBe([21]);
|
||||
});
|
||||
@@ -84,6 +84,17 @@ it('wires lane-level self-serve toggles through lane APIs, guest payloads, and e
|
||||
->and($edgeWorkspace)->toContain("(int)(\$selfServe['ready_lanes'] ?? 0) < (int)(\$selfServe['enabled_lanes'] ?? 0)");
|
||||
});
|
||||
|
||||
it('sources guest lane product availability from the published v2 self-serve config before legacy tasks', function (): void {
|
||||
$laneObject = file_get_contents(app_path('objects/department_lanes_o.php'));
|
||||
|
||||
expect($laneObject)->not->toBeFalse()
|
||||
->and($laneObject)->toContain('getPublishedSelfServeLaneProducts')
|
||||
->and($laneObject)->toContain('selfserve_config_versioning')
|
||||
->and($laneObject)->toContain('getPublishedV2Config')
|
||||
->and($laneObject)->toContain("\$taskLane !== 0 && \$taskLane !== \$laneId")
|
||||
->and($laneObject)->toContain('department_selfserve_tasks_o::getLaneProducts');
|
||||
});
|
||||
|
||||
it('wires self-serve config draft/publish/rollback lifecycle endpoints', function (): void {
|
||||
$configRoute = file_get_contents(app_path('routes/departmentSelfserveConfigVersionsRoute.php'));
|
||||
|
||||
@@ -170,8 +181,10 @@ it('keeps legacy self-serve CRUD routes syncing canonical drafts', function ():
|
||||
|
||||
it('wires machine relay status get and set endpoints', function (): void {
|
||||
$moduleSelfServeRoute = file_get_contents(app_path('routes/moduleSelfServeRoute.php'));
|
||||
$relayController = file_get_contents(app_path('modules/selfserve/traits/selfserve_lane_relay_controller_t.php'));
|
||||
|
||||
expect($moduleSelfServeRoute)->not->toBeFalse();
|
||||
expect($relayController)->not->toBeFalse();
|
||||
expect($moduleSelfServeRoute)->toContain('/modules/self-serve/lane/relay/machine/status');
|
||||
expect($moduleSelfServeRoute)->toContain('/modules/self-serve/lane/relay/machine/set');
|
||||
expect($moduleSelfServeRoute)->toContain('/modules/self-serve/lane/relay/machine_program_picker/status');
|
||||
@@ -185,6 +198,9 @@ it('wires machine relay status get and set endpoints', function (): void {
|
||||
expect($moduleSelfServeRoute)->toContain('getMachineCleanerRelayStatus');
|
||||
expect($moduleSelfServeRoute)->toContain('setMachineCleanerRelayStatus');
|
||||
expect($moduleSelfServeRoute)->toContain('setMachineCleanerRelayStatusHard(true)');
|
||||
expect($relayController)->toContain('markLatestSelfServeSessionRelayEnabledForLane');
|
||||
expect($relayController)->toContain('selectLatestOpenByLane(');
|
||||
expect($relayController)->toContain('$session->markRelayEnabled();');
|
||||
expect($moduleSelfServeRoute)->toContain('applyShellyTransportOverride($lane)');
|
||||
expect($moduleSelfServeRoute)->toContain("'transport' => \$this->requestedShellyTransportOverride()");
|
||||
expect($moduleSelfServeRoute)->toContain('buildRelayStatusResponse');
|
||||
@@ -240,6 +256,11 @@ it('wires allowed services route through machine relay visibility sync', functio
|
||||
|
||||
expect($moduleSelfServeRoute)->not->toBeFalse();
|
||||
expect($moduleSelfServeRoute)->toContain('/modules/self-serve/lane/services/allowed');
|
||||
expect($moduleSelfServeRoute)->toContain('selfserve_wash_session_tasks_o');
|
||||
expect($moduleSelfServeRoute)->toContain('selectLatestOpenByLane');
|
||||
expect($moduleSelfServeRoute)->toContain('$session_task_services[$task_id]');
|
||||
expect($moduleSelfServeRoute)->toContain('publishedConfigTaskServicesForLane');
|
||||
expect($moduleSelfServeRoute)->toContain('$published_config_task_services[$tid]');
|
||||
expect($moduleSelfServeRoute)->toContain('setAllowedServicesFromVisibleTasks($allowed_services)');
|
||||
expect($moduleSelfServeRoute)->not->toContain('syncMachineRelayFromVisibleServices($allowed_services, true)');
|
||||
expect($moduleSelfServeRoute)->toContain("'relay_sync' => \$relay_sync");
|
||||
@@ -274,6 +295,9 @@ it('wires self-serve property gate command permissions', function (): void {
|
||||
expect($moduleSelfServeRoute)->toContain('modules_selfserve_lane_command_execute_open_property_access_gate');
|
||||
expect($moduleSelfServeRoute)->toContain('modules_selfserve_lane_command_execute_open_property_exit_gate');
|
||||
expect($moduleSelfServeRoute)->toContain('Failed to execute self-serve property gate command');
|
||||
expect($moduleSelfServeRoute)->toContain('$this->canCustomerUsePropertyGateForLane($lane, $customer_number)');
|
||||
expect($moduleSelfServeRoute)->toContain('$this->isOwnCustomerContext($customer_number)');
|
||||
expect($moduleSelfServeRoute)->toContain('$this->customerHasActiveSelfServeWashInDepartment($department_id, $customer_number)');
|
||||
|
||||
expect($commandTrait)->not->toBeFalse();
|
||||
expect($commandTrait)->toContain('Failed to open property access gate.');
|
||||
@@ -424,7 +448,8 @@ it('wires vehicle type override into self-serve preview and synchronization rout
|
||||
expect($vehicleConditionsRoute)->toContain('normalizeVehicleTypeOverride');
|
||||
expect($vehicleConditionsRoute)->toContain('shouldRefreshSummaryForVehicleType');
|
||||
expect($vehicleConditionsRoute)->toContain('previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id)');
|
||||
expect($vehicleConditionsRoute)->toContain('synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false)');
|
||||
expect($vehicleConditionsRoute)->toContain('synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [');
|
||||
expect($vehicleConditionsRoute)->toContain("'create_session' => false");
|
||||
expect($vehicleConditionsRoute)->toContain('requestBooleanFlag');
|
||||
expect($vehicleConditionsRoute)->toContain('synchronizeSession($lane, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state)');
|
||||
expect($vehicleConditionsRoute)->toContain('synchronizeSession($lane_id, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state)');
|
||||
@@ -460,9 +485,11 @@ it('keeps read-only self-serve preview and summary refreshes from touching relay
|
||||
$vehicleConditionsRoute = file_get_contents(app_path('routes/departmentSelfserveVehicleConditionsRoute.php'));
|
||||
|
||||
expect($vehicleConditionsRoute)->not->toBeFalse();
|
||||
expect($vehicleConditionsRoute)->toContain('$flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false);');
|
||||
expect($vehicleConditionsRoute)->toContain('$flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [');
|
||||
expect($vehicleConditionsRoute)->toContain("'create_session' => false");
|
||||
expect($vehicleConditionsRoute)->toContain('$summary = $flow->synchronizeSession(');
|
||||
expect($vehicleConditionsRoute)->toContain('$summary = $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false);');
|
||||
expect($vehicleConditionsRoute)->toContain('$summary = $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [');
|
||||
expect($vehicleConditionsRoute)->toContain('$summary = $flow->getLatestSessionSummary($lane_id, $reg);');
|
||||
expect($vehicleConditionsRoute)->toContain('$activate_machine = $this->requestBooleanFlag(\'activate_machine\', true);');
|
||||
expect($vehicleConditionsRoute)->toContain('$sync_relay_state = $this->requestBooleanFlag(\'sync_relay_state\', true);');
|
||||
expect($vehicleConditionsRoute)->toContain('$this->getWashFlow()->synchronizeSession($lane, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state);');
|
||||
@@ -485,6 +512,10 @@ it('classifies self-serve lane command route authorization by customer product b
|
||||
expect($productDocs)->toContain('Customer `START` requires an enabled self-serve lane. Customer `STOP` and property gate commands require the customer\'s active wash in the lane department.');
|
||||
expect($washFlow)->toContain('$payload[\'command\'] = $relayRole === \'PROPERTY_ENTRANCE\' ? \'OPEN_PROPERTY_ACCESS_GATE\' : \'OPEN_PROPERTY_EXIT_GATE\'');
|
||||
expect($washFlow)->toContain('$signalType = \'studio_action_gate_open\'');
|
||||
expect($moduleSelfServeRoute)
|
||||
->toContain('if ($command === selfserve_lane_command::START)')
|
||||
->toContain('(new selfserve_wash_flow())->synchronizeSession(')
|
||||
->toContain('Failed to persist self-serve START session');
|
||||
|
||||
$commandCases = selfserve_lane_command_route_cases($moduleSelfServeRoute);
|
||||
|
||||
|
||||
+112
@@ -9,6 +9,118 @@ it('adds dynamic_images_vehicle_type column for legacy selfserve wash session ta
|
||||
expect($bootstrapContent)->toContain('ALTER TABLE selfserve_wash_session_tasks ADD COLUMN dynamic_images_vehicle_type INT NULL AFTER buttons');
|
||||
});
|
||||
|
||||
it('widens self-serve task descriptions for generated workbook instructions', function (): void {
|
||||
$bootstrapContent = file_get_contents(app_path('classes/selfserve_schema_bootstrap.php'));
|
||||
|
||||
expect($bootstrapContent)->not->toBeFalse();
|
||||
expect($bootstrapContent)->toContain('description TEXT NULL');
|
||||
expect($bootstrapContent)->toContain('ensureColumnDataType(');
|
||||
expect($bootstrapContent)->toContain("['text', 'mediumtext', 'longtext']");
|
||||
expect($bootstrapContent)->toContain('ALTER TABLE department_selfserve_tasks MODIFY COLUMN description TEXT NULL AFTER task');
|
||||
expect($bootstrapContent)->toContain('ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text');
|
||||
});
|
||||
|
||||
it('alters legacy bounded description columns to text', function (): void {
|
||||
$hadDb = array_key_exists('db', $GLOBALS);
|
||||
$previousDb = $GLOBALS['db'] ?? null;
|
||||
|
||||
try {
|
||||
foreach (['varchar', 'tinytext'] as $legacyType) {
|
||||
$fakeDb = new class ($legacyType) {
|
||||
public array $queries = [];
|
||||
|
||||
public function __construct(private readonly string $dataType)
|
||||
{
|
||||
}
|
||||
|
||||
public function escape_string(string $value): string
|
||||
{
|
||||
return addslashes($value);
|
||||
}
|
||||
|
||||
public function getDatabase(): string
|
||||
{
|
||||
return 'test_db';
|
||||
}
|
||||
|
||||
public function query(string $sql): object|bool
|
||||
{
|
||||
$this->queries[] = $sql;
|
||||
if (str_contains($sql, 'information_schema.COLUMNS')) {
|
||||
return new class ($this->dataType) {
|
||||
public function __construct(private readonly string $dataType)
|
||||
{
|
||||
}
|
||||
|
||||
public function fetch_assoc(): array
|
||||
{
|
||||
return ['DATA_TYPE' => $this->dataType];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
$GLOBALS['db'] = $fakeDb;
|
||||
|
||||
\classes\selfserve_schema_bootstrap::ensureColumnDataType(
|
||||
'selfserve_wash_session_tasks',
|
||||
'description',
|
||||
['text', 'mediumtext', 'longtext'],
|
||||
'ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text'
|
||||
);
|
||||
|
||||
expect($fakeDb->queries)->toContain('ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text');
|
||||
}
|
||||
|
||||
$textDb = new class {
|
||||
public array $queries = [];
|
||||
|
||||
public function escape_string(string $value): string
|
||||
{
|
||||
return addslashes($value);
|
||||
}
|
||||
|
||||
public function getDatabase(): string
|
||||
{
|
||||
return 'test_db';
|
||||
}
|
||||
|
||||
public function query(string $sql): object|bool
|
||||
{
|
||||
$this->queries[] = $sql;
|
||||
if (str_contains($sql, 'information_schema.COLUMNS')) {
|
||||
return new class {
|
||||
public function fetch_assoc(): array
|
||||
{
|
||||
return ['DATA_TYPE' => 'text'];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
$GLOBALS['db'] = $textDb;
|
||||
|
||||
\classes\selfserve_schema_bootstrap::ensureColumnDataType(
|
||||
'selfserve_wash_session_tasks',
|
||||
'description',
|
||||
['text', 'mediumtext', 'longtext'],
|
||||
'ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text'
|
||||
);
|
||||
|
||||
expect(implode("\n", $textDb->queries))->not->toContain('ALTER TABLE selfserve_wash_session_tasks MODIFY COLUMN description TEXT NULL AFTER task_text');
|
||||
} finally {
|
||||
if ($hadDb) {
|
||||
$GLOBALS['db'] = $previousDb;
|
||||
} else {
|
||||
unset($GLOBALS['db']);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('adds wash_started_at column for legacy selfserve wash session schemas', function (): void {
|
||||
$bootstrapContent = file_get_contents(app_path('classes/selfserve_schema_bootstrap.php'));
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
it('serializes self-serve session synchronization before reading or creating open sessions', function (): void {
|
||||
$washFlow = file_get_contents(app_path('modules/selfserve/classes/selfserve_wash_flow.php'));
|
||||
|
||||
expect($washFlow)->not->toBeFalse()
|
||||
->and($washFlow)->toContain('withSessionMutationLock')
|
||||
->and($washFlow)->toContain('sessionMutationLockKey')
|
||||
->and($washFlow)->toContain('set_if_absent_with_expiration')
|
||||
->and($washFlow)->toContain('GET_LOCK');
|
||||
|
||||
$syncOffset = strpos($washFlow, 'public function synchronizeSession');
|
||||
expect($syncOffset)->not->toBeFalse();
|
||||
|
||||
$syncMethod = substr($washFlow, (int)$syncOffset, 9000);
|
||||
$snapshotOffset = strpos($syncMethod, '$snapshot = $this->buildEligibilitySnapshot');
|
||||
$lockOffset = strpos($syncMethod, '$mutationResult = $this->withSessionMutationLock');
|
||||
$findOffset = strpos($syncMethod, '$session = $this->findLatestOpenSession');
|
||||
$addOffset = strpos($syncMethod, '$session = (new selfserve_wash_sessions_o())->add');
|
||||
$relayOffset = strpos($syncMethod, '$this->syncMachineRelayFromVisibleServices');
|
||||
|
||||
expect($snapshotOffset)->not->toBeFalse()
|
||||
->and($lockOffset)->not->toBeFalse()
|
||||
->and($findOffset)->not->toBeFalse()
|
||||
->and($addOffset)->not->toBeFalse()
|
||||
->and($relayOffset)->not->toBeFalse()
|
||||
->and($snapshotOffset)->toBeLessThan($lockOffset)
|
||||
->and($lockOffset)->toBeLessThan($findOffset)
|
||||
->and($findOffset)->toBeLessThan($addOffset)
|
||||
->and($addOffset)->toBeLessThan($relayOffset);
|
||||
});
|
||||
|
||||
it('closes self-serve wash sessions with an atomic open-session guard', function (): void {
|
||||
$sessionObject = file_get_contents(app_path('objects/selfserve_wash_sessions_o.php'));
|
||||
$washFlow = file_get_contents(app_path('modules/selfserve/classes/selfserve_wash_flow.php'));
|
||||
|
||||
expect($sessionObject)->not->toBeFalse()
|
||||
->and($sessionObject)->toContain('markCompletedIfOpen')
|
||||
->and($sessionObject)->toContain('markForceStoppedIfOpen')
|
||||
->and($sessionObject)->toContain('AND `completed_at` IS NULL')
|
||||
->and($sessionObject)->toContain('AND UPPER(TRIM(`status`)) NOT IN ($terminalStatuses)');
|
||||
|
||||
expect($washFlow)->not->toBeFalse()
|
||||
->and($washFlow)->toContain('if (!$session->markCompletedIfOpen($orderId))')
|
||||
->and($washFlow)->toContain('if (!$session->markForceStoppedIfOpen($orderId, $eventPayload))');
|
||||
});
|
||||
@@ -14,6 +14,17 @@ it('enforces a global 2 second Shelly gate in sendPostRequest', function (): voi
|
||||
expect($sendPostRequestBody)->toContain('$this->waitForShellyRateLimitWindow();');
|
||||
});
|
||||
|
||||
it('bounds Shelly cloud HTTP requests with curl timeouts', function (): void {
|
||||
$shellyClass = file_get_contents(app_path('classes/shelly.php'));
|
||||
|
||||
expect($shellyClass)->not->toBeFalse();
|
||||
expect($shellyClass)->toContain('private const SHELLY_CONNECT_TIMEOUT_SECONDS = 2;');
|
||||
expect($shellyClass)->toContain('private const SHELLY_REQUEST_TIMEOUT_SECONDS = 5;');
|
||||
expect($shellyClass)->toContain('CURLOPT_CONNECTTIMEOUT, self::SHELLY_CONNECT_TIMEOUT_SECONDS');
|
||||
expect($shellyClass)->toContain('CURLOPT_TIMEOUT, self::SHELLY_REQUEST_TIMEOUT_SECONDS');
|
||||
expect($shellyClass)->toContain('CURLOPT_NOSIGNAL, true');
|
||||
});
|
||||
|
||||
it('uses Redis NX PX semantics for cross-request Shelly rate limiting', function (): void {
|
||||
$shellyClass = file_get_contents(app_path('classes/shelly.php'));
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
it('registers Slack module config endpoints and customer registration webhook config', function (): void {
|
||||
$routeFile = app_path('routes/moduleConfigRoute.php');
|
||||
$routeContent = file_get_contents($routeFile);
|
||||
|
||||
expect($routeContent)->not->toBeFalse()
|
||||
->and($routeContent)->toContain('/slack/config')
|
||||
->and($routeContent)->toContain("requirePermission('slack_config')")
|
||||
->and($routeContent)->toContain("(new slack())->getConfig()->getConfigRequest()")
|
||||
->and($routeContent)->toContain("(new slack())->getConfig()->postConfigRequest()");
|
||||
|
||||
$moduleContent = file_get_contents(app_path('modules/slack/slack_c.php'));
|
||||
$variableContent = file_get_contents(app_path('modules/slack/config/slack_customer_registration_webhook_url_c.php'));
|
||||
$slackClassContent = file_get_contents(app_path('classes/slack.php'));
|
||||
$authRouteContent = file_get_contents(app_path('routes/authRoute.php'));
|
||||
$openApiContent = file_get_contents(app_path('openapi.yaml'));
|
||||
|
||||
expect($moduleContent)->not->toBeFalse()
|
||||
->and($moduleContent)->toContain("setupConfig('Slack')")
|
||||
->and($moduleContent)->toContain('slack_customer_registration_webhook_url_c::class')
|
||||
->and($variableContent)->not->toBeFalse()
|
||||
->and($variableContent)->toContain("'customer_registration_webhook_url'")
|
||||
->and($variableContent)->toContain('Slack webhook URL used for successful customer registration notifications')
|
||||
->and($slackClassContent)->not->toBeFalse()
|
||||
->and($slackClassContent)->toContain('send_customer_registration_notification')
|
||||
->and($slackClassContent)->toContain('format_customer_registration')
|
||||
->and($authRouteContent)->not->toBeFalse()
|
||||
->and($authRouteContent)->toContain("AUTH_REGISTER_CVR_SLACK_NOTIFICATION_FAILED")
|
||||
->and($openApiContent)->not->toBeFalse()
|
||||
->and($openApiContent)->toContain('/slack/config')
|
||||
->and($openApiContent)->toContain('SlackConfigListResponse')
|
||||
->and($openApiContent)->toContain('SlackConfigEntry');
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use classes\pdf_store;
|
||||
|
||||
it('falls back to local test storage when MinIO config values are empty', function (): void {
|
||||
global $MINIO;
|
||||
|
||||
$previousRunApiTests = getenv('RUN_API_TESTS');
|
||||
$previousMinio = $MINIO ?? null;
|
||||
putenv('RUN_API_TESTS=1');
|
||||
$MINIO = [
|
||||
'endpoint' => null,
|
||||
'access_key' => null,
|
||||
'secret_key' => null,
|
||||
];
|
||||
|
||||
try {
|
||||
$file = 'minio-local-test-' . bin2hex(random_bytes(4)) . '.pdf';
|
||||
$store = new pdf_store();
|
||||
|
||||
expect($store->createObject($file, 'local-pdf-content'))->toBeTrue();
|
||||
|
||||
$path = $store->download($file);
|
||||
|
||||
expect(is_file($path))->toBeTrue()
|
||||
->and(file_get_contents($path))->toBe('local-pdf-content');
|
||||
} finally {
|
||||
if (isset($path) && is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
if ($previousRunApiTests === false) {
|
||||
putenv('RUN_API_TESTS');
|
||||
} else {
|
||||
putenv('RUN_API_TESTS=' . $previousRunApiTests);
|
||||
}
|
||||
$MINIO = $previousMinio;
|
||||
}
|
||||
});
|
||||
@@ -150,10 +150,12 @@ namespace classes {
|
||||
class email
|
||||
{
|
||||
public static array $sent = [];
|
||||
public static array $superuser_notifications = [];
|
||||
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$sent = [];
|
||||
self::$superuser_notifications = [];
|
||||
}
|
||||
|
||||
public function sendWelcomeEmailToCustomer($phone, $email): bool
|
||||
@@ -166,6 +168,36 @@ namespace classes {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function sendNewCustomerRegistrationNotifications($phone): bool
|
||||
{
|
||||
self::$superuser_notifications[] = [
|
||||
'customer_number' => (int)$phone,
|
||||
];
|
||||
\objects\users_o::$interaction_log[] = 'superuser-notification:' . (int)$phone;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class slack
|
||||
{
|
||||
public static array $customer_registration_notifications = [];
|
||||
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$customer_registration_notifications = [];
|
||||
}
|
||||
|
||||
public function send_customer_registration_notification($customer_number): self
|
||||
{
|
||||
self::$customer_registration_notifications[] = [
|
||||
'customer_number' => (int)$customer_number,
|
||||
];
|
||||
\objects\users_o::$interaction_log[] = 'slack-customer-registration:' . (int)$customer_number;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
class authentication
|
||||
@@ -370,6 +402,8 @@ namespace {
|
||||
'assert' => static function (): void {
|
||||
assert_true(count(\classes\economic::$create_calls) === 0, 'Fresh create must not run for local duplicates.');
|
||||
assert_true(count(\classes\email::$sent) === 0, 'Duplicate registrations must not send welcome emails.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 0, 'Duplicate registrations must not send superuser notifications.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 0, 'Duplicate registrations must not send Slack customer registration notifications.');
|
||||
},
|
||||
],
|
||||
[
|
||||
@@ -395,6 +429,10 @@ namespace {
|
||||
assert_true(\objects\users_o::$interaction_log[0] === 'bootstrap:12345678', 'Local bootstrap must happen before sending emails.');
|
||||
assert_true(\classes\email::$sent[0]['email'] === 'jm@truckwash.dk', 'Recovery should notify the internal welcome recipient first.');
|
||||
assert_true(\classes\email::$sent[1]['email'] === 'test@test.com', 'Recovery should notify the invoice email.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 1, 'Recovery must notify opted-in superusers once.');
|
||||
assert_true(\classes\email::$superuser_notifications[0]['customer_number'] === 12345678, 'Recovery superuser notification must use the recovered customer number.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 1, 'Recovery must notify Slack once.');
|
||||
assert_true(\classes\slack::$customer_registration_notifications[0]['customer_number'] === 12345678, 'Recovery Slack notification must use the recovered customer number.');
|
||||
},
|
||||
],
|
||||
[
|
||||
@@ -413,6 +451,8 @@ namespace {
|
||||
'expected_status' => 400,
|
||||
'assert' => static function (): void {
|
||||
assert_true(count(\classes\email::$sent) === 0, 'Duplicate recovery attempts must not send welcome emails.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 0, 'Duplicate recovery attempts must not send superuser notifications.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 0, 'Duplicate recovery attempts must not send Slack customer registration notifications.');
|
||||
},
|
||||
],
|
||||
[
|
||||
@@ -431,6 +471,8 @@ namespace {
|
||||
'assert' => static function (): void {
|
||||
assert_true(count(\classes\economic::$create_calls) === 0, 'Conflict on existing mismatched customer must not trigger create.');
|
||||
assert_true(count(\classes\email::$sent) === 0, 'Conflict on existing mismatched customer must not send welcome emails.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 0, 'Conflict on existing mismatched customer must not send superuser notifications.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 0, 'Conflict on existing mismatched customer must not send Slack customer registration notifications.');
|
||||
assert_true(count(\objects\logs_o::$entries) === 1, 'Conflict should be logged for manual cleanup.');
|
||||
},
|
||||
],
|
||||
@@ -461,6 +503,10 @@ namespace {
|
||||
assert_true(count(\classes\email::$sent) === 2, 'Fresh registration must send two welcome emails.');
|
||||
assert_true(\objects\users_o::$interaction_log[0] === 'bootstrap:12345678', 'Fresh registration must bootstrap the local user before emails.');
|
||||
assert_true(\classes\email::$sent[0]['email'] === 'jm@truckwash.dk', 'Fresh registration should notify the internal welcome recipient first.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 1, 'Fresh registration must notify opted-in superusers once.');
|
||||
assert_true(\classes\email::$superuser_notifications[0]['customer_number'] === 12345678, 'Fresh registration superuser notification must use the created customer number.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 1, 'Fresh registration must notify Slack once.');
|
||||
assert_true(\classes\slack::$customer_registration_notifications[0]['customer_number'] === 12345678, 'Fresh registration Slack notification must use the created customer number.');
|
||||
},
|
||||
],
|
||||
[
|
||||
@@ -479,6 +525,8 @@ namespace {
|
||||
assert_true(count(\classes\economic::$create_calls) === 1, 'Create mismatch must still record the attempted create call.');
|
||||
assert_true(count(\objects\users_o::$interaction_log) === 0, 'Create mismatch must not bootstrap the wrong local customer.');
|
||||
assert_true(count(\classes\email::$sent) === 0, 'Create mismatch must not send welcome emails.');
|
||||
assert_true(count(\classes\email::$superuser_notifications) === 0, 'Create mismatch must not send superuser notifications.');
|
||||
assert_true(count(\classes\slack::$customer_registration_notifications) === 0, 'Create mismatch must not send Slack customer registration notifications.');
|
||||
assert_true(count(\objects\logs_o::$entries) === 1, 'Create mismatch should be logged for manual cleanup.');
|
||||
},
|
||||
],
|
||||
@@ -490,6 +538,7 @@ namespace {
|
||||
\classes\recaptcha::$mock_valid = true;
|
||||
\classes\economic::reset();
|
||||
\classes\email::reset();
|
||||
\classes\slack::reset();
|
||||
\classes\virkdata::$mock_name = 'Mock Company';
|
||||
\classes\virkdata::$mock_address = 'Demo Street 1';
|
||||
\classes\virkdata::$mock_zipcode = 2630;
|
||||
|
||||
@@ -76,7 +76,7 @@ trait minio_t
|
||||
public function getEndpoint(): string
|
||||
{
|
||||
global $MINIO;
|
||||
return $MINIO['endpoint'];
|
||||
return is_array($MINIO ?? null) ? (string)($MINIO['endpoint'] ?? '') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,7 +86,7 @@ trait minio_t
|
||||
public function getAccessKey(): string
|
||||
{
|
||||
global $MINIO;
|
||||
return $MINIO['access_key'];
|
||||
return is_array($MINIO ?? null) ? (string)($MINIO['access_key'] ?? '') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,7 +96,7 @@ trait minio_t
|
||||
public function getSecretKey(): string
|
||||
{
|
||||
global $MINIO;
|
||||
return $MINIO['secret_key'];
|
||||
return is_array($MINIO ?? null) ? (string)($MINIO['secret_key'] ?? '') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -276,7 +276,7 @@ trait module_config_variable
|
||||
private static function readDatabaseConfigFromEnvironment(): array
|
||||
{
|
||||
$readEnv = static function (string $key, string $default = ''): string {
|
||||
$value = $_ENV[$key] ?? getenv($key);
|
||||
$value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
|
||||
if ($value === false || $value === null) {
|
||||
return $default;
|
||||
}
|
||||
@@ -284,9 +284,25 @@ trait module_config_variable
|
||||
return trim((string)$value);
|
||||
};
|
||||
|
||||
$host = $readEnv('CONFIG_DB_HOST');
|
||||
$user = $readEnv('CONFIG_DB_USER');
|
||||
$database = $readEnv('CONFIG_DB_DATABASE');
|
||||
$dbTarget = strtolower(trim($readEnv('CONFIG_DB_TARGET', 'live')));
|
||||
if ($dbTarget !== 'live' && $dbTarget !== 'debug') {
|
||||
$dbTarget = 'live';
|
||||
}
|
||||
|
||||
$resolveDbValue = static function (string $key) use ($dbTarget, $readEnv): string {
|
||||
$liveValue = $readEnv('CONFIG_DB_' . $key);
|
||||
$debugValue = $readEnv('CONFIG_DB_DEBUG_' . $key);
|
||||
|
||||
if ($dbTarget === 'debug' && $debugValue !== '') {
|
||||
return $debugValue;
|
||||
}
|
||||
|
||||
return $liveValue;
|
||||
};
|
||||
|
||||
$host = $resolveDbValue('HOST');
|
||||
$user = $resolveDbValue('USER');
|
||||
$database = $resolveDbValue('DATABASE');
|
||||
|
||||
if ($host === '' || $user === '' || $database === '') {
|
||||
return [];
|
||||
@@ -295,10 +311,10 @@ trait module_config_variable
|
||||
return [
|
||||
'host' => $host,
|
||||
'user' => $user,
|
||||
'password' => $readEnv('CONFIG_DB_PASSWORD'),
|
||||
'password' => $resolveDbValue('PASSWORD'),
|
||||
'database' => $database,
|
||||
'port' => (int)($readEnv('CONFIG_DB_PORT', '3306') ?: '3306'),
|
||||
'ssl_mode' => $readEnv('CONFIG_DB_SSL_MODE', 'DISABLED') ?: 'DISABLED',
|
||||
'port' => (int)($resolveDbValue('PORT') ?: '3306'),
|
||||
'ssl_mode' => $resolveDbValue('SSL_MODE') ?: 'DISABLED',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,18 @@ http:
|
||||
certResolver: le
|
||||
|
||||
# Dashboard routers are declared via labels; middlewares are defined below.
|
||||
local:
|
||||
rule: Host(`localhost`)
|
||||
entryPoints: [web]
|
||||
middlewares: [secure-headers]
|
||||
service: caddy-local
|
||||
|
||||
local-api:
|
||||
rule: Host(`localhost`) && PathPrefix(`/api`)
|
||||
entryPoints: [web]
|
||||
middlewares: [strip-api-prefix, secure-headers]
|
||||
service: caddy-local
|
||||
priority: 100
|
||||
|
||||
middlewares:
|
||||
redirect-to-https:
|
||||
@@ -125,6 +137,10 @@ http:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://94.130.142.41:11000"
|
||||
caddy-local:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://caddy"
|
||||
|
||||
tls:
|
||||
options:
|
||||
|
||||
Reference in New Issue
Block a user