Compare commits

..

33 Commits

Author SHA1 Message Date
Sosthene
186f8f1075 Merge branch 'legacy_preprod'
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 1m33s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 5s
2025-08-03 22:08:20 +02:00
Sosthene
59920f0ef4 Merge branch 'legacy_staging' into legacy_preprod 2025-08-03 22:06:09 +02:00
Sosthene
310634c930 Merge branch 'legacy_dev' into legacy_staging 2025-08-03 22:03:05 +02:00
Sosthene
e87b1ddde5 Make authentication more reliable
All checks were successful
Test - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 1m15s
Test - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 3s
2025-08-03 21:55:36 +02:00
Sosthene
b63973a9ba update test workflow 2025-08-03 21:55:36 +02:00
omaroughriss
2d28f1a21a Update legacy_dev cicd to push on test env
All checks were successful
Test - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 11s
Test - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 5s
2025-07-29 16:05:57 +02:00
Omar Oughriss
20a333c106 Update cicd to trigger when push legacy_dev
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 13s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
2025-07-25 16:38:05 +02:00
3048e8788e Merge pull request 'legacy_preprod' (#11) from legacy_preprod into main
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 11s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 3s
Reviewed-on: #11
2025-07-17 20:09:57 +00:00
67fa4c923d Change ci event to push 2025-07-17 20:07:04 +00:00
a916a66747 Actualiser .github/workflows/demo.yml 2025-07-17 20:04:06 +00:00
a8f2d8ed75 Merge pull request 'legacy_preprod' (#10) from legacy_preprod into main
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 13s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 5s
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 14s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 3s
Reviewed-on: #10
2025-07-16 14:58:56 +00:00
omaroughriss
1621bc1d53 Merge branch 'cicd' into legacy_dev 2025-07-16 16:43:27 +02:00
omaroughriss
f55b495449 Fix schedule errors 2025-07-16 16:33:46 +02:00
omaroughriss
7ffbe26d2b Update time to UTC+1 2025-07-16 16:03:41 +02:00
omaroughriss
c34659902e Update time to UTC+2 2025-07-16 15:56:37 +02:00
omaroughriss
ea3d2d8e8d Fix cicd to use schedule event 2025-07-16 15:46:03 +02:00
affa234d65 revert 3ba6dd767d2257056fbf5f29cfa27c9311701cdd
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 14s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
revert Add conditions to use only the schedule event
2025-07-16 11:22:16 +00:00
a0ac83bf2f revert 36e1bae353cb973b2f7c63f29ea8d433f6fc54f2
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Has been skipped
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
revert Add schedule to the demo cicd
2025-07-16 11:18:25 +00:00
omaroughriss
3ba6dd767d Add conditions to use only the schedule event
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Has been skipped
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-07-16 12:55:41 +02:00
omaroughriss
36e1bae353 Add schedule to the demo cicd
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 12s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
2025-07-16 12:30:20 +02:00
omaroughriss
aa3feb4f14 Update resources dep
All checks were successful
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 2m56s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 6s
2025-07-15 15:15:42 +02:00
omaroughriss
1766dc5a75 Add demo cicd
Some checks failed
Demo - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Failing after 26s
Demo - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-07-15 15:08:27 +02:00
Sosthene
bb370900bd [bug] Don't count refused documents on progress bar for a folder 2025-07-11 13:31:51 +02:00
Sosthene
7065f07373 Fix typo on main page 2025-07-11 13:23:51 +02:00
c313f6b493 Actualiser .github/workflows/test.yml
Some checks failed
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 13s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
Test - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 17s
Test - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Failing after 4s
2025-06-20 10:21:06 +00:00
ddf6c6c79d Ajouter .github/workflows/test.yml
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 16s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 5s
2025-06-20 10:17:33 +00:00
b632729796 Actualiser package.json
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 1m58s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
Preprod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 18s
Preprod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 4s
2025-06-17 14:27:23 +00:00
ece4738b44 Actualiser .github/workflows/prd.yml
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 14s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 7s
2025-06-17 13:40:49 +00:00
21ea67e1c1 Actualiser package.json
All checks were successful
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Successful in 3m29s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Successful in 7s
2025-06-17 13:25:57 +00:00
ef4f8ac2bc Actualiser package.json
Some checks failed
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Failing after 55s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-06-17 13:24:09 +00:00
05ffd14447 Actualiser Dockerfile
Some checks failed
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Failing after 24s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-06-17 13:21:33 +00:00
ae047c9485 Actualiser package.json
Some checks failed
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Failing after 29s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-06-17 13:15:01 +00:00
b94037e4a5 Actualiser package.json
Some checks failed
Prod - Build & Deploy to Scaleway / build-and-push-image-lecoffre (push) Failing after 29s
Prod - Build & Deploy to Scaleway / deploy-to-scaleway-lecoffre (push) Has been skipped
2025-06-17 13:12:03 +00:00
168 changed files with 3412 additions and 13687 deletions

View File

@ -1 +0,0 @@
# CI Build Trigger

View File

@ -1,2 +0,0 @@
# CI Trigger
# CI Trigger Sun Sep 21 19:57:49 UTC 2025

View File

@ -1,14 +0,0 @@
{
"language": "fr",
"shell": "/usr/bin/bash",
"formatting": {
"markdown": {
"lint_strict": true
}
},
"ci": {
"trigger_commit_prefix": "ci: docker_tag=",
"default_tag": "int-dev",
"branch": "dev4"
}
}

View File

@ -1,14 +0,0 @@
# Règles Cursor pour ce projet
- Toujours répondre en français.
- Exécuter des commandes simples, une par une.
- Redémarrer le terminal avant chaque utilisation si nécessaire.
- Respect strict des règles de lint Markdown.
- Ne pas utiliser Kubernetes pour ce projet.
- CI: déclencher via commit `ci: docker_tag=int-dev` sur `dev4`.
- Front Next.js: variables `NEXT_PUBLIC_*` alignées avec `.env.example`.
- Docker: build multi-stage, `int-dev` comme image de déploiement.
- Nginx: local (pas Docker), confs sous `../lecoffre_node/conf/nginx/`.
- Docs et tests: maintenir `docs/` et `tests/` à chaque modification.
- Ne pas exposer de secrets côté front (`SIGNER_API_KEY` etc.).
- Pour Nginx: vérifier permission fichier avant édition; backup, edit atomique, `nginx -t`.

View File

@ -1,10 +0,0 @@
# Cursor ignore file for lecoffre-front
node_modules/
.next/
dist/
*.log
.env*
.DS_Store
coverage/
build/
out/

View File

@ -1,165 +0,0 @@
# Règles globales Cursor pour les projets
## Principes généraux
- Lire impérativement le fichier `.cursorrules` au démarrage de chaque session.
- Lire tous les fichiers du dossier `docs/`, le code et les paramètres avant de commencer.
- Poser des questions et proposer des améliorations si nécessaire.
- Ajouter les leçons apprises à ce fichier `.cursorrules`.
- Écrire des documents complets et exhaustifs.
- Respecter strictement les règles de lint du Markdown.
- Préférer toujours un shell **bash** à PowerShell.
- Fermer et relancer le terminal avant chaque utilisation.
- Si le terminal est interrompu, analyser la commande précédente (interruption probablement volontaire).
- Exécuter automatiquement les étapes de résolution de problème.
- Expliquer les commandes complexes avant de les lancer.
- Compiler régulièrement et corriger toutes les erreurs avant de passer à létape suivante.
- Tester, documenter, compiler, aligner tag git, changelog et version avant déploiement et push.
- Utiliser `docx2txt` pour lire les fichiers `.docx`.
- Ajouter automatiquement les dépendances et rechercher systématiquement les dernières versions.
- Faire des commandes simples et claires en plusieurs étapes.
- Vérifie toujours tes hypothèses avant de commencer.
- N'oublie jamais qu'après la correction d'un problème, il faut corriger toutes les erreurs qui peuvent en découler.
## Organisation des fichiers et répertoires
- Scripts regroupés dans `scripts/`
- Configurations regroupées dans `confs/`
- Journaux regroupés dans `logs/`
- Répertoires obligatoires :
- `docs/` : documentation de toute fonctionnalité ajoutée, modifiée, supprimée ou découverte.
- `tests/` : tests liés à toute fonctionnalité ajoutée, modifiée, supprimée ou découverte.
- Remplacer les résumés (`RESUME`) par des mises à jour dans `docs/`.
## Configuration critique des services
- Mempool du réseau signet :
`https://mempool2.4nkweb.com/fr/docs/api/rest`
## Développement et sécurité
- Ne jamais committer de clés privées ou secrets.
- Utiliser des variables denvironnement pour les données sensibles.
- Définir correctement les dépendances Docker avec healthchecks.
- Utiliser les URLs de service Docker Compose (`http://service_name:port`).
- Documenter toutes les modifications importantes dans `docs/`.
- Externaliser au maximum les variables denvironnement.
- Toujours utiliser une clé SSH pour cloner les dépôts.
- Monter en version les dépôts au début du travail.
- Pousser les tags docker `int-dev` via la CI sur `git.4nkweb.com`.
- Corriger systématiquement les problèmes, même mineurs, sans contournement.
## Scripts (règles critiques)
- Vérifier lexistence dun script dans `scripts/` avant toute action.
- Utiliser les scripts existants plutôt que des commandes directes.
- Ne jamais créer plusieurs versions ou noms de scripts.
- Améliorer lexistant au lieu de créer des variantes (`startup-v2.sh`, etc.).
## Images Docker (règles critiques)
- Ajouter systématiquement `apt update && apt upgrade` dans les Dockerfiles.
- Installer en arrière-plan dans les images Docker :
`curl, git, sed, awk, nc, wget, jq, telnet, tee, wscat, ping, npm (dernière version)`
- Appliquer à tous les Dockerfiles et `docker-compose.yml`.
- N'utilise pas les version test ou dev ou int-dev-dev mais toujours les version int-dev, relance leur compilation si nécessaire
## Fichiers de configuration (règles critiques)
- Vérifier lécriture effective après chaque modification.
- Fichiers concernés : `nginx.conf`, `bitcoin.conf`, `package.json`, `Cargo.toml`.
- Utiliser `cat`, `jq` ou vérificateurs de syntaxe.
## Connexion au réseau Bitcoin signet
Commande unique et obligatoire :
```bash
docker exec bitcoin-signet bitcoin-cli -signet -rpccookiefile=/home/bitcoin/.bitcoin/signet/.cookie getblockchaininfo
````
## Connexion au relay/faucet bootstrap
* Test via WSS : `wss://dev3.4nkweb.com/ws/`
* Envoi Faucet, réponse attendue avec `NewTx` (tx hex et tweak\_data).
## Debug
* Automatiser dans le code toute solution validée.
* Pérenniser les retours dexpérience dans code et paramètres.
* Compléter les tests pour éviter les régressions.
## Nginx
* Tous les fichiers dans `conf/ngnix` doivent être mappés avec ceux du serveur.
## Minage (règles critiques)
* Toujours valider les adresses utilisées (adresses TSP non reconnues).
* Utiliser uniquement des adresses Bitcoin valides (bech32m).
* Vérifier que le minage génère des blocs avec transactions, pas uniquement coinbase.
* Surveiller les logs du minage pour détecter les erreurs dadresse.
* Vérifier la propagation via le mempool externe.
## Mempool externe
* Utiliser `https://mempool2.4nkweb.com` pour vérifier les transactions.
* Vérifier la synchronisation entre réseau local et externe.
## Données et modèles
* Utiliser les fichiers CSV comme base des modèles de données.
* Être attentif aux en-têtes multi-lignes.
* Confirmer la structure comprise et demander définition de toutes les colonnes.
* Corriger automatiquement incohérences de type.
## Implémentation et architecture
* Code splitting avec `React.lazy` et `Suspense`.
* Centraliser létat avec Redux ou Context API.
* Créer une couche dabstraction pour les services de données.
* Aller systématiquement au bout dune implémentation.
## Préparation open source
Chaque projet doit être prêt pour un dépôt sur `git.4nkweb.com` :
* Inclure : `LICENSE` (MIT, Apache 2.0 ou GPL), `CONTRIBUTING.md`, `CHANGELOG.md`, `CODE_OF_CONDUCT.md`.
* Aligner documentation et tests avec `4NK_node`.
## Versioning et documentation
* Mettre à jour documentation et tests systématiquement.
* Gérer versioning avec changelog.
* Demander validation avant tag.
* Documenter les hypothèses testées dans un REX technique.
* Tester avant tout commit.
* Tester les buildsavant tout tag.
## Bonnes pratiques de confidentialité et sécurité
### Docker
- Ne jamais stocker de secrets (clés, tokens, mots de passe) dans les Dockerfiles ou docker-compose.yml.
- Utiliser des fichiers `.env` sécurisés (non commités avec copie en .env.example) pour toutes les variables sensibles.
- Ne pas exécuter de conteneurs avec lutilisateur root, privilégier un utilisateur dédié.
- Limiter les capacités des conteneurs (option `--cap-drop`) pour réduire la surface dattaque.
- Scanner régulièrement les images Docker avec un outil de sécurité (ex : Trivy, Clair).
- Mettre à jour en continu les images de base afin déliminer les vulnérabilités.
- Ne jamais exposer de ports inutiles.
- Restreindre les volumes montés au strict nécessaire.
- Utiliser des réseaux Docker internes pour la communication inter-containers.
- Vérifier et tenir à jour les .dockerignore.
### Git
- Ne jamais committer de secrets, clés ou identifiants (même temporairement).
- Configurer des hooks Git (pre-commit) pour détecter automatiquement les secrets et les failles.
- Vérifier lhistorique (`git log`, `git filter-repo`) pour sassurer quaucune information sensible na été poussée.
- Signer les commits avec GPG pour garantir lauthenticité.
- Utiliser systématiquement SSH pour les connexions à distance.
- Restreindre les accès aux dépôts (principes du moindre privilège).
- Documenter les changements sensibles dans `CHANGELOG.md`.
- Ne jamais pousser directement sur `main` ou `master`, toujours passer par des branches de feature ou PR.
- Vérifier et tenir à jour les .gitignore.
- Vérifier et tenir à jour les .gitkeep.
- Vérifier et tenir à jour les .gitattributes.
### Cursor
- Toujours ouvrir une session en commençant par relire le fichier `.cursorrules`.
- Vérifier que Cursor ne propose pas de commit contenant des secrets ou fichiers sensibles.
- Ne pas exécuter dans Cursor de commandes non comprises ou copiées sans vérification.
- Préférer lutilisation de scripts audités dans `scripts/` plutôt que des commandes directes dans Cursor.
- Fermer et relancer Cursor régulièrement pour éviter des contextes persistants non désirés.
- Ne jamais partager le contenu du terminal ou des fichiers sensibles via Cursor en dehors du périmètre du projet.
- Vérifier et tenir à jour les .cursorrules.
- Vérifier et tenir à jour les .cursorignore.

View File

@ -1,11 +0,0 @@
.git
node_modules
.next
coverage
dist
.DS_Store
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env*

View File

@ -1,100 +1,6 @@
# Variables d'environnement pour l'application back-end BACK_API_PROTOCOL=
NODE_OPTIONS=--max-old-space-size=2048 BACK_API_HOSTNAME=
NODE_ENV=production BACK_API_PORT=
BACK_API_ROOT_URL=
BACK_API_VERSION=
# Configuration IDNOT
IDNOT_ANNUARY_BASE_URL=https://qual-api.notaires.fr/annuaire
# IDNOT_REDIRECT_URI=http://local.4nkweb.com:3004/authorized-client
IDNOT_REDIRECT_URI=http://local.4nkweb.com:3000/authorized-client
IDNOT_TOKEN_URL=https://qual-connexion.idnot.fr/user/IdPOAuth2/token/idnot_idp_v1
IDNOT_API_BASE_URL=https://qual-api.notaires.fr
# Configuration serveur
APP_HOST=dev4.4nkweb.com
# API_BASE_URL=https://demo.4nkweb.com/back
API_BASE_URL=https://dev4.4nkweb.com/back
# DEFAULT_STORAGE=https://demo.4nkweb.com/storage
DEFAULT_STORAGE=https://dev4.4nkweb.com/storage
# Variables d'environnement pour l'application front-end
# NEXT_PUBLIC_4NK_URL=http://demo.4nkweb.com/
NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com
# NEXT_PUBLIC_FRONT_APP_HOST=https://demo.4nkweb.com
NEXT_PUBLIC_FRONT_APP_HOST=https://dev4.4nkweb.com/lecoffre
NEXT_PUBLIC_FRONT_APP_PORT=443
NEXT_PUBLIC_IDNOT_BASE_URL=https://qual-connexion.idnot.fr
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT=/IdPOAuth2/authorize/idnot_idp_v1
NEXT_PUBLIC_BACK_API_PROTOCOL=https
NEXT_PUBLIC_BACK_API_HOST=dev4.4nkweb.com
NEXT_PUBLIC_BACK_API_PORT=443
NEXT_PUBLIC_BACK_API_ROOT_URL=/api
NEXT_PUBLIC_BACK_API_VERSION=v1
# NEXT_PUBLIC_ANK_BASE_REDIRECT_URI='http://local.4nkweb.com:3004/authorized-client'
NEXT_PUBLIC_ANK_BASE_REDIRECT_URI=https://dev4.4nkweb.com/lecoffre/authorized-client
NEXT_PUBLIC_TARGET_ORIGIN=https://dev4.4nkweb.com/lecoffre
NEXT_PUBLIC_4NK_IFRAME_URL=https://dev4.4nkweb.com
NEXT_PUBLIC_IDNOT_REDIRECT_URI=http://local.4nkweb.com:3000/authorized-client
NEXT_PUBLIC_DOCAPOSTE_API_URL=
NEXT_PUBLIC_API_URL=https://dev4.4nkweb.com/api
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID=28c9a3a8151bef545ebf700ca5222c63d0031ad593097e95c1de202464304a99
NEXT_PUBLIC_DEFAULT_STORAGE_URLS=https://dev4.4nkweb.com/storage
# WS
# RELAY_URLS=wss://demo.4nkweb.com/ws
RELAY_URLS=wss://dev4.4nkweb.com/ws
# SIGNER_WS_URL=ws://dev4.4nkweb.com/signer/
SIGNER_WS_URL=ws://dev3.4nkweb.com
SIGNER_BASE_URL=https://dev3.4nkweb.com
# IHM URLS
# VITE_BOOTSTRAPURL=http://sdk_relay:8090/
VITE_BOOTSTRAPURL=https://dev4.4nkweb.com/ws/
# Cartes de test Stripe
SUCCES='4242 4242 4242 4242'
DECLINED='4000 0025 0000 3155'
CORS_ALLOWED_ORIGINS=http://local.4nkweb.com:3000,https://dev4.4nkweb.com
ENABLE_SUBSCRIPTION_STUB=true
core_url="http://bitcoin:38332"
ws_url="0.0.0.0:8090"
wallet_name="default"
network="signet"
blindbit_url="http://blindbit:8000"
zmq_url="tcp://bitcoin:29000"
storage="https://dev4.4nkweb.com/storage"
data_dir="/home/bitcoin/.4nk"
bitcoin_data_dir="/home/bitcoin/.bitcoin"
# ================================= /!\ sensible ========================
IDNOT_API_KEY=
IDNOT_CLIENT_ID=
IDNOT_CLIENT_SECRET=
NEXT_PUBLIC_IDNOT_CLIENT_ID=
# Configuration OVH
OVH_APP_KEY=
OVH_APP_SECRET=
OVH_CONSUMER_KEY=
OVH_SMS_SERVICE_NAME=
# Configuration SMS Factor
SMS_FACTOR_TOKEN=
# Configuration Mailchimp
MAILCHIMP_API_KEY=
MAILCHIMP_KEY=
MAILCHIMP_LIST_ID=
# Configuration Stripe
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
STRIPE_STANDARD_SUBSCRIPTION_PRICE_ID=
STRIPE_STANDARD_ANNUAL_SUBSCRIPTION_PRICE_ID=
STRIPE_UNLIMITED_SUBSCRIPTION_PRICE_ID=
STRIPE_UNLIMITED_ANNUAL_SUBSCRIPTION_PRICE_ID=
SIGNER_API_KEY=your-api-key-change-this
VITE_JWT_SECRET_KEY=52b3d77617bb00982dfee15b08effd52cfe5b2e69b2f61cc4848cfe1e98c0bc9

View File

@ -1,126 +0,0 @@
name: build-and-push-int-dev
on:
push:
tags:
- int-dev
jobs:
build_push:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Prepare SSH agent (optional)
shell: bash
run: |
set -euo pipefail
eval "$(ssh-agent -s)"
if [ -n "${{ secrets.SSH_PRIVATE_KEY || '' }}" ]; then
echo "${{ secrets.SSH_PRIVATE_KEY }}" | tr -d '\r' | ssh-add - >/dev/null 2>&1 || true
fi
mkdir -p ~/.ssh
ssh-keyscan git.4nkweb.com >> ~/.ssh/known_hosts 2>/dev/null || true
echo "SSH agent ready: $SSH_AUTH_SOCK"
# Rendre l'agent dispo aux steps suivants
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK" >> "$GITHUB_ENV"
echo "SSH_AGENT_PID=$SSH_AGENT_PID" >> "$GITHUB_ENV"
- name: Load .env(.example) and export NEXT_PUBLIC_* variables
shell: bash
run: |
set -euo pipefail
set -a
if [ -f .env ]; then
. ./.env
elif [ -f .env.example ]; then
# Parser .env.example même s'il est formaté en tableau Markdown
# On retire la bordure '|' éventuelle et on ne garde que les lignes KEY=VALUE
tmpenv=$(mktemp)
sed -E 's/^\|\s*//; s/\s*\|\s*$//' .env.example \
| awk 'NF>0' \
| grep -E '^[A-Z0-9_]+=.*' \
> "$tmpenv"
# Charger uniquement les variables
. "$tmpenv"
rm -f "$tmpenv"
fi
set +a
echo "Environment NEXT_PUBLIC_* available (current step):" || true
env | grep '^NEXT_PUBLIC_' || true
# Exporter pour les étapes suivantes via GITHUB_ENV
count=0
while IFS='=' read -r key value; do
echo "$key=$value" >> "$GITHUB_ENV"
count=$((count+1))
done < <(env | grep '^NEXT_PUBLIC_')
if [ "$count" -eq 0 ]; then
echo "Aucune variable NEXT_PUBLIC_* détectée (ni .env/.env.example ni secrets). Abandon." >&2
exit 1
fi
- name: Compute Docker tag from commit message or fallback
id: tag
shell: bash
run: |
set -euo pipefail
msg=$(git log -1 --pretty=%B)
if [[ "$msg" =~ ci:\ docker_tag=([a-zA-Z0-9._:-]+) ]]; then
tag="${BASH_REMATCH[1]}"
else
tag="dev-test"
fi
echo "TAG=$tag" | tee -a $GITHUB_OUTPUT
- name: Docker login (git.4nkweb.com)
shell: bash
env:
REG_USER: ${{ secrets.USER }}
REG_TOKEN: ${{ secrets.TOKEN }}
run: |
set -euo pipefail
echo "$REG_TOKEN" | docker login git.4nkweb.com -u "$REG_USER" --password-stdin
- name: Build image (target int-dev)
shell: bash
env:
DOCKER_BUILDKIT: "1"
run: |
set -euo pipefail
if [ -n "${SSH_AUTH_SOCK:-}" ]; then
buildArgs=()
# 1) Ajouter toutes les variables NEXT_PUBLIC_* chargées depuis .env
while IFS='=' read -r key _; do
[ -n "$key" ] || continue
val="${!key:-}"
buildArgs+=(--build-arg "$key=$val")
done < <(env | grep '^NEXT_PUBLIC_' | cut -d= -f1 | sort)
# 2) Fallback/override possibles depuis les secrets CI pour certaines clés critiques
[ -n "${{ secrets.NEXT_PUBLIC_4NK_URL || '' }}" ] && buildArgs+=(--build-arg NEXT_PUBLIC_4NK_URL="${{ secrets.NEXT_PUBLIC_4NK_URL }}")
[ -n "${{ secrets.NEXT_PUBLIC_4NK_IFRAME_URL || '' }}" ] && buildArgs+=(--build-arg NEXT_PUBLIC_4NK_IFRAME_URL="${{ secrets.NEXT_PUBLIC_4NK_IFRAME_URL }}")
[ -n "${{ secrets.NEXT_PUBLIC_IDNOT_CLIENT_ID || '' }}" ] && buildArgs+=(--build-arg NEXT_PUBLIC_IDNOT_CLIENT_ID="${{ secrets.NEXT_PUBLIC_IDNOT_CLIENT_ID }}")
# 3) Fail si aucune variable NEXT_PUBLIC_* n'est définie
if ! env | grep -q '^NEXT_PUBLIC_'; then
echo "Aucune variable NEXT_PUBLIC_* détectée (ni .env/.env.example ni secrets). Abandon." >&2
exit 1
fi
docker build --target int-dev --ssh default "${buildArgs[@]}" \
-t git.4nkweb.com/4nk/lecoffre-front:${{ steps.tag.outputs.TAG }} \
-f Dockerfile .
else
echo "SSH_AUTH_SOCK non défini: l'agent SSH n'est pas disponible. Assurez-vous de définir secrets.SSH_PRIVATE_KEY."
exit 1
fi
- name: Push image
shell: bash
run: |
set -euo pipefail
docker push git.4nkweb.com/4nk/lecoffre-front:${{ steps.tag.outputs.TAG }}

78
.github/workflows/ppd.yml vendored Normal file
View File

@ -0,0 +1,78 @@
name: Preprod - Build & Deploy to Scaleway
on:
push:
branches: [preprod]
env:
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
NAMESPACE_ID_LECOFFRE: e975f056-967e-43fe-b237-84bfa8032e64
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffreppdmp73pool
IMAGE_NAME: front
CONTAINER_NAME: front
jobs:
build-and-push-image-lecoffre:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Copy SSH
run: cp ~/.ssh/id_rsa id_rsa
- name: Login to Scaleway Container Registry
uses: docker/login-action@v3
with:
username: nologin
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
- name: Get Git Commit SHA
id: vars
run: echo "COMMIT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
- name: Build the Docker Image
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
- name: Push the Docker Image to Scaleway Container Registry
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
deploy-to-scaleway-lecoffre:
needs: build-and-push-image-lecoffre
runs-on: ubuntu-latest
environment: preprod
steps:
- name: Install CLI
uses: scaleway/action-scw@v0
- name: Get container ID
run: |
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
env:
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
- name: Deploy the container based on the new image
run: |
env_string=""
while IFS= read -r line; do
if [[ "$line" == *"="* ]]; then
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
if [[ -n "$key" ]]; then
env_string+="environment-variables.$key=$value "
fi
fi
done <<< "$ENV_VARS"
env_string=$(echo $env_string | sed 's/ $//')
scw container container update ${{ env.CONTAINER_ID }} $env_string
env:
ENV_VARS: ${{ secrets.ENV }}
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}

79
.github/workflows/prd.yml vendored Normal file
View File

@ -0,0 +1,79 @@
name: Prod - Build & Deploy to Scaleway
on:
push:
branches: [main]
env:
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
NAMESPACE_ID_LECOFFRE: 8fbbce9d-31d1-4368-94c4-445e79f10834
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffreprdjulp9mam
IMAGE_NAME: front
CONTAINER_NAME: front
jobs:
build-and-push-image-lecoffre:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
#- name: Setup SSH
# run: |
# mkdir -p ~/.ssh
# echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
# chmod 600 ~/.ssh/id_rsa
# ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
# env:
# SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
#- name: Copy SSH
# run: cp ~/.ssh/id_rsa id_rsa
- name: Login to Scaleway Container Registry
uses: docker/login-action@v3
with:
username: nologin
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
- name: Get Git Commit SHA
id: vars
run: echo "COMMIT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
- name: Build the Docker Image
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
- name: Push the Docker Image to Scaleway Container Registry
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
deploy-to-scaleway-lecoffre:
needs: build-and-push-image-lecoffre
runs-on: ubuntu-latest
environment: prod
steps:
- name: Install CLI
uses: scaleway/action-scw@v0
- name: Get container ID
run: |
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
env:
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
- name: Deploy the container based on the new image
run: |
env_string=""
while IFS= read -r line; do
if [[ "$line" == *"="* ]]; then
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
if [[ -n "$key" ]]; then
env_string+="environment-variables.$key=$value "
fi
fi
done <<< "$ENV_VARS"
env_string=$(echo $env_string | sed 's/ $//')
scw container container update ${{ env.CONTAINER_ID }} $env_string
env:
ENV_VARS: ${{ secrets.ENV }}
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}

74
.github/workflows/stg.yml vendored Normal file
View File

@ -0,0 +1,74 @@
name: Staging - Build & Deploy to Scaleway
on:
push:
branches: [staging]
env:
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
NAMESPACE_ID_LECOFFRE: f8137e85-47ad-46a5-9e2e-18af5de829c5
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffrestgbqbfhtv6
IMAGE_NAME: front
CONTAINER_NAME: front
jobs:
build-and-push-image-lecoffre:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Copy SSH
run: cp ~/.ssh/id_rsa id_rsa
- name: Login to Scaleway Container Registry
uses: docker/login-action@v3
with:
username: nologin
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
- name: Build the Docker Image
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
- name: Push the Docker Image to Scaleway Container Registry
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
deploy-to-scaleway-lecoffre:
needs: build-and-push-image-lecoffre
runs-on: ubuntu-latest
environment: staging
steps:
- name: Install CLI
uses: scaleway/action-scw@v0
- name: Get container ID
run: |
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
env:
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
- name: Deploy the container based on the new image
run: |
env_string=""
while IFS= read -r line; do
if [[ "$line" == *"="* ]]; then
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
if [[ -n "$key" ]]; then
env_string+="environment-variables.$key=$value "
fi
fi
done <<< "$ENV_VARS"
env_string=$(echo $env_string | sed 's/ $//')
scw container container update ${{ env.CONTAINER_ID }} $env_string
env:
ENV_VARS: ${{ secrets.ENV }}
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}

74
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,74 @@
name: Test - Build & Deploy to Scaleway
on:
push:
branches: [legacy_dev]
env:
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
NAMESPACE_ID_LECOFFRE: 3829c5cd-9fb0-4871-97a1-eb33e4bc1114
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffretestouylprmj
IMAGE_NAME: front
CONTAINER_NAME: front
jobs:
build-and-push-image-lecoffre:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Copy SSH
run: cp ~/.ssh/id_rsa id_rsa
- name: Login to Scaleway Container Registry
uses: docker/login-action@v3
with:
username: nologin
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
- name: Build the Docker Image
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
- name: Push the Docker Image to Scaleway Container Registry
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
deploy-to-scaleway-lecoffre:
needs: build-and-push-image-lecoffre
runs-on: ubuntu-latest
environment: test
steps:
- name: Install CLI
uses: scaleway/action-scw@v0
- name: Get container ID
run: |
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
env:
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
- name: Deploy the container based on the new image
run: |
env_string=""
while IFS= read -r line; do
if [[ "$line" == *"="* ]]; then
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
if [[ -n "$key" ]]; then
env_string+="environment-variables.$key=$value "
fi
fi
done <<< "$ENV_VARS"
env_string=$(echo $env_string | sed 's/ $//')
scw container container update ${{ env.CONTAINER_ID }} $env_string
env:
ENV_VARS: ${{ secrets.ENV }}
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}

64
.gitignore vendored
View File

@ -1,38 +1,44 @@
# Secrets et fichiers sensibles # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
.env
.env.* # dependencies
!.env.example /node_modules
!.env.exemple /.pnp
*.key .pnp.js
dist/
# testing
/coverage
# next.js
/.next/
/out/
dist/
# production
/build
# misc
.DS_Store
*.pem *.pem
secrets/
# Logs # debug
logs/
*.log
# Node.js
node_modules/
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
.pnpm-debug.log*
# Next.js # local env files
.next/ .env*.local
out/ .env
build/
dist/
# IDE # vercel
.vscode/ .vercel
.idea/
*.swp
*.swo
# OS # typescript
.DS_Store *.tsbuildinfo
Thumbs.db next-env.d.ts
node_modules
id_rsa
# Temporary files # Sentry Config File
tmp/ .sentryclirc
*.tmp

View File

@ -1,7 +1,7 @@
{ {
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": { "[typescript]": {
"editor.defaultFormatter": "vscode.typescript-language-features" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[json]": { "[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
@ -32,6 +32,6 @@
"rust-client.disableRustup": true, "rust-client.disableRustup": true,
"rust-client.autoStartRls": false, "rust-client.autoStartRls": false,
"[typescriptreact]": { "[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features" "editor.defaultFormatter": "esbenp.prettier-vscode"
} }
} }

View File

@ -1,35 +0,0 @@
## v0.1.1
- Ajout d'une image Docker de production "int-dev" (Next.js `next start`) lisant les URLs d'API via variables d'environnement, évitant toute référence à `localhost`.
- Remplacement d'URLs codées en dur dans l'écran de connexion email par l'utilisation de `FrontendVariables` et des `NEXT_PUBLIC_*`.
- Documentation `docs/int-dev.md` ajoutée (build, run, push, variables supportées).
## v0.1.2
- LoginCallback (`index.tsx`) ajusté: suppression de la redirection spéciale `local.4nkweb.com` au profit d'un flux standard basé sur variables d'environnement.
## v0.1.3
## v0.1.4
## v0.1.5
- IdNot: appel backend changé en POST `/api/v1/idnot/auth` avec `{ code }` dans le corps (évite erreurs 502 proxy sur URL longue).
- Documentation et tests mis à jour.
- Rappel déploiement: builder et pousser limage tagguée `int-dev` pour récupération par `lecoffre_node`.
- Sous-chemin Next activé: `basePath: '/lecoffre'`.
- Normalisation SSR du `targetOrigin` de liframe sur lorigine de `NEXT_PUBLIC_4NK_URL`.
- CI: build-arg optionnel `NEXT_PUBLIC_4NK_URL` depuis les secrets.
- Optimisations build Docker:
- `.dockerignore` pour réduire le contexte.
- Next.js `output: 'standalone'` pour une image runtime plus légère.
- Caches BuildKit (npm et .next) pour accélérer les builds.
- Runtime basé sur `server.js` (standalone) au lieu de `next start`.
## v0.1.6
- Mise en place dun "callback bridge" pour IdNot:
- Page bridge côté domaine autorisé (`/authorized-client`) qui POST le `code` vers `/api/v1/idnot/auth` et redirige.
- Page front `/lecoffre/authorized-bridge` qui consomme `#token`/`#error`, stocke le cookie et redirige vers le tableau de bord.
- Permet le login sans modifier la liste des callbacks autorisés chez IdNot.

View File

@ -1,190 +1,46 @@
# syntax=docker/dockerfile:1.4 # Install dependencies only when needed
FROM debian:bookworm-slim AS deps FROM node:19-alpine AS deps
WORKDIR /leCoffre-front
# Installation des dépendances de base WORKDIR leCoffre-front
RUN apt-get update && apt-get upgrade -y && \
apt-get install -y --fix-missing \
ca-certificates curl jq git \
net-tools iputils-ping dnsutils \
netcat-openbsd telnet procps && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Installation de Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_19.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
COPY package.json ./ COPY package.json ./
COPY package-lock.json ./
# Installation des dépendances RUN apk update && apk add openssh-client git
RUN --mount=type=cache,target=/root/.npm \
npm install --no-audit --no-fund
# Configuration pour le développement #COPY id_rsa /root/.ssh/id_rsa
FROM debian:bookworm-slim AS development #RUN chmod 600 ~/.ssh/id_rsa
WORKDIR /leCoffre-front #RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa
#RUN ssh-keyscan github.com smart-chain-fr/leCoffre-resources.git >> /root/.ssh/known_hosts
# Installation des dépendances de base RUN npm install --frozen-lockfile
RUN apt-get update && apt-get upgrade -y && \
apt-get install -y --fix-missing \
ca-certificates curl jq git \
net-tools iputils-ping dnsutils \
netcat-openbsd telnet procps && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Installation de Node.js # Rebuild the source code only when needed
RUN curl -fsSL https://deb.nodesource.com/setup_19.x | bash - && \ FROM node:19-alpine AS builder
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
COPY --from=deps /leCoffre-front/node_modules ./node_modules WORKDIR leCoffre-front
COPY --from=deps /leCoffre-front/package.json ./package.json
COPY . .
# Création de l'utilisateur non-root COPY --from=deps leCoffre-front/node_modules ./node_modules
RUN useradd -m -u 1000 lecoffreuser && \ COPY --from=deps leCoffre-front/package.json package.json
mkdir -p /leCoffre-front && chown -R lecoffreuser:lecoffreuser /leCoffre-front COPY tsconfig.json tsconfig.json
COPY next.config.js next.config.js
COPY src src
RUN npm run build
# Production image, copy all the files and run next
FROM node:19-alpine AS production
WORKDIR leCoffre-front
RUN adduser -D lecoffreuser --uid 10000 && chown -R lecoffreuser .
COPY public ./public
COPY --from=builder --chown=lecoffreuser leCoffre-front/node_modules ./node_modules
COPY --from=builder --chown=lecoffreuser leCoffre-front/.next ./.next
COPY --from=builder --chown=lecoffreuser leCoffre-front/next.config.js ./next.config.js
COPY --from=builder --chown=lecoffreuser leCoffre-front/package.json ./package.json
USER lecoffreuser USER lecoffreuser
CMD ["npm", "run", "dev"] CMD ["npm", "run", "start"]
EXPOSE 3000 EXPOSE 3000
# --- Build de production
FROM debian:bookworm-slim AS builder
WORKDIR /leCoffre-front
# Installation des dépendances de base
RUN apt-get update && apt-get upgrade -y && \
apt-get install -y --fix-missing \
ca-certificates curl jq git \
net-tools iputils-ping dnsutils \
netcat-openbsd telnet procps && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Installation de Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_19.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
COPY --from=deps /leCoffre-front/node_modules ./node_modules
COPY --from=deps /leCoffre-front/package.json ./package.json
COPY . .
# Arguments/variables d'environnement publics pour le build Next
ARG NEXT_PUBLIC_BACK_API_PROTOCOL
ARG NEXT_PUBLIC_BACK_API_HOST
ARG NEXT_PUBLIC_BACK_API_PORT
ARG NEXT_PUBLIC_BACK_API_ROOT_URL
ARG NEXT_PUBLIC_BACK_API_VERSION
ARG NEXT_PUBLIC_FRONT_APP_HOST
ARG NEXT_PUBLIC_FRONT_APP_PORT
ARG NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT
ARG NEXT_PUBLIC_IDNOT_CLIENT_ID
ARG NEXT_PUBLIC_IDNOT_BASE_URL
ARG NEXT_PUBLIC_IDNOT_REDIRECT_URI
ARG NEXT_PUBLIC_DOCAPOSTE_API_URL
ARG NEXT_PUBLIC_HOTJAR_SITE_ID
ARG NEXT_PUBLIC_HOTJAR_VERSION
ARG NEXT_PUBLIC_4NK_URL
ARG NEXT_PUBLIC_4NK_IFRAME_URL
ARG NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_DEFAULT_VALIDATOR_ID
ARG NEXT_PUBLIC_DEFAULT_STORAGE_URLS
ENV NEXT_PUBLIC_BACK_API_PROTOCOL=${NEXT_PUBLIC_BACK_API_PROTOCOL} \
NEXT_PUBLIC_BACK_API_HOST=${NEXT_PUBLIC_BACK_API_HOST} \
NEXT_PUBLIC_BACK_API_PORT=${NEXT_PUBLIC_BACK_API_PORT} \
NEXT_PUBLIC_BACK_API_ROOT_URL=${NEXT_PUBLIC_BACK_API_ROOT_URL} \
NEXT_PUBLIC_BACK_API_VERSION=${NEXT_PUBLIC_BACK_API_VERSION} \
NEXT_PUBLIC_FRONT_APP_HOST=${NEXT_PUBLIC_FRONT_APP_HOST} \
NEXT_PUBLIC_FRONT_APP_PORT=${NEXT_PUBLIC_FRONT_APP_PORT} \
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT=${NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT} \
NEXT_PUBLIC_IDNOT_CLIENT_ID=${NEXT_PUBLIC_IDNOT_CLIENT_ID} \
NEXT_PUBLIC_IDNOT_BASE_URL=${NEXT_PUBLIC_IDNOT_BASE_URL} \
NEXT_PUBLIC_IDNOT_REDIRECT_URI=${NEXT_PUBLIC_IDNOT_REDIRECT_URI} \
NEXT_PUBLIC_DOCAPOSTE_API_URL=${NEXT_PUBLIC_DOCAPOSTE_API_URL} \
NEXT_PUBLIC_HOTJAR_SITE_ID=${NEXT_PUBLIC_HOTJAR_SITE_ID} \
NEXT_PUBLIC_HOTJAR_VERSION=${NEXT_PUBLIC_HOTJAR_VERSION} \
NEXT_PUBLIC_4NK_URL=${NEXT_PUBLIC_4NK_URL} \
NEXT_PUBLIC_4NK_IFRAME_URL=${NEXT_PUBLIC_4NK_IFRAME_URL} \
NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL} \
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID=${NEXT_PUBLIC_DEFAULT_VALIDATOR_ID} \
NEXT_PUBLIC_DEFAULT_STORAGE_URLS=${NEXT_PUBLIC_DEFAULT_STORAGE_URLS}
RUN --mount=type=cache,target=/leCoffre-front/.next/cache npm run build
# --- Image d'exécution "int-dev"
FROM debian:bookworm-slim AS int-dev
WORKDIR /leCoffre-front
# Installation des dépendances de base
RUN apt-get update && apt-get upgrade -y && \
apt-get install -y --fix-missing \
ca-certificates curl jq git \
net-tools iputils-ping dnsutils \
netcat-openbsd telnet procps && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Installation de Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_19.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Re-déclarer les ARG pour l'étape runtime et les exposer en ENV
ARG NEXT_PUBLIC_BACK_API_PROTOCOL
ARG NEXT_PUBLIC_BACK_API_HOST
ARG NEXT_PUBLIC_BACK_API_PORT
ARG NEXT_PUBLIC_BACK_API_ROOT_URL
ARG NEXT_PUBLIC_BACK_API_VERSION
ARG NEXT_PUBLIC_FRONT_APP_HOST
ARG NEXT_PUBLIC_FRONT_APP_PORT
ARG NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT
ARG NEXT_PUBLIC_IDNOT_CLIENT_ID
ARG NEXT_PUBLIC_IDNOT_BASE_URL
ARG NEXT_PUBLIC_IDNOT_REDIRECT_URI
ARG NEXT_PUBLIC_DOCAPOSTE_API_URL
ARG NEXT_PUBLIC_HOTJAR_SITE_ID
ARG NEXT_PUBLIC_HOTJAR_VERSION
ARG NEXT_PUBLIC_4NK_URL
ARG NEXT_PUBLIC_4NK_IFRAME_URL
ARG NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_DEFAULT_VALIDATOR_ID
ARG NEXT_PUBLIC_DEFAULT_STORAGE_URLS
ENV NODE_ENV=production \
PORT=3000 \
NEXT_PUBLIC_BACK_API_PROTOCOL=${NEXT_PUBLIC_BACK_API_PROTOCOL} \
NEXT_PUBLIC_BACK_API_HOST=${NEXT_PUBLIC_BACK_API_HOST} \
NEXT_PUBLIC_BACK_API_PORT=${NEXT_PUBLIC_BACK_API_PORT} \
NEXT_PUBLIC_BACK_API_ROOT_URL=${NEXT_PUBLIC_BACK_API_ROOT_URL} \
NEXT_PUBLIC_BACK_API_VERSION=${NEXT_PUBLIC_BACK_API_VERSION} \
NEXT_PUBLIC_FRONT_APP_HOST=${NEXT_PUBLIC_FRONT_APP_HOST} \
NEXT_PUBLIC_FRONT_APP_PORT=${NEXT_PUBLIC_FRONT_APP_PORT} \
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT=${NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT} \
NEXT_PUBLIC_IDNOT_CLIENT_ID=${NEXT_PUBLIC_IDNOT_CLIENT_ID} \
NEXT_PUBLIC_IDNOT_BASE_URL=${NEXT_PUBLIC_IDNOT_BASE_URL} \
NEXT_PUBLIC_IDNOT_REDIRECT_URI=${NEXT_PUBLIC_IDNOT_REDIRECT_URI} \
NEXT_PUBLIC_DOCAPOSTE_API_URL=${NEXT_PUBLIC_DOCAPOSTE_API_URL} \
NEXT_PUBLIC_HOTJAR_SITE_ID=${NEXT_PUBLIC_HOTJAR_SITE_ID} \
NEXT_PUBLIC_HOTJAR_VERSION=${NEXT_PUBLIC_HOTJAR_VERSION} \
NEXT_PUBLIC_4NK_URL=${NEXT_PUBLIC_4NK_URL} \
NEXT_PUBLIC_4NK_IFRAME_URL=${NEXT_PUBLIC_4NK_IFRAME_URL} \
NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL} \
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID=${NEXT_PUBLIC_DEFAULT_VALIDATOR_ID} \
NEXT_PUBLIC_DEFAULT_STORAGE_URLS=${NEXT_PUBLIC_DEFAULT_STORAGE_URLS}
# Next.js standalone runtime (output: 'standalone')
COPY --from=builder /leCoffre-front/.next/standalone ./
COPY --from=builder /leCoffre-front/.next/static ./.next/static
COPY --from=builder /leCoffre-front/public ./public
# Création de l'utilisateur non-root
RUN useradd -m -u 1000 lecoffreuser && \
mkdir -p /leCoffre-front && chown -R lecoffreuser:lecoffreuser /leCoffre-front
USER lecoffreuser
EXPOSE 3000
CMD ["node", "server.js"]

44
Dockerfile.front Normal file
View File

@ -0,0 +1,44 @@
# Install dependencies only when needed
FROM node:19-alpine AS deps
WORKDIR leCoffre-front
COPY package.json ./
RUN apk update && apk add openssh-client git
COPY id_rsa /root/.ssh/id_rsa
RUN chmod 600 ~/.ssh/id_rsa
RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa
RUN ssh-keyscan github.com smart-chain-fr/leCoffre-resources.git >> /root/.ssh/known_hosts
RUN npm install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:19-alpine AS builder
WORKDIR leCoffre-front
COPY --from=deps leCoffre-front/node_modules ./node_modules
COPY --from=deps leCoffre-front/package.json package.json
COPY tsconfig.json tsconfig.json
COPY src src
RUN npm run build
# Production image, copy all the files and run next
FROM node:19-alpine AS production
WORKDIR leCoffre-front
RUN adduser -D lecoffreuser --uid 10000 && chown -R lecoffreuser .
COPY public ./public
COPY --from=builder --chown=lecoffreuser leCoffre-front/node_modules ./node_modules
COPY --from=builder --chown=lecoffreuser leCoffre-front/.next ./.next
COPY --from=builder --chown=lecoffreuser leCoffre-front/package.json ./package.json
USER lecoffreuser
CMD ["npm", "run", "start"]
EXPOSE 3000

View File

@ -1,301 +0,0 @@
# Analyse des Dépendances - lecoffre-front
## Vue d'ensemble
Ce document analyse les dépendances du projet lecoffre-front, leurs versions, leur utilisation et les recommandations de mise à jour.
## Dépendances principales
### Framework et Runtime
#### Next.js
- **Version actuelle**: 14.2.3
- **Type**: Framework React
- **Utilisation**: Framework principal de l'application
- **Statut**: Version récente et stable
- **Recommandation**: Maintenir la version actuelle
#### React
- **Version actuelle**: 18.2.0
- **Type**: Bibliothèque UI
- **Utilisation**: Bibliothèque de base pour l'interface utilisateur
- **Statut**: Version stable LTS
- **Recommandation**: Maintenir la version actuelle
#### React DOM
- **Version actuelle**: 18.2.0
- **Type**: Rendu DOM pour React
- **Utilisation**: Rendu des composants React dans le DOM
- **Statut**: Version stable LTS
- **Recommandation**: Maintenir la version actuelle
### Interface utilisateur
#### Material-UI (MUI)
- **Version actuelle**: 5.11.13
- **Type**: Bibliothèque de composants UI
- **Utilisation**: Composants d'interface utilisateur
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
#### Emotion
- **Versions**:
- @emotion/react: ^11.10.6
- @emotion/styled: ^11.10.6
- **Type**: Bibliothèque CSS-in-JS
- **Utilisation**: Styling des composants
- **Statut**: Versions récentes
- **Recommandation**: Maintenir les versions actuelles
#### Heroicons
- **Version actuelle**: ^2.1.3
- **Type**: Icônes SVG
- **Utilisation**: Icônes dans l'interface
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
### TypeScript et outils de développement
#### TypeScript
- **Version actuelle**: 4.9.5
- **Type**: Langage de programmation
- **Utilisation**: Typage statique
- **Statut**: Version stable mais ancienne
- **Recommandation**: ⚠️ Mettre à jour vers TypeScript 5.x
#### ESLint
- **Version actuelle**: 8.36.0
- **Type**: Linter JavaScript/TypeScript
- **Utilisation**: Analyse de code
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
#### Prettier
- **Version actuelle**: ^2.8.7
- **Type**: Formateur de code
- **Utilisation**: Formatage automatique
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
### Utilitaires et bibliothèques
#### Class Validator
- **Version actuelle**: ^0.14.0
- **Type**: Validation de classes
- **Utilisation**: Validation des données
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### Classnames
- **Version actuelle**: ^2.3.2
- **Type**: Utilitaire pour les noms de classes
- **Utilisation**: Gestion conditionnelle des classes CSS
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### UUIDv4
- **Version actuelle**: ^6.2.13
- **Type**: Générateur d'UUID
- **Utilisation**: Génération d'identifiants uniques
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
### Gestion de fichiers
#### File Saver
- **Version actuelle**: ^2.0.5
- **Type**: Sauvegarde de fichiers
- **Utilisation**: Téléchargement de fichiers
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### JSZip
- **Version actuelle**: ^3.10.1
- **Type**: Manipulation d'archives ZIP
- **Utilisation**: Création d'archives
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### PDF-lib
- **Version actuelle**: ^1.17.1
- **Type**: Manipulation de PDF
- **Utilisation**: Génération et modification de PDF
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
### Intégrations et services
#### le-coffre-resources
- **Version actuelle**: v2.167
- **Type**: Ressources partagées
- **Utilisation**: Ressources communes du projet
- **Source**: git+ssh://git@git.4nkweb.com/4nk/lecoffre-ressources.git
- **Statut**: Version spécifique
- **Recommandation**: Maintenir la version actuelle
#### React GTM Module
- **Version actuelle**: ^2.0.11
- **Type**: Intégration Google Tag Manager
- **Utilisation**: Analytics et tracking
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### React Toastify
- **Version actuelle**: ^9.1.3
- **Type**: Notifications toast
- **Utilisation**: Affichage de notifications
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### React Select
- **Version actuelle**: ^5.7.2
- **Type**: Composant de sélection
- **Utilisation**: Listes déroulantes avancées
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
### Sécurité et authentification
#### JWT Decode
- **Version actuelle**: ^3.1.2
- **Type**: Décodage de JWT
- **Utilisation**: Traitement des tokens JWT
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### Crypto Random String
- **Version actuelle**: ^5.0.0
- **Type**: Génération de chaînes aléatoires
- **Utilisation**: Génération de tokens sécurisés
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
### Styling et assets
#### SASS
- **Version actuelle**: ^1.59.2
- **Type**: Préprocesseur CSS
- **Utilisation**: Styles avancés
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### Sharp
- **Version actuelle**: ^0.32.1
- **Type**: Optimisation d'images
- **Utilisation**: Traitement d'images
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
## Dépendances de développement
### Types TypeScript
#### @types/node
- **Version actuelle**: 18.15.1
- **Type**: Types pour Node.js
- **Utilisation**: Typage Node.js
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
#### @types/react
- **Version actuelle**: 18.0.28
- **Type**: Types pour React
- **Utilisation**: Typage React
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
#### @types/react-dom
- **Version actuelle**: 18.0.11
- **Type**: Types pour React DOM
- **Utilisation**: Typage React DOM
- **Statut**: Version stable
- **Recommandation**: Maintenir la version actuelle
#### @types/file-saver
- **Version actuelle**: ^2.0.7
- **Type**: Types pour file-saver
- **Utilisation**: Typage file-saver
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
#### @types/react-gtm-module
- **Version actuelle**: ^2.0.3
- **Type**: Types pour react-gtm-module
- **Utilisation**: Typage react-gtm-module
- **Statut**: Version récente
- **Recommandation**: Maintenir la version actuelle
## Analyse de sécurité
### Dépendances avec des vulnérabilités potentielles
#### TypeScript 4.9.5
- **Risque**: Version ancienne
- **Impact**: Fonctionnalités manquantes, corrections de bugs
- **Recommandation**: Mettre à jour vers TypeScript 5.x
### Dépendances sécurisées
Toutes les autres dépendances sont à jour et ne présentent pas de vulnérabilités connues.
## Recommandations de mise à jour
### Priorité haute
1. **TypeScript**: Mettre à jour vers la version 5.x
```bash
npm install typescript@latest
```
### Priorité moyenne
1. **Vérification régulière**: Utiliser `npm audit` pour détecter les vulnérabilités
2. **Mise à jour des dépendances**: Utiliser `npm update` régulièrement
### Priorité basse
1. **Dépendances optionnelles**: Évaluer l'utilisation de certaines dépendances
2. **Optimisation**: Analyser les dépendances non utilisées
## Scripts de maintenance
### Audit de sécurité
```bash
npm audit
npm audit fix
```
### Mise à jour des dépendances
```bash
npm update
npm outdated
```
### Vérification des dépendances non utilisées
```bash
npx depcheck
```
## Monitoring des dépendances
### Outils recommandés
1. **Dependabot**: Mise à jour automatique des dépendances
2. **Snyk**: Détection des vulnérabilités
3. **npm audit**: Audit de sécurité intégré
### Processus de mise à jour
1. **Test**: Tester les mises à jour en environnement de développement
2. **Validation**: Valider le fonctionnement de l'application
3. **Déploiement**: Déployer en staging puis en production
## Conclusion
Le projet lecoffre-front utilise des dépendances modernes et bien maintenues. La seule recommandation majeure est la mise à jour de TypeScript vers la version 5.x pour bénéficier des dernières fonctionnalités et corrections de bugs.
Les dépendances sont globalement sécurisées et à jour, ce qui garantit la stabilité et la sécurité de l'application.
---
*Analyse effectuée le $(date) - Dépendances lecoffre-front*

View File

@ -1,228 +0,0 @@
# Analyse du Repository lecoffre-front
## Vue d'ensemble
Le projet **lecoffre-front** est une application Next.js développée en TypeScript pour la gestion de dossiers notariaux. Il s'agit d'une application frontend qui communique avec une API backend et intègre plusieurs services externes.
## Structure du Repository
### Architecture générale
```
lecoffre-front/
├── src/ # Code source principal
│ ├── common/ # Code partagé
│ │ └── Api/ # Services API communs
│ ├── front/ # Code spécifique au frontend
│ │ ├── Api/ # Services API frontend
│ │ ├── Components/ # Composants React
│ │ ├── Config/ # Configuration par environnement
│ │ ├── Hooks/ # Hooks React personnalisés
│ │ ├── Services/ # Services métier
│ │ ├── Stores/ # Gestion d'état
│ │ ├── Themes/ # Thèmes et styles
│ │ └── Utils/ # Utilitaires
│ ├── pages/ # Pages Next.js
│ └── sdk/ # SDK et intégrations
├── docs/ # Documentation
├── tests/ # Tests
├── public/ # Assets statiques
├── Dockerfile # Configuration Docker
├── next.config.js # Configuration Next.js
├── package.json # Dépendances et scripts
└── temp.yaml # Configuration Kubernetes temporaire
```
### Technologies utilisées
- **Framework**: Next.js 14.2.3
- **Language**: TypeScript 4.9.5
- **UI**: Material-UI (MUI) 5.11.13
- **Styling**: Emotion, SASS
- **État**: Context API / Hooks
- **Build**: Docker multi-stage
- **Déploiement**: Kubernetes
## Variables d'Environnement
### Variables principales
Le projet utilise un système de variables d'environnement préfixées par `NEXT_PUBLIC_` pour la configuration runtime.
#### Configuration API Backend
```bash
NEXT_PUBLIC_BACK_API_PROTOCOL=https://
NEXT_PUBLIC_BACK_API_HOST=api.example.com
NEXT_PUBLIC_BACK_API_PORT=443
NEXT_PUBLIC_BACK_API_ROOT_URL=/api
NEXT_PUBLIC_BACK_API_VERSION=v1
```
#### Configuration Frontend
```bash
NEXT_PUBLIC_FRONT_APP_HOST=https://app.example.com
NEXT_PUBLIC_FRONT_APP_PORT=443
```
#### Intégrations externes
```bash
# IDNot (authentification)
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT=/oauth/authorize
NEXT_PUBLIC_IDNOT_CLIENT_ID=client_id
NEXT_PUBLIC_IDNOT_BASE_URL=https://idnot.example.com
NEXT_PUBLIC_IDNOT_REDIRECT_URI=https://app.example.com/callback
# Docaposte
NEXT_PUBLIC_DOCAPOSTE_API_URL=https://api.docaposte.com
# 4NK (services blockchain)
NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com
NEXT_PUBLIC_4NK_IFRAME_URL=https://dev4.4nkweb.com
# Hotjar (analytics)
NEXT_PUBLIC_HOTJAR_SITE_ID=123456
NEXT_PUBLIC_HOTJAR_VERSION=6
# Configuration système
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID=862406317a35064537ac959cb5d8bbdf4f849283b63db3ffa9904de2b3427c43:0
NEXT_PUBLIC_DEFAULT_STORAGE_URLS=https://dev3.4nkweb.com/storage
```
### Gestion des environnements
Le projet supporte 4 environnements via la variable `NEXTJS_APP_ENV_NAME`:
- `development` (par défaut)
- `staging`
- `preprod`
- `production`
Chaque environnement a sa configuration dans `src/front/Config/Module/`:
- `development.json`
- `staging.json`
- `preprod.json`
- `production.json`
## Configuration Docker
### Multi-stage build
Le Dockerfile utilise un build multi-stage avec 3 cibles:
1. **deps**: Installation des dépendances avec support SSH pour git.4nkweb.com
2. **development**: Image de développement avec hot-reload
3. **builder**: Build de production
4. **int-dev**: Image de production finale
### Variables d'environnement Docker
Toutes les variables `NEXT_PUBLIC_*` sont passées comme arguments de build et variables d'environnement runtime.
### Sécurité
- Utilisateur non-root (`lecoffreuser` avec UID 10000)
- Support SSH agent pour cloner les dépendances privées
- Cache npm pour optimiser les builds
## Configuration Kubernetes
### Déploiement
Le fichier `temp.yaml` contient la configuration Kubernetes complète:
- **Namespace**: `lecoffre`
- **Service**: `lecoffre-front-svc` (port 80 → 3000)
- **Deployment**: `lecoffre-front` avec 1 replica
- **Ingress**: `app.stg.lecoffre.smart-chain.fr` avec SSL
### Gestion des secrets
- **Vault**: Intégration HashiCorp Vault pour les secrets
- **External Secrets**: Gestion automatique des secrets Docker
- **Service Account**: `lecoffre-front-sa` avec permissions appropriées
### Ressources
```yaml
resources:
limits:
memory: 2Gi
requests:
cpu: 200m
memory: 1Gi
```
## Dépendances principales
### Production
- **Next.js**: 14.2.3 (framework React)
- **React**: 18.2.0
- **Material-UI**: 5.11.13 (composants UI)
- **TypeScript**: 4.9.5
- **le-coffre-resources**: v2.167 (ressources partagées)
### Développement
- **ESLint**: 8.36.0
- **Prettier**: 2.8.7
- **SASS**: 1.59.2
### Intégrations
- **Google Tag Manager**: Analytics
- **Hotjar**: Heatmaps et enregistrements
- **Docaposte**: Services postaux
- **4NK**: Services blockchain
## Architecture de l'application
### Gestion d'état
- **FrontendVariables**: Singleton pour les variables d'environnement
- **Module**: Configuration par environnement
- **Context API**: Gestion d'état React
### Communication API
- **DatabaseService**: Service générique pour les appels API
- **BaseApiService**: Service de base pour les API
- **Construction dynamique d'URLs**: Basée sur les variables d'environnement
### SDK et intégrations
- **Iframe**: Communication avec les services 4NK
- **MessageBus**: Bus de messages pour la communication inter-iframe
- **User**: Gestion de l'authentification utilisateur
- **AuthModal**: Modal d'authentification
## Points d'attention
### Sécurité
- Variables d'environnement exposées côté client (préfixe `NEXT_PUBLIC_`)
- Authentification via IDNot
- Communication sécurisée avec les services 4NK
### Performance
- Build standalone Next.js
- Cache npm dans Docker
- Optimisation des images avec Sharp
### Déploiement
- Support multi-environnement
- Intégration Vault pour les secrets
- Monitoring avec Hotjar et GTM
## Recommandations
1. **Documentation**: Maintenir la documentation des variables d'environnement
2. **Tests**: Étendre la couverture de tests
3. **Monitoring**: Ajouter des métriques de performance
4. **Sécurité**: Auditer régulièrement les dépendances
5. **CI/CD**: Automatiser les déploiements avec validation des variables
## Version actuelle
- **Application**: v0.1.6 (package.json)
- **Frontend**: v2.5.1 (version.json)
- **Docker**: v0.1.9 (temp.yaml)
---
*Analyse effectuée le $(date) - Repository lecoffre-front*

View File

@ -1,50 +0,0 @@
## Analyse détaillée
### Périmètre
Front Next.js `lecoffre-front` (Next 14, TypeScript), build multiétapes et image `int-dev` runtime.
### Stack
- **Framework**: Next.js 14 (React 18), TypeScript 4.9.5
- **UI**: MUI, Emotion, Heroicons
- **Outillage**: ESLint (8.36), Prettier
- **Ressources externes**: `le-coffre-resources` via SSH Gitea (`#v2.167`)
### Build et exécution
- Scripts: `dev`, `build` (telemetry off, `--no-lint`), `start`, `lint`, `format`.
- `next.config.js`: `output: 'standalone'`, `basePath: '/lecoffre'`, `ignoreBuildErrors: true`.
- Docker multiétapes: `deps` (npm ci), `development` (npm run dev), `builder` (npm run build), `int-dev` (runtime node:19alpine, `server.js`).
### Variables denvironnement
Variables NEXT_PUBLIC nombreuses (API back, IDNot, Docaposte, 4NK URLs, defaults). Exposées en `env`, `publicRuntimeConfig`, `serverRuntimeConfig` et redéclarées en Docker (`ARG``ENV`).
### Ports et réseau
- Port 3000 interne; exposé 3004:3000 dans `lecoffre_node`.
### Dépendances clés
- `next@^14.2.3`, `react@18.2.0`, `sharp@^0.32.1` (build imageprocessing Alpine), `jszip`, `jwt-decode`, `react-select`, `react-toastify`.
### Risques et points dattention
- `ignoreBuildErrors: true` masque les erreurs TS. Risque de dérive de type.
- `--no-lint` en build désactive ESLint. Manque de garde qualité en CI.
- Node 19 sur Alpine: fin de support. Préférer LTS (20/22).
- Dépendance Git SSH privée (`lecoffre-ressources`): exige agent SSH BuildKit; documenter clé et politiques.
### Actions proposées
- Rétablir le lint en build (ou CI) et supprimer `ignoreBuildErrors` si possible.
- Monter vers Node LTS (20alpine) et tester `sharp`.
- Documenter toutes les variables NEXT_PUBLIC et fournir `.env.example`.
- Mettre en place codesplitting (React.lazy/Suspense) et centraliser létat (Context/Redux) selon les règles projet.

View File

@ -1,22 +0,0 @@
# Architecture - LeCoffre Front
## Composants
- Next.js (branche `int-dev`).
- Intègre `ihm_client` via iframe.
## Dépendances
- Backend `lecoffre-back-mini` (`NEXT_PUBLIC_BACK_*`).
- Redirections IdNot (local.4nkweb.com:3000).
## Réseau et ports
- Servi via Nginx: `https://dev4.4nkweb.com/lecoffre/`.
## Variables denvironnement (centralisées)
- `NEXT_PUBLIC_*` depuis `lecoffre_node/.env.master`.
## Monitoring
- Logs Promtail → Loki.
- Dashboard Grafana: Frontend Services.
## Notes
- Pas de `.env` local, utilisation variables runtime.

View File

@ -1,38 +0,0 @@
# Corrections Appliquées - LeCoffre Front
## Date: 20 Septembre 2025
### 🔧 Corrections Majeures
#### 1. Problème de Healthcheck
**Problème:** Le healthcheck échouait car `curl` n'était pas installé et Next.js écoutait sur l'IP du conteneur.
**Solution:**
- Changement du healthcheck pour vérifier le processus `next-server`
- Healthcheck: `ps aux | grep -v grep | grep next-server`
- Correction de l'entrypoint pour `npm start`
**Fichiers modifiés:**
- `docker-compose.yml` - Healthcheck corrigé
- Configuration - Entrypoint optimisé
#### 2. Installation des Outils
**Ajouté dans le Dockerfile:**
- `curl`, `git`, `wget`, `jq`, `telnet`, `npm`, `wscat`
- Outils de diagnostic et de connectivité
#### 3. Configuration Next.js
- Port: 3000 (mappé sur 3004)
- Processus: `next-server`
- Healthcheck: Vérification du processus
### 📊 État Actuel
- **Statut:** ✅ Healthy
- **Processus:** next-server en cours d'exécution
- **Port:** 3000 accessible sur 172.20.0.11
- **URL:** https://dev4.4nkweb.com/lecoffre
### 🔄 Prochaines Étapes
- Tests de connectivité frontend
- Monitoring des performances
- Optimisations supplémentaires

View File

@ -1,20 +0,0 @@
# Déploiement - LeCoffre Front
## Préparation
- Branche `int-dev`.
- `NEXT_PUBLIC_*` dans `lecoffre_node/.env.master`.
## Déploiement (orchestrateur)
```bash
cd /home/debian/4NK_env/lecoffre_node
./scripts/start.sh | cat
./scripts/validate-deployment.sh | cat
```
## Vérifications
- `https://dev4.4nkweb.com/lecoffre/` s'affiche.
- Iframe `ihm_client` s'ouvre.
## Règles
- Pas de compose direct.
- Push `int-dev` sans CI pour docs.

View File

@ -1,30 +0,0 @@
## Résumé des environnements (front)
### Contexte
- **Hôte iframe**: `https://dev4.4nkweb.com`
- **Site principal**: `https://dev4.4nkweb.com/lecoffre` (Next.js `basePath: '/lecoffre'`)
- **Signer utilisé**: `https://dev3.4nkweb.com`
### Variables `NEXT_PUBLIC_*` à aligner
- `NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com`
- `NEXT_PUBLIC_4NK_IFRAME_URL=https://dev4.4nkweb.com`
- `NEXT_PUBLIC_API_URL` → URL publique de lAPI back (chemin stable, CORS OK)
- `NEXT_PUBLIC_BACK_API_PROTOCOL=https`
- `NEXT_PUBLIC_BACK_API_HOST=dev4.4nkweb.com`
- `NEXT_PUBLIC_BACK_API_PORT` (vide en prod 443)
- `NEXT_PUBLIC_BACK_API_ROOT_URL` et `NEXT_PUBLIC_BACK_API_VERSION` si composées côté front
- `NEXT_PUBLIC_IDNOT_*`, `NEXT_PUBLIC_DOCAPOSTE_API_URL` selon intégrations
- `NEXT_PUBLIC_DEFAULT_VALIDATOR_ID`, `NEXT_PUBLIC_DEFAULT_STORAGE_URLS` selon besoins
### Points dattention
- Vérifier que toutes les URLs tiennent compte du `basePath` `/lecoffre`.
- Le service de signature est externalisé sur `dev3.4nkweb.com`.

View File

@ -1,6 +0,0 @@
# Description des Flux - LeCoffre Front
## Flux principaux
1. Auth notaire: Front → IdNot → Front (callback).
2. Intégration IHM: Front → iframe → IHM.
3. API: Front → Back (REST).

View File

@ -1,15 +0,0 @@
# Description Fonctionnelle - LeCoffre Front
## Objectif
Fournir linterface principale (Next.js) orchestrant lUX, incluant liframe IHM Client.
## Parcours clés
- Authentification notaire (redirections IdNot).
- Navigation dossiers et intégration iframe IHM.
- Appels API backend, feedback utilisateur et gestion derreurs.
## Rôles
- Notaire, utilisateur interne.
## Résultats attendus
- UX fluide, chargements différés (code splitting), gestion session robuste.

View File

@ -1,26 +0,0 @@
# Installation - LeCoffre Front
## Prérequis
- Dépôts sous `/home/debian/4NK_env` (branche `int-dev`).
- Docker/Compose.
- Variables `NEXT_PUBLIC_*` dans `lecoffre_node/.env.master`.
## Configuration
- Pas de `.env` local.
- Vérifier URLs backend et iframe IHM.
## Démarrage (orchestrateur)
```bash
cd /home/debian/4NK_env/lecoffre_node
./scripts/start.sh | cat
```
## Accès
- `https://dev4.4nkweb.com/lecoffre/`
## Vérifications
- Ouverture iframe IHM.
- Appels API vers `/api/` OK.
## Notes
- CI via tag `int-dev`.

View File

@ -1,6 +0,0 @@
# Qualité Logicielle - LeCoffre Front
- Lint/format: respecter règles Next/TS.
- Tests: E2E parcours IdNot et iframe IHM.
- Performance: audit Lighthouse, lazy loading.
- Observabilité: logs client minimaux, erreurs capturées.

View File

@ -1,159 +0,0 @@
# Résumé de l'Analyse - lecoffre-front
## Vue d'ensemble
L'analyse complète du repository **lecoffre-front** a été effectuée le $(date). Ce document présente un résumé des principales découvertes et recommandations.
## Structure du projet
### Type d'application
- **Framework**: Next.js 14.2.3 avec TypeScript 4.9.5
- **Architecture**: Application frontend SPA avec intégrations multiples
- **Déploiement**: Docker multi-stage + Kubernetes
- **Version actuelle**: v0.1.6 (package.json) / v2.5.1 (frontend)
### Architecture technique
```
Frontend (Next.js) → API Backend → Services externes
↓ ↓ ↓
Material-UI Base de données 4NK/IDNot/Docaposte
```
## Variables d'environnement
### Configuration identifiée
- **21 variables d'environnement** configurées
- **4 environnements** supportés (dev/staging/preprod/production)
- **Gestion centralisée** via Next.js config et FrontendVariables
### Variables critiques
```bash
# API Backend
NEXT_PUBLIC_BACK_API_PROTOCOL=https://
NEXT_PUBLIC_BACK_API_HOST=api.example.com
NEXT_PUBLIC_BACK_API_PORT=443
# Intégrations
NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com
NEXT_PUBLIC_IDNOT_BASE_URL=https://idnot.example.com
NEXT_PUBLIC_DOCAPOSTE_API_URL=https://api.docaposte.com
```
## Déploiement et infrastructure
### Docker
- **Multi-stage build** avec 4 cibles (deps/development/builder/int-dev)
- **Sécurité**: Utilisateur non-root, support SSH agent
- **Optimisation**: Cache npm, build standalone Next.js
### Kubernetes
- **Namespace**: lecoffre
- **Ressources**: 1Gi RAM (request) / 2Gi RAM (limit)
- **Sécurité**: Vault Agent pour injection des secrets
- **Ingress**: TLS avec cert-manager
### CI/CD
- **Registre**: git.4nkweb.com (Docker registry)
- **Tagging**: Contrôlé par message de commit
- **Secrets**: Gestion via Vault + External Secrets
## Dépendances
### État général
- **46 dépendances** principales
- **5 dépendances** de développement
- **Statut**: Majoritairement à jour et sécurisées
### Recommandations
- ✅ **Maintenir**: Next.js 14.2.3, React 18.2.0, MUI 5.11.13
- ⚠️ **Mettre à jour**: TypeScript 4.9.5 → 5.x
- ✅ **Sécurisé**: Toutes les autres dépendances
## Points forts identifiés
### Architecture
- ✅ Structure modulaire bien organisée
- ✅ Séparation claire des responsabilités
- ✅ Configuration multi-environnement
- ✅ Intégration Docker/Kubernetes robuste
### Sécurité
- ✅ Variables d'environnement externalisées
- ✅ Gestion des secrets via Vault
- ✅ Utilisateur non-root dans Docker
- ✅ Support SSH agent pour dépendances privées
### Développement
- ✅ TypeScript pour le typage statique
- ✅ ESLint + Prettier pour la qualité du code
- ✅ Tests organisés dans le dossier tests/
- ✅ Documentation complète
## Points d'attention
### Améliorations recommandées
1. **TypeScript**
- Mettre à jour vers la version 5.x
- Bénéficier des dernières fonctionnalités
2. **Monitoring**
- Ajouter des métriques de performance
- Monitoring des erreurs en production
3. **Tests**
- Étendre la couverture de tests
- Tests d'intégration avec les services externes
4. **Documentation**
- Maintenir la documentation des variables d'environnement
- Documenter les processus de déploiement
### Risques identifiés
1. **Dépendances privées**
- Dépendance à git.4nkweb.com pour le-coffre-resources
- Nécessite un accès SSH configuré
2. **Variables d'environnement**
- Variables NEXT_PUBLIC_* exposées côté client
- Nécessite une validation stricte des valeurs
3. **Intégrations externes**
- Dépendance à plusieurs services externes
- Nécessite une gestion des pannes
## Recommandations prioritaires
### Court terme (1-2 semaines)
1. Mettre à jour TypeScript vers la version 5.x
2. Effectuer un audit de sécurité complet (`npm audit`)
3. Vérifier la configuration des variables d'environnement
### Moyen terme (1-2 mois)
1. Étendre la couverture de tests
2. Ajouter des métriques de monitoring
3. Documenter les processus de déploiement
### Long terme (3-6 mois)
1. Évaluer l'optimisation des performances
2. Considérer l'ajout de tests d'intégration
3. Planifier les mises à jour des dépendances
## Conclusion
Le projet **lecoffre-front** présente une architecture solide et bien structurée. Les technologies utilisées sont modernes et appropriées pour le contexte. La configuration Docker/Kubernetes est robuste et sécurisée.
Les principales améliorations concernent la mise à jour de TypeScript et l'extension des tests. Le projet est globalement en bon état et prêt pour la production.
## Documentation créée
1. **ANALYSE-REPOSITORY.md**: Analyse complète du repository
2. **VARIABLES-ENVIRONNEMENT.md**: Documentation détaillée des variables d'environnement
3. **ANALYSE-DEPENDANCES.md**: Analyse des dépendances et recommandations
4. **RESUME-ANALYSE.md**: Ce résumé exécutif
---
*Analyse effectuée le $(date) - Repository lecoffre-front*
*Analyste: Assistant IA Claude*

View File

@ -1,6 +0,0 @@
# Sécurité - LeCoffre Front
- Aucune donnée sensible côté client.
- Variables exposées en `NEXT_PUBLIC_*` contrôlées.
- CSP/headers via Nginx.
- Sanitation des entrées utilisateur.

View File

@ -1,19 +0,0 @@
# Description Technique - LeCoffre Front
## Tech stack
- Next.js, Node.js 19.
## Configuration
- Variables `NEXT_PUBLIC_*` via `lecoffre_node/.env.master`.
## Interfaces
- Iframe vers `ihm_client`.
- REST vers `/api/`.
## Sécurité
- Aucun secret côté client.
- Headers via Nginx.
## Observabilité
- Logs Promtail → Loki.
- Dashboards Grafana.

View File

@ -1,6 +0,0 @@
# TODO - LeCoffre Front
- Vérifier URLs backend et iframe IHM.
- Tester parcours IdNot.
- Valider variables `NEXT_PUBLIC_*`.
- Vérifier dashboards Grafana Frontend.

View File

@ -1,336 +0,0 @@
# Variables d'Environnement - lecoffre-front
## Vue d'ensemble
Ce document détaille toutes les variables d'environnement utilisées dans l'application lecoffre-front, leur utilisation et leur configuration.
## Variables d'environnement supportées
### 1. Configuration API Backend
#### `NEXT_PUBLIC_BACK_API_PROTOCOL`
- **Description**: Protocole utilisé pour communiquer avec l'API backend
- **Valeurs possibles**: `https://`, `http://`
- **Exemple**: `https://`
- **Utilisation**: Construction des URLs d'API
#### `NEXT_PUBLIC_BACK_API_HOST`
- **Description**: Nom d'hôte de l'API backend
- **Exemple**: `api.lecoffre.com`, `dev4.4nkweb.com`
- **Utilisation**: Construction des URLs d'API
#### `NEXT_PUBLIC_BACK_API_PORT`
- **Description**: Port de l'API backend
- **Exemple**: `443`, `8080`, `3001`
- **Utilisation**: Construction des URLs d'API
- **Note**: Peut être vide pour les ports par défaut (80/443)
#### `NEXT_PUBLIC_BACK_API_ROOT_URL`
- **Description**: Chemin racine de l'API
- **Exemple**: `/api`, `/`
- **Utilisation**: Construction des URLs d'API
#### `NEXT_PUBLIC_BACK_API_VERSION`
- **Description**: Version de l'API
- **Exemple**: `v1`, `v2`
- **Utilisation**: Construction des URLs d'API
### 2. Configuration Frontend
#### `NEXT_PUBLIC_FRONT_APP_HOST`
- **Description**: URL de base de l'application frontend
- **Exemple**: `https://app.lecoffre.com`
- **Utilisation**: Redirections et liens internes
#### `NEXT_PUBLIC_FRONT_APP_PORT`
- **Description**: Port de l'application frontend
- **Exemple**: `443`, `3000`
- **Utilisation**: Construction des URLs frontend
### 3. Intégration IDNot (Authentification)
#### `NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT`
- **Description**: Point d'entrée pour l'autorisation OAuth
- **Exemple**: `/oauth/authorize`
- **Utilisation**: Flux d'authentification
#### `NEXT_PUBLIC_IDNOT_CLIENT_ID`
- **Description**: Identifiant client OAuth
- **Exemple**: `lecoffre-client-id`
- **Utilisation**: Authentification OAuth
#### `NEXT_PUBLIC_IDNOT_BASE_URL`
- **Description**: URL de base du service IDNot
- **Exemple**: `https://idnot.lecoffre.com`
- **Utilisation**: Authentification OAuth
#### `NEXT_PUBLIC_IDNOT_REDIRECT_URI`
- **Description**: URI de redirection après authentification
- **Exemple**: `https://app.lecoffre.com/callback`
- **Utilisation**: Flux d'authentification
### 4. Intégration Docaposte
#### `NEXT_PUBLIC_DOCAPOSTE_API_URL`
- **Description**: URL de l'API Docaposte
- **Exemple**: `https://api.docaposte.com`
- **Utilisation**: Services postaux
### 5. Intégration 4NK (Blockchain)
#### `NEXT_PUBLIC_4NK_URL`
- **Description**: URL de base des services 4NK
- **Exemple**: `https://dev4.4nkweb.com`
- **Utilisation**: Services blockchain et signature
#### `NEXT_PUBLIC_4NK_IFRAME_URL`
- **Description**: URL spécifique pour l'iframe 4NK
- **Exemple**: `https://dev4.4nkweb.com`
- **Utilisation**: Communication iframe
- **Note**: Peut être différente de `NEXT_PUBLIC_4NK_URL`
### 6. Analytics et Monitoring
#### `NEXT_PUBLIC_HOTJAR_SITE_ID`
- **Description**: Identifiant du site Hotjar
- **Exemple**: `123456`
- **Utilisation**: Analytics et heatmaps
#### `NEXT_PUBLIC_HOTJAR_VERSION`
- **Description**: Version de Hotjar
- **Exemple**: `6`
- **Utilisation**: Analytics et heatmaps
### 7. Configuration système
#### `NEXT_PUBLIC_API_URL`
- **Description**: URL générique de l'API
- **Exemple**: `https://api.lecoffre.com`
- **Utilisation**: Appels API génériques
#### `NEXT_PUBLIC_DEFAULT_VALIDATOR_ID`
- **Description**: Identifiant du validateur par défaut
- **Exemple**: `862406317a35064537ac959cb5d8bbdf4f849283b63db3ffa9904de2b3427c43:0`
- **Utilisation**: Validation des entités système
- **Valeur par défaut**: Définie dans `AppConstants.ts`
#### `NEXT_PUBLIC_DEFAULT_STORAGE_URLS`
- **Description**: URLs de stockage par défaut (séparées par des virgules)
- **Exemple**: `https://dev3.4nkweb.com/storage,https://backup.4nkweb.com/storage`
- **Utilisation**: Stockage des données
- **Valeur par défaut**: `https://dev3.4nkweb.com/storage`
### 8. Variables d'environnement système
#### `NEXTJS_APP_ENV_NAME`
- **Description**: Nom de l'environnement
- **Valeurs possibles**: `development`, `staging`, `preprod`, `production`
- **Utilisation**: Sélection de la configuration par environnement
- **Valeur par défaut**: `development`
#### `NODE_ENV`
- **Description**: Environnement Node.js
- **Valeurs possibles**: `development`, `production`
- **Utilisation**: Configuration Next.js
## Configuration par environnement
### Développement
```bash
NEXTJS_APP_ENV_NAME=development
NODE_ENV=development
NEXT_PUBLIC_BACK_API_PROTOCOL=http://
NEXT_PUBLIC_BACK_API_HOST=localhost
NEXT_PUBLIC_BACK_API_PORT=3001
NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com
```
### Staging
```bash
NEXTJS_APP_ENV_NAME=staging
NODE_ENV=production
NEXT_PUBLIC_BACK_API_PROTOCOL=https://
NEXT_PUBLIC_BACK_API_HOST=stg-api.lecoffre.com
NEXT_PUBLIC_BACK_API_PORT=443
NEXT_PUBLIC_4NK_URL=https://dev4.4nkweb.com
```
### Production
```bash
NEXTJS_APP_ENV_NAME=production
NODE_ENV=production
NEXT_PUBLIC_BACK_API_PROTOCOL=https://
NEXT_PUBLIC_BACK_API_HOST=api.lecoffre.com
NEXT_PUBLIC_BACK_API_PORT=443
NEXT_PUBLIC_4NK_URL=https://4nk.lecoffre.com
```
## Utilisation dans le code
### Configuration Next.js
Les variables sont configurées dans `next.config.js`:
```javascript
const nextConfig = {
publicRuntimeConfig: {
NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
// ... autres variables
},
serverRuntimeConfig: {
// Même configuration pour le serveur
},
env: {
// Configuration pour le build
}
};
```
### Initialisation dans l'application
Les variables sont initialisées dans `_app.tsx`:
```typescript
const { publicRuntimeConfig } = getConfig();
MyApp.getInitialProps = async () => {
return {
backApiProtocol: publicRuntimeConfig.NEXT_PUBLIC_BACK_API_PROTOCOL,
// ... autres variables
};
};
```
### Utilisation dans les services
```typescript
// DatabaseService.ts
private static buildBaseUrl(): string {
return `${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_PROTOCOL}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_HOST}:${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_PORT}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_ROOT_URL}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_VERSION}`;
}
```
## Déploiement Docker
### Variables de build
```dockerfile
ARG NEXT_PUBLIC_BACK_API_PROTOCOL
ARG NEXT_PUBLIC_BACK_API_HOST
# ... autres variables
```
### Variables d'environnement runtime
```dockerfile
ENV NEXT_PUBLIC_BACK_API_PROTOCOL=${NEXT_PUBLIC_BACK_API_PROTOCOL} \
NEXT_PUBLIC_BACK_API_HOST=${NEXT_PUBLIC_BACK_API_HOST} \
# ... autres variables
```
### Exécution
```bash
docker run -e NEXT_PUBLIC_BACK_API_PROTOCOL=https:// \
-e NEXT_PUBLIC_BACK_API_HOST=api.example.com \
lecoffre/front:latest
```
## Déploiement Kubernetes
### Via Vault (recommandé)
```yaml
annotations:
vault.hashicorp.com/agent-inject: "true"
vault.hashicorp.com/agent-inject-secret-envs: secret/data/lecoffre-front-stg/config/envs
vault.hashicorp.com/agent-inject-template-envs: |
{{ with secret "secret/data/lecoffre-front-stg/config/envs" }}
{{ range $k, $v := .Data.data }}
export {{ $k }}="{{ $v }}"
{{ end }}
{{ end }}
```
### Via ConfigMap
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: lecoffre-front-config
data:
NEXT_PUBLIC_BACK_API_PROTOCOL: "https://"
NEXT_PUBLIC_BACK_API_HOST: "api.example.com"
# ... autres variables
```
## Validation et tests
### Vérification des variables requises
```typescript
const requiredVars = [
'NEXT_PUBLIC_BACK_API_PROTOCOL',
'NEXT_PUBLIC_BACK_API_HOST',
'NEXT_PUBLIC_BACK_API_PORT',
'NEXT_PUBLIC_BACK_API_ROOT_URL',
'NEXT_PUBLIC_BACK_API_VERSION'
];
for (const varName of requiredVars) {
if (!publicRuntimeConfig[varName]) {
throw new Error(`${varName} is not defined in environment variables`);
}
}
```
### Tests d'environnement
```bash
# Vérifier les variables définies
env | grep NEXT_PUBLIC_
# Tester la construction d'URL
curl -I $(echo $NEXT_PUBLIC_BACK_API_PROTOCOL$NEXT_PUBLIC_BACK_API_HOST:$NEXT_PUBLIC_BACK_API_PORT$NEXT_PUBLIC_BACK_API_ROOT_URL$NEXT_PUBLIC_BACK_API_VERSION/health)
```
## Bonnes pratiques
1. **Sécurité**: Ne jamais exposer de secrets dans les variables `NEXT_PUBLIC_*`
2. **Validation**: Toujours valider la présence des variables requises
3. **Documentation**: Maintenir la documentation des variables
4. **Tests**: Tester avec différentes configurations d'environnement
5. **Fallbacks**: Prévoir des valeurs par défaut quand possible
## Dépannage
### Variables non définies
```bash
# Vérifier les variables d'environnement
docker exec -it <container> env | grep NEXT_PUBLIC_
# Vérifier la configuration Vault
vault kv get secret/data/lecoffre-front-stg/config/envs
```
### URLs malformées
```bash
# Tester la construction d'URL
node -e "
const config = {
protocol: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
host: process.env.NEXT_PUBLIC_BACK_API_HOST,
port: process.env.NEXT_PUBLIC_BACK_API_PORT,
root: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL,
version: process.env.NEXT_PUBLIC_BACK_API_VERSION
};
console.log(\`\${config.protocol}\${config.host}:\${config.port}\${config.root}\${config.version}\`);
"
```
---
*Documentation mise à jour le $(date) - Variables d'environnement lecoffre-front*

View File

@ -1,81 +0,0 @@
### Objet
Analyse synthétique de `lecoffre-front` (Next.js) : périmètre, dépendances, configuration, intégrations et points dattention.
### Périmètre et stack
- **Framework**: Next.js 14 (React 18), rendu côté serveur désactivable selon pages
- **Langage**: TypeScript
- **Styles**: SCSS + MUI (@mui/material), Emotion
- **Bundle**: `output: 'standalone'`, `basePath: '/lecoffre'`
### Arborescence notable
- **`src/front/`**: API client (services, entités, SDK) et composants UI (DesignSystem, Layouts, Elements)
- **`pages/`**: routes Next (tableau client, gestion utilisateurs, dossiers, documents, souscriptions)
- **`src/common/Api/LeCoffreApi`**: modules Admin/Customer/Notary/SuperAdmin et `sdk`
- **`src/front/Stores/`**: stores locaux (User, Customer, Window, Toasts)
- **`src/front/Services/`**: services utilitaires (JWT, PDF, Watermark, Crypto, Cookie)
### Configuration et variables
- **`next.config.js`**: publie `NEXT_PUBLIC_*` aux clients et serveur; `reactStrictMode: false`; `ignoreBuildErrors: true`
- **BasePath**: `/lecoffre` (impacte le routage et les assets)
- **Intégrations**: Hotjar, GTM, Docaposte, 4NK (iframe/URL), Idnot (OAuth)
### Dépendances clés
- **UI**: `@mui/material`, `@emotion/*`, `react-select`, `react-toastify`
- **Utilitaires**: `jwt-decode`, `file-saver`, `jszip`, `pdf-lib`, `sass`, `sharp`
- **Ressources**: `le-coffre-resources` (dépôt Git 4NK)
### Intégrations externes (indiciaires)
- **Back**: via `NEXT_PUBLIC_BACK_API_*` et `NEXT_PUBLIC_API_URL`
- **Idnot**: endpoints OAuth (authorize, base_url, redirect_uri)
- **Docaposte**: `NEXT_PUBLIC_DOCAPOSTE_API_URL`
### Points dattention
- **TypeScript**: `ignoreBuildErrors: true` masque des erreurs de typage
- **BasePath**: vérifier la cohérence côté Nginx et lors du déploiement
- **Ressources Git**: accès SSH requis pour `le-coffre-resources`
- **Sécurité**: exposition de multiples `NEXT_PUBLIC_*` (vérifier quaucun secret nest divulgué)
### Tests et qualité
- **Scripts**: `build` sans lint, `lint` séparé, `format` ciblé `src/`
- **`tests/`**: présent (à enrichir avec scénarios e2e/smoke sur pages principales)
### Déploiement
- **Dockerfile**: présent (build Next standalone)
- **Intégration**: orchestré via `lecoffre_node` (voir analyse dédiée)
## Scripts npm, build et configuration
### Scripts
- **dev**: `next dev`
- **build**: `NEXT_TELEMETRY_DISABLED=1 next build --no-lint`
- **start**: `next start`
- **lint**: `next lint`
- **format**: `prettier --write src`
### next.config.js
- `output: 'standalone'`, `basePath: '/lecoffre'`
- `typescript.ignoreBuildErrors: true` (risque: masquage derreurs)
- Exposition de nombreuses variables `NEXT_PUBLIC_*` via `env`, `publicRuntimeConfig` et `serverRuntimeConfig`
### Docker (multistage)
- Étapes: `deps` (install), `development` (dev), `builder` (build), `int-dev` (runtime)
- BuildKit SSH pour `le-coffre-resources` (clé non copiée dans limage)
- Port runtime 3000; utilisateur nonroot `lecoffreuser`
### Dépendances (extraits)
- UI: `@mui/material`, `@emotion/*`, `react-select`, `react-toastify`
- Utilitaires: `jwt-decode`, `file-saver`, `jszip`, `pdf-lib`, `sass`, `sharp`
- Ressources: `le-coffre-resources` (SSH Git 4NK)
- Versions Node/Next: Node 19alpine; Next `^14.2.3`
## Risques et recommandations
- Désactiver `ignoreBuildErrors` et corriger les erreurs TypeScript avant build
- Envisager Node LTS (20/22) pour les images
- Vérifier quaucune info sensible nest exposée via `NEXT_PUBLIC_*`
- Assurer la cohérence `basePath` `/lecoffre` avec Nginx et les liens internes
- Introduire du code splitting ciblé (`React.lazy`/`Suspense`) sur pages lourdes
- Centraliser létat (Redux/Context) pour limiter le prop drilling dans `src/front`
## Changements IdNot
- Lauthentification IdNot appelle désormais le backend en POST avec le code dautorisation dans le corps JSON sur `/api/v1/idnot/auth`.
- Ce changement évite des erreurs en reverse proxy liées à des segments dURL très longs.

View File

@ -1,115 +0,0 @@
### CI/CD — Fonctionnement observé et architecture de déploiement
Cette documentation décrit le pipeline CI/CD tel quil peut être déduit des artefacts présents dans le dépôt: `Dockerfile`, `package.json`, et les manifestes Kubernetes rendus dans `temp.yaml`. Aucune configuration de pipeline explicite nest présente dans le dépôt (pas de `.gitea/`, `.github/workflows/`, `.gitlab-ci.yml`, `.drone.yml`). Le flux ci-dessous sappuie donc sur ces éléments pour décrire le fonctionnement attendu.
### Portée
- **Build applicatif**: Next.js (Node 19-alpine) avec dépendance privée `le-coffre-resources` via SSH.
- **Image Docker**: construction multi-étapes, publication vers le registre Docker hébergé sur `git.4nkweb.com` (accès via clés SSH).
- **Déploiement Kubernetes**: namespace `lecoffre`, intégration Vault Agent pour linjection dENV, `ExternalSecret` pour le secret de pull Docker, `Ingress` TLS via cert-manager, ressources de `Deployment`/`Service`.
- **Variables front ajoutées**: `NEXT_PUBLIC_4NK_IFRAME_URL` pour distinguer lURL complète de liframe de son origin (`NEXT_PUBLIC_4NK_URL`).
### Chaîne de build
- **Dépendances**
- `package.json` indique Next.js 14, TypeScript 4.9, ESLint 8.36, etc.
- La dépendance privée `le-coffre-resources` est récupérée depuis `git.4nkweb.com` via SSH (`git+ssh`).
- **Dockerfile** (multi-étapes, Node 19-alpine)
- Étape `deps`: installation des dépendances avec `npm install` en utilisant BuildKit et le forward dagent SSH pour accéder au dépôt privé.
- Étape `development`: copie du code, exécution sous un utilisateur non-root, commande par défaut `npm run dev` (pour le développement local). Pour la prod, limage utilisée en cluster exécute `npm run start` (cf. manifeste).
- **Build Next.js**
- Script `build`: `NEXT_TELEMETRY_DISABLED=1 next build --no-lint`
- Script `start`: `next start`
- Le lint nest pas bloquant au build (flag `--no-lint`).
### Image, registre et version
- **Registre**: Docker registry interne sur `git.4nkweb.com`.
- **Tagging**: contrôlé par la CI via le message de commit (préfixe `ci: docker_tag=<valeur>`), sinon fallback `dev-test`. La branche peut être utilisée comme tag par défaut selon la CI. Recommandation: utiliser un tag non versionné `int-dev`.
### Déploiement Kubernetes (extrait de `temp.yaml`)
- **Namespace**: `lecoffre`
- **ServiceAccount**: `lecoffre-front-sa` avec `Secret` token associé.
- **ExternalSecret**: création de `imagePullSecret` à partir de Vault via `external-secrets.io` en lisant `secret/data/lecoffre-front-stg/config/dockerpullsecret` (clé `.dockerconfigjson`).
- **Deployment**: `apps/v1` nommé `lecoffre-front` avec:
- `image`: `rg.fr-par.scw.cloud/lecoffre/front:v0.1.9`
- `imagePullPolicy`: `Always`
- `resources`: `requests` (cpu 200m, ram 1Gi), `limits` (ram 2Gi)
- **Vault Agent Injector**: annotations pour injecter des variables denvironnement depuis `secret/data/lecoffre-front-stg/config/envs` en exportant chaque paire `clé=valeur` dans `/vault/secrets/envs`.
- **Commande de démarrage**: `['sh','-c', '. /vault/secrets/envs && npm run start']`
- **Service**: type ClusterIP exposant le port 80 vers le `targetPort` 3000 du conteneur Next.js.
- **Ingress**: classe `nginx` avec TLS géré par `cert-manager` (ClusterIssuer `letsencrypt-prod`) pour `app.stg.lecoffre.smart-chain.fr`.
### Flux CI/CD attendu (déduit)
1. **Checkout + préparation**
- Récupération du code et configuration de lagent SSH (accès à `git.4nkweb.com`).
2. **Installation des dépendances**
- `npm install` avec BuildKit (`--mount=type=ssh`) pour la dépendance privée.
3. **Build applicatif**
- `npm run build` (désactive la télémétrie et le lint bloquant).
4. **Construction de limage**
- Réalisée par la CI (BuildKit + forward dagent SSH) après un `git push` sur `git.4nkweb.com`.
- Taggage déterminé par le message de commit et/ou la branche.
5. **Push au registre**
- Réalisé par la CI vers le registre `git.4nkweb.com`.
6. **Déploiement Kubernetes**
- Application des manifestes (ou rendu Helm) dans le namespace `lecoffre`.
- Les secrets de pull sont fournis via `ExternalSecret` connecté à Vault.
- Au runtime, Vault Agent injecte les variables denvironnement nécessaires avant `npm run start`.
### Sécurité et secrets
- **Build**: le forward dagent SSH évite décrire la clé privée dans limage.
- **Runtime**: aucune variable sensible nest stockée dans limage; elles sont injectées à lexécution par Vault.
- **Pull de limage**: la config Docker (`.dockerconfigjson`) est fournie par `ExternalSecret` à partir de Vault.
### Secrets CI requis
- **USER**: identifiant du compte CI sur `git.4nkweb.com` disposant des droits requis (lecture repo, push dimage vers le registry).
- **TOKEN**: jeton daccès (API/registry) associé à `USER`. Utilisé par la CI pour:
- Authentifier les actions git/HTTP vers `git.4nkweb.com` (si nécessaire)
- Authentifier le `docker login` vers le registry Gitea si la CI ne repose pas sur des credentials intégrés.
Notes:
- Préférer des tokens à portée restreinte, régénérés périodiquement.
- Stocker `USER` et `TOKEN` dans le gestionnaire de secrets CI et ne jamais les committer.
### Points à confirmer
- Outil CI utilisé (Gitea Actions, Woodpecker/Drone, GitLab CI, autre) et fichiers de pipeline hébergés ailleurs.
- Règles de nommage des tags dimage et gouvernance de version (`vX.Y.Z`, tags denvironnement).
- Stratégie de déploiement (Helm chart source exact, commandes dapply, gestion multi-env: dev/stg/prod).
- Politique de lint/test avant build (actuellement `--no-lint` au build Next.js).
- Passage des variables `NEXT_PUBLIC_4NK_URL` et `NEXT_PUBLIC_4NK_IFRAME_URL` à létape de build Docker (ARG/ENV) dans la CI.
### Bonnes pratiques recommandées
- Activer un job de lint et tests unitaires avant build dimage.
- Signer les images (Cosign) et activer des scans SCA/Container.
- Gérer explicitement les tags et le changelog en CI.
- Déployer via Helm chart versionné, avec valeurs par environnement (`values.{env}.yaml`).
### Validation de l'image Docker « int-dev » (intégration des variables)
- Objectif: vérifier que les variables `NEXT_PUBLIC_*` sont bien injectées dans l'image construite par la CI.
- Commande:
```
docker pull git.4nkweb.com/4nk/lecoffre-front:int-dev
docker run --rm git.4nkweb.com/4nk/lecoffre-front:int-dev sh -lc "env | grep '^NEXT_PUBLIC_' | sort"
```
- Attendus clés:
- `NEXT_PUBLIC_4NK_URL` et `NEXT_PUBLIC_4NK_IFRAME_URL` doivent être définies.
- Les URLs API (`NEXT_PUBLIC_API_URL`, `NEXT_PUBLIC_BACK_API_*`) doivent refléter l'environnement.

View File

@ -1,58 +0,0 @@
### Image Docker "int-dev" (Next.js) variables d'environnement et publication
Cette image exécute l'app Next.js en mode production via `next start` et lit la configuration via les variables d'environnement exposées (préfixe `NEXT_PUBLIC_`). L'objectif est d'éviter toute dépendance à `localhost` dans les appels API : les URLs sont construites dynamiquement côté front à partir de ces variables.
#### Variables d'environnement supportées
- **NEXT_PUBLIC_BACK_API_PROTOCOL**: protocole de l'API (ex: `https://`)
- **NEXT_PUBLIC_BACK_API_HOST**: hôte de l'API (ex: `api.example.com`)
- **NEXT_PUBLIC_BACK_API_PORT**: port de l'API (ex: `443`)
- **NEXT_PUBLIC_BACK_API_ROOT_URL**: racine (ex: `/` ou `/api`)
- **NEXT_PUBLIC_BACK_API_VERSION**: version (ex: `v1`)
- **NEXT_PUBLIC_FRONT_APP_HOST**: base publique du front (ex: `https://app.example.com`)
- **NEXT_PUBLIC_FRONT_APP_PORT**: port front si nécessaire (ex: `443`)
- **NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT**
- **NEXT_PUBLIC_IDNOT_CLIENT_ID**
- **NEXT_PUBLIC_IDNOT_BASE_URL**
- **NEXT_PUBLIC_DOCAPOSTE_API_URL**
- **NEXT_PUBLIC_HOTJAR_SITE_ID**
- **NEXT_PUBLIC_HOTJAR_VERSION**
- **NEXT_PUBLIC_4NK_URL**
- **NEXT_PUBLIC_API_URL**
- **NEXT_PUBLIC_DEFAULT_VALIDATOR_ID**
- **NEXT_PUBLIC_DEFAULT_STORAGE_URLS** (liste séparée par des virgules)
Notes:
- Le front initialise ses variables via `next.config.js` et `_app.tsx`, ce qui alimente `FrontendVariables`. Les appels API utilisent ces valeurs et n'emploient pas `localhost`.
- Les valeurs doivent être passées au conteneur au runtime (`docker run -e ...` ou manifest K8s via `env:`/`secretRef`).
#### Construction de l'image (cible "int-dev")
Prérequis: Docker BuildKit activé et agent SSH opérationnel pour cloner `le-coffre-resources` depuis `git.4nkweb.com`.
1. `cd /home/debian/lecoffre-front`
2. `export DOCKER_BUILDKIT=1`
3. `docker build --target int-dev --ssh default -t lecoffre/front:int-dev -f /home/debian/lecoffre-front/Dockerfile /home/debian/lecoffre-front`
#### Exécution locale (validation)
Exemple minimal (adapter les valeurs):
```bash
docker run --rm -p 3000:3000 \
-e NEXT_PUBLIC_BACK_API_PROTOCOL=https:// \
-e NEXT_PUBLIC_BACK_API_HOST=api.example.com \
-e NEXT_PUBLIC_BACK_API_PORT=443 \
-e NEXT_PUBLIC_BACK_API_ROOT_URL=/ \
-e NEXT_PUBLIC_BACK_API_VERSION=v1 \
-e NEXT_PUBLIC_FRONT_APP_HOST=https://app.example.com \
-e NEXT_PUBLIC_4NK_URL=https://app.example.com \
lecoffre/front:int-dev
```
#### Publication via CI (git.4nkweb.com)
- Le push d'image est effectué par la CI de `git.4nkweb.com` suite à un `git push`.
- Définir le tag Docker dans le message de commit: `ci: docker_tag=int-dev` (fallback CI: `dev-test`).
- La branche peut être utilisée par la CI comme tag en labsence doverride.

View File

@ -1,7 +0,0 @@
{
"folders": [
{
"path": "."
}
]
}

5
next-env.d.ts vendored
View File

@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.

View File

@ -2,16 +2,10 @@
const nextConfig = { const nextConfig = {
reactStrictMode: false, reactStrictMode: false,
output: 'standalone',
basePath: '/lecoffre',
typescript: {
ignoreBuildErrors: true,
},
publicRuntimeConfig: { publicRuntimeConfig: {
// Will be available on both server and client // Will be available on both server and client
NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL, NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST, NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST,
NEXT_PUBLIC_BACK_API_PORT: process.env.NEXT_PUBLIC_BACK_API_PORT,
NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL, NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL,
NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION, NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION,
NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST, NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST,
@ -19,19 +13,14 @@ const nextConfig = {
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT, NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT,
NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID, NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID,
NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL, NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL,
NEXT_PUBLIC_IDNOT_REDIRECT_URI: process.env.NEXT_PUBLIC_IDNOT_REDIRECT_URI,
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL, NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL, NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
NEXT_PUBLIC_4NK_IFRAME_URL: process.env.NEXT_PUBLIC_4NK_IFRAME_URL, NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID: process.env.NEXT_PUBLIC_DEFAULT_VALIDATOR_ID,
NEXT_PUBLIC_DEFAULT_STORAGE_URLS: process.env.NEXT_PUBLIC_DEFAULT_STORAGE_URLS,
}, },
serverRuntimeConfig: { serverRuntimeConfig: {
NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL, NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST, NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST,
NEXT_PUBLIC_BACK_API_PORT: process.env.NEXT_PUBLIC_BACK_API_PORT,
NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL, NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL,
NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION, NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION,
NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST, NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST,
@ -39,19 +28,14 @@ const nextConfig = {
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT, NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT,
NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID, NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID,
NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL, NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL,
NEXT_PUBLIC_IDNOT_REDIRECT_URI: process.env.NEXT_PUBLIC_IDNOT_REDIRECT_URI,
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL, NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL, NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
NEXT_PUBLIC_4NK_IFRAME_URL: process.env.NEXT_PUBLIC_4NK_IFRAME_URL, NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID: process.env.NEXT_PUBLIC_DEFAULT_VALIDATOR_ID,
NEXT_PUBLIC_DEFAULT_STORAGE_URLS: process.env.NEXT_PUBLIC_DEFAULT_STORAGE_URLS,
}, },
env: { env: {
NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL, NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST, NEXT_PUBLIC_BACK_API_HOST: process.env.NEXT_PUBLIC_BACK_API_HOST,
NEXT_PUBLIC_BACK_API_PORT: process.env.NEXT_PUBLIC_BACK_API_PORT,
NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL, NEXT_PUBLIC_BACK_API_ROOT_URL: process.env.NEXT_PUBLIC_BACK_API_ROOT_URL,
NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION, NEXT_PUBLIC_BACK_API_VERSION: process.env.NEXT_PUBLIC_BACK_API_VERSION,
NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST, NEXT_PUBLIC_FRONT_APP_HOST: process.env.NEXT_PUBLIC_FRONT_APP_HOST,
@ -59,13 +43,9 @@ const nextConfig = {
NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT, NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT: process.env.NEXT_PUBLIC_IDNOT_AUTHORIZE_ENDPOINT,
NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID, NEXT_PUBLIC_IDNOT_CLIENT_ID: process.env.NEXT_PUBLIC_IDNOT_CLIENT_ID,
NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL, NEXT_PUBLIC_IDNOT_BASE_URL: process.env.NEXT_PUBLIC_IDNOT_BASE_URL,
NEXT_PUBLIC_IDNOT_REDIRECT_URI: process.env.NEXT_PUBLIC_IDNOT_REDIRECT_URI,
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL, NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL, NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
NEXT_PUBLIC_4NK_IFRAME_URL: process.env.NEXT_PUBLIC_4NK_IFRAME_URL, NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_DEFAULT_VALIDATOR_ID: process.env.NEXT_PUBLIC_DEFAULT_VALIDATOR_ID,
NEXT_PUBLIC_DEFAULT_STORAGE_URLS: process.env.NEXT_PUBLIC_DEFAULT_STORAGE_URLS,
}, },
// webpack: config => { // webpack: config => {

4059
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
{ {
"name": "lecoffre-front", "name": "lecoffre-front",
"version": "0.1.6", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
"build": "NEXT_TELEMETRY_DISABLED=1 next build --no-lint", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"format": "prettier --write src" "format": "prettier --write src"
@ -32,12 +32,11 @@
"jwt-decode": "^3.1.2", "jwt-decode": "^3.1.2",
"le-coffre-resources": "git+https://git.4nkweb.com/4nk/lecoffre-ressources.git#v2.167", "le-coffre-resources": "git+https://git.4nkweb.com/4nk/lecoffre-ressources.git#v2.167",
"next": "^14.2.3", "next": "^14.2.3",
"pdf-lib": "^1.17.1",
"prettier": "^2.8.7", "prettier": "^2.8.7",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-gtm-module": "^2.0.11", "react-gtm-module": "^2.0.11",
"react-hotjar": "^6.3.1",
"react-select": "^5.7.2", "react-select": "^5.7.2",
"react-toastify": "^9.1.3", "react-toastify": "^9.1.3",
"sass": "^1.59.2", "sass": "^1.59.2",

View File

@ -1,63 +0,0 @@
import MessageBus from 'src/sdk/MessageBus';
export default abstract class AbstractService {
protected static readonly messageBus: MessageBus = MessageBus.getInstance();
private static readonly CACHE_TTL = 60 * 60 * 1000; // 60 minutes cache TTL
protected constructor() { }
protected static setItem(key: string, processId: string, process: any): void {
const cache: Record<string, {process: any, timestamp: number}> =
JSON.parse(sessionStorage.getItem(key) || '{}');
cache[processId] = {
process: process, // we overwrite existing process
timestamp: Date.now()
};
sessionStorage.setItem(key, JSON.stringify(cache));
}
protected static getItem(key: string, processId: string): any | null {
const cache: Record<string, {process: any, timestamp: number}> =
JSON.parse(sessionStorage.getItem(key) || '{}');
const item = cache[processId];
if (!item) {
return null;
}
const now: number = Date.now();
if ((now - item.timestamp) < this.CACHE_TTL) {
return { process: item.process, timestamp: item.timestamp };
}
return null;
}
protected static getItems(key: string): Record<string, any> {
const cache: Record<string, {process: any, timestamp: number}> =
JSON.parse(sessionStorage.getItem(key) || '{}');
const now: number = Date.now();
const validItems: Record<string, any> = {};
for (const [processId, item] of Object.entries(cache)) {
if (now - item.timestamp < this.CACHE_TTL) {
validItems[processId] = item.process;
}
}
return validItems;
}
protected static removeItem(key: string, processId: string): void {
const cache: Record<string, {process: any, timestamp: number}> =
JSON.parse(sessionStorage.getItem(key) || '{}');
delete cache[processId];
sessionStorage.setItem(key, JSON.stringify(cache));
}
}

View File

@ -1,191 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class CollaboratorService extends AbstractService {
private constructor() {
super();
}
public static async createCollaborator(collaboratorData: any, validatorId: string): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'collaborator',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...collaboratorData
};
const privateFields: string[] = Object.keys(processData);
const allFields: string[] = [...privateFields, 'roles'];
const roles: any = {
demiurge: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId, validatorId],
validation_rules: [
{
quorum: 0.01,
fields: allFields,
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
try {
const processCreated = await this.messageBus.createProcess(processData, privateFields, roles);
await this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id);
await this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id);
const finalProcessData = await this.messageBus.getProcessData(processCreated.processId);
return { processId: processCreated.processId, processData: finalProcessData };
} catch (error) {
throw error;
}
}
public static getCollaborators(callback: (processes: Record<string, any>) => void): void {
const items: Record<string, any> = this.getItems('_collaborators_');
if (Object.keys(items).length > 0) {
setTimeout(() => callback(items), 0);
}
this.messageBus.getProcessesDecoded((processId: string, data: any) =>
data['utype'] &&
data['utype'] === 'collaborator' &&
data['isDeleted'] &&
data['isDeleted'] === 'false' &&
!Object.keys(items).includes(processId)
).then(async (processesData: Record<string, any>) => {
if (Object.keys(processesData).length === 0) {
// If no new processes and no cached items, return empty array
if (Object.keys(items).length === 0) {
callback([]);
}
return;
}
// Single callback with all completed items
callback(items);
}).catch(error => {
console.error('Failed to fetch collaborators:', error);
// Return cached data if available, otherwise empty array
callback(items);
});
}
public static getCollaboratorsBy(whereClause: { [path: string]: any }): Promise<Record<string, any>> {
return new Promise<Record<string, any>>((resolve: (collaborators: Record<string, any>) => void) => {
this.getCollaborators((processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
resolve({});
} else {
const filteredEntries = Object.entries(processes).filter(([processId, process]) => {
for (const path in whereClause) {
const paths: string[] = path.split('.');
let value: any = process;
value['processId'] = processId;
for (let i = 0; i < paths.length; i++) {
const currentPath = paths[i];
if (!currentPath || value === undefined || value === null) {
break;
}
value = value[currentPath];
}
if (value !== whereClause[path]) {
return false;
}
}
return true;
});
// Convert filtered entries back to a Record
const filteredProcesses: Record<string, any> = {};
filteredEntries.forEach(([processId, process]) => {
filteredProcesses[processId] = process;
});
resolve(filteredProcesses);
}
});
});
}
public static getCollaboratorBy(whereClause: { [path: string]: any }): Promise<any | null> {
return new Promise<any | null>((resolve: (collaborator: any | null) => void) => {
this.getCollaborators((processes: Record<string, any>) => {
const processArray = Object.values(processes);
if (processArray.length === 0) {
resolve(null);
} else {
resolve(processArray.find((process: any) => {
const collaborator: any = process.processData;
for (const path in whereClause) {
const paths: string[] = path.split('.');
let value: any = collaborator;
for (let i = 0; i < paths.length; i++) {
const currentPath = paths[i];
if (!currentPath || value === undefined || value === null) {
break;
}
value = value[currentPath];
}
if (value !== whereClause[path]) {
return false;
}
}
return true;
}));
}
});
});
}
public static async updateCollaborator(processId: string, newData: any): Promise<void> {
try {
const processUpdated = await this.messageBus.updateProcess(
processId,
{ updated_at: new Date().toISOString(), ...newData },
[],
null
);
const newStateId: string = processUpdated.diffs[0]?.state_id;
await this.messageBus.notifyUpdate(processId, newStateId);
await this.messageBus.validateState(processId, newStateId);
const processData = await this.messageBus.getProcessData(processId);
// Update cache
this.setItem('_collaborators_', processId, processData);
} catch (error) {
console.error('Failed to update collaborator:', error);
throw error; // Re-throw to allow caller to handle
}
}
}

View File

@ -1,111 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class CustomerService extends AbstractService {
private constructor() {
super();
}
public static async createCustomer(customerData: any, validatorId: string): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'customer',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...customerData
};
const privateFields: string[] = Object.keys(processData);
const allFields: string[] = [...privateFields, 'roles'];
const roles: any = {
demiurge: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId, validatorId],
validation_rules: [
{
quorum: 1,
fields: allFields,
min_sig_member: 1,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
try {
const processCreated = await this.messageBus.createProcess(processData, privateFields, roles);
await this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id);
await this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id);
const finalProcessData = await this.messageBus.getProcessData(processCreated.processId);
return { processId: processCreated.processId, processData: finalProcessData[processCreated.processId] };
} catch (error) {
throw error;
}
}
public static getCustomers(callback: (processes: Record<string, any>) => void): void {
// Check if we have valid cache
const items: Record<string, any> = this.getItems('_customers_');
if (Object.keys(items).length > 0) {
setTimeout(() => callback(items), 0);
}
this.messageBus.getProcessesDecoded((_processId: string, values: any) => {
return values['utype']
&& values['utype'] === 'customer'
&& values['isDeleted']
&& values['isDeleted'] === 'false';
}).then(async (processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
callback(items);
return;
}
const updatedItems: Record<string, any> = { ...items };
for (const [processId, process] of Object.entries(processes)) {
// Update cache
this.setItem('_customers_', processId, process);
updatedItems[processId] = process;
}
callback(updatedItems);
});
}
public static updateCustomer(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const customerUid: string = process.processData.uid;
this.removeItem('_customers_', customerUid);
resolve();
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,77 +0,0 @@
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
export default class DatabaseService {
// Empêcher l'instanciation de cette classe utilitaire
private constructor() { }
/**
* Récupère les données d'une table avec pagination
* @param tableName Nom de la table à consulter
* @param page Numéro de page (commence à 1)
* @param limit Nombre d'éléments par page
* @returns Données de la table avec pagination
*/
public static async getTableData(tableName: string, page: number = 1, limit: number = 10): Promise<any> {
// Vérification des paramètres
if (!tableName) {
throw new Error('Le nom de la table est requis');
}
// Validation du nom de la table (par sécurité)
const tableNameRegex = /^[a-zA-Z0-9_]+$/;
if (!tableNameRegex.test(tableName)) {
throw new Error('Nom de table invalide');
}
try {
// Construction de l'URL avec paramètres de pagination
const baseUrl = DatabaseService.buildBaseUrl();
const url = `${baseUrl}/db/${tableName}?page=${page}&limit=${limit}`;
// Appel à l'API REST
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || 'Erreur lors de la récupération des données');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Erreur lors de l\'accès à la base de données:', error);
throw error;
}
}
/**
* Construit l'URL de base en utilisant les variables d'environnement
* @returns URL de base de l'API
*/
private static buildBaseUrl(): string {
// Vérification des variables d'environnement requises
const requiredVars = [
'NEXT_PUBLIC_BACK_API_PROTOCOL',
'NEXT_PUBLIC_BACK_API_HOST',
'NEXT_PUBLIC_BACK_API_PORT',
'NEXT_PUBLIC_BACK_API_ROOT_URL',
'NEXT_PUBLIC_BACK_API_VERSION'
];
for (const varName of requiredVars) {
if (!publicRuntimeConfig[varName]) {
throw new Error(`${varName} is not defined in environment variables`);
}
}
// Construction de l'URL de base
return `${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_PROTOCOL}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_HOST}:${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_PORT}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_ROOT_URL}${publicRuntimeConfig.NEXT_PUBLIC_BACK_API_VERSION}`;
}
}

View File

@ -1,123 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class DeedTypeService extends AbstractService {
private constructor() {
super();
}
public static async createDeedType(deedTypeData: any, validatorId: string): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'deedType',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
document_types: [],
...deedTypeData
};
const privateFields: string[] = Object.keys(processData);
const allFields: string[] = [...privateFields, 'roles'];
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId, validatorId],
validation_rules: [
{
quorum: 0.01,
fields: allFields,
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
try {
const processCreated = await this.messageBus.createProcess(processData, privateFields, roles);
await this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id);
await this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id);
const finalProcessData = await this.messageBus.getProcessData(processCreated.processId);
return { processId: processCreated.processId, processData: finalProcessData };
} catch (error) {
throw error;
}
}
public static getDeedTypes(callback: (processes: Record<string, any>) => void): void {
// Check if we have valid cache
const items: Record<string, any> = this.getItems('_deed_types_');
if (Object.keys(items).length > 0) {
setTimeout(() => callback(items), 0);
}
this.messageBus.getProcessesDecoded((_processId: string, values: any) => {
return values['utype']
&& values['utype'] === 'deedType'
&& values['isDeleted']
&& values['isDeleted'] === 'false';
}).then(async (processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
callback(items);
return;
}
console.log('[DeedTypeService/getDeedTypes] processes', processes);
const updatedItems: Record<string, any> = { ...items };
for (const [processId, process] of Object.entries(processes)) {
// Update cache
this.setItem('_deed_types_', processId, process);
updatedItems[processId] = process;
}
callback(updatedItems);
});
}
public static async updateDeedType(processId: string, newData: any): Promise<void> {
try {
const processUpdated = await this.messageBus.updateProcess(
processId,
{ updated_at: new Date().toISOString(), ...newData },
[],
null
);
const newStateId: string = processUpdated.diffs[0]?.state_id;
await this.messageBus.notifyUpdate(processId, newStateId);
await this.messageBus.validateState(processId, newStateId);
const processData = await this.messageBus.getProcessData(processId);
// Update cache
this.setItem('_deed_types_', processId, processData);
} catch (error) {
console.error('Failed to update deed type:', error);
throw error; // Re-throw to allow caller to handle
}
}
}

View File

@ -1,152 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
export default class DocumentService extends AbstractService {
private constructor() {
super();
}
public static createDocument(documentData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'document',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...documentData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [...[ownerId], validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: []
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 0.5,
fields: ['idCertified', 'roles'],
min_sig_member: 1,
},
{
quorum: 0.0,
fields: [...privateFields],
min_sig_member: 0,
},
],
storages: []
},
apophis: {
members: [ownerId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getDocumentByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getDocuments(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_documents_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'document' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then((processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (const process of processes) {
// Update cache
this.setItem('_documents_', process);
items.push(process);
}
return items;
}
});
}
public static getDocumentByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_documents_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'document' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then((processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
const process: any = processes[0];
// Update cache
this.setItem('_documents_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateDocument(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const documentUid: string = process.processData.uid;
this.removeItem('_documents_', documentUid);
this.getDocumentByUid(documentUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,117 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class DocumentTypeService extends AbstractService {
private constructor() {
super();
}
public static createDocumentType(documentTypeData: any, validatorId: string): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'documentType',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...documentTypeData
};
const privateFields: string[] = Object.keys(processData);
const allFields: string[] = [...privateFields, 'roles'];
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId, validatorId],
validation_rules: [
{
quorum: 0.01,
fields: allFields,
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.messageBus.getProcessData(processCreated.processId).then((processData: any) => {
resolve({ processId: processCreated.processId, processData: processData });
}).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getDocumentTypes(callback: (processes: Record<string, any>) => void): void {
// Check if we have valid cache
const items: Record<string, any> = this.getItems('_document_types_');
if (Object.keys(items).length > 0) {
setTimeout(() => callback(items), 0);
}
this.messageBus.getProcessesDecoded((_processId: string, values: any) => {
return values['utype'] === 'documentType'
&& values['isDeleted'] === 'false';
}).then(async (processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
callback(items);
return;
}
const updatedItems: Record<string, any> = { ...items };
for (const [processId, process] of Object.entries(processes)) {
// Update cache
this.setItem('_document_types_', processId, process);
updatedItems[processId] = process;
}
callback(updatedItems);
});
}
public static async updateDocumentType(processId: string, newData: any): Promise<void> {
try {
const processUpdated = await this.messageBus.updateProcess(
processId,
{ updated_at: new Date().toISOString(), ...newData },
[],
null
);
const newStateId: string = processUpdated.diffs[0]?.state_id;
await this.messageBus.notifyUpdate(processId, newStateId);
await this.messageBus.validateState(processId, newStateId);
const processData = await this.messageBus.getProcessData(processId);
// Update cache
this.setItem('_document_types_', processId, processData);
} catch (error) {
console.error('Failed to update deed type:', error);
throw error; // Re-throw to allow caller to handle
}
}
}

View File

@ -1,98 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import MessageBus from 'src/sdk/MessageBus';
import User from 'src/sdk/User';
import { FileData } from '../../../../front/Api/Entities/types';
export default class FileService {
private static readonly messageBus: MessageBus = MessageBus.getInstance();
private constructor() { }
public static createFile(fileData: FileData, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'file',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...fileData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [...[ownerId], validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: []
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 0.5,
fields: ['idCertified', 'roles'],
min_sig_member: 1,
},
{
quorum: 0.0,
fields: [...privateFields],
min_sig_member: 0,
},
],
storages: []
},
apophis: {
members: [ownerId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
resolve(processCreated);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getFileByUid(uid: string): Promise<any> {
return this.messageBus.getFileByUid(uid);
}
public static updateFile(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
resolve();
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,180 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS, DEFAULT_VALIDATOR_ID } from '@Front/Config/AppConstants';
export default class FolderService extends AbstractService {
private constructor() {
super();
}
public static async createFolder(folderData: any, customersId: string[]): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'folder',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...folderData
};
const privateFields: string[] = Object.keys(processData);
const allFields: string[] = [...privateFields, 'roles'];
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owners: {
members: [ownerId, DEFAULT_VALIDATOR_ID],
validation_rules: [
{
quorum: 0.01,
fields: allFields,
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
guests: {
members: [],
validation_rules: [{
quorum: 0.01,
fields: allFields,
min_sig_member: 0.01,
}],
storages: [...DEFAULT_STORAGE_URLS]
},
customers: {
members: customersId,
validation_rules: [
{
quorum: 0.0,
fields: allFields,
min_sig_member: 0.0,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, DEFAULT_VALIDATOR_ID],
validation_rules: [],
storages: []
}
};
try {
const processCreated = await this.messageBus.createProcess(processData, privateFields, roles);
await this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id);
await this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id);
const finalProcessData = await this.messageBus.getProcessData(processCreated.processId);
return { processId: processCreated.processId, processData: finalProcessData };
} catch (error) {
throw error;
}
}
public static getFolders(callback: (processes: Record<string, any>) => void): void {
// Check if we have valid cache
const items: Record<string, any> = this.getItems('_folders_');
if (Object.keys(items).length > 0) {
setTimeout(() => callback(items), 0);
}
this.messageBus.getProcessesDecoded((_processId: string, values: any) => {
return values['utype']
&& values['utype'] === 'folder'
&& values['isDeleted']
&& values['isDeleted'] === 'false';
}).then(async (processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
callback(items);
return;
}
console.log('[FolderService/getFolders] processes', processes);
const updatedItems: Record<string, any> = { ...items };
for (const [processId, process] of Object.entries(processes)) {
// Update cache
this.setItem('_folders_', processId, process);
updatedItems[processId] = process;
}
callback(updatedItems);
});
}
public static getFoldersBy(whereClause: { [path: string]: any }): Promise<Record<string, any>> {
return new Promise<Record<string, any>>((resolve: (folders: Record<string, any>) => void) => {
this.getFolders((processes: Record<string, any>) => {
if (Object.keys(processes).length === 0) {
resolve({});
} else {
const filteredEntries = Object.entries(processes).filter(([processId, process]) => {
for (const path in whereClause) {
const paths: string[] = path.split('.');
let value: any = process;
value['processId'] = processId;
for (let i = 0; i < paths.length; i++) {
const currentPath = paths[i];
if (!currentPath || value === undefined || value === null) {
break;
}
value = value[currentPath];
}
if (value !== whereClause[path]) {
return false;
}
}
return true;
});
// Convert filtered entries back to a Record
const filteredProcesses: Record<string, any> = {};
filteredEntries.forEach(([processId, process]) => {
filteredProcesses[processId] = process;
});
resolve(filteredProcesses);
}
});
});
}
public static async updateFolder(processId: string, newData: any): Promise<void> {
try {
const processUpdated = await this.messageBus.updateProcess(
processId,
{ updated_at: new Date().toISOString(), ...newData },
[],
null
);
const newStateId: string = processUpdated.diffs[0]?.state_id;
await this.messageBus.notifyUpdate(processId, newStateId);
await this.messageBus.validateState(processId, newStateId);
const processData = await this.messageBus.getProcessData(processId);
// Update cache
this.setItem('_folders_', processId, processData);
} catch (error) {
console.error('Failed to update folder:', error);
throw error; // Re-throw to allow caller to handle
}
}
}

View File

@ -1,509 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import MessageBus from 'src/sdk/MessageBus';
import DatabaseService from './DatabaseService';
import RuleService from './RuleService';
import RuleGroupService from './RuleGroupService';
import RoleService from './RoleService';
import OfficeRoleService from './OfficeRoleService';
import { DEFAULT_VALIDATOR_ID } from '@Front/Config/AppConstants';
const mandatoryRoles = ['Notaire', 'Collaborateur'];
/**
* Type pour le callback de progression
*/
export interface ProgressInfo {
/** Progression globale (0-100) */
globalProgress: number;
/** Nom de l'étape en cours */
currentStep: string;
/** Progression de l'étape en cours (0-100) */
stepProgress: number;
/** Description optionnelle de l'action en cours */
description?: string;
}
export default class ImportData {
protected static readonly messageBus: MessageBus = MessageBus.getInstance();
public static async import(office: any, validatorId: string, onProgress?: (info: ProgressInfo) => void): Promise<void> {
// Définir les étapes d'importation dynamiquement
const importSteps = [
{
name: 'Règles',
function: async (progressCallback?: (subProgress: number, description?: string) => void) =>
await this.importRules(progressCallback)
},
{
name: 'Groupes de règles',
function: async (progressCallback?: (subProgress: number, description?: string) => void) =>
await this.importRuleGroups(progressCallback)
},
{
name: 'Rôles',
function: async (progressCallback?: (subProgress: number, description?: string) => void) =>
await this.importRoles(progressCallback)
},
{
name: 'Rôles d\'office',
function: async (progressCallback?: (subProgress: number, description?: string) => void, prevResults?: any[]) =>
await this.importOfficeRoles(office, prevResults![1], progressCallback)
}
];
// Calculer la part de progression pour chaque étape
const totalSteps = importSteps.length;
const stepWeight = 100 / totalSteps;
// Appel du callback avec 0% au début
onProgress?.({
globalProgress: 0,
currentStep: 'Initialisation',
stepProgress: 0,
description: 'Début de l\'importation des données'
});
// Exécuter chaque étape d'importation séquentiellement
const results: any[] = [];
for (let i = 0; i < importSteps.length; i++) {
const step = importSteps[i];
if (!step) continue; // S'assurer que l'étape existe
const startProgress = i * stepWeight;
// Créer un callback de progression pour cette étape
const stepProgressCallback = (subProgress: number, description?: string) => {
onProgress?.({
globalProgress: startProgress + (subProgress * stepWeight / 100),
currentStep: step.name,
stepProgress: subProgress,
description
});
};
// Exécuter l'étape et stocker le résultat si nécessaire
const result = await step.function(stepProgressCallback, results);
if (result !== undefined) {
results.push(result);
} else {
// Push empty array to maintain consistent indexing
results.push([]);
}
console.log(`Step ${i} (${step.name}): ${result?.length || 0} items`);
}
if (!await this.isDone()) {
await this.done(validatorId);
}
}
public static async isDone(): Promise<boolean> {
return await this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'importData' &&
publicValues['isDeleted'] && publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => processes.length > 0);
}
private static async done(validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'importData',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: []
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 0.5,
fields: ['idCertified', 'roles'],
min_sig_member: 1,
},
{
quorum: 0.0,
fields: [...privateFields],
min_sig_member: 0,
},
],
storages: []
},
apophis: {
members: [ownerId],
validation_rules: [],
storages: []
}
};
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
resolve();
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
private static async importRules(onProgress?: (progress: number, description?: string) => void): Promise<any[]> {
console.log('Importing rules');
const rules: any[] = [];
const INIT_PROGRESS = 0;
const FETCH_PROGRESS = 30;
const CREATE_END_PROGRESS = 90;
const FINAL_PROGRESS = 100;
onProgress?.(INIT_PROGRESS, 'Initialisation');
let page = 1;
let limit = 10;
let totalPages = 1;
onProgress?.(FETCH_PROGRESS, 'Récupération des règles existantes');
let result = await DatabaseService.getTableData('rules', page, limit);
if (result && result.success && result.pagination) {
totalPages = result.pagination.totalPages || 1;
}
const FETCH_PAGE_PROGRESS_START = FETCH_PROGRESS;
const FETCH_PAGE_PROGRESS_END = 60;
const CREATE_START_PROGRESS = 60;
while (result && result.success) {
const fetchPageProgress = FETCH_PAGE_PROGRESS_START + ((page / totalPages) * (FETCH_PAGE_PROGRESS_END - FETCH_PAGE_PROGRESS_START));
onProgress?.(fetchPageProgress, `Page ${page}/${totalPages} : Récupération des règles`);
const existingRules: any[] = (await RuleService.getRules()).map((process: any) => process.processData);
const filteredRules: any[] = result.data.filter((rule: any) => !existingRules.some((existingRule: any) => existingRule.uid === rule.uid));
if (filteredRules.length === 0) {
console.debug('All rules already imported');
}
const totalFilteredRules = filteredRules.length;
for (let i = 0; i < totalFilteredRules; i++) {
console.log(`Adding rule ${filteredRules[i].name}`);
rules.push((await RuleService.createRule(filteredRules[i], DEFAULT_VALIDATOR_ID)).processData);
const progressRange = CREATE_END_PROGRESS - CREATE_START_PROGRESS;
const ruleProgressIncrement = progressRange / (totalFilteredRules * totalPages);
const progress = CREATE_START_PROGRESS + ((page - 1) * totalFilteredRules + i + 1) * ruleProgressIncrement;
onProgress?.(progress, `Page ${page}/${totalPages} : Création de la règle ${i + 1}/${totalFilteredRules} - ${filteredRules[i].label}`);
}
if (!result.pagination.hasNextPage) {
break;
}
page++;
result = await DatabaseService.getTableData('rules', page, limit);
}
onProgress?.(FINAL_PROGRESS, 'Importation des règles terminée');
return rules;
}
private static async importRuleGroups(onProgress?: (progress: number, description?: string) => void): Promise<any[]> {
console.log('Importing rule groups');
const ruleGroups: any[] = [];
const INIT_PROGRESS = 0;
const FETCH_PROGRESS = 30;
const CREATE_END_PROGRESS = 90;
const FINAL_PROGRESS = 100;
onProgress?.(INIT_PROGRESS, 'Initialisation');
let page = 1;
let limit = 10;
let totalPages = 1;
onProgress?.(FETCH_PROGRESS, 'Récupération des groupes de règles existants');
let result = await DatabaseService.getTableData('rules_groups', page, limit);
if (result && result.success && result.pagination) {
totalPages = result.pagination.totalPages || 1;
}
const FETCH_PAGE_PROGRESS_START = FETCH_PROGRESS;
const FETCH_PAGE_PROGRESS_END = 60;
const CREATE_START_PROGRESS = 60;
while (result && result.success) {
const fetchPageProgress = FETCH_PAGE_PROGRESS_START + ((page / totalPages) * (FETCH_PAGE_PROGRESS_END - FETCH_PAGE_PROGRESS_START));
onProgress?.(fetchPageProgress, `Page ${page}/${totalPages} : Récupération du groupe de règles`);
const existingRuleGroups: any[] = (await RuleGroupService.getRuleGroups()).map((process: any) => process.processData);
const filteredRuleGroups: any[] = result.data.filter((rule: any) => !existingRuleGroups.some((existingRule: any) => existingRule.uid === rule.uid));
const totalFilteredRuleGroups = filteredRuleGroups.length;
for (let i = 0; i < totalFilteredRuleGroups; i++) {
console.log(`Adding rule group ${filteredRuleGroups[i].name}`);
ruleGroups.push((await RuleGroupService.createRuleGroup(filteredRuleGroups[i], DEFAULT_VALIDATOR_ID)).processData);
const progressRange = CREATE_END_PROGRESS - CREATE_START_PROGRESS;
const ruleProgressIncrement = progressRange / (totalFilteredRuleGroups * totalPages);
const progress = CREATE_START_PROGRESS + ((page - 1) * totalFilteredRuleGroups + i + 1) * ruleProgressIncrement;
onProgress?.(progress, `Page ${page}/${totalPages} : Création du groupe de règles ${i + 1}/${totalFilteredRuleGroups} - ${filteredRuleGroups[i].label}`);
}
if (!result.pagination.hasNextPage) {
break;
}
page++;
result = await DatabaseService.getTableData('rules_groups', page, limit);
}
onProgress?.(FINAL_PROGRESS, 'Importation des groupes de règles terminée');
return ruleGroups;
}
private static async importRoles(onProgress?: (progress: number, description?: string) => void): Promise<any[]> {
console.log('Importing roles');
// Constantes de progression - pourraient être paramétrées
const INIT_PROGRESS = 0;
const FETCH_PROGRESS = 30;
const CREATE_START_PROGRESS = FETCH_PROGRESS;
const CREATE_END_PROGRESS = 90;
const FINAL_PROGRESS = 100;
onProgress?.(INIT_PROGRESS, 'Initialisation');
return await new Promise<any[]>((resolve: (roles: any[]) => void) => {
const defaultRoles: any[] = [
{
name: 'super-admin',
label: 'Super administrateur'
},
{
name: 'admin',
label: 'Administrateur'
},
{
name: 'notary',
label: 'Notaire'
},
{
name: 'default',
label: 'Utilisateur'
}
];
RoleService.getRoles().then(async (processes: any[]) => {
onProgress?.(FETCH_PROGRESS, 'Récupération des rôles existants');
const roles: any[] = processes.map((process: any) => process.processData);
if (roles.length === 0) {
const defaultRolesNames: string[] = defaultRoles.map((role: any) => role.name);
const totalRoles = defaultRoles.length;
for (let i = 0; i < totalRoles; i++) {
if (!defaultRolesNames.includes(roles[i].name)) {
roles.push((await RoleService.createRole(defaultRoles[i], DEFAULT_VALIDATOR_ID)).processData);
} else {
console.log(`Role ${defaultRoles[i].name} already exists`);
}
// Progression dynamique pendant la création des rôles
const progressRange = CREATE_END_PROGRESS - CREATE_START_PROGRESS;
const progress = CREATE_START_PROGRESS + ((i + 1) / totalRoles) * progressRange;
onProgress?.(progress, `Création du rôle ${i + 1}/${totalRoles} : ${defaultRoles[i].label}`);
}
}
onProgress?.(FINAL_PROGRESS, 'Importation des rôles terminée');
resolve(roles);
});
});
}
private static async importDefaultRoles(officeUid: string, ruleGroups: any[], onProgress?: (progress: number, description?: string) => void): Promise<any[]> {
console.log('Importing default roles');
let officeRoles: any[] = [];
const CREATE_START_PROGRESS = 60;
const CREATE_END_PROGRESS = 90;
onProgress?.(CREATE_START_PROGRESS, 'Création des rôles par défaut');
// Prepare the collaborator rules from rule groups
const collaboratorRules: any[] = ruleGroups
.map((ruleGroup: any) => ruleGroup.rules || [])
.reduce((acc: any, curr: any) => [...acc, ...curr], [])
.map((rule: any) => ({ uid: rule.uid }));
console.log(`Found ${collaboratorRules.length} collaborator rules from ${ruleGroups.length} rule groups`);
// Get fresh list of existing roles (including ones we just created)
const updatedExistingRoles = await OfficeRoleService.getOfficeRoles();
const existingRoles = updatedExistingRoles
.map((role: any) => role.processData)
.filter((roleData: any) => roleData.office?.uid === officeUid);
const existingRoleNames = existingRoles.map((role: any) => role.name);
const missingMandatoryRoles = mandatoryRoles.filter(roleName =>
!existingRoleNames.includes(roleName)
);
console.log(`Found ${existingRoleNames.length} existing roles, ${missingMandatoryRoles.length} mandatory roles missing`);
if (missingMandatoryRoles.length === 0) {
onProgress?.(CREATE_END_PROGRESS, 'Tous les rôles obligatoires existent déjà');
return officeRoles;
}
for (let i = 0; i < missingMandatoryRoles.length; i++) {
const roleName = missingMandatoryRoles[i];
const fallbackRole = {
name: roleName,
office: { uid: officeUid },
// Only Notaire gets rules, Collaborateur gets none
...(roleName === 'Notaire' && { rules: collaboratorRules })
};
console.log(`Creating missing mandatory role: ${roleName}`);
officeRoles.push((await OfficeRoleService.createOfficeRole(fallbackRole, DEFAULT_VALIDATOR_ID)).processData);
const progressRange = CREATE_END_PROGRESS - CREATE_START_PROGRESS;
const progress = CREATE_START_PROGRESS + ((i + 1) / missingMandatoryRoles.length) * progressRange;
onProgress?.(progress, `Création rôle obligatoire ${i + 1}/${missingMandatoryRoles.length} - ${roleName}`);
}
return officeRoles;
}
private static async importOfficeRoles(office: any, ruleGroups: any[], onProgress?: (progress: number, description?: string) => void): Promise<any[]> {
console.log('Importing office roles');
let officeRoles: any[] = [];
const officeUid = office.processData?.uid;
if (!officeUid) {
console.error('Office UID is not set');
return officeRoles;
}
console.log(`Processing ${ruleGroups.length} rule groups for office ${officeUid}`);
const INIT_PROGRESS = 0;
const FETCH_PROGRESS = 30;
const CREATE_END_PROGRESS = 90;
const FINAL_PROGRESS = 100;
onProgress?.(INIT_PROGRESS, 'Initialisation');
let page = 1;
let limit = 10;
let totalPages = 1;
onProgress?.(FETCH_PROGRESS, 'Récupération des rôles d\'office existants');
let result = await DatabaseService.getTableData('office_roles', page, limit);
if (result && result.success && result.pagination) {
totalPages = result.pagination.totalPages || 1;
}
const FETCH_PAGE_PROGRESS_START = FETCH_PROGRESS;
const FETCH_PAGE_PROGRESS_END = 60;
const CREATE_START_PROGRESS = 60;
// Collect all office roles for this office from all pages
const allOfficeRolesForThisOffice: any[] = [];
while (result && result.success) {
const fetchPageProgress = FETCH_PAGE_PROGRESS_START + ((page / totalPages) * (FETCH_PAGE_PROGRESS_END - FETCH_PAGE_PROGRESS_START));
onProgress?.(fetchPageProgress, `Page ${page}/${totalPages} : Récupération des rôles d'office`);
// Collect office roles for this office from current page
const officeRolesFromPage = result.data.filter((officeRole: any) =>
officeRole.office?.uid === officeUid
);
allOfficeRolesForThisOffice.push(...officeRolesFromPage);
if (!result.pagination.hasNextPage) {
break;
}
page++;
result = await DatabaseService.getTableData('office_roles', page, limit);
}
console.log(`Found ${allOfficeRolesForThisOffice.length} office roles in database for this office`);
if (allOfficeRolesForThisOffice.length === 0) {
console.log('No office roles found in database, creating defaults');
return await this.importDefaultRoles(officeUid, ruleGroups, onProgress);
}
// Get all existing office role processes (to avoid duplicates)
const existingOfficeRoles: any[] = await OfficeRoleService.getOfficeRoles();
const existingOfficeRoleUids = existingOfficeRoles.map((existingRole: any) =>
existingRole.processData.uid
);
console.log(`Found ${existingOfficeRoles.length} existing office role processes`);
// Import all office roles found in database (if not already imported)
const dbRolesToImport = allOfficeRolesForThisOffice.filter((dbRole: any) =>
!existingOfficeRoleUids.includes(dbRole.uid)
);
console.log(`Importing ${dbRolesToImport.length} new office roles from database`);
for (let i = 0; i < dbRolesToImport.length; i++) {
const roleData = dbRolesToImport[i];
// Ensure office UID is set correctly
if (!roleData.office) {
roleData.office = { uid: officeUid };
} else if (!roleData.office.uid) {
roleData.office.uid = officeUid;
}
console.log(`Importing office role: ${roleData.name}`);
officeRoles.push((await OfficeRoleService.createOfficeRole(roleData, DEFAULT_VALIDATOR_ID)).processData);
const progressRange = (CREATE_END_PROGRESS - CREATE_START_PROGRESS) * 0.7; // 70% for db imports
const progress = CREATE_START_PROGRESS + ((i + 1) / dbRolesToImport.length) * progressRange;
onProgress?.(progress, `Import base de données ${i + 1}/${dbRolesToImport.length} - ${roleData.name}`);
}
// Now check for mandatory roles and create any missing ones
const mandatoryRolesProgress = CREATE_START_PROGRESS + (CREATE_END_PROGRESS - CREATE_START_PROGRESS) * 0.7;
onProgress?.(mandatoryRolesProgress, 'Vérification des rôles obligatoires');
const defaultRolesCreated = await this.importDefaultRoles(officeUid, ruleGroups, (subProgress, description) => {
// Map sub-progress to remaining 20% of total progress
const mappedProgress = mandatoryRolesProgress + (subProgress - 60) * 0.3 / 30; // Scale 60-90 to remaining 30%
onProgress?.(mappedProgress, description);
});
officeRoles.push(...defaultRolesCreated);
onProgress?.(FINAL_PROGRESS, 'Importation des rôles d\'office terminée');
return officeRoles;
}
}

View File

@ -1,45 +0,0 @@
class LoaderService {
private static instance: LoaderService;
private _isVisible: boolean = false;
private _callbacks: Array<(isVisible: boolean) => void> = [];
private constructor() { }
public static getInstance(): LoaderService {
if (!LoaderService.instance) {
LoaderService.instance = new LoaderService();
}
return LoaderService.instance;
}
public show(): void {
this._isVisible = true;
this._notifySubscribers();
}
public hide(): void {
this._isVisible = false;
this._notifySubscribers();
}
public get isVisible(): boolean {
return this._isVisible;
}
public subscribe(callback: (isVisible: boolean) => void): () => void {
this._callbacks.push(callback);
// Return unsubscribe function
return () => {
this._callbacks = this._callbacks.filter(cb => cb !== callback);
};
}
private _notifySubscribers(): void {
this._callbacks.forEach(callback => {
callback(this._isVisible);
});
}
}
export default LoaderService;

View File

@ -1,38 +0,0 @@
@keyframes spin {
to {
transform: rotate(1turn);
}
}
.loader-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(255, 255, 255, 0.7);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
}
.loader {
display: flex;
flex-direction: column;
align-items: center;
background-color: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.message {
margin-top: 1rem;
font-size: 1rem;
color: #333;
}
.spinner {
animation: spin 1s infinite linear;
}

View File

@ -1,37 +0,0 @@
import React, { useEffect, useState } from "react";
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import LoaderService from "./LoaderService";
import classes from "./classes.module.scss";
// Composant fusionné qui gère à la fois l'abonnement au service et l'affichage
const Loader: React.FC = () => {
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
// S'abonner aux changements d'état du loader
const unsubscribe = LoaderService.getInstance().subscribe((visible) => {
setIsVisible(visible);
});
// Nettoyage de l'abonnement
return () => {
unsubscribe();
};
}, []);
// Ne rien afficher si le loader n'est pas visible
if (!isVisible) return null;
// Affichage du loader avec overlay
return (
<div className={classes["loader-container"]}>
<div className={classes["loader"]}>
<ArrowPathIcon className={classes["spinner"]} width={40} />
</div>
</div>
);
};
export default Loader;

View File

@ -1,109 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import MessageBus from 'src/sdk/MessageBus';
import User from 'src/sdk/User';
export default class NoteService {
private static readonly messageBus: MessageBus = MessageBus.getInstance();
private constructor() { }
public static createNote(noteData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'note',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...noteData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [...[ownerId], validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: []
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 0.5,
fields: ['idCertified', 'roles'],
min_sig_member: 1,
},
{
quorum: 0.0,
fields: [...privateFields],
min_sig_member: 0,
},
],
storages: []
},
apophis: {
members: [ownerId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
resolve(processCreated);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getNotes(): Promise<any[]> {
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'note' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false');
}
public static getNoteByUid(uid: string): Promise<any> {
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'note' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false').then((processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
const process: any = processes[0];
resolve(process);
}
}).catch(reject);
});
}
public static updateNote(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
resolve();
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,98 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import MessageBus from 'src/sdk/MessageBus';
import User from 'src/sdk/User';
import { FileData } from '../../../../front/Api/Entities/types';
export default class OfficeRibService {
private static readonly messageBus: MessageBus = MessageBus.getInstance();
private constructor() { }
public static createOfficeRib(fileData: FileData, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'officeRib',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...fileData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [...[ownerId], validatorId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: []
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 0.5,
fields: ['idCertified', 'roles'],
min_sig_member: 1,
},
{
quorum: 0.0,
fields: [...privateFields],
min_sig_member: 0,
},
],
storages: []
},
apophis: {
members: [ownerId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
resolve(processCreated);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getOfficeRib(): Promise<any> {
return this.messageBus.getFileByUtype('officeRib');
}
public static updateOfficeRib(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
resolve();
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,150 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import OfficeService from './OfficeService';
import RuleService from './RuleService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class OfficeRoleService extends AbstractService {
private constructor() {
super();
}
public static createOfficeRole(roleData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'officeRole',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...roleData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.01,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 1,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getOfficeRoleByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getOfficeRoles(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_office_roles_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'officeRole' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then(async (processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (let process of processes) {
// Update cache
this.setItem('_office_roles_', process);
items.push(process);
}
return items;
}
});
}
public static getOfficeRoleByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_office_roles_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'officeRole' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => {
if (processes.length !== 1) {
resolve(null);
} else {
// Update cache
this.setItem('_office_roles_', processes[0]);
resolve(process);
}
}).catch(reject);
});
}
public static updateOfficeRole(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const roleUid: string = process.processData.uid;
this.removeItem('_office_roles_', roleUid);
this.getOfficeRoleByUid(roleUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,189 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
export default class OfficeService extends AbstractService {
private constructor() {
super();
}
public static createOffice(officeData: any, owners: string[], validatorId: string, storageUrls: string[]): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
// Create a set for all owners to avoid duplicates
const ownersSet: Set<string> = new Set([...owners, ownerId]);
const processData: any = {
uid: uuidv4(),
utype: 'office',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...officeData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: Array.from(ownersSet),
validation_rules: [],
storages: []
},
owner: {
members: Array.from(ownersSet),
validation_rules: [
{
quorum: 0.01, // effectively any owner can make any change
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 0.01, // need to sign with at least one device
},
],
storages: storageUrls
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1, // validator can do anything alone
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 1,
},
],
storages: storageUrls
},
apophis: {
members: Array.from(ownersSet), // any owner can terminate the office
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getOfficeByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getOffices(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_offices_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'office' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then((processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (const process of processes) {
// Update cache
this.setItem('_offices_', process);
items.push(process);
}
return items;
}
});
}
public static getOfficeByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_offices_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'office' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then((processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
const process: any = processes[0];
// Update cache
this.setItem('_offices_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateDocument(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const officeUid: string = process.processData.uid;
this.removeItem('_offices_', officeUid);
this.getOfficeByUid(officeUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static addCollaborators(process: any, existingRoles: any, collaborators: any[]): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
const newRoles: any = existingRoles;
const owners: string[] = newRoles['owner'].members;
if (!owners) {
console.error('[addCollaborators] owner role not found');
return;
}
const previousOwnersLength: number = owners.length;
for (const collaborator of collaborators) {
if (owners.includes(collaborator)) {
console.debug('[addCollaborators] collaborator already in owner role');
continue;
} else {
owners.push(collaborator);
}
}
if (previousOwnersLength === owners.length) {
console.error('[addCollaborators] no new collaborators added');
return;
}
console.log('newRoles : ', newRoles);
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString() }, [], newRoles).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const officeUid: string = process.processData.uid;
this.removeItem('_offices_', officeUid);
this.getOfficeByUid(officeUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,148 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class RoleService extends AbstractService {
private constructor() {
super();
}
public static createRole(roleData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'role',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...roleData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.01,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 1,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getRoleByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getRoles(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_roles_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'role' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then(async (processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (const process of processes) {
// Update cache
this.setItem('_roles_', process);
items.push(process);
}
return items;
}
});
}
public static getRoleByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_roles_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'role' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
const process: any = processes[0];
// Update cache
this.setItem('_roles_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateRole(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const roleUid: string = process.processData.uid;
this.removeItem('_roles_', roleUid);
this.getRoleByUid(roleUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -1,167 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import RuleService from './RuleService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class RuleGroupService extends AbstractService {
private constructor() {
super();
}
public static createRuleGroup(ruleGroupData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'ruleGroup',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...ruleGroupData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.01,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 1,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getRuleGroupByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getRuleGroups(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_rule_groups_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'ruleGroup' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then(async (processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (let process of processes) {
process = await this.completeRuleGroup(process);
// Update cache
this.setItem('_rule_groups_', process);
items.push(process);
}
return items;
}
});
}
public static getRuleGroupByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_rule_groups_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'ruleGroup' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
let process: any = processes[0];
process = await this.completeRuleGroup(process);
// Update cache
this.setItem('_rule_groups_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateRuleGroup(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const ruleUid: string = process.processData.uid;
this.removeItem('_rule_groups_', ruleUid);
this.getRuleGroupByUid(ruleUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
private static async completeRuleGroup(process: any): Promise<any> {
if (process.processData.rules && process.processData.rules.length > 0) {
process.processData.rules = await new Promise<any[]>(async (resolve: (rules: any[]) => void) => {
const rules: any[] = [];
for (const rule of process.processData.rules) {
rules.push((await RuleService.getRuleByUid(rule.uid)).processData);
}
resolve(rules);
});
}
return process;
}
}

View File

@ -1,148 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class RuleService extends AbstractService {
private constructor() {
super();
}
public static createRule(ruleData: any, validatorId: string): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'rule',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...ruleData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.01,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1,
fields: [...privateFields, 'roles', 'isDeleted', 'uid', 'utype'],
min_sig_member: 1,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
apophis: {
members: [ownerId, validatorId],
validation_rules: [],
storages: []
}
};
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
this.getRuleByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getRules(): Promise<any[]> {
// Check if we have valid cache
const items: any[] = this.getItems('_rules_');
return this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'rule' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then((processes: any[]) => {
if (processes.length === 0) {
return items;
} else {
for (const process of processes) {
// Update cache
this.setItem('_rules_', process);
items.push(process);
}
return items;
}
});
}
public static getRuleByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_rules_', uid);
if (item) {
return Promise.resolve(item);
}
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['uid'] === uid &&
publicValues['utype'] &&
publicValues['utype'] === 'rule' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then((processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
const process: any = processes[0];
// Update cache
this.setItem('_rules_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateRule(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const ruleUid: string = process.processData.uid;
this.removeItem('_rules_', ruleUid);
this.getRuleByUid(ruleUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
}

View File

@ -115,31 +115,4 @@ export default class Auth extends BaseApiService {
return Promise.reject(err); return Promise.reject(err);
} }
} }
public async clientAuth(body: IClientAuthParams): Promise<IClientAuthReturn> {
// Construct the full URL for the client-auth endpoint
// This endpoint is at /api/v1/client-auth, not part of the customer auth namespace
const url = new URL(this.baseURl.concat("/client-auth"));
try {
// Create custom headers for this specific endpoint
const headers = new Headers();
headers.set("Content-Type", "application/json");
headers.set("x-session-id", body.sessionId);
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify({ pairingId: body.pairingId })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
} }

View File

@ -27,13 +27,10 @@ export default class Auth extends BaseApiService {
public async loginWithIdNot() { public async loginWithIdNot() {
const variables = FrontendVariables.getInstance(); const variables = FrontendVariables.getInstance();
let redirectUri = variables.IDNOT_REDIRECT_URI || "";
if (!redirectUri) {
console.warn("[IDNOT] NEXT_PUBLIC_IDNOT_REDIRECT_URI vide; fallback sur FRONT_APP_HOST/authorized-client");
redirectUri = `${variables.FRONT_APP_HOST}/authorized-client`;
}
const url = new URL( const url = new URL(
`${variables.IDNOT_BASE_URL + variables.IDNOT_AUTHORIZE_ENDPOINT}?client_id=${variables.IDNOT_CLIENT_ID}&redirect_uri=${redirectUri}&scope=openid,profile&response_type=code`, `${variables.IDNOT_BASE_URL + variables.IDNOT_AUTHORIZE_ENDPOINT}?client_id=${variables.IDNOT_CLIENT_ID}&redirect_uri=${
variables.FRONT_APP_HOST
}/authorized-client&scope=openid,profile&response_type=code`,
); );
try { try {
return await this.getRequest(url); return await this.getRequest(url);
@ -43,85 +40,12 @@ export default class Auth extends BaseApiService {
} }
} }
public async idNotAuth(autorizationCode: string | string[]): Promise<{ idNotUser: any; authToken: string }> { public async getIdnotJwt(autorizationCode: string | string[]): Promise<{ accessToken: string; refreshToken: string }> {
const variables = FrontendVariables.getInstance(); const variables = FrontendVariables.getInstance();
const baseBackUrl = variables.BACK_API_PROTOCOL + variables.BACK_API_HOST;
const baseBackUrl = this.getBaseUrl(); const url = new URL(`${baseBackUrl}/api/v1/idnot/user/${autorizationCode}`);
const url = new URL(`${baseBackUrl}/idnot/auth`);
const code = Array.isArray(autorizationCode) ? autorizationCode[0] : autorizationCode;
try { try {
return await this.postRequest<{ idNotUser: any; authToken: string }>(url, { code }); return await this.postRequest<{ accessToken: string; refreshToken: string }>(url);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getIdNotUser(): Promise<{ success: boolean; data: any }> {
const variables = FrontendVariables.getInstance();
const baseBackUrl = this.getBaseUrl();
const url = new URL(`${baseBackUrl}/idnot/user`);
try {
return await this.getRequest(url);
}
catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getIdNotOfficeForUser(userId: string): Promise<any[]> {
const variables = FrontendVariables.getInstance();
const baseBackUrl = this.getBaseUrl();
const url = new URL(`${baseBackUrl}/idnot/user/rattachements`);
url.searchParams.set('idNot', userId);
try {
return await this.getRequest(url);
}
catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getIdNotUserForOffice(officeId: string): Promise<any[]> {
const variables = FrontendVariables.getInstance();
const baseBackUrl = this.getBaseUrl();
const url = new URL(`${baseBackUrl}/idnot/office/rattachements`);
url.searchParams.set('idNot', officeId);
try {
return await this.getRequest(url);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getUserProcessByIdNot(pairingId: string): Promise<{ success: boolean; data: { processId: string, processData: { [key: string]: any } } }> {
const variables = FrontendVariables.getInstance();
const baseBackUrl = this.getBaseUrl();
const url = new URL(`${baseBackUrl}/process/user`);
url.searchParams.set('pairingId', pairingId);
try {
return await this.getRequest(url);
} catch (err) {
this.onError(err);
return Promise.reject(err);
}
}
public async getOfficeProcessByIdNot(): Promise<{ success: boolean; data: { processId: string, processData: { [key: string]: any } } }> {
const variables = FrontendVariables.getInstance();
const baseBackUrl = this.getBaseUrl();
const url = new URL(`${baseBackUrl}/process/office`);
try {
return await this.getRequest(url);
} catch (err) { } catch (err) {
this.onError(err); this.onError(err);
return Promise.reject(err); return Promise.reject(err);

View File

@ -1,5 +1,7 @@
import { FrontendVariables } from "@Front/Config/VariablesFront"; import { FrontendVariables } from "@Front/Config/VariablesFront";
import CookieService from "@Front/Services/CookieService/CookieService"; import CookieService from "@Front/Services/CookieService/CookieService";
import jwt_decode from "jwt-decode";
import JwtService, { ICustomerJwtPayload, IUserJwtPayload } from "@Front/Services/JwtService/JwtService";
export enum ContentType { export enum ContentType {
JSON = "application/json", JSON = "application/json",
@ -16,15 +18,11 @@ export default abstract class BaseApiService {
protected readonly variables = FrontendVariables.getInstance(); protected readonly variables = FrontendVariables.getInstance();
protected constructor() { protected constructor() {
if (!BaseApiService.baseUrl) { BaseApiService.baseUrl ??=
const protocol = (this.variables.BACK_API_PROTOCOL || '').replace(/:\/\/$/, ''); this.variables.BACK_API_PROTOCOL +
const host = (this.variables.BACK_API_HOST || '').replace(/\/$/, ''); this.variables.BACK_API_HOST +
const port = this.variables.BACK_API_PORT ? `:${this.variables.BACK_API_PORT.replace(/^:/, '')}` : ''; this.variables.BACK_API_ROOT_URL +
const root = `/${(this.variables.BACK_API_ROOT_URL || '')}`.replace(/\/+/g, '/').replace(/\/$/, ''); this.variables.BACK_API_VERSION;
const version = `/${(this.variables.BACK_API_VERSION || '')}`.replace(/\/+/g, '/');
BaseApiService.baseUrl = `${protocol}://${host}${port}${root}${version}`;
}
} }
protected getBaseUrl(): string { protected getBaseUrl(): string {
@ -32,6 +30,15 @@ export default abstract class BaseApiService {
} }
protected buildHeaders(contentType: ContentType) { protected buildHeaders(contentType: ContentType) {
// Don't try to access cookies during server-side rendering
if (typeof window === 'undefined') {
const headers = new Headers();
if (contentType === ContentType.JSON || contentType === ContentType.PDF) {
headers.set("Content-Type", contentType);
}
return headers;
}
const token = CookieService.getInstance().getCookie("leCoffreAccessToken"); const token = CookieService.getInstance().getCookie("leCoffreAccessToken");
const headers = new Headers(); const headers = new Headers();
@ -39,7 +46,14 @@ export default abstract class BaseApiService {
if (contentType === ContentType.JSON || contentType === ContentType.PDF) { if (contentType === ContentType.JSON || contentType === ContentType.PDF) {
headers.set("Content-Type", contentType); headers.set("Content-Type", contentType);
} }
// Only set Authorization header if token exists
if (token) {
headers.set("Authorization", `Bearer ${token}`); headers.set("Authorization", `Bearer ${token}`);
} else {
console.warn("No access token found in cookies when building headers");
}
return headers; return headers;
} }
@ -47,7 +61,8 @@ export default abstract class BaseApiService {
return JSON.stringify(body); return JSON.stringify(body);
} }
protected async getRequest<T>(url: URL, contentType?: ContentType, ref?: IRef, fileName?: string) { protected async getRequest<T>(url: URL, token?: string, contentType?: ContentType, ref?: IRef, fileName?: string) {
await this.checkJwtToken();
const request = async () => const request = async () =>
await fetch(url, { await fetch(url, {
method: "GET", method: "GET",
@ -56,7 +71,8 @@ export default abstract class BaseApiService {
return this.sendRequest<T>(request, ref, fileName); return this.sendRequest<T>(request, ref, fileName);
} }
protected async postRequest<T>(url: URL, body: { [key: string]: unknown } = {}) { protected async postRequest<T>(url: URL, body: { [key: string]: unknown } = {}, token?: string) {
await this.checkJwtToken();
return this.sendRequest<T>( return this.sendRequest<T>(
async () => async () =>
await fetch(url, { await fetch(url, {
@ -68,6 +84,7 @@ export default abstract class BaseApiService {
} }
protected async postRequestFormData<T>(url: URL, body: FormData) { protected async postRequestFormData<T>(url: URL, body: FormData) {
await this.checkJwtToken();
return this.sendRequest<T>( return this.sendRequest<T>(
async () => async () =>
await fetch(url, { await fetch(url, {
@ -79,6 +96,7 @@ export default abstract class BaseApiService {
} }
protected async putRequest<T>(url: URL, body: { [key: string]: unknown } = {}, token?: string) { protected async putRequest<T>(url: URL, body: { [key: string]: unknown } = {}, token?: string) {
await this.checkJwtToken();
const request = async () => const request = async () =>
await fetch(url, { await fetch(url, {
method: "PUT", method: "PUT",
@ -90,6 +108,7 @@ export default abstract class BaseApiService {
} }
protected async patchRequest<T>(url: URL, body: { [key: string]: unknown } = {}) { protected async patchRequest<T>(url: URL, body: { [key: string]: unknown } = {}) {
await this.checkJwtToken();
const request = async () => const request = async () =>
await fetch(url, { await fetch(url, {
method: "PATCH", method: "PATCH",
@ -101,6 +120,7 @@ export default abstract class BaseApiService {
} }
protected async deleteRequest<T>(url: URL, body: { [key: string]: unknown } = {}, token?: string) { protected async deleteRequest<T>(url: URL, body: { [key: string]: unknown } = {}, token?: string) {
await this.checkJwtToken();
const request = async () => const request = async () =>
await fetch(url, { await fetch(url, {
method: "DELETE", method: "DELETE",
@ -112,6 +132,7 @@ export default abstract class BaseApiService {
} }
protected async putFormDataRequest<T>(url: URL, body: FormData, token?: string) { protected async putFormDataRequest<T>(url: URL, body: FormData, token?: string) {
await this.checkJwtToken();
const request = async () => const request = async () =>
await fetch(url, { await fetch(url, {
method: "PUT", method: "PUT",
@ -128,6 +149,69 @@ export default abstract class BaseApiService {
return this.processResponse<T>(response, request, ref, fileName); return this.processResponse<T>(response, request, ref, fileName);
} }
private async checkJwtToken() {
// Don't check tokens during server-side rendering
if (typeof window === 'undefined') {
return;
}
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
if (!accessToken) {
console.warn("No access token found during JWT check");
return;
}
try {
const userDecodedToken = jwt_decode(accessToken) as IUserJwtPayload;
const customerDecodedToken = jwt_decode(accessToken) as ICustomerJwtPayload;
if (!userDecodedToken && !customerDecodedToken) {
console.warn("Invalid token format during JWT check");
return;
}
const now = Math.floor(Date.now() / 1000);
if (userDecodedToken.userId && userDecodedToken.exp < now) {
const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
if (!refreshToken) {
console.warn("Access token expired but no refresh token found");
return;
}
const decodedRefreshToken = jwt_decode(refreshToken) as IUserJwtPayload | ICustomerJwtPayload;
if (decodedRefreshToken.exp < now) {
console.warn("Both access and refresh tokens are expired");
return;
}
const refreshSuccess = await JwtService.getInstance().refreshToken(refreshToken);
if (!refreshSuccess) {
console.error("Failed to refresh token");
return;
}
}
if (customerDecodedToken.customerId && customerDecodedToken.exp < now) {
const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
if (!refreshToken) {
console.warn("Access token expired but no refresh token found");
return;
}
const decodedRefreshToken = jwt_decode(refreshToken) as IUserJwtPayload | ICustomerJwtPayload;
if (decodedRefreshToken.exp < now) {
console.warn("Both access and refresh tokens are expired");
return;
}
const refreshSuccess = await JwtService.getInstance().refreshToken(refreshToken);
if (!refreshSuccess) {
console.error("Failed to refresh token");
return;
}
}
} catch (error) {
console.error("Error during JWT token check:", error);
}
}
protected async processResponse<T>(response: Response, request: () => Promise<Response>, ref?: IRef, fileName?: string): Promise<T> { protected async processResponse<T>(response: Response, request: () => Promise<Response>, ref?: IRef, fileName?: string): Promise<T> {
let responseContent: T; let responseContent: T;
ref && (ref["response"] = response); ref && (ref["response"] = response);

View File

@ -1,2 +0,0 @@
export * from './types';
export * from './rule';

View File

@ -1,21 +0,0 @@
/**
* FileBlob interface representing a file's binary data and metadata
* Used for file transmission and storage in the application
*/
export interface FileBlob {
/** MIME type of the file (e.g., "application/pdf", "image/jpeg") */
type: string;
/** Binary data of the file as Uint8Array */
data: Uint8Array;
}
/**
* FileData interface representing a complete file object with blob and metadata
* Used when creating or updating files in the system
*/
export interface FileData {
/** The file blob containing type and binary data */
file_blob: FileBlob;
/** The name of the file */
file_name: string;
}

View File

@ -2,7 +2,6 @@ import { Contact, Customer } from "le-coffre-resources/dist/Notary";
import BaseNotary from "../BaseNotary"; import BaseNotary from "../BaseNotary";
import { ECivility } from "le-coffre-resources/dist/Customer/Contact"; import { ECivility } from "le-coffre-resources/dist/Customer/Contact";
import { FrontendVariables } from "@Front/Config/VariablesFront";
// TODO Type get query params -> Where + inclue + orderby // TODO Type get query params -> Where + inclue + orderby
export interface IGetCustomersparams { export interface IGetCustomersparams {
@ -89,15 +88,10 @@ export default class Customers extends BaseNotary {
} }
} }
public async sendReminder(office: any, customer: any): Promise<void> { public async sendReminder(uid: string, documentsUid: string[]): Promise<void> {
const variables = FrontendVariables.getInstance(); const url = new URL(this.baseURl.concat(`/${uid}/send_reminder`));
const baseBackUrl = `${variables.BACK_API_PROTOCOL}://${variables.BACK_API_HOST}:${variables.BACK_API_PORT}${variables.BACK_API_ROOT_URL}${variables.BACK_API_VERSION}`;
const url = new URL(`${baseBackUrl}/api/send_reminder`);
//const url = new URL(this.baseURl.concat(`/${uid}/send_reminder`));
try { try {
await this.postRequest<void>(url, { office, customer }); await this.postRequest<void>(url, { documentsUid });
} catch (err) { } catch (err) {
this.onError(err); this.onError(err);
return Promise.reject(err); return Promise.reject(err);

View File

@ -14,15 +14,10 @@ import classNames from "classnames";
import Button, { EButtonstyletype, EButtonVariant } from "../Button"; import Button, { EButtonstyletype, EButtonVariant } from "../Button";
import Confirm from "../OldModal/Confirm"; import Confirm from "../OldModal/Confirm";
import Documents from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";
import Files from "@Front/Api/LeCoffreApi/Customer/Files/Files";
import Alert from "../OldModal/Alert"; import Alert from "../OldModal/Alert";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";
type IProps = { type IProps = {
onChange?: (files: File[]) => void; onChange?: (files: File[]) => void;
open: boolean; open: boolean;
@ -211,91 +206,35 @@ export default class DepositOtherDocument extends React.Component<IProps, IState
this.setState({ this.setState({
isLoading: true, isLoading: true,
}); });
const filesArray = this.state.currentFiles; const filesArray = this.state.currentFiles;
if (!filesArray) return;
LoaderService.getInstance().show(); if (!filesArray) return;
let documentCreated: any; let documentCreated: Document = {} as Document;
try { try {
documentCreated = await new Promise<any>((resolve: (document: any) => void) => { documentCreated = await Documents.getInstance().post({
const documentTypeData: any = {
folder: { folder: {
uid: this.props.folder_uid, uid: this.props.folder_uid,
}, },
depositor: { depositor: {
uid: this.props.customer_uid, uid: this.props.customer_uid,
} },
};
DocumentService.createDocument(documentTypeData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
if (processCreated) {
const document: any = processCreated.processData;
resolve(document);
}
});
}); });
} catch (e) { } catch (e) {
this.setState({ showFailedDocument: "Le dossier est vérifié aucune modification n'est acceptée", isLoading: false }); this.setState({ showFailedDocument: "Le dossier est vérifié aucune modification n'est acceptée", isLoading: false });
return; return;
} }
const customer: any = await new Promise<void>((resolve: (customer: any) => void) => {
CustomerService.getCustomerByUid(this.props.customer_uid).then((process: any) => {
if (process) {
const customer: any = process.processData;
resolve(customer);
}
});
});
for (let i = 0; i < filesArray.length; i++) { for (let i = 0; i < filesArray.length; i++) {
const file = filesArray[i]!.file; const formData = new FormData();
await new Promise<void>((resolve: () => void) => { formData.append("file", filesArray[i]!.file, filesArray[i]!.fileName);
const reader = new FileReader(); const query = JSON.stringify({ document: { uid: documentCreated.uid } });
reader.onload = (event) => { formData.append("q", query);
if (event.target?.result) { try {
const date: Date = new Date(); await Files.getInstance().post(formData);
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`; } catch (e) {
this.setState({ showFailedUploaded: "Le fichier ne correspond pas aux critères demandés", isLoading: false });
const fileName: string = `${file.name.split('.')[0]}_${strDate}.${file.name.split('.').pop()}`; return;
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
const fileBlob: any = {
type: file.type,
data: uint8Array
};
const fileData: any = {
file_blob: fileBlob,
file_name: fileName
};
FileService.createFile(fileData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
const fileUid: string = processCreated.processData.uid;
DocumentService.getDocumentByUid(documentCreated.uid).then((process: any) => {
if (process) {
const document: any = process.processData;
let files: any[] = document.files;
if (!files) {
files = [];
} }
files.push({ uid: fileUid });
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => {
FolderService.refreshFolderByUid(document.folder.uid).then(() => resolve());
});
}
});
});
}
};
reader.readAsArrayBuffer(file);
});
} }
this.setState({ this.setState({

View File

@ -213,9 +213,9 @@ export default function DragAndDrop(props: IProps) {
</div> </div>
{documentFiles.length > 0 && ( {documentFiles.length > 0 && (
<div className={classes["documents"]}> <div className={classes["documents"]}>
{documentFiles.map((documentFile, index) => ( {documentFiles.map((documentFile) => (
<DocumentFileElement <DocumentFileElement
key={documentFile.uid || `${documentFile.id}-${index}`} key={documentFile.id}
isLoading={documentFile.isLoading} isLoading={documentFile.isLoading}
file={documentFile.file} file={documentFile.file}
onRemove={() => handleRemove(documentFile)} onRemove={() => handleRemove(documentFile)}

View File

@ -1,4 +1,6 @@
import { AppRuleActions, AppRuleNames } from "@Front/Api/Entities/rule"; import { AppRuleActions, AppRuleNames } from "@Front/Api/Entities/rule";
import Notifications from "@Front/Api/LeCoffreApi/Notary/Notifications/Notifications";
import OfficeFolderAnchors from "@Front/Api/LeCoffreApi/Notary/OfficeFolderAnchors/OfficeFolderAnchors";
import Rules, { RulesMode } from "@Front/Components/Elements/Rules"; import Rules, { RulesMode } from "@Front/Components/Elements/Rules";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import Toasts from "@Front/Stores/Toasts"; import Toasts from "@Front/Stores/Toasts";
@ -15,7 +17,6 @@ export default function Navigation() {
const pathname = usePathname(); const pathname = usePathname();
const getAnchoringStatus = useCallback(async () => { const getAnchoringStatus = useCallback(async () => {
/* TODO: review
const anchors = await OfficeFolderAnchors.getInstance().get({ const anchors = await OfficeFolderAnchors.getInstance().get({
where: { where: {
status: { status: {
@ -26,10 +27,7 @@ export default function Navigation() {
folder: true, folder: true,
}, },
}); });
*/
// const anchors = [] as any[];
/* TODO: review
try { try {
for (const anchor of anchors) { for (const anchor of anchors) {
await OfficeFolderAnchors.getInstance().getByUid(anchor.folder?.uid as string); await OfficeFolderAnchors.getInstance().getByUid(anchor.folder?.uid as string);
@ -37,13 +35,10 @@ export default function Navigation() {
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
*/
}, []); }, []);
const getNotifications = useCallback(async () => { const getNotifications = useCallback(async () => {
//await getAnchoringStatus(); //await getAnchoringStatus();
/* TODO: review
const notifications = await Notifications.getInstance().get({ const notifications = await Notifications.getInstance().get({
where: { where: {
read: false, read: false,
@ -55,9 +50,6 @@ export default function Navigation() {
notification: { created_at: "desc" }, notification: { created_at: "desc" },
}, },
}); });
*/
const notifications = [] as any[];
notifications.forEach((notification) => { notifications.forEach((notification) => {
Toasts.getInstance().open({ Toasts.getInstance().open({
title: notification.notification.message, title: notification.notification.message,

View File

@ -8,7 +8,6 @@ import MenuItem from "@Front/Components/DesignSystem/Menu/MenuItem";
type IProps = { type IProps = {
isOpen: boolean; isOpen: boolean;
closeModal: () => void; closeModal: () => void;
isCustomer?: boolean;
}; };
type IState = {}; type IState = {};
@ -20,31 +19,29 @@ export default class ProfileModal extends React.Component<IProps, IState> {
<> <>
<div className={classes["background"]} onClick={this.props.closeModal} /> <div className={classes["background"]} onClick={this.props.closeModal} />
<div className={classes["root"]}> <div className={classes["root"]}>
{!this.props.isCustomer && <MenuItem <MenuItem
item={{ item={{
text: "Mon compte", text: "Mon compte",
link: Module.getInstance().get().modules.pages.MyAccount.props.path, link: Module.getInstance().get().modules.pages.MyAccount.props.path,
}} }}
/>} />
{!this.props.isCustomer && <MenuItem <MenuItem
item={{ item={{
text: "Guide de Prise en Main", text: "Guide de Prise en Main",
link: "https://ressources.lecoffre.io/", link: "https://ressources.lecoffre.io/",
target: "_blank", target: "_blank",
}} }}
/>} />
<MenuItem
{!this.props.isCustomer && <MenuItem
item={{ item={{
text: "CGU", text: "CGU",
link: "/CGU_LeCoffre_io.pdf", link: "/CGU_LeCoffre_io.pdf",
hasSeparator: true, hasSeparator: true,
}} }}
/>} />
<LogOutButton />
<LogOutButton isCustomer={this.props.isCustomer} />
</div> </div>
</> </>
); );

View File

@ -9,7 +9,7 @@ import ProfileModal from "./ProfileModal";
const headerBreakpoint = 1023; const headerBreakpoint = 1023;
export default function Profile(props: { isCustomer?: boolean }) { export default function Profile() {
const { isOpen, toggle, close } = useOpenable(); const { isOpen, toggle, close } = useOpenable();
useEffect(() => { useEffect(() => {
@ -27,7 +27,7 @@ export default function Profile(props: { isCustomer?: boolean }) {
return ( return (
<div className={classes["root"]}> <div className={classes["root"]}>
<IconButton icon={<UserIcon />} onClick={toggle} /> <IconButton icon={<UserIcon />} onClick={toggle} />
<ProfileModal isOpen={isOpen} closeModal={close} isCustomer={props.isCustomer} /> <ProfileModal isOpen={isOpen} closeModal={close} />
</div> </div>
); );
} }

View File

@ -1,16 +1,17 @@
import LogoIcon from "@Assets/logo_standard_neutral.svg"; import LogoIcon from "@Assets/logo_standard_neutral.svg";
// import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe"; import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe";
// import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions"; import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
// import JwtService from "@Front/Services/JwtService/JwtService"; import JwtService from "@Front/Services/JwtService/JwtService";
import { LifebuoyIcon } from "@heroicons/react/24/outline"; import { InformationCircleIcon, LifebuoyIcon } from "@heroicons/react/24/outline";
import Head from "next/head"; import Head from "next/head";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import React, { useCallback, useEffect } from "react"; import React, { useCallback, useEffect, useState } from "react";
import IconButton from "../IconButton"; import IconButton from "../IconButton";
import Typography, { ETypo, ETypoColor } from "../Typography";
import BurgerMenu from "./BurgerMenu"; import BurgerMenu from "./BurgerMenu";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import LogoCielNatureIcon from "./logo-ciel-notaires.jpeg"; import LogoCielNatureIcon from "./logo-ciel-notaires.jpeg";
@ -20,22 +21,20 @@ import Profile from "./Profile";
type IProps = { type IProps = {
isUserConnected: boolean; isUserConnected: boolean;
isCustomer?: boolean;
}; };
const headerHeight = 75; const headerHeight = 75;
export default function Header(props: IProps) { export default function Header(props: IProps) {
const { isUserConnected, isCustomer } = props; const { isUserConnected } = props;
const router = useRouter(); const router = useRouter();
const { pathname } = router; const { pathname } = router;
const isOnCustomerLoginPage = Module.getInstance().get().modules.pages.CustomersLogin.props.path === pathname; const isOnCustomerLoginPage = Module.getInstance().get().modules.pages.CustomersLogin.props.path === pathname;
// const [cancelAt, setCancelAt] = useState<Date | null>(null); const [cancelAt, setCancelAt] = useState<Date | null>(null);
const loadSubscription = useCallback(async () => { const loadSubscription = useCallback(async () => {
/* TODO: review
const jwt = JwtService.getInstance().decodeJwt(); const jwt = JwtService.getInstance().decodeJwt();
const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } }); const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
if (subscription[0]) { if (subscription[0]) {
@ -44,7 +43,6 @@ export default function Header(props: IProps) {
setCancelAt(new Date(stripeSubscription.cancel_at! * 1000)); setCancelAt(new Date(stripeSubscription.cancel_at! * 1000));
} }
} }
*/
}, []); }, []);
useEffect(() => { useEffect(() => {
@ -63,7 +61,7 @@ export default function Header(props: IProps) {
<Image src={LogoIcon} alt="logo" className={classes["logo"]} /> <Image src={LogoIcon} alt="logo" className={classes["logo"]} />
</Link> </Link>
</div> </div>
{isUserConnected && !isCustomer && ( {isUserConnected && (
<> <>
<div className={classes["desktop"]}> <div className={classes["desktop"]}>
<Navigation /> <Navigation />
@ -84,14 +82,9 @@ export default function Header(props: IProps) {
</div> </div>
</> </>
)} )}
{isCustomer && (
<div className={classes["desktop"]}>
<Profile isCustomer={isCustomer} />
</div>
)}
{isOnCustomerLoginPage && <Image width={70} height={70} alt="ciel-nature" src={LogoCielNatureIcon}></Image>} {isOnCustomerLoginPage && <Image width={70} height={70} alt="ciel-nature" src={LogoCielNatureIcon}></Image>}
</div> </div>
{/* {cancelAt && ( {cancelAt && (
<div className={classes["subscription-line"]}> <div className={classes["subscription-line"]}>
<InformationCircleIcon height="24" /> <InformationCircleIcon height="24" />
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_GENERIC_BLACK}> <Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_GENERIC_BLACK}>
@ -99,7 +92,7 @@ export default function Header(props: IProps) {
{cancelAt.toLocaleDateString()}. {cancelAt.toLocaleDateString()}.
</Typography> </Typography>
</div> </div>
)} */} )}
</> </>
); );
} }

View File

@ -6,18 +6,14 @@ import React, { useCallback } from "react";
import MenuItem from "../Menu/MenuItem"; import MenuItem from "../Menu/MenuItem";
export default function LogOut(props: { isCustomer?: boolean }) { export default function LogOut() {
const router = useRouter(); const router = useRouter();
const variables = FrontendVariables.getInstance(); const variables = FrontendVariables.getInstance();
const disconnect = useCallback(() => { const disconnect = useCallback(() => {
if (!props.isCustomer) {
UserStore.instance UserStore.instance
.disconnect() .disconnect()
.then(() => router.push(`https://qual-connexion.idnot.fr/user/auth/logout?sourceURL=${variables.FRONT_APP_HOST}`)); .then(() => router.push(`https://qual-connexion.idnot.fr/user/auth/logout?sourceURL=${variables.FRONT_APP_HOST}`));
} else {
router.push("/");
}
}, [router, variables.FRONT_APP_HOST]); }, [router, variables.FRONT_APP_HOST]);
return <MenuItem item={{ text: "Déconnexion", icon: <PowerIcon />, onClick: disconnect }} />; return <MenuItem item={{ text: "Déconnexion", icon: <PowerIcon />, onClick: disconnect }} />;

View File

@ -4,8 +4,6 @@ import { IAppRule } from "@Front/Api/Entities/rule";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import UserStore from "@Front/Stores/UserStore";
export enum RulesMode { export enum RulesMode {
OPTIONAL = "optional", OPTIONAL = "optional",
NECESSARY = "necessary", NECESSARY = "necessary",
@ -22,23 +20,18 @@ export default function Rules(props: IProps) {
const router = useRouter(); const router = useRouter();
const [isShowing, setIsShowing] = React.useState(false); const [isShowing, setIsShowing] = React.useState(false);
// const [hasJwt, setHasJwt] = React.useState(false); const [hasJwt, setHasJwt] = React.useState(false);
const getShowValue = useCallback(() => { const getShowValue = useCallback(() => {
//const user: any = UserStore.instance.getUser();
if (props.mode === RulesMode.NECESSARY) { if (props.mode === RulesMode.NECESSARY) {
//return user.isAdmin && user.isAdmin === 'true';
return props.rules.every((rule) => JwtService.getInstance().hasRule(rule.name, rule.action)); return props.rules.every((rule) => JwtService.getInstance().hasRule(rule.name, rule.action));
} }
//const ruleNames: string[] = props.rules.map((rule: any) => rule.name);
//return user.role.rules.map((rule: any) => rule.name).filter((ruleName: string) => ruleNames.includes(ruleName)).length > 0;
return props.rules.length === 0 || !!props.rules.find((rule) => JwtService.getInstance().hasRule(rule.name, rule.action)); return props.rules.length === 0 || !!props.rules.find((rule) => JwtService.getInstance().hasRule(rule.name, rule.action));
}, [props.mode, props.rules]); }, [props.mode, props.rules]);
useEffect(() => { useEffect(() => {
// TODO: review if (!JwtService.getInstance().decodeJwt()) return;
//if (!JwtService.getInstance().decodeJwt()) return; setHasJwt(true);
// setHasJwt(true);
setIsShowing(getShowValue()); setIsShowing(getShowValue());
}, [getShowValue, isShowing]); }, [getShowValue, isShowing]);
@ -47,8 +40,7 @@ export default function Rules(props: IProps) {
return null; return null;
} }
// TODO: review if (!hasJwt || !isShowing) return null;
//if (!hasJwt || !isShowing) return null;
return props.children; return props.children;
} }

View File

@ -57,13 +57,6 @@ export default function Tabs<T>({ onSelect, tabs: propsTabs }: IProps<T>) {
useEffect(() => { useEffect(() => {
tabs.current = propsTabs; tabs.current = propsTabs;
if (tabs.current && tabs.current.length > 0 && tabs.current[0]) {
setSelectedTab(tabs.current[0].value);
onSelect(tabs.current[0].value);
setTimeout(() => calculateVisibleElements(), 100);
}
}, [propsTabs]); }, [propsTabs]);
useEffect(() => { useEffect(() => {

View File

@ -2,12 +2,11 @@ import React, { useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import UserStore from "@Front/Stores/UserStore";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import User from "le-coffre-resources/dist/Notary"; import User from "le-coffre-resources/dist/Notary";
import JwtService from "@Front/Services/JwtService/JwtService";
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService"; import Users, { IGetUsersparams } from "@Front/Api/LeCoffreApi/Admin/Users/Users";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
@ -16,7 +15,6 @@ export default function DefaultCollaboratorDashboard(props: IProps) {
const router = useRouter(); const router = useRouter();
const { collaboratorUid } = router.query; const { collaboratorUid } = router.query;
useEffect(() => { useEffect(() => {
/* TODO: review
const jwt = JwtService.getInstance().decodeJwt(); const jwt = JwtService.getInstance().decodeJwt();
if (!jwt) return; if (!jwt) return;
const query: IGetUsersparams = { const query: IGetUsersparams = {
@ -30,24 +28,10 @@ export default function DefaultCollaboratorDashboard(props: IProps) {
}, },
}, },
}; };
Users.getInstance() Users.getInstance()
.get(query) .get(query)
.then((users) => setCollaborators(users)); .then((users) => setCollaborators(users));
*/
const user: any = UserStore.instance.getUser();
const officeId: string = user.office.uid;
CollaboratorService.getCollaborators((processes: any[]) => {
if (processes.length > 0) {
let collaborators: any[] = processes.map((process: any) => process.processData);
// FilterBy office.uid
collaborators = collaborators.filter((collaborator: any) => collaborator.office.uid === officeId);
setCollaborators(collaborators);
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {

View File

@ -1,3 +1,4 @@
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import JwtService from "@Front/Services/JwtService/JwtService"; import JwtService from "@Front/Services/JwtService/JwtService";
@ -7,22 +8,17 @@ import React, { useEffect, useState } from "react";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService"; type IProps = IPropsDashboardWithList & {};
type IProps = IPropsDashboardWithList & {
isReady: boolean;
};
export default function DefaultCustomerDashboard(props: IProps) { export default function DefaultCustomerDashboard(props: IProps) {
const router = useRouter(); const router = useRouter();
const { folderUid, profileUid } = router.query; const { folderUid } = router.query;
const [folders, setFolders] = useState<OfficeFolder[]>([]); const [folders, setFolders] = useState<OfficeFolder[]>([]);
useEffect(() => { useEffect(() => {
//const jwt = JwtService.getInstance().decodeCustomerJwt(); const jwt = JwtService.getInstance().decodeCustomerJwt();
//if (!jwt) return; if (!jwt) return;
/*
Folders.getInstance() Folders.getInstance()
.get({ .get({
q: { q: {
@ -46,21 +42,7 @@ export default function DefaultCustomerDashboard(props: IProps) {
}, },
}) })
.then((folders) => setFolders(folders)); .then((folders) => setFolders(folders));
*/ }, []);
if (props.isReady) {
FolderService.getFolders((processes: any[]) => {
if (processes.length > 0) {
let folders: any[] = processes.map((process: any) => process.processData);
// Filter By customer.uid
folders = folders.filter((folder: any) => folder.customers.some((customer: any) => customer.uid === profileUid));
setFolders(folders);
}
});
}
}, [props.isReady]);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {
const folder = folders.find((folder) => folder.uid === block.id); const folder = folders.find((folder) => folder.uid === block.id);
@ -68,12 +50,10 @@ export default function DefaultCustomerDashboard(props: IProps) {
router.push( router.push(
Module.getInstance() Module.getInstance()
.get() .get()
.modules.pages.ClientDashboard.props.path .modules.pages.ClientDashboard.props.path.replace("[folderUid]", folder.uid ?? ""),
.replace("[folderUid]", folder.uid ?? "")
.replace("[profileUid]", profileUid as string ?? ""),
); );
}; };
return <DefaultDashboardWithList {...props} onSelectedBlock={onSelectedBlock} blocks={getBlocks(folders)} headerConnected={false} isCustomer={true} />; return <DefaultDashboardWithList {...props} onSelectedBlock={onSelectedBlock} blocks={getBlocks(folders)} headerConnected={false}/>;
function getBlocks(folders: OfficeFolder[]): IBlock[] { function getBlocks(folders: OfficeFolder[]): IBlock[] {
return folders.map((folder) => { return folders.map((folder) => {

View File

@ -15,7 +15,6 @@ export type IPropsDashboardWithList = {
mobileBackText?: string; mobileBackText?: string;
headerConnected?: boolean; headerConnected?: boolean;
noPadding?: boolean; noPadding?: boolean;
isCustomer?: boolean;
}; };
type IProps = IPropsDashboardWithList & ISearchBlockListProps; type IProps = IPropsDashboardWithList & ISearchBlockListProps;
@ -30,12 +29,11 @@ export default function DefaultDashboardWithList(props: IProps) {
headerConnected = true, headerConnected = true,
bottomButton, bottomButton,
noPadding = false, noPadding = false,
isCustomer = false,
} = props; } = props;
return ( return (
<div className={classes["root"]}> <div className={classes["root"]}>
<Header isUserConnected={headerConnected} isCustomer={isCustomer} /> <Header isUserConnected={headerConnected} />
<div className={classes["content"]}> <div className={classes["content"]}>
<SearchBlockList blocks={blocks} onSelectedBlock={onSelectedBlock} bottomButton={bottomButton} /> <SearchBlockList blocks={blocks} onSelectedBlock={onSelectedBlock} bottomButton={bottomButton} />
<div className={classes["right-side"]} data-no-padding={noPadding}> <div className={classes["right-side"]} data-no-padding={noPadding}>

View File

@ -5,40 +5,31 @@ import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import { DeedType } from "le-coffre-resources/dist/Notary"; import { DeedType } from "le-coffre-resources/dist/Notary";
import DeedTypes, { IGetDeedTypesParams } from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
export default function DefaultDeedTypeDashboard(props: IProps) { export default function DefaultDeedTypeDashboard(props: IProps) {
const router = useRouter();
const { deedTypeUid } = router.query;
const [deedTypes, setDeedTypes] = React.useState<DeedType[] | null>(null); const [deedTypes, setDeedTypes] = React.useState<DeedType[] | null>(null);
const router = useRouter();
const { deedTypeUid } = router.query;
useEffect(() => { useEffect(() => {
DeedTypeService.getDeedTypes((processes: Record<string, any>) => { const query: IGetDeedTypesParams = {
const deedTypes = Object.entries(processes).map(([processId, processData]) => ({ where: {
...processData, archived_at: null,
processId: processId },
})); orderBy: {
if (deedTypes.length > 0) { name: "asc",
deedTypes.filter((deedType: any) => !deedType.archived_at); },
// OrderBy name asc };
deedTypes.sort((a: any, b: any) => a.name.localeCompare(b.name));
setDeedTypes(deedTypes); DeedTypes.getInstance()
} else { .get(query)
console.log('[DefaultDeedTypeDashboard] No deed types found'); .then((deedTypes) => setDeedTypes(deedTypes));
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {
// Remove ':0' suffix from processId for URL navigation router.push(Module.getInstance().get().modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", block.id));
const urlId = idAsUrl(block.id as string);
router.push(Module.getInstance().get().modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", urlId));
}; };
return ( return (
@ -47,19 +38,16 @@ export default function DefaultDeedTypeDashboard(props: IProps) {
onSelectedBlock={onSelectedBlock} onSelectedBlock={onSelectedBlock}
blocks={ blocks={
deedTypes deedTypes
? deedTypes.map((deedType: any) => { ? deedTypes.map((deedTypes) => ({
const urlId = idAsUrl(deedType.processId); id: deedTypes.uid!,
return { primaryText: deedTypes.name,
id: deedType.processId, // Keep full processId for internal use isActive: deedTypes.uid === deedTypeUid,
primaryText: deedType.name, }))
isActive: urlId === deedTypeUid, // Compare without ':0' suffix
};
})
: [] : []
} }
bottomButton={{ bottomButton={{
link: Module.getInstance().get().modules.pages.DeedTypes.pages.Create.props.path, link: Module.getInstance().get().modules.pages.DeedTypes.pages.Create.props.path,
text: "Créer une liste de pièces", // TODO I think this is misleading, should be "Créer un type d'acte" text: "Créer une liste de pièces",
}} }}
/> />
); );

View File

@ -1,14 +1,13 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import JwtService from "@Front/Services/JwtService/JwtService"; import JwtService from "@Front/Services/JwtService/JwtService";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import { DocumentType } from "le-coffre-resources/dist/Notary"; import { DocumentType } from "le-coffre-resources/dist/Notary";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import UserStore from "@Front/Stores/UserStore";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
export default function DefaultDocumentTypeDashboard(props: IProps) { export default function DefaultDocumentTypeDashboard(props: IProps) {
@ -16,22 +15,18 @@ export default function DefaultDocumentTypeDashboard(props: IProps) {
const router = useRouter(); const router = useRouter();
const { documentTypeUid } = router.query; const { documentTypeUid } = router.query;
useEffect(() => { useEffect(() => {
const user: any = UserStore.instance.getUser(); const jwt = JwtService.getInstance().decodeJwt();
const officeId: string = user.office.uid; if (!jwt) return;
DocumentTypes.getInstance()
DocumentTypeService.getDocumentTypes().then((processes: any[]) => { .get({
if (processes.length > 0) { where: {
let documents: any[] = processes.map((process: any) => process.processData); office_uid: jwt.office_Id,
},
// FilterBy office.uid orderBy: {
documents = documents.filter((document: any) => document.office.uid === officeId); name: "asc",
},
// OrderBy name asc })
documents = documents.sort((a: any, b: any) => a.name.localeCompare(b.name)); .then((documentTypes) => setDocumentTypes(documentTypes));
setDocumentTypes(documents);
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {

View File

@ -1,3 +1,4 @@
import Folders, { IGetFoldersParams } from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus"; import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus";
import { OfficeFolder } from "le-coffre-resources/dist/Notary"; import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import React, { useCallback, useEffect } from "react"; import React, { useCallback, useEffect } from "react";
@ -8,9 +9,6 @@ import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";
type IProps = IPropsDashboardWithList & { type IProps = IPropsDashboardWithList & {
isArchived?: boolean; isArchived?: boolean;
}; };
@ -26,11 +24,11 @@ export default function DefaultNotaryDashboard(props: IProps) {
: Module.getInstance().get().modules.pages.Folder.pages.FolderInformation.props.path; : Module.getInstance().get().modules.pages.Folder.pages.FolderInformation.props.path;
const getBlocks = useCallback( const getBlocks = useCallback(
(folders: any[]): IBlock[] => { (folders: OfficeFolder[]): IBlock[] => {
const pendingFolders = folders const pendingFolders = folders
.filter((folder) => { .filter((folder) => {
const pendingDocuments = (folder.documents ?? []).filter( const pendingDocuments = (folder.documents ?? []).filter(
(document: any) => document.document_status === EDocumentStatus.DEPOSITED, (document) => document.document_status === EDocumentStatus.DEPOSITED,
); );
return pendingDocuments.length >= 1; return pendingDocuments.length >= 1;
}) })
@ -41,7 +39,7 @@ export default function DefaultNotaryDashboard(props: IProps) {
const otherFolders = folders const otherFolders = folders
.filter((folder) => { .filter((folder) => {
const pendingDocuments = (folder.documents ?? []).filter( const pendingDocuments = (folder.documents ?? []).filter(
(document: any) => document.document_status === EDocumentStatus.DEPOSITED, (document) => document.document_status === EDocumentStatus.DEPOSITED,
); );
return pendingDocuments.length === 0; return pendingDocuments.length === 0;
}) })
@ -49,18 +47,15 @@ export default function DefaultNotaryDashboard(props: IProps) {
return folder1.created_at! > folder2.created_at! ? -1 : 1; return folder1.created_at! > folder2.created_at! ? -1 : 1;
}); });
const blocks = [...pendingFolders, ...otherFolders].map((folder) => { return [...pendingFolders, ...otherFolders].map((folder) => {
const res = { return {
id: idAsUrl(folder.processId), id: folder.uid!,
primaryText: folder.name, primaryText: folder.name,
secondaryText: folder.folder_number, secondaryText: folder.folder_number,
isActive: folderUid === idAsUrl(folder.processId), isActive: folderUid === folder.uid,
showAlert: folder.documents?.some((document: any) => document.document_status === EDocumentStatus.DEPOSITED), showAlert: folder.documents?.some((document) => document.document_status === EDocumentStatus.DEPOSITED),
}; };
return res;
}); });
return blocks;
}, },
[folderUid], [folderUid],
); );
@ -81,8 +76,6 @@ export default function DefaultNotaryDashboard(props: IProps) {
useEffect(() => { useEffect(() => {
let targetedStatus: EFolderStatus = EFolderStatus["LIVE" as keyof typeof EFolderStatus]; let targetedStatus: EFolderStatus = EFolderStatus["LIVE" as keyof typeof EFolderStatus];
if (isArchived) targetedStatus = EFolderStatus.ARCHIVED; if (isArchived) targetedStatus = EFolderStatus.ARCHIVED;
/* TODO: review
const query: IGetFoldersParams = { const query: IGetFoldersParams = {
q: { q: {
where: { status: targetedStatus }, where: { status: targetedStatus },
@ -117,30 +110,6 @@ export default function DefaultNotaryDashboard(props: IProps) {
Folders.getInstance() Folders.getInstance()
.get(query) .get(query)
.then((folders) => setFolders(folders)); .then((folders) => setFolders(folders));
*/
FolderService.getFolders((processes: Record<string, any>) => {
if (Object.keys(processes).length > 0) {
let folders: any[] = Object.entries(processes).map(([processId, process]) => {
const res = {
...process,
processId: processId
};
return res;
});
// FilterBy status
folders = folders.filter((folder: any) => {
const matches = folder.status === targetedStatus;
return matches;
});
setFolders(folders);
} else {
console.debug('[DefaultNotaryDashboard] No processes found');
}
});
}, [isArchived]); }, [isArchived]);
return ( return (

View File

@ -1,26 +1,22 @@
import { Office } from "le-coffre-resources/dist/SuperAdmin";
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import Offices from "@Front/Api/LeCoffreApi/SuperAdmin/Offices/Offices";
import OfficeService from "src/common/Api/LeCoffreApi/sdk/OfficeService";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
export default function DefaultOfficeDashboard(props: IProps) { export default function DefaultOfficeDashboard(props: IProps) {
const [offices, setOffices] = React.useState<any[] | null>(null); const [offices, setOffices] = React.useState<Office[] | null>(null);
const router = useRouter(); const router = useRouter();
const { officeUid } = router.query; const { officeUid } = router.query;
useEffect(() => { useEffect(() => {
OfficeService.getOffices().then((processes: any[]) => { Offices.getInstance()
if (processes.length > 0) { .get()
const offices: any[] = processes.map((process: any) => process.processData); .then((offices) => setOffices(offices));
setOffices(offices);
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {

View File

@ -4,43 +4,23 @@ import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import { OfficeRole } from "le-coffre-resources/dist/Notary";
import UserStore from "@Front/Stores/UserStore"; import OfficeRoles, { IGetRolesParams } from "@Front/Api/LeCoffreApi/Admin/OfficeRoles/OfficeRoles";
import OfficeRoleService from "src/common/Api/LeCoffreApi/sdk/OfficeRoleService";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
export default function DefaultRoleDashboard(props: IProps) { export default function DefaultRoleDashboard(props: IProps) {
const [roles, setRoles] = React.useState<any[] | null>(null); const [roles, setRoles] = React.useState<OfficeRole[] | null>(null);
const router = useRouter(); const router = useRouter();
const { roleUid } = router.query; const { roleUid } = router.query;
useEffect(() => { useEffect(() => {
const user: any = UserStore.instance.getUser(); const query: IGetRolesParams = {
if (!user) { include: { rules: true },
return; };
}
const office: any = user.office; OfficeRoles.getInstance()
if (!office) { .get(query)
return; .then((roles) => setRoles(roles));
}
OfficeRoleService.getOfficeRoles().then(async (processes: any[]) => {
if (processes.length > 0) {
let officeRoles: any[] = processes.map((process: any) => process.processData);
// FilterBy office.uid
officeRoles = officeRoles.filter((officeRole: any) => officeRole.office.uid === office.uid);
// OrderBy name
officeRoles = officeRoles.sort((a: any, b: any) => a.name.localeCompare(b.name));
setRoles(officeRoles);
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {

View File

@ -1,34 +1,26 @@
import Users, { IGetUsersparams } from "@Front/Api/LeCoffreApi/SuperAdmin/Users/Users";
import User from "le-coffre-resources/dist/SuperAdmin";
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
import UserStore from "@Front/Stores/UserStore";
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";
type IProps = IPropsDashboardWithList; type IProps = IPropsDashboardWithList;
export default function DefaultUserDashboard(props: IProps) { export default function DefaultUserDashboard(props: IProps) {
const [users, setUsers] = React.useState<any[] | null>(null); const [users, setUsers] = React.useState<User[] | null>(null);
const router = useRouter(); const router = useRouter();
const { userUid } = router.query; const { userUid } = router.query;
useEffect(() => { useEffect(() => {
const user: any = UserStore.instance.getUser(); const query: IGetUsersparams = {
if (!user) return; include: { contact: true, office_membership: true },
const officeId: string = user.office.uid; };
CollaboratorService.getCollaborators((processes: any[]) => { Users.getInstance()
if (processes.length > 0) { .get(query)
let collaborators: any[] = processes.map((process: any) => process.processData); .then((users) => setUsers(users));
// FilterBy office.uid
collaborators = collaborators.filter((collaborator: any) => collaborator.office.uid === officeId);
setUsers(collaborators);
}
});
}, []); }, []);
const onSelectedBlock = (block: IBlock) => { const onSelectedBlock = (block: IBlock) => {
@ -45,7 +37,7 @@ export default function DefaultUserDashboard(props: IProps) {
id: user.uid!, id: user.uid!,
primaryText: user.contact?.first_name + " " + user.contact?.last_name, primaryText: user.contact?.first_name + " " + user.contact?.last_name,
isActive: user.uid === userUid, isActive: user.uid === userUid,
secondaryText: user.office?.crpcen + " - " + user.office?.name, secondaryText: user.office_membership?.crpcen + " - " + user.office_membership?.name,
})) }))
: [] : []
} }

View File

@ -6,8 +6,7 @@ import { OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Not
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import OfficeRib from "@Front/Api/LeCoffreApi/Customer/OfficeRib/OfficeRib";
import OfficeRibService from "src/common/Api/LeCoffreApi/sdk/OfficeRibService";
type IProps = { type IProps = {
folder: OfficeFolderNotary; folder: OfficeFolderNotary;
@ -20,7 +19,9 @@ export default function ContactBox(props: IProps) {
const [ribUrl, setRibUrl] = useState<string | null>(null); const [ribUrl, setRibUrl] = useState<string | null>(null);
const notaryContact = useMemo( const notaryContact = useMemo(
() => folder?.stakeholders!.find((stakeholder) => stakeholder.office_role?.name === "Notaire")?.contact ?? folder?.stakeholders![0]!.contact, () =>
folder?.stakeholders!.find((stakeholder) => stakeholder.office_role?.name === "Notaire")?.contact ??
folder?.stakeholders![0]!.contact,
[folder], [folder],
); );
@ -36,13 +37,9 @@ export default function ContactBox(props: IProps) {
useEffect(() => { useEffect(() => {
if (!folder?.office?.uid) return; if (!folder?.office?.uid) return;
OfficeRibService.getOfficeRib().then((process: any) => { OfficeRib.getInstance()
if (process) { .getRibStream(folder.office.uid)
const officeRib: any = process.processData; .then((blob) => setRibUrl(URL.createObjectURL(blob)));
const fileBlob: Blob = new Blob([officeRib.file_blob.data], { type: officeRib.file_blob.type });
setRibUrl(URL.createObjectURL(fileBlob));
}
});
}, [folder]); }, [folder]);
const downloadRib = useCallback(async () => { const downloadRib = useCallback(async () => {

View File

@ -1,178 +1,52 @@
import DragAndDrop, { IDocumentFileWithUid } from "@Front/Components/DesignSystem/DragAndDrop"; import DragAndDrop, { IDocumentFileWithUid } from "@Front/Components/DesignSystem/DragAndDrop";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import { Document } from "le-coffre-resources/dist/Customer";
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document"; import Files from "@Front/Api/LeCoffreApi/Customer/Files/Files";
import { ToasterService } from "@Front/Components/DesignSystem/Toaster"; import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm"; import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import { FileBlob, FileData } from "@Front/Api/Entities/types";
import WatermarkService from "@Front/Services/WatermarkService";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";
type IProps = { type IProps = {
document: any; document: Document;
customer: any;
onChange: () => void; onChange: () => void;
}; };
export default function DepositDocumentComponent(props: IProps) { export default function DepositDocumentComponent(props: IProps) {
const { document, customer, onChange } = props; const { document, onChange } = props;
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const [refused_reason, setRefusedReason] = useState<string | null>(null); const [refused_reason, setRefusedReason] = useState<string | null>(null);
const defaultFiles: IDocumentFileWithUid[] = useMemo(() => { const defaultFiles: IDocumentFileWithUid[] = useMemo(() => {
const filesNotArchived = document.files?.filter((file: any) => !file.archived_at) ?? []; const filesNotArchived = document.files?.filter((file) => !file.archived_at) ?? [];
return filesNotArchived.map((file: any) => ({ return filesNotArchived.map((file) => ({
id: file.uid!, id: file.uid!,
file: new File([""], file.file_name!, { type: file.file_blob.type }), file: new File([""], file.file_name!, { type: file.mimetype }),
uid: file.uid!, uid: file.uid!,
})); }));
}, [document.files]); }, [document.files]);
const addFile = useCallback( const addFile = useCallback(
async (file: File) => { (file: File) => {
try { const formData = new FormData();
// Add watermark to the file before processing const safeFileName = file.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
const watermarkedFile = await WatermarkService.getInstance().addWatermark(file); formData.append("file", file, safeFileName);
const query = JSON.stringify({ document: { uid: document.uid } });
return new Promise<void>( formData.append("q", query);
(resolve: () => void) => { return Files.getInstance()
const reader = new FileReader(); .post(formData)
reader.onload = (event) => {
if (event.target?.result) {
const date: Date = new Date();
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
const fileName: string = `${document.document_type.name}-${customer.contact.last_name}_${strDate}.${file.name.split('.').pop()}`;
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
const fileBlob: FileBlob = {
type: watermarkedFile.type,
data: uint8Array
};
const fileData: FileData = {
file_blob: fileBlob,
file_name: fileName
};
FileService.createFile(fileData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
const fileUid: string = processCreated.processData.uid;
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
if (process) {
const document: any = process.processData;
let files: any[] = document.files;
if (!files) {
files = [];
}
files.push({ uid: fileUid });
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => {
FolderService.refreshFolderByUid(document.folder.uid).then(() => resolve());
});
}
});
});
}
};
reader.readAsArrayBuffer(watermarkedFile);
})
.then(onChange) .then(onChange)
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" })) .then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message })); .catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
} catch (error) {
console.error('Error processing file with watermark:', error);
// If watermarking fails, proceed with original file
return new Promise<void>(
(resolve: () => void) => {
const reader = new FileReader();
reader.onload = (event) => {
if (event.target?.result) {
const date: Date = new Date();
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
const fileName: string = `${document.document_type.name}-${customer.contact.last_name}_${strDate}.${file.name.split('.').pop()}`;
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
const fileBlob: FileBlob = {
type: file.type,
data: uint8Array
};
const fileData: FileData = {
file_blob: fileBlob,
file_name: fileName
};
FileService.createFile(fileData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
const fileUid: string = processCreated.processData.uid;
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
if (process) {
const document: any = process.processData;
let files: any[] = document.files;
if (!files) {
files = [];
}
files.push({ uid: fileUid });
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => {
FolderService.refreshFolderByUid(document.folder.uid).then(() => resolve());
});
}
});
});
}
};
reader.readAsArrayBuffer(file);
})
.then(onChange)
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
}
}, },
[document.uid, onChange], [document.uid, onChange],
); );
const deleteFile = useCallback( const deleteFile = useCallback(
(fileUid: string) => { (filedUid: string) => {
return new Promise<void>( return Files.getInstance()
(resolve: () => void) => { .delete(filedUid)
FileService.getFileByUid(fileUid).then((res: any) => {
if (res) {
FileService.updateFile(res.processId, { isDeleted: 'true', archived_at: new Date().toISOString() }).then(() => {
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
if (process) {
const document: any = process.processData;
let files: any[] = document.files;
if (!files) {
files = [];
}
files = files.filter((file: any) => file.uid !== fileUid);
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.ASKED }).then(() => {
FolderService.refreshFolderByUid(document.folder.uid).then(() => resolve());
});
}
});
});
}
});
})
.then(onChange) .then(onChange)
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier supprimé avec succès!" })) .then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier supprimé avec succès!" }))
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message })); .catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
@ -181,8 +55,7 @@ export default function DepositDocumentComponent(props: IProps) {
); );
const onOpenModal = useCallback(async () => { const onOpenModal = useCallback(async () => {
if (document.document_status !== "REFUSED") return; const refused_reason = document.document_history?.find((history) => history.document_status === "REFUSED")?.refused_reason;
const refused_reason = document.refused_reason;
if (!refused_reason) return; if (!refused_reason) return;
setRefusedReason(refused_reason); setRefusedReason(refused_reason);
setIsModalOpen(true); setIsModalOpen(true);

View File

@ -1,3 +1,5 @@
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
import FilesNotary from "@Front/Api/LeCoffreApi/Customer/FilesNotary/Files";
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import IconButton from "@Front/Components/DesignSystem/IconButton"; import IconButton from "@Front/Components/DesignSystem/IconButton";
import Table from "@Front/Components/DesignSystem/Table"; import Table from "@Front/Components/DesignSystem/Table";
@ -6,7 +8,7 @@ import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Ty
import BackArrow from "@Front/Components/Elements/BackArrow"; import BackArrow from "@Front/Components/Elements/BackArrow";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate"; import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
// import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService"; import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
import { ArrowDownTrayIcon, EyeIcon } from "@heroicons/react/24/outline"; import { ArrowDownTrayIcon, EyeIcon } from "@heroicons/react/24/outline";
import { saveAs } from "file-saver"; import { saveAs } from "file-saver";
import JSZip from "jszip"; import JSZip from "jszip";
@ -14,14 +16,9 @@ import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react"; import React, { useCallback, useEffect, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import Link from "next/link"; import Link from "next/link";
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
import Customer from "le-coffre-resources/dist/Customer"; import Customer from "le-coffre-resources/dist/Customer";
import { DocumentNotary } from "le-coffre-resources/dist/Notary"; import { DocumentNotary } from "le-coffre-resources/dist/Notary";
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
const header: readonly IHead[] = [ const header: readonly IHead[] = [
{ {
@ -45,31 +42,11 @@ export default function ReceivedDocuments() {
const [customer, setCustomer] = useState<Customer | null>(null); const [customer, setCustomer] = useState<Customer | null>(null);
const fetchFolderAndCustomer = useCallback(async () => { const fetchFolderAndCustomer = useCallback(async () => {
// let jwt: ICustomerJwtPayload | undefined; let jwt: ICustomerJwtPayload | undefined;
// if (typeof document !== "undefined") { if (typeof document !== "undefined") {
// jwt = JwtService.getInstance().decodeCustomerJwt(); jwt = JwtService.getInstance().decodeCustomerJwt();
// }
// TODO: review
LoaderService.getInstance().show();
const folder: any = await new Promise<any>((resolve: (folder: any) => void) => {
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
if (process) {
const folder: any = process.processData;
resolve(folder);
} }
});
});
//const customer = folder?.customers?.find((customer) => customer.contact?.email === jwt?.email);
const customer = folder?.customers?.[0];
if (!customer) throw new Error("Customer not found");
setCustomer(customer);
return { folder, customer };
/*
const folder = await Folders.getInstance().getByUid(folderUid as string, { const folder = await Folders.getInstance().getByUid(folderUid as string, {
q: { q: {
office: true, office: true,
@ -99,72 +76,32 @@ export default function ReceivedDocuments() {
setCustomer(customer); setCustomer(customer);
return { folder, customer }; return { folder, customer };
*/
}, [folderUid]); }, [folderUid]);
useEffect(() => { useEffect(() => {
fetchFolderAndCustomer(); fetchFolderAndCustomer();
}, [folderUid]); // Ne dépend que de folderUid
// Effet séparé pour charger les documents lorsque customer change
useEffect(() => {
const customerUid = customer?.uid; const customerUid = customer?.uid;
if (!folderUid || !customerUid) return; if (!folderUid || !customerUid) return;
DocumentsNotary.getInstance()
.get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
.then((documentsNotary) => setDocumentsNotary(documentsNotary));
}, [folderUid, customer, fetchFolderAndCustomer]);
DocumentService.getDocuments().then(async (processes: any[]) => { const onDownload = useCallback((doc: DocumentNotary) => {
if (processes.length > 0) {
let documents: any[] = processes.map((process: any) => process.processData);
// FilterBy folder.uid & customer.uid
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.customer /*&& document.customer.uid === customerUid*/);
for (const document of documents) {
if (document.files && document.files.length > 0) {
const files: any[] = [];
for (const file of document.files) {
files.push((await FileService.getFileByUid(file.uid)).processData);
}
document.files = files;
}
}
setDocumentsNotary(documents);
LoaderService.getInstance().hide();
}
});
}, [folderUid, customer]);
const onDownload = useCallback(async (doc: any) => {
const file = doc.files?.[0]; const file = doc.files?.[0];
if (!file) return; if (!file || !file?.uid || !doc.uid) return;
if (doc.document_status !== EDocumentNotaryStatus.DOWNLOADED) { return FilesNotary.getInstance()
await new Promise<void>((resolve: () => void) => { .download(file.uid, doc.uid)
LoaderService.getInstance().show(); .then((blob) => {
DocumentService.getDocumentByUid(doc.uid).then((process: any) => {
if (process) {
DocumentService.updateDocument(process, { document_status: EDocumentNotaryStatus.DOWNLOADED }).then(() => {
LoaderService.getInstance().hide();
resolve();
});
}
});
});
}
return new Promise<void>((resolve: () => void) => {
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement('a'); const a = document.createElement("a");
a.href = url; a.href = url;
a.download = file.file_name; a.download = file.file_name ?? "file";
document.body.appendChild(a);
a.click(); a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
})
resolve(); .catch((e) => console.warn(e));
}).catch((e) => console.warn(e));
}, []); }, []);
const onDownloadAll = useCallback(async () => { const onDownloadAll = useCallback(async () => {
@ -173,28 +110,16 @@ export default function ReceivedDocuments() {
const zip = new JSZip(); const zip = new JSZip();
const folder = zip.folder("documents") || zip; const folder = zip.folder("documents") || zip;
documentsNotary.map(async (doc: any) => { const downloadPromises = documentsNotary.map(async (doc) => {
const file = doc.files?.[0]; const file = doc.files?.[0];
if (file) { if (file && file.uid && doc.uid) {
if (doc.document_status !== EDocumentNotaryStatus.DOWNLOADED) { const blob = await FilesNotary.getInstance().download(file.uid, doc.uid);
await new Promise<void>((resolve: () => void) => {
LoaderService.getInstance().show();
DocumentService.getDocumentByUid(doc.uid).then((process: any) => {
if (process) {
DocumentService.updateDocument(process, { document_status: EDocumentNotaryStatus.DOWNLOADED }).then(() => {
LoaderService.getInstance().hide();
resolve();
});
}
});
});
}
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
folder.file(file.file_name ?? "file", blob); folder.file(file.file_name ?? "file", blob);
} }
}); });
await Promise.all(downloadPromises);
zip.generateAsync({ type: "blob" }) zip.generateAsync({ type: "blob" })
.then((blob: any) => { .then((blob: any) => {
saveAs(blob, "documents.zip"); saveAs(blob, "documents.zip");
@ -235,9 +160,12 @@ function buildRows(
folderUid: string | string[], folderUid: string | string[],
onDownloadFileNotary: (doc: DocumentNotary) => void, onDownloadFileNotary: (doc: DocumentNotary) => void,
): IRowProps[] { ): IRowProps[] {
console.log(documentsNotary);
console.log(folderUid);
return documentsNotary.map((documentNotary) => ({ return documentsNotary.map((documentNotary) => ({
key: documentNotary.uid ?? "", key: documentNotary.uid ?? "",
name: documentNotary.files?.[0]?.file_name?.split(".")?.[0] || "_", name: formatName(documentNotary.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
sentAt: new Date(documentNotary.created_at!).toLocaleDateString(), sentAt: new Date(documentNotary.created_at!).toLocaleDateString(),
// actions: <IconButton onClick={() => onDownloadFileNotary(documentNotary)} icon={<ArrowDownTrayIcon />} />, // actions: <IconButton onClick={() => onDownloadFileNotary(documentNotary)} icon={<ArrowDownTrayIcon />} />,
actions: { actions: {
@ -257,3 +185,7 @@ function buildRows(
}, },
})); }));
} }
function formatName(text: string): string {
return text.replace(/[^a-zA-Z0-9 ]/g, "");
}

View File

@ -3,20 +3,16 @@ import RightArrowIcon from "@Assets/Icons/right-arrow.svg";
import Button from "@Front/Components/DesignSystem/Button"; import Button from "@Front/Components/DesignSystem/Button";
import FilePreview from "@Front/Components/DesignSystem/FilePreview"; import FilePreview from "@Front/Components/DesignSystem/FilePreview";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import { DocumentNotary } from "le-coffre-resources/dist/Notary"; import { DocumentNotary, File } from "le-coffre-resources/dist/Notary";
import Image from "next/image"; import Image from "next/image";
import { NextRouter, useRouter } from "next/router"; import { NextRouter, useRouter } from "next/router";
import React from "react"; import React from "react";
import { FileBlob } from "@Front/Api/Entities/types";
import BasePage from "../../Base"; import BasePage from "../../Base";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate"; import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import FilesNotary from "@Front/Api/LeCoffreApi/Customer/FilesNotary/Files";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
type IProps = {}; type IProps = {};
type IPropsClass = { type IPropsClass = {
@ -29,8 +25,8 @@ type IState = {
isValidateModalVisible: boolean; isValidateModalVisible: boolean;
refuseText: string; refuseText: string;
selectedFileIndex: number; selectedFileIndex: number;
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null; selectedFile: File | null;
documentNotary: any | null; documentNotary: DocumentNotary | null;
fileBlob: Blob | null; fileBlob: Blob | null;
isLoading: boolean; isLoading: boolean;
}; };
@ -75,10 +71,10 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
</div> </div>
)} )}
<div className={classes["file-container"]}> <div className={classes["file-container"]}>
{this.state.selectedFile.file_blob.type === "application/pdf" || {this.state.selectedFile.mimetype === "application/pdf" ||
this.state.selectedFile.file_blob.type === "image/jpeg" || this.state.selectedFile.mimetype === "image/jpeg" ||
this.state.selectedFile.file_blob.type === "image/png" || this.state.selectedFile.mimetype === "image/png" ||
this.state.selectedFile.file_blob.type === "image/jpg" ? ( this.state.selectedFile.mimetype === "image/jpg" ? (
<FilePreview <FilePreview
href={this.state.fileBlob ? URL.createObjectURL(this.state.fileBlob) : ""} href={this.state.fileBlob ? URL.createObjectURL(this.state.fileBlob) : ""}
fileName={this.state.selectedFile.file_name} fileName={this.state.selectedFile.file_name}
@ -127,31 +123,16 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
override async componentDidMount() { override async componentDidMount() {
try { try {
LoaderService.getInstance().show(); const documentNotary = await DocumentsNotary.getInstance().getByUid(this.props.documentUid, {
const documentNotary: any = await new Promise<any>((resolve: (document: any) => void) => { files: true,
DocumentService.getDocumentByUid(this.props.documentUid).then(async (process: any) => { folder: true,
if (process) { depositor: true,
const document: any = process.processData;
if (document.files && document.files.length > 0) {
const files: any[] = [];
for (const file of document.files) {
files.push((await FileService.getFileByUid(file.uid)).processData);
}
document.files = files;
}
resolve(document);
}
}); });
});
LoaderService.getInstance().hide();
this.setState( this.setState(
{ {
documentNotary, documentNotary,
selectedFileIndex: 0, selectedFileIndex: 0,
selectedFile: documentNotary.files![0] as any, selectedFile: documentNotary.files![0]!,
isLoading: false, isLoading: false,
}, },
() => { () => {
@ -168,7 +149,8 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
private async getFilePreview(): Promise<void> { private async getFilePreview(): Promise<void> {
try { try {
const fileBlob: Blob = new Blob([this.state.selectedFile!.file_blob.data], { type: this.state.selectedFile!.file_blob.type }); const fileBlob: Blob = await FilesNotary.getInstance().download(this.state.selectedFile?.uid as string, this.props.documentUid);
this.setState({ this.setState({
fileBlob, fileBlob,
}); });

View File

@ -1,14 +1,16 @@
"use client"; "use client";
import Documents, { IGetDocumentsparams } from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import Customer, { Document, DocumentType } from "le-coffre-resources/dist/Customer"; import Customer, { Document, DocumentType } from "le-coffre-resources/dist/Customer";
import React, { useCallback, useEffect, useMemo, useState } from "react"; import React, { useCallback, useEffect, useMemo, useState } from "react";
import { DocumentNotary, OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary"; import { DocumentNotary, type OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService"; import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag"; import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
import DefaultCustomerDashboard from "@Front/Components/LayoutTemplates/DefaultCustomerDashboard"; import DefaultCustomerDashboard from "@Front/Components/LayoutTemplates/DefaultCustomerDashboard";
@ -19,63 +21,28 @@ import Module from "@Front/Config/Module";
import Separator, { ESeperatorColor, ESeperatorDirection } from "@Front/Components/DesignSystem/Separator"; import Separator, { ESeperatorColor, ESeperatorDirection } from "@Front/Components/DesignSystem/Separator";
import NotificationBox from "@Front/Components/DesignSystem/NotificationBox"; import NotificationBox from "@Front/Components/DesignSystem/NotificationBox";
import ContactBox from "./ContactBox"; import ContactBox from "./ContactBox";
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary"; import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
import DepositOtherDocument from "@Front/Components/DesignSystem/DepositOtherDocument"; import DepositOtherDocument from "@Front/Components/DesignSystem/DepositOtherDocument";
import AuthModal from "src/sdk/AuthModal";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
type IProps = {}; type IProps = {};
export default function ClientDashboard(props: IProps) { export default function ClientDashboard(props: IProps) {
const router = useRouter(); const router = useRouter();
let { folderUid, profileUid } = router.query; let { folderUid } = router.query;
const [documents, setDocuments] = useState<Document[] | null>(null); const [documents, setDocuments] = useState<Document[] | null>(null);
const [customer, setCustomer] = useState<Customer | null>(null); const [customer, setCustomer] = useState<Customer | null>(null);
const [folder, setFolder] = useState<OfficeFolderNotary | null>(null); const [folder, setFolder] = useState<OfficeFolderNotary | null>(null);
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]); const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
const [isAddDocumentModalVisible, setIsAddDocumentModalVisible] = useState<boolean>(false); const [isAddDocumentModalVisible, setIsAddDocumentModalVisible] = useState<boolean>(false);
const [isReady, setIsReady] = useState(false);
const [isAuthModalOpen, setIsAuthModalOpen] = useState(true);
const fetchFolderAndCustomer = useCallback(async () => { const fetchFolderAndCustomer = useCallback(async () => {
let jwt: ICustomerJwtPayload | undefined; let jwt: ICustomerJwtPayload | undefined;
if (typeof document !== "undefined") { if (typeof document !== "undefined") {
jwt = JwtService.getInstance().decodeCustomerJwt(); jwt = JwtService.getInstance().decodeCustomerJwt();
} }
// TODO: review
LoaderService.getInstance().show();
const { folder, customer } = await new Promise<any>((resolve) => {
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
if (process) {
const folder: any = process.processData;
const customers: any[] = folder.customers;
const customer: any = customers.find((customer: any) => customer.uid === profileUid as string);
if (customer) {
resolve({ folder: folder, customer });
}
}
});
});
setCustomer(customer);
setFolder(folder);
LoaderService.getInstance().hide();
return { folder, customer };
/*
const folder = await Folders.getInstance().getByUid(folderUid as string, { const folder = await Folders.getInstance().getByUid(folderUid as string, {
q: { q: {
office: true, office: true,
@ -106,77 +73,46 @@ export default function ClientDashboard(props: IProps) {
setCustomer(customer); setCustomer(customer);
return { folder, customer }; return { folder, customer };
*/
}, [folderUid]); }, [folderUid]);
const fetchDocuments = useCallback( const fetchDocuments = useCallback(
async (customerUid: string | undefined) => { (customerUid: string | undefined) => {
setDocuments([]); const query: IGetDocumentsparams = {
LoaderService.getInstance().show(); where: { depositor: { uid: customerUid }, folder_uid: folderUid as string },
return new Promise<void>((resolve: () => void) => { include: {
DocumentService.getDocuments().then(async (processes: any[]) => { files: true,
if (processes.length > 0) { document_history: true,
let documents: any[] = processes.map((process: any) => process.processData); document_type: true,
depositor: true,
folder: {
include: {
customers: {
include: {
contact: true,
},
},
},
},
},
};
// FilterBy folder.uid & depositor.uid return Documents.getInstance()
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor && document.depositor.uid === customerUid); .get(query)
.then((documents) => setDocuments(documents));
for (const document of documents) {
if (document.document_type) {
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
}
if (document.files && document.files.length > 0) {
const files: any[] = [];
for (const file of document.files) {
files.push((await FileService.getFileByUid(file.uid)).processData);
}
document.files = files;
}
}
setDocuments(documents);
}
LoaderService.getInstance().hide();
resolve();
});
});
}, },
[folderUid], [folderUid],
); );
/*
useEffect(() => { useEffect(() => {
fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid)); fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid));
}, [fetchDocuments, fetchFolderAndCustomer]); }, [fetchDocuments, fetchFolderAndCustomer]);
*/
useEffect(() => { useEffect(() => {
setDocumentsNotary([]);
const customerUid = customer?.uid; const customerUid = customer?.uid;
if (!folderUid || !customerUid) return; if (!folderUid || !customerUid) return;
LoaderService.getInstance().show(); DocumentsNotary.getInstance()
DocumentService.getDocuments().then(async (processes: any[]) => { .get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
if (processes.length > 0) { .then((documentsNotary) => setDocumentsNotary(documentsNotary));
let documents: any[] = processes.map((process: any) => process.processData);
// FilterBy folder.uid & customer.uid
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.customer && document.customer.uid === customerUid);
for (const document of documents) {
if (document.files && document.files.length > 0) {
const files: any[] = [];
for (const file of document.files) {
files.push((await FileService.getFileByUid(file.uid)).processData);
}
document.files = files;
}
}
setDocumentsNotary(documents);
LoaderService.getInstance().hide();
}
});
}, [folderUid, customer?.uid]); }, [folderUid, customer?.uid]);
const documentsNotaryNotRead = useMemo( const documentsNotaryNotRead = useMemo(
@ -211,8 +147,8 @@ export default function ClientDashboard(props: IProps) {
}, [customer, folderUid, isAddDocumentModalVisible, onCloseModalAddDocument, folder]); }, [customer, folderUid, isAddDocumentModalVisible, onCloseModalAddDocument, folder]);
return ( return (
<DefaultCustomerDashboard isReady={isReady}> <DefaultCustomerDashboard>
{isReady && (<div className={classes["root"]}> <div className={classes["root"]}>
<div className={classes["top"]}> <div className={classes["top"]}>
<div className={classes["folder-info-container"]}> <div className={classes["folder-info-container"]}>
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_SECONDARY}> <Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
@ -291,7 +227,6 @@ export default function ClientDashboard(props: IProps) {
<DepositDocumentComponent <DepositDocumentComponent
key={document.uid} key={document.uid}
document={document} document={document}
customer={customer}
onChange={() => fetchDocuments(customer?.uid)} onChange={() => fetchDocuments(customer?.uid)}
/> />
))} ))}
@ -309,16 +244,7 @@ export default function ClientDashboard(props: IProps) {
Ajouter d'autres documents Ajouter d'autres documents
</Button> </Button>
{isAddDocumentModalVisible && renderBox()} {isAddDocumentModalVisible && renderBox()}
</div>)} </div>
{isAuthModalOpen && <AuthModal
isOpen={isAuthModalOpen}
onClose={() => {
setIsReady(true);
setIsAuthModalOpen(false);
fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid));
}}
/>}
</DefaultCustomerDashboard> </DefaultCustomerDashboard>
); );
} }

View File

@ -1,10 +1,14 @@
import { ChevronLeftIcon } from "@heroicons/react/24/solid"; import { ChevronLeftIcon } from "@heroicons/react/24/solid";
import OfficeRoles from "@Front/Api/LeCoffreApi/Admin/OfficeRoles/OfficeRoles";
import Roles from "@Front/Api/LeCoffreApi/Admin/Roles/Roles";
import Users from "@Front/Api/LeCoffreApi/Admin/Users/Users";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm"; import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import Switch from "@Front/Components/DesignSystem/Switch"; import Switch from "@Front/Components/DesignSystem/Switch";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import DefaultCollaboratorDashboard from "@Front/Components/LayoutTemplates/DefaultCollaboratorDashboard"; import DefaultCollaboratorDashboard from "@Front/Components/LayoutTemplates/DefaultCollaboratorDashboard";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import User, { OfficeRole } from "le-coffre-resources/dist/Admin";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
@ -14,17 +18,12 @@ import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/Dr
import { getLabel } from "@Front/Components/DesignSystem/Dropdown"; import { getLabel } from "@Front/Components/DesignSystem/Dropdown";
import SelectField from "@Front/Components/DesignSystem/Form/SelectField"; import SelectField from "@Front/Components/DesignSystem/Form/SelectField";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";
import OfficeRoleService from "src/common/Api/LeCoffreApi/sdk/OfficeRoleService";
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
type IProps = {}; type IProps = {};
export default function CollaboratorInformations(props: IProps) { export default function CollaboratorInformations(props: IProps) {
const router = useRouter(); const router = useRouter();
let { collaboratorUid } = router.query; let { collaboratorUid } = router.query;
const [userSelected, setUserSelected] = useState<any | null>(null); const [userSelected, setUserSelected] = useState<User | null>(null);
const [availableRoles, setAvailableRoles] = useState<IOption[]>([]); const [availableRoles, setAvailableRoles] = useState<IOption[]>([]);
const [roleModalOpened, setRoleModalOpened] = useState<boolean>(false); const [roleModalOpened, setRoleModalOpened] = useState<boolean>(false);
@ -36,7 +35,7 @@ export default function CollaboratorInformations(props: IProps) {
useEffect(() => { useEffect(() => {
if (!userSelected) return; if (!userSelected) return;
setIsAdminChecked(userSelected.role.name === "admin"); setIsAdminChecked(userSelected.role?.name === "admin");
}, [userSelected]); }, [userSelected]);
const handleRoleChange = useCallback((option: IOption) => { const handleRoleChange = useCallback((option: IOption) => {
@ -47,54 +46,60 @@ export default function CollaboratorInformations(props: IProps) {
const closeRoleModal = useCallback(() => { const closeRoleModal = useCallback(() => {
setRoleModalOpened(false); setRoleModalOpened(false);
setSelectedOption({ setSelectedOption({
id: userSelected?.role?.uid ?? "", id: (userSelected?.office_role ? userSelected?.office_role?.uid : userSelected?.role?.uid) ?? "",
label: userSelected?.role?.name ?? "Utilisateur restreint" label: userSelected?.office_role ? userSelected?.office_role?.name : "Utilisateur restreint",
}); });
}, [userSelected?.role]); }, [userSelected?.office_role, userSelected?.role?.uid]);
const changeRole = useCallback(async () => { const changeRole = useCallback(async () => {
LoaderService.getInstance().show(); await Users.getInstance().put(
CollaboratorService.getCollaboratorByUid(collaboratorUid as string).then((process: any) => { userSelected?.uid as string,
if (process) { User.hydrate<User>({
CollaboratorService.updateCollaborator(process, { office_role: { uid: selectedOption?.id as string } }).then(() => { uid: userSelected?.uid as string,
LoaderService.getInstance().hide(); office_role: OfficeRole.hydrate<OfficeRole>({
uid: selectedOption?.id as string,
}),
}),
);
setRoleModalOpened(false); setRoleModalOpened(false);
});
}
});
}, [selectedOption, userSelected]); }, [selectedOption, userSelected]);
const changeAdmin = useCallback(async () => { const changeAdmin = useCallback(async () => {
try { try {
if (adminRoleType === "add") { if (adminRoleType === "add") {
LoaderService.getInstance().show(); const adminRole = await Roles.getInstance().getOne({
CollaboratorService.getCollaboratorByUid(collaboratorUid as string).then(async (process: any) => { where: {
if (process) { name: "admin",
const role: any = (await RoleService.getRoles()) },
.map((process: any) => process.processData) });
.filter((role: any) => role.name === "admin")[0];
CollaboratorService.updateCollaborator(process, { role: { uid: role.uid } }).then(() => { if (!adminRole) return;
LoaderService.getInstance().hide(); await Users.getInstance().put(
setAdminModalOpened(false); userSelected?.uid as string,
}); User.hydrate<User>({
} uid: userSelected?.uid as string,
}); office_role: undefined,
role: adminRole,
}),
);
} else { } else {
LoaderService.getInstance().show(); const defaultRole = await Roles.getInstance().getOne({
CollaboratorService.getCollaboratorByUid(collaboratorUid as string).then(async (process: any) => { where: {
if (process) { name: "default",
const role: any = (await RoleService.getRoles()) },
.map((process: any) => process.processData) });
.filter((role: any) => role.name === "default")[0];
CollaboratorService.updateCollaborator(process, { role: { uid: role.uid } }).then(() => { if (!defaultRole) return;
LoaderService.getInstance().hide(); await Users.getInstance().put(
userSelected?.uid as string,
User.hydrate<User>({
uid: userSelected?.uid as string,
office_role: undefined,
role: defaultRole,
}),
);
}
setAdminModalOpened(false); setAdminModalOpened(false);
});
}
});
}
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
@ -108,29 +113,37 @@ export default function CollaboratorInformations(props: IProps) {
}, []); }, []);
const closeAdminModal = useCallback(() => { const closeAdminModal = useCallback(() => {
setIsAdminChecked(userSelected?.role.name === "admin"); setIsAdminChecked(userSelected?.role?.name === "admin" && !userSelected.office_role);
setAdminModalOpened(false); setAdminModalOpened(false);
}, [userSelected]); }, [userSelected]);
useEffect(() => { useEffect(() => {
async function getUser() { async function getUser() {
if (!collaboratorUid) return; if (!collaboratorUid) return;
LoaderService.getInstance().show(); const user = await Users.getInstance().getByUid(collaboratorUid as string, {
CollaboratorService.getCollaboratorByUid(collaboratorUid as string).then(async (process: any) => { q: {
if (process) { contact: true,
const collaborator: any = process.processData; office_role: true,
role: true,
seats: {
include: {
subscription: true,
},
},
},
});
if (!user) return;
const officeRoles: any[] = (await OfficeRoleService.getOfficeRoles()) const roles = await OfficeRoles.getInstance().get();
.map((process: any) => process.processData); if (!roles) return;
setAvailableRoles(roles.map((role) => ({ id: role.uid ?? "", label: role.name })));
setUserSelected(collaborator); setUserSelected(user);
setAvailableRoles(officeRoles.map((officeRole: any) => ({ id: officeRole.uid, label: officeRole.name }))); setSelectedOption({
setSelectedOption({ id: collaborator.office_role.uid, label: collaborator.office_role.name }); id: (user?.office_role ? user?.office_role?.uid : user?.role?.uid) ?? "",
label: user?.office_role ? user?.office_role?.name : "Utilisateur restreint",
LoaderService.getInstance().hide();
}
}); });
} }
getUser(); getUser();
}, [collaboratorUid]); }, [collaboratorUid]);
@ -141,7 +154,7 @@ export default function CollaboratorInformations(props: IProps) {
<Typography typo={ETypo.TITLE_H1}> <Typography typo={ETypo.TITLE_H1}>
{userSelected?.contact?.first_name + " " + userSelected?.contact?.last_name} {userSelected?.contact?.first_name + " " + userSelected?.contact?.last_name}
</Typography> </Typography>
{userSelected && userSelected.seats?.some((seat: any) => new Date(seat.subscription!.end_date) >= new Date()) && ( {userSelected && userSelected.seats?.some((seat) => new Date(seat.subscription!.end_date) >= new Date()) && (
<div className={classes["subscription-active"]}> <div className={classes["subscription-active"]}>
<div className={classes["subscription-active-dot"]} /> <div className={classes["subscription-active-dot"]} />
<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.COLOR_SUCCESS_600}> <Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.COLOR_SUCCESS_600}>

View File

@ -1,3 +1,4 @@
import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form"; import Form from "@Front/Components/DesignSystem/Form";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField"; import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
@ -5,22 +6,15 @@ import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm"; import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
import DefaultDeedTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDeedTypeDashboard"; import DefaultDeedTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDeedTypeDashboard";
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import JwtService from "@Front/Services/JwtService/JwtService";
import { DeedType, Office } from "le-coffre-resources/dist/Admin";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import { validateOrReject, ValidationError } from "class-validator"; import { validateOrReject, ValidationError } from "class-validator";
import UserStore from "@Front/Stores/UserStore";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";
import Auth from "@Front/Api/Auth/IdNot";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";
type IProps = {}; type IProps = {};
export default function DeedTypesCreate(props: IProps) { export default function DeedTypesCreate(props: IProps) {
const [hasChanged, setHasChanged] = useState<boolean>(false); const [hasChanged, setHasChanged] = useState<boolean>(false);
@ -31,66 +25,38 @@ export default function DeedTypesCreate(props: IProps) {
const onSubmitHandler = useCallback( const onSubmitHandler = useCallback(
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => { async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
try { try {
const user: any = UserStore.instance.getUser(); const jwt = JwtService.getInstance().decodeJwt();
if (!user) { const deedType = DeedType.hydrate<DeedType>({
console.error("DeedTypesCreate: User not found - user is null or undefined");
return;
}
const res = await Auth.getInstance().getOfficeProcessByIdNot();
if (!res.success) {
console.error("DeedTypesCreate: Office not found - office is null or undefined");
return;
}
const officeId: string | undefined = res.data.processId;
const officeIdNot: string | undefined = res.data.processData['idNot'];
if (!officeId || !officeIdNot) {
console.error("DeedTypesCreate: officeId or officeIdNot is undefined - office.processData.idNot is missing");
return;
}
// TODO: We should update the type definition to be able to use validation again
// const deedType = DeedType.hydrate<DeedType>({
// name: values["name"],
// description: values["description"],
// office: Office.hydrate<Office>({
// idNot: officeId,
// }),
// });
// try {
// await validateOrReject(deedType, { groups: ["createDeedType"], forbidUnknownValues: true });
// } catch (validationErrors: Array<ValidationError> | any) {
// console.log("validationErrors", validationErrors);
// setValidationError(Array.isArray(validationErrors) ? validationErrors : []);
// return;
// }
const deedTypeData: any = {
name: values["name"], name: values["name"],
description: values["description"], description: values["description"],
office: { office: Office.hydrate<Office>({
uid: officeId, uid: jwt?.office_Id,
idNot: officeIdNot, }),
}
};
LoaderService.getInstance().show();
DeedTypeService.createDeedType(deedTypeData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
ToasterService.getInstance().success({
title: "Succès !",
description: "Type d'acte créé avec succès"
}); });
const deedTypeUid = processCreated.processId; try {
// Remove ':0' suffix from processId for URL navigation await validateOrReject(deedType, { groups: ["createDeedType"], forbidUnknownValues: true });
const urlId = idAsUrl(deedTypeUid); } catch (validationErrors: Array<ValidationError> | any) {
setValidationError(validationErrors as ValidationError[]);
return;
}
const deedTypeCreated = await DeedTypes.getInstance().post(
DeedType.hydrate<DeedType>({
name: values["name"],
description: values["description"],
office: Office.hydrate<Office>({
uid: jwt?.office_Id,
}),
}),
);
router.push( router.push(
Module.getInstance() Module.getInstance()
.get() .get()
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", urlId), .modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeCreated.uid!),
); );
LoaderService.getInstance().hide();
});
} catch (validationErrors: Array<ValidationError> | any) { } catch (validationErrors: Array<ValidationError> | any) {
setValidationError(Array.isArray(validationErrors) ? validationErrors : []); setValidationError(validationErrors as ValidationError[]);
return; return;
} }
}, },
@ -127,12 +93,12 @@ export default function DeedTypesCreate(props: IProps) {
<TextField <TextField
name="name" name="name"
placeholder="Nom de l'acte" placeholder="Nom de l'acte"
validationError={Array.isArray(validationError) ? validationError.find((error) => error.property === "name") : undefined} validationError={validationError.find((error) => error.property === "name")}
/> />
<TextAreaField <TextAreaField
name="description" name="description"
placeholder="Description" placeholder="Description"
validationError={Array.isArray(validationError) ? validationError.find((error) => error.property === "description") : undefined} validationError={validationError.find((error) => error.property === "description")}
/> />
<div className={classes["buttons-container"]}> <div className={classes["buttons-container"]}>
<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED} onClick={onCancel}> <Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED} onClick={onCancel}>

View File

@ -14,11 +14,6 @@ import { ValidationError } from "class-validator";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import MessageBus from "src/sdk/MessageBus";
import { idAsProcessId } from "@Front/Utils/ProcessIdUtils";
export default function DeedTypesEdit() { export default function DeedTypesEdit() {
const router = useRouter(); const router = useRouter();
let { deedTypeUid } = router.query; let { deedTypeUid } = router.query;
@ -32,15 +27,12 @@ export default function DeedTypesEdit() {
setHasChanged(false); setHasChanged(false);
async function getDeedType() { async function getDeedType() {
if (!deedTypeUid) return; if (!deedTypeUid) return;
LoaderService.getInstance().show(); const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, {
// deedTypeUid comes from URL without ':0' suffix, add it back for API calls q: {
const processId = idAsProcessId(deedTypeUid as string); document_types: true,
MessageBus.getInstance().getProcessData(processId).then((processData: any) => { },
if (processData) {
setDeedTypeSelected(processData);
}
LoaderService.getInstance().hide();
}); });
setDeedTypeSelected(deedType);
} }
getDeedType(); getDeedType();
@ -50,52 +42,42 @@ export default function DeedTypesEdit() {
setIsConfirmModalVisible(false); setIsConfirmModalVisible(false);
}, []); }, []);
const onSubmitHandler = async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string | undefined }) => { const onSubmitHandler = useCallback(
// const deedType = DeedType.hydrate<DeedType>({ async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string | undefined }) => {
// name: values["name"], const deedType = DeedType.hydrate<DeedType>({
// description: values["description"], uid: deedTypeUid as string,
// });
// try {
// await deedType.validateOrReject?.({ groups: ["updateDeedType"], forbidUnknownValues: true });
// } catch (validationErrors: Array<ValidationError> | any) {
// if (!Array.isArray(validationErrors)) return;
// setValidationError(validationErrors as ValidationError[]);
// return;
// }
try {
LoaderService.getInstance().show();
// deedTypeUid comes from URL without ':0' suffix, add it back for API calls
const processId = idAsProcessId(deedTypeUid as string);
const process = await MessageBus.getInstance().getProcessData(processId);
if (process) {
console.log('process', process);
// New data
const newData: any = {
name: values["name"], name: values["name"],
description: values["description"] description: values["description"],
}; });
try {
// Merge process data with new data & update process await deedType.validateOrReject?.({ groups: ["updateDeedType"], forbidUnknownValues: true });
process[processId].name = newData.name; } catch (validationErrors: Array<ValidationError> | any) {
process[processId].description = newData.description; if (!Array.isArray(validationErrors)) return;
await DeedTypeService.updateDeedType(processId, newData); setValidationError(validationErrors as ValidationError[]);
return;
}
try {
await DeedTypes.getInstance().put(
deedTypeUid as string,
DeedType.hydrate<DeedType>({
uid: deedTypeUid as string,
name: values["name"],
description: values["description"],
}),
);
router.push( router.push(
Module.getInstance() Module.getInstance()
.get() .get()
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeUid as string), .modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeUid as string),
); );
} catch (validationErrors) {
if (!Array.isArray(validationErrors)) return;
setValidationError(validationErrors as ValidationError[]);
return;
} }
} catch (error) { },
console.error('Error updating deed type:', error); [deedTypeUid, router],
// Handle error appropriately );
} finally {
LoaderService.getInstance().hide();
}
};
const onFieldChange = useCallback((name: string, field: any) => { const onFieldChange = useCallback((name: string, field: any) => {
setHasChanged(true); setHasChanged(true);

View File

@ -1,5 +1,7 @@
import ChevronIcon from "@Assets/Icons/chevron.svg"; import ChevronIcon from "@Assets/Icons/chevron.svg";
import PenICon from "@Assets/Icons/pen.svg"; import PenICon from "@Assets/Icons/pen.svg";
import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
import Form from "@Front/Components/DesignSystem/Form"; import Form from "@Front/Components/DesignSystem/Form";
@ -18,12 +20,6 @@ import { useCallback, useEffect, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import MessageBus from "src/sdk/MessageBus";
import { idAsProcessId } from "@Front/Utils/ProcessIdUtils";
type IProps = {}; type IProps = {};
export default function DeedTypesInformations(props: IProps) { export default function DeedTypesInformations(props: IProps) {
const router = useRouter(); const router = useRouter();
@ -52,76 +48,43 @@ export default function DeedTypesInformations(props: IProps) {
setIsSaveModalOpened(false); setIsSaveModalOpened(false);
}, []); }, []);
const deleteDeedType = async () => { const deleteDeedType = useCallback(async () => {
LoaderService.getInstance().show(); await DeedTypes.getInstance().put(
try { deedTypeUid as string,
// deedTypeUid comes from URL without ':0' suffix, add it back for API calls DeedType.hydrate<DeedType>({
const processId = idAsProcessId(deedTypeUid as string); uid: deedTypeUid as string,
const process = await MessageBus.getInstance().getProcessData(processId); archived_at: new Date(),
}),
if (process && process[processId]) {
// New data
const newData: any = {
isDeleted: 'true',
archived_at: new Date().toISOString()
};
// Merge process data with new data & update process
process[processId].isDeleted = newData.isDeleted;
process[processId].archived_at = newData.archived_at;
await DeedTypeService.updateDeedType(processId, newData);
router.push(
Module.getInstance()
.get()
.modules.pages.DeedTypes.props.path
); );
} router.push(Module.getInstance().get().modules.pages.DeedTypes.props.path);
} catch (error) { }, [deedTypeUid, router]);
console.error('Error deleting deed type:', error);
} finally {
LoaderService.getInstance().hide();
}
};
useEffect(() => { useEffect(() => {
async function getDeedType() { async function getDeedType() {
if (!deedTypeUid) return; if (!deedTypeUid) return;
const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, {
setSelectedDocuments([]); q: {
// deedTypeUid comes from URL without ':0' suffix, add it back for API calls document_types: true,
const processId = idAsProcessId(deedTypeUid as string); },
MessageBus.getInstance().getProcessData(processId).then((process: any) => { });
if (process) {
console.log('[DeedTypesInformations] process', process);
const deedType: any = process;
setDeedTypeSelected(deedType); setDeedTypeSelected(deedType);
if (!deedType.document_types) return; if (!deedType.document_types) return;
const documentsOptions: IOption[] = deedType.document_types const documentsOptions: IOption[] = deedType.document_types
?.map((documentType: any) => { ?.map((documentType) => {
return { return {
label: documentType.name, label: documentType.name,
id: documentType.uid ?? "", id: documentType.uid ?? "",
}; };
}) })
.sort((a: any, b: any) => a.label.localeCompare(b.label)); .sort((a, b) => a.label.localeCompare(b.label));
setSelectedDocuments(documentsOptions); setSelectedDocuments(documentsOptions);
} else {
console.warn('[DeedTypesInformations] process not found:', processId);
}
});
} }
function getDocuments() { async function getDocuments() {
setAvailableDocuments([]); const documents = await DocumentTypes.getInstance().get({});
DocumentTypeService.getDocumentTypes((processes: Record<string, any>) => {
const documents = Object.values(processes);
if (documents.length) {
setAvailableDocuments(documents); setAvailableDocuments(documents);
} }
});
}
getDocuments(); getDocuments();
getDeedType(); getDeedType();
@ -135,35 +98,11 @@ export default function DeedTypesInformations(props: IProps) {
); );
const saveDocumentTypes = useCallback(async () => { const saveDocumentTypes = useCallback(async () => {
LoaderService.getInstance().show(); await DeedTypes.getInstance().put(deedTypeUid as string, {
// deedTypeUid comes from URL without ':0' suffix, add it back for API calls uid: deedTypeUid as string,
const processId = idAsProcessId(deedTypeUid as string); document_types: selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
console.log('[DeedTypesInformations] processId', processId); });
const deedType = (await MessageBus.getInstance().getProcessData(processId))[processId];
if (deedType) {
console.log('[DeedTypesInformations] deedType', deedType);
let document_types: any[] = deedType['document_types'];
if (!document_types) {
document_types = [];
}
selectedDocuments.map((selectedDocument: any) => selectedDocument.id as string)
.forEach((uid: any) => document_types.push(availableDocuments.find((document: any) => document.uid === uid)));
// New data
const newData: any = {
document_types: document_types
};
console.log('[DeedTypesInformations] newData', newData);
await DeedTypeService.updateDeedType(processId, newData);
LoaderService.getInstance().hide();
closeSaveModal(); closeSaveModal();
} else {
console.warn('[DeedTypesInformations] process not found:', processId);
}
}, [closeSaveModal, deedTypeUid, selectedDocuments]); }, [closeSaveModal, deedTypeUid, selectedDocuments]);
const onDocumentChangeHandler = useCallback((options: IOption[] | null) => { const onDocumentChangeHandler = useCallback((options: IOption[] | null) => {

View File

@ -1,10 +1,10 @@
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form"; import Form from "@Front/Components/DesignSystem/Form";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField"; import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
import TextField from "@Front/Components/DesignSystem/Form/TextField"; import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard"; import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard";
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import JwtService from "@Front/Services/JwtService/JwtService"; import JwtService from "@Front/Services/JwtService/JwtService";
import { validateOrReject, ValidationError } from "class-validator"; import { validateOrReject, ValidationError } from "class-validator";
@ -14,85 +14,35 @@ import { useCallback, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";
import UserStore from "@Front/Stores/UserStore";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";
type IProps = {}; type IProps = {};
export default function DocumentTypesCreate(props: IProps) { export default function DocumentTypesCreate(props: IProps) {
const [validationError, setValidationError] = useState<ValidationError[]>([]); const [validationError, setValidationError] = useState<ValidationError[]>([]);
const router = useRouter(); const router = useRouter();
const handleCancel = useCallback(() => {
router.push(Module.getInstance().get().modules.pages.DocumentTypes.props.path);
}, [router]);
const onSubmitHandler = useCallback( const onSubmitHandler = useCallback(
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => { async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
try { try {
const user: any = UserStore.instance.getUser(); const jwt = JwtService.getInstance().decodeJwt();
if (!user) { if (!jwt) return;
console.error("DocumentTypesCreate: User not found - user is null or undefined"); const office = Office.hydrate<Office>({
return; uid: jwt.office_Id,
}
const office = UserStore.instance.getOffice();
if (!office) {
console.error("DocumentTypesCreate: office not found - office is undefined or null");
return;
}
const officeId = office.processId;
const officeIdNot = office.processData.idNot;
// const documentFormModel = DocumentType.hydrate<DocumentType>({
// ...values,
// office: Office.hydrate<Office>({
// uid: officeId,
// })
// });
// await validateOrReject(documentFormModel, { groups: ["createDocumentType"] });
const documentTypeData: any = {
...values,
office: {
uid: officeId,
idNot: officeIdNot,
}
};
LoaderService.getInstance().show();
try {
const processCreated = await DocumentTypeService.createDocumentType(documentTypeData, DEFAULT_VALIDATOR_ID);
ToasterService.getInstance().success({
title: "Succès !",
description: "Type de document créé avec succès"
}); });
const documentTypeUid = idAsUrl(processCreated.processId); const documentToCreate = DocumentType.hydrate<DocumentType>({
if (!documentTypeUid) { ...values,
console.error("DocumentTypesCreate: documentTypeUid is undefined - processCreated.processId is missing"); office: office,
return; });
} await validateOrReject(documentToCreate, { groups: ["createDocumentType"] });
const documentTypeCreated = await DocumentTypes.getInstance().post(documentToCreate);
router.push( router.push(
Module.getInstance() Module.getInstance()
.get() .get()
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", documentTypeUid), .modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", documentTypeCreated.uid!),
); );
} catch (apiError) {
ToasterService.getInstance().error({
title: "Erreur !",
description: "Une erreur est survenue lors de la création du type de document"
});
console.error("Document type creation error:", apiError);
} finally {
LoaderService.getInstance().hide();
}
} catch (e) { } catch (e) {
if (e instanceof Array) { if (e instanceof Array) {
setValidationError(e); setValidationError(e);
} }
LoaderService.getInstance().hide();
} }
}, },
[router], [router],
@ -121,7 +71,7 @@ export default function DocumentTypesCreate(props: IProps) {
validationError={validationError.find((error) => error.property === "public_description")} validationError={validationError.find((error) => error.property === "public_description")}
/> />
<div className={classes["buttons-container"]}> <div className={classes["buttons-container"]}>
<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED} onClick={handleCancel}> <Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
Annuler Annuler
</Button> </Button>
<Button type="submit">Créer le document</Button> <Button type="submit">Créer le document</Button>

View File

@ -1,3 +1,4 @@
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form"; import Form from "@Front/Components/DesignSystem/Form";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField"; import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
@ -12,9 +13,6 @@ import { useCallback, useEffect, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
export default function DocumentTypesEdit() { export default function DocumentTypesEdit() {
const router = useRouter(); const router = useRouter();
let { documentTypeUid } = router.query; let { documentTypeUid } = router.query;
@ -25,17 +23,10 @@ export default function DocumentTypesEdit() {
useEffect(() => { useEffect(() => {
async function getDocumentType() { async function getDocumentType() {
if (!documentTypeUid) return; if (!documentTypeUid) return;
LoaderService.getInstance().show(); const documentType = await DocumentTypes.getInstance().getByUid(documentTypeUid as string, {
DocumentTypeService.getDocumentTypeByProcessId(documentTypeUid as string).then((process: any) => { _count: true,
if (process) {
const documentType: any = {
...process.processData,
processId: process.processId
};
setDocumentTypeSelected(documentType);
}
LoaderService.getInstance().hide();
}); });
setDocumentTypeSelected(documentType);
} }
getDocumentType(); getDocumentType();
@ -55,22 +46,16 @@ export default function DocumentTypesEdit() {
setValidationError(validationErrors as ValidationError[]); setValidationError(validationErrors as ValidationError[]);
return; return;
} }
LoaderService.getInstance().show();
DocumentTypeService.getDocumentTypeByProcessId(documentTypeUid as string).then((process: any) => { const documentTypeUpdated = await DocumentTypes.getInstance().put(documentTypeUid as string, documentToUpdate);
if (process) {
DocumentTypeService.updateDocumentType(process, values).then(() => {
router.push( router.push(
Module.getInstance() Module.getInstance()
.get() .get()
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace( .modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace(
"[uid]", "[uid]",
documentTypeUid as string ?? "", documentTypeUpdated.uid ?? "",
) ),
); );
LoaderService.getInstance().hide();
});
}
});
} catch (validationErrors: Array<ValidationError> | any) { } catch (validationErrors: Array<ValidationError> | any) {
if (!Array.isArray(validationErrors)) return; if (!Array.isArray(validationErrors)) return;
setValidationError(validationErrors as ValidationError[]); setValidationError(validationErrors as ValidationError[]);

View File

@ -1,5 +1,6 @@
import ChevronIcon from "@Assets/Icons/chevron.svg"; import ChevronIcon from "@Assets/Icons/chevron.svg";
import PenICon from "@Assets/Icons/pen.svg"; import PenICon from "@Assets/Icons/pen.svg";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard"; import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
@ -12,8 +13,6 @@ import { useEffect, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
export default function DocumentTypesInformations() { export default function DocumentTypesInformations() {
const router = useRouter(); const router = useRouter();
let { documentTypeUid } = router.query; let { documentTypeUid } = router.query;
@ -22,24 +21,12 @@ export default function DocumentTypesInformations() {
useEffect(() => { useEffect(() => {
async function getDocument() { async function getDocument() {
if (!documentTypeUid) { if (!documentTypeUid) return;
console.log('DocumentTypesInformations: documentTypeUid is not available yet'); const document = await DocumentTypes.getInstance().getByUid(documentTypeUid as string, {
return; _count: true,
}
DocumentTypeService.getDocumentTypeByProcessId(documentTypeUid as string).then((process: any) => {
if (process) {
const document: any = {
...process.processData,
processId: process.processId
};
setDocumentSelected(document);
} else {
console.log('DocumentTypesInformations: No process found for processId:', documentTypeUid);
}
}).catch((error) => {
console.error('DocumentTypesInformations: Error fetching document:', error);
}); });
if (!document) return;
setDocumentSelected(document);
} }
getDocument(); getDocument();
@ -79,15 +66,13 @@ export default function DocumentTypesInformations() {
</div> </div>
</div> </div>
<div className={classes["right"]}> <div className={classes["right"]}>
{(documentSelected as any)?.processId && (
<Link <Link
href={Module.getInstance() href={Module.getInstance()
.get() .get()
.modules.pages.DocumentTypes.pages.Edit.props.path.replace("[uid]", (documentSelected as any).processId)} .modules.pages.DocumentTypes.pages.Edit.props.path.replace("[uid]", documentSelected?.uid ?? "")}
className={classes["edit-icon-container"]}> className={classes["edit-icon-container"]}>
<Image src={PenICon} alt="edit informations" /> <Image src={PenICon} alt="edit informations" />
</Link> </Link>
)}
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,3 +1,5 @@
import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import AutocompleteMultiSelect from "@Front/Components/DesignSystem/AutocompleteMultiSelect"; import AutocompleteMultiSelect from "@Front/Components/DesignSystem/AutocompleteMultiSelect";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
@ -7,10 +9,9 @@ import RadioBox from "@Front/Components/DesignSystem/RadioBox";
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography"; import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow"; import BackArrow from "@Front/Components/Elements/BackArrow";
import Module from "@Front/Config/Module"; import Module from "@Front/Config/Module";
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
import { ValidationError } from "class-validator"; import { ValidationError } from "class-validator";
import { ECivility } from "le-coffre-resources/dist/Customer/Contact"; import { ECivility } from "le-coffre-resources/dist/Customer/Contact";
import { Contact, Customer } from "le-coffre-resources/dist/Notary"; import { Contact, Customer, OfficeFolder } from "le-coffre-resources/dist/Notary";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import backgroundImage from "@Assets/images/background_refonte.svg"; import backgroundImage from "@Assets/images/background_refonte.svg";
@ -18,11 +19,6 @@ import classes from "./classes.module.scss";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage"; import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import { DEFAULT_VALIDATOR_ID } from "../../../../Config/AppConstants";
enum ESelectedOption { enum ESelectedOption {
EXISTING_CUSTOMER = "existing_customer", EXISTING_CUSTOMER = "existing_customer",
NEW_CUSTOMER = "new_customer", NEW_CUSTOMER = "new_customer",
@ -67,64 +63,34 @@ export default function AddClientToFolder(props: IProps) {
values["cell_phone_number"] = "+33" + values["cell_phone_number"].substring(1); values["cell_phone_number"] = "+33" + values["cell_phone_number"].substring(1);
} }
} }
const contactFormModel = Contact.hydrate<Customer>(values); const contactToCreate = Contact.hydrate<Customer>(values);
await contactFormModel.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false }); await contactToCreate.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
} catch (validationErrors) { } catch (validationErrors) {
setValidationError(validationErrors as ValidationError[]); setValidationError(validationErrors as ValidationError[]);
return; return;
} }
try { try {
// TODO: review const customer: Customer = await Customers.getInstance().post({
const customerData: any = { contact: values,
contact: values
};
LoaderService.getInstance().show();
CustomerService.createCustomer(customerData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
if (process) {
const customers: any[] = [];
for (const customerUid of process.processData.customers.map((customer: any) => customer.uid)) {
customers.push({ uid: customerUid });
}
customers.push({ uid: processCreated.processData.uid });
FolderService.updateFolder(process, { customers: customers }).then(() => {
ToasterService.getInstance().success({
title: "Succès !",
description: "Client ajouté avec succès au dossier"
});
router.push(`/folders/${folderUid}`);
LoaderService.getInstance().hide();
});
}
});
}); });
if (!customer.uid) return;
customersToLink?.push({ uid: customer.uid } as Partial<Customer>);
} catch (backError) { } catch (backError) {
if (!Array.isArray(backError)) return; if (!Array.isArray(backError)) return;
setValidationError(backError as ValidationError[]); setValidationError(backError as ValidationError[]);
return; return;
} }
} else {
LoaderService.getInstance().show();
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
if (process) {
const customers: any[] = [];
for (const customerUid of customersToLink.map((customer: any) => customer.uid)) {
customers.push({ uid: customerUid });
} }
FolderService.updateFolder(process, { customers: customers }).then(() => { if (customersToLink) {
ToasterService.getInstance().success({ const body = OfficeFolder.hydrate<OfficeFolder>({
title: "Succès !", customers: customersToLink.map((customer) => {
description: selectedCustomers.length > 1 ? "Clients associés avec succès au dossier" : "Client associé avec succès au dossier" return Customer.hydrate<Customer>(customer);
}),
}); });
await Folders.getInstance().put(folderUid as string, body);
router.push(`/folders/${folderUid}`); router.push(`/folders/${folderUid}`);
LoaderService.getInstance().hide();
});
}
});
} }
}, },
[existingCustomers, folderUid, router, selectedCustomers, selectedOption], [existingCustomers, folderUid, router, selectedCustomers, selectedOption],
@ -132,23 +98,24 @@ export default function AddClientToFolder(props: IProps) {
const getFolderPreSelectedCustomers = useCallback( const getFolderPreSelectedCustomers = useCallback(
async (folderUid: string): Promise<IOption[] | undefined> => { async (folderUid: string): Promise<IOption[] | undefined> => {
const query = {
q: {
customers: {
include: {
contact: true,
},
},
},
};
let preExistingCustomers: IOption[] = []; let preExistingCustomers: IOption[] = [];
try { try {
preExistingCustomers = await new Promise(resolve => { const folder = await Folders.getInstance().getByUid(folderUid, query);
FolderService.getFolderByUid(folderUid as string).then((process: any) => { preExistingCustomers = folder.customers!.map((customer) => {
if (process) {
const folder: any = process.processData;
const preExistingCustomers: IOption[] = folder.customers
.map((customer: any) => {
return { return {
label: customer.contact?.first_name + " " + customer.contact?.last_name, label: customer.contact?.first_name + " " + customer.contact?.last_name,
id: customer.uid ?? "", id: customer.uid ?? "",
}; };
}); });
resolve(preExistingCustomers);
}
});
});
} catch (error) { } catch (error) {
router.push(Module.getInstance().get().modules.pages["404"].props.path); router.push(Module.getInstance().get().modules.pages["404"].props.path);
return; return;
@ -159,13 +126,11 @@ export default function AddClientToFolder(props: IProps) {
); );
const loadCustomers = useCallback(async () => { const loadCustomers = useCallback(async () => {
LoaderService.getInstance().show(); const query = {};
CustomerService.getCustomers().then(async (processes: any[]) => { const availableCustomers = await Customers.getInstance().get(query);
const availableCustomers: any[] = processes.map((process: any) => process.processData); let preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string);
const preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string);
const existingCustomers = preExistingCustomers ?? []; const existingCustomers = preExistingCustomers ?? [];
existingCustomers.forEach((customer) => { existingCustomers.forEach((customer) => {
const index = availableCustomers.findIndex((availableCustomer) => availableCustomer.uid === customer.id); const index = availableCustomers.findIndex((availableCustomer) => availableCustomer.uid === customer.id);
if (index !== -1) availableCustomers.splice(index, 1); if (index !== -1) availableCustomers.splice(index, 1);
@ -180,9 +145,6 @@ export default function AddClientToFolder(props: IProps) {
setExistingCustomers(existingCustomers); setExistingCustomers(existingCustomers);
setIsLoaded(true); setIsLoaded(true);
setSelectedOption(selectedOption); setSelectedOption(selectedOption);
LoaderService.getInstance().hide();
});
}, [folderUid, getFolderPreSelectedCustomers]); }, [folderUid, getFolderPreSelectedCustomers]);
const getSelectedOptions = useCallback((): IOption[] => { const getSelectedOptions = useCallback((): IOption[] => {

View File

@ -1,3 +1,5 @@
import Deeds from "@Front/Api/LeCoffreApi/Notary/Deeds/Deeds";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField"; import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld"; import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
@ -5,16 +7,11 @@ import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
import TextField from "@Front/Components/DesignSystem/Form/TextField"; import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Modal from "@Front/Components/DesignSystem/Modal"; import Modal from "@Front/Components/DesignSystem/Modal";
import RadioBox from "@Front/Components/DesignSystem/RadioBox"; import RadioBox from "@Front/Components/DesignSystem/RadioBox";
import { OfficeFolder } from "le-coffre-resources/dist/Notary"; import { DocumentType, OfficeFolder } from "le-coffre-resources/dist/Notary";
import { ChangeEvent, useCallback, useEffect, useState } from "react"; import { ChangeEvent, useCallback, useEffect, useState } from "react";
import classes from "./classes.module.scss"; import classes from "./classes.module.scss";
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";
type IProps = { type IProps = {
isCreateDocumentModalVisible: boolean; isCreateDocumentModalVisible: boolean;
closeModal: () => void; closeModal: () => void;
@ -32,9 +29,7 @@ export default function ParameterDocuments(props: IProps) {
const [formattedOptions, setFormattedOptions] = useState<IOption[]>([]); const [formattedOptions, setFormattedOptions] = useState<IOption[]>([]);
const getAvailableDocuments = useCallback(async () => { const getAvailableDocuments = useCallback(async () => {
DocumentTypeService.getDocumentTypes().then((processes: any[]) => { const documents = await DocumentTypes.getInstance().get({});
if (processes.length > 0) {
const documents: any[] = processes.map((process: any) => process.processData);
const formattedOptions: IOption[] = documents const formattedOptions: IOption[] = documents
.filter((document) => { .filter((document) => {
@ -46,11 +41,8 @@ export default function ParameterDocuments(props: IProps) {
id: document.uid ?? "", id: document.uid ?? "",
}; };
}); });
formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1)); formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1));
setFormattedOptions(formattedOptions); setFormattedOptions(formattedOptions);
}
});
}, [props.folder.deed?.document_types]); }, [props.folder.deed?.document_types]);
const onVisibleDescriptionChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => { const onVisibleDescriptionChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
@ -76,44 +68,18 @@ export default function ParameterDocuments(props: IProps) {
const addDocument = useCallback(async () => { const addDocument = useCallback(async () => {
if (addOrEditDocument === "add") { if (addOrEditDocument === "add") {
try { try {
LoaderService.getInstance().show(); const documentType = await DocumentTypes.getInstance().post({
const documentTypeData: any = {
name: documentName, name: documentName,
private_description: visibleDescription, private_description: visibleDescription,
office: { office: {
uid: props.folder.office!.uid!, uid: props.folder.office!.uid!,
}, },
public_description: visibleDescription, public_description: visibleDescription,
};
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
DocumentTypeService.createDocumentType(documentTypeData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
const documentType: any = processCreated.processData;
resolve(documentType);
});
}); });
const oldDocumentsType = props.folder.deed?.document_types!; const oldDocumentsType = props.folder.deed?.document_types!;
await Deeds.getInstance().put(props.folder.deed?.uid!, {
await new Promise<void>((resolve: () => void) => { document_types: [...oldDocumentsType, documentType],
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then(async (process: any) => {
if (process) {
// New data
const newData: any = {
document_types: [
...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
{ uid: documentType.uid }
]
};
// Merge process data with new data & update process
process.processData.document_types = newData.document_types;
await DeedTypeService.updateDeedType(process, newData);
resolve();
}
});
}); });
// Create a new document type in the format expected by the parent component // Create a new document type in the format expected by the parent component
@ -127,51 +93,28 @@ export default function ParameterDocuments(props: IProps) {
props.onDocumentsUpdated([newDocumentType]); props.onDocumentsUpdated([newDocumentType]);
} }
LoaderService.getInstance().hide();
handleClose(); handleClose();
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
} else { } else {
try { try {
LoaderService.getInstance().show();
const oldDocumentsType = props.folder.deed?.document_types!; const oldDocumentsType = props.folder.deed?.document_types!;
await new Promise<void>((resolve: () => void) => { await Deeds.getInstance().put(props.folder.deed?.uid!, {
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then(async (process: any) => {
if (process) {
// New data
const newData: any = {
document_types: [ document_types: [
...oldDocumentsType.map((document: any) => ({ uid: document.uid })), ...oldDocumentsType,
...selectedDocuments.map((document: any) => ({ uid: document.id as string })) ...selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
] ],
};
// Merge process data with new data & update process
process.processData.document_types = newData.document_types;
await DeedTypeService.updateDeedType(process, newData);
resolve();
}
});
}); });
// Get the full document details for the selected documents // Get the full document details for the selected documents
const documentsById = await Promise.all( const documentsById = await Promise.all(
selectedDocuments.map(async (doc) => { selectedDocuments.map(async (doc) => {
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => { const fullDoc = await DocumentTypes.getInstance().getByUid(doc.id as string);
DocumentTypeService.getDocumentTypeByUid(doc.id as string).then((process: any) => {
if (process) {
const documentType: any = process.processData;
resolve(documentType);
}
});
});
return { return {
label: documentType.name!, label: fullDoc.name!,
value: documentType.uid!, value: fullDoc.uid!,
description: documentType.private_description!, description: fullDoc.private_description!,
} as IFormOption; } as IFormOption;
}) })
); );
@ -180,7 +123,6 @@ export default function ParameterDocuments(props: IProps) {
props.onDocumentsUpdated(documentsById); props.onDocumentsUpdated(documentsById);
} }
LoaderService.getInstance().hide();
handleClose(); handleClose();
} catch (e) { } catch (e) {
console.error(e); console.error(e);

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