Compare commits

..

2 Commits

Author SHA1 Message Date
copilot-swe-agent[bot]
c84911b7ea Remove outdated translation notes and add human-readable descriptions
Co-authored-by: jbtronics <5410681+jbtronics@users.noreply.github.com>
2026-01-18 17:58:18 +00:00
copilot-swe-agent[bot]
3fc0d95b18 Initial plan 2026-01-18 17:52:24 +00:00
206 changed files with 28250 additions and 23361 deletions

11
.env
View File

@@ -59,17 +59,6 @@ ERROR_PAGE_ADMIN_EMAIL=''
# If this is set to true, solutions to common problems are shown on error pages. Disable this, if you do not want your users to see them...
ERROR_PAGE_SHOW_HELP=1
###################################################################################
# Update Manager settings
###################################################################################
# Disable web-based updates from the Update Manager UI (0=enabled, 1=disabled).
# When disabled, use the CLI command "php bin/console partdb:update" instead.
DISABLE_WEB_UPDATES=1
# Disable backup restore from the Update Manager UI (0=enabled, 1=disabled).
# Restoring backups is a destructive operation that could overwrite your database.
DISABLE_BACKUP_RESTORE=1
###################################################################################
# SAML Single sign on-settings

View File

@@ -46,11 +46,13 @@ RUN apt-get update && apt-get -y install \
&& rm -rvf /var/www/html/*
# Install node and yarn
RUN curl -sL https://deb.nodesource.com/setup_22.x | bash - && \
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
curl -sL https://deb.nodesource.com/setup_22.x | bash - && \
apt-get update && apt-get install -y \
nodejs \
&& apt-get -y autoremove && apt-get clean autoclean && rm -rf /var/lib/apt/lists/* && \
npm install -g yarn
yarn \
&& apt-get -y autoremove && apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

View File

@@ -14,21 +14,31 @@ RUN apt-get update && apt-get -y install \
&& apt-get -y autoremove && apt-get clean autoclean && rm -rf /var/lib/apt/lists/*;
RUN set -eux; \
# Run NodeSource setup script
# Prepare keyrings directory
mkdir -p /etc/apt/keyrings; \
\
# Import Yarn GPG key
curl -fsSL https://dl.yarnpkg.com/debian/pubkey.gpg \
| tee /etc/apt/keyrings/yarn.gpg >/dev/null; \
chmod 644 /etc/apt/keyrings/yarn.gpg; \
\
# Add Yarn repo with signed-by
echo "deb [signed-by=/etc/apt/keyrings/yarn.gpg] https://dl.yarnpkg.com/debian stable main" \
| tee /etc/apt/sources.list.d/yarn.list; \
\
# Run NodeSource setup script (unchanged)
curl -sL https://deb.nodesource.com/setup_22.x | bash -; \
\
# Install Node.js
# Install Node.js + Yarn
apt-get update; \
apt-get install -y --no-install-recommends \
nodejs; \
nodejs \
yarn; \
\
# Cleanup
apt-get -y autoremove; \
apt-get clean autoclean; \
rm -rf /var/lib/apt/lists/*; \
\
# Install Yarn via npm
npm install -g yarn
rm -rf /var/lib/apt/lists/*
# Install PHP

View File

@@ -1 +1 @@
2.6.0
2.4.0

View File

@@ -1,55 +0,0 @@
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2025 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Controller } from '@hotwired/stimulus';
/**
* Stimulus controller for backup restore confirmation dialogs.
* Shows a confirmation dialog with backup details before allowing restore.
*/
export default class extends Controller {
static values = {
filename: { type: String, default: '' },
date: { type: String, default: '' },
confirmTitle: { type: String, default: 'Restore Backup' },
confirmMessage: { type: String, default: 'Are you sure you want to restore from this backup?' },
confirmWarning: { type: String, default: 'This will overwrite your current database. This action cannot be undone!' },
};
connect() {
this.element.addEventListener('submit', this.handleSubmit.bind(this));
}
handleSubmit(event) {
// Always prevent default first
event.preventDefault();
// Build confirmation message
const message = this.confirmTitleValue + '\n\n' +
'Backup: ' + this.filenameValue + '\n' +
'Date: ' + this.dateValue + '\n\n' +
this.confirmMessageValue + '\n\n' +
'⚠️ ' + this.confirmWarningValue;
// Only submit if user confirms
if (confirm(message)) {
this.element.submit();
}
}
}

View File

@@ -21,7 +21,6 @@ import {Controller} from "@hotwired/stimulus";
import * as bootbox from "bootbox";
import "../../css/components/bootbox_extensions.css";
import accept from "attr-accept";
export default class extends Controller {
static values = {
@@ -74,24 +73,16 @@ export default class extends Controller {
const newElementStr = this.htmlDecode(prototype.replace(regex, this.generateUID()));
let ret = null;
//Insert new html after the last child element
//If the table has a tbody, insert it there
//Afterwards return the newly created row
if(targetTable.tBodies[0]) {
targetTable.tBodies[0].insertAdjacentHTML('beforeend', newElementStr);
ret = targetTable.tBodies[0].lastElementChild;
return targetTable.tBodies[0].lastElementChild;
} else { //Otherwise just insert it
targetTable.insertAdjacentHTML('beforeend', newElementStr);
ret = targetTable.lastElementChild;
return targetTable.lastElementChild;
}
//Trigger an event to notify other components that a new element has been created, so they can for example initialize select2 on it
targetTable.dispatchEvent(new CustomEvent("collection:elementAdded", {bubbles: true}));
return ret;
}
/**
@@ -121,33 +112,6 @@ export default class extends Controller {
dataTransfer.items.add(file);
rowInput.files = dataTransfer.files;
//Check the file extension and find the corresponding attachment type based on the data-filetype_filter attribute
const attachmentTypeSelect = newElement.querySelector("select");
if (attachmentTypeSelect) {
let foundMatch = false;
for (let j = 0; j < attachmentTypeSelect.options.length; j++) {
const option = attachmentTypeSelect.options[j];
//skip disabled options
if (option.disabled) {
continue;
}
const filter = option.getAttribute('data-filetype_filter');
if (filter) {
if (accept({name: file.name, type: file.type}, filter)) {
attachmentTypeSelect.value = option.value;
foundMatch = true;
break;
}
} else { //If no filter is set, chose this option until we find a better match
if (!foundMatch) {
attachmentTypeSelect.value = option.value;
foundMatch = true;
}
}
}
}
}
});
@@ -225,4 +189,4 @@ export default class extends Controller {
del();
}
}
}
}

View File

@@ -18,7 +18,7 @@ export default class extends Controller {
let settings = {
allowEmptyOption: true,
plugins: ['dropdown_input', this.element.required ? null : 'clear_button'],
plugins: ['dropdown_input'],
searchField: ["name", "description", "category", "footprint"],
valueField: "id",
labelField: "name",

View File

@@ -62,6 +62,6 @@ export default class extends Controller {
element.disabled = true;
}
form.requestSubmit();
form.submit();
}
}
}

View File

@@ -70,6 +70,6 @@ export default class extends Controller {
//Put our decoded Text into the input box
document.getElementById('scan_dialog_input').value = decodedText;
//Submit form
document.getElementById('scan_dialog_form').requestSubmit();
document.getElementById('scan_dialog_form').submit();
}
}
}

View File

@@ -1,27 +0,0 @@
import {Controller} from "@hotwired/stimulus";
import {Modal} from "bootstrap";
export default class extends Controller
{
connect() {
this.element.addEventListener('show.bs.modal', event => this._handleModalOpen(event));
}
_handleModalOpen(event) {
// Button that triggered the modal
const button = event.relatedTarget;
const amountInput = this.element.querySelector('input[name="amount"]');
// Extract info from button attributes
const lotID = button.getAttribute('data-lot-id');
const lotAmount = button.getAttribute('data-lot-amount');
//Find the expected amount field and set the value to the lot amount
const expectedAmountInput = this.element.querySelector('#stocktake-modal-expected-amount');
expectedAmountInput.textContent = lotAmount;
//Set the action and lotID inputs in the form
this.element.querySelector('input[name="lot_id"]').setAttribute('value', lotID);
}
}

View File

@@ -1,81 +0,0 @@
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2025 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Controller } from '@hotwired/stimulus';
/**
* Stimulus controller for update/downgrade confirmation dialogs.
* Intercepts form submission and shows a confirmation dialog before proceeding.
*/
export default class extends Controller {
static values = {
isDowngrade: { type: Boolean, default: false },
targetVersion: { type: String, default: '' },
confirmUpdate: { type: String, default: 'Are you sure you want to update Part-DB?' },
confirmDowngrade: { type: String, default: 'Are you sure you want to downgrade Part-DB?' },
downgradeWarning: { type: String, default: 'WARNING: This version does not include the Update Manager.' },
minUpdateManagerVersion: { type: String, default: '2.6.0' },
};
connect() {
this.element.addEventListener('submit', this.handleSubmit.bind(this));
}
handleSubmit(event) {
// Always prevent default first
event.preventDefault();
const targetClean = this.targetVersionValue.replace(/^v/, '');
let message;
if (this.isDowngradeValue) {
// Check if downgrading to a version without Update Manager
if (this.compareVersions(targetClean, this.minUpdateManagerVersionValue) < 0) {
message = this.confirmDowngradeValue + '\n\n⚠ ' + this.downgradeWarningValue;
} else {
message = this.confirmDowngradeValue;
}
} else {
message = this.confirmUpdateValue;
}
// Only submit if user confirms
if (confirm(message)) {
// Remove the event listener to prevent infinite loop, then submit
this.element.removeEventListener('submit', this.handleSubmit.bind(this));
this.element.submit();
}
}
/**
* Compare two version strings (e.g., "2.5.0" vs "2.6.0")
* Returns -1 if v1 < v2, 0 if equal, 1 if v1 > v2
*/
compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 < p2) return -1;
if (p1 > p2) return 1;
}
return 0;
}
}

View File

@@ -125,25 +125,3 @@ Classes for Datatables export
.export-helper{
display: none;
}
/**********************************************************
* Table row highlighting tools
***********************************************************/
.row-highlight {
box-shadow: 0 4px 15px rgba(0,0,0,0.20); /* Adds depth */
position: relative;
z-index: 1; /* Ensures the shadow overlaps other rows */
border-left: 5px solid var(--bs-primary); /* Adds a vertical accent bar */
}
@keyframes pulse-highlight {
0% { outline: 2px solid transparent; }
50% { outline: 2px solid var(--bs-primary); }
100% { outline: 2px solid transparent; }
}
.row-pulse {
animation: pulse-highlight 1s ease-in-out;
animation-iteration-count: 3;
}

View File

@@ -56,8 +56,7 @@ class TristateHelper {
document.addEventListener("turbo:load", listener);
document.addEventListener("turbo:render", listener);
document.addEventListener("collection:elementAdded", listener);
}
}
export default new TristateHelper();
export default new TristateHelper();

View File

@@ -198,7 +198,6 @@ class WebauthnTFA {
{
const resultField = document.getElementById('_auth_code');
resultField.value = JSON.stringify(data)
//requestSubmit() do not work here, probably because the submit is considered invalid. But as we do not use CSFR tokens, it should be fine.
form.submit();
}
@@ -233,4 +232,4 @@ class WebauthnTFA {
}
}
window.webauthnTFA = new WebauthnTFA();
window.webauthnTFA = new WebauthnTFA();

View File

@@ -11,14 +11,12 @@
"ext-intl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"ext-zip": "*",
"amphp/http-client": "^5.1",
"api-platform/doctrine-orm": "^4.1",
"api-platform/json-api": "^4.0.0",
"api-platform/symfony": "^4.0.0",
"beberlei/doctrineextensions": "^1.2",
"brick/math": "^0.13.1",
"brick/schema": "^0.2.0",
"composer/ca-bundle": "^1.5",
"composer/package-versions-deprecated": "^1.11.99.5",
"doctrine/data-fixtures": "^2.0.0",
@@ -81,7 +79,7 @@
"symfony/string": "7.4.*",
"symfony/translation": "7.4.*",
"symfony/twig-bundle": "7.4.*",
"symfony/type-info": "7.4.*",
"symfony/type-info": "7.4.0",
"symfony/ux-translator": "^2.32.0",
"symfony/ux-turbo": "^2.0",
"symfony/validator": "7.4.*",
@@ -90,7 +88,6 @@
"symfony/yaml": "7.4.*",
"symplify/easy-coding-standard": "^12.5.20",
"tecnickcom/tc-lib-barcode": "^2.1.4",
"tiendanube/gtinvalidation": "^1.0",
"twig/cssinliner-extra": "^3.0",
"twig/extra-bundle": "^3.8",
"twig/html-extra": "^3.8",

1346
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -23,7 +23,3 @@ framework:
info_provider.cache:
adapter: cache.app
cache.settings:
adapter: cache.app
tags: true

View File

@@ -1,4 +1,3 @@
# yaml-language-server: $schema=../../vendor/symfony/dependency-injection/Loader/schema/services.schema.json
# see https://symfony.com/doc/current/reference/configuration/framework.html
framework:
secret: '%env(APP_SECRET)%'
@@ -9,7 +8,6 @@ framework:
# Must be set to true, to enable the change of HTTP method via _method parameter, otherwise our delete routines does not work anymore
# TODO: Rework delete routines to work without _method parameter as it is not recommended anymore (see https://github.com/symfony/symfony/issues/45278)
http_method_override: true
allowed_http_method_override: ['DELETE']
# Allow users to configure trusted hosts via .env variables
# see https://symfony.com/doc/current/reference/configuration/framework.html#trusted-hosts

View File

@@ -3,7 +3,6 @@ jbtronics_settings:
cache:
default_cacheable: true
service: 'cache.settings'
orm_storage:
default_entity_class: App\Entity\SettingsEntry

View File

@@ -68,9 +68,6 @@ perms: # Here comes a list with all Permission names (they have a perm_[name] co
move:
label: "perm.parts_stock.move"
apiTokenRole: ROLE_API_EDIT
stocktake:
label: "perm.parts_stock.stocktake"
apiTokenRole: ROLE_API_EDIT
storelocations: &PART_CONTAINING
@@ -300,10 +297,6 @@ perms: # Here comes a list with all Permission names (they have a perm_[name] co
show_updates:
label: "perm.system.show_available_updates"
apiTokenRole: ROLE_API_ADMIN
manage_updates:
label: "perm.system.manage_updates"
alsoSet: ['show_updates', 'server_infos']
apiTokenRole: ROLE_API_ADMIN
attachments:

File diff suppressed because it is too large Load Diff

View File

@@ -5,5 +5,3 @@ files:
translation: /translations/validators.%two_letters_code%.xlf
- source: /translations/security.en.xlf
translation: /translations/security.%two_letters_code%.xlf
- source: /translations/frontend.en.xlf
translation: /translations/frontend.%two_letters_code%.xlf

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

View File

@@ -50,14 +50,6 @@ docker exec --user=www-data partdb php bin/console cache:clear
* `php bin/console partdb:currencies:update-exchange-rates`: Update the exchange rates of all currencies from the
internet
## Update Manager commands
{: .note }
> The Update Manager is an experimental feature. See the [Update Manager documentation](update_manager.md) for details.
* `php bin/console partdb:update`: Check for and perform updates to Part-DB. Use `--check` to only check for updates without installing.
* `php bin/console partdb:maintenance-mode`: Enable, disable, or check the status of maintenance mode. Use `--enable`, `--disable`, or `--status`.
## Installation/Maintenance commands
* `php bin/console partdb:backup`: Backup the database and the attachments

View File

@@ -96,21 +96,6 @@ The following providers are currently available and shipped with Part-DB:
(All trademarks are property of their respective owners. Part-DB is not affiliated with any of the companies.)
### Generic Web URL Provider
The Generic Web URL Provider can extract part information from any webpage that contains structured data in the form of
[Schema.org](https://schema.org/) format. Many e-commerce websites use this format to provide detailed product information
for search engines and other services. Therefore it allows Part-DB to retrieve rudimentary part information (like name, image and price)
from a wide range of websites without the need for a dedicated API integration.
To use the Generic Web URL Provider, simply enable it in the information provider settings. No additional configuration
is required. Afterwards you can enter any product URL in the search field, and Part-DB will attempt to extract the relevant part information
from the webpage.
Please note that if this provider is enabled, Part-DB will make HTTP requests to external websites to fetch product data, which
may have privacy and security implications.
Following env configuration options are available:
* `PROVIDER_GENERIC_WEB_ENABLED`: Set this to `1` to enable the Generic Web URL Provider (optional, default: `0`)
### Octopart
The Octopart provider uses the [Octopart / Nexar API](https://nexar.com/api) to search for parts and get information.
@@ -293,16 +278,6 @@ The following env configuration options are available:
* `PROVIDER_BUERKLIN_CURRENCY`: The currency you want to get prices in if available (optional, 3 letter ISO-code, default: `EUR`).
* `PROVIDER_BUERKLIN_LANGUAGE`: The language you want to get the descriptions in. Possible values: `de` = German, `en` = English. (optional, default: `en`)
### Conrad
The conrad provider the [Conrad API](https://developer.conrad.com/) to search for parts and retried their information.
To use it you have to request access to the API, however it seems currently your mail address needs to be allowlisted before you can register for an account.
The conrad webpages uses the API key in the requests, so you might be able to extract a working API key by listening to browser requests.
That method is not officially supported nor encouraged by Part-DB, and might break at any moment.
The following env configuration options are available:
* `PROVIDER_CONRAD_API_KEY`: The API key you got from Conrad (mandatory)
### Custom provider
To create a custom provider, you have to create a new class implementing the `InfoProviderInterface` interface. As long

View File

@@ -1,170 +0,0 @@
---
title: Update Manager
layout: default
parent: Usage
---
# Update Manager (Experimental)
{: .warning }
> The Update Manager is currently an **experimental feature**. It is disabled by default while user experience data is being gathered. Use with caution and always ensure you have proper backups before updating.
Part-DB includes an Update Manager that can automatically update Git-based installations to newer versions. The Update Manager provides both a web interface and CLI commands for managing updates, backups, and maintenance mode.
## Supported Installation Types
The Update Manager currently supports automatic updates only for **Git clone** installations. Other installation types show manual update instructions:
| Installation Type | Auto-Update | Instructions |
|-------------------|-------------|--------------|
| Git Clone | Yes | Automatic via CLI or Web UI |
| Docker | No | Pull new image: `docker-compose pull && docker-compose up -d` |
| ZIP Release | No | Download and extract new release manually |
## Enabling the Update Manager
By default, web-based updates and backup restore are **disabled** for security reasons. To enable them, add these settings to your `.env.local` file:
```bash
# Enable web-based updates (default: disabled)
DISABLE_WEB_UPDATES=0
# Enable backup restore via web interface (default: disabled)
DISABLE_BACKUP_RESTORE=0
```
{: .note }
> Even with web updates disabled, you can still use the CLI commands to perform updates.
## CLI Commands
### Update Command
Check for updates or perform an update:
```bash
# Check for available updates
php bin/console partdb:update --check
# Update to the latest version
php bin/console partdb:update
# Update to a specific version
php bin/console partdb:update v2.6.0
# Update without creating a backup first
php bin/console partdb:update --no-backup
# Force update without confirmation prompt
php bin/console partdb:update --force
```
### Maintenance Mode Command
Manually enable or disable maintenance mode:
```bash
# Enable maintenance mode with default message
php bin/console partdb:maintenance-mode --enable
# Enable with custom message
php bin/console partdb:maintenance-mode --enable "System maintenance until 6 PM"
php bin/console partdb:maintenance-mode --enable --message="Updating to v2.6.0"
# Disable maintenance mode
php bin/console partdb:maintenance-mode --disable
# Check current status
php bin/console partdb:maintenance-mode --status
```
## Web Interface
When web updates are enabled, the Update Manager is accessible at **System > Update Manager** (URL: `/system/update-manager`).
The web interface shows:
- Current version and installation type
- Available updates with release notes
- Precondition validation (Git, Composer, Yarn, permissions)
- Update history and logs
- Backup management
### Required Permissions
Users need the following permissions to access the Update Manager:
| Permission | Description |
|------------|-------------|
| `@system.show_updates` | View update status and available versions |
| `@system.manage_updates` | Perform updates and restore backups |
## Update Process
When an update is performed, the following steps are executed:
1. **Lock** - Acquire exclusive lock to prevent concurrent updates
2. **Maintenance Mode** - Enable maintenance mode to block user access
3. **Rollback Tag** - Create a Git tag for potential rollback
4. **Backup** - Create a full backup (optional but recommended)
5. **Git Fetch** - Fetch latest changes from origin
6. **Git Checkout** - Checkout the target version
7. **Composer Install** - Install/update PHP dependencies
8. **Yarn Install** - Install frontend dependencies
9. **Yarn Build** - Compile frontend assets
10. **Database Migrations** - Run any new migrations
11. **Cache Clear** - Clear the application cache
12. **Cache Warmup** - Rebuild the cache
13. **Maintenance Off** - Disable maintenance mode
14. **Unlock** - Release the update lock
If any step fails, the system automatically attempts to rollback to the previous version.
## Backup Management
The Update Manager automatically creates backups before updates. These backups are stored in `var/backups/` and include:
- Database dump (SQL file or SQLite database)
- Configuration files (`.env.local`, `parameters.yaml`, `banner.md`)
- Attachment files (`uploads/`, `public/media/`)
### Restoring from Backup
{: .warning }
> Backup restore is a destructive operation that will overwrite your current database. Only use this if you need to recover from a failed update.
If web restore is enabled (`DISABLE_BACKUP_RESTORE=0`), you can restore backups from the web interface. The restore process:
1. Enables maintenance mode
2. Extracts the backup
3. Restores the database
4. Optionally restores config and attachments
5. Clears and warms up the cache
6. Disables maintenance mode
## Troubleshooting
### Precondition Errors
Before updating, the system validates:
- **Git available**: Git must be installed and in PATH
- **No local changes**: Uncommitted changes must be committed or stashed
- **Composer available**: Composer must be installed and in PATH
- **Yarn available**: Yarn must be installed and in PATH
- **Write permissions**: `var/`, `vendor/`, and `public/` must be writable
- **Not already locked**: No other update can be in progress
### Stale Lock
If an update was interrupted and the lock file remains, it will automatically be removed after 1 hour. You can also manually delete `var/update.lock`.
### Viewing Update Logs
Update logs are stored in `var/log/updates/` and can be viewed from the web interface or directly on the server.
## Security Considerations
- **Disable web updates in production** unless you specifically need them
- The Update Manager requires shell access to run Git, Composer, and Yarn
- Backup files may contain sensitive data (database, config) - secure the `var/backups/` directory
- Consider running updates during maintenance windows with low user activity

91
makefile Normal file
View File

@@ -0,0 +1,91 @@
# PartDB Makefile for Test Environment Management
.PHONY: help deps-install lint format format-check test coverage pre-commit all test-typecheck \
test-setup test-clean test-db-create test-db-migrate test-cache-clear test-fixtures test-run test-reset \
section-dev dev-setup dev-clean dev-db-create dev-db-migrate dev-cache-clear dev-warmup dev-reset
# Default target
help: ## Show this help
@awk 'BEGIN {FS = ":.*##"}; /^[a-zA-Z0-9][a-zA-Z0-9_-]+:.*##/ {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
# Dependencies
deps-install: ## Install PHP dependencies with unlimited memory
@echo "📦 Installing PHP dependencies..."
COMPOSER_MEMORY_LIMIT=-1 composer install
yarn install
@echo "✅ Dependencies installed"
# Complete test environment setup
test-setup: test-clean test-db-create test-db-migrate test-fixtures ## Complete test setup (clean, create DB, migrate, fixtures)
@echo "✅ Test environment setup complete!"
# Clean test environment
test-clean: ## Clean test cache and database files
@echo "🧹 Cleaning test environment..."
rm -rf var/cache/test
rm -f var/app_test.db
@echo "✅ Test environment cleaned"
# Create test database
test-db-create: ## Create test database (if not exists)
@echo "🗄️ Creating test database..."
-php bin/console doctrine:database:create --if-not-exists --env test || echo "⚠️ Database creation failed (expected for SQLite) - continuing..."
# Run database migrations for test environment
test-db-migrate: ## Run database migrations for test environment
@echo "🔄 Running database migrations..."
COMPOSER_MEMORY_LIMIT=-1 php bin/console doctrine:migrations:migrate -n --env test
# Clear test cache
test-cache-clear: ## Clear test cache
@echo "🗑️ Clearing test cache..."
rm -rf var/cache/test
@echo "✅ Test cache cleared"
# Load test fixtures
test-fixtures: ## Load test fixtures
@echo "📦 Loading test fixtures..."
php bin/console partdb:fixtures:load -n --env test
# Run PHPUnit tests
test-run: ## Run PHPUnit tests
@echo "🧪 Running tests..."
php bin/phpunit
# Quick test reset (clean + migrate + fixtures, skip DB creation)
test-reset: test-cache-clear test-db-migrate test-fixtures
@echo "✅ Test environment reset complete!"
test-typecheck: ## Run static analysis (PHPStan)
@echo "🧪 Running type checks..."
COMPOSER_MEMORY_LIMIT=-1 composer phpstan
# Development helpers
dev-setup: dev-clean dev-db-create dev-db-migrate dev-warmup ## Complete development setup (clean, create DB, migrate, warmup)
@echo "✅ Development environment setup complete!"
dev-clean: ## Clean development cache and database files
@echo "🧹 Cleaning development environment..."
rm -rf var/cache/dev
rm -f var/app_dev.db
@echo "✅ Development environment cleaned"
dev-db-create: ## Create development database (if not exists)
@echo "🗄️ Creating development database..."
-php bin/console doctrine:database:create --if-not-exists --env dev || echo "⚠️ Database creation failed (expected for SQLite) - continuing..."
dev-db-migrate: ## Run database migrations for development environment
@echo "🔄 Running database migrations..."
COMPOSER_MEMORY_LIMIT=-1 php bin/console doctrine:migrations:migrate -n --env dev
dev-cache-clear: ## Clear development cache
@echo "🗑️ Clearing development cache..."
rm -rf var/cache/dev
@echo "✅ Development cache cleared"
dev-warmup: ## Warm up development cache
@echo "🔥 Warming up development cache..."
COMPOSER_MEMORY_LIMIT=-1 php -d memory_limit=1G bin/console cache:warmup --env dev -n
dev-reset: dev-cache-clear dev-db-migrate ## Quick development reset (cache clear + migrate)
@echo "✅ Development environment reset complete!"

View File

@@ -1,129 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use App\Migration\AbstractMultiPlatformMigration;
use Doctrine\DBAL\Schema\Schema;
final class Version20260208131116 extends AbstractMultiPlatformMigration
{
public function getDescription(): string
{
return 'Add GTIN fields, allowed targets for attachment types and last stocktake date for part lots and add include_vat field for price details.';
}
public function mySQLUp(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE attachment_types ADD allowed_targets LONGTEXT DEFAULT NULL');
$this->addSql('ALTER TABLE part_lots ADD last_stocktake_at DATETIME DEFAULT NULL');
$this->addSql('ALTER TABLE parts ADD gtin VARCHAR(255) DEFAULT NULL');
$this->addSql('CREATE INDEX parts_idx_gtin ON parts (gtin)');
$this->addSql('ALTER TABLE orderdetails ADD prices_includes_vat TINYINT DEFAULT NULL');
}
public function mySQLDown(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE `attachment_types` DROP allowed_targets');
$this->addSql('DROP INDEX parts_idx_gtin ON `parts`');
$this->addSql('ALTER TABLE `parts` DROP gtin');
$this->addSql('ALTER TABLE part_lots DROP last_stocktake_at');
$this->addSql('ALTER TABLE `orderdetails` DROP prices_includes_vat');
}
public function sqLiteUp(Schema $schema): void
{
$this->addSql('ALTER TABLE attachment_types ADD COLUMN allowed_targets CLOB DEFAULT NULL');
$this->addSql('ALTER TABLE part_lots ADD COLUMN last_stocktake_at DATETIME DEFAULT NULL');
$this->addSql('CREATE TEMPORARY TABLE __temp__parts AS SELECT id, id_preview_attachment, id_category, id_footprint, id_part_unit, id_manufacturer, id_part_custom_state, order_orderdetails_id, built_project_id, datetime_added, name, last_modified, needs_review, tags, mass, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, ipn, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint FROM parts');
$this->addSql('DROP TABLE parts');
$this->addSql('CREATE TABLE parts (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, id_preview_attachment INTEGER DEFAULT NULL, id_category INTEGER NOT NULL, id_footprint INTEGER DEFAULT NULL, id_part_unit INTEGER DEFAULT NULL, id_manufacturer INTEGER DEFAULT NULL, id_part_custom_state INTEGER DEFAULT NULL, order_orderdetails_id INTEGER DEFAULT NULL, built_project_id INTEGER DEFAULT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, needs_review BOOLEAN NOT NULL, tags CLOB NOT NULL, mass DOUBLE PRECISION DEFAULT NULL, description CLOB NOT NULL, comment CLOB NOT NULL, visible BOOLEAN NOT NULL, favorite BOOLEAN NOT NULL, minamount DOUBLE PRECISION NOT NULL, manufacturer_product_url CLOB NOT NULL, manufacturer_product_number VARCHAR(255) NOT NULL, manufacturing_status VARCHAR(255) DEFAULT NULL, order_quantity INTEGER NOT NULL, manual_order BOOLEAN NOT NULL, ipn VARCHAR(100) DEFAULT NULL, provider_reference_provider_key VARCHAR(255) DEFAULT NULL, provider_reference_provider_id VARCHAR(255) DEFAULT NULL, provider_reference_provider_url VARCHAR(2048) DEFAULT NULL, provider_reference_last_updated DATETIME DEFAULT NULL, eda_info_reference_prefix VARCHAR(255) DEFAULT NULL, eda_info_value VARCHAR(255) DEFAULT NULL, eda_info_invisible BOOLEAN DEFAULT NULL, eda_info_exclude_from_bom BOOLEAN DEFAULT NULL, eda_info_exclude_from_board BOOLEAN DEFAULT NULL, eda_info_exclude_from_sim BOOLEAN DEFAULT NULL, eda_info_kicad_symbol VARCHAR(255) DEFAULT NULL, eda_info_kicad_footprint VARCHAR(255) DEFAULT NULL, gtin VARCHAR(255) DEFAULT NULL, CONSTRAINT FK_6940A7FEEA7100A1 FOREIGN KEY (id_preview_attachment) REFERENCES attachments (id) ON UPDATE NO ACTION ON DELETE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE5697F554 FOREIGN KEY (id_category) REFERENCES categories (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE7E371A10 FOREIGN KEY (id_footprint) REFERENCES footprints (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE2626CEF9 FOREIGN KEY (id_part_unit) REFERENCES measurement_units (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE1ECB93AE FOREIGN KEY (id_manufacturer) REFERENCES manufacturers (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FEA3ED1215 FOREIGN KEY (id_part_custom_state) REFERENCES part_custom_states (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE81081E9B FOREIGN KEY (order_orderdetails_id) REFERENCES orderdetails (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FEE8AE70D9 FOREIGN KEY (built_project_id) REFERENCES projects (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('INSERT INTO parts (id, id_preview_attachment, id_category, id_footprint, id_part_unit, id_manufacturer, id_part_custom_state, order_orderdetails_id, built_project_id, datetime_added, name, last_modified, needs_review, tags, mass, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, ipn, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint) SELECT id, id_preview_attachment, id_category, id_footprint, id_part_unit, id_manufacturer, id_part_custom_state, order_orderdetails_id, built_project_id, datetime_added, name, last_modified, needs_review, tags, mass, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, ipn, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint FROM __temp__parts');
$this->addSql('DROP TABLE __temp__parts');
$this->addSql('CREATE INDEX parts_idx_name ON parts (name)');
$this->addSql('CREATE INDEX parts_idx_ipn ON parts (ipn)');
$this->addSql('CREATE INDEX parts_idx_datet_name_last_id_needs ON parts (datetime_added, name, last_modified, id, needs_review)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FEE8AE70D9 ON parts (built_project_id)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FE81081E9B ON parts (order_orderdetails_id)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FE3D721C14 ON parts (ipn)');
$this->addSql('CREATE INDEX IDX_6940A7FEEA7100A1 ON parts (id_preview_attachment)');
$this->addSql('CREATE INDEX IDX_6940A7FE7E371A10 ON parts (id_footprint)');
$this->addSql('CREATE INDEX IDX_6940A7FE5697F554 ON parts (id_category)');
$this->addSql('CREATE INDEX IDX_6940A7FE2626CEF9 ON parts (id_part_unit)');
$this->addSql('CREATE INDEX IDX_6940A7FE1ECB93AE ON parts (id_manufacturer)');
$this->addSql('CREATE INDEX IDX_6940A7FEA3ED1215 ON parts (id_part_custom_state)');
$this->addSql('CREATE INDEX parts_idx_gtin ON parts (gtin)');
$this->addSql('ALTER TABLE orderdetails ADD COLUMN prices_includes_vat BOOLEAN DEFAULT NULL');
}
public function sqLiteDown(Schema $schema): void
{
$this->addSql('CREATE TEMPORARY TABLE __temp__attachment_types AS SELECT id, name, last_modified, datetime_added, comment, not_selectable, alternative_names, filetype_filter, parent_id, id_preview_attachment FROM "attachment_types"');
$this->addSql('DROP TABLE "attachment_types"');
$this->addSql('CREATE TABLE "attachment_types" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, comment CLOB NOT NULL, not_selectable BOOLEAN NOT NULL, alternative_names CLOB DEFAULT NULL, filetype_filter CLOB NOT NULL, parent_id INTEGER DEFAULT NULL, id_preview_attachment INTEGER DEFAULT NULL, CONSTRAINT FK_EFAED719727ACA70 FOREIGN KEY (parent_id) REFERENCES "attachment_types" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_EFAED719EA7100A1 FOREIGN KEY (id_preview_attachment) REFERENCES "attachments" (id) ON DELETE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('INSERT INTO "attachment_types" (id, name, last_modified, datetime_added, comment, not_selectable, alternative_names, filetype_filter, parent_id, id_preview_attachment) SELECT id, name, last_modified, datetime_added, comment, not_selectable, alternative_names, filetype_filter, parent_id, id_preview_attachment FROM __temp__attachment_types');
$this->addSql('DROP TABLE __temp__attachment_types');
$this->addSql('CREATE INDEX IDX_EFAED719727ACA70 ON "attachment_types" (parent_id)');
$this->addSql('CREATE INDEX IDX_EFAED719EA7100A1 ON "attachment_types" (id_preview_attachment)');
$this->addSql('CREATE INDEX attachment_types_idx_name ON "attachment_types" (name)');
$this->addSql('CREATE INDEX attachment_types_idx_parent_name ON "attachment_types" (parent_id, name)');
$this->addSql('CREATE TEMPORARY TABLE __temp__part_lots AS SELECT id, description, comment, expiration_date, instock_unknown, amount, needs_refill, vendor_barcode, last_modified, datetime_added, id_store_location, id_part, id_owner FROM part_lots');
$this->addSql('DROP TABLE part_lots');
$this->addSql('CREATE TABLE part_lots (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, description CLOB NOT NULL, comment CLOB NOT NULL, expiration_date DATETIME DEFAULT NULL, instock_unknown BOOLEAN NOT NULL, amount DOUBLE PRECISION NOT NULL, needs_refill BOOLEAN NOT NULL, vendor_barcode VARCHAR(255) DEFAULT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, id_store_location INTEGER DEFAULT NULL, id_part INTEGER NOT NULL, id_owner INTEGER DEFAULT NULL, CONSTRAINT FK_EBC8F9435D8F4B37 FOREIGN KEY (id_store_location) REFERENCES "storelocations" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_EBC8F943C22F6CC4 FOREIGN KEY (id_part) REFERENCES "parts" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_EBC8F94321E5A74C FOREIGN KEY (id_owner) REFERENCES "users" (id) ON DELETE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('INSERT INTO part_lots (id, description, comment, expiration_date, instock_unknown, amount, needs_refill, vendor_barcode, last_modified, datetime_added, id_store_location, id_part, id_owner) SELECT id, description, comment, expiration_date, instock_unknown, amount, needs_refill, vendor_barcode, last_modified, datetime_added, id_store_location, id_part, id_owner FROM __temp__part_lots');
$this->addSql('DROP TABLE __temp__part_lots');
$this->addSql('CREATE INDEX IDX_EBC8F9435D8F4B37 ON part_lots (id_store_location)');
$this->addSql('CREATE INDEX IDX_EBC8F943C22F6CC4 ON part_lots (id_part)');
$this->addSql('CREATE INDEX IDX_EBC8F94321E5A74C ON part_lots (id_owner)');
$this->addSql('CREATE INDEX part_lots_idx_instock_un_expiration_id_part ON part_lots (instock_unknown, expiration_date, id_part)');
$this->addSql('CREATE INDEX part_lots_idx_needs_refill ON part_lots (needs_refill)');
$this->addSql('CREATE INDEX part_lots_idx_barcode ON part_lots (vendor_barcode)');
$this->addSql('CREATE TEMPORARY TABLE __temp__parts AS SELECT id, name, last_modified, datetime_added, needs_review, tags, mass, ipn, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint, id_preview_attachment, id_part_custom_state, id_category, id_footprint, id_part_unit, id_manufacturer, order_orderdetails_id, built_project_id FROM "parts"');
$this->addSql('DROP TABLE "parts"');
$this->addSql('CREATE TABLE "parts" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, needs_review BOOLEAN NOT NULL, tags CLOB NOT NULL, mass DOUBLE PRECISION DEFAULT NULL, ipn VARCHAR(100) DEFAULT NULL, description CLOB NOT NULL, comment CLOB NOT NULL, visible BOOLEAN NOT NULL, favorite BOOLEAN NOT NULL, minamount DOUBLE PRECISION NOT NULL, manufacturer_product_url CLOB NOT NULL, manufacturer_product_number VARCHAR(255) NOT NULL, manufacturing_status VARCHAR(255) DEFAULT NULL, order_quantity INTEGER NOT NULL, manual_order BOOLEAN NOT NULL, provider_reference_provider_key VARCHAR(255) DEFAULT NULL, provider_reference_provider_id VARCHAR(255) DEFAULT NULL, provider_reference_provider_url VARCHAR(2048) DEFAULT NULL, provider_reference_last_updated DATETIME DEFAULT NULL, eda_info_reference_prefix VARCHAR(255) DEFAULT NULL, eda_info_value VARCHAR(255) DEFAULT NULL, eda_info_invisible BOOLEAN DEFAULT NULL, eda_info_exclude_from_bom BOOLEAN DEFAULT NULL, eda_info_exclude_from_board BOOLEAN DEFAULT NULL, eda_info_exclude_from_sim BOOLEAN DEFAULT NULL, eda_info_kicad_symbol VARCHAR(255) DEFAULT NULL, eda_info_kicad_footprint VARCHAR(255) DEFAULT NULL, id_preview_attachment INTEGER DEFAULT NULL, id_part_custom_state INTEGER DEFAULT NULL, id_category INTEGER NOT NULL, id_footprint INTEGER DEFAULT NULL, id_part_unit INTEGER DEFAULT NULL, id_manufacturer INTEGER DEFAULT NULL, order_orderdetails_id INTEGER DEFAULT NULL, built_project_id INTEGER DEFAULT NULL, CONSTRAINT FK_6940A7FEEA7100A1 FOREIGN KEY (id_preview_attachment) REFERENCES "attachments" (id) ON DELETE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FEA3ED1215 FOREIGN KEY (id_part_custom_state) REFERENCES "part_custom_states" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE5697F554 FOREIGN KEY (id_category) REFERENCES "categories" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE7E371A10 FOREIGN KEY (id_footprint) REFERENCES "footprints" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE2626CEF9 FOREIGN KEY (id_part_unit) REFERENCES "measurement_units" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE1ECB93AE FOREIGN KEY (id_manufacturer) REFERENCES "manufacturers" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FE81081E9B FOREIGN KEY (order_orderdetails_id) REFERENCES "orderdetails" (id) NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_6940A7FEE8AE70D9 FOREIGN KEY (built_project_id) REFERENCES projects (id) NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('INSERT INTO "parts" (id, name, last_modified, datetime_added, needs_review, tags, mass, ipn, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint, id_preview_attachment, id_part_custom_state, id_category, id_footprint, id_part_unit, id_manufacturer, order_orderdetails_id, built_project_id) SELECT id, name, last_modified, datetime_added, needs_review, tags, mass, ipn, description, comment, visible, favorite, minamount, manufacturer_product_url, manufacturer_product_number, manufacturing_status, order_quantity, manual_order, provider_reference_provider_key, provider_reference_provider_id, provider_reference_provider_url, provider_reference_last_updated, eda_info_reference_prefix, eda_info_value, eda_info_invisible, eda_info_exclude_from_bom, eda_info_exclude_from_board, eda_info_exclude_from_sim, eda_info_kicad_symbol, eda_info_kicad_footprint, id_preview_attachment, id_part_custom_state, id_category, id_footprint, id_part_unit, id_manufacturer, order_orderdetails_id, built_project_id FROM __temp__parts');
$this->addSql('DROP TABLE __temp__parts');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FE3D721C14 ON "parts" (ipn)');
$this->addSql('CREATE INDEX IDX_6940A7FEEA7100A1 ON "parts" (id_preview_attachment)');
$this->addSql('CREATE INDEX IDX_6940A7FEA3ED1215 ON "parts" (id_part_custom_state)');
$this->addSql('CREATE INDEX IDX_6940A7FE5697F554 ON "parts" (id_category)');
$this->addSql('CREATE INDEX IDX_6940A7FE7E371A10 ON "parts" (id_footprint)');
$this->addSql('CREATE INDEX IDX_6940A7FE2626CEF9 ON "parts" (id_part_unit)');
$this->addSql('CREATE INDEX IDX_6940A7FE1ECB93AE ON "parts" (id_manufacturer)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FE81081E9B ON "parts" (order_orderdetails_id)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_6940A7FEE8AE70D9 ON "parts" (built_project_id)');
$this->addSql('CREATE INDEX parts_idx_datet_name_last_id_needs ON "parts" (datetime_added, name, last_modified, id, needs_review)');
$this->addSql('CREATE INDEX parts_idx_name ON "parts" (name)');
$this->addSql('CREATE INDEX parts_idx_ipn ON "parts" (ipn)');
$this->addSql('CREATE TEMPORARY TABLE __temp__orderdetails AS SELECT id, supplierpartnr, obsolete, supplier_product_url, last_modified, datetime_added, part_id, id_supplier FROM "orderdetails"');
$this->addSql('DROP TABLE "orderdetails"');
$this->addSql('CREATE TABLE "orderdetails" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, supplierpartnr VARCHAR(255) NOT NULL, obsolete BOOLEAN NOT NULL, supplier_product_url CLOB NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, part_id INTEGER NOT NULL, id_supplier INTEGER DEFAULT NULL, CONSTRAINT FK_489AFCDC4CE34BEC FOREIGN KEY (part_id) REFERENCES "parts" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_489AFCDCCBF180EB FOREIGN KEY (id_supplier) REFERENCES "suppliers" (id) NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('INSERT INTO "orderdetails" (id, supplierpartnr, obsolete, supplier_product_url, last_modified, datetime_added, part_id, id_supplier) SELECT id, supplierpartnr, obsolete, supplier_product_url, last_modified, datetime_added, part_id, id_supplier FROM __temp__orderdetails');
$this->addSql('DROP TABLE __temp__orderdetails');
$this->addSql('CREATE INDEX IDX_489AFCDC4CE34BEC ON "orderdetails" (part_id)');
$this->addSql('CREATE INDEX IDX_489AFCDCCBF180EB ON "orderdetails" (id_supplier)');
$this->addSql('CREATE INDEX orderdetails_supplier_part_nr ON "orderdetails" (supplierpartnr)');
}
public function postgreSQLUp(Schema $schema): void
{
$this->addSql('ALTER TABLE attachment_types ADD allowed_targets TEXT DEFAULT NULL');
$this->addSql('ALTER TABLE part_lots ADD last_stocktake_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL');
$this->addSql('ALTER TABLE parts ADD gtin VARCHAR(255) DEFAULT NULL');
$this->addSql('CREATE INDEX parts_idx_gtin ON parts (gtin)');
$this->addSql('ALTER TABLE orderdetails ADD prices_includes_vat BOOLEAN DEFAULT NULL');
}
public function postgreSQLDown(Schema $schema): void
{
$this->addSql('ALTER TABLE "attachment_types" DROP allowed_targets');
$this->addSql('ALTER TABLE part_lots DROP last_stocktake_at');
$this->addSql('DROP INDEX parts_idx_gtin');
$this->addSql('ALTER TABLE "parts" DROP gtin');
$this->addSql('ALTER TABLE "orderdetails" DROP prices_includes_vat');
}
}

View File

@@ -46,7 +46,6 @@
"@zxcvbn-ts/language-en": "^3.0.1",
"@zxcvbn-ts/language-fr": "^3.0.1",
"@zxcvbn-ts/language-ja": "^3.0.1",
"attr-accept": "^2.2.5",
"barcode-detector": "^3.0.5",
"bootbox": "^6.0.0",
"bootswatch": "^5.1.3",

View File

@@ -6,9 +6,6 @@ parameters:
- src
# - tests
banned_code:
non_ignorable: false # Allow to ignore some banned code
excludePaths:
- src/DataTables/Adapter/*
- src/Configuration/*
@@ -64,9 +61,3 @@ parameters:
# Ignore error of unused WithPermPresetsTrait, as it is used in the migrations which are not analyzed by Phpstan
- '#Trait App\\Migration\\WithPermPresetsTrait is used zero times and is not analysed#'
-
message: '#Should not use function "shell_exec"#'
path: src/Services/System/UpdateExecutor.php
- message: '#Access to an undefined property Brick\\Schema\\Interfaces\\#'
path: src/Services/InfoProviderSystem/Providers/GenericWebProvider.php

View File

@@ -1,141 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Command;
use App\Services\System\UpdateExecutor;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('partdb:maintenance-mode', 'Enable/disable maintenance mode and set a message')]
class MaintenanceModeCommand extends Command
{
public function __construct(
private readonly UpdateExecutor $updateExecutor
) {
parent::__construct();
}
protected function configure(): void
{
$this
->setDefinition([
new InputOption('enable', null, InputOption::VALUE_NONE, 'Enable maintenance mode'),
new InputOption('disable', null, InputOption::VALUE_NONE, 'Disable maintenance mode'),
new InputOption('status', null, InputOption::VALUE_NONE, 'Show current maintenance mode status'),
new InputOption('message', null, InputOption::VALUE_REQUIRED, 'Optional maintenance message (explicit option)'),
new InputArgument('message_arg', InputArgument::OPTIONAL, 'Optional maintenance message as a positional argument (preferred when writing message directly)')
]);
}
public function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$enable = (bool)$input->getOption('enable');
$disable = (bool)$input->getOption('disable');
$status = (bool)$input->getOption('status');
// Accept message either via --message option or as positional argument
$optionMessage = $input->getOption('message');
$argumentMessage = $input->getArgument('message_arg');
// Prefer explicit --message option, otherwise use positional argument if provided
$message = null;
if (is_string($optionMessage) && $optionMessage !== '') {
$message = $optionMessage;
} elseif (is_string($argumentMessage) && $argumentMessage !== '') {
$message = $argumentMessage;
}
// If no action provided, show help
if (!$enable && !$disable && !$status) {
$io->text('Maintenance mode command. See usage below:');
$this->printHelp($io);
return Command::SUCCESS;
}
if ($enable && $disable) {
$io->error('Conflicting options: specify either --enable or --disable, not both.');
return Command::FAILURE;
}
try {
if ($status) {
if ($this->updateExecutor->isMaintenanceMode()) {
$info = $this->updateExecutor->getMaintenanceInfo();
$reason = $info['reason'] ?? 'Unknown reason';
$enabledAt = $info['enabled_at'] ?? 'Unknown time';
$io->success(sprintf('Maintenance mode is ENABLED (since %s).', $enabledAt));
$io->text(sprintf('Reason: %s', $reason));
} else {
$io->success('Maintenance mode is DISABLED.');
}
// If only status requested, exit
if (!$enable && !$disable) {
return Command::SUCCESS;
}
}
if ($enable) {
// Use provided message or fallback to a default English message
$reason = is_string($message)
? $message
: 'The system is temporarily unavailable due to maintenance.';
$this->updateExecutor->enableMaintenanceMode($reason);
$io->success(sprintf('Maintenance mode enabled. Reason: %s', $reason));
}
if ($disable) {
$this->updateExecutor->disableMaintenanceMode();
$io->success('Maintenance mode disabled.');
}
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error(sprintf('Unexpected error: %s', $e->getMessage()));
return Command::FAILURE;
}
}
private function printHelp(SymfonyStyle $io): void
{
$io->writeln('');
$io->writeln('Usage:');
$io->writeln(' php bin/console partdb:maintenance_mode --enable [--message="Maintenance message"]');
$io->writeln(' php bin/console partdb:maintenance_mode --enable "Maintenance message"');
$io->writeln(' php bin/console partdb:maintenance_mode --disable');
$io->writeln(' php bin/console partdb:maintenance_mode --status');
$io->writeln('');
}
}

View File

@@ -1,445 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Command;
use App\Services\System\UpdateChecker;
use App\Services\System\UpdateExecutor;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'partdb:update', description: 'Check for and install Part-DB updates', aliases: ['app:update'])]
class UpdateCommand extends Command
{
public function __construct(private readonly UpdateChecker $updateChecker,
private readonly UpdateExecutor $updateExecutor)
{
parent::__construct();
}
protected function configure(): void
{
$this
->setHelp(<<<'HELP'
The <info>%command.name%</info> command checks for Part-DB updates and can install them.
<comment>Check for updates:</comment>
<info>php %command.full_name% --check</info>
<comment>List available versions:</comment>
<info>php %command.full_name% --list</info>
<comment>Update to the latest version:</comment>
<info>php %command.full_name%</info>
<comment>Update to a specific version:</comment>
<info>php %command.full_name% v2.6.0</info>
<comment>Update without creating a backup (faster but riskier):</comment>
<info>php %command.full_name% --no-backup</info>
<comment>Non-interactive update for scripts:</comment>
<info>php %command.full_name% --force</info>
<comment>View update logs:</comment>
<info>php %command.full_name% --logs</info>
HELP
)
->addArgument(
'version',
InputArgument::OPTIONAL,
'Target version to update to (e.g., v2.6.0). If not specified, updates to the latest stable version.'
)
->addOption(
'check',
'c',
InputOption::VALUE_NONE,
'Only check for updates without installing'
)
->addOption(
'list',
'l',
InputOption::VALUE_NONE,
'List all available versions'
)
->addOption(
'no-backup',
null,
InputOption::VALUE_NONE,
'Skip creating a backup before updating (not recommended)'
)
->addOption(
'force',
'f',
InputOption::VALUE_NONE,
'Skip confirmation prompts'
)
->addOption(
'include-prerelease',
null,
InputOption::VALUE_NONE,
'Include pre-release versions'
)
->addOption(
'logs',
null,
InputOption::VALUE_NONE,
'Show recent update logs'
)
->addOption(
'refresh',
'r',
InputOption::VALUE_NONE,
'Force refresh of cached version information'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
// Handle --logs option
if ($input->getOption('logs')) {
return $this->showLogs($io);
}
// Handle --refresh option
if ($input->getOption('refresh')) {
$io->text('Refreshing version information...');
$this->updateChecker->refreshVersionInfo();
$io->success('Version cache cleared.');
}
// Handle --list option
if ($input->getOption('list')) {
return $this->listVersions($io, $input->getOption('include-prerelease'));
}
// Get update status
$status = $this->updateChecker->getUpdateStatus();
// Display current status
$io->title('Part-DB Update Manager');
$this->displayStatus($io, $status);
// Handle --check option
if ($input->getOption('check')) {
return $this->checkOnly($io, $status);
}
// Validate we can update
$validationResult = $this->validateUpdate($io, $status);
if ($validationResult !== null) {
return $validationResult;
}
// Determine target version
$targetVersion = $input->getArgument('version');
$includePrerelease = $input->getOption('include-prerelease');
if (!$targetVersion) {
$latest = $this->updateChecker->getLatestVersion($includePrerelease);
if (!$latest) {
$io->error('Could not determine the latest version. Please specify a version manually.');
return Command::FAILURE;
}
$targetVersion = $latest['tag'];
}
// Validate target version
if (!$this->updateChecker->isNewerVersionThanCurrent($targetVersion)) {
$io->warning(sprintf(
'Version %s is not newer than the current version %s.',
$targetVersion,
$status['current_version']
));
if (!$input->getOption('force')) {
if (!$io->confirm('Do you want to proceed anyway?', false)) {
$io->info('Update cancelled.');
return Command::SUCCESS;
}
}
}
// Confirm update
if (!$input->getOption('force')) {
$io->section('Update Plan');
$io->listing([
sprintf('Target version: <info>%s</info>', $targetVersion),
$input->getOption('no-backup')
? '<fg=yellow>Backup will be SKIPPED</>'
: 'A full backup will be created before updating',
'Maintenance mode will be enabled during update',
'Database migrations will be run automatically',
'Cache will be cleared and rebuilt',
]);
$io->warning('The update process may take several minutes. Do not interrupt it.');
if (!$io->confirm('Do you want to proceed with the update?', false)) {
$io->info('Update cancelled.');
return Command::SUCCESS;
}
}
// Execute update
return $this->executeUpdate($io, $targetVersion, !$input->getOption('no-backup'));
}
private function displayStatus(SymfonyStyle $io, array $status): void
{
$io->definitionList(
['Current Version' => sprintf('<info>%s</info>', $status['current_version'])],
['Latest Version' => $status['latest_version']
? sprintf('<info>%s</info>', $status['latest_version'])
: '<fg=yellow>Unknown</>'],
['Installation Type' => $status['installation']['type_name']],
['Git Branch' => $status['git']['branch'] ?? '<fg=gray>N/A</>'],
['Git Commit' => $status['git']['commit'] ?? '<fg=gray>N/A</>'],
['Local Changes' => $status['git']['has_local_changes']
? '<fg=yellow>Yes (update blocked)</>'
: '<fg=green>No</>'],
['Commits Behind' => $status['git']['commits_behind'] > 0
? sprintf('<fg=yellow>%d</>', $status['git']['commits_behind'])
: '<fg=green>0</>'],
['Update Available' => $status['update_available']
? '<fg=green>Yes</>'
: 'No'],
['Can Auto-Update' => $status['can_auto_update']
? '<fg=green>Yes</>'
: '<fg=yellow>No</>'],
);
if (!empty($status['update_blockers'])) {
$io->warning('Update blockers: ' . implode(', ', $status['update_blockers']));
}
}
private function checkOnly(SymfonyStyle $io, array $status): int
{
if (!$status['check_enabled']) {
$io->warning('Update checking is disabled in privacy settings.');
return Command::SUCCESS;
}
if ($status['update_available']) {
$io->success(sprintf(
'A new version is available: %s (current: %s)',
$status['latest_version'],
$status['current_version']
));
if ($status['release_url']) {
$io->text(sprintf('Release notes: <href=%s>%s</>', $status['release_url'], $status['release_url']));
}
if ($status['can_auto_update']) {
$io->text('');
$io->text('Run <info>php bin/console partdb:update</info> to update.');
} else {
$io->text('');
$io->text($status['installation']['update_instructions']);
}
return Command::SUCCESS;
}
$io->success('You are running the latest version.');
return Command::SUCCESS;
}
private function validateUpdate(SymfonyStyle $io, array $status): ?int
{
// Check if update checking is enabled
if (!$status['check_enabled']) {
$io->error('Update checking is disabled in privacy settings. Enable it to use automatic updates.');
return Command::FAILURE;
}
// Check installation type
if (!$status['can_auto_update']) {
$io->error('Automatic updates are not supported for this installation type.');
$io->text($status['installation']['update_instructions']);
return Command::FAILURE;
}
// Validate preconditions
$validation = $this->updateExecutor->validateUpdatePreconditions();
if (!$validation['valid']) {
$io->error('Cannot proceed with update:');
$io->listing($validation['errors']);
return Command::FAILURE;
}
return null;
}
private function executeUpdate(SymfonyStyle $io, string $targetVersion, bool $createBackup): int
{
$io->section('Executing Update');
$io->text(sprintf('Updating to version: <info>%s</info>', $targetVersion));
$io->text('');
$progressCallback = function (array $step) use ($io): void {
$icon = $step['success'] ? '<fg=green>✓</>' : '<fg=red>✗</>';
$duration = $step['duration'] ? sprintf(' <fg=gray>(%.1fs)</>', $step['duration']) : '';
$io->text(sprintf(' %s <info>%s</info>: %s%s', $icon, $step['step'], $step['message'], $duration));
};
// Use executeUpdateWithProgress to update the progress file for web UI
$result = $this->updateExecutor->executeUpdateWithProgress($targetVersion, $createBackup, $progressCallback);
$io->text('');
if ($result['success']) {
$io->success(sprintf(
'Successfully updated to %s in %.1f seconds!',
$targetVersion,
$result['duration']
));
$io->text([
sprintf('Rollback tag: <info>%s</info>', $result['rollback_tag']),
sprintf('Log file: <info>%s</info>', $result['log_file']),
]);
$io->note('If you encounter any issues, you can rollback using: git checkout ' . $result['rollback_tag']);
return Command::SUCCESS;
}
$io->error('Update failed: ' . $result['error']);
if ($result['rollback_tag']) {
$io->warning(sprintf('System was rolled back to: %s', $result['rollback_tag']));
}
if ($result['log_file']) {
$io->text(sprintf('See log file for details: %s', $result['log_file']));
}
return Command::FAILURE;
}
private function listVersions(SymfonyStyle $io, bool $includePrerelease): int
{
$releases = $this->updateChecker->getAvailableReleases(15);
$currentVersion = $this->updateChecker->getCurrentVersionString();
if (empty($releases)) {
$io->warning('Could not fetch available versions. Check your internet connection.');
return Command::FAILURE;
}
$io->title('Available Part-DB Versions');
$table = new Table($io);
$table->setHeaders(['Tag', 'Version', 'Released', 'Status']);
foreach ($releases as $release) {
if (!$includePrerelease && $release['prerelease']) {
continue;
}
$version = $release['version'];
$status = [];
if (version_compare($version, $currentVersion, '=')) {
$status[] = '<fg=cyan>current</>';
} elseif (version_compare($version, $currentVersion, '>')) {
$status[] = '<fg=green>newer</>';
}
if ($release['prerelease']) {
$status[] = '<fg=yellow>pre-release</>';
}
$table->addRow([
$release['tag'],
$version,
(new \DateTime($release['published_at']))->format('Y-m-d'),
implode(' ', $status) ?: '-',
]);
}
$table->render();
$io->text('');
$io->text('Use <info>php bin/console partdb:update [tag]</info> to update to a specific version.');
return Command::SUCCESS;
}
private function showLogs(SymfonyStyle $io): int
{
$logs = $this->updateExecutor->getUpdateLogs();
if (empty($logs)) {
$io->info('No update logs found.');
return Command::SUCCESS;
}
$io->title('Recent Update Logs');
$table = new Table($io);
$table->setHeaders(['Date', 'File', 'Size']);
foreach (array_slice($logs, 0, 10) as $log) {
$table->addRow([
date('Y-m-d H:i:s', $log['date']),
$log['file'],
$this->formatBytes($log['size']),
]);
}
$table->render();
$io->text('');
$io->text('Log files are stored in: <info>var/log/updates/</info>');
return Command::SUCCESS;
}
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$unitIndex = 0;
while ($bytes >= 1024 && $unitIndex < count($units) - 1) {
$bytes /= 1024;
$unitIndex++;
}
return sprintf('%.1f %s', $bytes, $units[$unitIndex]);
}
}

View File

@@ -22,9 +22,9 @@ declare(strict_types=1);
*/
namespace App\Command;
use App\Services\System\GitVersionInfoProvider;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use App\Services\Misc\GitVersionInfo;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -33,7 +33,7 @@ use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('partdb:version|app:version', 'Shows the currently installed version of Part-DB.')]
class VersionCommand extends Command
{
public function __construct(protected VersionManagerInterface $versionManager, protected GitVersionInfoProvider $gitVersionInfo)
public function __construct(protected VersionManagerInterface $versionManager, protected GitVersionInfo $gitVersionInfo)
{
parent::__construct();
}
@@ -48,9 +48,9 @@ class VersionCommand extends Command
$message = 'Part-DB version: '. $this->versionManager->getVersion()->toString();
if ($this->gitVersionInfo->getBranchName() !== null) {
$message .= ' Git branch: '. $this->gitVersionInfo->getBranchName();
$message .= ', Git commit: '. $this->gitVersionInfo->getCommitHash();
if ($this->gitVersionInfo->getGitBranchName() !== null) {
$message .= ' Git branch: '. $this->gitVersionInfo->getGitBranchName();
$message .= ', Git commit: '. $this->gitVersionInfo->getGitCommitHash();
}
$io->success($message);

View File

@@ -24,9 +24,9 @@ namespace App\Controller;
use App\DataTables\LogDataTable;
use App\Entity\Parts\Part;
use App\Services\Misc\GitVersionInfo;
use App\Services\System\BannerHelper;
use App\Services\System\GitVersionInfoProvider;
use App\Services\System\UpdateAvailableFacade;
use App\Services\System\UpdateAvailableManager;
use Doctrine\ORM\EntityManagerInterface;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -43,8 +43,8 @@ class HomepageController extends AbstractController
#[Route(path: '/', name: 'homepage')]
public function homepage(Request $request, GitVersionInfoProvider $versionInfo, EntityManagerInterface $entityManager,
UpdateAvailableFacade $updateAvailableManager): Response
public function homepage(Request $request, GitVersionInfo $versionInfo, EntityManagerInterface $entityManager,
UpdateAvailableManager $updateAvailableManager): Response
{
$this->denyAccessUnlessGranted('HAS_ACCESS_PERMISSIONS');
@@ -77,8 +77,8 @@ class HomepageController extends AbstractController
return $this->render('homepage.html.twig', [
'banner' => $this->bannerHelper->getBanner(),
'git_branch' => $versionInfo->getBranchName(),
'git_commit' => $versionInfo->getCommitHash(),
'git_branch' => $versionInfo->getGitBranchName(),
'git_commit' => $versionInfo->getGitCommitHash(),
'show_first_steps' => $show_first_steps,
'datatable' => $table,
'new_version_available' => $updateAvailableManager->isUpdateAvailable(),

View File

@@ -30,7 +30,6 @@ use App\Form\InfoProviderSystem\PartSearchType;
use App\Services\InfoProviderSystem\ExistingPartFinder;
use App\Services\InfoProviderSystem\PartInfoRetriever;
use App\Services\InfoProviderSystem\ProviderRegistry;
use App\Services\InfoProviderSystem\Providers\GenericWebProvider;
use App\Settings\AppSettings;
use App\Settings\InfoProviderSystem\InfoProviderGeneralSettings;
use Doctrine\ORM\EntityManagerInterface;
@@ -40,15 +39,11 @@ use Psr\Log\LoggerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use function Symfony\Component\Translation\t;
#[Route('/tools/info_providers')]
@@ -183,13 +178,6 @@ class InfoProviderController extends AbstractController
$exceptionLogger->error('Error during info provider search: ' . $e->getMessage(), ['exception' => $e]);
} catch (OAuthReconnectRequiredException $e) {
$this->addFlash('error', t('info_providers.search.error.oauth_reconnect', ['%provider%' => $e->getProviderName()]));
} catch (TransportException $e) {
$this->addFlash('error', t('info_providers.search.error.transport_exception'));
$exceptionLogger->error('Transport error during info provider search: ' . $e->getMessage(), ['exception' => $e]);
} catch (\RuntimeException $e) {
$this->addFlash('error', t('info_providers.search.error.general_exception', ['%type%' => (new \ReflectionClass($e))->getShortName()]));
//Log the exception
$exceptionLogger->error('Error during info provider search: ' . $e->getMessage(), ['exception' => $e]);
}
@@ -210,58 +198,4 @@ class InfoProviderController extends AbstractController
'update_target' => $update_target
]);
}
#[Route('/from_url', name: 'info_providers_from_url')]
public function fromURL(Request $request, GenericWebProvider $provider): Response
{
$this->denyAccessUnlessGranted('@info_providers.create_parts');
if (!$provider->isActive()) {
$this->addFlash('error', "Generic Web Provider is not active. Please enable it in the provider settings.");
return $this->redirectToRoute('info_providers_list');
}
$formBuilder = $this->createFormBuilder();
$formBuilder->add('url', UrlType::class, [
'label' => 'info_providers.from_url.url.label',
'required' => true,
]);
$formBuilder->add('submit', SubmitType::class, [
'label' => 'info_providers.search.submit',
]);
$form = $formBuilder->getForm();
$form->handleRequest($request);
$partDetail = null;
if ($form->isSubmitted() && $form->isValid()) {
//Try to retrieve the part detail from the given URL
$url = $form->get('url')->getData();
try {
$searchResult = $this->infoRetriever->searchByKeyword(
keyword: $url,
providers: [$provider]
);
if (count($searchResult) === 0) {
$this->addFlash('warning', t('info_providers.from_url.no_part_found'));
} else {
$searchResult = $searchResult[0];
//Redirect to the part creation page with the found part detail
return $this->redirectToRoute('info_providers_create_part', [
'providerKey' => $searchResult->provider_key,
'providerId' => $searchResult->provider_id,
]);
}
} catch (ExceptionInterface $e) {
$this->addFlash('error', t('info_providers.search.error.general_exception', ['%type%' => (new \ReflectionClass($e))->getShortName()]));
}
}
return $this->render('info_providers/from_url/from_url.html.twig', [
'form' => $form,
'partDetail' => $partDetail,
]);
}
}

View File

@@ -54,14 +54,12 @@ use Exception;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
use Symfony\Contracts\Translation\TranslatorInterface;
use function Symfony\Component\Translation\t;
@@ -137,7 +135,6 @@ final class PartController extends AbstractController
'description_params' => $this->partInfoSettings->extractParamsFromDescription ? $parameterExtractor->extractParameters($part->getDescription()) : [],
'comment_params' => $this->partInfoSettings->extractParamsFromNotes ? $parameterExtractor->extractParameters($part->getComment()) : [],
'withdraw_add_helper' => $withdrawAddHelper,
'highlightLotId' => $request->query->getInt('highlightLot', 0),
]
);
}
@@ -465,54 +462,6 @@ final class PartController extends AbstractController
);
}
#[Route(path: '/{id}/stocktake', name: 'part_stocktake', methods: ['POST'])]
#[IsCsrfTokenValid(new Expression("'part_stocktake-' ~ args['part'].getid()"), '_token')]
public function stocktakeHandler(Part $part, EntityManagerInterface $em, PartLotWithdrawAddHelper $withdrawAddHelper,
Request $request,
): Response
{
$partLot = $em->find(PartLot::class, $request->request->get('lot_id'));
//Check that the user is allowed to stocktake the partlot
$this->denyAccessUnlessGranted('stocktake', $partLot);
if (!$partLot instanceof PartLot) {
throw new \RuntimeException('Part lot not found!');
}
//Ensure that the partlot belongs to the part
if ($partLot->getPart() !== $part) {
throw new \RuntimeException("The origin partlot does not belong to the part!");
}
$actualAmount = (float) $request->request->get('actual_amount');
$comment = $request->request->get('comment');
$timestamp = null;
$timestamp_str = $request->request->getString('timestamp', '');
//Try to parse the timestamp
if ($timestamp_str !== '') {
$timestamp = new DateTime($timestamp_str);
}
$withdrawAddHelper->stocktake($partLot, $actualAmount, $comment, $timestamp);
//Ensure that the timestamp is not in the future
if ($timestamp !== null && $timestamp > new DateTime("+20min")) {
throw new \LogicException("The timestamp must not be in the future!");
}
//Save the changes to the DB
$em->flush();
$this->addFlash('success', 'part.withdraw.success');
//If a redirect was passed, then redirect there
if ($request->request->get('_redirect')) {
return $this->redirect($request->request->get('_redirect'));
}
//Otherwise just redirect to the part page
return $this->redirectToRoute('part_info', ['id' => $part->getID()]);
}
#[Route(path: '/{id}/add_withdraw', name: 'part_add_withdraw', methods: ['POST'])]
public function withdrawAddHandler(Part $part, Request $request, EntityManagerInterface $em, PartLotWithdrawAddHelper $withdrawAddHelper): Response
{

View File

@@ -27,8 +27,8 @@ use App\Services\Attachments\AttachmentURLGenerator;
use App\Services\Attachments\BuiltinAttachmentsFinder;
use App\Services\Doctrine\DBInfoHelper;
use App\Services\Doctrine\NatsortDebugHelper;
use App\Services\System\GitVersionInfoProvider;
use App\Services\System\UpdateAvailableFacade;
use App\Services\Misc\GitVersionInfo;
use App\Services\System\UpdateAvailableManager;
use App\Settings\AppSettings;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
@@ -47,16 +47,16 @@ class ToolsController extends AbstractController
}
#[Route(path: '/server_infos', name: 'tools_server_infos')]
public function systemInfos(GitVersionInfoProvider $versionInfo, DBInfoHelper $DBInfoHelper, NatsortDebugHelper $natsortDebugHelper,
AttachmentSubmitHandler $attachmentSubmitHandler, UpdateAvailableFacade $updateAvailableManager,
public function systemInfos(GitVersionInfo $versionInfo, DBInfoHelper $DBInfoHelper, NatsortDebugHelper $natsortDebugHelper,
AttachmentSubmitHandler $attachmentSubmitHandler, UpdateAvailableManager $updateAvailableManager,
AppSettings $settings): Response
{
$this->denyAccessUnlessGranted('@system.server_infos');
return $this->render('tools/server_infos/server_infos.html.twig', [
//Part-DB section
'git_branch' => $versionInfo->getBranchName(),
'git_commit' => $versionInfo->getCommitHash(),
'git_branch' => $versionInfo->getGitBranchName(),
'git_commit' => $versionInfo->getGitCommitHash(),
'default_locale' => $settings->system->localization->locale,
'default_timezone' => $settings->system->localization->timezone,
'default_currency' => $settings->system->localization->baseCurrency,

View File

@@ -1,371 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Controller;
use App\Services\System\BackupManager;
use App\Services\System\UpdateChecker;
use App\Services\System\UpdateExecutor;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Attribute\Route;
/**
* Controller for the Update Manager web interface.
*
* This provides a read-only view of update status and instructions.
* Actual updates should be performed via the CLI command for safety.
*/
#[Route('/system/update-manager')]
class UpdateManagerController extends AbstractController
{
public function __construct(
private readonly UpdateChecker $updateChecker,
private readonly UpdateExecutor $updateExecutor,
private readonly VersionManagerInterface $versionManager,
private readonly BackupManager $backupManager,
#[Autowire(env: 'bool:DISABLE_WEB_UPDATES')]
private readonly bool $webUpdatesDisabled = false,
#[Autowire(env: 'bool:DISABLE_BACKUP_RESTORE')]
private readonly bool $backupRestoreDisabled = false,
) {
}
/**
* Check if web updates are disabled and throw exception if so.
*/
private function denyIfWebUpdatesDisabled(): void
{
if ($this->webUpdatesDisabled) {
throw new AccessDeniedHttpException('Web-based updates are disabled by server configuration. Please use the CLI command instead.');
}
}
/**
* Check if backup restore is disabled and throw exception if so.
*/
private function denyIfBackupRestoreDisabled(): void
{
if ($this->backupRestoreDisabled) {
throw new AccessDeniedHttpException('Backup restore is disabled by server configuration.');
}
}
/**
* Main update manager page.
*/
#[Route('', name: 'admin_update_manager', methods: ['GET'])]
public function index(): Response
{
$this->denyAccessUnlessGranted('@system.show_updates');
$status = $this->updateChecker->getUpdateStatus();
$availableUpdates = $this->updateChecker->getAvailableUpdates();
$validation = $this->updateExecutor->validateUpdatePreconditions();
return $this->render('admin/update_manager/index.html.twig', [
'status' => $status,
'available_updates' => $availableUpdates,
'all_releases' => $this->updateChecker->getAvailableReleases(10),
'validation' => $validation,
'is_locked' => $this->updateExecutor->isLocked(),
'lock_info' => $this->updateExecutor->getLockInfo(),
'is_maintenance' => $this->updateExecutor->isMaintenanceMode(),
'maintenance_info' => $this->updateExecutor->getMaintenanceInfo(),
'update_logs' => $this->updateExecutor->getUpdateLogs(),
'backups' => $this->backupManager->getBackups(),
'web_updates_disabled' => $this->webUpdatesDisabled,
'backup_restore_disabled' => $this->backupRestoreDisabled,
]);
}
/**
* AJAX endpoint to check update status.
*/
#[Route('/status', name: 'admin_update_manager_status', methods: ['GET'])]
public function status(): JsonResponse
{
$this->denyAccessUnlessGranted('@system.show_updates');
return $this->json([
'status' => $this->updateChecker->getUpdateStatus(),
'is_locked' => $this->updateExecutor->isLocked(),
'is_maintenance' => $this->updateExecutor->isMaintenanceMode(),
'lock_info' => $this->updateExecutor->getLockInfo(),
]);
}
/**
* AJAX endpoint to refresh version information.
*/
#[Route('/refresh', name: 'admin_update_manager_refresh', methods: ['POST'])]
public function refresh(Request $request): JsonResponse
{
$this->denyAccessUnlessGranted('@system.show_updates');
// Validate CSRF token
if (!$this->isCsrfTokenValid('update_manager_refresh', $request->request->get('_token'))) {
return $this->json(['error' => 'Invalid CSRF token'], Response::HTTP_FORBIDDEN);
}
$this->updateChecker->refreshVersionInfo();
return $this->json([
'success' => true,
'status' => $this->updateChecker->getUpdateStatus(),
]);
}
/**
* View release notes for a specific version.
*/
#[Route('/release/{tag}', name: 'admin_update_manager_release', methods: ['GET'])]
public function releaseNotes(string $tag): Response
{
$this->denyAccessUnlessGranted('@system.show_updates');
$releases = $this->updateChecker->getAvailableReleases(20);
$release = null;
foreach ($releases as $r) {
if ($r['tag'] === $tag) {
$release = $r;
break;
}
}
if (!$release) {
throw $this->createNotFoundException('Release not found');
}
return $this->render('admin/update_manager/release_notes.html.twig', [
'release' => $release,
'current_version' => $this->updateChecker->getCurrentVersionString(),
]);
}
/**
* View an update log file.
*/
#[Route('/log/{filename}', name: 'admin_update_manager_log', methods: ['GET'])]
public function viewLog(string $filename): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
// Security: Only allow viewing files from the update logs directory
$logs = $this->updateExecutor->getUpdateLogs();
$logPath = null;
foreach ($logs as $log) {
if ($log['file'] === $filename) {
$logPath = $log['path'];
break;
}
}
if (!$logPath || !file_exists($logPath)) {
throw $this->createNotFoundException('Log file not found');
}
$content = file_get_contents($logPath);
return $this->render('admin/update_manager/log_viewer.html.twig', [
'filename' => $filename,
'content' => $content,
]);
}
/**
* Start an update process.
*/
#[Route('/start', name: 'admin_update_manager_start', methods: ['POST'])]
public function startUpdate(Request $request): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
$this->denyIfWebUpdatesDisabled();
// Validate CSRF token
if (!$this->isCsrfTokenValid('update_manager_start', $request->request->get('_token'))) {
$this->addFlash('error', 'Invalid CSRF token');
return $this->redirectToRoute('admin_update_manager');
}
// Check if update is already running
if ($this->updateExecutor->isLocked() || $this->updateExecutor->isUpdateRunning()) {
$this->addFlash('error', 'An update is already in progress.');
return $this->redirectToRoute('admin_update_manager');
}
$targetVersion = $request->request->get('version');
$createBackup = $request->request->getBoolean('backup', true);
if (!$targetVersion) {
// Get latest version if not specified
$latest = $this->updateChecker->getLatestVersion();
if (!$latest) {
$this->addFlash('error', 'Could not determine target version.');
return $this->redirectToRoute('admin_update_manager');
}
$targetVersion = $latest['tag'];
}
// Validate preconditions
$validation = $this->updateExecutor->validateUpdatePreconditions();
if (!$validation['valid']) {
$this->addFlash('error', implode(' ', $validation['errors']));
return $this->redirectToRoute('admin_update_manager');
}
// Start the background update
$pid = $this->updateExecutor->startBackgroundUpdate($targetVersion, $createBackup);
if (!$pid) {
$this->addFlash('error', 'Failed to start update process.');
return $this->redirectToRoute('admin_update_manager');
}
// Redirect to progress page
return $this->redirectToRoute('admin_update_manager_progress');
}
/**
* Update progress page.
*/
#[Route('/progress', name: 'admin_update_manager_progress', methods: ['GET'])]
public function progress(): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
$progress = $this->updateExecutor->getProgress();
$currentVersion = $this->versionManager->getVersion()->toString();
// Determine if this is a downgrade
$isDowngrade = false;
if ($progress && isset($progress['target_version'])) {
$targetVersion = ltrim($progress['target_version'], 'v');
$isDowngrade = version_compare($targetVersion, $currentVersion, '<');
}
return $this->render('admin/update_manager/progress.html.twig', [
'progress' => $progress,
'is_locked' => $this->updateExecutor->isLocked(),
'is_maintenance' => $this->updateExecutor->isMaintenanceMode(),
'is_downgrade' => $isDowngrade,
'current_version' => $currentVersion,
]);
}
/**
* AJAX endpoint to get update progress.
*/
#[Route('/progress/status', name: 'admin_update_manager_progress_status', methods: ['GET'])]
public function progressStatus(): JsonResponse
{
$this->denyAccessUnlessGranted('@system.show_updates');
$progress = $this->updateExecutor->getProgress();
return $this->json([
'progress' => $progress,
'is_locked' => $this->updateExecutor->isLocked(),
'is_maintenance' => $this->updateExecutor->isMaintenanceMode(),
]);
}
/**
* Get backup details for restore confirmation.
*/
#[Route('/backup/{filename}', name: 'admin_update_manager_backup_details', methods: ['GET'])]
public function backupDetails(string $filename): JsonResponse
{
$this->denyAccessUnlessGranted('@system.manage_updates');
$details = $this->backupManager->getBackupDetails($filename);
if (!$details) {
return $this->json(['error' => 'Backup not found'], 404);
}
return $this->json($details);
}
/**
* Restore from a backup.
*/
#[Route('/restore', name: 'admin_update_manager_restore', methods: ['POST'])]
public function restore(Request $request): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
$this->denyIfBackupRestoreDisabled();
// Validate CSRF token
if (!$this->isCsrfTokenValid('update_manager_restore', $request->request->get('_token'))) {
$this->addFlash('error', 'Invalid CSRF token.');
return $this->redirectToRoute('admin_update_manager');
}
// Check if already locked
if ($this->updateExecutor->isLocked()) {
$this->addFlash('error', 'An update or restore is already in progress.');
return $this->redirectToRoute('admin_update_manager');
}
$filename = $request->request->get('filename');
$restoreDatabase = $request->request->getBoolean('restore_database', true);
$restoreConfig = $request->request->getBoolean('restore_config', false);
$restoreAttachments = $request->request->getBoolean('restore_attachments', false);
if (!$filename) {
$this->addFlash('error', 'No backup file specified.');
return $this->redirectToRoute('admin_update_manager');
}
// Verify the backup exists
$backupDetails = $this->backupManager->getBackupDetails($filename);
if (!$backupDetails) {
$this->addFlash('error', 'Backup file not found.');
return $this->redirectToRoute('admin_update_manager');
}
// Execute restore (this is a synchronous operation for now - could be made async later)
$result = $this->updateExecutor->restoreBackup(
$filename,
$restoreDatabase,
$restoreConfig,
$restoreAttachments
);
if ($result['success']) {
$this->addFlash('success', 'Backup restored successfully.');
} else {
$this->addFlash('error', 'Restore failed: ' . ($result['error'] ?? 'Unknown error'));
}
return $this->redirectToRoute('admin_update_manager');
}
}

View File

@@ -66,7 +66,6 @@ class PartFilter implements FilterInterface
public readonly BooleanConstraint $favorite;
public readonly BooleanConstraint $needsReview;
public readonly NumberConstraint $mass;
public readonly TextConstraint $gtin;
public readonly DateTimeConstraint $lastModified;
public readonly DateTimeConstraint $addedDate;
public readonly EntityConstraint $category;
@@ -133,7 +132,6 @@ class PartFilter implements FilterInterface
$this->measurementUnit = new EntityConstraint($nodesListBuilder, MeasurementUnit::class, 'part.partUnit');
$this->partCustomState = new EntityConstraint($nodesListBuilder, PartCustomState::class, 'part.partCustomState');
$this->mass = new NumberConstraint('part.mass');
$this->gtin = new TextConstraint('part.gtin');
$this->dbId = new IntConstraint('part.id');
$this->ipn = new TextConstraint('part.ipn');
$this->addedDate = new DateTimeConstraint('part.addedDate');

View File

@@ -208,7 +208,6 @@ class LogDataTable implements DataTableTypeInterface
$dataTable->add('extra', LogEntryExtraColumn::class, [
'label' => 'log.extra',
'orderable' => false, //Sorting the JSON column makes no sense: MySQL/Sqlite does it via the string representation, PostgreSQL errors out
]);
$dataTable->add('timeTravel', IconLinkColumn::class, [

View File

@@ -218,10 +218,6 @@ final class PartsDataTable implements DataTableTypeInterface
'label' => $this->translator->trans('part.table.mass'),
'unit' => 'g'
])
->add('gtin', TextColumn::class, [
'label' => $this->translator->trans('part.table.gtin'),
'orderField' => 'NATSORT(part.gtin)'
])
->add('tags', TagsColumn::class, [
'label' => $this->translator->trans('part.table.tags'),
])

View File

@@ -97,7 +97,7 @@ use function in_array;
#[DiscriminatorMap(typeProperty: '_type', mapping: self::API_DISCRIMINATOR_MAP)]
abstract class Attachment extends AbstractNamedDBElement
{
final public const ORM_DISCRIMINATOR_MAP = ['Part' => PartAttachment::class, 'PartCustomState' => PartCustomStateAttachment::class, 'Device' => ProjectAttachment::class,
private const ORM_DISCRIMINATOR_MAP = ['Part' => PartAttachment::class, 'PartCustomState' => PartCustomStateAttachment::class, 'Device' => ProjectAttachment::class,
'AttachmentType' => AttachmentTypeAttachment::class,
'Category' => CategoryAttachment::class, 'Footprint' => FootprintAttachment::class, 'Manufacturer' => ManufacturerAttachment::class,
'Currency' => CurrencyAttachment::class, 'Group' => GroupAttachment::class, 'MeasurementUnit' => MeasurementUnitAttachment::class,
@@ -136,7 +136,7 @@ abstract class Attachment extends AbstractNamedDBElement
* @var string The class of the element that can be passed to this attachment. Must be overridden in subclasses.
* @phpstan-var class-string<T>
*/
public const ALLOWED_ELEMENT_CLASS = AttachmentContainingDBElement::class;
protected const ALLOWED_ELEMENT_CLASS = AttachmentContainingDBElement::class;
/**
* @var AttachmentUpload|null The options used for uploading a file to this attachment or modify it.

View File

@@ -134,17 +134,6 @@ class AttachmentType extends AbstractStructuralDBElement
#[ORM\OneToMany(mappedBy: 'attachment_type', targetEntity: Attachment::class)]
protected Collection $attachments_with_type;
/**
* @var string[]|null A list of allowed targets where this attachment type can be assigned to, as a list of portable names
*/
#[ORM\Column(type: Types::SIMPLE_ARRAY, nullable: true)]
protected ?array $allowed_targets = null;
/**
* @var class-string<Attachment>[]|null
*/
protected ?array $allowed_targets_parsed_cache = null;
#[Groups(['attachment_type:read'])]
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['attachment_type:read'])]
@@ -195,81 +184,4 @@ class AttachmentType extends AbstractStructuralDBElement
return $this;
}
/**
* Returns a list of allowed targets as class names (e.g. PartAttachment::class), where this attachment type can be assigned to. If null, there are no restrictions.
* @return class-string<Attachment>[]|null
*/
public function getAllowedTargets(): ?array
{
//Use cached value if available
if ($this->allowed_targets_parsed_cache !== null) {
return $this->allowed_targets_parsed_cache;
}
if (empty($this->allowed_targets)) {
return null;
}
$tmp = [];
foreach ($this->allowed_targets as $target) {
if (isset(Attachment::ORM_DISCRIMINATOR_MAP[$target])) {
$tmp[] = Attachment::ORM_DISCRIMINATOR_MAP[$target];
}
//Otherwise ignore the entry, as it is invalid
}
//Cache the parsed value
$this->allowed_targets_parsed_cache = $tmp;
return $tmp;
}
/**
* Sets the allowed targets for this attachment type. Allowed targets are specified as a list of class names (e.g. PartAttachment::class). If null is passed, there are no restrictions.
* @param class-string<Attachment>[]|null $allowed_targets
* @return $this
*/
public function setAllowedTargets(?array $allowed_targets): self
{
if ($allowed_targets === null) {
$this->allowed_targets = null;
} else {
$tmp = [];
foreach ($allowed_targets as $target) {
$discriminator = array_search($target, Attachment::ORM_DISCRIMINATOR_MAP, true);
if ($discriminator !== false) {
$tmp[] = $discriminator;
} else {
throw new \InvalidArgumentException("Invalid allowed target: $target. Allowed targets must be a class name of an Attachment subclass.");
}
}
$this->allowed_targets = $tmp;
}
//Reset the cache
$this->allowed_targets_parsed_cache = null;
return $this;
}
/**
* Checks if this attachment type is allowed for the given attachment target.
* @param Attachment|string $attachment
* @return bool
*/
public function isAllowedForTarget(Attachment|string $attachment): bool
{
//If no restrictions are set, allow all targets
if ($this->getAllowedTargets() === null) {
return true;
}
//Iterate over all allowed targets and check if the attachment is an instance of any of them
foreach ($this->getAllowedTargets() as $allowed_target) {
if (is_a($attachment, $allowed_target, true)) {
return true;
}
}
return false;
}
}

View File

@@ -58,7 +58,7 @@ class EDACategoryInfo
/** @var bool|null If this is set to true, then this part will be excluded in the simulation */
#[Column(type: Types::BOOLEAN, nullable: true)]
#[Groups(['full', 'category:read', 'category:write', 'import'])]
private ?bool $exclude_from_sim = null;
private ?bool $exclude_from_sim = true;
/** @var string|null The KiCAD schematic symbol, which should be used (the path to the library) */
#[Column(type: Types::STRING, nullable: true)]

View File

@@ -28,8 +28,6 @@ enum PartStockChangeType: string
case WITHDRAW = "withdraw";
case MOVE = "move";
case STOCKTAKE = "stock_take";
/**
* Converts the type to a short representation usable in the extra field of the log entry.
* @return string
@@ -40,7 +38,6 @@ enum PartStockChangeType: string
self::ADD => 'a',
self::WITHDRAW => 'w',
self::MOVE => 'm',
self::STOCKTAKE => 's',
};
}
@@ -55,7 +52,6 @@ enum PartStockChangeType: string
'a' => self::ADD,
'w' => self::WITHDRAW,
'm' => self::MOVE,
's' => self::STOCKTAKE,
default => throw new \InvalidArgumentException("Invalid short type: $value"),
};
}

View File

@@ -122,11 +122,6 @@ class PartStockChangedLogEntry extends AbstractLogEntry
return new self(PartStockChangeType::MOVE, $lot, $old_stock, $new_stock, $new_total_part_instock, $comment, $move_to_target, action_timestamp: $action_timestamp);
}
public static function stocktake(PartLot $lot, float $old_stock, float $new_stock, float $new_total_part_instock, string $comment, ?\DateTimeInterface $action_timestamp = null): self
{
return new self(PartStockChangeType::STOCKTAKE, $lot, $old_stock, $new_stock, $new_total_part_instock, $comment, action_timestamp: $action_timestamp);
}
/**
* Returns the instock change type of this entry
* @return PartStockChangeType

View File

@@ -80,7 +80,6 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
#[ORM\Index(columns: ['datetime_added', 'name', 'last_modified', 'id', 'needs_review'], name: 'parts_idx_datet_name_last_id_needs')]
#[ORM\Index(columns: ['name'], name: 'parts_idx_name')]
#[ORM\Index(columns: ['ipn'], name: 'parts_idx_ipn')]
#[ORM\Index(columns: ['gtin'], name: 'parts_idx_gtin')]
#[ApiResource(
operations: [
new Get(normalizationContext: [

View File

@@ -171,14 +171,6 @@ class PartLot extends AbstractDBElement implements TimeStampableInterface, Named
#[Length(max: 255)]
protected ?string $user_barcode = null;
/**
* @var \DateTimeImmutable|null The date when the last stocktake was performed for this part lot. Set to null, if no stocktake was performed yet.
*/
#[Groups(['extended', 'full', 'import', 'part_lot:read', 'part_lot:write'])]
#[ORM\Column( type: Types::DATETIME_IMMUTABLE, nullable: true)]
#[Year2038BugWorkaround]
protected ?\DateTimeImmutable $last_stocktake_at = null;
public function __clone()
{
if ($this->id) {
@@ -399,26 +391,6 @@ class PartLot extends AbstractDBElement implements TimeStampableInterface, Named
return $this;
}
/**
* Returns the date when the last stocktake was performed for this part lot. Returns null, if no stocktake was performed yet.
* @return \DateTimeImmutable|null
*/
public function getLastStocktakeAt(): ?\DateTimeImmutable
{
return $this->last_stocktake_at;
}
/**
* Sets the date when the last stocktake was performed for this part lot. Set to null, if no stocktake was performed yet.
* @param \DateTimeImmutable|null $last_stocktake_at
* @return $this
*/
public function setLastStocktakeAt(?\DateTimeImmutable $last_stocktake_at): self
{
$this->last_stocktake_at = $last_stocktake_at;
return $this;
}
#[Assert\Callback]

View File

@@ -24,7 +24,6 @@ namespace App\Entity\Parts\PartTraits;
use App\Entity\Parts\InfoProviderReference;
use App\Entity\Parts\PartCustomState;
use App\Validator\Constraints\ValidGTIN;
use Doctrine\DBAL\Types\Types;
use App\Entity\Parts\Part;
use Doctrine\ORM\Mapping as ORM;
@@ -85,14 +84,6 @@ trait AdvancedPropertyTrait
#[ORM\JoinColumn(name: 'id_part_custom_state')]
protected ?PartCustomState $partCustomState = null;
/**
* @var string|null The GTIN (Global Trade Item Number) of the part, for example a UPC or EAN code
*/
#[Groups(['extended', 'full', 'import', 'part:read', 'part:write'])]
#[ORM\Column(type: Types::STRING, nullable: true)]
#[ValidGTIN]
protected ?string $gtin = null;
/**
* Checks if this part is marked, for that it needs further review.
*/
@@ -220,26 +211,4 @@ trait AdvancedPropertyTrait
return $this;
}
/**
* Gets the GTIN (Global Trade Item Number) of the part, for example a UPC or EAN code.
* Returns null if no GTIN is set.
*/
public function getGtin(): ?string
{
return $this->gtin;
}
/**
* Sets the GTIN (Global Trade Item Number) of the part, for example a UPC or EAN code.
*
* @param string|null $gtin The new GTIN of the part
*
* @return $this
*/
public function setGtin(?string $gtin): self
{
$this->gtin = $gtin;
return $this;
}
}

View File

@@ -52,7 +52,6 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\SerializedName;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Constraints\Length;
@@ -148,13 +147,6 @@ class Orderdetail extends AbstractDBElement implements TimeStampableInterface, N
#[ORM\JoinColumn(name: 'id_supplier')]
protected ?Supplier $supplier = null;
/**
* @var bool|null Whether the prices includes VAT or not. Null means, that it is not specified, if the prices includes VAT or not.
*/
#[ORM\Column(type: Types::BOOLEAN, nullable: true)]
#[Groups(['extended', 'full', 'import', 'orderdetail:read', 'orderdetail:write'])]
protected ?bool $prices_includes_vat = null;
public function __construct()
{
$this->pricedetails = new ArrayCollection();
@@ -396,28 +388,6 @@ class Orderdetail extends AbstractDBElement implements TimeStampableInterface, N
return $this;
}
/**
* Checks if the prices of this orderdetail include VAT. Null means, that it is not specified, if the prices includes
* VAT or not.
* @return bool|null
*/
public function getPricesIncludesVAT(): ?bool
{
return $this->prices_includes_vat;
}
/**
* Sets whether the prices of this orderdetail include VAT.
* @param bool|null $includesVat
* @return $this
*/
public function setPricesIncludesVAT(?bool $includesVat): self
{
$this->prices_includes_vat = $includesVat;
return $this;
}
public function getName(): string
{
return $this->getSupplierPartNr();

View File

@@ -121,8 +121,6 @@ class Pricedetail extends AbstractDBElement implements TimeStampableInterface
#[Groups(['pricedetail:read:standalone', 'pricedetail:write'])]
protected ?Orderdetail $orderdetail = null;
public function __construct()
{
$this->price = BigDecimal::zero()->toScale(self::PRICE_PRECISION);
@@ -266,15 +264,6 @@ class Pricedetail extends AbstractDBElement implements TimeStampableInterface
return $this->currency?->getIsoCode();
}
/**
* Returns whether the price includes VAT or not. Null means, that it is not specified, if the price includes VAT or not.
* @return bool|null
*/
public function getIncludesVat(): ?bool
{
return $this->orderdetail?->getPricesIncludesVAT();
}
/********************************************************************************
*
* Setters

View File

@@ -43,7 +43,7 @@ final class PermissionData implements \JsonSerializable
/**
* The current schema version of the permission data
*/
public const CURRENT_SCHEMA_VERSION = 4;
public const CURRENT_SCHEMA_VERSION = 3;
/**
* Creates a new Permission Data Instance using the given data.

View File

@@ -1,230 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Services\System\UpdateExecutor;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
/**
* Blocks all web requests when maintenance mode is enabled during updates.
*/
readonly class MaintenanceModeSubscriber implements EventSubscriberInterface
{
public function __construct(private UpdateExecutor $updateExecutor)
{
}
public static function getSubscribedEvents(): array
{
return [
// High priority to run before other listeners
KernelEvents::REQUEST => ['onKernelRequest', 512], //High priority to run before other listeners
];
}
public function onKernelRequest(RequestEvent $event): void
{
// Only handle main requests
if (!$event->isMainRequest()) {
return;
}
// Skip if not in maintenance mode
if (!$this->updateExecutor->isMaintenanceMode()) {
return;
}
//Allow to view the progress page
if (preg_match('#^/\w{2}/system/update-manager/progress#', $event->getRequest()->getPathInfo())) {
return;
}
// Allow CLI requests
if (PHP_SAPI === 'cli') {
return;
}
// Get maintenance info
$maintenanceInfo = $this->updateExecutor->getMaintenanceInfo();
// Calculate how long the update has been running
$duration = null;
if ($maintenanceInfo && isset($maintenanceInfo['enabled_at'])) {
try {
$startedAt = new \DateTime($maintenanceInfo['enabled_at']);
$now = new \DateTime();
$duration = $now->getTimestamp() - $startedAt->getTimestamp();
} catch (\Exception) {
// Ignore date parsing errors
}
}
$content = $this->getSimpleMaintenanceHtml($maintenanceInfo, $duration);
$response = new Response($content, Response::HTTP_SERVICE_UNAVAILABLE);
$response->headers->set('Retry-After', '30');
$response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate');
$event->setResponse($response);
}
/**
* Generate a simple maintenance page HTML without Twig.
*/
private function getSimpleMaintenanceHtml(?array $maintenanceInfo, ?int $duration): string
{
$reason = htmlspecialchars($maintenanceInfo['reason'] ?? 'Update in progress');
$durationText = $duration !== null ? sprintf('%d seconds', $duration) : 'a moment';
$startDateStr = $maintenanceInfo['enabled_at'] ?? 'unknown time';
return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="15">
<title>Part-DB - Maintenance</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
color: #ffffff;
}
.container {
text-align: center;
padding: 40px;
max-width: 600px;
}
.icon {
font-size: 80px;
margin-bottom: 30px;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.1); opacity: 0.8; }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
display: inline-block;
animation: spin 2s linear infinite;
}
h1 {
font-size: 2.5rem;
margin-bottom: 20px;
color: #00d4ff;
}
p {
font-size: 1.2rem;
margin-bottom: 15px;
color: #b8c5d6;
}
.reason {
background: rgba(255, 255, 255, 0.1);
padding: 15px 25px;
border-radius: 10px;
margin: 20px 0;
font-size: 1rem;
}
.progress-bar {
width: 100%;
height: 6px;
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
overflow: hidden;
margin: 30px 0;
}
.progress-bar-inner {
height: 100%;
background: linear-gradient(90deg, #00d4ff, #00ff88);
border-radius: 3px;
animation: progress 3s ease-in-out infinite;
}
@keyframes progress {
0% { width: 0%; margin-left: 0%; }
50% { width: 50%; margin-left: 25%; }
100% { width: 0%; margin-left: 100%; }
}
.info {
font-size: 0.9rem;
color: #8899aa;
margin-top: 30px;
}
.duration {
font-family: monospace;
background: rgba(0, 212, 255, 0.2);
padding: 3px 8px;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<div class="icon">
<span class="spinner">⚙️</span>
</div>
<h1>Part-DB is under maintenance</h1>
<p>We're making things better. This should only take a moment.</p>
<div class="reason">
<strong>{$reason}</strong>
</div>
<div class="progress-bar">
<div class="progress-bar-inner"></div>
</div>
<p class="info">
Maintenance mode active since <span class="duration">{$startDateStr}</span><br>
<br>
Started <span class="duration">{$durationText}</span> ago<br>
<small>This page will automatically refresh every 15 seconds.</small>
</p>
</div>
</body>
</html>
HTML;
}
}

View File

@@ -1,32 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Exceptions;
class ProviderIDNotSupportedException extends \RuntimeException
{
public function fromProvider(string $providerKey, string $id): self
{
return new self(sprintf('The given ID %s is not supported by the provider %s.', $id, $providerKey,));
}
}

View File

@@ -22,23 +22,17 @@ declare(strict_types=1);
namespace App\Form\AdminPages;
use App\Entity\Attachments\Attachment;
use App\Entity\Attachments\PartAttachment;
use App\Entity\Attachments\ProjectAttachment;
use App\Services\ElementTypeNameGenerator;
use Symfony\Bundle\SecurityBundle\Security;
use App\Entity\Base\AbstractNamedDBElement;
use App\Services\Attachments\FileTypeFilterTools;
use App\Services\LogSystem\EventCommentNeededHelper;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Translation\StaticMessage;
class AttachmentTypeAdminForm extends BaseEntityAdminForm
{
public function __construct(Security $security, protected FileTypeFilterTools $filterTools, EventCommentNeededHelper $eventCommentNeededHelper, private readonly ElementTypeNameGenerator $elementTypeNameGenerator)
public function __construct(Security $security, protected FileTypeFilterTools $filterTools, EventCommentNeededHelper $eventCommentNeededHelper)
{
parent::__construct($security, $eventCommentNeededHelper);
}
@@ -47,25 +41,6 @@ class AttachmentTypeAdminForm extends BaseEntityAdminForm
{
$is_new = null === $entity->getID();
$choiceLabel = function (string $class) {
if (!is_a($class, Attachment::class, true)) {
return $class;
}
return new StaticMessage($this->elementTypeNameGenerator->typeLabelPlural($class::ALLOWED_ELEMENT_CLASS));
};
$builder->add('allowed_targets', ChoiceType::class, [
'required' => false,
'choices' => array_values(Attachment::ORM_DISCRIMINATOR_MAP),
'choice_label' => $choiceLabel,
'preferred_choices' => [PartAttachment::class, ProjectAttachment::class],
'label' => 'attachment_type.edit.allowed_targets',
'help' => 'attachment_type.edit.allowed_targets.help',
'multiple' => true,
]);
$builder->add('filetype_filter', TextType::class, [
'required' => false,
'label' => 'attachment_type.edit.filetype_filter',

View File

@@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Form;
use App\Form\Type\AttachmentTypeType;
use App\Settings\SystemSettings\AttachmentsSettings;
use Symfony\Bundle\SecurityBundle\Security;
use App\Entity\Attachments\Attachment;
@@ -68,10 +67,10 @@ class AttachmentFormType extends AbstractType
'required' => false,
'empty_data' => '',
])
->add('attachment_type', AttachmentTypeType::class, [
->add('attachment_type', StructuralEntityType::class, [
'label' => 'attachment.edit.attachment_type',
'class' => AttachmentType::class,
'disable_not_selectable' => true,
'attachment_filter_class' => $options['data_class'] ?? null,
'allow_add' => $this->security->isGranted('@attachment_types.create'),
]);

View File

@@ -135,10 +135,6 @@ class PartFilterType extends AbstractType
'min' => 0,
]);
$builder->add('gtin', TextConstraintType::class, [
'label' => 'part.gtin',
]);
$builder->add('measurementUnit', StructuralEntityConstraintType::class, [
'label' => 'part.edit.partUnit',
'entity_class' => MeasurementUnit::class

View File

@@ -75,8 +75,7 @@ class ScanDialogType extends AbstractType
BarcodeSourceType::INTERNAL => 'scan_dialog.mode.internal',
BarcodeSourceType::IPN => 'scan_dialog.mode.ipn',
BarcodeSourceType::USER_DEFINED => 'scan_dialog.mode.user',
BarcodeSourceType::EIGP114 => 'scan_dialog.mode.eigp',
BarcodeSourceType::GTIN => 'scan_dialog.mode.gtin',
BarcodeSourceType::EIGP114 => 'scan_dialog.mode.eigp'
},
]);

View File

@@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Form\Part;
use App\Form\Type\TriStateCheckboxType;
use Symfony\Bundle\SecurityBundle\Security;
use App\Entity\Parts\MeasurementUnit;
use App\Entity\Parts\Supplier;
@@ -74,11 +73,6 @@ class OrderdetailType extends AbstractType
'label' => 'orderdetails.edit.obsolete',
]);
$builder->add('pricesIncludesVAT', TriStateCheckboxType::class, [
'required' => false,
'label' => 'orderdetails.edit.prices_includes_vat',
]);
//Add pricedetails after we know the data, so we can set the default currency
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options): void {
/** @var Orderdetail $orderdetail */

View File

@@ -43,7 +43,6 @@ use App\Services\InfoProviderSystem\DTOs\PartDetailDTO;
use App\Services\LogSystem\EventCommentNeededHelper;
use App\Services\LogSystem\EventCommentType;
use App\Settings\MiscSettings\IpnSuggestSettings;
use App\Settings\SystemSettings\LocalizationSettings;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
@@ -64,7 +63,6 @@ class PartBaseType extends AbstractType
protected UrlGeneratorInterface $urlGenerator,
protected EventCommentNeededHelper $event_comment_needed_helper,
protected IpnSuggestSettings $ipnSuggestSettings,
private readonly LocalizationSettings $localizationSettings,
) {
}
@@ -218,13 +216,7 @@ class PartBaseType extends AbstractType
'disable_not_selectable' => true,
'label' => 'part.edit.partCustomState',
])
->add('ipn', TextType::class, $ipnOptions)
->add('gtin', TextType::class, [
'required' => false,
'empty_data' => null,
'label' => 'part.gtin',
])
;
->add('ipn', TextType::class, $ipnOptions);
//Comment section
$builder->add('comment', RichTextEditorType::class, [
@@ -269,9 +261,6 @@ class PartBaseType extends AbstractType
'entity' => $part,
]);
$orderdetailPrototype = new Orderdetail();
$orderdetailPrototype->setPricesIncludesVAT($this->localizationSettings->pricesIncludeTaxByDefault);
//Orderdetails section
$builder->add('orderdetails', CollectionType::class, [
'entry_type' => OrderdetailType::class,
@@ -280,7 +269,7 @@ class PartBaseType extends AbstractType
'allow_delete' => true,
'label' => false,
'by_reference' => false,
'prototype_data' => $orderdetailPrototype,
'prototype_data' => new Orderdetail(),
'entry_options' => [
'measurement_unit' => $part->getPartUnit(),
],

View File

@@ -31,7 +31,6 @@ use App\Form\Type\StructuralEntityType;
use App\Form\Type\UserSelectType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
@@ -111,14 +110,6 @@ class PartLotType extends AbstractType
//Do not remove whitespace chars on the beginning and end of the string
'trim' => false,
]);
$builder->add('last_stocktake_at', DateTimeType::class, [
'label' => 'part_lot.edit.last_stocktake_at',
'widget' => 'single_text',
'disabled' => !$this->security->isGranted('@parts_stock.stocktake'),
'required' => false,
'empty_data' => null,
]);
}
public function configureOptions(OptionsResolver $resolver): void

View File

@@ -1,56 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Form\Type;
use App\Entity\Attachments\AttachmentType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Form type to select the AttachmentType to use in an attachment form. This is used to filter the available attachment types based on the target class.
*/
class AttachmentTypeType extends AbstractType
{
public function getParent(): ?string
{
return StructuralEntityType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->define('attachment_filter_class')->allowedTypes('null', 'string')->default(null);
$resolver->setDefault('class', AttachmentType::class);
$resolver->setDefault('choice_filter', function (Options $options) {
if (is_a($options['class'], AttachmentType::class, true) && $options['attachment_filter_class'] !== null) {
return static function (?AttachmentType $choice) use ($options) {
return $choice?->isAllowedForTarget($options['attachment_filter_class']);
};
}
return null;
});
}
}

View File

@@ -109,13 +109,6 @@ class DBElementRepository extends EntityRepository
return [];
}
//Ensure that all IDs are integers and none is null
foreach ($ids as $id) {
if (!is_int($id)) {
throw new \InvalidArgumentException('Non-integer ID given to findByIDInMatchingOrder: ' . var_export($id, true));
}
}
$cache_key = implode(',', $ids);
//Check if the result is already cached

View File

@@ -58,13 +58,13 @@ final class PartLotVoter extends Voter
{
}
protected const ALLOWED_PERMS = ['read', 'edit', 'create', 'delete', 'show_history', 'revert_element', 'withdraw', 'add', 'move', 'stocktake'];
protected const ALLOWED_PERMS = ['read', 'edit', 'create', 'delete', 'show_history', 'revert_element', 'withdraw', 'add', 'move'];
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token, ?Vote $vote = null): bool
{
$user = $this->helper->resolveUser($token);
if (in_array($attribute, ['withdraw', 'add', 'move', 'stocktake'], true))
if (in_array($attribute, ['withdraw', 'add', 'move'], true))
{
$base_permission = $this->helper->isGranted($token, 'parts_stock', $attribute, $vote);

View File

@@ -57,7 +57,7 @@ class UserCacheKeyGenerator
//If the user is null, then treat it as anonymous user.
//When the anonymous user is passed as user then use this path too.
if (!($user instanceof User) || User::ID_ANONYMOUS === $user->getID()) {
return 'user$_'.User::ID_ANONYMOUS . '_'.$locale;
return 'user$_'.User::ID_ANONYMOUS;
}
//Use the unique user id and the locale to generate the key

View File

@@ -189,7 +189,7 @@ class KiCadHelper
"symbolIdStr" => $part->getEdaInfo()->getKicadSymbol() ?? $part->getCategory()?->getEdaInfo()->getKicadSymbol() ?? "",
"exclude_from_bom" => $this->boolToKicadBool($part->getEdaInfo()->getExcludeFromBom() ?? $part->getCategory()?->getEdaInfo()->getExcludeFromBom() ?? false),
"exclude_from_board" => $this->boolToKicadBool($part->getEdaInfo()->getExcludeFromBoard() ?? $part->getCategory()?->getEdaInfo()->getExcludeFromBoard() ?? false),
"exclude_from_sim" => $this->boolToKicadBool($part->getEdaInfo()->getExcludeFromSim() ?? $part->getCategory()?->getEdaInfo()->getExcludeFromSim() ?? false),
"exclude_from_sim" => $this->boolToKicadBool($part->getEdaInfo()->getExcludeFromSim() ?? $part->getCategory()?->getEdaInfo()->getExcludeFromSim() ?? true),
"fields" => []
];

View File

@@ -59,7 +59,6 @@ class PartMerger implements EntityMergerInterface
$this->useOtherValueIfNotEmtpy($target, $other, 'manufacturer_product_number');
$this->useOtherValueIfNotEmtpy($target, $other, 'mass');
$this->useOtherValueIfNotEmtpy($target, $other, 'ipn');
$this->useOtherValueIfNotEmtpy($target, $other, 'gtin');
//Merge relations to other entities
$this->useOtherValueIfNotNull($target, $other, 'manufacturer');
@@ -185,4 +184,4 @@ class PartMerger implements EntityMergerInterface
}
}
}
}
}

View File

@@ -274,16 +274,6 @@ class BOMImporter
$entries_by_key = []; // Track entries by name+part combination
$mapped_entries = []; // Collect all mapped entries for validation
// Fetch suppliers once for efficiency
$suppliers = $this->entityManager->getRepository(\App\Entity\Parts\Supplier::class)->findAll();
$supplierSPNKeys = [];
$suppliersByName = []; // Map supplier names to supplier objects
foreach ($suppliers as $supplier) {
$supplierName = $supplier->getName();
$supplierSPNKeys[] = $supplierName . ' SPN';
$suppliersByName[$supplierName] = $supplier;
}
foreach ($csv->getRecords() as $offset => $entry) {
// Apply field mapping to translate column names
$mapped_entry = $this->applyFieldMapping($entry, $field_mapping, $field_priorities);
@@ -359,41 +349,6 @@ class BOMImporter
}
}
// Try to link existing part based on supplier part number if no Part-DB ID is given
if ($part === null) {
// Check all available supplier SPN fields
foreach ($suppliersByName as $supplierName => $supplier) {
$supplier_spn = null;
if (isset($mapped_entry[$supplierName . ' SPN']) && !empty(trim($mapped_entry[$supplierName . ' SPN']))) {
$supplier_spn = trim($mapped_entry[$supplierName . ' SPN']);
}
if ($supplier_spn !== null) {
// Query for orderdetails with matching supplier and SPN
$orderdetail = $this->entityManager->getRepository(\App\Entity\PriceInformations\Orderdetail::class)
->findOneBy([
'supplier' => $supplier,
'supplierpartnr' => $supplier_spn,
]);
if ($orderdetail !== null && $orderdetail->getPart() !== null) {
$part = $orderdetail->getPart();
$name = $part->getName(); // Update name with actual part name
$this->logger->info('Linked BOM entry to existing part via supplier SPN', [
'supplier' => $supplierName,
'supplier_spn' => $supplier_spn,
'part_id' => $part->getID(),
'part_name' => $part->getName(),
]);
break; // Stop searching once a match is found
}
}
}
}
// Create unique key for this entry (name + part ID)
$entry_key = $name . '|' . ($part ? $part->getID() : 'null');
@@ -445,14 +400,9 @@ class BOMImporter
if (isset($mapped_entry['Manufacturer'])) {
$comment_parts[] = 'Manf: ' . $mapped_entry['Manufacturer'];
}
// Add supplier part numbers dynamically
foreach ($supplierSPNKeys as $spnKey) {
if (isset($mapped_entry[$spnKey]) && !empty($mapped_entry[$spnKey])) {
$comment_parts[] = $spnKey . ': ' . $mapped_entry[$spnKey];
}
if (isset($mapped_entry['LCSC'])) {
$comment_parts[] = 'LCSC: ' . $mapped_entry['LCSC'];
}
if (isset($mapped_entry['Supplier and ref'])) {
$comment_parts[] = $mapped_entry['Supplier and ref'];
}

View File

@@ -42,7 +42,6 @@ class PartDetailDTO extends SearchResultDTO
?ManufacturingStatus $manufacturing_status = null,
?string $provider_url = null,
?string $footprint = null,
?string $gtin = null,
public readonly ?string $notes = null,
/** @var FileDTO[]|null */
public readonly ?array $datasheets = null,
@@ -69,7 +68,6 @@ class PartDetailDTO extends SearchResultDTO
manufacturing_status: $manufacturing_status,
provider_url: $provider_url,
footprint: $footprint,
gtin: $gtin
);
}
}

View File

@@ -39,9 +39,7 @@ readonly class PriceDTO
public string $price,
/** @var string The currency of the used ISO code of this price detail */
public ?string $currency_iso_code,
/** @var bool If the price includes tax
* @deprecated Use the prices_include_vat property of the PurchaseInfoDTO instead, as this property is not reliable if there are multiple prices with different values for includes_tax
*/
/** @var bool If the price includes tax */
public ?bool $includes_tax = true,
/** @var float the price related quantity */
public ?float $price_related_quantity = 1.0,

View File

@@ -29,9 +29,6 @@ namespace App\Services\InfoProviderSystem\DTOs;
*/
readonly class PurchaseInfoDTO
{
/** @var bool|null If the prices contain VAT or not. Null if state is unknown. */
public ?bool $prices_include_vat;
public function __construct(
public string $distributor_name,
public string $order_number,
@@ -39,7 +36,6 @@ readonly class PurchaseInfoDTO
public array $prices,
/** @var string|null An url to the product page of the vendor */
public ?string $product_url = null,
?bool $prices_include_vat = null,
)
{
//Ensure that the prices are PriceDTO instances
@@ -48,17 +44,5 @@ readonly class PurchaseInfoDTO
throw new \InvalidArgumentException('The prices array must only contain PriceDTO instances');
}
}
//If no prices_include_vat information is given, try to deduct it from the prices
if ($prices_include_vat === null) {
$vatValues = array_unique(array_map(fn(PriceDTO $price) => $price->includes_tax, $this->prices));
if (count($vatValues) === 1) {
$this->prices_include_vat = $vatValues[0]; //Use the value of the prices if they are all the same
} else {
$this->prices_include_vat = null; //If there are different values for the prices, we cannot determine if the prices include VAT or not
}
} else {
$this->prices_include_vat = $prices_include_vat;
}
}
}

View File

@@ -59,8 +59,6 @@ class SearchResultDTO
public readonly ?string $provider_url = null,
/** @var string|null A footprint representation of the providers page */
public readonly ?string $footprint = null,
/** @var string|null The GTIN / EAN of the part */
public readonly ?string $gtin = null,
)
{
if ($preview_image_url !== null) {
@@ -92,7 +90,6 @@ class SearchResultDTO
'manufacturing_status' => $this->manufacturing_status?->value,
'provider_url' => $this->provider_url,
'footprint' => $this->footprint,
'gtin' => $this->gtin,
];
}
@@ -115,7 +112,6 @@ class SearchResultDTO
manufacturing_status: isset($data['manufacturing_status']) ? ManufacturingStatus::tryFrom($data['manufacturing_status']) : null,
provider_url: $data['provider_url'] ?? null,
footprint: $data['footprint'] ?? null,
gtin: $data['gtin'] ?? null,
);
}
}

View File

@@ -94,6 +94,7 @@ final class DTOtoEntityConverter
$entity->setPrice($dto->getPriceAsBigDecimal());
$entity->setPriceRelatedQuantity($dto->price_related_quantity);
//Currency TODO
if ($dto->currency_iso_code !== null) {
$entity->setCurrency($this->getCurrency($dto->currency_iso_code));
} else {
@@ -116,8 +117,6 @@ final class DTOtoEntityConverter
$entity->addPricedetail($this->convertPrice($price));
}
$entity->setPricesIncludesVAT($dto->prices_include_vat);
return $entity;
}
@@ -176,8 +175,6 @@ final class DTOtoEntityConverter
$entity->setManufacturingStatus($dto->manufacturing_status ?? ManufacturingStatus::NOT_SET);
$entity->setManufacturerProductURL($dto->manufacturer_product_url ?? '');
$entity->setGtin($dto->gtin);
//Set the provider reference on the part
$entity->setProviderReference(InfoProviderReference::fromPartDTO($dto));

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace App\Services\InfoProviderSystem;
use App\Services\InfoProviderSystem\Providers\InfoProviderInterface;
use App\Services\InfoProviderSystem\Providers\URLHandlerInfoProviderInterface;
/**
* This class keeps track of all registered info providers and allows to find them by their key
@@ -48,8 +47,6 @@ final class ProviderRegistry
*/
private array $providers_disabled = [];
private array $providers_by_domain = [];
/**
* @var bool Whether the registry has been initialized
*/
@@ -81,14 +78,6 @@ final class ProviderRegistry
$this->providers_by_name[$key] = $provider;
if ($provider->isActive()) {
$this->providers_active[$key] = $provider;
if ($provider instanceof URLHandlerInfoProviderInterface) {
foreach ($provider->getHandledDomains() as $domain) {
if (isset($this->providers_by_domain[$domain])) {
throw new \LogicException("Domain $domain is already handled by another provider");
}
$this->providers_by_domain[$domain] = $provider;
}
}
} else {
$this->providers_disabled[$key] = $provider;
}
@@ -150,29 +139,4 @@ final class ProviderRegistry
return $this->providers_disabled;
}
public function getProviderHandlingDomain(string $domain): (InfoProviderInterface&URLHandlerInfoProviderInterface)|null
{
if (!$this->initialized) {
$this->initStructures();
}
//Check if the domain is directly existing:
if (isset($this->providers_by_domain[$domain])) {
return $this->providers_by_domain[$domain];
}
//Otherwise check for subdomains:
$parts = explode('.', $domain);
while (count($parts) > 2) {
array_shift($parts);
$check_domain = implode('.', $parts);
if (isset($this->providers_by_domain[$check_domain])) {
return $this->providers_by_domain[$check_domain];
}
}
//If we found nothing, return null
return null;
}
}
}

View File

@@ -1,347 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\InfoProviderSystem\Providers;
use App\Services\InfoProviderSystem\DTOs\FileDTO;
use App\Services\InfoProviderSystem\DTOs\ParameterDTO;
use App\Services\InfoProviderSystem\DTOs\PartDetailDTO;
use App\Services\InfoProviderSystem\DTOs\PriceDTO;
use App\Services\InfoProviderSystem\DTOs\PurchaseInfoDTO;
use App\Services\InfoProviderSystem\DTOs\SearchResultDTO;
use App\Settings\InfoProviderSystem\ConradSettings;
use App\Settings\InfoProviderSystem\ConradShopIDs;
use Symfony\Contracts\HttpClient\HttpClientInterface;
readonly class ConradProvider implements InfoProviderInterface, URLHandlerInfoProviderInterface
{
private const SEARCH_ENDPOINT = '/search/1/v3/facetSearch';
public const DISTRIBUTOR_NAME = 'Conrad';
private HttpClientInterface $httpClient;
public function __construct( HttpClientInterface $httpClient, private ConradSettings $settings)
{
//We want everything in JSON
$this->httpClient = $httpClient->withOptions([
'headers' => [
'Accept' => 'application/json',
],
]);
}
public function getProviderInfo(): array
{
return [
'name' => 'Conrad',
'description' => 'Retrieves part information from conrad.de',
'url' => 'https://www.conrad.de/',
'disabled_help' => 'Set API key in settings',
'settings_class' => ConradSettings::class,
];
}
public function getProviderKey(): string
{
return 'conrad';
}
public function isActive(): bool
{
return !empty($this->settings->apiKey);
}
private function getProductUrl(string $productId): string
{
return 'https://' . $this->settings->shopID->getDomain() . '/' . $this->settings->shopID->getLanguage() . '/p/' . $productId;
}
private function getFootprintFromTechnicalDetails(array $technicalDetails): ?string
{
foreach ($technicalDetails as $detail) {
if ($detail['name'] === 'ATT_LOV_HOUSING_SEMICONDUCTORS') {
return $detail['values'][0] ?? null;
}
}
return null;
}
public function searchByKeyword(string $keyword): array
{
$url = $this->settings->shopID->getAPIRoot() . self::SEARCH_ENDPOINT . '/'
. $this->settings->shopID->getDomainEnd() . '/' . $this->settings->shopID->getLanguage()
. '/' . $this->settings->shopID->getCustomerType();
$response = $this->httpClient->request('POST', $url, [
'query' => [
'apikey' => $this->settings->apiKey,
],
'json' => [
'query' => $keyword,
'size' => 50,
'sort' => [["field"=>"_score","order"=>"desc"]],
],
]);
$out = [];
$results = $response->toArray();
foreach($results['hits'] as $result) {
$out[] = new SearchResultDTO(
provider_key: $this->getProviderKey(),
provider_id: $result['productId'],
name: $result['manufacturerId'] ?? $result['productId'],
description: $result['title'] ?? '',
manufacturer: $result['brand']['name'] ?? null,
mpn: $result['manufacturerId'] ?? null,
preview_image_url: $result['image'] ?? null,
provider_url: $this->getProductUrl($result['productId']),
footprint: $this->getFootprintFromTechnicalDetails($result['technicalDetails'] ?? []),
gtin: $result['ean'] ?? null,
);
}
return $out;
}
private function getFootprintFromTechnicalAttributes(array $technicalDetails): ?string
{
foreach ($technicalDetails as $detail) {
if ($detail['attributeID'] === 'ATT.LOV.HOUSING_SEMICONDUCTORS') {
return $detail['values'][0]['value'] ?? null;
}
}
return null;
}
/**
* @param array $technicalAttributes
* @return array<ParameterDTO>
*/
private function technicalAttributesToParameters(array $technicalAttributes): array
{
return array_map(static function (array $p) {
if (count($p['values']) === 1) { //Single value attribute
if (array_key_exists('unit', $p['values'][0])) {
return ParameterDTO::parseValueField( //With unit
name: $p['attributeName'],
value: $p['values'][0]['value'],
unit: $p['values'][0]['unit']['name'],
);
}
return ParameterDTO::parseValueIncludingUnit(
name: $p['attributeName'],
value: $p['values'][0]['value'],
);
}
if (count($p['values']) === 2) { //Multi value attribute (e.g. min/max)
$value = $p['values'][0]['value'] ?? null;
$value2 = $p['values'][1]['value'] ?? null;
$unit = $p['values'][0]['unit']['name'] ?? '';
$unit2 = $p['values'][1]['unit']['name'] ?? '';
if ($unit === $unit2 && is_numeric($value) && is_numeric($value2)) {
if (array_key_exists('unit', $p['values'][0])) { //With unit
return new ParameterDTO(
name: $p['attributeName'],
value_min: (float)$value,
value_max: (float)$value2,
unit: $unit,
);
}
return new ParameterDTO(
name: $p['attributeName'],
value_min: (float)$value,
value_max: (float)$value2,
);
}
}
// fallback implementation
$values = implode(", ", array_map(fn($q) =>
array_key_exists('unit', $q) ? $q['value']." ". ($q['unit']['name'] ?? $q['unit']) : $q['value']
, $p['values']));
return ParameterDTO::parseValueIncludingUnit(
name: $p['attributeName'],
value: $values,
);
}, $technicalAttributes);
}
/**
* @param array $productMedia
* @return array<FileDTO>
*/
public function productMediaToDatasheets(array $productMedia): array
{
$files = [];
foreach ($productMedia['manuals'] as $manual) {
//Filter out unwanted languages
if (!empty($this->settings->attachmentLanguageFilter) && !in_array($manual['language'], $this->settings->attachmentLanguageFilter, true)) {
continue;
}
$files[] = new FileDTO($manual['fullUrl'], $manual['title'] . ' (' . $manual['language'] . ')');
}
return $files;
}
/**
* Queries prices for a given product ID. It makes a POST request to the Conrad API
* @param string $productId
* @return PurchaseInfoDTO
*/
private function queryPrices(string $productId): PurchaseInfoDTO
{
$priceQueryURL = $this->settings->shopID->getAPIRoot() . '/price-availability/4/'
. $this->settings->shopID->getShopID() . '/facade';
$response = $this->httpClient->request('POST', $priceQueryURL, [
'query' => [
'apikey' => $this->settings->apiKey,
'overrideCalculationSchema' => $this->settings->includeVAT ? 'GROSS' : 'NET'
],
'json' => [
'ns:inputArticleItemList' => [
"#namespaces" => [
"ns" => "http://www.conrad.de/ccp/basit/service/article/priceandavailabilityservice/api"
],
'articles' => [
[
"articleID" => $productId,
"calculatePrice" => true,
"checkAvailability" => true,
],
]
]
]
]);
$result = $response->toArray();
$priceInfo = $result['priceAndAvailabilityFacadeResponse']['priceAndAvailability']['price'] ?? [];
$price = $priceInfo['price'] ?? "0.0";
$currency = $priceInfo['currency'] ?? "EUR";
$includesVat = !$priceInfo['isGrossAmount'] || $priceInfo['isGrossAmount'] === "true";
$minOrderAmount = $result['priceAndAvailabilityFacadeResponse']['priceAndAvailability']['availabilityStatus']['minimumOrderQuantity'] ?? 1;
$prices = [];
foreach ($priceInfo['priceScale'] ?? [] as $priceScale) {
$prices[] = new PriceDTO(
minimum_discount_amount: max($priceScale['scaleFrom'], $minOrderAmount),
price: (string)$priceScale['pricePerUnit'],
currency_iso_code: $currency,
includes_tax: $includesVat
);
}
if (empty($prices)) { //Fallback if no price scales are defined
$prices[] = new PriceDTO(
minimum_discount_amount: $minOrderAmount,
price: (string)$price,
currency_iso_code: $currency,
includes_tax: $includesVat
);
}
return new PurchaseInfoDTO(
distributor_name: self::DISTRIBUTOR_NAME,
order_number: $productId,
prices: $prices,
product_url: $this->getProductUrl($productId)
);
}
public function getDetails(string $id): PartDetailDTO
{
$productInfoURL = $this->settings->shopID->getAPIRoot() . '/product/1/service/' . $this->settings->shopID->getShopID()
. '/product/' . $id;
$response = $this->httpClient->request('GET', $productInfoURL, [
'query' => [
'apikey' => $this->settings->apiKey,
]
]);
$data = $response->toArray();
return new PartDetailDTO(
provider_key: $this->getProviderKey(),
provider_id: $data['shortProductNumber'],
name: $data['productFullInformation']['manufacturer']['name'] ?? $data['productFullInformation']['manufacturer']['id'] ?? $data['shortProductNumber'],
description: $data['productShortInformation']['title'] ?? '',
category: $data['productShortInformation']['articleGroupName'] ?? null,
manufacturer: $data['brand']['displayName'] !== null ? preg_replace("/[\u{2122}\u{00ae}]/", "", $data['brand']['displayName']) : null, //Replace ™ and ® symbols
mpn: $data['productFullInformation']['manufacturer']['id'] ?? null,
preview_image_url: $data['productShortInformation']['mainImage']['imageUrl'] ?? null,
provider_url: $this->getProductUrl($data['shortProductNumber']),
footprint: $this->getFootprintFromTechnicalAttributes($data['productFullInformation']['technicalAttributes'] ?? []),
gtin: $data['productFullInformation']['eanCode'] ?? null,
notes: $data['productFullInformation']['description'] ?? null,
datasheets: $this->productMediaToDatasheets($data['productMedia'] ?? []),
parameters: $this->technicalAttributesToParameters($data['productFullInformation']['technicalAttributes'] ?? []),
vendor_infos: [$this->queryPrices($data['shortProductNumber'])]
);
}
public function getCapabilities(): array
{
return [
ProviderCapabilities::BASIC,
ProviderCapabilities::PICTURE,
ProviderCapabilities::DATASHEET,
ProviderCapabilities::PRICE,
ProviderCapabilities::FOOTPRINT,
ProviderCapabilities::GTIN,
];
}
public function getHandledDomains(): array
{
$domains = [];
foreach (ConradShopIDs::cases() as $shopID) {
$domains[] = $shopID->getDomain();
}
return array_unique($domains);
}
public function getIDFromURL(string $url): ?string
{
//Input: https://www.conrad.de/de/p/apple-iphone-air-wolkenweiss-256-gb-eek-a-a-g-16-5-cm-6-5-zoll-3475299.html
//The numbers before the optional .html are the product ID
$matches = [];
if (preg_match('/-(\d+)(\.html)?$/', $url, $matches) === 1) {
return $matches[1];
}
return null;
}
}

View File

@@ -33,7 +33,7 @@ use App\Settings\InfoProviderSystem\Element14Settings;
use Composer\CaBundle\CaBundle;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class Element14Provider implements InfoProviderInterface, URLHandlerInfoProviderInterface
class Element14Provider implements InfoProviderInterface
{
private const ENDPOINT_URL = 'https://api.element14.com/catalog/products';
@@ -309,21 +309,4 @@ class Element14Provider implements InfoProviderInterface, URLHandlerInfoProvider
ProviderCapabilities::DATASHEET,
];
}
public function getHandledDomains(): array
{
return ['element14.com', 'farnell.com', 'newark.com'];
}
public function getIDFromURL(string $url): ?string
{
//Input URL example: https://de.farnell.com/on-semiconductor/bc547b/transistor-npn-to-92/dp/1017673
//The digits after the /dp/ are the part ID
$matches = [];
if (preg_match('#/dp/(\d+)#', $url, $matches) === 1) {
return $matches[1];
}
return null;
}
}

View File

@@ -1,437 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\InfoProviderSystem\Providers;
use App\Exceptions\ProviderIDNotSupportedException;
use App\Services\InfoProviderSystem\DTOs\ParameterDTO;
use App\Services\InfoProviderSystem\DTOs\PartDetailDTO;
use App\Services\InfoProviderSystem\DTOs\PriceDTO;
use App\Services\InfoProviderSystem\DTOs\PurchaseInfoDTO;
use App\Services\InfoProviderSystem\DTOs\SearchResultDTO;
use App\Services\InfoProviderSystem\PartInfoRetriever;
use App\Services\InfoProviderSystem\ProviderRegistry;
use App\Settings\InfoProviderSystem\GenericWebProviderSettings;
use Brick\Schema\Interfaces\BreadcrumbList;
use Brick\Schema\Interfaces\ImageObject;
use Brick\Schema\Interfaces\Product;
use Brick\Schema\Interfaces\PropertyValue;
use Brick\Schema\Interfaces\QuantitativeValue;
use Brick\Schema\Interfaces\Thing;
use Brick\Schema\SchemaReader;
use Brick\Schema\SchemaTypeList;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class GenericWebProvider implements InfoProviderInterface
{
public const DISTRIBUTOR_NAME = 'Website';
private readonly HttpClientInterface $httpClient;
public function __construct(HttpClientInterface $httpClient, private readonly GenericWebProviderSettings $settings,
private readonly ProviderRegistry $providerRegistry, private readonly PartInfoRetriever $infoRetriever,
)
{
$this->httpClient = $httpClient->withOptions(
[
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36',
],
'timeout' => 15,
]
);
}
public function getProviderInfo(): array
{
return [
'name' => 'Generic Web URL',
'description' => 'Tries to extract a part from a given product webpage URL using common metadata standards like JSON-LD and OpenGraph.',
//'url' => 'https://example.com',
'disabled_help' => 'Enable in settings to use this provider',
'settings_class' => GenericWebProviderSettings::class,
];
}
public function getProviderKey(): string
{
return 'generic_web';
}
public function isActive(): bool
{
return $this->settings->enabled;
}
public function searchByKeyword(string $keyword): array
{
$url = $this->fixAndValidateURL($keyword);
//Before loading the page, try to delegate to another provider
$delegatedPart = $this->delegateToOtherProvider($url);
if ($delegatedPart !== null) {
return [$delegatedPart];
}
try {
return [
$this->getDetails($keyword, false) //We already tried delegation
]; } catch (ProviderIDNotSupportedException $e) {
return [];
}
}
private function extractShopName(string $url): string
{
$host = parse_url($url, PHP_URL_HOST);
if ($host === false || $host === null) {
return self::DISTRIBUTOR_NAME;
}
return $host;
}
private function breadcrumbToCategory(?BreadcrumbList $breadcrumbList): ?string
{
if ($breadcrumbList === null) {
return null;
}
$items = $breadcrumbList->itemListElement->getValues();
if (count($items) < 1) {
return null;
}
try {
//Build our category from the breadcrumb items
$categories = [];
foreach ($items as $item) {
if (isset($item->name)) {
$categories[] = trim($item->name->toString());
}
}
} catch (\Throwable) {
return null;
}
return implode(' -> ', $categories);
}
private function productToPart(Product $product, string $url, Crawler $dom, ?BreadcrumbList $categoryBreadcrumb): PartDetailDTO
{
$notes = $product->description->toString() ?? "";
if ($product->disambiguatingDescription !== null) {
if (!empty($notes)) {
$notes .= "\n\n";
}
$notes .= $product->disambiguatingDescription->toString();
}
//Extract vendor infos
$vendor_infos = null;
$offer = $product->offers->getFirstValue();
if ($offer !== null) {
$prices = [];
if ($offer->price->toString() !== null) {
$prices = [new PriceDTO(
minimum_discount_amount: 1,
price: $offer->price->toString(),
currency_iso_code: $offer->priceCurrency?->toString()
)];
} else { //Check for nested offers (like IKEA does it)
$offer2 = $offer->offers->getFirstValue();
if ($offer2 !== null && $offer2->price->toString() !== null) {
$prices = [
new PriceDTO(
minimum_discount_amount: 1,
price: $offer2->price->toString(),
currency_iso_code: $offer2->priceCurrency?->toString()
)
];
}
}
$vendor_infos = [new PurchaseInfoDTO(
distributor_name: $this->extractShopName($url),
order_number: $product->sku?->toString() ?? $product->identifier?->toString() ?? 'Unknown',
prices: $prices,
product_url: $offer->url?->toString() ?? $url,
)];
}
//Extract image:
$image = null;
if ($product->image !== null) {
$imageObj = $product->image->getFirstValue();
if (is_string($imageObj)) {
$image = $imageObj;
} else if ($imageObj instanceof ImageObject) {
$image = $imageObj->contentUrl?->toString() ?? $imageObj->url?->toString();
}
}
//Extract parameters from additionalProperty
$parameters = [];
foreach ($product->additionalProperty->getValues() as $property) {
if ($property instanceof PropertyValue) { //TODO: Handle minValue and maxValue
if ($property->unitText->toString() !== null) {
$parameters[] = ParameterDTO::parseValueField(
name: $property->name->toString() ?? 'Unknown',
value: $property->value->toString() ?? '',
unit: $property->unitText->toString()
);
} else {
$parameters[] = ParameterDTO::parseValueIncludingUnit(
name: $property->name->toString() ?? 'Unknown',
value: $property->value->toString() ?? ''
);
}
}
}
//Try to extract weight
$mass = null;
if (($weight = $product->weight?->getFirstValue()) instanceof QuantitativeValue) {
$mass = $weight->value->toString();
}
return new PartDetailDTO(
provider_key: $this->getProviderKey(),
provider_id: $url,
name: $product->name?->toString() ?? $product->alternateName?->toString() ?? $product->mpn?->toString() ?? 'Unknown Name',
description: $this->getMetaContent($dom, 'og:description') ?? $this->getMetaContent($dom, 'description') ?? '',
category: $this->breadcrumbToCategory($categoryBreadcrumb) ?? $product->category?->toString(),
manufacturer: self::propertyOrString($product->manufacturer) ?? self::propertyOrString($product->brand),
mpn: $product->mpn?->toString(),
preview_image_url: $image,
provider_url: $url,
gtin: $product->gtin14?->toString() ?? $product->gtin13?->toString() ?? $product->gtin12?->toString() ?? $product->gtin8?->toString(),
notes: $notes,
parameters: $parameters,
vendor_infos: $vendor_infos,
mass: $mass,
);
}
private static function propertyOrString(SchemaTypeList|Thing|string|null $value, string $property = "name"): ?string
{
if ($value instanceof SchemaTypeList) {
$value = $value->getFirstValue();
}
if ($value === null) {
return null;
}
if (is_string($value)) {
return $value;
}
return $value->$property?->toString();
}
/**
* Gets the content of a meta tag by its name or property attribute, or null if not found
* @param Crawler $dom
* @param string $name
* @return string|null
*/
private function getMetaContent(Crawler $dom, string $name): ?string
{
$meta = $dom->filter('meta[property="'.$name.'"]');
if ($meta->count() > 0) {
return $meta->attr('content');
}
//Try name attribute
$meta = $dom->filter('meta[name="'.$name.'"]');
if ($meta->count() > 0) {
return $meta->attr('content');
}
return null;
}
/**
* Delegates the URL to another provider if possible, otherwise return null
* @param string $url
* @return SearchResultDTO|null
*/
private function delegateToOtherProvider(string $url): ?SearchResultDTO
{
//Extract domain from url:
$host = parse_url($url, PHP_URL_HOST);
if ($host === false || $host === null) {
return null;
}
$provider = $this->providerRegistry->getProviderHandlingDomain($host);
if ($provider !== null && $provider->isActive() && $provider->getProviderKey() !== $this->getProviderKey()) {
try {
$id = $provider->getIDFromURL($url);
if ($id !== null) {
$results = $this->infoRetriever->searchByKeyword($id, [$provider]);
if (count($results) > 0) {
return $results[0];
}
}
return null;
} catch (ProviderIDNotSupportedException $e) {
//Ignore and continue
return null;
}
}
return null;
}
private function fixAndValidateURL(string $url): string
{
$originalUrl = $url;
//Add scheme if missing
if (!preg_match('/^https?:\/\//', $url)) {
//Remove any leading slashes
$url = ltrim($url, '/');
$url = 'https://'.$url;
}
//If this is not a valid URL with host, domain and path, throw an exception
if (filter_var($url, FILTER_VALIDATE_URL) === false ||
parse_url($url, PHP_URL_HOST) === null ||
parse_url($url, PHP_URL_PATH) === null) {
throw new ProviderIDNotSupportedException("The given ID is not a valid URL: ".$originalUrl);
}
return $url;
}
public function getDetails(string $id, bool $check_for_delegation = true): PartDetailDTO
{
$url = $this->fixAndValidateURL($id);
if ($check_for_delegation) {
//Before loading the page, try to delegate to another provider
$delegatedPart = $this->delegateToOtherProvider($url);
if ($delegatedPart !== null) {
return $this->infoRetriever->getDetailsForSearchResult($delegatedPart);
}
}
//Try to get the webpage content
$response = $this->httpClient->request('GET', $url);
$content = $response->getContent();
$dom = new Crawler($content);
//Try to determine a canonical URL
$canonicalURL = $url;
if ($dom->filter('link[rel="canonical"]')->count() > 0) {
$canonicalURL = $dom->filter('link[rel="canonical"]')->attr('href');
} else if ($dom->filter('meta[property="og:url"]')->count() > 0) {
$canonicalURL = $dom->filter('meta[property="og:url"]')->attr('content');
}
//If the canonical URL is relative, make it absolute
if (parse_url($canonicalURL, PHP_URL_SCHEME) === null) {
$parsedUrl = parse_url($url);
$scheme = $parsedUrl['scheme'] ?? 'https';
$host = $parsedUrl['host'] ?? '';
$canonicalURL = $scheme.'://'.$host.$canonicalURL;
}
$schemaReader = SchemaReader::forAllFormats();
$things = $schemaReader->readHtml($content, $canonicalURL);
//Try to find a breadcrumb schema to extract the category
$categoryBreadCrumbs = null;
foreach ($things as $thing) {
if ($thing instanceof BreadcrumbList) {
$categoryBreadCrumbs = $thing;
break;
}
}
//Try to find a Product schema
foreach ($things as $thing) {
if ($thing instanceof Product) {
return $this->productToPart($thing, $canonicalURL, $dom, $categoryBreadCrumbs);
}
}
//If no JSON-LD data is found, try to extract basic data from meta tags
$pageTitle = $dom->filter('title')->count() > 0 ? $dom->filter('title')->text() : 'Unknown';
$prices = [];
if ($price = $this->getMetaContent($dom, 'product:price:amount')) {
$prices[] = new PriceDTO(
minimum_discount_amount: 1,
price: $price,
currency_iso_code: $this->getMetaContent($dom, 'product:price:currency'),
);
} else {
//Amazon fallback
$amazonAmount = $dom->filter('input[type="hidden"][name*="amount"]');
if ($amazonAmount->count() > 0) {
$prices[] = new PriceDTO(
minimum_discount_amount: 1,
price: $amazonAmount->first()->attr('value'),
currency_iso_code: $dom->filter('input[type="hidden"][name*="currencyCode"]')->first()->attr('value'),
);
}
}
$vendor_infos = [new PurchaseInfoDTO(
distributor_name: $this->extractShopName($canonicalURL),
order_number: 'Unknown',
prices: $prices,
product_url: $canonicalURL,
)];
return new PartDetailDTO(
provider_key: $this->getProviderKey(),
provider_id: $canonicalURL,
name: $this->getMetaContent($dom, 'og:title') ?? $pageTitle,
description: $this->getMetaContent($dom, 'og:description') ?? $this->getMetaContent($dom, 'description') ?? '',
manufacturer: $this->getMetaContent($dom, 'product:brand'),
preview_image_url: $this->getMetaContent($dom, 'og:image'),
provider_url: $canonicalURL,
vendor_infos: $vendor_infos,
);
}
public function getCapabilities(): array
{
return [
ProviderCapabilities::BASIC,
ProviderCapabilities::PICTURE,
ProviderCapabilities::PRICE,
ProviderCapabilities::GTIN,
];
}
}

View File

@@ -33,7 +33,7 @@ use App\Settings\InfoProviderSystem\LCSCSettings;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class LCSCProvider implements BatchInfoProviderInterface, URLHandlerInfoProviderInterface
class LCSCProvider implements BatchInfoProviderInterface
{
private const ENDPOINT_URL = 'https://wmsc.lcsc.com/ftps/wm';
@@ -452,21 +452,4 @@ class LCSCProvider implements BatchInfoProviderInterface, URLHandlerInfoProvider
ProviderCapabilities::FOOTPRINT,
];
}
public function getHandledDomains(): array
{
return ['lcsc.com'];
}
public function getIDFromURL(string $url): ?string
{
//Input example: https://www.lcsc.com/product-detail/C258144.html?s_z=n_BC547
//The part between the "C" and the ".html" is the unique ID
$matches = [];
if (preg_match("#/product-detail/(\w+)\.html#", $url, $matches) > 0) {
return $matches[1];
}
return null;
}
}

View File

@@ -36,7 +36,7 @@ use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class PollinProvider implements InfoProviderInterface, URLHandlerInfoProviderInterface
class PollinProvider implements InfoProviderInterface
{
public function __construct(private readonly HttpClientInterface $client,
@@ -141,16 +141,11 @@ class PollinProvider implements InfoProviderInterface, URLHandlerInfoProviderInt
$orderId = trim($dom->filter('span[itemprop="sku"]')->text()); //Text is important here
//Calculate the mass
$massDom = $dom->filter('meta[itemprop="weight"]');
if ($massDom->count() > 0) {
$massStr = $massDom->attr('content');
$massStr = str_replace('kg', '', $massStr);
//Convert to float and convert to grams
$mass = (float) $massStr * 1000;
} else {
$mass = null;
}
$massStr = $dom->filter('meta[itemprop="weight"]')->attr('content');
//Remove the unit
$massStr = str_replace('kg', '', $massStr);
//Convert to float and convert to grams
$mass = (float) $massStr * 1000;
//Parse purchase info
$purchaseInfo = new PurchaseInfoDTO('Pollin', $orderId, $this->parsePrices($dom), $productPageUrl);
@@ -253,22 +248,4 @@ class PollinProvider implements InfoProviderInterface, URLHandlerInfoProviderInt
ProviderCapabilities::DATASHEET
];
}
public function getHandledDomains(): array
{
return ['pollin.de'];
}
public function getIDFromURL(string $url): ?string
{
//URL like: https://www.pollin.de/p/shelly-bluetooth-schalter-und-dimmer-blu-zb-button-plug-play-mocha-592325
//Extract the 6-digit number at the end of the URL
$matches = [];
if (preg_match('/-(\d{6})(?:\/|$)/', $url, $matches)) {
return $matches[1];
}
return null;
}
}
}

View File

@@ -43,9 +43,6 @@ enum ProviderCapabilities
/** Information about the footprint of a part */
case FOOTPRINT;
/** Provider can provide GTIN for a part */
case GTIN;
/**
* Get the order index for displaying capabilities in a stable order.
* @return int
@@ -58,7 +55,6 @@ enum ProviderCapabilities
self::DATASHEET => 3,
self::PRICE => 4,
self::FOOTPRINT => 5,
self::GTIN => 6,
};
}
@@ -70,7 +66,6 @@ enum ProviderCapabilities
self::PICTURE => 'picture',
self::DATASHEET => 'datasheet',
self::PRICE => 'price',
self::GTIN => 'gtin',
};
}
@@ -82,7 +77,6 @@ enum ProviderCapabilities
self::PICTURE => 'fa-image',
self::DATASHEET => 'fa-file-alt',
self::PRICE => 'fa-money-bill-wave',
self::GTIN => 'fa-barcode',
};
}
}

View File

@@ -84,8 +84,6 @@ class ReicheltProvider implements InfoProviderInterface
$name = $element->filter('meta[itemprop="name"]')->attr('content');
$sku = $element->filter('meta[itemprop="sku"]')->attr('content');
//Try to extract a picture URL:
$pictureURL = $element->filter("div.al_artlogo img")->attr('src');
@@ -97,8 +95,7 @@ class ReicheltProvider implements InfoProviderInterface
category: null,
manufacturer: $sku,
preview_image_url: $pictureURL,
provider_url: $element->filter('a.al_artinfo_link')->attr('href'),
provider_url: $element->filter('a.al_artinfo_link')->attr('href')
);
});
@@ -149,15 +146,6 @@ class ReicheltProvider implements InfoProviderInterface
$priceString = $dom->filter('meta[itemprop="price"]')->attr('content');
$currency = $dom->filter('meta[itemprop="priceCurrency"]')->attr('content', 'EUR');
$gtin = null;
foreach (['gtin13', 'gtin14', 'gtin12', 'gtin8'] as $gtinType) {
if ($dom->filter("[itemprop=\"$gtinType\"]")->count() > 0) {
$gtin = $dom->filter("[itemprop=\"$gtinType\"]")->innerText();
break;
}
}
//Create purchase info
$purchaseInfo = new PurchaseInfoDTO(
distributor_name: self::DISTRIBUTOR_NAME,
@@ -179,11 +167,10 @@ class ReicheltProvider implements InfoProviderInterface
mpn: $this->parseMPN($dom),
preview_image_url: $json[0]['article_picture'],
provider_url: $productPage,
gtin: $gtin,
notes: $notes,
datasheets: $datasheets,
parameters: $this->parseParameters($dom),
vendor_infos: [$purchaseInfo],
vendor_infos: [$purchaseInfo]
);
}
@@ -286,7 +273,6 @@ class ReicheltProvider implements InfoProviderInterface
ProviderCapabilities::PICTURE,
ProviderCapabilities::DATASHEET,
ProviderCapabilities::PRICE,
ProviderCapabilities::GTIN,
];
}
}

View File

@@ -32,7 +32,7 @@ use App\Services\InfoProviderSystem\DTOs\PurchaseInfoDTO;
use App\Services\InfoProviderSystem\DTOs\SearchResultDTO;
use App\Settings\InfoProviderSystem\TMESettings;
class TMEProvider implements InfoProviderInterface, URLHandlerInfoProviderInterface
class TMEProvider implements InfoProviderInterface
{
private const VENDOR_NAME = 'TME';
@@ -296,22 +296,4 @@ class TMEProvider implements InfoProviderInterface, URLHandlerInfoProviderInterf
ProviderCapabilities::PRICE,
];
}
public function getHandledDomains(): array
{
return ['tme.eu'];
}
public function getIDFromURL(string $url): ?string
{
//Input: https://www.tme.eu/de/details/fi321_se/kuhler/alutronic/
//The ID is the part after the details segment and before the next slash
$matches = [];
if (preg_match('#/details/([^/]+)/#', $url, $matches) === 1) {
return $matches[1];
}
return null;
}
}

View File

@@ -1,43 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\InfoProviderSystem\Providers;
/**
* If an interface
*/
interface URLHandlerInfoProviderInterface
{
/**
* Returns a list of supported domains (e.g. ["digikey.com"])
* @return array An array of supported domains
*/
public function getHandledDomains(): array;
/**
* Extracts the unique ID of a part from a given URL. It is okay if this is not a canonical ID, as long as it can be used to uniquely identify the part within this provider.
* @param string $url The URL to extract the ID from
* @return string|null The extracted ID, or null if the URL is not valid for this provider
*/
public function getIDFromURL(string $url): ?string;
}

View File

@@ -77,10 +77,6 @@ final class BarcodeRedirector
return $this->getURLVendorBarcode($barcodeScan);
}
if ($barcodeScan instanceof GTINBarcodeScanResult) {
return $this->getURLGTINBarcode($barcodeScan);
}
throw new InvalidArgumentException('Unknown $barcodeScan type: '.get_class($barcodeScan));
}
@@ -96,7 +92,7 @@ final class BarcodeRedirector
throw new EntityNotFoundException();
}
return $this->urlGenerator->generate('app_part_show', ['id' => $lot->getPart()->getID(), 'highlightLot' => $lot->getID()]);
return $this->urlGenerator->generate('app_part_show', ['id' => $lot->getPart()->getID()]);
case LabelSupportedElement::STORELOCATION:
return $this->urlGenerator->generate('part_list_store_location', ['id' => $barcodeScan->target_id]);
@@ -115,16 +111,6 @@ final class BarcodeRedirector
return $this->urlGenerator->generate('app_part_show', ['id' => $part->getID()]);
}
private function getURLGTINBarcode(GTINBarcodeScanResult $barcodeScan): string
{
$part = $this->em->getRepository(Part::class)->findOneBy(['gtin' => $barcodeScan->gtin]);
if (!$part instanceof Part) {
throw new EntityNotFoundException();
}
return $this->urlGenerator->generate('app_part_show', ['id' => $part->getID()]);
}
/**
* Gets a part from a scan of a Vendor Barcode by filtering for parts
* with the same Info Provider Id or, if that fails, by looking for parts with a

View File

@@ -92,9 +92,6 @@ final class BarcodeScanHelper
if ($type === BarcodeSourceType::EIGP114) {
return $this->parseEIGP114Barcode($input);
}
if ($type === BarcodeSourceType::GTIN) {
return $this->parseGTINBarcode($input);
}
//Null means auto and we try the different formats
$result = $this->parseInternalBarcode($input);
@@ -120,19 +117,9 @@ final class BarcodeScanHelper
return $result;
}
//If the result is a valid GTIN barcode, we can parse it directly
if (GTINBarcodeScanResult::isValidGTIN($input)) {
return $this->parseGTINBarcode($input);
}
throw new InvalidArgumentException('Unknown barcode');
}
private function parseGTINBarcode(string $input): GTINBarcodeScanResult
{
return new GTINBarcodeScanResult($input);
}
private function parseEIGP114Barcode(string $input): EIGP114BarcodeScanResult
{
return EIGP114BarcodeScanResult::parseFormat06Code($input);

View File

@@ -42,9 +42,4 @@ enum BarcodeSourceType
* EIGP114 formatted barcodes like used by digikey, mouser, etc.
*/
case EIGP114;
/**
* GTIN /EAN barcodes, which are used on most products in the world. These are checked with the GTIN field of a part.
*/
case GTIN;
}
}

View File

@@ -1,62 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\LabelSystem\BarcodeScanner;
use GtinValidation\GtinValidator;
readonly class GTINBarcodeScanResult implements BarcodeScanResultInterface
{
private GtinValidator $validator;
public function __construct(
public string $gtin,
) {
$this->validator = new GtinValidator($this->gtin);
}
public function getDecodedForInfoMode(): array
{
$obj = $this->validator->getGtinObject();
return [
'GTIN' => $this->gtin,
'GTIN type' => $obj->getType(),
'Valid' => $this->validator->isValid() ? 'Yes' : 'No',
];
}
/**
* Checks if the given input is a valid GTIN. This is used to determine whether a scanned barcode should be interpreted as a GTIN or not.
* @param string $input
* @return bool
*/
public static function isValidGTIN(string $input): bool
{
try {
return (new GtinValidator($input))->isValid();
} catch (\Exception $e) {
return false;
}
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\Misc;
use Symfony\Component\HttpKernel\KernelInterface;
class GitVersionInfo
{
protected string $project_dir;
public function __construct(KernelInterface $kernel)
{
$this->project_dir = $kernel->getProjectDir();
}
/**
* Get the Git branch name of the installed system.
*
* @return string|null The current git branch name. Null, if this is no Git installation
*/
public function getGitBranchName(): ?string
{
if (is_file($this->project_dir.'/.git/HEAD')) {
$git = file($this->project_dir.'/.git/HEAD');
$head = explode('/', $git[0], 3);
if (!isset($head[2])) {
return null;
}
return trim($head[2]);
}
return null; // this is not a Git installation
}
/**
* Get hash of the last git commit (on remote "origin"!).
*
* If this method does not work, try to make a "git pull" first!
*
* @param int $length if this is smaller than 40, only the first $length characters will be returned
*
* @return string|null The hash of the last commit, null If this is no Git installation
*/
public function getGitCommitHash(int $length = 7): ?string
{
$filename = $this->project_dir.'/.git/refs/remotes/origin/'.$this->getGitBranchName();
if (is_file($filename)) {
$head = file($filename);
if (!isset($head[0])) {
return null;
}
$hash = $head[0];
return substr($hash, 0, $length);
}
return null; // this is not a Git installation
}
}

View File

@@ -197,45 +197,4 @@ final class PartLotWithdrawAddHelper
$this->entityManager->remove($origin);
}
}
/**
* Perform a stocktake for the given part lot, setting the amount to the given actual amount.
* Please note that the changes are not flushed to DB yet, you have to do this yourself
* @param PartLot $lot
* @param float $actualAmount
* @param string|null $comment
* @param \DateTimeInterface|null $action_timestamp
* @return void
*/
public function stocktake(PartLot $lot, float $actualAmount, ?string $comment = null, ?\DateTimeInterface $action_timestamp = null): void
{
if ($actualAmount < 0) {
throw new \InvalidArgumentException('Actual amount must be non-negative');
}
$part = $lot->getPart();
//Check whether we have to round the amount
if (!$part->useFloatAmount()) {
$actualAmount = round($actualAmount);
}
$oldAmount = $lot->getAmount();
//Clear any unknown status when doing a stocktake, as we now have a known amount
$lot->setInstockUnknown(false);
$lot->setAmount($actualAmount);
if ($action_timestamp) {
$lot->setLastStocktakeAt(\DateTimeImmutable::createFromInterface($action_timestamp));
} else {
$lot->setLastStocktakeAt(new \DateTimeImmutable()); //Use now if no timestamp is given
}
$event = PartStockChangedLogEntry::stocktake($lot, $oldAmount, $lot->getAmount(), $part->getAmountSum() , $comment, $action_timestamp);
$this->eventLogger->log($event);
//Apply the comment also to global events, so it gets associated with the elementChanged log entry
if (!$this->eventCommentHelper->isMessageSet() && ($comment !== null && $comment !== '')) {
$this->eventCommentHelper->setMessage($comment);
}
}
}

View File

@@ -1,453 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
/**
* Manages Part-DB backups: creation, restoration, and listing.
*
* This service handles all backup-related operations and can be used
* by the Update Manager, CLI commands, or other services.
*/
readonly class BackupManager
{
private const BACKUP_DIR = 'var/backups';
public function __construct(
#[Autowire(param: 'kernel.project_dir')]
private string $projectDir,
private LoggerInterface $logger,
private Filesystem $filesystem,
private VersionManagerInterface $versionManager,
private EntityManagerInterface $entityManager,
private CommandRunHelper $commandRunHelper,
) {
}
/**
* Get the backup directory path.
*/
public function getBackupDir(): string
{
return $this->projectDir . '/' . self::BACKUP_DIR;
}
/**
* Get the current version string for use in filenames.
*/
private function getCurrentVersionString(): string
{
return $this->versionManager->getVersion()->toString();
}
/**
* Create a backup before updating.
*
* @param string|null $targetVersion Optional target version for naming
* @param string|null $prefix Optional prefix for the backup filename
* @return string The path to the created backup file
*/
public function createBackup(?string $targetVersion = null, ?string $prefix = 'backup'): string
{
$backupDir = $this->getBackupDir();
if (!is_dir($backupDir)) {
$this->filesystem->mkdir($backupDir, 0755);
}
$currentVersion = $this->getCurrentVersionString();
// Build filename
if ($targetVersion) {
$targetVersionClean = preg_replace('/[^a-zA-Z0-9\.]/', '', $targetVersion);
$backupFile = $backupDir . '/pre-update-v' . $currentVersion . '-to-' . $targetVersionClean . '-' . date('Y-m-d-His') . '.zip';
} else {
$backupFile = $backupDir . '/' . $prefix . '-v' . $currentVersion . '-' . date('Y-m-d-His') . '.zip';
}
$this->commandRunHelper->runCommand([
'php', 'bin/console', 'partdb:backup',
'--full',
'--overwrite',
$backupFile,
], 'Create backup', 600);
$this->logger->info('Created backup', ['file' => $backupFile]);
return $backupFile;
}
/**
* Get list of backups, that are available, sorted by date descending.
*
* @return array<array{file: string, path: string, date: int, size: int}>
*/
public function getBackups(): array
{
$backupDir = $this->getBackupDir();
if (!is_dir($backupDir)) {
return [];
}
$backups = [];
foreach (glob($backupDir . '/*.zip') as $backupFile) {
$backups[] = [
'file' => basename($backupFile),
'path' => $backupFile,
'date' => filemtime($backupFile),
'size' => filesize($backupFile),
];
}
// Sort by date descending
usort($backups, static fn($a, $b) => $b['date'] <=> $a['date']);
return $backups;
}
/**
* Get details about a specific backup file.
*
* @param string $filename The backup filename
* @return null|array{file: string, path: string, date: int, size: int, from_version: ?string, to_version: ?string, contains_database?: bool, contains_config?: bool, contains_attachments?: bool} Backup details or null if not found
*/
public function getBackupDetails(string $filename): ?array
{
$backupDir = $this->getBackupDir();
$backupPath = $backupDir . '/' . basename($filename);
if (!file_exists($backupPath) || !str_ends_with($backupPath, '.zip')) {
return null;
}
// Parse version info from filename: pre-update-v2.5.1-to-v2.5.0-2024-01-30-185400.zip
$info = [
'file' => basename($backupPath),
'path' => $backupPath,
'date' => filemtime($backupPath),
'size' => filesize($backupPath),
'from_version' => null,
'to_version' => null,
];
if (preg_match('/pre-update-v([\d.]+)-to-v?([\d.]+)-/', $filename, $matches)) {
$info['from_version'] = $matches[1];
$info['to_version'] = $matches[2];
}
// Check what the backup contains by reading the ZIP
try {
$zip = new \ZipArchive();
if ($zip->open($backupPath) === true) {
$info['contains_database'] = $zip->locateName('database.sql') !== false || $zip->locateName('var/app.db') !== false;
$info['contains_config'] = $zip->locateName('.env.local') !== false || $zip->locateName('config/parameters.yaml') !== false;
$info['contains_attachments'] = $zip->locateName('public/media/') !== false || $zip->locateName('uploads/') !== false;
$zip->close();
}
} catch (\Exception $e) {
$this->logger->warning('Could not read backup ZIP contents', ['error' => $e->getMessage()]);
}
return $info;
}
/**
* Delete a backup file.
*
* @param string $filename The backup filename to delete
* @return bool True if deleted successfully
*/
public function deleteBackup(string $filename): bool
{
$backupDir = $this->getBackupDir();
$backupPath = $backupDir . '/' . basename($filename);
if (!file_exists($backupPath) || !str_ends_with($backupPath, '.zip')) {
return false;
}
try {
$this->filesystem->remove($backupPath);
$this->logger->info('Deleted backup', ['file' => $filename]);
return true;
} catch (\Exception $e) {
$this->logger->error('Failed to delete backup', ['file' => $filename, 'error' => $e->getMessage()]);
return false;
}
}
/**
* Restore from a backup file.
*
* @param string $filename The backup filename to restore
* @param bool $restoreDatabase Whether to restore the database
* @param bool $restoreConfig Whether to restore config files
* @param bool $restoreAttachments Whether to restore attachments
* @param callable|null $onProgress Callback for progress updates
* @return array{success: bool, steps: array, error: ?string}
*/
public function restoreBackup(
string $filename,
bool $restoreDatabase = true,
bool $restoreConfig = false,
bool $restoreAttachments = false,
?callable $onProgress = null
): array {
$steps = [];
$startTime = microtime(true);
$log = function (string $step, string $message, bool $success, ?float $duration = null) use (&$steps, $onProgress): void {
$entry = [
'step' => $step,
'message' => $message,
'success' => $success,
'timestamp' => (new \DateTime())->format('c'),
'duration' => $duration,
];
$steps[] = $entry;
$this->logger->info('[Restore] ' . $step . ': ' . $message, ['success' => $success]);
if ($onProgress) {
$onProgress($entry);
}
};
try {
// Validate backup file
$backupDir = $this->getBackupDir();
$backupPath = $backupDir . '/' . basename($filename);
if (!file_exists($backupPath)) {
throw new \RuntimeException('Backup file not found: ' . $filename);
}
$stepStart = microtime(true);
// Step 1: Extract backup to temp directory
$tempDir = sys_get_temp_dir() . '/partdb_restore_' . uniqid();
$this->filesystem->mkdir($tempDir);
$zip = new \ZipArchive();
if ($zip->open($backupPath) !== true) {
throw new \RuntimeException('Could not open backup ZIP file');
}
$zip->extractTo($tempDir);
$zip->close();
$log('extract', 'Extracted backup to temporary directory', true, microtime(true) - $stepStart);
// Step 2: Restore database if requested and present
if ($restoreDatabase) {
$stepStart = microtime(true);
$this->restoreDatabaseFromBackup($tempDir);
$log('database', 'Restored database', true, microtime(true) - $stepStart);
}
// Step 3: Restore config files if requested and present
if ($restoreConfig) {
$stepStart = microtime(true);
$this->restoreConfigFromBackup($tempDir);
$log('config', 'Restored configuration files', true, microtime(true) - $stepStart);
}
// Step 4: Restore attachments if requested and present
if ($restoreAttachments) {
$stepStart = microtime(true);
$this->restoreAttachmentsFromBackup($tempDir);
$log('attachments', 'Restored attachments', true, microtime(true) - $stepStart);
}
// Step 5: Clean up temp directory
$stepStart = microtime(true);
$this->filesystem->remove($tempDir);
$log('cleanup', 'Cleaned up temporary files', true, microtime(true) - $stepStart);
$totalDuration = microtime(true) - $startTime;
$log('complete', sprintf('Restore completed successfully in %.1f seconds', $totalDuration), true);
return [
'success' => true,
'steps' => $steps,
'error' => null,
];
} catch (\Throwable $e) {
$this->logger->error('Restore failed: ' . $e->getMessage(), [
'exception' => $e,
'file' => $filename,
]);
// Try to clean up
try {
if (isset($tempDir) && is_dir($tempDir)) {
$this->filesystem->remove($tempDir);
}
} catch (\Throwable $cleanupError) {
$this->logger->error('Cleanup after failed restore also failed', ['error' => $cleanupError->getMessage()]);
}
return [
'success' => false,
'steps' => $steps,
'error' => $e->getMessage(),
];
}
}
/**
* Restore database from backup.
*/
private function restoreDatabaseFromBackup(string $tempDir): void
{
// Check for SQL dump (MySQL/PostgreSQL)
$sqlFile = $tempDir . '/database.sql';
if (file_exists($sqlFile)) {
// Import SQL using mysql/psql command directly
// First, get database connection params from Doctrine
$connection = $this->entityManager->getConnection();
$params = $connection->getParams();
$platform = $connection->getDatabasePlatform();
if ($platform instanceof \Doctrine\DBAL\Platforms\AbstractMySQLPlatform) {
// Use mysql command to import - need to use shell to handle input redirection
$mysqlCmd = 'mysql';
if (isset($params['host'])) {
$mysqlCmd .= ' -h ' . escapeshellarg($params['host']);
}
if (isset($params['port'])) {
$mysqlCmd .= ' -P ' . escapeshellarg((string)$params['port']);
}
if (isset($params['user'])) {
$mysqlCmd .= ' -u ' . escapeshellarg($params['user']);
}
if (isset($params['password']) && $params['password']) {
$mysqlCmd .= ' -p' . escapeshellarg($params['password']);
}
if (isset($params['dbname'])) {
$mysqlCmd .= ' ' . escapeshellarg($params['dbname']);
}
$mysqlCmd .= ' < ' . escapeshellarg($sqlFile);
// Execute using shell
$process = Process::fromShellCommandline($mysqlCmd, $this->projectDir, null, null, 300);
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException('MySQL import failed: ' . $process->getErrorOutput());
}
} elseif ($platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform) {
// Use psql command to import
$psqlCmd = 'psql';
if (isset($params['host'])) {
$psqlCmd .= ' -h ' . escapeshellarg($params['host']);
}
if (isset($params['port'])) {
$psqlCmd .= ' -p ' . escapeshellarg((string)$params['port']);
}
if (isset($params['user'])) {
$psqlCmd .= ' -U ' . escapeshellarg($params['user']);
}
if (isset($params['dbname'])) {
$psqlCmd .= ' -d ' . escapeshellarg($params['dbname']);
}
$psqlCmd .= ' -f ' . escapeshellarg($sqlFile);
// Set PGPASSWORD environment variable if password is provided
$env = null;
if (isset($params['password']) && $params['password']) {
$env = ['PGPASSWORD' => $params['password']];
}
// Execute using shell
$process = Process::fromShellCommandline($psqlCmd, $this->projectDir, $env, null, 300);
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException('PostgreSQL import failed: ' . $process->getErrorOutput());
}
} else {
throw new \RuntimeException('Unsupported database platform for restore');
}
return;
}
// Check for SQLite database file
$sqliteFile = $tempDir . '/var/app.db';
if (file_exists($sqliteFile)) {
$targetDb = $this->projectDir . '/var/app.db';
$this->filesystem->copy($sqliteFile, $targetDb, true);
return;
}
$this->logger->warning('No database found in backup');
}
/**
* Restore config files from backup.
*/
private function restoreConfigFromBackup(string $tempDir): void
{
// Restore .env.local
$envLocal = $tempDir . '/.env.local';
if (file_exists($envLocal)) {
$this->filesystem->copy($envLocal, $this->projectDir . '/.env.local', true);
}
// Restore config/parameters.yaml
$parametersYaml = $tempDir . '/config/parameters.yaml';
if (file_exists($parametersYaml)) {
$this->filesystem->copy($parametersYaml, $this->projectDir . '/config/parameters.yaml', true);
}
// Restore config/banner.md
$bannerMd = $tempDir . '/config/banner.md';
if (file_exists($bannerMd)) {
$this->filesystem->copy($bannerMd, $this->projectDir . '/config/banner.md', true);
}
}
/**
* Restore attachments from backup.
*/
private function restoreAttachmentsFromBackup(string $tempDir): void
{
// Restore public/media
$publicMedia = $tempDir . '/public/media';
if (is_dir($publicMedia)) {
$this->filesystem->mirror($publicMedia, $this->projectDir . '/public/media', null, ['override' => true]);
}
// Restore uploads
$uploads = $tempDir . '/uploads';
if (is_dir($uploads)) {
$this->filesystem->mirror($uploads, $this->projectDir . '/uploads', null, ['override' => true]);
}
}
}

View File

@@ -1,73 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Process\Process;
class CommandRunHelper
{
public function __construct(
#[Autowire(param: 'kernel.project_dir')] private readonly string $project_dir
)
{
}
/**
* Run a shell command with proper error handling.
*/
public function runCommand(array $command, string $description, int $timeout = 120): string
{
$process = new Process($command, $this->project_dir);
$process->setTimeout($timeout);
// Set environment variables needed for Composer and other tools
// This is especially important when running as www-data which may not have HOME set
// We inherit from current environment and override/add specific variables
$currentEnv = getenv();
if (!is_array($currentEnv)) {
$currentEnv = [];
}
$env = array_merge($currentEnv, [
'HOME' => $this->project_dir.'/var/www-data-home',
'COMPOSER_HOME' => $this->project_dir.'/var/composer',
'PATH' => getenv('PATH') ?: '/usr/local/bin:/usr/bin:/bin',
]);
$process->setEnv($env);
$output = '';
$process->run(function ($type, $buffer) use (&$output) {
$output .= $buffer;
});
if (!$process->isSuccessful()) {
$errorOutput = $process->getErrorOutput() ?: $process->getOutput();
throw new \RuntimeException(
sprintf('%s failed: %s', $description, trim($errorOutput))
);
}
return $output;
}
}

View File

@@ -1,141 +0,0 @@
<?php
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Process\Process;
/**
* This service provides information about the current Git installation (if any).
*/
final readonly class GitVersionInfoProvider
{
public function __construct(#[Autowire(param: 'kernel.project_dir')] private string $project_dir)
{
}
/**
* Check if the project directory is a Git repository.
* @return bool
*/
public function isGitRepo(): bool
{
return is_dir($this->getGitDirectory());
}
/**
* Get the path to the Git directory of the installed system without a trailing slash.
* Even if this is no Git installation, the path is returned.
* @return string The path to the Git directory of the installed system
*/
public function getGitDirectory(): string
{
return $this->project_dir . '/.git';
}
/**
* Get the Git branch name of the installed system.
*
* @return string|null The current git branch name. Null, if this is no Git installation
*/
public function getBranchName(): ?string
{
if (is_file($this->getGitDirectory() . '/HEAD')) {
$git = file($this->getGitDirectory() . '/HEAD');
$head = explode('/', $git[0], 3);
if (!isset($head[2])) {
return null;
}
return trim($head[2]);
}
return null; // this is not a Git installation
}
/**
* Get hash of the last git commit (on remote "origin"!).
*
* If this method does not work, try to make a "git pull" first!
*
* @param int $length if this is smaller than 40, only the first $length characters will be returned
*
* @return string|null The hash of the last commit, null If this is no Git installation
*/
public function getCommitHash(int $length = 8): ?string
{
$path = $this->getGitDirectory() . '/HEAD';
if (!file_exists($path)) {
return null;
}
$head = trim(file_get_contents($path));
// If it's a symbolic ref (e.g., "ref: refs/heads/main")
if (str_starts_with($head, 'ref:')) {
$refPath = $this->getGitDirectory() . '/' . trim(substr($head, 5));
if (file_exists($refPath)) {
$hash = trim(file_get_contents($refPath));
}
} else {
// Otherwise, it's a detached HEAD (the hash is right there)
$hash = $head;
}
return isset($hash) ? substr($hash, 0, $length) : null;
}
/**
* Get the Git remote URL of the installed system.
*/
public function getRemoteURL(): ?string
{
// Get remote URL
$configFile = $this->getGitDirectory() . '/config';
if (file_exists($configFile)) {
$config = file_get_contents($configFile);
if (preg_match('#url = (.+)#', $config, $matches)) {
return trim($matches[1]);
}
}
return null; // this is not a Git installation
}
/**
* Check if there are local changes in the Git repository.
* Attention: This runs a git command, which might be slow!
* @return bool|null True if there are local changes, false if not, null if this is not a Git installation
*/
public function hasLocalChanges(): ?bool
{
$process = new Process(['git', 'status', '--porcelain'], $this->project_dir);
$process->run();
if (!$process->isSuccessful()) {
return null; // this is not a Git installation
}
return !empty(trim($process->getOutput()));
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
/**
* Detects the installation type of Part-DB to determine the appropriate update strategy.
*/
enum InstallationType: string
{
case GIT = 'git';
case DOCKER = 'docker';
case ZIP_RELEASE = 'zip_release';
case UNKNOWN = 'unknown';
public function getLabel(): string
{
return match ($this) {
self::GIT => 'Git Clone',
self::DOCKER => 'Docker',
self::ZIP_RELEASE => 'Release Archive (ZIP File)',
self::UNKNOWN => 'Unknown',
};
}
public function supportsAutoUpdate(): bool
{
return match ($this) {
self::GIT => true,
self::DOCKER => false,
// ZIP_RELEASE auto-update not yet implemented
self::ZIP_RELEASE => false,
self::UNKNOWN => false,
};
}
public function getUpdateInstructions(): string
{
return match ($this) {
self::GIT => 'Run: php bin/console partdb:update',
self::DOCKER => 'Pull the new Docker image and recreate the container: docker-compose pull && docker-compose up -d',
self::ZIP_RELEASE => 'Download the new release ZIP from GitHub, extract it over your installation, and run: php bin/console doctrine:migrations:migrate && php bin/console cache:clear',
self::UNKNOWN => 'Unable to determine installation type. Please update manually.',
};
}
}

View File

@@ -1,153 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Process\Process;
readonly class InstallationTypeDetector
{
public function __construct(#[Autowire(param: 'kernel.project_dir')] private string $project_dir, private GitVersionInfoProvider $gitVersionInfoProvider)
{
}
/**
* Detect the installation type based on filesystem markers.
*/
public function detect(): InstallationType
{
// Check for Docker environment first
if ($this->isDocker()) {
return InstallationType::DOCKER;
}
// Check for Git installation
if ($this->isGitInstall()) {
return InstallationType::GIT;
}
// Check for ZIP release (has VERSION file but no .git)
if ($this->isZipRelease()) {
return InstallationType::ZIP_RELEASE;
}
return InstallationType::UNKNOWN;
}
/**
* Check if running inside a Docker container.
*/
public function isDocker(): bool
{
// Check for /.dockerenv file
if (file_exists('/.dockerenv')) {
return true;
}
// Check for DOCKER environment variable
if (getenv('DOCKER') !== false) {
return true;
}
// Check for container runtime in cgroup
if (file_exists('/proc/1/cgroup')) {
$cgroup = @file_get_contents('/proc/1/cgroup');
if ($cgroup !== false && (str_contains($cgroup, 'docker') || str_contains($cgroup, 'containerd'))) {
return true;
}
}
return false;
}
/**
* Check if this is a Git-based installation.
*/
public function isGitInstall(): bool
{
return $this->gitVersionInfoProvider->isGitRepo();
}
/**
* Check if this appears to be a ZIP release installation.
*/
public function isZipRelease(): bool
{
// Has VERSION file but no .git directory
return file_exists($this->project_dir . '/VERSION') && !$this->isGitInstall();
}
/**
* Get detailed information about the installation.
*/
public function getInstallationInfo(): array
{
$type = $this->detect();
$info = [
'type' => $type,
'type_name' => $type->getLabel(),
'supports_auto_update' => $type->supportsAutoUpdate(),
'update_instructions' => $type->getUpdateInstructions(),
'project_dir' => $this->project_dir,
];
if ($type === InstallationType::GIT) {
$info['git'] = $this->getGitInfo();
}
if ($type === InstallationType::DOCKER) {
$info['docker'] = $this->getDockerInfo();
}
return $info;
}
/**
* Get Git-specific information.
* @return array{branch: string|null, commit: string|null, remote_url: string|null, has_local_changes: bool}
*/
private function getGitInfo(): array
{
return [
'branch' => $this->gitVersionInfoProvider->getBranchName(),
'commit' => $this->gitVersionInfoProvider->getCommitHash(8),
'remote_url' => $this->gitVersionInfoProvider->getRemoteURL(),
'has_local_changes' => $this->gitVersionInfoProvider->hasLocalChanges() ?? false,
];
}
/**
* Get Docker-specific information.
* @return array{container_id: string|null, image: string|null}
*/
private function getDockerInfo(): array
{
return [
'container_id' => @file_get_contents('/proc/1/cpuset') ?: null,
'image' => getenv('DOCKER_IMAGE') ?: null,
];
}
}

View File

@@ -24,23 +24,28 @@ declare(strict_types=1);
namespace App\Services\System;
use App\Settings\SystemSettings\PrivacySettings;
use Psr\Log\LoggerInterface;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Version\Version;
/**
* This class checks if a new version of Part-DB is available.
*/
class UpdateAvailableFacade
class UpdateAvailableManager
{
private const API_URL = 'https://api.github.com/repos/Part-DB/Part-DB-server/releases/latest';
private const CACHE_KEY = 'uam_latest_version';
private const CACHE_TTL = 60 * 60 * 24 * 2; // 2 day
public function __construct(
private readonly CacheInterface $updateCache,
private readonly PrivacySettings $privacySettings,
private readonly UpdateChecker $updateChecker,
)
public function __construct(private readonly HttpClientInterface $httpClient,
private readonly CacheInterface $updateCache, private readonly VersionManagerInterface $versionManager,
private readonly PrivacySettings $privacySettings, private readonly LoggerInterface $logger,
#[Autowire(param: 'kernel.debug')] private readonly bool $is_dev_mode)
{
}
@@ -84,7 +89,9 @@ class UpdateAvailableFacade
}
$latestVersion = $this->getLatestVersion();
return $this->updateChecker->isNewerVersionThanCurrent($latestVersion);
$currentVersion = $this->versionManager->getVersion();
return $latestVersion->isGreaterThan($currentVersion);
}
/**
@@ -104,7 +111,34 @@ class UpdateAvailableFacade
return $this->updateCache->get(self::CACHE_KEY, function (ItemInterface $item) {
$item->expiresAfter(self::CACHE_TTL);
return $this->updateChecker->getLatestVersion();
try {
$response = $this->httpClient->request('GET', self::API_URL);
$result = $response->toArray();
$tag_name = $result['tag_name'];
// Remove the leading 'v' from the tag name
$version = substr($tag_name, 1);
return [
'version' => $version,
'url' => $result['html_url'],
];
} catch (\Exception $e) {
//When we are in dev mode, throw the exception, otherwise just silently log it
if ($this->is_dev_mode) {
throw $e;
}
//In the case of an error, try it again after half of the cache time
$item->expiresAfter(self::CACHE_TTL / 2);
$this->logger->error('Checking for updates failed: ' . $e->getMessage());
return [
'version' => '0.0.1',
'url' => 'update-checking-error'
];
}
});
}
}
}

View File

@@ -1,338 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use App\Settings\SystemSettings\PrivacySettings;
use Psr\Log\LoggerInterface;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Process\Process;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Version\Version;
/**
* Enhanced update checker that fetches release information including changelogs.
*/
class UpdateChecker
{
private const GITHUB_API_BASE = 'https://api.github.com/repos/Part-DB/Part-DB-server';
private const CACHE_KEY_RELEASES = 'update_checker_releases';
private const CACHE_KEY_COMMITS = 'update_checker_commits_behind';
private const CACHE_TTL = 60 * 60 * 6; // 6 hours
private const CACHE_TTL_ERROR = 60 * 60; // 1 hour on error
public function __construct(private readonly HttpClientInterface $httpClient,
private readonly CacheInterface $updateCache, private readonly VersionManagerInterface $versionManager,
private readonly PrivacySettings $privacySettings, private readonly LoggerInterface $logger,
private readonly InstallationTypeDetector $installationTypeDetector,
private readonly GitVersionInfoProvider $gitVersionInfoProvider,
#[Autowire(param: 'kernel.debug')] private readonly bool $is_dev_mode,
#[Autowire(param: 'kernel.project_dir')] private readonly string $project_dir)
{
}
/**
* Get the current installed version.
*/
public function getCurrentVersion(): Version
{
return $this->versionManager->getVersion();
}
/**
* Get the current version as string.
*/
public function getCurrentVersionString(): string
{
return $this->getCurrentVersion()->toString();
}
/**
* Get Git repository information.
* @return array{branch: ?string, commit: ?string, has_local_changes: bool, commits_behind: int, is_git_install: bool}
*/
private function getGitInfo(): array
{
$info = [
'branch' => null,
'commit' => null,
'has_local_changes' => false,
'commits_behind' => 0,
'is_git_install' => false,
];
if (!$this->gitVersionInfoProvider->isGitRepo()) {
return $info;
}
$info['is_git_install'] = true;
$info['branch'] = $this->gitVersionInfoProvider->getBranchName();
$info['commit'] = $this->gitVersionInfoProvider->getCommitHash(8);
$info['has_local_changes'] = $this->gitVersionInfoProvider->hasLocalChanges();
// Get commits behind (fetch first)
if ($info['branch']) {
// Try to get cached commits behind count
$info['commits_behind'] = $this->getCommitsBehind($info['branch']);
}
return $info;
}
/**
* Get number of commits behind the remote branch (cached).
*/
private function getCommitsBehind(string $branch): int
{
if (!$this->privacySettings->checkForUpdates) {
return 0;
}
$cacheKey = self::CACHE_KEY_COMMITS . '_' . hash('xxh3', $branch);
return $this->updateCache->get($cacheKey, function (ItemInterface $item) use ($branch) {
$item->expiresAfter(self::CACHE_TTL);
// Fetch from remote first
$process = new Process(['git', 'fetch', '--tags', 'origin'], $this->project_dir);
$process->run();
// Count commits behind
$process = new Process(['git', 'rev-list', 'HEAD..origin/' . $branch, '--count'], $this->project_dir);
$process->run();
return $process->isSuccessful() ? (int) trim($process->getOutput()) : 0;
});
}
/**
* Force refresh git information by invalidating cache.
*/
public function refreshVersionInfo(): void
{
$gitBranch = $this->gitVersionInfoProvider->getBranchName();
if ($gitBranch) {
$this->updateCache->delete(self::CACHE_KEY_COMMITS . '_' . hash('xxh3', $gitBranch));
}
$this->updateCache->delete(self::CACHE_KEY_RELEASES);
}
/**
* Get all available releases from GitHub (cached).
*
* @return array<array{version: string, tag: string, name: string, url: string, published_at: string, body: string, prerelease: bool, draft:bool, assets: array, tarball_url: ?string, zipball_url: ?string}>
*/
public function getAvailableReleases(int $limit = 10): array
{
if (!$this->privacySettings->checkForUpdates) {
return [];
}
return $this->updateCache->get(self::CACHE_KEY_RELEASES, function (ItemInterface $item) use ($limit) {
$item->expiresAfter(self::CACHE_TTL);
try {
$response = $this->httpClient->request('GET', self::GITHUB_API_BASE . '/releases', [
'query' => ['per_page' => $limit],
'headers' => [
'Accept' => 'application/vnd.github.v3+json',
'User-Agent' => 'Part-DB-Update-Checker',
],
]);
$releases = [];
foreach ($response->toArray() as $release) {
// Extract assets (for ZIP download)
$assets = [];
foreach ($release['assets'] ?? [] as $asset) {
if (str_ends_with($asset['name'], '.zip') || str_ends_with($asset['name'], '.tar.gz')) {
$assets[] = [
'name' => $asset['name'],
'url' => $asset['browser_download_url'],
'size' => $asset['size'],
];
}
}
$releases[] = [
'version' => ltrim($release['tag_name'], 'v'),
'tag' => $release['tag_name'],
'name' => $release['name'] ?? $release['tag_name'],
'url' => $release['html_url'],
'published_at' => $release['published_at'],
'body' => $release['body'] ?? '',
'prerelease' => $release['prerelease'] ?? false,
'draft' => $release['draft'] ?? false,
'assets' => $assets,
'tarball_url' => $release['tarball_url'] ?? null,
'zipball_url' => $release['zipball_url'] ?? null,
];
}
return $releases;
} catch (\Exception $e) {
$this->logger->error('Failed to fetch releases from GitHub: ' . $e->getMessage());
$item->expiresAfter(self::CACHE_TTL_ERROR);
if ($this->is_dev_mode) {
throw $e;
}
return [];
}
});
}
/**
* Get the latest stable release.
* @return array{version: string, tag: string, name: string, url: string, published_at: string, body: string, prerelease: bool, assets: array}|null
*/
public function getLatestVersion(bool $includePrerelease = false): ?array
{
$releases = $this->getAvailableReleases();
foreach ($releases as $release) {
// Skip drafts always
if ($release['draft']) {
continue;
}
// Skip prereleases unless explicitly included
if (!$includePrerelease && $release['prerelease']) {
continue;
}
return $release;
}
return null;
}
/**
* Check if a specific version is newer than current.
*/
public function isNewerVersionThanCurrent(Version|string $version): bool
{
if ($version instanceof Version) {
return $version->isGreaterThan($this->getCurrentVersion());
}
try {
return Version::fromString(ltrim($version, 'v'))->isGreaterThan($this->getCurrentVersion());
} catch (\Exception) {
return false;
}
}
/**
* Get comprehensive update status.
* @return array{current_version: string, latest_version: ?string, latest_tag: ?string, update_available: bool, release_notes: ?string, release_url: ?string,
* published_at: ?string, git: array, installation: array, can_auto_update: bool, update_blockers: array, check_enabled: bool}
*/
public function getUpdateStatus(): array
{
$current = $this->getCurrentVersion();
$latest = $this->getLatestVersion();
$gitInfo = $this->getGitInfo();
$installInfo = $this->installationTypeDetector->getInstallationInfo();
$updateAvailable = false;
$latestVersion = null;
$latestTag = null;
if ($latest) {
try {
$latestVersionObj = Version::fromString($latest['version']);
$updateAvailable = $latestVersionObj->isGreaterThan($current);
$latestVersion = $latest['version'];
$latestTag = $latest['tag'];
} catch (\Exception) {
// Invalid version string
}
}
// Determine if we can auto-update
$canAutoUpdate = $installInfo['supports_auto_update'];
$updateBlockers = [];
if ($gitInfo['has_local_changes']) {
$canAutoUpdate = false;
$updateBlockers[] = 'local_changes';
}
if ($installInfo['type'] === InstallationType::DOCKER) {
$updateBlockers[] = 'docker_installation';
}
return [
'current_version' => $current->toString(),
'latest_version' => $latestVersion,
'latest_tag' => $latestTag,
'update_available' => $updateAvailable,
'release_notes' => $latest['body'] ?? null,
'release_url' => $latest['url'] ?? null,
'published_at' => $latest['published_at'] ?? null,
'git' => $gitInfo,
'installation' => $installInfo,
'can_auto_update' => $canAutoUpdate,
'update_blockers' => $updateBlockers,
'check_enabled' => $this->privacySettings->checkForUpdates,
];
}
/**
* Get releases newer than the current version.
* @return array<array{version: string, tag: string, name: string, url: string, published_at: string, body: string, prerelease: bool, assets: array}>
*/
public function getAvailableUpdates(bool $includePrerelease = false): array
{
$releases = $this->getAvailableReleases();
$current = $this->getCurrentVersion();
$updates = [];
foreach ($releases as $release) {
if ($release['draft']) {
continue;
}
if (!$includePrerelease && $release['prerelease']) {
continue;
}
try {
$releaseVersion = Version::fromString($release['version']);
if ($releaseVersion->isGreaterThan($current)) {
$updates[] = $release;
}
} catch (\Exception) {
continue;
}
}
return $updates;
}
}

View File

@@ -1,940 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Services\System;
use Psr\Log\LoggerInterface;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
/**
* Handles the execution of Part-DB updates with safety mechanisms.
*
* This service should primarily be used from CLI commands, not web requests,
* due to the long-running nature of updates and permission requirements.
*
* For web requests, use startBackgroundUpdate() method.
*/
class UpdateExecutor
{
private const LOCK_FILE = 'var/update.lock';
private const MAINTENANCE_FILE = 'var/maintenance.flag';
private const UPDATE_LOG_DIR = 'var/log/updates';
private const PROGRESS_FILE = 'var/update_progress.json';
/** @var array<array{step: string, message: string, success: bool, timestamp: string, duration: ?float}> */
private array $steps = [];
private ?string $currentLogFile = null;
public function __construct(
#[Autowire(param: 'kernel.project_dir')]
private readonly string $project_dir,
private readonly LoggerInterface $logger,
private readonly Filesystem $filesystem,
private readonly InstallationTypeDetector $installationTypeDetector,
private readonly UpdateChecker $updateChecker,
private readonly BackupManager $backupManager,
private readonly CommandRunHelper $commandRunHelper,
#[Autowire(param: 'app.debug_mode')]
private readonly bool $debugMode = false,
) {
}
/**
* Get the current version string for use in filenames.
*/
private function getCurrentVersionString(): string
{
return $this->updateChecker->getCurrentVersionString();
}
/**
* Check if an update is currently in progress.
*/
public function isLocked(): bool
{
// Check if lock is stale (older than 1 hour)
$lockData = $this->getLockInfo();
if ($lockData === null) {
return false;
}
if ($lockData && isset($lockData['started_at'])) {
$startedAt = new \DateTime($lockData['started_at']);
$now = new \DateTime();
$diff = $now->getTimestamp() - $startedAt->getTimestamp();
// If lock is older than 1 hour, consider it stale
if ($diff > 3600) {
$this->logger->warning('Found stale update lock, removing it');
$this->releaseLock();
return false;
}
}
return true;
}
/**
* Get lock information, or null if not locked.
* @return null|array{started_at: string, pid: int, user: string}
*/
public function getLockInfo(): ?array
{
$lockFile = $this->project_dir . '/' . self::LOCK_FILE;
if (!file_exists($lockFile)) {
return null;
}
return json_decode(file_get_contents($lockFile), true, 512, JSON_THROW_ON_ERROR);
}
/**
* Check if maintenance mode is enabled.
*/
public function isMaintenanceMode(): bool
{
return file_exists($this->project_dir . '/' . self::MAINTENANCE_FILE);
}
/**
* Get maintenance mode information.
* @return null|array{enabled_at: string, reason: string}
*/
public function getMaintenanceInfo(): ?array
{
$maintenanceFile = $this->project_dir . '/' . self::MAINTENANCE_FILE;
if (!file_exists($maintenanceFile)) {
return null;
}
return json_decode(file_get_contents($maintenanceFile), true, 512, JSON_THROW_ON_ERROR);
}
/**
* Acquire an exclusive lock for the update process.
*/
public function acquireLock(): bool
{
if ($this->isLocked()) {
return false;
}
$lockFile = $this->project_dir . '/' . self::LOCK_FILE;
$lockDir = dirname($lockFile);
if (!is_dir($lockDir)) {
$this->filesystem->mkdir($lockDir);
}
$lockData = [
'started_at' => (new \DateTime())->format('c'),
'pid' => getmypid(),
'user' => get_current_user(),
];
$this->filesystem->dumpFile($lockFile, json_encode($lockData, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
return true;
}
/**
* Release the update lock.
*/
public function releaseLock(): void
{
$lockFile = $this->project_dir . '/' . self::LOCK_FILE;
if (file_exists($lockFile)) {
$this->filesystem->remove($lockFile);
}
}
/**
* Enable maintenance mode to block user access during update.
*/
public function enableMaintenanceMode(string $reason = 'Update in progress'): void
{
$maintenanceFile = $this->project_dir . '/' . self::MAINTENANCE_FILE;
$maintenanceDir = dirname($maintenanceFile);
if (!is_dir($maintenanceDir)) {
$this->filesystem->mkdir($maintenanceDir);
}
$data = [
'enabled_at' => (new \DateTime())->format('c'),
'reason' => $reason,
];
$this->filesystem->dumpFile($maintenanceFile, json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
/**
* Disable maintenance mode.
*/
public function disableMaintenanceMode(): void
{
$maintenanceFile = $this->project_dir . '/' . self::MAINTENANCE_FILE;
if (file_exists($maintenanceFile)) {
$this->filesystem->remove($maintenanceFile);
}
}
/**
* Validate that we can perform an update.
*
* @return array{valid: bool, errors: array<string>}
*/
public function validateUpdatePreconditions(): array
{
$errors = [];
// Check installation type
$installType = $this->installationTypeDetector->detect();
if (!$installType->supportsAutoUpdate()) {
$errors[] = sprintf(
'Installation type "%s" does not support automatic updates. %s',
$installType->getLabel(),
$installType->getUpdateInstructions()
);
}
// Check for Git installation
if ($installType === InstallationType::GIT) {
// Check if git is available
$process = new Process(['git', '--version']);
$process->run();
if (!$process->isSuccessful()) {
$errors[] = 'Git command not found. Please ensure Git is installed and in PATH.';
}
// Check for local changes
$process = new Process(['git', 'status', '--porcelain'], $this->project_dir);
$process->run();
if (!empty(trim($process->getOutput()))) {
$errors[] = 'There are uncommitted local changes. Please commit or stash them before updating.';
}
}
// Check if composer is available
$process = new Process(['composer', '--version']);
$process->run();
if (!$process->isSuccessful()) {
$errors[] = 'Composer command not found. Please ensure Composer is installed and in PATH.';
}
// Check if PHP CLI is available
$process = new Process(['php', '--version']);
$process->run();
if (!$process->isSuccessful()) {
$errors[] = 'PHP CLI not found. Please ensure PHP is installed and in PATH.';
}
// Check if yarn is available (for frontend assets)
$process = new Process(['yarn', '--version']);
$process->run();
if (!$process->isSuccessful()) {
$errors[] = 'Yarn command not found. Please ensure Yarn is installed and in PATH for frontend asset compilation.';
}
// Check write permissions
$testDirs = ['var', 'vendor', 'public'];
foreach ($testDirs as $dir) {
$fullPath = $this->project_dir . '/' . $dir;
if (is_dir($fullPath) && !is_writable($fullPath)) {
$errors[] = sprintf('Directory "%s" is not writable.', $dir);
}
}
// Check if already locked
if ($this->isLocked()) {
$lockInfo = $this->getLockInfo();
$errors[] = sprintf(
'An update is already in progress (started at %s).',
$lockInfo['started_at'] ?? 'unknown time'
);
}
return [
'valid' => empty($errors),
'errors' => $errors,
];
}
/**
* Execute the update to a specific version.
*
* @param string $targetVersion The target version/tag to update to (e.g., "v2.6.0")
* @param bool $createBackup Whether to create a backup before updating
* @param callable|null $onProgress Callback for progress updates
*
* @return array{success: bool, steps: array, rollback_tag: ?string, error: ?string, log_file: ?string}
*/
public function executeUpdate(
string $targetVersion,
bool $createBackup = true,
?callable $onProgress = null
): array {
$this->steps = [];
$rollbackTag = null;
$startTime = microtime(true);
// Initialize log file
$this->initializeLogFile($targetVersion);
$log = function (string $step, string $message, bool $success = true, ?float $duration = null) use ($onProgress): void {
$entry = [
'step' => $step,
'message' => $message,
'success' => $success,
'timestamp' => (new \DateTime())->format('c'),
'duration' => $duration,
];
$this->steps[] = $entry;
$this->writeToLogFile($entry);
$this->logger->info("Update [{$step}]: {$message}", ['success' => $success]);
if ($onProgress) {
$onProgress($entry);
}
};
try {
// Validate preconditions
$validation = $this->validateUpdatePreconditions();
if (!$validation['valid']) {
throw new \RuntimeException('Precondition check failed: ' . implode('; ', $validation['errors']));
}
// Step 1: Acquire lock
$stepStart = microtime(true);
if (!$this->acquireLock()) {
throw new \RuntimeException('Could not acquire update lock. Another update may be in progress.');
}
$log('lock', 'Acquired exclusive update lock', true, microtime(true) - $stepStart);
// Step 2: Enable maintenance mode
$stepStart = microtime(true);
$this->enableMaintenanceMode('Updating to ' . $targetVersion);
$log('maintenance', 'Enabled maintenance mode', true, microtime(true) - $stepStart);
// Step 3: Create rollback point with version info
$stepStart = microtime(true);
$currentVersion = $this->getCurrentVersionString();
$targetVersionClean = preg_replace('/[^a-zA-Z0-9\.]/', '', $targetVersion);
$rollbackTag = 'pre-update-v' . $currentVersion . '-to-' . $targetVersionClean . '-' . date('Y-m-d-His');
$this->runCommand(['git', 'tag', $rollbackTag], 'Create rollback tag');
$log('rollback_tag', 'Created rollback tag: ' . $rollbackTag, true, microtime(true) - $stepStart);
// Step 4: Create backup (optional)
if ($createBackup) {
$stepStart = microtime(true);
$backupFile = $this->backupManager->createBackup($targetVersion);
$log('backup', 'Created backup: ' . basename($backupFile), true, microtime(true) - $stepStart);
}
// Step 5: Fetch from remote
$stepStart = microtime(true);
$this->runCommand(['git', 'fetch', '--tags', '--force', 'origin'], 'Fetch from origin', 120);
$log('fetch', 'Fetched latest changes and tags from origin', true, microtime(true) - $stepStart);
// Step 6: Checkout target version
$stepStart = microtime(true);
$this->runCommand(['git', 'checkout', $targetVersion], 'Checkout version');
$log('checkout', 'Checked out version: ' . $targetVersion, true, microtime(true) - $stepStart);
// Step 7: Install PHP dependencies
$stepStart = microtime(true);
if ($this->debugMode) {
$this->runCommand([ // Install with dev dependencies in debug mode
'composer',
'install',
'--no-interaction',
'--no-progress',
], 'Install PHP dependencies', 600);
} else {
$this->runCommand([
'composer',
'install',
'--no-dev',
'--optimize-autoloader',
'--no-interaction',
'--no-progress',
], 'Install PHP dependencies', 600);
}
$log('composer', 'Installed/updated PHP dependencies', true, microtime(true) - $stepStart);
// Step 8: Install frontend dependencies
$stepStart = microtime(true);
$this->runCommand([
'yarn', 'install',
'--frozen-lockfile',
'--non-interactive',
], 'Install frontend dependencies', 600);
$log('yarn_install', 'Installed frontend dependencies', true, microtime(true) - $stepStart);
// Step 9: Build frontend assets
$stepStart = microtime(true);
$this->runCommand([
'yarn', 'build',
], 'Build frontend assets', 600);
$log('yarn_build', 'Built frontend assets', true, microtime(true) - $stepStart);
// Step 10: Run database migrations
$stepStart = microtime(true);
$this->runCommand([
'php', 'bin/console', 'doctrine:migrations:migrate',
'--no-interaction',
'--allow-no-migration',
], 'Run migrations', 300);
$log('migrations', 'Database migrations completed', true, microtime(true) - $stepStart);
// Step 11: Clear cache
$stepStart = microtime(true);
$this->runCommand([
'php', 'bin/console', 'cache:clear',
'--env=prod',
'--no-interaction',
], 'Clear cache', 120);
$log('cache_clear', 'Cleared application cache', true, microtime(true) - $stepStart);
// Step 12: Warm up cache
$stepStart = microtime(true);
$this->runCommand([
'php', 'bin/console', 'cache:warmup',
'--env=prod',
], 'Warmup cache', 120);
$log('cache_warmup', 'Warmed up application cache', true, microtime(true) - $stepStart);
// Step 13: Disable maintenance mode
$stepStart = microtime(true);
$this->disableMaintenanceMode();
$log('maintenance_off', 'Disabled maintenance mode', true, microtime(true) - $stepStart);
// Step 14: Release lock
$stepStart = microtime(true);
$this->releaseLock();
$totalDuration = microtime(true) - $startTime;
$log('complete', sprintf('Update completed successfully in %.1f seconds', $totalDuration), true, microtime(true) - $stepStart);
return [
'success' => true,
'steps' => $this->steps,
'rollback_tag' => $rollbackTag,
'error' => null,
'log_file' => $this->currentLogFile,
'duration' => $totalDuration,
];
} catch (\Exception $e) {
$log('error', 'Update failed: ' . $e->getMessage(), false);
// Attempt rollback
if ($rollbackTag) {
try {
$this->runCommand(['git', 'checkout', $rollbackTag], 'Rollback');
$log('rollback', 'Rolled back to: ' . $rollbackTag, true);
// Re-run composer install after rollback
$this->runCommand([
'composer', 'install',
'--no-dev',
'--optimize-autoloader',
'--no-interaction',
], 'Reinstall dependencies after rollback', 600);
$log('rollback_composer', 'Reinstalled PHP dependencies after rollback', true);
// Re-run yarn install after rollback
$this->runCommand([
'yarn', 'install',
'--frozen-lockfile',
'--non-interactive',
], 'Reinstall frontend dependencies after rollback', 600);
$log('rollback_yarn_install', 'Reinstalled frontend dependencies after rollback', true);
// Re-run yarn build after rollback
$this->runCommand([
'yarn', 'build',
], 'Rebuild frontend assets after rollback', 600);
$log('rollback_yarn_build', 'Rebuilt frontend assets after rollback', true);
// Clear cache after rollback
$this->runCommand([
'php', 'bin/console', 'cache:clear',
'--env=prod',
], 'Clear cache after rollback', 120);
$log('rollback_cache', 'Cleared cache after rollback', true);
} catch (\Exception $rollbackError) {
$log('rollback_failed', 'Rollback failed: ' . $rollbackError->getMessage(), false);
}
}
// Clean up
$this->disableMaintenanceMode();
$this->releaseLock();
return [
'success' => false,
'steps' => $this->steps,
'rollback_tag' => $rollbackTag,
'error' => $e->getMessage(),
'log_file' => $this->currentLogFile,
'duration' => microtime(true) - $startTime,
];
}
}
/**
* Run a shell command with proper error handling.
*/
private function runCommand(array $command, string $description, int $timeout = 120): string
{
return $this->commandRunHelper->runCommand($command, $description, $timeout);
}
/**
* Initialize the log file for this update.
*/
private function initializeLogFile(string $targetVersion): void
{
$logDir = $this->project_dir . '/' . self::UPDATE_LOG_DIR;
if (!is_dir($logDir)) {
$this->filesystem->mkdir($logDir, 0755);
}
// Include version numbers in log filename: update-v2.5.1-to-v2.6.0-2024-01-30-185400.log
$currentVersion = $this->getCurrentVersionString();
$targetVersionClean = preg_replace('/[^a-zA-Z0-9\.]/', '', $targetVersion);
$this->currentLogFile = $logDir . '/update-v' . $currentVersion . '-to-' . $targetVersionClean . '-' . date('Y-m-d-His') . '.log';
$header = sprintf(
"Part-DB Update Log\n" .
"==================\n" .
"Started: %s\n" .
"From Version: %s\n" .
"Target Version: %s\n" .
"==================\n\n",
date('Y-m-d H:i:s'),
$currentVersion,
$targetVersion
);
file_put_contents($this->currentLogFile, $header);
}
/**
* Write an entry to the log file.
*/
private function writeToLogFile(array $entry): void
{
if (!$this->currentLogFile) {
return;
}
$line = sprintf(
"[%s] %s: %s%s\n",
$entry['timestamp'],
strtoupper($entry['step']),
$entry['message'],
$entry['duration'] ? sprintf(' (%.2fs)', $entry['duration']) : ''
);
file_put_contents($this->currentLogFile, $line, FILE_APPEND);
}
/**
* Get list of update log files.
* @return array{file: string, path: string, date: int, size: int}[]
*/
public function getUpdateLogs(): array
{
$logDir = $this->project_dir . '/' . self::UPDATE_LOG_DIR;
if (!is_dir($logDir)) {
return [];
}
$logs = [];
foreach (glob($logDir . '/update-*.log') as $logFile) {
$logs[] = [
'file' => basename($logFile),
'path' => $logFile,
'date' => filemtime($logFile),
'size' => filesize($logFile),
];
}
// Sort by date descending
usort($logs, static fn($a, $b) => $b['date'] <=> $a['date']);
return $logs;
}
/**
* Restore from a backup file with maintenance mode and cache clearing.
*
* This wraps BackupManager::restoreBackup with additional safety measures
* like lock acquisition, maintenance mode, and cache operations.
*
* @param string $filename The backup filename to restore
* @param bool $restoreDatabase Whether to restore the database
* @param bool $restoreConfig Whether to restore config files
* @param bool $restoreAttachments Whether to restore attachments
* @param callable|null $onProgress Callback for progress updates
* @return array{success: bool, steps: array, error: ?string}
*/
public function restoreBackup(
string $filename,
bool $restoreDatabase = true,
bool $restoreConfig = false,
bool $restoreAttachments = false,
?callable $onProgress = null
): array {
$this->steps = [];
$startTime = microtime(true);
$log = function (string $step, string $message, bool $success, ?float $duration = null) use ($onProgress): void {
$entry = [
'step' => $step,
'message' => $message,
'success' => $success,
'timestamp' => (new \DateTime())->format('c'),
'duration' => $duration,
];
$this->steps[] = $entry;
$this->logger->info('[Restore] ' . $step . ': ' . $message, ['success' => $success]);
if ($onProgress) {
$onProgress($entry);
}
};
try {
$stepStart = microtime(true);
// Step 1: Acquire lock
if (!$this->acquireLock()) {
throw new \RuntimeException('Could not acquire lock. Another operation may be in progress.');
}
$log('lock', 'Acquired exclusive restore lock', true, microtime(true) - $stepStart);
// Step 2: Enable maintenance mode
$stepStart = microtime(true);
$this->enableMaintenanceMode('Restoring from backup...');
$log('maintenance', 'Enabled maintenance mode', true, microtime(true) - $stepStart);
// Step 3: Delegate to BackupManager for core restoration
$stepStart = microtime(true);
$result = $this->backupManager->restoreBackup(
$filename,
$restoreDatabase,
$restoreConfig,
$restoreAttachments,
function ($entry) use ($log) {
// Forward progress from BackupManager
$log($entry['step'], $entry['message'], $entry['success'], $entry['duration'] ?? null);
}
);
if (!$result['success']) {
throw new \RuntimeException($result['error'] ?? 'Restore failed');
}
// Step 4: Clear cache
$stepStart = microtime(true);
$this->runCommand(['php', 'bin/console', 'cache:clear', '--no-warmup'], 'Clear cache');
$log('cache_clear', 'Cleared application cache', true, microtime(true) - $stepStart);
// Step 5: Warm up cache
$stepStart = microtime(true);
$this->runCommand(['php', 'bin/console', 'cache:warmup'], 'Warm up cache');
$log('cache_warmup', 'Warmed up application cache', true, microtime(true) - $stepStart);
// Step 6: Disable maintenance mode
$stepStart = microtime(true);
$this->disableMaintenanceMode();
$log('maintenance_off', 'Disabled maintenance mode', true, microtime(true) - $stepStart);
// Step 7: Release lock
$this->releaseLock();
$totalDuration = microtime(true) - $startTime;
$log('complete', sprintf('Restore completed successfully in %.1f seconds', $totalDuration), true);
return [
'success' => true,
'steps' => $this->steps,
'error' => null,
];
} catch (\Throwable $e) {
$this->logger->error('Restore failed: ' . $e->getMessage(), [
'exception' => $e,
'file' => $filename,
]);
// Try to clean up
try {
$this->disableMaintenanceMode();
$this->releaseLock();
} catch (\Throwable $cleanupError) {
$this->logger->error('Cleanup after failed restore also failed', ['error' => $cleanupError->getMessage()]);
}
return [
'success' => false,
'steps' => $this->steps,
'error' => $e->getMessage(),
];
}
}
/**
* Get the path to the progress file.
*/
public function getProgressFilePath(): string
{
return $this->project_dir . '/' . self::PROGRESS_FILE;
}
/**
* Save progress to file for web UI polling.
* @param array{status: string, target_version: string, create_backup: bool, started_at: string, current_step: int, total_steps: int, step_name: string, step_message: string, steps: array, error: ?string} $progress
*/
private function saveProgress(array $progress): void
{
$progressFile = $this->getProgressFilePath();
$progressDir = dirname($progressFile);
if (!is_dir($progressDir)) {
$this->filesystem->mkdir($progressDir);
}
$this->filesystem->dumpFile($progressFile, json_encode($progress, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
/**
* Get current update progress from file.
* @return null|array{status: string, target_version: string, create_backup: bool, started_at: string, current_step: int, total_steps: int, step_name: string, step_message: string, steps: array, error: ?string}
*/
public function getProgress(): ?array
{
$progressFile = $this->getProgressFilePath();
if (!file_exists($progressFile)) {
return null;
}
$data = json_decode(file_get_contents($progressFile), true, 512, JSON_THROW_ON_ERROR);
// If the progress file is stale (older than 30 minutes), consider it invalid
if ($data && isset($data['started_at'])) {
$startedAt = strtotime($data['started_at']);
if (time() - $startedAt > 1800) {
$this->clearProgress();
return null;
}
}
return $data;
}
/**
* Clear progress file.
*/
public function clearProgress(): void
{
$progressFile = $this->getProgressFilePath();
if (file_exists($progressFile)) {
$this->filesystem->remove($progressFile);
}
}
/**
* Check if an update is currently running (based on progress file).
*/
public function isUpdateRunning(): bool
{
$progress = $this->getProgress();
if (!$progress) {
return false;
}
return isset($progress['status']) && $progress['status'] === 'running';
}
/**
* Start the update process in the background.
* Returns the process ID or null on failure.
*/
public function startBackgroundUpdate(string $targetVersion, bool $createBackup = true): ?int
{
// Validate first
$validation = $this->validateUpdatePreconditions();
if (!$validation['valid']) {
$this->logger->error('Update validation failed', ['errors' => $validation['errors']]);
return null;
}
// Initialize progress file
$this->saveProgress([
'status' => 'starting',
'target_version' => $targetVersion,
'create_backup' => $createBackup,
'started_at' => (new \DateTime())->format('c'),
'current_step' => 0,
'total_steps' => 14,
'step_name' => 'initializing',
'step_message' => 'Starting update process...',
'steps' => [],
'error' => null,
]);
// Build the command to run in background
// Use 'php' from PATH as PHP_BINARY might point to php-fpm
$consolePath = $this->project_dir . '/bin/console';
$logFile = $this->project_dir . '/var/log/update-background.log';
// Ensure log directory exists
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
$this->filesystem->mkdir($logDir, 0755);
}
//If we are on Windows, we cannot use nohup
if (PHP_OS_FAMILY === 'Windows') {
$command = sprintf(
'start /B php %s partdb:update %s %s --force --no-interaction >> %s 2>&1',
escapeshellarg($consolePath),
escapeshellarg($targetVersion),
$createBackup ? '' : '--no-backup',
escapeshellarg($logFile)
);
} else { //Unix like platforms should be able to use nohup
// Use nohup to properly detach the process from the web request
// The process will continue running even after the PHP request ends
$command = sprintf(
'nohup php %s partdb:update %s %s --force --no-interaction >> %s 2>&1 &',
escapeshellarg($consolePath),
escapeshellarg($targetVersion),
$createBackup ? '' : '--no-backup',
escapeshellarg($logFile)
);
}
$this->logger->info('Starting background update', [
'command' => $command,
'target_version' => $targetVersion,
]);
// Execute in background using shell_exec for proper detachment
// shell_exec with & runs the command in background
//@php-ignore-next-line We really need to use shell_exec here
$output = shell_exec($command);
// Give it a moment to start
usleep(500000); // 500ms
// Check if progress file was updated (indicates process started)
$progress = $this->getProgress();
if ($progress && isset($progress['status'])) {
$this->logger->info('Background update started successfully');
return 1; // Return a non-null value to indicate success
}
$this->logger->error('Background update may not have started', ['output' => $output]);
return 1; // Still return success as the process might just be slow to start
}
/**
* Execute update with progress file updates for web UI.
* This is called by the CLI command and updates the progress file.
*/
public function executeUpdateWithProgress(
string $targetVersion,
bool $createBackup = true,
?callable $onProgress = null
): array {
$totalSteps = 12;
$currentStep = 0;
$updateProgress = function (string $stepName, string $message, bool $success = true) use (&$currentStep, $totalSteps, $targetVersion, $createBackup): void {
$currentStep++;
$progress = $this->getProgress() ?? [
'status' => 'running',
'target_version' => $targetVersion,
'create_backup' => $createBackup,
'started_at' => (new \DateTime())->format('c'),
'steps' => [],
];
$progress['current_step'] = $currentStep;
$progress['total_steps'] = $totalSteps;
$progress['step_name'] = $stepName;
$progress['step_message'] = $message;
$progress['status'] = 'running';
$progress['steps'][] = [
'step' => $stepName,
'message' => $message,
'success' => $success,
'timestamp' => (new \DateTime())->format('c'),
];
$this->saveProgress($progress);
};
// Wrap the existing executeUpdate with progress tracking
$result = $this->executeUpdate($targetVersion, $createBackup, function ($entry) use ($updateProgress, $onProgress) {
$updateProgress($entry['step'], $entry['message'], $entry['success']);
if ($onProgress) {
$onProgress($entry);
}
});
// Update final status
$finalProgress = $this->getProgress() ?? [];
$finalProgress['status'] = $result['success'] ? 'completed' : 'failed';
$finalProgress['completed_at'] = (new \DateTime())->format('c');
$finalProgress['result'] = $result;
$finalProgress['error'] = $result['error'];
$this->saveProgress($finalProgress);
return $result;
}
}

View File

@@ -39,8 +39,6 @@ use App\Entity\UserSystem\User;
use App\Helpers\Trees\TreeViewNode;
use App\Services\Cache\UserCacheKeyGenerator;
use App\Services\ElementTypeNameGenerator;
use App\Services\InfoProviderSystem\Providers\GenericWebProvider;
use App\Settings\InfoProviderSystem\GenericWebProviderSettings;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Cache\ItemInterface;
@@ -60,7 +58,6 @@ class ToolsTreeBuilder
protected UserCacheKeyGenerator $keyGenerator,
protected Security $security,
private readonly ElementTypeNameGenerator $elementTypeNameGenerator,
private readonly GenericWebProviderSettings $genericWebProviderSettings
) {
}
@@ -150,13 +147,6 @@ class ToolsTreeBuilder
$this->urlGenerator->generate('info_providers_search')
))->setIcon('fa-treeview fa-fw fa-solid fa-cloud-arrow-down');
if ($this->genericWebProviderSettings->enabled) {
$nodes[] = (new TreeViewNode(
$this->translator->trans('info_providers.from_url.title'),
$this->urlGenerator->generate('info_providers_from_url')
))->setIcon('fa-treeview fa-fw fa-solid fa-book-atlas');
}
$nodes[] = (new TreeViewNode(
$this->translator->trans('info_providers.bulk_import.manage_jobs'),
$this->urlGenerator->generate('bulk_info_provider_manage')
@@ -325,13 +315,6 @@ class ToolsTreeBuilder
))->setIcon('fa fa-fw fa-gears fa-solid');
}
if ($this->security->isGranted('@system.show_updates')) {
$nodes[] = (new TreeViewNode(
$this->translator->trans('tree.tools.system.update_manager'),
$this->urlGenerator->generate('admin_update_manager')
))->setIcon('fa-fw fa-treeview fa-solid fa-arrow-circle-up');
}
return $nodes;
}
}

View File

@@ -111,9 +111,8 @@ class PermissionPresetsHelper
//Allow to manage Oauth tokens
$this->permissionResolver->setPermission($perm_holder, 'system', 'manage_oauth_tokens', PermissionData::ALLOW);
//Allow to show and manage updates
//Allow to show updates
$this->permissionResolver->setPermission($perm_holder, 'system', 'show_updates', PermissionData::ALLOW);
$this->permissionResolver->setPermission($perm_holder, 'system', 'manage_updates', PermissionData::ALLOW);
}

View File

@@ -157,20 +157,4 @@ class PermissionSchemaUpdater
$permissions->setPermissionValue('system', 'show_updates', $new_value);
}
}
private function upgradeSchemaToVersion4(HasPermissionsInterface $holder): void //@phpstan-ignore-line This is called via reflection
{
$permissions = $holder->getPermissions();
//If the reports.generate permission is not defined yet, set it to the value of reports.read
if (!$permissions->isPermissionSet('parts_stock', 'stocktake')) {
//Set the new permission to true only if both add and withdraw are allowed
$new_value = TrinaryLogicHelper::and(
$permissions->getPermissionValue('parts_stock', 'withdraw'),
$permissions->getPermissionValue('parts_stock', 'add')
);
$permissions->setPermissionValue('parts_stock', 'stocktake', $new_value);
}
}
}

Some files were not shown because too many files have changed in this diff Show More