Compare commits
29 Commits
c963bd9646
..
2.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 81fce773a9 | |||
| 5cdad7fb7d | |||
| a5f8943c72 | |||
| a5f2f79fac | |||
| e86fdf0c9b | |||
| 505349e10b | |||
| c0d3f87a7e | |||
| 1d9b4902d4 | |||
| e707045d63 | |||
| d8a2069640 | |||
| 7fe8453e7a | |||
| 8e229fc77c | |||
| 5915537e83 | |||
| a50b295c59 | |||
| 33381a9950 | |||
| 5e14c1bc22 | |||
| 5f3f1c4fa6 | |||
| 6ab03ba420 | |||
| 31c53eff33 | |||
| ee7f925fb3 | |||
| 263ae063ac | |||
| 71c38b4e90 | |||
| deeeef984e | |||
| f3afede0e1 | |||
| 16075c10c1 | |||
| 5b1d7d1ea2 | |||
| c74a00511c | |||
| 4b27c6a11d | |||
| c6beb9e88b |
@@ -0,0 +1,287 @@
|
|||||||
|
# Gitea Actions per Data-Coupler
|
||||||
|
|
||||||
|
## 📋 Panoramica
|
||||||
|
|
||||||
|
Questo repository utilizza **Gitea Actions** per automatizzare la build e la pubblicazione delle immagini Docker del progetto Data-Coupler.
|
||||||
|
|
||||||
|
## 🔧 Configurazione
|
||||||
|
|
||||||
|
### Prerequisiti
|
||||||
|
|
||||||
|
Per utilizzare Gitea Actions su questo repository, è necessario:
|
||||||
|
|
||||||
|
1. **Gitea Account**: Avere un account su Gitea (gitea.com o istanza self-hosted)
|
||||||
|
2. **Repository Settings**: Abilitare Gitea Actions nelle impostazioni del repository
|
||||||
|
3. **Container Registry**: Avere accesso al Gitea Container Registry
|
||||||
|
4. **Secret Configuration**: Configurare il secret `GITEA_TOKEN`
|
||||||
|
|
||||||
|
### Configurazione del Secret REGISTRY_TOKEN
|
||||||
|
|
||||||
|
Il workflow richiede un token di accesso per pubblicare le immagini Docker sul registry:
|
||||||
|
|
||||||
|
1. Vai su **Settings → Secrets** nel repository Gitea
|
||||||
|
2. Crea un nuovo secret chiamato `REGISTRY_TOKEN`
|
||||||
|
3. Il valore deve essere un Personal Access Token con i seguenti permessi:
|
||||||
|
- `write:packages` - Per pubblicare container images
|
||||||
|
- `read:packages` - Per leggere images esistenti
|
||||||
|
|
||||||
|
#### Come Creare un Personal Access Token su Gitea
|
||||||
|
|
||||||
|
1. Vai su **Settings → Applications** nel tuo profilo Gitea
|
||||||
|
2. Clicca su **Generate New Token**
|
||||||
|
3. Nome del token: `Data-Coupler Docker Build`
|
||||||
|
4. Seleziona i seguenti scopes:
|
||||||
|
- `write:packages`
|
||||||
|
- `read:packages`
|
||||||
|
5. Clicca su **Generate Token**
|
||||||
|
6. Copia il token generato (sarà mostrato solo una volta)
|
||||||
|
|
||||||
|
### Configurazione del Repository Path
|
||||||
|
|
||||||
|
Nel file `.gitea/workflows/docker-build.yml`, verifica le variabili di registry:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
env:
|
||||||
|
REGISTRY: gitea.home-nas-ds.org # La tua istanza Gitea self-hosted
|
||||||
|
IMAGE_NAME: alessio/data-coupler # username/repo sulla tua istanza
|
||||||
|
```
|
||||||
|
|
||||||
|
**Importante**:
|
||||||
|
- `REGISTRY` deve puntare alla tua istanza Gitea con Container Registry abilitato
|
||||||
|
- `IMAGE_NAME` deve essere nel formato `username/repo` della tua istanza
|
||||||
|
- Assicurati che il Container Registry sia abilitato su Gitea (Settings → Packages)
|
||||||
|
|
||||||
|
## 🚀 Workflow
|
||||||
|
|
||||||
|
### Docker Build Workflow
|
||||||
|
|
||||||
|
**File**: `.gitea/workflows/docker-build.yml`
|
||||||
|
|
||||||
|
#### Trigger Events
|
||||||
|
|
||||||
|
Il workflow si attiva automaticamente su:
|
||||||
|
- **Push** sui branch: `main`, `development`, `staging`
|
||||||
|
- **Manual dispatch** tramite interfaccia web
|
||||||
|
|
||||||
|
#### Jobs
|
||||||
|
|
||||||
|
Il workflow è composto da 3 job principali:
|
||||||
|
|
||||||
|
##### 1. `build-linux` - Build Immagine Linux
|
||||||
|
- **Runner**: `ubuntu-latest`
|
||||||
|
- **Dockerfile**: `./Dockerfile`
|
||||||
|
- **Platform**: `linux/amd64`
|
||||||
|
- **Tags generati**:
|
||||||
|
- `latest` (per branch `main` e `development`)
|
||||||
|
- `development-latest` (per branch `development`)
|
||||||
|
- `staging-latest` (per branch `staging`)
|
||||||
|
- `<branch>-<sha>` (per ogni commit)
|
||||||
|
- `<branch>-<timestamp>` (con data/ora)
|
||||||
|
|
||||||
|
##### 2. `build-windows` - Build Immagine Windows
|
||||||
|
- **Runner**: `windows-2022`
|
||||||
|
- **Dockerfile**: `./Dockerfile.windows`
|
||||||
|
- **Platform**: Windows Server 2022
|
||||||
|
- **Tags generati**: Come Linux ma con suffisso `-windows`
|
||||||
|
|
||||||
|
##### 3. `create-manifest` - Multi-Platform Manifest
|
||||||
|
- **Runner**: `ubuntu-latest`
|
||||||
|
- **Dipendenze**: `build-linux`, `build-windows`
|
||||||
|
- Crea manifest multi-piattaforma che combinano le immagini Linux e Windows
|
||||||
|
|
||||||
|
### Strategia di Tagging
|
||||||
|
|
||||||
|
#### Branch `main`
|
||||||
|
- `latest` - Tag condiviso per versione stabile
|
||||||
|
- `latest-windows` - Versione Windows
|
||||||
|
- `main-<sha>` - Tag specifico per commit
|
||||||
|
- `main-<timestamp>` - Tag con timestamp
|
||||||
|
|
||||||
|
#### Branch `development`
|
||||||
|
- `latest` - Tag condiviso per ultime funzionalità
|
||||||
|
- `development-latest` - Tag specifico per development
|
||||||
|
- `latest-windows` / `development-latest-windows` - Versioni Windows
|
||||||
|
- `development-<sha>` - Tag specifico per commit
|
||||||
|
- `development-<timestamp>` - Tag con timestamp
|
||||||
|
|
||||||
|
#### Branch `staging`
|
||||||
|
- `staging-latest` - Tag per ambiente di staging
|
||||||
|
- `staging-latest-windows` - Versione Windows
|
||||||
|
- `staging-<sha>` - Tag specifico per commit
|
||||||
|
- `staging-<timestamp>` - Tag con timestamp
|
||||||
|
|
||||||
|
## 📦 Utilizzo delle Immagini
|
||||||
|
|
||||||
|
### Pull delle Immagini
|
||||||
|
|
||||||
|
#### Da Gitea Container Registry
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Ultima versione stabile (main/development)
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:latest
|
||||||
|
|
||||||
|
# Versione development specifica
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:development-latest
|
||||||
|
|
||||||
|
# Versione staging
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:staging-latest
|
||||||
|
|
||||||
|
# Versione Windows
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:latest-windows
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Compose
|
||||||
|
|
||||||
|
Modifica il `docker-compose.yml` per usare le immagini Gitea:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
data-coupler:
|
||||||
|
image: gitea.home-nas-ds.org/alessio/data-coupler:latest
|
||||||
|
# ... resto della configurazione
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔍 Monitoraggio
|
||||||
|
|
||||||
|
### Visualizzare lo Stato dei Workflow
|
||||||
|
|
||||||
|
1. Vai nella tab **Actions** del repository Gitea
|
||||||
|
2. Seleziona il workflow **Build and Push Docker Images**
|
||||||
|
3. Visualizza i dettagli di ogni esecuzione
|
||||||
|
|
||||||
|
### Log e Debug
|
||||||
|
|
||||||
|
- I log di ogni job sono disponibili nell'interfaccia Gitea Actions
|
||||||
|
- Per debug dettagliato, attiva il manual dispatch con opzione `force_build`
|
||||||
|
|
||||||
|
## 🔄 Differenze con GitHub Actions
|
||||||
|
|
||||||
|
### Principali Differenze
|
||||||
|
|
||||||
|
1. **Context Variables**:
|
||||||
|
- Gitea Actions usa le **stesse variabili** di GitHub Actions: `github.*`
|
||||||
|
- Esempio: `github.ref`, `github.sha`, `github.actor`
|
||||||
|
- **Nota**: Anche se il servizio è Gitea, le variabili mantengono il prefisso `github` per compatibilità
|
||||||
|
|
||||||
|
2. **Username**:
|
||||||
|
- Nel workflow è hardcoded come `alessio` per semplicità
|
||||||
|
- Puoi usare `${{ github.actor }}` se preferisci (utente che ha triggerato il workflow)
|
||||||
|
|
||||||
|
3. **Registry**:
|
||||||
|
- GitHub: `ghcr.io` → Gitea: `gitea.home-nas-ds.org` (istanza self-hosted)
|
||||||
|
- Gitea non ha un registry pubblico centralizzato come GitHub
|
||||||
|
|
||||||
|
4. **Secret Name**:
|
||||||
|
- GitHub: `GITHUB_TOKEN` (automatico) → Gitea: `REGISTRY_TOKEN` (configurato manualmente)
|
||||||
|
- **Nota**: Il secret non può iniziare con `GITEA_` per limitazioni di Gitea
|
||||||
|
|
||||||
|
4. **Attestation**:
|
||||||
|
- Il job di attestation non è presente su Gitea (feature GitHub specifica)
|
||||||
|
|
||||||
|
### Compatibilità
|
||||||
|
|
||||||
|
Gitea Actions è compatibile con la maggior parte delle GitHub Actions disponibili su GitHub Marketplace, incluse:
|
||||||
|
- `actions/checkout@v4`
|
||||||
|
- `docker/setup-buildx-action@v3`
|
||||||
|
- `docker/login-action@v3`
|
||||||
|
- `docker/build-push-action@v5`
|
||||||
|
- `docker/metadata-action@v5`
|
||||||
|
|
||||||
|
## 🛠️ Troubleshooting
|
||||||
|
|
||||||
|
### Verificare che il Container Registry sia Abilitato
|
||||||
|
|
||||||
|
Prima di tutto, verifica che il Container Registry sia abilitato sulla tua istanza Gitea:
|
||||||
|
|
||||||
|
1. **Controlla la configurazione Gitea** (`app.ini`):
|
||||||
|
```ini
|
||||||
|
[packages]
|
||||||
|
ENABLED = true
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Verifica accesso al registry**:
|
||||||
|
```bash
|
||||||
|
curl https://gitea.home-nas-ds.org/v2/
|
||||||
|
# Dovrebbe rispondere con status 401 (richiede autenticazione)
|
||||||
|
# Se ottieni 404, il registry non è abilitato
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Test autenticazione**:
|
||||||
|
```bash
|
||||||
|
echo "YOUR_TOKEN" | docker login gitea.home-nas-ds.org -u alessio --password-stdin
|
||||||
|
```
|
||||||
|
|
||||||
|
### Errore di Autenticazione
|
||||||
|
|
||||||
|
Se ottieni errori di autenticazione:
|
||||||
|
1. Verifica che il secret `REGISTRY_TOKEN` sia configurato correttamente
|
||||||
|
2. Assicurati che il token abbia i permessi `write:packages`
|
||||||
|
3. Controlla che il token non sia scaduto
|
||||||
|
|
||||||
|
### Build Fallita
|
||||||
|
|
||||||
|
Se la build fallisce:
|
||||||
|
1. Controlla i log del job specifico
|
||||||
|
2. Verifica che i Dockerfile siano presenti e corretti
|
||||||
|
3. Assicurati che le dipendenze NuGet siano accessibili
|
||||||
|
|
||||||
|
### Immagini Non Pubblicate
|
||||||
|
|
||||||
|
Se le immagini non vengono pubblicate:
|
||||||
|
1. Verifica che `IMAGE_NAME` sia corretto
|
||||||
|
2. Controlla che il registry sia accessibile
|
||||||
|
3. Verifica i permessi del token
|
||||||
|
|
||||||
|
## 📚 Risorse
|
||||||
|
|
||||||
|
- [Gitea Actions Documentation](https://docs.gitea.io/en-us/actions/)
|
||||||
|
- [GitHub Actions Compatibility](https://docs.gitea.io/en-us/usage/actions/comparison/)
|
||||||
|
- [Docker Build Push Action](https://github.com/docker/build-push-action)
|
||||||
|
|
||||||
|
## 📝 Note
|
||||||
|
|
||||||
|
- **Registry Self-Hosted**: Questo workflow è configurato per usare un'istanza Gitea self-hosted (`gitea.home-nas-ds.org`)
|
||||||
|
- **Container Registry**: Assicurati che il Container Registry sia abilitato nella tua istanza Gitea (Settings → Packages)
|
||||||
|
- **Accesso Pubblico/Privato**: Le immagini sono private per default; configura le impostazioni del package per renderle pubbliche se necessario
|
||||||
|
- **Esecuzione Manuale**: Il workflow supporta anche l'esecuzione manuale tramite `workflow_dispatch`
|
||||||
|
- **Manifest Multi-Platform**: I manifest multi-platform permettono di usare lo stesso tag per Linux e Windows
|
||||||
|
- **Alternative Registry**: Se non hai un'istanza Gitea con registry, puoi configurare Docker Hub o altri registry modificando la variabile `REGISTRY`
|
||||||
|
|
||||||
|
### 🐳 Configurazione Registry Alternativi
|
||||||
|
|
||||||
|
Se il Container Registry di Gitea non è disponibile, puoi usare alternative:
|
||||||
|
|
||||||
|
#### Docker Hub
|
||||||
|
```yaml
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
IMAGE_NAME: username/data-coupler
|
||||||
|
|
||||||
|
# Nel login step:
|
||||||
|
- name: Log in to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_TOKEN }}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### GitHub Container Registry (come fallback)
|
||||||
|
```yaml
|
||||||
|
env:
|
||||||
|
REGISTRY: ghcr.io
|
||||||
|
IMAGE_NAME: alessio/data-coupler
|
||||||
|
|
||||||
|
# Nel login step:
|
||||||
|
- name: Log in to GHCR
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Versione**: 1.0
|
||||||
|
**Ultimo Aggiornamento**: 24 Gennaio 2026
|
||||||
|
**Maintainer**: Alessio Dalsanto
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
name: Build and Push Docker Images
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- staging
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
force_build:
|
||||||
|
description: 'Force build even without code changes'
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Gitea Container Registry (self-hosted instance)
|
||||||
|
REGISTRY: gitea.home-nas-ds.org
|
||||||
|
# Repository path (format: owner/repo)
|
||||||
|
IMAGE_NAME: alessio/data-coupler
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-linux:
|
||||||
|
name: Build Linux Container
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Debug - Check registry access
|
||||||
|
run: |
|
||||||
|
echo "Testing registry access..."
|
||||||
|
curl -v https://gitea.home-nas-ds.org/v2/ || echo "Registry not accessible"
|
||||||
|
echo "Registry: ${{ env.REGISTRY }}"
|
||||||
|
echo "Image: ${{ env.IMAGE_NAME }}"
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Debug - Verify secret is configured
|
||||||
|
run: |
|
||||||
|
if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
|
||||||
|
echo "::error::REGISTRY_TOKEN secret is not configured or is empty!"
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "REGISTRY_TOKEN secret is configured (length: ${#REGISTRY_TOKEN})"
|
||||||
|
fi
|
||||||
|
env:
|
||||||
|
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Log in to Gitea Container Registry
|
||||||
|
run: |
|
||||||
|
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login ${{ env.REGISTRY }} -u alessio --password-stdin
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Extract metadata for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
# Tag based on branch
|
||||||
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
type=raw,value=latest-linux,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/development' }}
|
||||||
|
type=raw,value=latest-linux,enable=${{ github.ref == 'refs/heads/development' }}
|
||||||
|
type=raw,value=development-latest,enable=${{ github.ref == 'refs/heads/development' }}
|
||||||
|
type=raw,value=development-latest-linux,enable=${{ github.ref == 'refs/heads/development' }}
|
||||||
|
type=raw,value=dev-latest,enable=${{ github.ref == 'refs/heads/dev' }}
|
||||||
|
type=raw,value=dev-latest-linux,enable=${{ github.ref == 'refs/heads/dev' }}
|
||||||
|
type=raw,value=staging-latest,enable=${{ github.ref == 'refs/heads/staging' }}
|
||||||
|
type=raw,value=staging-latest-linux,enable=${{ github.ref == 'refs/heads/staging' }}
|
||||||
|
# Tag with commit sha
|
||||||
|
type=sha,prefix={{branch}}-,format=short
|
||||||
|
# Tag with date
|
||||||
|
type=raw,value={{branch}}-{{date 'YYYYMMDD-HHmmss'}}
|
||||||
|
flavor: |
|
||||||
|
latest=false
|
||||||
|
|
||||||
|
- name: Build and push Linux Docker image
|
||||||
|
id: build
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
platforms: linux/amd64
|
||||||
|
# Aumenta timeout per registry lenti
|
||||||
|
build-args: |
|
||||||
|
BUILDKIT_STEP_LOG_MAX_SIZE=50000000
|
||||||
|
provenance: false
|
||||||
|
sbom: false
|
||||||
|
env:
|
||||||
|
BUILDX_NO_DEFAULT_ATTESTATIONS: 1
|
||||||
|
|
||||||
|
- name: Retry push on failure
|
||||||
|
if: failure() && steps.build.outcome == 'failure'
|
||||||
|
run: |
|
||||||
|
echo "Retry push after 30 seconds..."
|
||||||
|
sleep 30
|
||||||
|
docker push $(echo "${{ steps.meta.outputs.tags }}" | head -n1)
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
name: Build Windows Container
|
||||||
|
runs-on: windows
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository with Git
|
||||||
|
run: |
|
||||||
|
git clone --depth 1 --branch ${{ github.ref_name }} https://alessio:%REGISTRY_TOKEN%@gitea.home-nas-ds.org/${{ github.repository }}.git .
|
||||||
|
if not exist Dockerfile.windows (
|
||||||
|
echo ERROR: Dockerfile.windows not found
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
echo SUCCESS: Repository cloned
|
||||||
|
env:
|
||||||
|
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
shell: cmd
|
||||||
|
|
||||||
|
- name: Debug - Verify files
|
||||||
|
run: |
|
||||||
|
echo Working directory:
|
||||||
|
cd
|
||||||
|
echo.
|
||||||
|
echo Dockerfiles found:
|
||||||
|
dir Dockerfile* /B 2>nul || echo No Dockerfiles found
|
||||||
|
shell: cmd
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Debug - Verify secret
|
||||||
|
run: |
|
||||||
|
if "${{ secrets.REGISTRY_TOKEN }}"=="" (
|
||||||
|
echo ERROR: REGISTRY_TOKEN not configured!
|
||||||
|
exit /b 1
|
||||||
|
) else (
|
||||||
|
echo REGISTRY_TOKEN is configured
|
||||||
|
)
|
||||||
|
shell: cmd
|
||||||
|
|
||||||
|
- name: Log in to Gitea Container Registry
|
||||||
|
run: echo ${{ secrets.REGISTRY_TOKEN }} | docker login ${{ env.REGISTRY }} -u alessio --password-stdin
|
||||||
|
shell: cmd
|
||||||
|
|
||||||
|
- name: Build and push Windows Docker image
|
||||||
|
run: |
|
||||||
|
set IMAGE_LOWER=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
set BRANCH=${{ github.ref_name }}
|
||||||
|
set SHA=${{ github.sha }}
|
||||||
|
set SHORT_SHA=%SHA:~0,7%
|
||||||
|
|
||||||
|
REM Determine tags based on branch
|
||||||
|
set TAGS=
|
||||||
|
if "%BRANCH%"=="main" (
|
||||||
|
set TAGS=%IMAGE_LOWER%:latest-windows
|
||||||
|
set TAGS=%TAGS% %IMAGE_LOWER%:main-windows-%SHORT_SHA%
|
||||||
|
)
|
||||||
|
if "%BRANCH%"=="development" (
|
||||||
|
set TAGS=%IMAGE_LOWER%:latest-windows
|
||||||
|
set TAGS=%TAGS% %IMAGE_LOWER%:development-latest-windows
|
||||||
|
set TAGS=%TAGS% %IMAGE_LOWER%:development-windows-%SHORT_SHA%
|
||||||
|
)
|
||||||
|
if "%BRANCH%"=="staging" (
|
||||||
|
set TAGS=%IMAGE_LOWER%:staging-latest-windows
|
||||||
|
set TAGS=%TAGS% %IMAGE_LOWER%:staging-windows-%SHORT_SHA%
|
||||||
|
)
|
||||||
|
|
||||||
|
echo Building Windows Docker image...
|
||||||
|
docker build -t temp-windows -f Dockerfile.windows .
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo Build failed!
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo Tagging and pushing images...
|
||||||
|
for %%t in (%TAGS%) do (
|
||||||
|
echo Tagging: %%t
|
||||||
|
docker tag temp-windows %%t
|
||||||
|
echo Pushing: %%t
|
||||||
|
docker push %%t
|
||||||
|
)
|
||||||
|
|
||||||
|
echo Cleaning up temporary image...
|
||||||
|
docker rmi temp-windows
|
||||||
|
|
||||||
|
echo Windows build completed successfully!
|
||||||
|
shell: cmd
|
||||||
|
|
||||||
|
create-manifest:
|
||||||
|
name: Create Multi-Platform Manifest
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build-linux, build-windows]
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Log in to Gitea Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: alessio
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Create and push manifest for main branch
|
||||||
|
if: github.ref == 'refs/heads/main'
|
||||||
|
run: |
|
||||||
|
IMAGE_LOWER=$(echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
docker buildx imagetools create -t ${IMAGE_LOWER}:latest \
|
||||||
|
${IMAGE_LOWER}:latest-linux \
|
||||||
|
${IMAGE_LOWER}:latest-windows
|
||||||
|
|
||||||
|
- name: Create and push manifest for development branch
|
||||||
|
if: github.ref == 'refs/heads/development'
|
||||||
|
run: |
|
||||||
|
IMAGE_LOWER=$(echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
docker buildx imagetools create -t ${IMAGE_LOWER}:latest \
|
||||||
|
${IMAGE_LOWER}:latest-linux \
|
||||||
|
${IMAGE_LOWER}:latest-windows
|
||||||
|
docker buildx imagetools create -t ${IMAGE_LOWER}:development-latest \
|
||||||
|
${IMAGE_LOWER}:development-latest-linux \
|
||||||
|
${IMAGE_LOWER}:development-latest-windows
|
||||||
|
|
||||||
|
- name: Create and push manifest for dev branch
|
||||||
|
if: github.ref == 'refs/heads/dev'
|
||||||
|
run: |
|
||||||
|
IMAGE_LOWER=$(echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
docker buildx imagetools create -t ${IMAGE_LOWER}:dev-latest \
|
||||||
|
${IMAGE_LOWER}:dev-latest-linux \
|
||||||
|
${IMAGE_LOWER}:dev-latest-windows
|
||||||
|
|
||||||
|
- name: Create and push manifest for staging branch
|
||||||
|
if: github.ref == 'refs/heads/staging'
|
||||||
|
run: |
|
||||||
|
IMAGE_LOWER=$(echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
docker buildx imagetools create -t ${IMAGE_LOWER}:staging-latest \
|
||||||
|
${IMAGE_LOWER}:staging-latest-linux \
|
||||||
|
${IMAGE_LOWER}:staging-latest-windows
|
||||||
@@ -146,6 +146,8 @@
|
|||||||
- **Pausa/Riprendi**: Controllo dinamico schedulazioni
|
- **Pausa/Riprendi**: Controllo dinamico schedulazioni
|
||||||
- **Override Database**: Possibilità di sovrascrivere sorgente/destinazione
|
- **Override Database**: Possibilità di sovrascrivere sorgente/destinazione
|
||||||
- **Deletion Sync Configurabile**: Opzione per abilitare sincronizzazione eliminazioni (disabilitata di default)
|
- **Deletion Sync Configurabile**: Opzione per abilitare sincronizzazione eliminazioni (disabilitata di default)
|
||||||
|
- **Supporto File CSV/Excel**: Schedulazione completa per profili con file come sorgente
|
||||||
|
- **Validazione File**: Verifica esistenza e leggibilità file prima dell'esecuzione
|
||||||
|
|
||||||
#### File Chiave:
|
#### File Chiave:
|
||||||
- `CredentialManager/Models/ProfileSchedule.cs`
|
- `CredentialManager/Models/ProfileSchedule.cs`
|
||||||
@@ -249,7 +251,38 @@
|
|||||||
- **Dark/Light Mode**: Temi personalizzabili
|
- **Dark/Light Mode**: Temi personalizzabili
|
||||||
- **Mobile Responsive**: Ottimizzato per dispositivi mobili
|
- **Mobile Responsive**: Ottimizzato per dispositivi mobili
|
||||||
|
|
||||||
### 10. Health Checks e Monitoraggio
|
### 10. Gestione File per Schedulazioni
|
||||||
|
|
||||||
|
#### Caratteristiche:
|
||||||
|
- **Doppia Modalità Caricamento**: Browser (preview) + percorso manuale (schedulazione)
|
||||||
|
- **Validazione Percorsi**: Verifica esistenza e permessi lettura file
|
||||||
|
- **Supporto CSV**: Rilevamento automatico separatori, gestione quote e escape
|
||||||
|
- **Supporto Excel**: Formati .xlsx e .xls, lettura automatica primo foglio
|
||||||
|
- **Schedulazione Completa**: File CSV/Excel utilizzabili in schedulazioni automatiche
|
||||||
|
- **Logging Dettagliato**: Tracciamento lettura file e parsing
|
||||||
|
|
||||||
|
#### Modalità Operative:
|
||||||
|
|
||||||
|
**Caricamento Browser (Preview)**:
|
||||||
|
- Carica file tramite InputFile component
|
||||||
|
- Processato in memoria per anteprima
|
||||||
|
- Non salvato sul server
|
||||||
|
- Utilizzato solo per configurazione mapping
|
||||||
|
|
||||||
|
**Percorso Manuale (Schedulazione)**:
|
||||||
|
- Campo "Percorso File sul Server" obbligatorio
|
||||||
|
- Validazione esistenza e leggibilità
|
||||||
|
- Percorso salvato in `SourceFilePath` del profilo
|
||||||
|
- Utilizzato per esecuzioni schedulate
|
||||||
|
- Esempi: `C:\Data\products.csv`, `/data/customers.xlsx`
|
||||||
|
|
||||||
|
#### File Chiave:
|
||||||
|
- `Data_Coupler/Pages/DataCoupler.razor` (UI caricamento file)
|
||||||
|
- `Data_Coupler/Pages/DataCoupler.razor.cs` (validazione file)
|
||||||
|
- `Data_Coupler/Services/ScheduledProfileExecutionService.cs` (lettura file schedulazioni)
|
||||||
|
- `CSV_SCHEDULING_IMPLEMENTATION.md` (documentazione completa)
|
||||||
|
|
||||||
|
### 11. Health Checks e Monitoraggio
|
||||||
|
|
||||||
#### Caratteristiche:
|
#### Caratteristiche:
|
||||||
- **Health Checks**: Endpoint per monitoraggio stato applicazione
|
- **Health Checks**: Endpoint per monitoraggio stato applicazione
|
||||||
@@ -368,15 +401,26 @@
|
|||||||
- `hotfix/*`: Fix urgenti
|
- `hotfix/*`: Fix urgenti
|
||||||
|
|
||||||
### CI/CD Pipeline:
|
### CI/CD Pipeline:
|
||||||
|
|
||||||
|
#### GitHub Actions (`.github/workflows/docker-build.yml`)
|
||||||
- **Branch `main`**: Pubblica immagini Docker con tag `latest`
|
- **Branch `main`**: Pubblica immagini Docker con tag `latest`
|
||||||
- **Branch `development`**: Pubblica immagini Docker con tag `latest` e `development-latest`
|
- **Branch `development`**: Pubblica immagini Docker con tag `latest` e `development-latest`
|
||||||
- **Branch `staging`**: Pubblica immagini Docker con tag `staging-latest`
|
- **Branch `staging`**: Pubblica immagini Docker con tag `staging-latest`
|
||||||
- **Ogni commit**: Crea tag con SHA e timestamp per tracciabilità
|
- **Ogni commit**: Crea tag con SHA e timestamp per tracciabilità
|
||||||
|
- **Registry**: GitHub Container Registry (`ghcr.io`)
|
||||||
|
|
||||||
|
#### Gitea Actions (`.gitea/workflows/docker-build.yml`)
|
||||||
|
- **Stessa configurazione** di GitHub Actions
|
||||||
|
- **Registry**: Gitea Container Registry (`gitea.home-nas-ds.org`)
|
||||||
|
- **Supporto**: Istanza Gitea self-hosted con registry abilitato
|
||||||
|
- **Setup**: Richiede secret `REGISTRY_TOKEN` con permessi `write:packages`
|
||||||
|
- **Documentazione**: `.gitea/workflows/README.md`
|
||||||
|
|
||||||
**Note sui Tag Docker**:
|
**Note sui Tag Docker**:
|
||||||
- `latest`: Condiviso tra `main` e `development` per garantire accesso alle ultime funzionalità
|
- `latest`: Condiviso tra `main` e `development` per garantire accesso alle ultime funzionalità
|
||||||
- `development-latest`: Specifico per il branch `development`, utile per distinguere le versioni in sviluppo
|
- `development-latest`: Specifico per il branch `development`, utile per distinguere le versioni in sviluppo
|
||||||
- `staging-latest`: Dedicato al branch `staging` per test pre-produzione
|
- `staging-latest`: Dedicato al branch `staging` per test pre-produzione
|
||||||
|
- Disponibile su **entrambi** i registry (GitHub e Gitea)
|
||||||
|
|
||||||
### Commit Messages:
|
### Commit Messages:
|
||||||
- Formato: `[Tipo] Descrizione breve`
|
- Formato: `[Tipo] Descrizione breve`
|
||||||
@@ -397,8 +441,10 @@
|
|||||||
- **SALESFORCE_BATCH_EXTRACTION_IMPROVEMENTS.md**: Batch extraction Salesforce
|
- **SALESFORCE_BATCH_EXTRACTION_IMPROVEMENTS.md**: Batch extraction Salesforce
|
||||||
- **PRE_DISCOVERY_SYSTEM.md**: Sistema pre-discovery associazioni
|
- **PRE_DISCOVERY_SYSTEM.md**: Sistema pre-discovery associazioni
|
||||||
- **DELETION_SYNC_IMPLEMENTATION.md**: Sincronizzazione eliminazioni
|
- **DELETION_SYNC_IMPLEMENTATION.md**: Sincronizzazione eliminazioni
|
||||||
|
- **CSV_SCHEDULING_IMPLEMENTATION.md**: Schedulazione file CSV/Excel (NUOVO)
|
||||||
- **DOCKER_DEPLOYMENT.md**: Guida deployment Docker
|
- **DOCKER_DEPLOYMENT.md**: Guida deployment Docker
|
||||||
- **WINDOWS_SERVICE_DEPLOYMENT.md**: Deploy come Windows Service
|
- **WINDOWS_SERVICE_DEPLOYMENT.md**: Deploy come Windows Service
|
||||||
|
- **.gitea/workflows/README.md**: Configurazione Gitea Actions
|
||||||
|
|
||||||
## 🎓 Best Practices per AI Assistants
|
## 🎓 Best Practices per AI Assistants
|
||||||
|
|
||||||
@@ -431,7 +477,7 @@
|
|||||||
## 🚀 Roadmap Futura
|
## 🚀 Roadmap Futura
|
||||||
|
|
||||||
### Feature in Pianificazione:
|
### Feature in Pianificazione:
|
||||||
- [ ] Supporto file Excel/CSV avanzato
|
- [x] Supporto file Excel/CSV avanzato (Completato - Gennaio 2026)
|
||||||
- [ ] Sistema di notifiche (email, webhook)
|
- [ ] Sistema di notifiche (email, webhook)
|
||||||
- [ ] Dashboard analytics avanzato
|
- [ ] Dashboard analytics avanzato
|
||||||
- [ ] Multi-tenant support
|
- [ ] Multi-tenant support
|
||||||
@@ -439,6 +485,8 @@
|
|||||||
- [ ] Plugin system per connectors custom
|
- [ ] Plugin system per connectors custom
|
||||||
- [ ] Machine learning per mapping suggeriti
|
- [ ] Machine learning per mapping suggeriti
|
||||||
- [ ] Real-time data sync
|
- [ ] Real-time data sync
|
||||||
|
- [ ] Lettura fogli Excel multipli
|
||||||
|
- [ ] Supporto file remoti (HTTP, FTP, Azure Blob)
|
||||||
|
|
||||||
### Miglioramenti Tecnici:
|
### Miglioramenti Tecnici:
|
||||||
- [ ] Migrazione a .NET 10 (quando disponibile)
|
- [ ] Migrazione a .NET 10 (quando disponibile)
|
||||||
@@ -449,8 +497,8 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Versione**: 2.0
|
**Versione**: 2.1
|
||||||
**Ultimo Aggiornamento**: 22 Gennaio 2026
|
**Ultimo Aggiornamento**: 25 Gennaio 2026
|
||||||
**Framework**: .NET 9.0
|
**Framework**: .NET 9.0
|
||||||
**Sviluppatore**: Alessio Dalsanto
|
**Sviluppatore**: Alessio Dalsanto
|
||||||
**Repository**: https://github.com/AlessioDalsi/Data-Coupler
|
**Repository**: https://github.com/AlessioDalsi/Data-Coupler
|
||||||
|
|||||||
@@ -0,0 +1,410 @@
|
|||||||
|
# Implementazione Schedulazione File CSV/Excel
|
||||||
|
|
||||||
|
## Data
|
||||||
|
24 Gennaio 2026
|
||||||
|
|
||||||
|
## Panoramica
|
||||||
|
Implementata la funzionalità completa di schedulazione per profili che utilizzano file CSV o Excel come sorgente dati. Precedentemente questa funzionalità era disattivata per motivi di sicurezza, ora è completamente funzionale con validazioni appropriate.
|
||||||
|
|
||||||
|
## Modifiche Implementate
|
||||||
|
|
||||||
|
### 1. Validazione File CSV nel Salvataggio Profilo
|
||||||
|
**File**: `Data_Coupler/Pages/DataCoupler.razor.cs`
|
||||||
|
|
||||||
|
**Modifica**: Aggiunta validazione nel metodo `OnProfileSaved` per verificare che:
|
||||||
|
- Il file CSV/Excel specificato esista nel filesystem
|
||||||
|
- Il file sia leggibile dall'applicazione
|
||||||
|
|
||||||
|
**Implementazione**:
|
||||||
|
```csharp
|
||||||
|
// Validazione specifica per file CSV
|
||||||
|
if (profile.SourceType == "file" && !string.IsNullOrEmpty(profile.SourceFilePath))
|
||||||
|
{
|
||||||
|
// Verifica esistenza
|
||||||
|
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||||
|
{
|
||||||
|
await JSRuntime.InvokeVoidAsync("alert",
|
||||||
|
"Errore: Il file non esiste o non è accessibile.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verifica leggibilità
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var fs = System.IO.File.OpenRead(profile.SourceFilePath);
|
||||||
|
fs.Close();
|
||||||
|
}
|
||||||
|
catch (Exception fileEx)
|
||||||
|
{
|
||||||
|
await JSRuntime.InvokeVoidAsync("alert",
|
||||||
|
$"Errore: Il file non può essere letto. Dettagli: {fileEx.Message}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefici**:
|
||||||
|
- Previene errori durante l'esecuzione schedulata
|
||||||
|
- Fornisce feedback immediato all'utente in fase di configurazione
|
||||||
|
- Verifica i permessi di lettura del file
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. Implementazione Lettura File per Schedulazioni
|
||||||
|
**File**: `Data_Coupler/Services/ScheduledProfileExecutionService.cs`
|
||||||
|
|
||||||
|
**Modifica**: Implementati i seguenti metodi per la lettura di file CSV e Excel:
|
||||||
|
|
||||||
|
#### Metodi Implementati:
|
||||||
|
|
||||||
|
1. **`GetAllRecordsFromFileAsync`** - Metodo principale
|
||||||
|
- Determina il tipo di file (CSV, XLSX, XLS)
|
||||||
|
- Verifica esistenza del file
|
||||||
|
- Delega alla funzione appropriata
|
||||||
|
|
||||||
|
2. **`ReadCsvFileAsync`** - Lettura file CSV
|
||||||
|
- Rilevamento automatico del separatore (`,`, `;`, `\t`, `|`)
|
||||||
|
- Parsing corretto con gestione virgolette
|
||||||
|
- Supporto per file di grandi dimensioni
|
||||||
|
|
||||||
|
3. **`ReadExcelFileAsync`** - Lettura file Excel
|
||||||
|
- Supporto per formati `.xlsx` e `.xls`
|
||||||
|
- Utilizzo di `ExcelDataReader` library
|
||||||
|
- Registrazione encoding provider (`System.Text.CodePagesEncodingProvider`)
|
||||||
|
- Lettura del primo foglio Excel
|
||||||
|
|
||||||
|
4. **Helper Methods**:
|
||||||
|
- `DetectCsvSeparator`: Rilevamento automatico separatore CSV
|
||||||
|
- `ParseCsvLine`: Parsing linea CSV con gestione quote e escape
|
||||||
|
|
||||||
|
**Esempio di utilizzo**:
|
||||||
|
```csharp
|
||||||
|
private async Task<IEnumerable<Dictionary<string, object>>> GetAllRecordsFromSourceAsync(
|
||||||
|
DataCouplerProfile profile, IDatabaseManager? databaseManager)
|
||||||
|
{
|
||||||
|
if (profile.SourceType.ToLower() == "file")
|
||||||
|
{
|
||||||
|
return await GetAllRecordsFromFileAsync(profile);
|
||||||
|
}
|
||||||
|
// ... altri tipi
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Caratteristiche**:
|
||||||
|
- Supporto completo per CSV con separatori multipli
|
||||||
|
- Gestione corretta di campi con virgolette e caratteri speciali
|
||||||
|
- Parsing robusto con logging dettagliato
|
||||||
|
- Compatibilità con file Excel legacy (.xls) e moderni (.xlsx)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. Abilitazione Profili File nella Schedulazione
|
||||||
|
**File**: `Data_Coupler/Pages/Scheduling.razor`
|
||||||
|
|
||||||
|
**Modifica**: Rimosso il filtro `Where(p => p.SourceType != "file")` che escludeva i profili file dalla lista di schedulazione.
|
||||||
|
|
||||||
|
**Prima**:
|
||||||
|
```csharp
|
||||||
|
@foreach (var profile in availableProfiles.Where(p => p.SourceType != "file"))
|
||||||
|
{
|
||||||
|
<option value="@profile.Id">@profile.Name</option>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dopo**:
|
||||||
|
```csharp
|
||||||
|
@foreach (var profile in availableProfiles)
|
||||||
|
{
|
||||||
|
<option value="@profile.Id">@profile.Name @(profile.SourceType == "file" ? "(File)" : "")</option>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Miglioramenti UI**:
|
||||||
|
- Etichetta `(File)` per identificare profili con file
|
||||||
|
- Messaggio informativo aggiornato:
|
||||||
|
> ℹ️ I profili con file CSV/Excel come sorgente sono ora supportati per le schedulazioni.
|
||||||
|
> Il file specificato nel profilo verrà letto ad ogni esecuzione.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. Gestione Cancellazioni per File CSV
|
||||||
|
**Implementazione**: La gestione delle cancellazioni opzionali funziona automaticamente anche per i profili file grazie all'architettura esistente.
|
||||||
|
|
||||||
|
**Flusso**:
|
||||||
|
1. I record vengono letti dal file CSV/Excel
|
||||||
|
2. Vengono trasformati in `Dictionary<string, object>` come i record database
|
||||||
|
3. Il sistema di associazioni (`KeyAssociationService`) traccia i record
|
||||||
|
4. Se abilitato, il `DeletionSyncService` sincronizza le eliminazioni
|
||||||
|
|
||||||
|
**Compatibilità**:
|
||||||
|
- ✅ Supporto completo per `EnableDeletionSync` flag
|
||||||
|
- ✅ Tracking chiavi sorgente (`SourceKeyField`)
|
||||||
|
- ✅ Sistema di associazioni record
|
||||||
|
- ✅ Pre-discovery di record esistenti
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gestione File per Schedulazioni
|
||||||
|
|
||||||
|
### Due Modalità di Caricamento
|
||||||
|
|
||||||
|
#### 1. **Caricamento Browser** (per Preview)
|
||||||
|
- **Scopo**: Configurare mapping e vedere anteprima dati
|
||||||
|
- **Funzionamento**:
|
||||||
|
- File caricato tramite browser (InputFile component)
|
||||||
|
- Processato in memoria
|
||||||
|
- **Non salvato sul server**
|
||||||
|
- **Uso**: Solo per configurazione iniziale del profilo
|
||||||
|
|
||||||
|
#### 2. **Percorso Manuale** (per Schedulazione) ⭐
|
||||||
|
- **Scopo**: Specificare posizione file per schedulazioni
|
||||||
|
- **Funzionamento**:
|
||||||
|
- Utente inserisce percorso completo (es: `C:\Data\products.csv`)
|
||||||
|
- Sistema valida esistenza e leggibilità
|
||||||
|
- Percorso salvato nel profilo
|
||||||
|
- **Uso**: **Obbligatorio** per profili che devono essere schedulati
|
||||||
|
|
||||||
|
### Esempi di Percorsi Validi
|
||||||
|
|
||||||
|
**Windows**:
|
||||||
|
```
|
||||||
|
C:\Data\products.csv
|
||||||
|
\\server\share\customers.xlsx
|
||||||
|
D:\ImportFiles\orders.csv
|
||||||
|
```
|
||||||
|
|
||||||
|
**Linux/Container**:
|
||||||
|
```
|
||||||
|
/data/products.csv
|
||||||
|
/mnt/share/customers.xlsx
|
||||||
|
/app/import/orders.csv
|
||||||
|
```
|
||||||
|
|
||||||
|
### Workflow Completo
|
||||||
|
|
||||||
|
1. **Configurazione Iniziale**:
|
||||||
|
- Carica file da browser per preview
|
||||||
|
- Configura mapping campi vedendo i dati reali
|
||||||
|
- **Importante**: Questo file è solo temporaneo
|
||||||
|
|
||||||
|
2. **Preparazione Schedulazione**:
|
||||||
|
- Posiziona il file nella location definitiva sul server
|
||||||
|
- Inserisci il percorso completo nel campo "Percorso File sul Server"
|
||||||
|
- Clicca "Valida e Carica" per verificare
|
||||||
|
- Salva il profilo
|
||||||
|
|
||||||
|
3. **Esecuzione Schedulata**:
|
||||||
|
- Il sistema legge il file dal percorso salvato
|
||||||
|
- Il file deve esistere e essere accessibile
|
||||||
|
- Aggiornamenti al file vengono letti automaticamente
|
||||||
|
|
||||||
|
### Considerazioni Importanti
|
||||||
|
|
||||||
|
**Sicurezza**:
|
||||||
|
- Il file deve essere accessibile dal processo dell'applicazione
|
||||||
|
- Verificare permessi di lettura sulla directory
|
||||||
|
- Per ambienti multi-utente, considerare ACL appropriati
|
||||||
|
|
||||||
|
**Percorsi Relativi vs Assoluti**:
|
||||||
|
- **Consigliato**: Percorsi assoluti per chiarezza
|
||||||
|
- Se si usano percorsi relativi, sono relativi alla working directory dell'applicazione
|
||||||
|
|
||||||
|
**Aggiornamento File**:
|
||||||
|
- Il sistema legge sempre il file corrente dal percorso
|
||||||
|
- Per aggiornare i dati, basta sovrascrivere il file nella stessa posizione
|
||||||
|
- Non serve modificare il profilo se il percorso rimane invariato
|
||||||
|
|
||||||
|
**Deployment Container**:
|
||||||
|
- Montare volumi per directory contenenti i file
|
||||||
|
- Esempio docker-compose:
|
||||||
|
```yaml
|
||||||
|
volumes:
|
||||||
|
- /host/data:/data # Monta directory host in /data nel container
|
||||||
|
```
|
||||||
|
- Nel profilo usare: `/data/products.csv`
|
||||||
|
|
||||||
|
**Best Practices**:
|
||||||
|
- ✅ Usare una directory dedicata per file di import (es: `/data/imports/`)
|
||||||
|
- ✅ Nominare i file in modo descrittivo
|
||||||
|
- ✅ Implementare rotazione/backup dei file
|
||||||
|
- ✅ Monitorare spazio disco
|
||||||
|
- ❌ Non usare directory temporanee che vengono pulite
|
||||||
|
- ❌ Non usare percorsi di rete senza verifica connessione
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Funzionamento Completo
|
||||||
|
|
||||||
|
### Creazione Profilo con File CSV
|
||||||
|
1. L'utente seleziona "File" come tipo sorgente
|
||||||
|
2. **Opzione A - Caricamento Browser (per preview)**:
|
||||||
|
- Carica un file CSV/Excel tramite browser
|
||||||
|
- Il file viene processato in memoria per preview
|
||||||
|
- Permette di configurare il mapping vedendo i dati reali
|
||||||
|
- **Non viene salvato sul server** - solo per anteprima
|
||||||
|
|
||||||
|
3. **Opzione B - Percorso Manuale (richiesto per schedulazione)**:
|
||||||
|
- Inserisce il percorso completo del file sul server (es: `C:\Data\products.csv`)
|
||||||
|
- Clicca "Valida e Carica" per:
|
||||||
|
- Verificare che il file esista
|
||||||
|
- Verificare che sia leggibile
|
||||||
|
- Caricare preview per configurare mapping
|
||||||
|
- Il percorso viene salvato nel profilo
|
||||||
|
|
||||||
|
4. L'utente configura il mapping campi
|
||||||
|
5. **Salvataggio**: Il sistema valida che il file sia accessibile e leggibile
|
||||||
|
6. Il **percorso completo originale** del file viene salvato in `SourceFilePath`
|
||||||
|
|
||||||
|
**Nota Importante**: Per le schedulazioni è **necessario** specificare il percorso file manualmente. Il file deve essere accessibile dal server nella posizione specificata.
|
||||||
|
|
||||||
|
### Schedulazione Profilo File
|
||||||
|
1. L'utente crea una nuova schedulazione
|
||||||
|
2. Seleziona un profilo con `SourceType = "file"`
|
||||||
|
3. Configura la frequenza (giornaliera, settimanale, intervallo, ecc.)
|
||||||
|
4. Abilita opzionalmente `EnableDeletionSync` per sincronizzare eliminazioni
|
||||||
|
|
||||||
|
### Esecuzione Schedulata
|
||||||
|
1. Il background service avvia l'esecuzione alla schedulazione prevista
|
||||||
|
2. `ScheduledProfileExecutionService.ExecuteProfileAsync` viene chiamato
|
||||||
|
3. Il servizio legge il file dal percorso salvato usando `GetAllRecordsFromFileAsync`
|
||||||
|
4. I record vengono trasformati e inviati alla destinazione REST
|
||||||
|
5. Il sistema di associazioni traccia i record per evitare duplicati
|
||||||
|
6. Se configurato, vengono sincronizzate le eliminazioni
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sicurezza e Validazioni
|
||||||
|
|
||||||
|
### Validazioni Implementate:
|
||||||
|
- ✅ Verifica esistenza file prima del salvataggio profilo
|
||||||
|
- ✅ Verifica permessi di lettura file
|
||||||
|
- ✅ Gestione eccezioni durante la lettura file
|
||||||
|
- ✅ Logging dettagliato per troubleshooting
|
||||||
|
- ✅ Validazione formato file (CSV, XLSX, XLS)
|
||||||
|
|
||||||
|
### Considerazioni di Sicurezza:
|
||||||
|
- Il file deve essere accessibile dal processo dell'applicazione
|
||||||
|
- Percorsi assoluti sono salvati nel database
|
||||||
|
- Per ambienti containerizzati, montare volumi con i file
|
||||||
|
- Permessi filesystem devono consentire lettura
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Formati File Supportati
|
||||||
|
|
||||||
|
### CSV
|
||||||
|
- **Separatori**: `,` (virgola), `;` (punto e virgola), `\t` (tab), `|` (pipe)
|
||||||
|
- **Rilevamento automatico**: Sì
|
||||||
|
- **Gestione quote**: Supporto completo per campi tra virgolette
|
||||||
|
- **Escape caratteri**: Supporto per `""` (double quote escape)
|
||||||
|
- **Dimensione massima**: 50 MB (configurabile)
|
||||||
|
|
||||||
|
### Excel
|
||||||
|
- **Formati**: `.xlsx` (Office Open XML), `.xls` (Binary Format)
|
||||||
|
- **Fogli multipli**: Legge il primo foglio per default
|
||||||
|
- **Header**: Prima riga utilizzata come intestazione
|
||||||
|
- **Dimensione massima**: 50 MB (configurabile)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Esempi di Utilizzo
|
||||||
|
|
||||||
|
### Esempio 1: Schedulazione Giornaliera CSV
|
||||||
|
```
|
||||||
|
Profilo: "Import Prodotti da CSV"
|
||||||
|
- Sorgente: File CSV (products.csv)
|
||||||
|
- Destinazione: REST API (Salesforce)
|
||||||
|
- SourceKeyField: "ProductCode"
|
||||||
|
- UseRecordAssociations: true
|
||||||
|
|
||||||
|
Schedulazione: "Import Prodotti Quotidiano"
|
||||||
|
- Tipo: Daily (Giornaliera)
|
||||||
|
- Ora: 08:00
|
||||||
|
- EnableDeletionSync: false
|
||||||
|
```
|
||||||
|
|
||||||
|
**Comportamento**: Ogni giorno alle 08:00, il sistema legge `products.csv`, trasforma i dati secondo il mapping configurato, e li invia a Salesforce. I record esistenti vengono aggiornati, i nuovi creati.
|
||||||
|
|
||||||
|
### Esempio 2: Sincronizzazione con Eliminazioni
|
||||||
|
```
|
||||||
|
Profilo: "Sincronizza Clienti Excel"
|
||||||
|
- Sorgente: File Excel (customers.xlsx)
|
||||||
|
- Destinazione: REST API (SAP Business One)
|
||||||
|
- SourceKeyField: "CustomerID"
|
||||||
|
- UseRecordAssociations: true
|
||||||
|
|
||||||
|
Schedulazione: "Sync Clienti Settimanale"
|
||||||
|
- Tipo: Weekly (Settimanale)
|
||||||
|
- Giorno: Lunedì
|
||||||
|
- Ora: 06:00
|
||||||
|
- EnableDeletionSync: true
|
||||||
|
```
|
||||||
|
|
||||||
|
**Comportamento**: Ogni lunedì alle 06:00, il sistema:
|
||||||
|
1. Legge `customers.xlsx`
|
||||||
|
2. Sincronizza i clienti con SAP Business One
|
||||||
|
3. Identifica clienti eliminati dal file
|
||||||
|
4. Elimina i corrispondenti record in SAP B1
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing e Validazione
|
||||||
|
|
||||||
|
### Test Consigliati:
|
||||||
|
1. **Test file CSV con separatori diversi**
|
||||||
|
- Comma-separated
|
||||||
|
- Semicolon-separated
|
||||||
|
- Tab-separated
|
||||||
|
|
||||||
|
2. **Test file Excel**
|
||||||
|
- Formato .xlsx moderno
|
||||||
|
- Formato .xls legacy
|
||||||
|
- Fogli con molte colonne/righe
|
||||||
|
|
||||||
|
3. **Test errori**
|
||||||
|
- File non esistente
|
||||||
|
- File senza permessi di lettura
|
||||||
|
- File corrotto
|
||||||
|
- File troppo grande
|
||||||
|
|
||||||
|
4. **Test schedulazione**
|
||||||
|
- Esecuzione immediata manuale
|
||||||
|
- Esecuzione automatica schedulata
|
||||||
|
- Verifica storico esecuzioni
|
||||||
|
- Test con `EnableDeletionSync` attivo
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Limitazioni Note
|
||||||
|
|
||||||
|
1. **Fogli Excel**: Attualmente viene letto solo il primo foglio del file Excel
|
||||||
|
2. **Dimensione file**: Limite di 50 MB per sicurezza (configurabile in codice)
|
||||||
|
3. **Percorsi assoluti**: I file devono essere accessibili tramite percorso assoluto
|
||||||
|
4. **Encoding**: Supporto per encoding standard (UTF-8, Windows-1252)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prossimi Sviluppi Potenziali
|
||||||
|
|
||||||
|
- [ ] Supporto per lettura di fogli Excel multipli
|
||||||
|
- [ ] Configurazione dinamica del foglio Excel da leggere
|
||||||
|
- [ ] Supporto per file remoti (HTTP, FTP, Azure Blob)
|
||||||
|
- [ ] Cache intelligente per file grandi non modificati
|
||||||
|
- [ ] Validazione schema file prima dell'esecuzione
|
||||||
|
- [ ] Notifiche in caso di file non trovato durante schedulazione
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Conclusioni
|
||||||
|
|
||||||
|
L'implementazione della schedulazione per file CSV/Excel è ora completa e robusta. La funzionalità include:
|
||||||
|
|
||||||
|
✅ Validazione completa del file in fase di configurazione
|
||||||
|
✅ Lettura affidabile di CSV con separatori multipli
|
||||||
|
✅ Supporto per file Excel moderni e legacy
|
||||||
|
✅ Integrazione completa con sistema di associazioni
|
||||||
|
✅ Supporto per sincronizzazione eliminazioni opzionale
|
||||||
|
✅ Logging dettagliato per troubleshooting
|
||||||
|
✅ Error handling robusto
|
||||||
|
|
||||||
|
Gli utenti possono ora schedulare trasferimenti dati da file CSV/Excel esattamente come farebbero con sorgenti database, con le stesse funzionalità avanzate di tracking record e sincronizzazione.
|
||||||
@@ -93,6 +93,9 @@ public class ProfileScheduleService : IProfileScheduleService
|
|||||||
existingSchedule.IntervalValue = schedule.IntervalValue;
|
existingSchedule.IntervalValue = schedule.IntervalValue;
|
||||||
existingSchedule.IntervalUnit = schedule.IntervalUnit;
|
existingSchedule.IntervalUnit = schedule.IntervalUnit;
|
||||||
existingSchedule.IsActive = schedule.IsActive;
|
existingSchedule.IsActive = schedule.IsActive;
|
||||||
|
existingSchedule.EnableDeletionSync = schedule.EnableDeletionSync;
|
||||||
|
existingSchedule.SourceDatabaseOverride = schedule.SourceDatabaseOverride;
|
||||||
|
existingSchedule.DestinationDatabaseOverride = schedule.DestinationDatabaseOverride;
|
||||||
existingSchedule.UpdatedAt = DateTime.UtcNow;
|
existingSchedule.UpdatedAt = DateTime.UtcNow;
|
||||||
|
|
||||||
// Ricalcola la prossima esecuzione
|
// Ricalcola la prossima esecuzione
|
||||||
|
|||||||
@@ -232,7 +232,8 @@ public class ScheduledJobService : BackgroundService
|
|||||||
var result = await dataTransferService.ExecuteProfileAsync(
|
var result = await dataTransferService.ExecuteProfileAsync(
|
||||||
schedule.Profile,
|
schedule.Profile,
|
||||||
schedule.SourceDatabaseOverride,
|
schedule.SourceDatabaseOverride,
|
||||||
schedule.DestinationDatabaseOverride);
|
schedule.DestinationDatabaseOverride,
|
||||||
|
schedule.EnableDeletionSync);
|
||||||
|
|
||||||
// Aggiorna lo storico con il risultato
|
// Aggiorna lo storico con il risultato
|
||||||
executionHistory.EndTime = DateTime.Now;
|
executionHistory.EndTime = DateTime.Now;
|
||||||
|
|||||||
@@ -294,13 +294,56 @@
|
|||||||
<!-- Sezione File -->
|
<!-- Sezione File -->
|
||||||
@if (selectedSourceType == "file")
|
@if (selectedSourceType == "file")
|
||||||
{
|
{
|
||||||
|
<div class="alert alert-info" role="alert">
|
||||||
|
<i class="fas fa-info-circle"></i>
|
||||||
|
<strong>Due modalità disponibili:</strong>
|
||||||
|
<ul class="mb-0 mt-2">
|
||||||
|
<li><strong>Caricamento Browser:</strong> Carica un file per preview e configurazione mapping (file temporaneo)</li>
|
||||||
|
<li><strong>Percorso File:</strong> Specifica il percorso completo del file sul server per schedulazioni</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Opzione 1: Caricamento Browser per Preview -->
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label class="form-label">Seleziona File (Excel/CSV):</label>
|
<label class="form-label">
|
||||||
|
<i class="fas fa-upload"></i> Carica File per Preview (opzionale):
|
||||||
|
</label>
|
||||||
<InputFile class="form-control" OnChange="OnFileSelected" accept=".xlsx,.xls,.csv" />
|
<InputFile class="form-control" OnChange="OnFileSelected" accept=".xlsx,.xls,.csv" />
|
||||||
@if (!string.IsNullOrEmpty(selectedFileName))
|
@if (!string.IsNullOrEmpty(selectedFileName))
|
||||||
{
|
{
|
||||||
<small class="text-muted">File selezionato: @selectedFileName</small>
|
<small class="text-muted">File caricato: @selectedFileName</small>
|
||||||
}
|
}
|
||||||
|
<small class="form-text text-muted">
|
||||||
|
Carica un file per vedere preview e configurare il mapping. Questo file non verrà salvato.
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Opzione 2: Percorso File Manuale (Richiesto per Schedulazione) -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">
|
||||||
|
<i class="fas fa-folder-open"></i> Percorso File sul Server (richiesto per schedulazione): *
|
||||||
|
</label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="text" class="form-control" @bind="manualFilePath"
|
||||||
|
placeholder="Es: C:\Data\products.csv o /data/products.csv" />
|
||||||
|
<button class="btn btn-outline-primary" @onclick="ValidateAndLoadFileFromPath"
|
||||||
|
disabled="@(string.IsNullOrEmpty(manualFilePath) || isProcessingFile)">
|
||||||
|
@if (isProcessingFile)
|
||||||
|
{
|
||||||
|
<span class="spinner-border spinner-border-sm me-1"></span>
|
||||||
|
}
|
||||||
|
<i class="fas fa-check"></i> Valida e Carica
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
@if (!string.IsNullOrEmpty(uploadedFilePath) && uploadedFilePath == manualFilePath)
|
||||||
|
{
|
||||||
|
<small class="text-success">
|
||||||
|
<i class="fas fa-check-circle"></i> File validato e caricato con successo!
|
||||||
|
</small>
|
||||||
|
}
|
||||||
|
<small class="form-text text-muted">
|
||||||
|
Inserisci il percorso completo del file. Il file deve essere accessibile dal server.
|
||||||
|
</small>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (isProcessingFile)
|
@if (isProcessingFile)
|
||||||
@@ -1016,7 +1059,7 @@
|
|||||||
SourceSchema="@GetCurrentDatabaseSchema()"
|
SourceSchema="@GetCurrentDatabaseSchema()"
|
||||||
SourceTable="@(useCustomQuery ? "custom_query" : selectedTable)"
|
SourceTable="@(useCustomQuery ? "custom_query" : selectedTable)"
|
||||||
SourceCustomQuery="@(useCustomQuery ? customQuery : null)"
|
SourceCustomQuery="@(useCustomQuery ? customQuery : null)"
|
||||||
SourceFilePath="@selectedFileName"
|
SourceFilePath="@uploadedFilePath"
|
||||||
DestinationType="rest"
|
DestinationType="rest"
|
||||||
DestinationCredentialId="@(GetCurrentDestinationCredentialIdAsync().Result)"
|
DestinationCredentialId="@(GetCurrentDestinationCredentialIdAsync().Result)"
|
||||||
DestinationCredentialName="@selectedRestCredential"
|
DestinationCredentialName="@selectedRestCredential"
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ public partial class DataCoupler : ComponentBase
|
|||||||
|
|
||||||
// File handling
|
// File handling
|
||||||
private string selectedFileName = "";
|
private string selectedFileName = "";
|
||||||
|
private string manualFilePath = ""; // Percorso inserito manualmente dall'utente
|
||||||
|
private string uploadedFilePath = ""; // Percorso completo del file validato
|
||||||
private bool isProcessingFile = false;
|
private bool isProcessingFile = false;
|
||||||
private string fileErrorMessage = "";
|
private string fileErrorMessage = "";
|
||||||
private Dictionary<string, IEnumerable<string>> fileSheets = new(); // SheetName -> Columns
|
private Dictionary<string, IEnumerable<string>> fileSheets = new(); // SheetName -> Columns
|
||||||
@@ -250,8 +252,10 @@ public partial class DataCoupler : ComponentBase
|
|||||||
// Per i file, non possiamo ricreare il file caricato, ma possiamo impostare le informazioni
|
// Per i file, non possiamo ricreare il file caricato, ma possiamo impostare le informazioni
|
||||||
if (!string.IsNullOrEmpty(profile.SourceFilePath))
|
if (!string.IsNullOrEmpty(profile.SourceFilePath))
|
||||||
{
|
{
|
||||||
|
uploadedFilePath = profile.SourceFilePath;
|
||||||
selectedFileName = Path.GetFileName(profile.SourceFilePath);
|
selectedFileName = Path.GetFileName(profile.SourceFilePath);
|
||||||
Logger.LogInformation("Informazioni file impostate: {FileName}", selectedFileName);
|
Logger.LogInformation("Informazioni file impostate - Nome: {FileName}, Percorso: {FilePath}",
|
||||||
|
selectedFileName, uploadedFilePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -401,6 +405,37 @@ public partial class DataCoupler : ComponentBase
|
|||||||
var profileService = new DataCouplerProfileService(null!); // Usa il service di conversione
|
var profileService = new DataCouplerProfileService(null!); // Usa il service di conversione
|
||||||
var profile = profileService.FromDto(profileDto, "System"); // TODO: Usa utente corrente
|
var profile = profileService.FromDto(profileDto, "System"); // TODO: Usa utente corrente
|
||||||
|
|
||||||
|
// Validazione specifica per file CSV
|
||||||
|
if (profile.SourceType == "file" && !string.IsNullOrEmpty(profile.SourceFilePath))
|
||||||
|
{
|
||||||
|
Logger.LogInformation("Validazione file CSV: {FilePath}", profile.SourceFilePath);
|
||||||
|
|
||||||
|
// Verifica che il file esista
|
||||||
|
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||||
|
{
|
||||||
|
await JSRuntime.InvokeVoidAsync("alert",
|
||||||
|
$"Errore: Il file '{profile.SourceFilePath}' non esiste o non è accessibile. " +
|
||||||
|
"Verifica il percorso del file prima di salvare il profilo.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verifica che il file sia leggibile
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var fs = new System.IO.FileStream(profile.SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
fs.Close();
|
||||||
|
Logger.LogInformation("File CSV validato con successo: {FilePath}", profile.SourceFilePath);
|
||||||
|
}
|
||||||
|
catch (Exception fileEx)
|
||||||
|
{
|
||||||
|
Logger.LogError(fileEx, "Errore nella lettura del file CSV: {FilePath}", profile.SourceFilePath);
|
||||||
|
await JSRuntime.InvokeVoidAsync("alert",
|
||||||
|
$"Errore: Il file '{profile.SourceFilePath}' non può essere letto. " +
|
||||||
|
$"Dettagli: {fileEx.Message}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Controlla se esiste già un profilo con lo stesso nome (inclusi quelli inattivi)
|
// Controlla se esiste già un profilo con lo stesso nome (inclusi quelli inattivi)
|
||||||
Logger.LogInformation("Controllo esistenza profilo con nome: {ProfileName}", profileDto.Name);
|
Logger.LogInformation("Controllo esistenza profilo con nome: {ProfileName}", profileDto.Name);
|
||||||
var existingProfile = await ProfileService.GetProfileByNameIncludingInactiveAsync(profileDto.Name);
|
var existingProfile = await ProfileService.GetProfileByNameIncludingInactiveAsync(profileDto.Name);
|
||||||
@@ -685,6 +720,8 @@ public partial class DataCoupler : ComponentBase
|
|||||||
|
|
||||||
// Reset file state
|
// Reset file state
|
||||||
selectedFileName = "";
|
selectedFileName = "";
|
||||||
|
manualFilePath = "";
|
||||||
|
uploadedFilePath = "";
|
||||||
isProcessingFile = false;
|
isProcessingFile = false;
|
||||||
fileErrorMessage = "";
|
fileErrorMessage = "";
|
||||||
fileSheets.Clear();
|
fileSheets.Clear();
|
||||||
@@ -698,6 +735,213 @@ public partial class DataCoupler : ComponentBase
|
|||||||
ClearAllMappings();
|
ClearAllMappings();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Valida e carica un file dal percorso specificato manualmente
|
||||||
|
/// </summary>
|
||||||
|
private async Task ValidateAndLoadFileFromPath()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
isProcessingFile = true;
|
||||||
|
fileErrorMessage = "";
|
||||||
|
fileSheets.Clear();
|
||||||
|
fileData.Clear();
|
||||||
|
selectedSheet = "";
|
||||||
|
uploadedFilePath = "";
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(manualFilePath))
|
||||||
|
{
|
||||||
|
fileErrorMessage = "Inserire il percorso del file";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valida che il file esista
|
||||||
|
if (!System.IO.File.Exists(manualFilePath))
|
||||||
|
{
|
||||||
|
fileErrorMessage = $"Il file '{manualFilePath}' non esiste o non è accessibile";
|
||||||
|
Logger.LogWarning("File non trovato: {FilePath}", manualFilePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valida estensione
|
||||||
|
var extension = Path.GetExtension(manualFilePath).ToLowerInvariant();
|
||||||
|
if (extension != ".xlsx" && extension != ".xls" && extension != ".csv")
|
||||||
|
{
|
||||||
|
fileErrorMessage = "Formato file non supportato. Utilizzare Excel (.xlsx, .xls) o CSV (.csv)";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verifica che il file sia leggibile
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var testStream = new System.IO.FileStream(manualFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
testStream.Close();
|
||||||
|
}
|
||||||
|
catch (Exception readEx)
|
||||||
|
{
|
||||||
|
fileErrorMessage = $"Il file non può essere letto: {readEx.Message}";
|
||||||
|
Logger.LogError(readEx, "Errore nella lettura del file: {FilePath}", manualFilePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.LogInformation("Validazione file completata: {FilePath}", manualFilePath);
|
||||||
|
|
||||||
|
// Carica il file dal percorso per preview
|
||||||
|
selectedFileName = Path.GetFileName(manualFilePath);
|
||||||
|
|
||||||
|
if (extension == ".csv")
|
||||||
|
{
|
||||||
|
await ProcessCsvFileFromPath(manualFilePath);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await ProcessExcelFileFromPath(manualFilePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se tutto è andato bene, salva il percorso validato
|
||||||
|
uploadedFilePath = manualFilePath;
|
||||||
|
Logger.LogInformation("File caricato con successo dal percorso: {FilePath}", uploadedFilePath);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logger.LogError(ex, "Errore nella validazione/caricamento del file dal percorso: {FilePath}", manualFilePath);
|
||||||
|
fileErrorMessage = $"Errore: {ex.Message}";
|
||||||
|
uploadedFilePath = "";
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
isProcessingFile = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Processa un file CSV dal percorso specificato
|
||||||
|
/// </summary>
|
||||||
|
private async Task ProcessCsvFileFromPath(string filePath)
|
||||||
|
{
|
||||||
|
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
using var reader = new StreamReader(stream);
|
||||||
|
|
||||||
|
var firstLine = await reader.ReadLineAsync();
|
||||||
|
if (string.IsNullOrEmpty(firstLine))
|
||||||
|
{
|
||||||
|
fileErrorMessage = "Il file CSV è vuoto";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var separator = DetectCsvSeparator(firstLine);
|
||||||
|
var headers = ParseCsvLine(firstLine, separator);
|
||||||
|
|
||||||
|
var sheetName = Path.GetFileNameWithoutExtension(filePath);
|
||||||
|
fileSheets[sheetName] = headers;
|
||||||
|
|
||||||
|
var dataRows = new List<Dictionary<string, object>>();
|
||||||
|
string? line;
|
||||||
|
while ((line = await reader.ReadLineAsync()) != null)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||||
|
|
||||||
|
var values = ParseCsvLine(line, separator);
|
||||||
|
var row = new Dictionary<string, object>();
|
||||||
|
for (int i = 0; i < headers.Count; i++)
|
||||||
|
{
|
||||||
|
var value = i < values.Count ? values[i] : "";
|
||||||
|
row[headers[i]] = string.IsNullOrEmpty(value) ? "" : value;
|
||||||
|
}
|
||||||
|
dataRows.Add(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
fileData[sheetName] = dataRows;
|
||||||
|
selectedSheet = sheetName;
|
||||||
|
|
||||||
|
Logger.LogInformation("File CSV processato: {FilePath}, Headers: {HeaderCount}, Rows: {RowCount}",
|
||||||
|
filePath, headers.Count, dataRows.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Processa un file Excel dal percorso specificato
|
||||||
|
/// </summary>
|
||||||
|
private async Task ProcessExcelFileFromPath(string filePath)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||||
|
|
||||||
|
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
var extension = Path.GetExtension(filePath).ToLowerInvariant();
|
||||||
|
|
||||||
|
IExcelDataReader reader;
|
||||||
|
if (extension == ".xlsx")
|
||||||
|
{
|
||||||
|
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
|
||||||
|
}
|
||||||
|
else if (extension == ".xls")
|
||||||
|
{
|
||||||
|
reader = ExcelReaderFactory.CreateBinaryReader(stream);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
fileErrorMessage = "Formato Excel non supportato";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
using (reader)
|
||||||
|
{
|
||||||
|
var configuration = new ExcelDataSetConfiguration()
|
||||||
|
{
|
||||||
|
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
|
||||||
|
{
|
||||||
|
UseHeaderRow = true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var dataSet = reader.AsDataSet(configuration);
|
||||||
|
|
||||||
|
foreach (DataTable table in dataSet.Tables)
|
||||||
|
{
|
||||||
|
var sheetName = table.TableName;
|
||||||
|
var headers = new List<string>();
|
||||||
|
var dataRows = new List<Dictionary<string, object>>();
|
||||||
|
|
||||||
|
foreach (DataColumn column in table.Columns)
|
||||||
|
{
|
||||||
|
headers.Add(column.ColumnName);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (DataRow dataRow in table.Rows)
|
||||||
|
{
|
||||||
|
var row = new Dictionary<string, object>();
|
||||||
|
foreach (var header in headers)
|
||||||
|
{
|
||||||
|
var value = dataRow[header];
|
||||||
|
row[header] = value == DBNull.Value ? "" : value?.ToString() ?? "";
|
||||||
|
}
|
||||||
|
dataRows.Add(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
fileSheets[sheetName] = headers;
|
||||||
|
fileData[sheetName] = dataRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileSheets.Any())
|
||||||
|
{
|
||||||
|
selectedSheet = fileSheets.First().Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.LogInformation("File Excel processato: {FilePath}, Sheets: {SheetCount}",
|
||||||
|
filePath, dataSet.Tables.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.CompletedTask;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logger.LogError(ex, "Errore nel processing del file Excel: {FilePath}", filePath);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task OnFileSelected(InputFileChangeEventArgs e)
|
private async Task OnFileSelected(InputFileChangeEventArgs e)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -719,7 +963,9 @@ public partial class DataCoupler : ComponentBase
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process file based on type
|
Logger.LogInformation("File caricato per preview: {FileName}", file.Name);
|
||||||
|
|
||||||
|
// Process file based on type (solo per preview, non salva sul server)
|
||||||
if (extension == ".csv")
|
if (extension == ".csv")
|
||||||
{
|
{
|
||||||
await ProcessCsvFile(file);
|
await ProcessCsvFile(file);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<div class="login-container">
|
<div class="login-container">
|
||||||
<div class="login-card">
|
<div class="login-card">
|
||||||
<div class="login-header">
|
<div class="login-header">
|
||||||
<h2>TEST Data Coupler</h2>
|
<h2>Data Coupler</h2>
|
||||||
<p>Accedi per continuare</p>
|
<p>Accedi per continuare</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -174,9 +174,9 @@
|
|||||||
<option value="0">-- Seleziona Profilo --</option>
|
<option value="0">-- Seleziona Profilo --</option>
|
||||||
@if (availableProfiles != null)
|
@if (availableProfiles != null)
|
||||||
{
|
{
|
||||||
@foreach (var profile in availableProfiles.Where(p => p.SourceType != "file"))
|
@foreach (var profile in availableProfiles)
|
||||||
{
|
{
|
||||||
<option value="@profile.Id">@profile.Name</option>
|
<option value="@profile.Id">@profile.Name @(profile.SourceType == "file" ? "(File)" : "")</option>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</InputSelect>
|
</InputSelect>
|
||||||
@@ -184,7 +184,8 @@
|
|||||||
@if (availableProfiles?.Any(p => p.SourceType == "file") == true)
|
@if (availableProfiles?.Any(p => p.SourceType == "file") == true)
|
||||||
{
|
{
|
||||||
<small class="form-text text-muted">
|
<small class="form-text text-muted">
|
||||||
⚠️ I profili con file come sorgente sono esclusi dalle schedulazioni per motivi di sicurezza.
|
ℹ️ I profili con file CSV/Excel come sorgente sono ora supportati per le schedulazioni.
|
||||||
|
Il file specificato nel profilo verrà letto ad ogni esecuzione.
|
||||||
</small>
|
</small>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -86,7 +86,8 @@ public partial class Scheduling : ComponentBase
|
|||||||
IntervalValue = schedule.IntervalValue,
|
IntervalValue = schedule.IntervalValue,
|
||||||
IntervalUnit = schedule.IntervalUnit,
|
IntervalUnit = schedule.IntervalUnit,
|
||||||
SourceDatabaseOverride = schedule.SourceDatabaseOverride,
|
SourceDatabaseOverride = schedule.SourceDatabaseOverride,
|
||||||
DestinationDatabaseOverride = schedule.DestinationDatabaseOverride
|
DestinationDatabaseOverride = schedule.DestinationDatabaseOverride,
|
||||||
|
EnableDeletionSync = schedule.EnableDeletionSync
|
||||||
};
|
};
|
||||||
|
|
||||||
// Imposta il profilo selezionato per mostrare i campi di override
|
// Imposta il profilo selezionato per mostrare i campi di override
|
||||||
@@ -278,7 +279,8 @@ public partial class Scheduling : ComponentBase
|
|||||||
var result = await DataTransferService.ExecuteProfileAsync(
|
var result = await DataTransferService.ExecuteProfileAsync(
|
||||||
schedule.Profile,
|
schedule.Profile,
|
||||||
schedule.SourceDatabaseOverride,
|
schedule.SourceDatabaseOverride,
|
||||||
schedule.DestinationDatabaseOverride);
|
schedule.DestinationDatabaseOverride,
|
||||||
|
schedule.EnableDeletionSync);
|
||||||
|
|
||||||
// Aggiorna lo storico con il risultato
|
// Aggiorna lo storico con il risultato
|
||||||
executionHistory.EndTime = DateTime.Now;
|
executionHistory.EndTime = DateTime.Now;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ namespace Data_Coupler.Services;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IDataTransferService
|
public interface IDataTransferService
|
||||||
{
|
{
|
||||||
Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null);
|
Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null, bool enableDeletionSync = false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class DataTransferResult
|
public class DataTransferResult
|
||||||
@@ -37,7 +37,7 @@ public class DataTransferService : IDataTransferService
|
|||||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null)
|
public async Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null, bool enableDeletionSync = false)
|
||||||
{
|
{
|
||||||
var result = new DataTransferResult
|
var result = new DataTransferResult
|
||||||
{
|
{
|
||||||
@@ -59,21 +59,11 @@ public class DataTransferService : IDataTransferService
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Controlla se il profilo ha file come sorgente e blocca l'esecuzione
|
|
||||||
if (profile.SourceType?.ToLower() == "file")
|
|
||||||
{
|
|
||||||
result.IsSuccess = false;
|
|
||||||
result.ErrorMessage = "I profili con file come sorgente non sono supportati nelle schedulazioni per motivi di sicurezza.";
|
|
||||||
result.EndTime = DateTime.Now; // Usa l'ora locale per coerenza
|
|
||||||
_logger.LogWarning("Tentativo di esecuzione di profilo con file come sorgente bloccato: {ProfileName}", profile.Name);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Applica override del database se specificati
|
// Applica override del database se specificati
|
||||||
var profileToExecute = await ApplyDatabaseOverrides(profile, sourceDatabaseOverride, destinationDatabaseOverride);
|
var profileToExecute = await ApplyDatabaseOverrides(profile, sourceDatabaseOverride, destinationDatabaseOverride);
|
||||||
|
|
||||||
// Utilizza il servizio esistente per l'esecuzione
|
// Utilizza il servizio esistente per l'esecuzione
|
||||||
var executionResult = await _scheduledExecutionService.ExecuteProfileAsync(profileToExecute.Id);
|
var executionResult = await _scheduledExecutionService.ExecuteProfileAsync(profileToExecute.Id, enableDeletionSync);
|
||||||
|
|
||||||
result.IsSuccess = executionResult.Success;
|
result.IsSuccess = executionResult.Success;
|
||||||
result.RecordsProcessed = executionResult.RecordsProcessed;
|
result.RecordsProcessed = executionResult.RecordsProcessed;
|
||||||
@@ -175,7 +165,8 @@ public class DataTransferService : IDataTransferService
|
|||||||
if (string.IsNullOrEmpty(profile.DestinationType))
|
if (string.IsNullOrEmpty(profile.DestinationType))
|
||||||
return (false, "Tipo destinazione non specificato");
|
return (false, "Tipo destinazione non specificato");
|
||||||
|
|
||||||
if (!profile.SourceCredentialId.HasValue)
|
// Per le sorgenti file, la credenziale non è richiesta
|
||||||
|
if (profile.SourceType != "file" && !profile.SourceCredentialId.HasValue)
|
||||||
return (false, "Credenziale sorgente non specificata");
|
return (false, "Credenziale sorgente non specificata");
|
||||||
|
|
||||||
if (!profile.DestinationCredentialId.HasValue)
|
if (!profile.DestinationCredentialId.HasValue)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ using System.Text;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Data_Coupler.Models;
|
using Data_Coupler.Models;
|
||||||
using Data_Coupler.Services;
|
using Data_Coupler.Services;
|
||||||
|
using ExcelDataReader;
|
||||||
|
|
||||||
namespace Data_Coupler.Services;
|
namespace Data_Coupler.Services;
|
||||||
|
|
||||||
@@ -130,9 +131,15 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
|||||||
var (restClient, restCredential, restEntity) = await SetupDestinationConnectionAsync(profile);
|
var (restClient, restCredential, restEntity) = await SetupDestinationConnectionAsync(profile);
|
||||||
|
|
||||||
// 2. Verifica che le connessioni siano valide
|
// 2. Verifica che le connessioni siano valide
|
||||||
if (sourceManager == null)
|
// Per i file, sourceManager sarà null (è normale), per database deve essere presente
|
||||||
|
if (profile.SourceType.ToLower() == "database" && sourceManager == null)
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Impossibile stabilire connessione con la sorgente dati");
|
throw new InvalidOperationException("Impossibile stabilire connessione con il database sorgente");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (profile.SourceType.ToLower() == "file" && string.IsNullOrEmpty(profile.SourceFilePath))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Percorso file sorgente non specificato nel profilo");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (restClient == null || restEntity == null)
|
if (restClient == null || restEntity == null)
|
||||||
@@ -187,11 +194,18 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<(IDatabaseManager? manager, DatabaseCredential? credential)> SetupSourceConnectionAsync(DataCouplerProfile profile)
|
private async Task<(IDatabaseManager? manager, DatabaseCredential? credential)> SetupSourceConnectionAsync(DataCouplerProfile profile)
|
||||||
{
|
{
|
||||||
if (profile.SourceType.ToLower() != "database")
|
_logger.LogInformation("SetupSourceConnectionAsync - SourceType: '{SourceType}', SourceCredentialId: {SourceCredentialId}, SourceFilePath: '{SourceFilePath}'",
|
||||||
|
profile.SourceType, profile.SourceCredentialId, profile.SourceFilePath);
|
||||||
|
|
||||||
|
// Se la sorgente è un file, non servono credenziali database
|
||||||
|
if (string.IsNullOrEmpty(profile.SourceType) ||
|
||||||
|
profile.SourceType.Equals("file", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
return (null, null); // Per i file gestiremo diversamente
|
_logger.LogInformation("Sorgente tipo file, nessuna connessione database necessaria");
|
||||||
|
return (null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Per database, la credenziale è obbligatoria
|
||||||
if (!profile.SourceCredentialId.HasValue)
|
if (!profile.SourceCredentialId.HasValue)
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Credenziale sorgente non specificata per il database");
|
throw new InvalidOperationException("Credenziale sorgente non specificata per il database");
|
||||||
@@ -378,18 +392,233 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ottiene tutti i record da file (implementazione future)
|
/// Ottiene tutti i record da file CSV o Excel
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<IEnumerable<Dictionary<string, object>>> GetAllRecordsFromFileAsync(DataCouplerProfile profile)
|
private async Task<IEnumerable<Dictionary<string, object>>> GetAllRecordsFromFileAsync(DataCouplerProfile profile)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(profile.SourceFilePath))
|
if (string.IsNullOrEmpty(profile.SourceFilePath))
|
||||||
throw new InvalidOperationException("Percorso file sorgente non specificato");
|
throw new InvalidOperationException("Percorso file sorgente non specificato");
|
||||||
|
|
||||||
// TODO: Implementazione per file Excel/CSV per le schedulazioni
|
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||||
// Per ora restituiamo una lista vuota
|
throw new FileNotFoundException($"Il file '{profile.SourceFilePath}' non esiste");
|
||||||
_logger.LogWarning("Lettura file non ancora implementata per le schedulazioni. File: {FilePath}", profile.SourceFilePath);
|
|
||||||
await Task.Delay(1); // Placeholder async
|
var extension = System.IO.Path.GetExtension(profile.SourceFilePath).ToLowerInvariant();
|
||||||
return new List<Dictionary<string, object>>();
|
|
||||||
|
_logger.LogInformation("Lettura file sorgente: {FilePath} (Tipo: {Extension})", profile.SourceFilePath, extension);
|
||||||
|
|
||||||
|
if (extension == ".csv")
|
||||||
|
{
|
||||||
|
return await ReadCsvFileAsync(profile.SourceFilePath);
|
||||||
|
}
|
||||||
|
else if (extension == ".xlsx" || extension == ".xls")
|
||||||
|
{
|
||||||
|
return await ReadExcelFileAsync(profile.SourceFilePath);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new NotSupportedException($"Formato file non supportato: {extension}. Utilizzare .csv, .xlsx o .xls");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Legge un file CSV e restituisce i record come dizionari
|
||||||
|
/// </summary>
|
||||||
|
private async Task<IEnumerable<Dictionary<string, object>>> ReadCsvFileAsync(string filePath)
|
||||||
|
{
|
||||||
|
var dataRows = new List<Dictionary<string, object>>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Apri in modalità condivisa per permettere ad altri processi di accedere al file
|
||||||
|
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
using var reader = new System.IO.StreamReader(stream);
|
||||||
|
|
||||||
|
var firstLine = await reader.ReadLineAsync();
|
||||||
|
if (string.IsNullOrEmpty(firstLine))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Il file CSV è vuoto: {FilePath}", filePath);
|
||||||
|
return dataRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect separator automatically
|
||||||
|
var separator = DetectCsvSeparator(firstLine);
|
||||||
|
_logger.LogDebug("CSV separator rilevato: '{Separator}'", separator);
|
||||||
|
|
||||||
|
// Parse headers (first row)
|
||||||
|
var headers = ParseCsvLine(firstLine, separator);
|
||||||
|
_logger.LogInformation("CSV headers: {Headers} (Totale: {Count})", string.Join(", ", headers), headers.Count);
|
||||||
|
|
||||||
|
// Read data rows
|
||||||
|
string? line;
|
||||||
|
int rowNumber = 2;
|
||||||
|
|
||||||
|
while ((line = await reader.ReadLineAsync()) != null)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||||
|
|
||||||
|
var values = ParseCsvLine(line, separator);
|
||||||
|
var row = new Dictionary<string, object>();
|
||||||
|
|
||||||
|
for (int i = 0; i < headers.Count; i++)
|
||||||
|
{
|
||||||
|
var value = i < values.Count ? values[i] : "";
|
||||||
|
row[headers[i]] = string.IsNullOrEmpty(value) ? "" : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
dataRows.Add(row);
|
||||||
|
rowNumber++;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("File CSV letto con successo: {FilePath}, Record: {RecordCount}", filePath, dataRows.Count);
|
||||||
|
return dataRows;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Errore nella lettura del file CSV: {FilePath}", filePath);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Legge un file Excel e restituisce i record come dizionari
|
||||||
|
/// </summary>
|
||||||
|
private async Task<IEnumerable<Dictionary<string, object>>> ReadExcelFileAsync(string filePath)
|
||||||
|
{
|
||||||
|
var dataRows = new List<Dictionary<string, object>>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Registra il provider di encoding per ExcelDataReader
|
||||||
|
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||||
|
|
||||||
|
// Apri in modalità condivisa per permettere ad altri processi di accedere al file
|
||||||
|
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
|
var extension = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
|
||||||
|
|
||||||
|
ExcelDataReader.IExcelDataReader reader;
|
||||||
|
if (extension == ".xlsx")
|
||||||
|
{
|
||||||
|
reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream);
|
||||||
|
}
|
||||||
|
else if (extension == ".xls")
|
||||||
|
{
|
||||||
|
reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(stream);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new NotSupportedException($"Formato Excel non supportato: {extension}");
|
||||||
|
}
|
||||||
|
|
||||||
|
using (reader)
|
||||||
|
{
|
||||||
|
var configuration = new ExcelDataReader.ExcelDataSetConfiguration()
|
||||||
|
{
|
||||||
|
ConfigureDataTable = (_) => new ExcelDataReader.ExcelDataTableConfiguration()
|
||||||
|
{
|
||||||
|
UseHeaderRow = true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var dataSet = reader.AsDataSet(configuration);
|
||||||
|
_logger.LogInformation("File Excel letto: {FilePath}, Fogli: {SheetCount}", filePath, dataSet.Tables.Count);
|
||||||
|
|
||||||
|
// Legge il primo foglio (o tutti i fogli se necessario)
|
||||||
|
if (dataSet.Tables.Count > 0)
|
||||||
|
{
|
||||||
|
var table = dataSet.Tables[0];
|
||||||
|
var headers = new List<string>();
|
||||||
|
|
||||||
|
foreach (System.Data.DataColumn column in table.Columns)
|
||||||
|
{
|
||||||
|
headers.Add(column.ColumnName);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (System.Data.DataRow dataRow in table.Rows)
|
||||||
|
{
|
||||||
|
var row = new Dictionary<string, object>();
|
||||||
|
foreach (var header in headers)
|
||||||
|
{
|
||||||
|
var value = dataRow[header];
|
||||||
|
row[header] = value == DBNull.Value ? "" : value?.ToString() ?? "";
|
||||||
|
}
|
||||||
|
dataRows.Add(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Foglio Excel '{SheetName}' letto con successo: {RecordCount} record",
|
||||||
|
table.TableName, dataRows.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.CompletedTask; // Per mantenere il metodo async
|
||||||
|
return dataRows;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Errore nella lettura del file Excel: {FilePath}", filePath);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rileva automaticamente il separatore CSV
|
||||||
|
/// </summary>
|
||||||
|
private char DetectCsvSeparator(string line)
|
||||||
|
{
|
||||||
|
var separators = new[] { ',', ';', '\t', '|' };
|
||||||
|
var maxCount = 0;
|
||||||
|
var detectedSeparator = ',';
|
||||||
|
|
||||||
|
foreach (var sep in separators)
|
||||||
|
{
|
||||||
|
var count = line.Count(c => c == sep);
|
||||||
|
if (count > maxCount)
|
||||||
|
{
|
||||||
|
maxCount = count;
|
||||||
|
detectedSeparator = sep;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return detectedSeparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parse di una riga CSV gestendo correttamente le virgolette
|
||||||
|
/// </summary>
|
||||||
|
private List<string> ParseCsvLine(string line, char separator = ',')
|
||||||
|
{
|
||||||
|
var result = new List<string>();
|
||||||
|
var current = new System.Text.StringBuilder();
|
||||||
|
bool inQuotes = false;
|
||||||
|
|
||||||
|
for (int i = 0; i < line.Length; i++)
|
||||||
|
{
|
||||||
|
char c = line[i];
|
||||||
|
|
||||||
|
if (c == '"')
|
||||||
|
{
|
||||||
|
if (inQuotes && i + 1 < line.Length && line[i + 1] == '"')
|
||||||
|
{
|
||||||
|
current.Append('"');
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
inQuotes = !inQuotes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (c == separator && !inQuotes)
|
||||||
|
{
|
||||||
|
result.Add(current.ToString().Trim());
|
||||||
|
current.Clear();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
current.Append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Add(current.ToString().Trim());
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+8
-5
@@ -24,17 +24,20 @@ RUN dotnet build "Data_Coupler.csproj" -c Release -o /app/build
|
|||||||
|
|
||||||
# Stage 2: Publish
|
# Stage 2: Publish
|
||||||
FROM build AS publish
|
FROM build AS publish
|
||||||
RUN dotnet publish "Data_Coupler.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
RUN dotnet publish "Data_Coupler.csproj" -c Release -o /app/publish \
|
||||||
|
/p:UseAppHost=false \
|
||||||
|
/p:PublishTrimmed=false \
|
||||||
|
/p:PublishSingleFile=false
|
||||||
|
|
||||||
# Stage 3: Runtime
|
# Stage 3: Runtime
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final
|
FROM mcr.microsoft.com/dotnet/aspnet:9.0-alpine AS final
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Installa le dipendenze necessarie per ExcelDataReader e altre librerie
|
# Installa le dipendenze necessarie per ExcelDataReader e altre librerie
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apk add --no-cache \
|
||||||
libgdiplus \
|
libgdiplus \
|
||||||
libc6-dev \
|
icu-libs \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
# Crea la directory per il database con i permessi corretti
|
# Crea la directory per il database con i permessi corretti
|
||||||
RUN mkdir -p /var/lib/Data_Coupler && \
|
RUN mkdir -p /var/lib/Data_Coupler && \
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ Data-Coupler è una soluzione integrata per la gestione di connessioni dati e cr
|
|||||||
- **DataConnection**: Libreria per connessioni a database e API REST
|
- **DataConnection**: Libreria per connessioni a database e API REST
|
||||||
- **Data_Coupler**: Applicazione Blazor Server per l'interfaccia utente
|
- **Data_Coupler**: Applicazione Blazor Server per l'interfaccia utente
|
||||||
|
|
||||||
|
### 🆕 Novità Recenti (Gennaio 2026)
|
||||||
|
- ✅ **Schedulazione File CSV/Excel**: Supporto completo per schedulare trasferimenti da file
|
||||||
|
- ✅ **Validazione Percorsi**: Validazione file prima del salvataggio profili
|
||||||
|
- ✅ **Deletion Sync Configurabile**: Controllo granulare sincronizzazione eliminazioni
|
||||||
|
- ✅ **Doppia Modalità File**: Caricamento browser (preview) + percorso manuale (schedulazione)
|
||||||
|
|
||||||
## Architettura
|
## Architettura
|
||||||
|
|
||||||
### CredentialManager
|
### CredentialManager
|
||||||
@@ -130,6 +136,36 @@ dotnet run --project Data_Coupler/Data_Coupler.csproj
|
|||||||
L'applicazione sarà disponibile su:
|
L'applicazione sarà disponibile su:
|
||||||
- HTTP: http://localhost:7550
|
- HTTP: http://localhost:7550
|
||||||
|
|
||||||
|
## Formati File Supportati
|
||||||
|
|
||||||
|
### CSV
|
||||||
|
- **Separatori**: `,` (virgola), `;` (punto e virgola), `\t` (tab), `|` (pipe)
|
||||||
|
- **Rilevamento automatico**: Sì
|
||||||
|
- **Gestione quote**: Supporto completo per campi tra virgolette
|
||||||
|
- **Escape caratteri**: Supporto per `""` (double quote escape)
|
||||||
|
- **Dimensione massima**: 50 MB (configurabile)
|
||||||
|
- **Schedulazione**: ✅ Supportato con percorso file manuale
|
||||||
|
|
||||||
|
### Excel
|
||||||
|
- **Formati**: `.xlsx` (Office Open XML), `.xls` (Binary Format)
|
||||||
|
- **Fogli multipli**: Legge il primo foglio per default
|
||||||
|
- **Header**: Prima riga utilizzata come intestazione
|
||||||
|
- **Dimensione massima**: 50 MB (configurabile)
|
||||||
|
- **Schedulazione**: ✅ Supportato con percorso file manuale
|
||||||
|
|
||||||
|
### Modalità Caricamento File
|
||||||
|
|
||||||
|
#### 1. Caricamento Browser (Preview)
|
||||||
|
- Carica file tramite browser per configurare mapping
|
||||||
|
- Processato in memoria, **non salvato sul server**
|
||||||
|
- Ideale per setup iniziale profilo
|
||||||
|
|
||||||
|
#### 2. Percorso Manuale (Schedulazione) ⭐
|
||||||
|
- Specifica percorso completo file sul server
|
||||||
|
- **Obbligatorio** per profili schedulati
|
||||||
|
- Sistema valida esistenza e leggibilità
|
||||||
|
- Esempi: `C:\Data\products.csv`, `/data/customers.xlsx`
|
||||||
|
|
||||||
### 🐳 Deployment Docker
|
### 🐳 Deployment Docker
|
||||||
|
|
||||||
**Quick Start con Docker:**
|
**Quick Start con Docker:**
|
||||||
@@ -167,16 +203,45 @@ docker build -t data-coupler:local-windows -f Dockerfile.windows .
|
|||||||
|
|
||||||
📚 **Documentazione Docker Completa**: Vedi [DOCKER_DEPLOYMENT.md](DOCKER_DEPLOYMENT.md) e [GITHUB_ACTIONS_SETUP.md](GITHUB_ACTIONS_SETUP.md)
|
📚 **Documentazione Docker Completa**: Vedi [DOCKER_DEPLOYMENT.md](DOCKER_DEPLOYMENT.md) e [GITHUB_ACTIONS_SETUP.md](GITHUB_ACTIONS_SETUP.md)
|
||||||
|
|
||||||
|
### 🔄 CI/CD Pipeline
|
||||||
|
|
||||||
|
Il progetto supporta pipeline CI/CD automatiche su:
|
||||||
|
|
||||||
|
**GitHub Actions** (`.github/workflows/docker-build.yml`):
|
||||||
|
- Build automatica su push ai branch `main`, `development`, `staging`
|
||||||
|
- Pubblicazione su GitHub Container Registry (`ghcr.io`)
|
||||||
|
- Multi-platform manifest (Linux + Windows)
|
||||||
|
|
||||||
|
**Gitea Actions** (`.gitea/workflows/docker-build.yml`):
|
||||||
|
- Stessa configurazione di GitHub Actions
|
||||||
|
- Pubblicazione su Gitea Container Registry (`gitea.home-nas-ds.org`)
|
||||||
|
- Istanza Gitea self-hosted con registry abilitato
|
||||||
|
- Configurazione: `.gitea/workflows/README.md`
|
||||||
|
|
||||||
|
**Immagini su Gitea** (self-hosted):
|
||||||
|
```bash
|
||||||
|
# Pull da Gitea Container Registry
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:latest
|
||||||
|
|
||||||
|
# Versioni disponibili
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:development-latest
|
||||||
|
docker pull gitea.home-nas-ds.org/alessio/data-coupler:staging-latest
|
||||||
|
```
|
||||||
|
|
||||||
|
📚 **Setup Gitea**: Vedi [.gitea/workflows/README.md](.gitea/workflows/README.md)
|
||||||
|
|
||||||
## Caratteristiche di Sicurezza
|
## Caratteristiche di Sicurezza
|
||||||
|
|
||||||
- **Crittografia**: Le password vengono crittografate prima del salvataggio
|
- **Crittografia**: Le password vengono crittografate prima del salvataggio
|
||||||
- **Validazione**: Validazione completa dei dati in input
|
- **Validazione**: Validazione completa dei dati in input
|
||||||
- **Isolamento**: Ogni progetto ha responsabilità specifiche
|
- **Isolamento**: Ogni progetto ha responsabilità specifiche
|
||||||
- **Type Safety**: Uso di tipi forti per evitare errori
|
- **Type Safety**: Uso di tipi forti per evitare errori
|
||||||
|
- **Validazione File**: Verifica esistenza e leggibilità file prima del salvataggio
|
||||||
- **Deletion Sync Sicuro**:
|
- **Deletion Sync Sicuro**:
|
||||||
- Disabilitato di default per prevenire eliminazioni accidentali
|
- Disabilitato di default per prevenire eliminazioni accidentali
|
||||||
- Disponibile solo nelle schedulazioni con configurazione esplicita
|
- Disponibile solo nelle schedulazioni con configurazione esplicita
|
||||||
- Warning chiaro nell'interfaccia utente per operazioni critiche
|
- Warning chiaro nell'interfaccia utente per operazioni critiche
|
||||||
|
- **Percorsi File Validati**: Controllo permessi e accessibilità per schedulazioni
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user