Compare commits
No commits in common. "3623035ede3c72874293b7d6c59fc4c466b0a860" and "cc37500564fdb2f1d7f294d2d455cf07ffd76d90" have entirely different histories.
3623035ede
...
cc37500564
46 changed files with 186 additions and 4171 deletions
4
.gitattributes
vendored
4
.gitattributes
vendored
|
|
@ -1,4 +0,0 @@
|
||||||
# Les scripts shell doivent rester en LF, même commités depuis Windows (sinon "bad interpreter" sur le Pi)
|
|
||||||
*.sh text eol=lf
|
|
||||||
.githooks/* text eol=lf
|
|
||||||
*.service text eol=lf
|
|
||||||
|
|
@ -13,7 +13,7 @@ if [ -n "$bad" ]; then
|
||||||
fi
|
fi
|
||||||
|
|
||||||
scan=$(echo "$staged" | grep -v '^\.githooks/')
|
scan=$(echo "$staged" | grep -v '^\.githooks/')
|
||||||
if [ -n "$scan" ] && git diff --cached -U0 -- $scan | grep -E '^\+' | grep -E '(sk-ant-[a-z]+[0-9]{2}-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20}|-----BEGIN [A-Z ]*PRIVATE KEY|GOCSPX-)' >/dev/null; then
|
if [ -n "$scan" ] && git diff --cached -U0 -- $scan | grep -E '^\+' | grep -Ei '(sk-ant-|ghp_[A-Za-z0-9]{20}|-----BEGIN [A-Z ]*PRIVATE KEY|GOCSPX-)' >/dev/null; then
|
||||||
echo "✗ Un secret semble présent dans le diff. Vérifie avant de commit."; exit 1
|
echo "✗ Un secret semble présent dans le diff. Vérifie avant de commit."; exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
|
||||||
153
README.md
153
README.md
|
|
@ -20,77 +20,6 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
- secrets chiffrés en AES-256-GCM en base ;
|
- secrets chiffrés en AES-256-GCM en base ;
|
||||||
- token Forgejo jamais écrit sur disque.
|
- token Forgejo jamais écrit sur disque.
|
||||||
|
|
||||||
## Suivi des réponses, relances et test A/B
|
|
||||||
|
|
||||||
- **Détection des réponses** : la boîte de réception du projet est lue en IMAP toutes les 15 minutes, et à la demande avec « Vérifier maintenant ».
|
|
||||||
- Une réponse fait passer le prospect en « A répondu ». Elle est rattachée par le fil de discussion (Message-ID), puis par l'adresse, puis par le domaine pro s'il est unique.
|
|
||||||
- Les absences, réponses automatiques et newsletters sont ignorées.
|
|
||||||
- Les mails rejetés (bounces) passent le prospect en « Rejeté » et l'adresse en liste d'opposition.
|
|
||||||
- Aucun token Claude n'est consommé : on ne lit que les en-têtes, et le début du corps pour les bounces.
|
|
||||||
- **Relance automatique** : une seule, après N jours (7 par défaut), dans le même fil (« Re: » + In-Reply-To). Elle part à quatre conditions :
|
|
||||||
- le modèle de relance est validé ;
|
|
||||||
- la boîte IMAP a été lue avec succès il y a moins de 2 h. Sinon, on relancerait des gens qui ont déjà répondu ;
|
|
||||||
- on est en heures ouvrées, du lundi au vendredi de 9h à 18h (heure de Paris). L'heure est revérifiée entre chaque mail ;
|
|
||||||
- les plafonds quotidiens ne sont pas atteints (premiers mails et relances confondus).
|
|
||||||
- **Test A/B de l'objet** : renseigne un « Objet B » et les envois alternent de façon équilibrée. Le taux de réponse de chaque objet s'affiche sous le bouton Envoyer.
|
|
||||||
|
|
||||||
> Test IMAP de bout en bout (optionnel) : `IMAP_TEST=hôte:port:utilisateur:motdepasse npm test`. Voir `test/inbox.live.test.js` pour les 4 mails attendus dans la boîte de test.
|
|
||||||
|
|
||||||
## Pilotage
|
|
||||||
|
|
||||||
- **Jobs de nuit** : Prospecter et Évolution proposent « Maintenant » ou « Cette nuit ». Le job démarre au prochain créneau entre 1h et 6h (heure de Paris, changements d'heure gérés), quand le Pi est au frais et que ton quota Claude est libre. Il est annulable jusqu'au départ.
|
|
||||||
- **Budget IA** : plafonds glissants sur 24 h et sur 30 jours, en équivalent $ API remonté par Claude Code. L'abonnement Pro ne facture rien en plus ; c'est un garde-fou pour ton quota.
|
|
||||||
- Plafond atteint : les jobs IA **restent en file** et repartent seuls quand la fenêtre glisse. Les envois et relances, qui ne consomment pas d'IA, continuent.
|
|
||||||
- Un job en cours n'est jamais coupé : le plafond peut donc être dépassé d'un job.
|
|
||||||
- **Notifications Discord** via webhook : URL chiffrée, validée, sans mention possible. Tu choisis les événements :
|
|
||||||
- fin de job ou erreur ;
|
|
||||||
- réponses de prospects ;
|
|
||||||
- relances envoyées ;
|
|
||||||
- pause thermique ;
|
|
||||||
- budget atteint ;
|
|
||||||
- rapport hebdo.
|
|
||||||
|
|
||||||
Un bouton permet d'envoyer une notification de test.
|
|
||||||
- **Rapport hebdo** : le lundi à 8h, par mail (SMTP global vers ton email de réception) et en résumé sur Discord. Pour chaque projet, sur 7 jours :
|
|
||||||
- prospects trouvés ;
|
|
||||||
- mails et relances envoyés ;
|
|
||||||
- réponses et taux de réponse ;
|
|
||||||
- clients ;
|
|
||||||
- adresses invalides ;
|
|
||||||
- objet gagnant du test A/B, dès 10 envois par objet ;
|
|
||||||
- coût IA.
|
|
||||||
|
|
||||||
Le bouton « Envoyer le rapport maintenant » permet de tester.
|
|
||||||
|
|
||||||
## CRM
|
|
||||||
|
|
||||||
- **Recherche et filtres** sur les prospects :
|
|
||||||
- recherche par entreprise, email, ville ou secteur ;
|
|
||||||
- filtres par statut, score minimum et « Actions à faire » ;
|
|
||||||
- tri ;
|
|
||||||
- pagination par 100.
|
|
||||||
|
|
||||||
Tout est côté serveur, donc ça reste léger sur le Pi même avec des milliers de prospects.
|
|
||||||
- **Fiche prospect** : un clic sur l'entreprise ouvre la fiche, avec :
|
|
||||||
- l'accroche et l'origine de l'email ;
|
|
||||||
- l'historique : premier mail (avec la variante A/B), relance, réponse et échecs d'envoi ;
|
|
||||||
- une **prochaine action** datée (rappel à 9h, heure de Paris), qui alimente le filtre « Actions à faire » ;
|
|
||||||
- des **notes** libres.
|
|
||||||
- **Export CSV** : format Excel FR (`;` et BOM UTF-8). L'export reprend les filtres affichés.
|
|
||||||
- Les cellules qui commencent par `= + - @` sont neutralisées pour qu'Excel ne les exécute pas comme des formules.
|
|
||||||
- **Import CSV** (2000 lignes max) :
|
|
||||||
- colonnes reconnues en français ou en anglais (entreprise, email, site, ville, secteur, score, source, accroche) ;
|
|
||||||
- encodage UTF-8 ou Windows-1252 détecté, donc les fichiers enregistrés par Excel passent tels quels ;
|
|
||||||
- doublons et adresses en liste d'opposition ignorés ;
|
|
||||||
- rapport ligne par ligne ;
|
|
||||||
- l'origine de chaque contact est toujours renseignée (« Import CSV du JJ/MM/AAAA » par défaut), pour le RGPD.
|
|
||||||
- **Courbes** (onglet Récapitulatif, sur 30 ou 90 jours) :
|
|
||||||
- utilisateurs, clients payants et revenu : une photo quotidienne est prise automatiquement, plus une à chaque ouverture du récap ;
|
|
||||||
- mails envoyés et réponses par semaine, recalculés depuis l'historique.
|
|
||||||
|
|
||||||
Les graphiques ont des infobulles au survol et une vue tableau (« Voir les données »).
|
|
||||||
- Les données business démarrent le jour où tu configures l'accès BDD du projet : l'historique ne peut pas être reconstitué avant.
|
|
||||||
|
|
||||||
## Garde-fous d'envoi
|
## Garde-fous d'envoi
|
||||||
|
|
||||||
- Tu choisis le nombre de mails à chaque envoi, avec une confirmation obligatoire.
|
- Tu choisis le nombre de mails à chaque envoi, avec une confirmation obligatoire.
|
||||||
|
|
@ -103,67 +32,61 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
|
|
||||||
## Installation sur le Pi
|
## Installation sur le Pi
|
||||||
|
|
||||||
Pré-requis : **Raspberry Pi OS Lite 64 bits** fraîchement installé, accès SSH, et ton HDD branché.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y git
|
# Node 22 LTS (arm64)
|
||||||
git clone -b develop https://git.tony-averty.dev/Tony/AiTools.git
|
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
|
||||||
cd AiTools
|
sudo apt install -y nodejs git
|
||||||
sudo ./install.sh
|
|
||||||
|
# Utilisateur dédié + code
|
||||||
|
sudo useradd -m -s /bin/bash aitools
|
||||||
|
sudo git clone https://git.tony-averty.dev/Tony/AiTools.git /opt/aitools
|
||||||
|
sudo chown -R aitools: /opt/aitools
|
||||||
|
cd /opt/aitools && sudo -u aitools npm ci --omit=dev && sudo -u aitools mkdir -p data
|
||||||
|
|
||||||
|
# Claude Code, connecté à TON compte Pro (une seule fois, en interactif)
|
||||||
|
sudo npm i -g @anthropic-ai/claude-code
|
||||||
|
sudo -u aitools -i claude # puis /login, ouvre le lien sur ton PC
|
||||||
```
|
```
|
||||||
|
|
||||||
Pour voir ce qui serait fait sans rien toucher : `./install.sh --dry-run`.
|
Configuration :
|
||||||
|
|
||||||
### Ce que fait `install.sh`
|
```bash
|
||||||
|
sudo -u aitools cp .env.example .env && sudo -u aitools nano .env
|
||||||
|
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" # → SECRET_KEY
|
||||||
|
```
|
||||||
|
|
||||||
1. **Questions d'abord** :
|
> Conseil : mets `DATA_DIR` sur un SSD USB. La carte SD n'aime pas les écritures SQLite.
|
||||||
- quel disque pour les données (le disque système est exclu d'office) ;
|
|
||||||
- partition existante, ou formatage ext4 ;
|
|
||||||
- interface réseau, Wi-Fi et Bluetooth ;
|
|
||||||
- nettoyage du système ;
|
|
||||||
- config de l'app ;
|
|
||||||
- token Cloudflare ;
|
|
||||||
- connexion Claude.
|
|
||||||
|
|
||||||
Puis un **récapitulatif à valider**. Rien n'est modifié avant.
|
Service :
|
||||||
2. **Installation sans interruption** :
|
|
||||||
- mise à jour du système et du firmware ;
|
|
||||||
- nettoyage : services inutiles coupés, swap SD remplacé par zram, journaux en RAM ;
|
|
||||||
- montage du HDD par UUID dans `/etc/fstab` (`nofail`, `noatime`) ;
|
|
||||||
- Node 22, Claude Code et cloudflared ;
|
|
||||||
- déploiement dans `/opt/aitools` avec l'utilisateur système `aitools` et les dépendances de prod uniquement (sans les tests) ;
|
|
||||||
- `.env` généré avec `SECRET_KEY` aléatoire, en droits 600 ;
|
|
||||||
- services systemd + sauvegarde quotidienne de la base (04:30, 14 jours) ;
|
|
||||||
- tunnel Cloudflare.
|
|
||||||
3. **Connexion Claude** via `claude setup-token`, puis un test réel, et démarrage avec vérification HTTP.
|
|
||||||
|
|
||||||
Garde-fous :
|
```bash
|
||||||
- formater un disque exige de **taper son nom** ;
|
sudo cp deploy/aitools.service /etc/systemd/system/
|
||||||
- les partitions exFAT/NTFS sont refusées, car SQLite et les droits Linux ne les supportent pas ;
|
sudo systemctl daemon-reload && sudo systemctl enable --now aitools
|
||||||
- `/etc/fstab` et `config.txt` sont sauvegardés (`*.aitools.bak`) avant modification ;
|
journalctl -u aitools -f
|
||||||
- les tokens ne passent jamais en ligne de commande ni dans le log.
|
```
|
||||||
|
|
||||||
**Mise à jour de l'app** : `git pull` dans ton clone, puis relance `sudo ./install.sh` et garde la config existante. Le script est relançable sans risque.
|
### Cloudflare Tunnel
|
||||||
|
|
||||||
> Le service ne démarre pas si le HDD n'est pas monté (`RequiresMountsFor`). Ça évite d'écrire une base vide sur la carte SD par erreur.
|
```bash
|
||||||
|
cloudflared tunnel login
|
||||||
|
cloudflared tunnel create aitools
|
||||||
|
cloudflared tunnel route dns aitools ai.tony-averty.dev
|
||||||
|
sudo cp deploy/cloudflared-config.yml /etc/cloudflared/config.yml # remplacer <TUNNEL_ID>
|
||||||
|
sudo cloudflared service install
|
||||||
|
```
|
||||||
|
|
||||||
|
Aucun port à ouvrir sur la box. L'app écoute uniquement sur `127.0.0.1`.
|
||||||
|
|
||||||
### Google OAuth
|
### Google OAuth
|
||||||
|
|
||||||
Dans la console Google Cloud, crée un ID client OAuth de type « Application Web » (menu Identifiants).
|
Dans la console Google Cloud, va dans Identifiants, puis crée un ID client OAuth de type « Application Web ».
|
||||||
|
|
||||||
- URI de redirection : `https://ai.tony-averty.dev/auth/google/callback`
|
- URI de redirection : `https://ai.tony-averty.dev/auth/google/callback`
|
||||||
- Écran de consentement : mode « Test » avec ton email en testeur, ça suffit.
|
- Écran de consentement : mode « Test » avec ton email en testeur, ça suffit.
|
||||||
|
|
||||||
### Cloudflare Tunnel
|
|
||||||
|
|
||||||
Dans Zero Trust, va dans Networks → Tunnels → Create a tunnel (Cloudflared).
|
|
||||||
|
|
||||||
- Public hostname : `ai.tony-averty.dev` → `http://localhost:3100`
|
|
||||||
- Copie le token, `install.sh` te le demandera.
|
|
||||||
|
|
||||||
### Forgejo
|
### Forgejo
|
||||||
|
|
||||||
Le token se crée dans Paramètres → Applications. Donne-lui la portée `read:repository` seulement, puis colle-le dans **Réglages** du panel avec l'hôte `git.tony-averty.dev`.
|
Le token se crée dans Paramètres → Applications. Donne-lui la portée `read:repository` seulement. Colle-le ensuite dans **Réglages** avec l'hôte `git.tony-averty.dev`.
|
||||||
|
|
||||||
## À faire côté mails (sinon spam garanti)
|
## À faire côté mails (sinon spam garanti)
|
||||||
|
|
||||||
|
|
@ -186,5 +109,3 @@ npm run check # lint + tests
|
||||||
```
|
```
|
||||||
|
|
||||||
Les tests utilisent un faux binaire Claude (`test/fixtures/fake-claude.js`) : aucun token consommé.
|
Les tests utilisent un faux binaire Claude (`test/fixtures/fake-claude.js`) : aucun token consommé.
|
||||||
|
|
||||||
`test/install.test.sh` teste les fonctions d'`install.sh` qui écrivent des fichiers : `.env`, unit systemd, migration, sauvegarde. Il tourne en root et écrit dans `/opt/aitools` et `/etc/systemd`, donc **uniquement dans une VM ou un conteneur jetable**, jamais sur le Pi en service.
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Sauvegarde à chaud de la base SQLite (cohérente même pendant l'écriture) + rotation.
|
|
||||||
# Usage : aitools-backup <fichier.sqlite> <dossier de sauvegarde> [jours à garder]
|
|
||||||
set -eu
|
|
||||||
src=$1
|
|
||||||
dest=$2
|
|
||||||
keep=${3:-14}
|
|
||||||
|
|
||||||
[ -f "$src" ] || { echo "Pas de base à sauvegarder ($src)"; exit 0; }
|
|
||||||
mkdir -p "$dest"
|
|
||||||
out="$dest/aitools-$(date +%F).sqlite"
|
|
||||||
sqlite3 "$src" ".backup '$out'"
|
|
||||||
sqlite3 "$out" 'PRAGMA integrity_check;' | grep -qx ok || { echo "Sauvegarde corrompue : $out" >&2; exit 1; }
|
|
||||||
find "$dest" -name 'aitools-*.sqlite' -mtime +"$keep" -delete
|
|
||||||
echo "Sauvegarde OK : $out"
|
|
||||||
|
|
@ -1,16 +1,13 @@
|
||||||
# Template : install.sh remplace @APP_DIR@, @DATA_DIR@ et @APP_USER@.
|
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=AiTools (panel prospection IA)
|
Description=AiTools (panel prospection IA)
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
# Ne démarre pas si le disque de données n'est pas monté
|
|
||||||
RequiresMountsFor=@DATA_DIR@
|
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=@APP_USER@
|
User=aitools
|
||||||
WorkingDirectory=@APP_DIR@
|
WorkingDirectory=/opt/aitools
|
||||||
ExecStart=/usr/bin/node --env-file=@APP_DIR@/.env --no-warnings=ExperimentalWarning src/server.js
|
ExecStart=/usr/bin/node --env-file=/opt/aitools/.env --no-warnings=ExperimentalWarning src/server.js
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
Environment=NODE_ENV=production
|
Environment=NODE_ENV=production
|
||||||
|
|
@ -22,7 +19,7 @@ NoNewPrivileges=true
|
||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
ProtectSystem=strict
|
ProtectSystem=strict
|
||||||
ProtectHome=read-only
|
ProtectHome=read-only
|
||||||
ReadWritePaths=@DATA_DIR@ /home/@APP_USER@
|
ReadWritePaths=/opt/aitools/data -/home/aitools/.claude -/home/aitools/.claude.json
|
||||||
ProtectKernelTunables=true
|
ProtectKernelTunables=true
|
||||||
ProtectControlGroups=true
|
ProtectControlGroups=true
|
||||||
|
|
||||||
|
|
|
||||||
825
install.sh
825
install.sh
|
|
@ -1,825 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
|
||||||
# AiTools — installation sur Raspberry Pi OS Lite 64 bits
|
|
||||||
#
|
|
||||||
# Usage : sudo ./install.sh installation / mise à jour
|
|
||||||
# ./install.sh --dry-run montre ce qui serait fait, sans rien toucher
|
|
||||||
#
|
|
||||||
# Phase 1 : questions (disque, réseau, nettoyage, config, tunnel, Claude)
|
|
||||||
# Phase 2 : récapitulatif, puis installation sans interruption
|
|
||||||
# Relançable sans risque : chaque étape vérifie l'existant.
|
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
|
||||||
set -Eeuo pipefail
|
|
||||||
|
|
||||||
readonly APP_USER=aitools
|
|
||||||
readonly APP_DIR=/opt/aitools
|
|
||||||
readonly PORT=3100
|
|
||||||
readonly NODE_MIN=22.13
|
|
||||||
readonly LOG=/var/log/aitools-install.log
|
|
||||||
SRC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
|
||||||
readonly SRC_DIR
|
|
||||||
# ${#var} doit compter des caractères (accents) et pas des octets
|
|
||||||
export LC_CTYPE=C.UTF-8
|
|
||||||
|
|
||||||
DRY_RUN=0
|
|
||||||
|
|
||||||
# Réponses (remplies en phase 1)
|
|
||||||
DATA_MODE=system # system | existing | format
|
|
||||||
DISK="" PART="" FSTYPE="" MOUNT_POINT="" DATA_DIR="$APP_DIR/data" BACKUP_DIR=""
|
|
||||||
BACKUPS=0
|
|
||||||
IFACE="" DISABLE_WIFI=0 DISABLE_BT=0
|
|
||||||
DO_CLEAN=0 DO_UPGRADE=0
|
|
||||||
KEEP_ENV=0 DOMAIN="" ALLOWED="" GOOGLE_ID="" GOOGLE_SECRET="" THERMAL=75
|
|
||||||
TUNNEL_MODE=later TUNNEL_TOKEN=""
|
|
||||||
CLAUDE_MODE=later
|
|
||||||
NEED_REBOOT=0
|
|
||||||
CLEAN_SERVICES=() CLEAN_PACKAGES=() CLEAN_SWAP=0
|
|
||||||
|
|
||||||
# ─── Affichage ───────────────────────────────────────────────────────────────
|
|
||||||
if [[ -t 1 ]]; then
|
|
||||||
B=$'\e[1m' D=$'\e[2m' R=$'\e[0m' RED=$'\e[31m' GRN=$'\e[32m' YLW=$'\e[33m' BLU=$'\e[34m' CYN=$'\e[36m'
|
|
||||||
else
|
|
||||||
B="" D="" R="" RED="" GRN="" YLW="" BLU="" CYN=""
|
|
||||||
fi
|
|
||||||
|
|
||||||
banner() {
|
|
||||||
printf '\n%s' "$BLU$B"
|
|
||||||
printf ' ╭──────────────────────────────────────────────╮\n'
|
|
||||||
printf ' │ AiTools · installation Raspberry Pi │\n'
|
|
||||||
printf ' ╰──────────────────────────────────────────────╯%s\n' "$R"
|
|
||||||
(( DRY_RUN )) && printf ' %s[dry-run] rien ne sera modifié%s\n' "$YLW" "$R"
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
section() { printf '\n%s━━ %s %s%s\n' "$BLU$B" "$1" "$(printf '━%.0s' $(seq 1 $((44 - ${#1}))))" "$R"; }
|
|
||||||
info() { printf ' %s%s%s\n' "$D" "$*" "$R"; }
|
|
||||||
ok() { printf ' %s✓%s %s\n' "$GRN" "$R" "$*"; }
|
|
||||||
warn() { printf ' %s!%s %s\n' "$YLW" "$R" "$*"; }
|
|
||||||
pad() { local s=$1 w=$2 n; n=$((w - ${#s})); (( n < 0 )) && n=0; printf '%s%*s' "$s" "$n" ""; }
|
|
||||||
row() { printf ' %s %s\n' "$(pad "$1" 14)" "$2"; }
|
|
||||||
die() { printf '\n %s✗ %s%s\n' "$RED$B" "$*" "$R" >&2; exit 1; }
|
|
||||||
|
|
||||||
on_error() {
|
|
||||||
local line=$1
|
|
||||||
printf '\n %s✗ Erreur inattendue (ligne %s).%s\n' "$RED$B" "$line" "$R" >&2
|
|
||||||
[[ -f $LOG ]] && printf ' Détails : %s\n' "$LOG" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
trap 'on_error $LINENO' ERR
|
|
||||||
trap 'printf "\n\n %sInstallation interrompue.%s\n" "$YLW" "$R"; exit 130' INT
|
|
||||||
|
|
||||||
# ─── Saisie ──────────────────────────────────────────────────────────────────
|
|
||||||
ask() { # ask VAR "Question" [défaut]
|
|
||||||
local __v=$1 __q=$2 __d=${3:-} __a
|
|
||||||
read -r -p " $__q${__d:+ ${D}[$__d]${R}} : " __a || die "Saisie interrompue"
|
|
||||||
printf -v "$__v" '%s' "${__a:-$__d}"
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_secret() { # ask_secret VAR "Question" (saisie masquée)
|
|
||||||
local __v=$1 __q=$2 __a
|
|
||||||
read -r -s -p " $__q : " __a || die "Saisie interrompue"
|
|
||||||
printf '\n'
|
|
||||||
printf -v "$__v" '%s' "$__a"
|
|
||||||
}
|
|
||||||
|
|
||||||
confirm() { # confirm "Question" [o|n] → code retour 0 = oui
|
|
||||||
local q=$1 def=${2:-o} a hint
|
|
||||||
[[ $def == o ]] && hint="O/n" || hint="o/N"
|
|
||||||
while :; do
|
|
||||||
read -r -p " $q ${D}[$hint]${R} " a || die "Saisie interrompue"
|
|
||||||
a=${a,,}; a=${a:-$def}
|
|
||||||
case $a in o|oui|y|yes) return 0 ;; n|non|no) return 1 ;; esac
|
|
||||||
warn "Réponds o ou n."
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
menu() { # menu VAR "Question" option1 option2 … → VAR = numéro choisi (1…n)
|
|
||||||
local __v=$1 __q=$2 __n __i=1 __c __o
|
|
||||||
shift 2; __n=$#
|
|
||||||
printf '\n %s%s%s\n' "$B" "$__q" "$R"
|
|
||||||
for __o in "$@"; do printf ' %s%2d)%s %s\n' "$CYN" "$__i" "$R" "$__o"; __i=$((__i + 1)); done
|
|
||||||
while :; do
|
|
||||||
read -r -p " Choix [1-$__n] : " __c || die "Saisie interrompue"
|
|
||||||
if [[ $__c =~ ^[0-9]+$ ]] && (( __c >= 1 && __c <= __n )); then break; fi
|
|
||||||
warn "Tape un nombre entre 1 et $__n."
|
|
||||||
done
|
|
||||||
printf -v "$__v" '%s' "$__c"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Exécution ───────────────────────────────────────────────────────────────
|
|
||||||
# run "Libellé" commande args… → spinner, sortie dans le log, arrêt propre si échec
|
|
||||||
run() {
|
|
||||||
local label=$1; shift
|
|
||||||
if (( DRY_RUN )); then printf ' %s·%s %s %s→ %s%s\n' "$CYN" "$R" "$label" "$D" "$*" "$R"; return 0; fi
|
|
||||||
printf '\n>>> %s\n$ %s\n' "$label" "$*" >>"$LOG"
|
|
||||||
"$@" >>"$LOG" 2>&1 &
|
|
||||||
local pid=$! i=0 rc=0 frames=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
|
|
||||||
if [[ -t 1 ]]; then
|
|
||||||
while kill -0 "$pid" 2>/dev/null; do
|
|
||||||
printf '\r %s%s%s %s' "$CYN" "${frames[i % 10]}" "$R" "$label"
|
|
||||||
i=$((i + 1)); sleep 0.1
|
|
||||||
done
|
|
||||||
printf '\r\e[K'
|
|
||||||
fi
|
|
||||||
wait "$pid" || rc=$?
|
|
||||||
if (( rc == 0 )); then ok "$label"; return 0; fi
|
|
||||||
printf ' %s✗%s %s\n\n' "$RED" "$R" "$label"
|
|
||||||
tail -n 15 "$LOG" | sed 's/^/ /'
|
|
||||||
die "Échec : $label (log complet : $LOG)"
|
|
||||||
}
|
|
||||||
|
|
||||||
is_installed() { dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q "ok installed"; }
|
|
||||||
has_unit() { systemctl list-unit-files "$1" --no-legend 2>/dev/null | grep -q .; }
|
|
||||||
kv() { [[ $1 =~ (^|[[:space:]])$2=\"([^\"]*)\" ]] && printf '%s' "${BASH_REMATCH[2]}"; return 0; }
|
|
||||||
|
|
||||||
# ─── Détection ───────────────────────────────────────────────────────────────
|
|
||||||
system_disks() { # disques qui portent / ou /boot : jamais proposés
|
|
||||||
local m src pk
|
|
||||||
for m in / /boot/firmware /boot; do
|
|
||||||
src=$(findmnt -no SOURCE "$m" 2>/dev/null) || continue
|
|
||||||
[[ $src == /dev/* ]] || continue
|
|
||||||
pk=$(lsblk -no PKNAME "$src" 2>/dev/null | head -n1)
|
|
||||||
printf '/dev/%s\n' "${pk:-${src#/dev/}}"
|
|
||||||
done | sort -u
|
|
||||||
}
|
|
||||||
|
|
||||||
DISKS=() DISK_LABELS=()
|
|
||||||
scan_disks() {
|
|
||||||
DISKS=() DISK_LABELS=()
|
|
||||||
local sys line name type size tran rota model kind
|
|
||||||
sys=$(system_disks)
|
|
||||||
while IFS= read -r line; do
|
|
||||||
name=$(kv "$line" NAME); type=$(kv "$line" TYPE)
|
|
||||||
[[ $type == disk && -n $name ]] || continue
|
|
||||||
[[ $name == /dev/zram* || $name == /dev/loop* || $name == /dev/ram* ]] && continue
|
|
||||||
grep -qxF "$name" <<<"$sys" && continue
|
|
||||||
size=$(kv "$line" SIZE); tran=$(kv "$line" TRAN); rota=$(kv "$line" ROTA); model=$(kv "$line" MODEL)
|
|
||||||
kind="SSD/clé"; [[ $rota == 1 ]] && kind="HDD"; [[ $name == /dev/mmcblk* ]] && kind="carte SD"
|
|
||||||
tran=${tran^^}
|
|
||||||
DISKS+=("$name")
|
|
||||||
DISK_LABELS+=("$(printf '%-13s %7s %s %-5s %s' "$name" "$size" "$(pad "$kind" 8)" "${tran:--}" "${model:-modèle inconnu}")")
|
|
||||||
done < <(lsblk -dnpP -o NAME,TYPE,SIZE,TRAN,ROTA,MODEL 2>/dev/null)
|
|
||||||
}
|
|
||||||
|
|
||||||
PARTS=() PART_FS=() PART_LABELS=()
|
|
||||||
scan_parts() {
|
|
||||||
PARTS=() PART_FS=() PART_LABELS=()
|
|
||||||
local line name type size fs label mnt
|
|
||||||
while IFS= read -r line; do
|
|
||||||
name=$(kv "$line" NAME); type=$(kv "$line" TYPE); size=$(kv "$line" SIZE); fs=$(kv "$line" FSTYPE)
|
|
||||||
# Partition, ou disque formaté directement sans table de partitions
|
|
||||||
[[ $type == part || ( $type == disk && -n $fs ) ]] || continue
|
|
||||||
label=$(kv "$line" LABEL); mnt=$(kv "$line" MOUNTPOINT)
|
|
||||||
PARTS+=("$name"); PART_FS+=("$fs")
|
|
||||||
PART_LABELS+=("$(printf '%-13s %7s %-6s %s%s' "$name" "$size" "${fs:-vide}" "${label:+« $label » }" "${mnt:+(monté sur $mnt)}")")
|
|
||||||
done < <(lsblk -npP -o NAME,TYPE,SIZE,FSTYPE,LABEL,MOUNTPOINT "$1" 2>/dev/null)
|
|
||||||
}
|
|
||||||
|
|
||||||
IFACES=() IFACE_KINDS=() IFACE_LABELS=()
|
|
||||||
scan_ifaces() {
|
|
||||||
IFACES=() IFACE_KINDS=() IFACE_LABELS=()
|
|
||||||
local name kind state ip
|
|
||||||
for path in /sys/class/net/*; do
|
|
||||||
name=${path##*/}
|
|
||||||
case $name in lo|docker*|veth*|br-*|virbr*|tun*|wg*|ifb*|dummy*) continue ;; esac
|
|
||||||
case $name in wl*) kind="Wi-Fi" ;; eth*|en*) kind="Ethernet" ;; *) kind="autre" ;; esac
|
|
||||||
state=$(cat "$path/operstate" 2>/dev/null || echo "?")
|
|
||||||
ip=$(ip -4 -o addr show dev "$name" 2>/dev/null | awk '{print $4; exit}' || true)
|
|
||||||
IFACES+=("$name"); IFACE_KINDS+=("$kind")
|
|
||||||
[[ -n $ip ]] || ip="sans IP"
|
|
||||||
IFACE_LABELS+=("$(printf '%-10s %-9s %-5s %s' "$name" "$kind" "${state^^}" "$ip")")
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
ram_mb() { awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo; }
|
|
||||||
config_txt() { [[ -f /boot/firmware/config.txt ]] && echo /boot/firmware/config.txt || echo /boot/config.txt; }
|
|
||||||
version_ge() { [[ $(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n1) == "$2" ]]; }
|
|
||||||
|
|
||||||
# ─── Phase 0 : vérifications ─────────────────────────────────────────────────
|
|
||||||
preflight() {
|
|
||||||
section "Vérifications"
|
|
||||||
[[ -f $SRC_DIR/package.json && -f $SRC_DIR/src/server.js ]] || die "Lance ce script depuis le dossier du projet cloné."
|
|
||||||
|
|
||||||
if (( ! DRY_RUN )); then
|
|
||||||
[[ $EUID -eq 0 ]] || die "Lance-le avec sudo : sudo ./install.sh"
|
|
||||||
mkdir -p "$(dirname "$LOG")"; : >"$LOG"; chmod 600 "$LOG"
|
|
||||||
fi
|
|
||||||
|
|
||||||
local arch model os
|
|
||||||
arch=$(uname -m)
|
|
||||||
model=$(tr -d '\0' 2>/dev/null </proc/device-tree/model || echo "machine inconnue")
|
|
||||||
os=$(. /etc/os-release && echo "${PRETTY_NAME:-?}")
|
|
||||||
info "$model · $os · $arch · $(ram_mb) Mo de RAM"
|
|
||||||
|
|
||||||
if [[ $arch != aarch64 ]]; then
|
|
||||||
(( DRY_RUN )) && warn "Architecture $arch (attendu : aarch64), ignoré en dry-run" \
|
|
||||||
|| die "Il faut un OS 64 bits (aarch64). Réinstalle Raspberry Pi OS Lite 64-bit."
|
|
||||||
fi
|
|
||||||
(( $(ram_mb) < 1800 )) && warn "Moins de 2 Go de RAM : ça marchera, mais un seul job à la fois et MemoryMax réduit."
|
|
||||||
|
|
||||||
if (( ! DRY_RUN )); then
|
|
||||||
curl -fsS -m 10 -o /dev/null https://deb.nodesource.com || die "Pas d'accès Internet (deb.nodesource.com injoignable)."
|
|
||||||
fi
|
|
||||||
ok "Prêt"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Phase 1 : questions ─────────────────────────────────────────────────────
|
|
||||||
ask_storage() {
|
|
||||||
section "Stockage des données"
|
|
||||||
info "Base SQLite + clones Git des projets. Un disque externe épargne la carte SD."
|
|
||||||
local sys; sys=$(system_disks | tr '\n' ' ')
|
|
||||||
[[ -n ${sys// } ]] && info "Disque système (exclu) : $sys"
|
|
||||||
|
|
||||||
local c
|
|
||||||
scan_disks
|
|
||||||
while (( ${#DISKS[@]} == 0 )); do
|
|
||||||
warn "Aucun disque externe détecté."
|
|
||||||
menu c "Que faire ?" "J'ai branché le disque, relancer la détection" "Garder les données sur le disque système"
|
|
||||||
[[ $c == 2 ]] && { DATA_MODE=system; return; }
|
|
||||||
sleep 2; scan_disks
|
|
||||||
done
|
|
||||||
|
|
||||||
menu c "Quel disque utiliser pour les données ?" "${DISK_LABELS[@]}" "Aucun — garder les données sur le disque système"
|
|
||||||
if (( c > ${#DISKS[@]} )); then DATA_MODE=system; return; fi
|
|
||||||
DISK=${DISKS[c - 1]}
|
|
||||||
|
|
||||||
while :; do
|
|
||||||
scan_parts "$DISK"
|
|
||||||
local opts=() i
|
|
||||||
for i in "${!PARTS[@]}"; do opts+=("Utiliser la partition ${PART_LABELS[i]}"); done
|
|
||||||
opts+=("Formater tout le disque en ext4 ${RED}(efface tout)${R}")
|
|
||||||
menu c "Comment utiliser $DISK ?" "${opts[@]}"
|
|
||||||
|
|
||||||
if (( c <= ${#PARTS[@]} )); then
|
|
||||||
PART=${PARTS[c - 1]}; FSTYPE=${PART_FS[c - 1]}
|
|
||||||
case $FSTYPE in
|
|
||||||
ext4|xfs|btrfs) DATA_MODE=existing; break ;;
|
|
||||||
"") warn "$PART n'a pas de système de fichiers : il faut formater." ;;
|
|
||||||
*) warn "$FSTYPE ne gère pas les droits Linux et abîme SQLite. Choisis une partition ext4 ou formate." ;;
|
|
||||||
esac
|
|
||||||
else
|
|
||||||
DATA_MODE=format
|
|
||||||
printf '\n'; lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT "$DISK" | sed 's/^/ /'
|
|
||||||
printf '\n %s⚠ Tout le contenu de %s sera définitivement effacé.%s\n' "$RED$B" "$DISK" "$R"
|
|
||||||
local used
|
|
||||||
used=$(lsblk -lnpo MOUNTPOINT "$DISK" | grep -vE '^$|^/media/|^/mnt/' || true)
|
|
||||||
[[ -n $used ]] && warn "Ce disque est actuellement utilisé sur : $(tr '\n' ' ' <<<"$used")"
|
|
||||||
local typed
|
|
||||||
ask typed "Pour confirmer, tape le nom du disque (${DISK##*/})"
|
|
||||||
[[ $typed == "${DISK##*/}" ]] && break
|
|
||||||
warn "Confirmation incorrecte, rien ne sera formaté."
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
while :; do
|
|
||||||
ask MOUNT_POINT "Point de montage" "/srv/aitools"
|
|
||||||
[[ $MOUNT_POINT == /?* && $MOUNT_POINT != *" "* ]] || { warn "Chemin absolu sans espace attendu."; continue; }
|
|
||||||
case $MOUNT_POINT in /|/boot*|/etc*|/usr*|/var|/bin*|/sbin*|/lib*|/proc*|/sys*|/dev*|/home) warn "Dossier système refusé." ;; *) break ;; esac
|
|
||||||
done
|
|
||||||
MOUNT_POINT=${MOUNT_POINT%/}
|
|
||||||
DATA_DIR=$MOUNT_POINT/data
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_backups() {
|
|
||||||
local where=$APP_DIR/backups
|
|
||||||
[[ $DATA_MODE != system ]] && where=$MOUNT_POINT/backups
|
|
||||||
printf '\n'
|
|
||||||
if confirm "Sauvegarde quotidienne de la base (04:30, 14 jours gardés, dans $where) ?" o; then
|
|
||||||
BACKUPS=1; BACKUP_DIR=$where
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_network() {
|
|
||||||
section "Réseau"
|
|
||||||
scan_ifaces
|
|
||||||
(( ${#IFACES[@]} )) || { warn "Aucune interface réseau détectée."; return; }
|
|
||||||
local c=1
|
|
||||||
if (( ${#IFACES[@]} == 1 )); then
|
|
||||||
info "Interface détectée : ${IFACE_LABELS[0]}"
|
|
||||||
else
|
|
||||||
menu c "Quelle interface le Raspberry utilise-t-il pour Internet ?" "${IFACE_LABELS[@]}"
|
|
||||||
fi
|
|
||||||
IFACE=${IFACES[c - 1]}
|
|
||||||
|
|
||||||
printf '\n'
|
|
||||||
if [[ ${IFACE_KINDS[c - 1]} == Ethernet ]] && compgen -G "/sys/class/net/wl*" >/dev/null; then
|
|
||||||
confirm "Tu es en Ethernet : désactiver le Wi-Fi (moins de chaleur) ?" o && DISABLE_WIFI=1
|
|
||||||
fi
|
|
||||||
confirm "Désactiver le Bluetooth (inutile pour un serveur) ?" o && DISABLE_BT=1
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_cleanup() {
|
|
||||||
section "Nettoyage du système"
|
|
||||||
local s p
|
|
||||||
for s in triggerhappy ModemManager cups cups-browsed; do has_unit "$s.service" && CLEAN_SERVICES+=("$s"); done
|
|
||||||
if (( DISABLE_BT )); then for s in bluetooth hciuart; do has_unit "$s.service" && CLEAN_SERVICES+=("$s"); done; fi
|
|
||||||
for p in triggerhappy modemmanager cups cups-daemon man-db; do is_installed "$p" && CLEAN_PACKAGES+=("$p"); done
|
|
||||||
is_installed dphys-swapfile && CLEAN_SWAP=1
|
|
||||||
|
|
||||||
info "Ce qui sera fait :"
|
|
||||||
(( ${#CLEAN_SERVICES[@]} )) && printf ' • services désactivés : %s\n' "${CLEAN_SERVICES[*]}"
|
|
||||||
(( ${#CLEAN_PACKAGES[@]} )) && printf ' • paquets supprimés : %s\n' "${CLEAN_PACKAGES[*]}"
|
|
||||||
(( CLEAN_SWAP )) && printf ' • swap sur carte SD remplacé par zram (swap compressé en RAM)\n'
|
|
||||||
printf " • journaux système en RAM (50 Mo max) : beaucoup moins d'écritures disque\n"
|
|
||||||
printf ' • apt autoremove + nettoyage du cache\n'
|
|
||||||
printf '\n'
|
|
||||||
confirm "Appliquer ce nettoyage ?" o && DO_CLEAN=1
|
|
||||||
confirm "Mettre le système à jour (apt full-upgrade + firmware, ~5-15 min) ?" o && DO_UPGRADE=1
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_app() {
|
|
||||||
section "Configuration de l'application"
|
|
||||||
if [[ -f $APP_DIR/.env ]]; then
|
|
||||||
if confirm "Une configuration existe déjà ($APP_DIR/.env). La garder ?" o; then KEEP_ENV=1; return; fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
while :; do
|
|
||||||
ask DOMAIN "Domaine public" "ai.tony-averty.dev"
|
|
||||||
[[ $DOMAIN =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$ ]] && break
|
|
||||||
warn "Domaine invalide (ex. ai.mondomaine.fr)."
|
|
||||||
done
|
|
||||||
|
|
||||||
local def; def=$(sed -n 's/^ALLOWED_EMAILS=//p' "$SRC_DIR/.env.example" 2>/dev/null | head -n1)
|
|
||||||
while :; do
|
|
||||||
ask ALLOWED "Emails Google autorisés (séparés par des virgules)" "$def"
|
|
||||||
[[ $ALLOWED =~ ^[^,[:space:]]+@[^,[:space:]]+(,[^,[:space:]]+@[^,[:space:]]+)*$ ]] && break
|
|
||||||
warn "Format attendu : moi@gmail.com,autre@gmail.com"
|
|
||||||
done
|
|
||||||
|
|
||||||
printf '\n'
|
|
||||||
info "Google Cloud Console › Identifiants › ID client OAuth (« Application Web »)"
|
|
||||||
info "URI de redirection : https://$DOMAIN/auth/google/callback"
|
|
||||||
ask GOOGLE_ID "Client ID Google (vide = plus tard)"
|
|
||||||
[[ -n $GOOGLE_ID ]] && ask_secret GOOGLE_SECRET "Client secret Google"
|
|
||||||
|
|
||||||
while :; do
|
|
||||||
ask THERMAL "Température CPU max avant pause des jobs (°C)" "75"
|
|
||||||
[[ $THERMAL =~ ^[0-9]+$ ]] && (( THERMAL >= 60 && THERMAL <= 85 )) && break
|
|
||||||
warn "Entre 60 et 85."
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_tunnel() {
|
|
||||||
section "Accès public (Cloudflare Tunnel)"
|
|
||||||
local c
|
|
||||||
if has_unit cloudflared.service; then
|
|
||||||
menu c "Un tunnel Cloudflare est déjà installé." "Le garder tel quel" "Le remplacer par un nouveau token"
|
|
||||||
[[ $c == 1 ]] && { TUNNEL_MODE=keep; return; }
|
|
||||||
else
|
|
||||||
menu c "Configurer le tunnel maintenant ?" "Oui, j'ai un token de tunnel (recommandé)" "Plus tard"
|
|
||||||
[[ $c == 2 ]] && { TUNNEL_MODE=later; return; }
|
|
||||||
fi
|
|
||||||
info "Cloudflare Zero Trust › Networks › Tunnels › Create a tunnel (Cloudflared)"
|
|
||||||
info "Public hostname : ${DOMAIN:-ai.tony-averty.dev} → http://localhost:$PORT"
|
|
||||||
info "Copie le token (la longue chaîne après « --token » dans la commande proposée)."
|
|
||||||
while :; do
|
|
||||||
ask_secret TUNNEL_TOKEN "Token du tunnel"
|
|
||||||
[[ $TUNNEL_TOKEN =~ ^[A-Za-z0-9+/=_-]{50,}$ ]] && break
|
|
||||||
warn "Ça ne ressemble pas à un token (chaîne base64 de 50+ caractères)."
|
|
||||||
done
|
|
||||||
TUNNEL_MODE=token
|
|
||||||
}
|
|
||||||
|
|
||||||
ask_claude() {
|
|
||||||
section "Connexion à Claude"
|
|
||||||
info "Claude Code tourne en headless avec ton abonnement Pro (pas de clé API)."
|
|
||||||
local c
|
|
||||||
menu c "Comment connecter Claude ?" \
|
|
||||||
"Token longue durée via « claude setup-token » (recommandé pour un serveur)" \
|
|
||||||
"Connexion interactive (/login)" \
|
|
||||||
"Plus tard"
|
|
||||||
case $c in 1) CLAUDE_MODE=token ;; 2) CLAUDE_MODE=login ;; *) CLAUDE_MODE=later ;; esac
|
|
||||||
}
|
|
||||||
|
|
||||||
recap() {
|
|
||||||
section "Récapitulatif"
|
|
||||||
local line
|
|
||||||
case $DATA_MODE in
|
|
||||||
system) line="disque système ($DATA_DIR)" ;;
|
|
||||||
existing) line="$PART ($FSTYPE) monté sur $MOUNT_POINT" ;;
|
|
||||||
format) line="${RED}${B}FORMATAGE de $DISK${R} en ext4, monté sur $MOUNT_POINT" ;;
|
|
||||||
esac
|
|
||||||
local google="Google à faire plus tard"
|
|
||||||
[[ -n $GOOGLE_ID ]] && google="Google OK"
|
|
||||||
row "Données" "$line"
|
|
||||||
row "Sauvegardes" "$( (( BACKUPS )) && echo "$BACKUP_DIR" || echo "non")"
|
|
||||||
row "Réseau" "${IFACE:-?}$( (( DISABLE_WIFI )) && echo ", Wi-Fi coupé")$( (( DISABLE_BT )) && echo ", Bluetooth coupé")"
|
|
||||||
row "Nettoyage" "$( (( DO_CLEAN )) && echo oui || echo non)"
|
|
||||||
row "Mise à jour" "$( (( DO_UPGRADE )) && echo oui || echo non)"
|
|
||||||
row "Config" "$( (( KEEP_ENV )) && echo "conservée" || echo "https://$DOMAIN · $google")"
|
|
||||||
row "Tunnel" "$TUNNEL_MODE"
|
|
||||||
row "Claude" "$CLAUDE_MODE"
|
|
||||||
row "Application" "$APP_DIR (utilisateur $APP_USER, port $PORT)"
|
|
||||||
printf '\n'
|
|
||||||
confirm "Lancer l'installation ?" o || die "Annulé, rien n'a été modifié."
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Phase 2 : installation ──────────────────────────────────────────────────
|
|
||||||
do_upgrade() {
|
|
||||||
section "Système"
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
run "Mise à jour de la liste des paquets" apt-get update -q
|
|
||||||
if (( DO_UPGRADE )); then
|
|
||||||
run "Mise à jour du système" apt-get -y -q -o Dpkg::Options::=--force-confold full-upgrade
|
|
||||||
command -v rpi-eeprom-update >/dev/null && run "Mise à jour du firmware (EEPROM)" rpi-eeprom-update -a
|
|
||||||
fi
|
|
||||||
run "Outils de base (git, curl, sqlite3, fdisk)" apt-get install -y -q --no-install-recommends git curl ca-certificates sqlite3 fdisk openssl
|
|
||||||
}
|
|
||||||
|
|
||||||
apply_cleanup() {
|
|
||||||
local s
|
|
||||||
for s in "${CLEAN_SERVICES[@]}"; do systemctl disable --now "$s.service" || true; done
|
|
||||||
if (( ${#CLEAN_PACKAGES[@]} )); then apt-get purge -y -q "${CLEAN_PACKAGES[@]}"; fi
|
|
||||||
if (( CLEAN_SWAP )); then
|
|
||||||
dphys-swapfile swapoff || true
|
|
||||||
dphys-swapfile uninstall || true
|
|
||||||
systemctl disable --now dphys-swapfile || true
|
|
||||||
apt-get purge -y -q dphys-swapfile
|
|
||||||
fi
|
|
||||||
if (( CLEAN_SWAP )) || ! swapon --show=NAME --noheadings | grep -q zram; then
|
|
||||||
apt-get install -y -q --no-install-recommends zram-tools
|
|
||||||
printf 'ALGO=zstd\nPERCENT=50\nPRIORITY=100\n' >/etc/default/zramswap
|
|
||||||
systemctl restart zramswap
|
|
||||||
fi
|
|
||||||
mkdir -p /etc/systemd/journald.conf.d
|
|
||||||
printf '[Journal]\nStorage=volatile\nRuntimeMaxUse=50M\n' >/etc/systemd/journald.conf.d/aitools.conf
|
|
||||||
systemctl restart systemd-journald
|
|
||||||
apt-get autoremove -y -q --purge
|
|
||||||
apt-get clean
|
|
||||||
}
|
|
||||||
|
|
||||||
apply_boot_config() {
|
|
||||||
local f; f=$(config_txt)
|
|
||||||
[[ -f $f ]] || return 0
|
|
||||||
[[ -f $f.aitools.bak ]] || cp "$f" "$f.aitools.bak"
|
|
||||||
local line
|
|
||||||
for line in "$@"; do grep -qxF "$line" "$f" || printf '\n[all]\n%s\n' "$line" >>"$f"; done
|
|
||||||
}
|
|
||||||
|
|
||||||
do_cleanup() {
|
|
||||||
section "Nettoyage"
|
|
||||||
(( DO_CLEAN )) && run "Services, paquets, swap et journaux" apply_cleanup
|
|
||||||
local lines=() f; f=$(config_txt)
|
|
||||||
(( DISABLE_WIFI )) && lines+=("dtoverlay=disable-wifi")
|
|
||||||
(( DISABLE_BT )) && lines+=("dtoverlay=disable-bt")
|
|
||||||
if (( ${#lines[@]} )); then
|
|
||||||
for l in "${lines[@]}"; do grep -qxF "$l" "$f" 2>/dev/null || NEED_REBOOT=1; done
|
|
||||||
run "Wi-Fi / Bluetooth coupés au démarrage (${lines[*]})" apply_boot_config "${lines[@]}"
|
|
||||||
fi
|
|
||||||
(( DO_CLEAN || ${#lines[@]} )) || info "Rien à faire."
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
prepare_disk() {
|
|
||||||
local part=$PART fstype=$FSTYPE uuid opts p
|
|
||||||
# Formatage : on démonte tout le disque. Partition existante : seulement elle.
|
|
||||||
local target=$PART
|
|
||||||
[[ $DATA_MODE == format ]] && target=$DISK
|
|
||||||
while read -r p; do umount "$p" || true; done < <(lsblk -lnpo NAME,MOUNTPOINT "$target" | awk 'NF==2 {print $1}')
|
|
||||||
|
|
||||||
if [[ $DATA_MODE == format ]]; then
|
|
||||||
wipefs -a "$DISK"
|
|
||||||
printf 'label: gpt\n,,L\n' | sfdisk --wipe always "$DISK"
|
|
||||||
partprobe "$DISK" 2>/dev/null || true
|
|
||||||
udevadm settle
|
|
||||||
part=$(lsblk -lnpo NAME,TYPE "$DISK" | awk '$2=="part" {print $1; exit}')
|
|
||||||
[[ -n $part ]] || { echo "Partition introuvable après partitionnement"; return 1; }
|
|
||||||
mkfs.ext4 -F -q -L aitools -m 1 "$part"
|
|
||||||
fstype=ext4
|
|
||||||
fi
|
|
||||||
|
|
||||||
uuid=$(blkid -s UUID -o value "$part")
|
|
||||||
[[ -n $uuid ]] || { echo "UUID introuvable pour $part"; return 1; }
|
|
||||||
opts="defaults,noatime,nofail,x-systemd.device-timeout=30s"
|
|
||||||
[[ $fstype == ext4 ]] && opts+=",commit=60"
|
|
||||||
|
|
||||||
[[ -f /etc/fstab.aitools.bak ]] || cp /etc/fstab /etc/fstab.aitools.bak
|
|
||||||
awk -v mp="$MOUNT_POINT" -v id="UUID=$uuid" '$2 != mp && $1 != id' /etc/fstab >/etc/fstab.tmp
|
|
||||||
printf 'UUID=%s %s %s %s 0 2\n' "$uuid" "$MOUNT_POINT" "$fstype" "$opts" >>/etc/fstab.tmp
|
|
||||||
mv /etc/fstab.tmp /etc/fstab
|
|
||||||
systemctl daemon-reload
|
|
||||||
mkdir -p "$MOUNT_POINT"
|
|
||||||
mountpoint -q "$MOUNT_POINT" || mount "$MOUNT_POINT"
|
|
||||||
findmnt "$MOUNT_POINT"
|
|
||||||
}
|
|
||||||
|
|
||||||
do_storage() {
|
|
||||||
section "Stockage"
|
|
||||||
if [[ $DATA_MODE == system ]]; then info "Données sur le disque système : $DATA_DIR"; return 0; fi
|
|
||||||
local label="Montage de $PART sur $MOUNT_POINT"
|
|
||||||
[[ $DATA_MODE == format ]] && label="Formatage de $DISK et montage sur $MOUNT_POINT"
|
|
||||||
run "$label" prepare_disk
|
|
||||||
(( DRY_RUN )) || ok "Espace libre : $(df -h --output=avail "$MOUNT_POINT" | tail -n1 | tr -d ' ')"
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
install_node() {
|
|
||||||
curl -fsSL https://deb.nodesource.com/setup_22.x -o /tmp/nodesource_setup.sh
|
|
||||||
bash /tmp/nodesource_setup.sh
|
|
||||||
rm -f /tmp/nodesource_setup.sh
|
|
||||||
apt-get install -y -q nodejs
|
|
||||||
}
|
|
||||||
|
|
||||||
install_cloudflared() {
|
|
||||||
curl -fsSL -o /tmp/cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64.deb
|
|
||||||
dpkg -i /tmp/cloudflared.deb
|
|
||||||
rm -f /tmp/cloudflared.deb
|
|
||||||
}
|
|
||||||
|
|
||||||
do_runtime() {
|
|
||||||
section "Node.js, Claude Code, cloudflared"
|
|
||||||
local v=""
|
|
||||||
command -v node >/dev/null && v=$(node -v | tr -d v)
|
|
||||||
if [[ -n $v ]] && version_ge "$v" "$NODE_MIN"; then ok "Node.js $v déjà présent"
|
|
||||||
else run "Installation de Node.js 22 LTS" install_node; fi
|
|
||||||
|
|
||||||
if command -v claude >/dev/null; then
|
|
||||||
run "Mise à jour de Claude Code" npm install -g --no-audit --no-fund @anthropic-ai/claude-code@latest
|
|
||||||
else
|
|
||||||
run "Installation de Claude Code" npm install -g --no-audit --no-fund @anthropic-ai/claude-code
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ $TUNNEL_MODE != keep ]]; then
|
|
||||||
if command -v cloudflared >/dev/null; then ok "cloudflared déjà présent"
|
|
||||||
else run "Installation de cloudflared" install_cloudflared; fi
|
|
||||||
fi
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
deploy_app() {
|
|
||||||
# root lit un repo appartenant à un autre utilisateur : on lève la protection "dubious ownership"
|
|
||||||
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=safe.directory GIT_CONFIG_VALUE_0='*'
|
|
||||||
id "$APP_USER" &>/dev/null || useradd --system --create-home --shell /usr/sbin/nologin "$APP_USER"
|
|
||||||
local branch origin
|
|
||||||
if [[ -d $SRC_DIR/.git ]]; then
|
|
||||||
branch=$(git -C "$SRC_DIR" rev-parse --abbrev-ref HEAD)
|
|
||||||
[[ $branch == HEAD ]] && { echo "Le dossier source est en HEAD détachée : fais git checkout develop"; return 1; }
|
|
||||||
origin=$(git -C "$SRC_DIR" remote get-url origin 2>/dev/null || true)
|
|
||||||
# Passage par un bundle : un clone local direct relance git dans un sous-process qui
|
|
||||||
# ignore safe.directory, et échoue quand le dossier source appartient à un autre utilisateur.
|
|
||||||
local bundle; bundle=$(mktemp /tmp/aitools-XXXXXX.bundle)
|
|
||||||
git -C "$SRC_DIR" bundle create "$bundle" "$branch"
|
|
||||||
if [[ -d $APP_DIR/.git ]]; then
|
|
||||||
git -C "$APP_DIR" fetch "$bundle" "$branch"
|
|
||||||
git -C "$APP_DIR" reset --hard FETCH_HEAD
|
|
||||||
else
|
|
||||||
git clone --branch "$branch" "$bundle" "$APP_DIR"
|
|
||||||
fi
|
|
||||||
rm -f "$bundle"
|
|
||||||
if [[ -n $origin ]]; then git -C "$APP_DIR" remote set-url origin "$origin"; else git -C "$APP_DIR" remote remove origin; fi
|
|
||||||
# Le serveur n'a pas besoin des tests ni des hooks de dev
|
|
||||||
git -C "$APP_DIR" sparse-checkout set --no-cone '/*' '!/test/' '!/.githooks/'
|
|
||||||
else
|
|
||||||
mkdir -p "$APP_DIR"
|
|
||||||
tar -C "$SRC_DIR" --exclude=./test --exclude=./.githooks --exclude=./node_modules --exclude=./data --exclude=./.env -cf - . | tar -C "$APP_DIR" -xf -
|
|
||||||
fi
|
|
||||||
chown -R "$APP_USER:" "$APP_DIR"
|
|
||||||
(cd "$APP_DIR" && runuser -u "$APP_USER" -- env HOME="/home/$APP_USER" npm_config_cache="/home/$APP_USER/.npm" npm ci --omit=dev --no-audit --no-fund)
|
|
||||||
(cd "$APP_DIR" && runuser -u "$APP_USER" -- env HOME="/home/$APP_USER" npm_config_cache="/home/$APP_USER/.npm" npm cache clean --force)
|
|
||||||
mkdir -p "$DATA_DIR"; chown "$APP_USER:" "$DATA_DIR"; chmod 750 "$DATA_DIR"
|
|
||||||
if (( BACKUPS )); then mkdir -p "$BACKUP_DIR"; chown "$APP_USER:" "$BACKUP_DIR"; chmod 750 "$BACKUP_DIR"; fi
|
|
||||||
}
|
|
||||||
|
|
||||||
set_env() { # set_env clé valeur (dans $APP_DIR/.env)
|
|
||||||
local f=$APP_DIR/.env
|
|
||||||
if grep -q "^$1=" "$f"; then
|
|
||||||
__V=$2 awk -v k="$1" 'BEGIN { v = ENVIRON["__V"] } index($0, k "=") == 1 { print k "=" v; next } { print }' "$f" >"$f.tmp"
|
|
||||||
cat "$f.tmp" >"$f"; rm -f "$f.tmp"
|
|
||||||
else
|
|
||||||
printf '%s=%s\n' "$1" "$2" >>"$f"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
write_env() {
|
|
||||||
local f=$APP_DIR/.env claude_bin
|
|
||||||
claude_bin=$(command -v claude || echo claude)
|
|
||||||
umask 077
|
|
||||||
if (( ! KEEP_ENV )); then
|
|
||||||
cat >"$f" <<EOF
|
|
||||||
# Généré par install.sh le $(date '+%F %T')
|
|
||||||
APP_URL=https://$DOMAIN
|
|
||||||
PORT=$PORT
|
|
||||||
HOST=127.0.0.1
|
|
||||||
GOOGLE_CLIENT_ID=$GOOGLE_ID
|
|
||||||
GOOGLE_CLIENT_SECRET=$GOOGLE_SECRET
|
|
||||||
ALLOWED_EMAILS=$ALLOWED
|
|
||||||
SECRET_KEY=$(openssl rand -hex 32 2>/dev/null || node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
|
|
||||||
DATA_DIR=$DATA_DIR
|
|
||||||
CLAUDE_BIN=$claude_bin
|
|
||||||
THERMAL_MAX=$THERMAL
|
|
||||||
EOF
|
|
||||||
fi
|
|
||||||
set_env DATA_DIR "$DATA_DIR"
|
|
||||||
set_env CLAUDE_BIN "$claude_bin"
|
|
||||||
chown "$APP_USER:" "$f"; chmod 600 "$f"
|
|
||||||
}
|
|
||||||
|
|
||||||
old_data_dir() { # DATA_DIR de la config existante, chemin absolu
|
|
||||||
local d; d=$(sed -n 's/^DATA_DIR=//p' "$APP_DIR/.env" 2>/dev/null | tail -n1)
|
|
||||||
[[ -z $d ]] && return 0
|
|
||||||
[[ $d == /* ]] || d="$APP_DIR/${d#./}"
|
|
||||||
printf '%s' "${d%/}"
|
|
||||||
}
|
|
||||||
|
|
||||||
migrate_data() {
|
|
||||||
local old=$1
|
|
||||||
systemctl stop aitools 2>/dev/null || true
|
|
||||||
cp -a "$old/." "$DATA_DIR/"
|
|
||||||
chown -R "$APP_USER:" "$DATA_DIR"
|
|
||||||
}
|
|
||||||
|
|
||||||
install_units() {
|
|
||||||
local mem=900M unit=/etc/systemd/system/aitools.service
|
|
||||||
(( $(ram_mb) < 1800 )) && mem=600M
|
|
||||||
sed -e "s|@APP_DIR@|$APP_DIR|g" -e "s|@DATA_DIR@|$DATA_DIR|g" -e "s|@APP_USER@|$APP_USER|g" \
|
|
||||||
-e "s|^MemoryMax=.*|MemoryMax=$mem|" "$SRC_DIR/deploy/aitools.service" >"$unit"
|
|
||||||
|
|
||||||
if (( BACKUPS )); then
|
|
||||||
install -m 755 "$SRC_DIR/deploy/aitools-backup.sh" /usr/local/sbin/aitools-backup
|
|
||||||
cat >/etc/systemd/system/aitools-backup.service <<EOF
|
|
||||||
[Unit]
|
|
||||||
Description=Sauvegarde quotidienne AiTools
|
|
||||||
RequiresMountsFor=$DATA_DIR $BACKUP_DIR
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
User=$APP_USER
|
|
||||||
Nice=15
|
|
||||||
IOSchedulingClass=idle
|
|
||||||
ExecStart=/usr/local/sbin/aitools-backup $DATA_DIR/aitools.sqlite $BACKUP_DIR 14
|
|
||||||
EOF
|
|
||||||
cat >/etc/systemd/system/aitools-backup.timer <<EOF
|
|
||||||
[Unit]
|
|
||||||
Description=Sauvegarde quotidienne AiTools (04:30)
|
|
||||||
|
|
||||||
[Timer]
|
|
||||||
OnCalendar=*-*-* 04:30
|
|
||||||
Persistent=true
|
|
||||||
RandomizedDelaySec=10min
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=timers.target
|
|
||||||
EOF
|
|
||||||
fi
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable aitools.service
|
|
||||||
(( BACKUPS )) && systemctl enable --now aitools-backup.timer
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
config_complete() {
|
|
||||||
local id secret
|
|
||||||
id=$(sed -n 's/^GOOGLE_CLIENT_ID=//p' "$APP_DIR/.env" | tail -n1)
|
|
||||||
secret=$(sed -n 's/^GOOGLE_CLIENT_SECRET=//p' "$APP_DIR/.env" | tail -n1)
|
|
||||||
[[ -n $id && -n $secret ]]
|
|
||||||
}
|
|
||||||
|
|
||||||
do_app() {
|
|
||||||
section "Application"
|
|
||||||
local old=""
|
|
||||||
(( KEEP_ENV )) && old=$(old_data_dir)
|
|
||||||
run "Déploiement dans $APP_DIR (dépendances de prod uniquement)" deploy_app
|
|
||||||
if [[ -n $old && $old != "$DATA_DIR" && -f $old/aitools.sqlite && ! -f $DATA_DIR/aitools.sqlite ]]; then
|
|
||||||
run "Migration des données de $old vers $DATA_DIR" migrate_data "$old"
|
|
||||||
fi
|
|
||||||
run "Configuration (.env, droits 600)" write_env
|
|
||||||
run "Services systemd" install_units
|
|
||||||
}
|
|
||||||
|
|
||||||
install_tunnel() { cloudflared service install "$TUNNEL_TOKEN"; }
|
|
||||||
|
|
||||||
do_tunnel() {
|
|
||||||
[[ $TUNNEL_MODE == token ]] || return 0
|
|
||||||
section "Cloudflare Tunnel"
|
|
||||||
has_unit cloudflared.service && run "Suppression de l'ancien tunnel" cloudflared service uninstall
|
|
||||||
run "Installation du tunnel" install_tunnel
|
|
||||||
}
|
|
||||||
|
|
||||||
do_claude() {
|
|
||||||
[[ $CLAUDE_MODE == later ]] && return 0
|
|
||||||
section "Connexion à Claude"
|
|
||||||
if (( DRY_RUN )); then info "[dry-run] étape interactive ignorée"; return 0; fi
|
|
||||||
local bin; bin=$(command -v claude) || { warn "Claude Code introuvable."; return 0; }
|
|
||||||
if [[ $CLAUDE_MODE == token ]]; then
|
|
||||||
info "Une URL va s'afficher : ouvre-la, connecte-toi avec ton compte Claude Pro,"
|
|
||||||
info "puis reviens ici. Le token s'affichera à la fin (il commence par sk-ant-oat)."
|
|
||||||
printf '\n'
|
|
||||||
runuser -u "$APP_USER" -- env HOME="/home/$APP_USER" "$bin" setup-token || warn "setup-token a échoué."
|
|
||||||
printf '\n'
|
|
||||||
local token=""
|
|
||||||
while :; do
|
|
||||||
ask_secret token "Colle le token ici (vide = plus tard)"
|
|
||||||
[[ -z $token ]] && { warn "Token non enregistré, tu pourras relancer l'install."; return 0; }
|
|
||||||
[[ $token =~ ^sk-ant-[A-Za-z0-9_-]{20,}$ ]] && break
|
|
||||||
warn "Format inattendu (attendu : sk-ant-…)."
|
|
||||||
done
|
|
||||||
set_env CLAUDE_CODE_OAUTH_TOKEN "$token"
|
|
||||||
ok "Token enregistré dans $APP_DIR/.env"
|
|
||||||
else
|
|
||||||
info "Claude Code va s'ouvrir : tape /login, suis les instructions, puis /exit."
|
|
||||||
printf '\n'
|
|
||||||
runuser -u "$APP_USER" -- env HOME="/home/$APP_USER" "$bin" || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf '\n'
|
|
||||||
if confirm "Tester la connexion à Claude (une requête minuscule sur Haiku) ?" o; then
|
|
||||||
local out
|
|
||||||
if out=$(cd /tmp && runuser -u "$APP_USER" -- env HOME="/home/$APP_USER" bash -c \
|
|
||||||
'set -a; . '"$APP_DIR"'/.env; exec "$CLAUDE_BIN" -p "Réponds uniquement: OK" --model haiku --max-turns 1' 2>&1); then
|
|
||||||
ok "Claude répond : ${out:0:60}"
|
|
||||||
else
|
|
||||||
warn "Claude ne répond pas : ${out:0:200}"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
do_start() {
|
|
||||||
section "Démarrage"
|
|
||||||
if (( DRY_RUN )); then info "[dry-run] démarrage ignoré"; return 0; fi
|
|
||||||
if ! config_complete; then
|
|
||||||
warn "Identifiants Google manquants : le service n'est pas démarré."
|
|
||||||
info "Complète $APP_DIR/.env puis : sudo systemctl start aitools"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
run "Démarrage d'AiTools" systemctl restart aitools
|
|
||||||
local i code=""
|
|
||||||
for i in $(seq 1 20); do
|
|
||||||
code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/login" || true)
|
|
||||||
[[ $code == 200 ]] && break
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
if [[ $code == 200 ]]; then ok "AiTools répond sur http://127.0.0.1:$PORT"
|
|
||||||
else warn "AiTools ne répond pas (HTTP ${code:-aucun}). Voir : journalctl -u aitools -n 50"; fi
|
|
||||||
}
|
|
||||||
|
|
||||||
finish() {
|
|
||||||
section "Terminé"
|
|
||||||
local domain; domain=$(sed -n 's|^APP_URL=||p' "$APP_DIR/.env" 2>/dev/null | tail -n1 || true)
|
|
||||||
row "Panel" "${domain:-https://$DOMAIN}"
|
|
||||||
row "Données" "$DATA_DIR"
|
|
||||||
(( BACKUPS )) && row "Sauvegardes" "$BACKUP_DIR (tous les jours à 04:30)"
|
|
||||||
row "Logs" "journalctl -u aitools -f"
|
|
||||||
row "Température" "vcgencmd measure_temp · vcgencmd get_throttled (0x0 = OK)"
|
|
||||||
row "Log install" "$LOG"
|
|
||||||
[[ $TUNNEL_MODE == later ]] && warn "Tunnel non configuré : relance ./install.sh quand tu as le token."
|
|
||||||
[[ $CLAUDE_MODE == later ]] && warn "Claude non connecté : relance ./install.sh pour le faire."
|
|
||||||
(( DRY_RUN )) && return 0
|
|
||||||
|
|
||||||
if [[ $SRC_DIR != "$APP_DIR" ]]; then
|
|
||||||
printf '\n'
|
|
||||||
info "L'application tourne depuis $APP_DIR. Le dossier cloné $SRC_DIR ne sert plus."
|
|
||||||
if confirm "Supprimer $SRC_DIR ?" n; then cd / && rm -rf -- "$SRC_DIR" && ok "Dossier source supprimé"; fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if (( NEED_REBOOT )); then
|
|
||||||
printf '\n'
|
|
||||||
if confirm "Un redémarrage est nécessaire (Wi-Fi/Bluetooth). Redémarrer maintenant ?" o; then
|
|
||||||
info "Redémarrage…"; sleep 2; reboot
|
|
||||||
else
|
|
||||||
warn "Pense à redémarrer : sudo reboot"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<EOF
|
|
||||||
Usage : sudo ./install.sh [--dry-run]
|
|
||||||
--dry-run pose les questions et affiche ce qui serait fait, sans rien modifier
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
|
||||||
for arg in "$@"; do
|
|
||||||
case $arg in
|
|
||||||
--dry-run) DRY_RUN=1 ;;
|
|
||||||
-h|--help) usage; exit 0 ;;
|
|
||||||
*) usage; die "Option inconnue : $arg" ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
banner
|
|
||||||
preflight
|
|
||||||
ask_storage
|
|
||||||
ask_backups
|
|
||||||
ask_network
|
|
||||||
ask_cleanup
|
|
||||||
ask_app
|
|
||||||
ask_tunnel
|
|
||||||
ask_claude
|
|
||||||
recap
|
|
||||||
|
|
||||||
do_upgrade
|
|
||||||
do_cleanup
|
|
||||||
do_storage
|
|
||||||
do_runtime
|
|
||||||
do_app
|
|
||||||
do_tunnel
|
|
||||||
do_claude
|
|
||||||
do_start
|
|
||||||
finish
|
|
||||||
}
|
|
||||||
|
|
||||||
# Tout est dans des fonctions : le script est entièrement lu avant de s'exécuter.
|
|
||||||
# (sourcé = mode test : on charge les fonctions sans lancer l'installation)
|
|
||||||
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then main "$@"; exit 0; fi
|
|
||||||
222
package-lock.json
generated
222
package-lock.json
generated
|
|
@ -8,7 +8,6 @@
|
||||||
"name": "aitools",
|
"name": "aitools",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"imapflow": "^1.7.8",
|
|
||||||
"mysql2": "^3.11.0",
|
"mysql2": "^3.11.0",
|
||||||
"nodemailer": "^6.9.15",
|
"nodemailer": "^6.9.15",
|
||||||
"pg": "^8.13.0"
|
"pg": "^8.13.0"
|
||||||
|
|
@ -17,12 +16,6 @@
|
||||||
"node": ">=22.13"
|
"node": ">=22.13"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@pinojs/redact": {
|
|
||||||
"version": "0.4.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
|
||||||
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "26.6.5",
|
"version": "26.6.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
|
||||||
|
|
@ -33,26 +26,6 @@
|
||||||
"undici-types": "~8.9.0"
|
"undici-types": "~8.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@zone-eu/mailsplit": {
|
|
||||||
"version": "5.4.16",
|
|
||||||
"resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.16.tgz",
|
|
||||||
"integrity": "sha512-zQ9iXvlT3Wi/hazeC1MdI4rQc1UJwJ6IQ6QzSZ5KDxLZZWQSazWLOzImLFluXadKShJ9WJvI1xH+AyVS8b9azg==",
|
|
||||||
"license": "(MIT OR EUPL-1.1+)",
|
|
||||||
"dependencies": {
|
|
||||||
"libbase64": "1.3.0",
|
|
||||||
"libmime": "5.4.3",
|
|
||||||
"libqp": "2.1.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/atomic-sleep": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=8.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/aws-ssl-profiles": {
|
"node_modules/aws-ssl-profiles": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
||||||
|
|
@ -62,15 +35,6 @@
|
||||||
"node": ">= 6.0.0"
|
"node": ">= 6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/encoding-japanese": {
|
|
||||||
"version": "2.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/encoding-japanese/-/encoding-japanese-2.3.0.tgz",
|
|
||||||
"integrity": "sha512-eQyh1vzHz13DUkZcJO+0IOAoKXRQwKV5IBffeuYsWZyRLGiSzfzXObCqWvqFXdX0UU8qOk+lBXbkUhMCpdJe4Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/generate-function": {
|
"node_modules/generate-function": {
|
||||||
"version": "2.3.1",
|
"version": "2.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||||
|
|
@ -96,61 +60,12 @@
|
||||||
"url": "https://opencollective.com/express"
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/imapflow": {
|
|
||||||
"version": "1.7.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/imapflow/-/imapflow-1.7.8.tgz",
|
|
||||||
"integrity": "sha512-dJoCIdZOJh26Rn2PdwEzwj0bRDgGBxxX38pio534FagIHVuR2l0SAfLr6sJo32YfuJHiSs/U2ntNDHnMg3/Hlg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@zone-eu/mailsplit": "5.4.16",
|
|
||||||
"encoding-japanese": "2.3.0",
|
|
||||||
"iconv-lite": "0.7.3",
|
|
||||||
"libbase64": "1.3.0",
|
|
||||||
"libmime": "5.4.3",
|
|
||||||
"libqp": "2.1.1",
|
|
||||||
"pino": "10.3.1",
|
|
||||||
"socks": "2.8.9"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ip-address": {
|
|
||||||
"version": "10.7.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz",
|
|
||||||
"integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 12"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/is-property": {
|
"node_modules/is-property": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/libbase64": {
|
|
||||||
"version": "1.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.0.tgz",
|
|
||||||
"integrity": "sha512-GgOXd0Eo6phYgh0DJtjQ2tO8dc0IVINtZJeARPeiIJqge+HdsWSuaDTe8ztQ7j/cONByDZ3zeB325AHiv5O0dg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/libmime": {
|
|
||||||
"version": "5.4.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.3.tgz",
|
|
||||||
"integrity": "sha512-di9BoDabBUMqjeD/wGj+hHpSgdqAph5ui7w6OdY6NpzU6O6VFLQsMOg9tqCjm/zf9OHzAM9EZxSOF7uIb8O8Hw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"encoding-japanese": "2.3.0",
|
|
||||||
"iconv-lite": "0.7.3",
|
|
||||||
"libbase64": "1.3.0",
|
|
||||||
"libqp": "2.1.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/libqp": {
|
|
||||||
"version": "2.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.1.tgz",
|
|
||||||
"integrity": "sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/long": {
|
"node_modules/long": {
|
||||||
"version": "5.3.2",
|
"version": "5.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
||||||
|
|
@ -214,15 +129,6 @@
|
||||||
"node": ">=6.0.0"
|
"node": ">=6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/on-exit-leak-free": {
|
|
||||||
"version": "2.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
|
|
||||||
"integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=14.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/pg": {
|
"node_modules/pg": {
|
||||||
"version": "8.23.1",
|
"version": "8.23.1",
|
||||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||||
|
|
@ -312,43 +218,6 @@
|
||||||
"split2": "^4.1.0"
|
"split2": "^4.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/pino": {
|
|
||||||
"version": "10.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
|
|
||||||
"integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@pinojs/redact": "^0.4.0",
|
|
||||||
"atomic-sleep": "^1.0.0",
|
|
||||||
"on-exit-leak-free": "^2.1.0",
|
|
||||||
"pino-abstract-transport": "^3.0.0",
|
|
||||||
"pino-std-serializers": "^7.0.0",
|
|
||||||
"process-warning": "^5.0.0",
|
|
||||||
"quick-format-unescaped": "^4.0.3",
|
|
||||||
"real-require": "^0.2.0",
|
|
||||||
"safe-stable-stringify": "^2.3.1",
|
|
||||||
"sonic-boom": "^4.0.1",
|
|
||||||
"thread-stream": "^4.0.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"pino": "bin.js"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/pino-abstract-transport": {
|
|
||||||
"version": "3.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
|
|
||||||
"integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"split2": "^4.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/pino-std-serializers": {
|
|
||||||
"version": "7.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",
|
|
||||||
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/postgres-array": {
|
"node_modules/postgres-array": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
|
|
@ -388,85 +257,12 @@
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/process-warning": {
|
|
||||||
"version": "5.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz",
|
|
||||||
"integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==",
|
|
||||||
"funding": [
|
|
||||||
{
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/fastify"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "opencollective",
|
|
||||||
"url": "https://opencollective.com/fastify"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/quick-format-unescaped": {
|
|
||||||
"version": "4.0.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
|
|
||||||
"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/real-require": {
|
|
||||||
"version": "0.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
|
|
||||||
"integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 12.13.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/safe-stable-stringify": {
|
|
||||||
"version": "2.5.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
|
|
||||||
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=10"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/safer-buffer": {
|
"node_modules/safer-buffer": {
|
||||||
"version": "2.1.2",
|
"version": "2.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/smart-buffer": {
|
|
||||||
"version": "4.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
|
|
||||||
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 6.0.0",
|
|
||||||
"npm": ">= 3.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/socks": {
|
|
||||||
"version": "2.8.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz",
|
|
||||||
"integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"ip-address": "^10.1.1",
|
|
||||||
"smart-buffer": "^4.2.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 10.0.0",
|
|
||||||
"npm": ">= 3.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/sonic-boom": {
|
|
||||||
"version": "4.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
|
|
||||||
"integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"atomic-sleep": "^1.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/split2": {
|
"node_modules/split2": {
|
||||||
"version": "4.2.0",
|
"version": "4.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||||
|
|
@ -491,24 +287,6 @@
|
||||||
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/thread-stream": {
|
|
||||||
"version": "4.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
|
|
||||||
"integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"real-require": "^1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/thread-stream/node_modules/real-require": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/undici-types": {
|
"node_modules/undici-types": {
|
||||||
"version": "8.9.0",
|
"version": "8.9.0",
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@
|
||||||
"hooks": "git config core.hooksPath .githooks"
|
"hooks": "git config core.hooksPath .githooks"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"imapflow": "^1.7.8",
|
|
||||||
"mysql2": "^3.11.0",
|
"mysql2": "^3.11.0",
|
||||||
"nodemailer": "^6.9.15",
|
"nodemailer": "^6.9.15",
|
||||||
"pg": "^8.13.0"
|
"pg": "^8.13.0"
|
||||||
|
|
|
||||||
|
|
@ -2,14 +2,12 @@
|
||||||
--bg: #f4f5f7; --card: #fff; --text: #17191c; --muted: #6b7078; --line: #e2e4e8;
|
--bg: #f4f5f7; --card: #fff; --text: #17191c; --muted: #6b7078; --line: #e2e4e8;
|
||||||
--accent: #2f5bea; --accent-text: #fff; --ok: #15803d; --warn: #b45309; --err: #b91c1c;
|
--accent: #2f5bea; --accent-text: #fff; --ok: #15803d; --warn: #b45309; --err: #b91c1c;
|
||||||
--locked: #eceef1; --radius: 10px;
|
--locked: #eceef1; --radius: 10px;
|
||||||
--series-1: #2a78d6; --series-2: #eb6834; /* paire validée (daltonisme, contraste) sur fond clair */
|
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
}
|
}
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
:root {
|
:root {
|
||||||
--bg: #111317; --card: #1a1d22; --text: #e8eaed; --muted: #9097a1; --line: #2b2f36;
|
--bg: #111317; --card: #1a1d22; --text: #e8eaed; --muted: #9097a1; --line: #2b2f36;
|
||||||
--accent: #5b82ff; --ok: #4ade80; --warn: #fbbf24; --err: #f87171; --locked: #23272e;
|
--accent: #5b82ff; --ok: #4ade80; --warn: #fbbf24; --err: #f87171; --locked: #23272e;
|
||||||
--series-1: #3987e5; --series-2: #d95926; /* mêmes teintes, pas d'inversion automatique */
|
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -99,60 +97,3 @@ pre.md { white-space: pre-wrap; background: var(--locked); padding: 12px; border
|
||||||
.toast.error { background: var(--err); color: #fff; }
|
.toast.error { background: var(--err); color: #fff; }
|
||||||
form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
|
form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||||
@media (max-width: 640px) { .sys { order: 3; flex-basis: 100%; } }
|
@media (max-width: 640px) { .sys { order: 3; flex-basis: 100%; } }
|
||||||
.inbox { margin: 10px 0 4px; line-height: 1.9; }
|
|
||||||
.inbox:empty { display: none; }
|
|
||||||
.followup { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); }
|
|
||||||
.running.scheduled { background: transparent; border: 1px dashed var(--line); }
|
|
||||||
.moon { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset -5px -3px 0 0 var(--accent); flex: none; transform: rotate(-20deg); }
|
|
||||||
.checks { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 0 12px; margin: 4px 0 10px; }
|
|
||||||
.checks label.check { margin: 4px 0; }
|
|
||||||
.pfilters { display: grid; grid-template-columns: 2fr repeat(4, auto); gap: 8px; margin: 10px 0; }
|
|
||||||
.pfilters input, .pfilters select { margin: 0; }
|
|
||||||
@media (max-width: 640px) { .pfilters { grid-template-columns: 1fr 1fr; } .pfilters input { grid-column: 1 / -1; } }
|
|
||||||
.pager { display: flex; gap: 10px; align-items: center; justify-content: center; margin: 8px 0; }
|
|
||||||
select.st-replied, select.st-client { color: var(--ok); font-weight: 600; }
|
|
||||||
select.st-refused, select.st-bounced { color: var(--err); }
|
|
||||||
select.st-new { color: var(--accent); }
|
|
||||||
.prospect-dialog { width: min(720px, calc(100vw - 32px)); max-height: calc(100vh - 48px); border: 1px solid var(--line); border-radius: var(--radius); background: var(--card); color: var(--text); padding: 18px; }
|
|
||||||
.prospect-dialog::backdrop { background: rgba(0, 0, 0, .45); }
|
|
||||||
.dlg-head { align-items: flex-start; }
|
|
||||||
.dlg-head h3 { margin: 0 0 4px; }
|
|
||||||
.hook { font-style: italic; border-left: 3px solid var(--accent); padding-left: 10px; margin: 10px 0; }
|
|
||||||
.timeline { list-style: none; padding: 0; margin: 0; border-left: 2px solid var(--line); }
|
|
||||||
.timeline li { position: relative; padding: 0 0 10px 14px; }
|
|
||||||
.timeline li::before { content: ""; position: absolute; left: -6px; top: 6px; width: 10px; height: 10px; border-radius: 50%; background: var(--accent); }
|
|
||||||
.timeline time { display: block; font-size: .8rem; color: var(--muted); }
|
|
||||||
.notes { list-style: none; padding: 0; }
|
|
||||||
.notes li { border-top: 1px solid var(--line); padding: 8px 0; }
|
|
||||||
.note-body { white-space: pre-wrap; }
|
|
||||||
.pfilters .todo { margin: 0; align-self: center; }
|
|
||||||
@media (max-width: 640px) { .pfilters .todo { grid-column: 1 / -1; } }
|
|
||||||
.csv { justify-content: flex-start; margin: 4px 0 8px; }
|
|
||||||
label.btn.file { display: inline-block; margin: 0; color: var(--text); font-size: .85rem; }
|
|
||||||
.chart-head { margin-top: 14px; }
|
|
||||||
.chart-head h4 { margin: 0; }
|
|
||||||
.seg { display: flex; gap: 6px; }
|
|
||||||
.seg [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
|
|
||||||
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; margin: 10px 0; }
|
|
||||||
figure.chart { position: relative; margin: 0; border: 1px solid var(--line); border-radius: 8px; padding: 10px; min-width: 0; }
|
|
||||||
figure.chart figcaption { font-size: .85rem; font-weight: 600; margin-bottom: 4px; }
|
|
||||||
.chart .plot { width: 100%; }
|
|
||||||
.chart svg { display: block; overflow: visible; touch-action: pan-y; }
|
|
||||||
.chart .grid { stroke: var(--line); stroke-width: 1; }
|
|
||||||
.chart .base { stroke: var(--muted); stroke-width: 1; }
|
|
||||||
.chart .axis { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
|
||||||
.chart .end { fill: var(--text); font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
|
||||||
.chart .line { fill: none; stroke: var(--series-1); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
|
|
||||||
.chart .dot { fill: var(--series-1); stroke: var(--card); stroke-width: 2; }
|
|
||||||
.chart .cross { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 3 3; }
|
|
||||||
.chart .cross, .chart .dot.hover { visibility: hidden; }
|
|
||||||
.chart.hovering .cross, .chart.hovering .dot.hover { visibility: visible; }
|
|
||||||
.chart .b1 { fill: var(--series-1); }
|
|
||||||
.chart .b2 { fill: var(--series-2); }
|
|
||||||
.chart .hit { fill: transparent; cursor: crosshair; }
|
|
||||||
.chart .tip { position: absolute; transform: translate(-50%, -100%); pointer-events: none; background: var(--card); color: var(--text);
|
|
||||||
border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; font-size: 12px; white-space: nowrap; box-shadow: 0 2px 10px rgba(0,0,0,.15); z-index: 2; }
|
|
||||||
.legend { margin: 0 0 4px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; color: var(--muted); }
|
|
||||||
.sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-left: 8px; }
|
|
||||||
.sw.s1 { background: var(--series-1); margin-left: 0; }
|
|
||||||
.sw.s2 { background: var(--series-2); }
|
|
||||||
|
|
|
||||||
434
public/app.js
434
public/app.js
|
|
@ -23,27 +23,10 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
const formData = (form) => Object.fromEntries(new FormData(form));
|
const formData = (form) => Object.fromEntries(new FormData(form));
|
||||||
const ago = (ts) => {
|
|
||||||
if (!ts) return 'jamais';
|
|
||||||
const m = Math.round((Date.now() / 1000 - ts) / 60);
|
|
||||||
return m < 1 ? "à l'instant" : m < 60 ? `il y a ${m} min` : m < 1440 ? `il y a ${Math.round(m / 60)} h` : `il y a ${Math.round(m / 1440)} j`;
|
|
||||||
};
|
|
||||||
const pct = (x) => `${Math.round(x * 100)} %`;
|
|
||||||
const ACTIVE = ['queued', 'running'];
|
const ACTIVE = ['queued', 'running'];
|
||||||
const LABELS = {
|
const LABELS = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions' };
|
||||||
analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions',
|
|
||||||
followup_template: 'Modèle de relance', followup: 'Relances',
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---------- Barre système ----------
|
// ---------- Barre système ----------
|
||||||
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
|
||||||
function gauge(label, x) {
|
|
||||||
const used = `${x.used.toFixed(2)} $`;
|
|
||||||
if (!x.limit) return `<span title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used}</span>`;
|
|
||||||
const r = x.used / x.limit;
|
|
||||||
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshSys() {
|
async function refreshSys() {
|
||||||
const el = $('#sys');
|
const el = $('#sys');
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
@ -51,10 +34,8 @@
|
||||||
const s = await api('/api/system');
|
const s = await api('/api/system');
|
||||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
<span title="Équivalent API, consommé sur ton quota Pro">IA 24 h : $${s.usage.day.cost.toFixed(2)} · 30 j : $${s.usage.month.cost.toFixed(2)}</span>
|
||||||
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}
|
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}`;
|
||||||
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
|
|
||||||
${s.scheduled ? `<span>${s.scheduled} programmé(s) cette nuit</span>` : ''}`;
|
|
||||||
} catch { /* silencieux */ }
|
} catch { /* silencieux */ }
|
||||||
}
|
}
|
||||||
refreshSys();
|
refreshSys();
|
||||||
|
|
@ -65,18 +46,11 @@
|
||||||
if (!box) return;
|
if (!box) return;
|
||||||
if (!job) { box.innerHTML = ''; return; }
|
if (!job) { box.innerHTML = ''; return; }
|
||||||
const p = job.progress || {};
|
const p = job.progress || {};
|
||||||
if (job.status === 'queued' && job.runAfter && job.runAfter * 1000 > Date.now()) {
|
|
||||||
const at = new Date(job.runAfter * 1000).toLocaleString('fr-FR', { weekday: 'long', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' });
|
|
||||||
box.innerHTML = `<div class="running scheduled"><span class="moon" aria-hidden="true"></span>
|
|
||||||
<div><div>${LABELS[type]} programmé(e) : ${esc(at)}</div><div class="small muted">Le Pi est au frais et ton quota Claude est libre.</div></div>
|
|
||||||
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (ACTIVE.includes(job.status)) {
|
if (ACTIVE.includes(job.status)) {
|
||||||
const extra = type === 'prospect' && p.found !== undefined
|
const extra = type === 'prospect' && p.found !== undefined
|
||||||
? `<strong>${p.found}</strong> prospect(s) trouvé(s) sur ${p.target}` : '';
|
? `<strong>${p.found}</strong> prospect(s) trouvé(s) sur ${p.target}` : '';
|
||||||
box.innerHTML = `<div class="running"><span class="spinner"></span>
|
box.innerHTML = `<div class="running"><span class="spinner"></span>
|
||||||
<div><div>${esc(p.message || (job.status === 'queued' ? 'En file d\'attente…' : 'En cours…'))}</div>${extra ? `<div class="small">${extra}</div>` : ''}</div>
|
<div><div>${esc(job.status === 'queued' ? 'En file d\'attente…' : p.message || 'En cours…')}</div>${extra ? `<div class="small">${extra}</div>` : ''}</div>
|
||||||
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
|
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
|
||||||
} else if (job.status === 'error') {
|
} else if (job.status === 'error') {
|
||||||
box.innerHTML = `<p class="error small">${LABELS[type]} en échec : ${esc(job.error)}</p>`;
|
box.innerHTML = `<p class="error small">${LABELS[type]} en échec : ${esc(job.error)}</p>`;
|
||||||
|
|
@ -87,7 +61,6 @@
|
||||||
let txt = `${LABELS[type]} terminé(e).`;
|
let txt = `${LABELS[type]} terminé(e).`;
|
||||||
if (type === 'prospect') txt = `Recherche terminée : ${r.found} nouveau(x) prospect(s) sur ${r.requested} demandés.`;
|
if (type === 'prospect') txt = `Recherche terminée : ${r.found} nouveau(x) prospect(s) sur ${r.requested} demandés.`;
|
||||||
if (type === 'send') txt = `Envoi terminé : ${r.sent} envoyé(s), ${r.failed} échec(s).`;
|
if (type === 'send') txt = `Envoi terminé : ${r.sent} envoyé(s), ${r.failed} échec(s).`;
|
||||||
if (type === 'followup') txt = r.postponed ? 'Relances reportées au prochain créneau (lun-ven 9h-18h).' : `Relances terminées : ${r.sent} envoyée(s), ${r.failed} échec(s).`;
|
|
||||||
if (type === 'evolution') {
|
if (type === 'evolution') {
|
||||||
box.innerHTML = `<p class="ok small">Envoyé à ${esc(r.sentTo)}.</p><pre class="md">${esc(r.markdown)}</pre>`;
|
box.innerHTML = `<p class="ok small">Envoyé à ${esc(r.sentTo)}.</p><pre class="md">${esc(r.markdown)}</pre>`;
|
||||||
return;
|
return;
|
||||||
|
|
@ -105,7 +78,7 @@
|
||||||
try { s = await api(`/api/projects/${id}/status`); } catch (e) { return schedule(el, 30_000); }
|
try { s = await api(`/api/projects/${id}/status`); } catch (e) { return schedule(el, 30_000); }
|
||||||
const st = state.get(id) || {};
|
const st = state.get(id) || {};
|
||||||
const jobs = s.jobs;
|
const jobs = s.jobs;
|
||||||
for (const type of ['prospect', 'template', 'send', 'evolution', 'followup_template', 'followup']) renderJob($(`[data-job="${type}"]`, el), jobs[type], type);
|
for (const type of ['prospect', 'template', 'send', 'evolution']) renderJob($(`[data-job="${type}"]`, el), jobs[type], type);
|
||||||
|
|
||||||
const running = Object.entries(jobs).filter(([, j]) => ACTIVE.includes(j.status)).map(([t]) => LABELS[t]);
|
const running = Object.entries(jobs).filter(([, j]) => ACTIVE.includes(j.status)).map(([t]) => LABELS[t]);
|
||||||
$('[data-state]', el).innerHTML = running.length
|
$('[data-state]', el).innerHTML = running.length
|
||||||
|
|
@ -123,29 +96,14 @@
|
||||||
if (an?.status === 'error' && !s.hasProfile) $('.profile p', el).outerHTML = `<p class="error small">${esc(an.error)}</p>`;
|
if (an?.status === 'error' && !s.hasProfile) $('.profile p', el).outerHTML = `<p class="error small">${esc(an.error)}</p>`;
|
||||||
|
|
||||||
// Modèle de mail : on ne remplace le formulaire que s'il a changé côté serveur
|
// Modèle de mail : on ne remplace le formulaire que s'il a changé côté serveur
|
||||||
st.tplStamp ||= {};
|
const tplForm = $('form[data-action="template"]', el);
|
||||||
for (const kind of ['initial', 'followup']) {
|
if (s.template && st.tplStamp !== s.template.updated_at) {
|
||||||
const t = s.templates[kind];
|
st.tplStamp = s.template.updated_at;
|
||||||
const form = $(`form[data-action="template"][data-kind="${kind}"]`, el);
|
tplForm.subject.value = s.template.subject;
|
||||||
if (t && st.tplStamp[kind] !== t.updated_at) {
|
tplForm.body.value = s.template.body;
|
||||||
st.tplStamp[kind] = t.updated_at;
|
|
||||||
form.subject.value = t.subject;
|
|
||||||
if (form.subjectB) form.subjectB.value = t.subjectB || '';
|
|
||||||
form.body.value = t.body;
|
|
||||||
}
|
|
||||||
$('[data-tpl-state]', form).innerHTML = t
|
|
||||||
? (t.status === 'validated' ? '<span class="badge ok">validé</span>' : '<span class="badge warn">brouillon</span>') : '';
|
|
||||||
}
|
}
|
||||||
|
$('[data-tpl-state]', el).innerHTML = s.template
|
||||||
// Relance automatique : ce qui est prévu, ou ce qui bloque
|
? (s.template.status === 'validated' ? '<span class="badge ok">validé</span>' : '<span class="badge warn">brouillon</span>') : '';
|
||||||
const f = s.followup;
|
|
||||||
$('[data-followup-info]', el).innerHTML = !f.enabled
|
|
||||||
? 'Désactivée.'
|
|
||||||
: f.blockers.length
|
|
||||||
? `<span class="warn">En attente : ${esc(f.blockers.join(', '))}.</span> ${f.due} relance(s) due(s).`
|
|
||||||
: f.due
|
|
||||||
? `${f.due} relance(s) due(s) : ${f.inHours ? 'envoi au prochain passage (≤ 15 min)' : 'envoi aux heures ouvrées (lun-ven 9h-18h)'}.`
|
|
||||||
: `Active : les prospects sans réponse après ${f.days} jours seront relancés une fois.`;
|
|
||||||
|
|
||||||
// Bouton Envoyer : recherche finie + modèle validé + SMTP + quota dispo
|
// Bouton Envoyer : recherche finie + modèle validé + SMTP + quota dispo
|
||||||
const prospecting = jobs.prospect && ACTIVE.includes(jobs.prospect.status);
|
const prospecting = jobs.prospect && ACTIVE.includes(jobs.prospect.status);
|
||||||
|
|
@ -154,7 +112,7 @@
|
||||||
const blockers = [];
|
const blockers = [];
|
||||||
if (prospecting) blockers.push('recherche en cours');
|
if (prospecting) blockers.push('recherche en cours');
|
||||||
if (sending) blockers.push('envoi en cours');
|
if (sending) blockers.push('envoi en cours');
|
||||||
if (s.templates.initial?.status !== 'validated') blockers.push('modèle à valider');
|
if (s.template?.status !== 'validated') blockers.push('modèle à valider');
|
||||||
if (!s.hasSmtp) blockers.push('SMTP à configurer');
|
if (!s.hasSmtp) blockers.push('SMTP à configurer');
|
||||||
if (!s.sendMax) blockers.push(s.stats.new ? 'plafond du jour atteint' : 'aucun prospect à contacter');
|
if (!s.sendMax) blockers.push(s.stats.new ? 'plafond du jour atteint' : 'aucun prospect à contacter');
|
||||||
$('button', sendForm).disabled = blockers.length > 0;
|
$('button', sendForm).disabled = blockers.length > 0;
|
||||||
|
|
@ -165,19 +123,6 @@
|
||||||
: `${s.stats.new} prospect(s) en attente · max ${s.sendMax} maintenant`;
|
: `${s.stats.new} prospect(s) en attente · max ${s.sendMax} maintenant`;
|
||||||
$('[data-count]', el).textContent = `(${s.stats.total || 0})`;
|
$('[data-count]', el).textContent = `(${s.stats.total || 0})`;
|
||||||
|
|
||||||
// Boîte de réception + test A/B
|
|
||||||
const ib = $('[data-inbox]', el);
|
|
||||||
const ab = s.ab.length > 1
|
|
||||||
? `<br>Test A/B : ${s.ab.map((v) => `<strong>${v.variant}</strong> ${v.replied}/${v.sent} réponses (${pct(v.rate)})`).join(' · ')}` : '';
|
|
||||||
if (!s.hasImap) {
|
|
||||||
ib.innerHTML = `<span class="muted">Boîte non connectée : configure l'IMAP (Configuration du projet) pour détecter les réponses.</span>${ab}`;
|
|
||||||
} else {
|
|
||||||
const i = s.inbox || {};
|
|
||||||
const head = i.lastError ? `<span class="error">Boîte en erreur : ${esc(i.lastError)}</span>` : `Boîte vérifiée ${ago(i.lastOk)}`;
|
|
||||||
ib.innerHTML = `${head} · ${i.replies || 0} réponse(s) · ${i.bounces || 0} adresse(s) invalide(s)
|
|
||||||
<button class="btn small" data-inbox-check="${id}">Vérifier maintenant</button>${ab}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
state.set(id, st);
|
state.set(id, st);
|
||||||
schedule(el, running.length ? 4000 : 30_000);
|
schedule(el, running.length ? 4000 : 30_000);
|
||||||
}
|
}
|
||||||
|
|
@ -231,28 +176,6 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true);
|
if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true);
|
||||||
|
|
||||||
if (e.target.closest('[data-report-send]')) {
|
|
||||||
try { const r = await api('/api/report/send', {}); toast(`Rapport envoyé (${r.channels.join(' + ')})`); }
|
|
||||||
catch (err) { toast(err.message, 'error'); }
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e.target.closest('[data-notify-test]')) {
|
|
||||||
try { await api('/api/notify/test', {}); toast('Notification envoyée sur Discord'); }
|
|
||||||
catch (err) { toast(err.message, 'error'); }
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const inboxBtn = e.target.closest('[data-inbox-check]');
|
|
||||||
if (inboxBtn) {
|
|
||||||
inboxBtn.disabled = true;
|
|
||||||
try {
|
|
||||||
const r = await api(`/api/projects/${inboxBtn.dataset.inboxCheck}/inbox/check`, {});
|
|
||||||
toast(`Boîte lue : ${r.check.replies} nouvelle(s) réponse(s), ${r.check.bounces} rejet(s)`);
|
|
||||||
} catch (err) { toast(err.message, 'error'); }
|
|
||||||
refreshProject(inboxBtn.closest('.project'));
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------- Formulaires ----------
|
// ---------- Formulaires ----------
|
||||||
|
|
@ -276,19 +199,12 @@
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break;
|
case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break;
|
||||||
case 'prospect': {
|
case 'prospect': await api(`/api/projects/${id}/prospect`, data); toast('Recherche lancée en arrière-plan'); break;
|
||||||
const r = await api(`/api/projects/${id}/prospect`, data);
|
|
||||||
toast(r.budgetBlocked ? `En file, mais ${r.budgetBlocked}` : r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Recherche programmée cette nuit' : 'Recherche lancée en arrière-plan', r.budgetBlocked ? 'error' : 'ok');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'evolution': {
|
case 'evolution': {
|
||||||
if (data.level === 'approfondi' && !confirm('Le niveau approfondi utilise Opus et consomme beaucoup de quota. Continuer ?')) break;
|
if (data.level === 'approfondi' && !confirm('Le niveau approfondi utilise Opus et consomme beaucoup de quota. Continuer ?')) break;
|
||||||
const r = await api(`/api/projects/${id}/evolution`, data);
|
await api(`/api/projects/${id}/evolution`, data); toast('Recherche d\'évolutions lancée'); break;
|
||||||
toast(r.budgetBlocked ? `En file, mais ${r.budgetBlocked}` : r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Évolutions programmées cette nuit' : 'Recherche d\'évolutions lancée', r.budgetBlocked ? 'error' : 'ok');
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
case 'template': {
|
case 'template': {
|
||||||
data.kind = form.dataset.kind;
|
|
||||||
const r = await api(`/api/projects/${id}/template/save`, data);
|
const r = await api(`/api/projects/${id}/template/save`, data);
|
||||||
toast(r.status === 'validated' ? 'Modèle validé' : 'Brouillon enregistré');
|
toast(r.status === 'validated' ? 'Modèle validé' : 'Brouillon enregistré');
|
||||||
break;
|
break;
|
||||||
|
|
@ -301,20 +217,6 @@
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'smtp': data.pass ||= ''; await api(`/api/projects/${id}/smtp`, data); toast('SMTP enregistré'); form.pass.value = ''; break;
|
case 'smtp': data.pass ||= ''; await api(`/api/projects/${id}/smtp`, data); toast('SMTP enregistré'); form.pass.value = ''; break;
|
||||||
case 'imap': {
|
|
||||||
const r = await api(`/api/projects/${id}/imap`, data);
|
|
||||||
form.pass.value = '';
|
|
||||||
if (r.disabled) toast('Détection des réponses désactivée');
|
|
||||||
else if (r.ok) toast(`Boîte connectée : ${r.check.replies} réponse(s) trouvée(s)`);
|
|
||||||
else toast(r.error, 'error');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'followup': {
|
|
||||||
data.enabled = form.enabled.checked;
|
|
||||||
await api(`/api/projects/${id}/followup`, data);
|
|
||||||
toast(data.enabled ? 'Relance automatique activée' : 'Relance automatique désactivée');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'db': data.ssl = form.ssl.checked; await api(`/api/projects/${id}/db`, data); toast('Accès BDD enregistré'); form.password.value = ''; break;
|
case 'db': data.ssl = form.ssl.checked; await api(`/api/projects/${id}/db`, data); toast('Accès BDD enregistré'); form.password.value = ''; break;
|
||||||
case 'delete': await api(`/api/projects/${id}/delete`, {}); location.reload(); break;
|
case 'delete': await api(`/api/projects/${id}/delete`, {}); location.reload(); break;
|
||||||
}
|
}
|
||||||
|
|
@ -327,150 +229,6 @@
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------- Courbes (SVG maison : pas de lib externe, CSP stricte) ----------
|
|
||||||
// Dessinées à la largeur réelle du conteneur (1 unité = 1 px) pour que les textes restent lisibles sur mobile.
|
|
||||||
const M = { l: 46, r: 56, t: 12, b: 24, h: 150 };
|
|
||||||
const niceMax = (v) => { if (!(v > 0)) return 1; const p = 10 ** Math.floor(Math.log10(v)); const m = v / p; return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p; };
|
|
||||||
const fmtVal = (v, unit) => (unit === '€'
|
|
||||||
? v.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 })
|
|
||||||
: v.toLocaleString('fr-FR', { maximumFractionDigits: 1 }));
|
|
||||||
const shortDay = (d) => { const [, m, dd] = d.split('-'); return `${dd}/${m}`; };
|
|
||||||
const yGrid = (w, max, unit, Y) => [0, 0.5, 1].map((f) => `<line class="grid" x1="${M.l}" x2="${w - M.r}" y1="${Y(max * f)}" y2="${Y(max * f)}"/>
|
|
||||||
<text class="axis" x="${M.l - 6}" y="${Y(max * f) + 4}" text-anchor="end">${esc(fmtVal(max * f, unit))}</text>`).join('');
|
|
||||||
|
|
||||||
function drawLine(fig, w) {
|
|
||||||
const { unit, xs, ys } = JSON.parse(fig.dataset.series);
|
|
||||||
const max = niceMax(Math.max(...ys));
|
|
||||||
const step = (w - M.l - M.r) / (xs.length - 1);
|
|
||||||
const X = (i) => M.l + i * step;
|
|
||||||
const Y = (v) => M.t + (M.h - M.t - M.b) * (1 - v / max);
|
|
||||||
const d = ys.map((v, i) => `${i ? 'L' : 'M'}${X(i).toFixed(1)},${Y(v).toFixed(1)}`).join('');
|
|
||||||
const n = xs.length - 1;
|
|
||||||
fig.querySelector('.plot').innerHTML = `<svg width="${w}" height="${M.h}" role="img" aria-label="${esc(fig.dataset.title)}">
|
|
||||||
${yGrid(w, max, unit, Y)}
|
|
||||||
<text class="axis" x="${M.l}" y="${M.h - 6}">${shortDay(xs[0])}</text>
|
|
||||||
<text class="axis" x="${w - M.r}" y="${M.h - 6}" text-anchor="end">${shortDay(xs[n])}</text>
|
|
||||||
<path class="line" d="${d}"/>
|
|
||||||
<circle class="dot" cx="${X(n)}" cy="${Y(ys[n])}" r="4"/>
|
|
||||||
<text class="end" x="${X(n) + 8}" y="${Y(ys[n]) + 4}">${esc(fmtVal(ys[n], unit))}</text>
|
|
||||||
<line class="cross" x1="0" x2="0" y1="${M.t}" y2="${M.h - M.b}"/>
|
|
||||||
<circle class="dot hover" r="5"/>
|
|
||||||
<rect class="hit" x="${M.l - step / 2}" y="0" width="${w - M.l - M.r + step}" height="${M.h}"/>
|
|
||||||
</svg>`;
|
|
||||||
fig._hover = (vx) => {
|
|
||||||
const i = Math.max(0, Math.min(n, Math.round((vx - M.l) / step)));
|
|
||||||
return { x: X(i), y: Y(ys[i]), html: `<strong>${esc(fmtVal(ys[i], unit))}</strong> · ${shortDay(xs[i])}` };
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Barres arrondies en haut (4 px), à plat sur la ligne de base
|
|
||||||
const bar = (x, y, bw, base) => {
|
|
||||||
const r = Math.min(4, bw / 2, base - y);
|
|
||||||
return base - y < 1 ? '' : `M${x},${base}V${y + r}Q${x},${y} ${x + r},${y}H${x + bw - r}Q${x + bw},${y} ${x + bw},${y + r}V${base}Z`;
|
|
||||||
};
|
|
||||||
|
|
||||||
function drawBars(fig, w) {
|
|
||||||
const { weeks } = JSON.parse(fig.dataset.series);
|
|
||||||
const max = niceMax(Math.max(1, ...weeks.flatMap((x) => [x.sent, x.replies])));
|
|
||||||
const base = M.h - M.b;
|
|
||||||
const Y = (v) => M.t + (base - M.t) * (1 - v / max);
|
|
||||||
const gw = (w - M.l - M.r) / weeks.length;
|
|
||||||
const bw = Math.max(3, Math.min(18, (gw - 8) / 2));
|
|
||||||
// Une étiquette de date tous les ~56 px au minimum, quelle que soit la largeur
|
|
||||||
const every = Math.max(1, Math.ceil(weeks.length / Math.max(1, Math.floor((w - M.l - M.r) / 56))));
|
|
||||||
const marks = weeks.map((x, i) => {
|
|
||||||
const x0 = M.l + i * gw + (gw - (2 * bw + 2)) / 2;
|
|
||||||
const last = i === weeks.length - 1;
|
|
||||||
return `<path class="b1" d="${bar(x0, Y(x.sent), bw, base)}"/><path class="b2" d="${bar(x0 + bw + 2, Y(x.replies), bw, base)}"/>
|
|
||||||
${(weeks.length - 1 - i) % every === 0 ? `<text class="axis" x="${x0 + bw + 1}" y="${M.h - 6}" text-anchor="middle">${shortDay(x.start)}</text>` : ''}
|
|
||||||
${last ? `<text class="end" x="${x0 + bw / 2}" y="${Y(x.sent) - 5}" text-anchor="middle">${x.sent}</text>
|
|
||||||
<text class="end" x="${x0 + bw * 1.5 + 2}" y="${Y(x.replies) - 5}" text-anchor="middle">${x.replies}</text>` : ''}`;
|
|
||||||
}).join('');
|
|
||||||
fig.querySelector('.plot').innerHTML = `<svg width="${w}" height="${M.h}" role="img" aria-label="${esc(fig.dataset.title)}">
|
|
||||||
${yGrid(w, max, '', Y)}<line class="base" x1="${M.l}" x2="${w - M.r}" y1="${base}" y2="${base}"/>${marks}
|
|
||||||
<rect class="hit" x="${M.l}" y="0" width="${w - M.l - M.r}" height="${M.h}"/></svg>`;
|
|
||||||
fig._hover = (vx) => {
|
|
||||||
const i = Math.max(0, Math.min(weeks.length - 1, Math.floor((vx - M.l) / gw)));
|
|
||||||
const x = weeks[i];
|
|
||||||
const rate = x.sent ? ` (${Math.round((x.replies / x.sent) * 100)} %)` : '';
|
|
||||||
return { x: M.l + (i + 0.5) * gw, y: Y(Math.max(x.sent, x.replies)), band: true,
|
|
||||||
html: `Semaine du ${shortDay(x.start)}<br><strong>${x.sent}</strong> envoyé(s) · <strong>${x.replies}</strong> réponse(s)${rate}` };
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function drawChart(fig) {
|
|
||||||
const w = Math.max(240, Math.floor(fig.querySelector('.plot').clientWidth));
|
|
||||||
(fig.dataset.kind === 'bars' ? drawBars : drawLine)(fig, w);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Survol : réticule + infobulle (souris et tactile)
|
|
||||||
document.addEventListener('pointermove', (e) => {
|
|
||||||
const svg = e.target.closest?.('.chart svg');
|
|
||||||
const fig = svg?.closest('.chart');
|
|
||||||
// L'attribut hidden n'agit pas sur les éléments SVG : on passe par une classe
|
|
||||||
$$('.chart.hovering').forEach((c) => { if (c !== fig) { c.classList.remove('hovering'); c.querySelector('.tip').hidden = true; } });
|
|
||||||
if (!svg) return;
|
|
||||||
fig.classList.add('hovering');
|
|
||||||
if (!fig._hover) return;
|
|
||||||
const box = svg.getBoundingClientRect();
|
|
||||||
const h = fig._hover(e.clientX - box.left);
|
|
||||||
const cross = svg.querySelector('.cross');
|
|
||||||
const dot = svg.querySelector('.dot.hover');
|
|
||||||
if (cross) { cross.setAttribute('x1', h.x); cross.setAttribute('x2', h.x); }
|
|
||||||
if (dot) { dot.setAttribute('cx', h.x); dot.setAttribute('cy', h.y); }
|
|
||||||
const tip = fig.querySelector('.tip');
|
|
||||||
tip.innerHTML = h.html;
|
|
||||||
tip.hidden = false;
|
|
||||||
tip.style.left = `${Math.min(box.width - 70, Math.max(70, h.x))}px`;
|
|
||||||
tip.style.top = `${h.y + fig.querySelector('.plot').offsetTop - 8}px`;
|
|
||||||
});
|
|
||||||
|
|
||||||
function figure(kind, title, series, empty) {
|
|
||||||
return `<figure class="chart" data-kind="${kind}" data-title="${esc(title)}" data-series="${esc(JSON.stringify(series))}">
|
|
||||||
<figcaption>${esc(title)}</figcaption>
|
|
||||||
${kind === 'bars' ? '<p class="legend small"><span class="sw s1"></span>Mails envoyés <span class="sw s2"></span>Réponses</p>' : ''}${empty ? `<p class="muted small">${empty}</p>` : '<div class="plot"></div><div class="tip" hidden></div>'}</figure>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadHistory(proj, days = 30) {
|
|
||||||
const box = $('[data-charts]', proj);
|
|
||||||
if (!box) return;
|
|
||||||
let h;
|
|
||||||
try { h = await api(`/api/projects/${proj.dataset.id}/history?days=${days}`); }
|
|
||||||
catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; return; }
|
|
||||||
const kpi = (key, title, unit) => {
|
|
||||||
const pts = h.daily.filter((d) => d[key] != null);
|
|
||||||
return figure('line', title, { unit, xs: pts.map((d) => d.day), ys: pts.map((d) => d[key]) },
|
|
||||||
pts.length < 2 ? 'Pas encore assez de données : une photo est prise chaque jour (et à chaque ouverture du récap).' : '');
|
|
||||||
};
|
|
||||||
box.innerHTML = `
|
|
||||||
<div class="row chart-head"><h4>Évolution</h4>
|
|
||||||
<div class="seg" role="group" aria-label="Période">${[30, 90].map((d) => `<button type="button" class="btn small" data-days="${d}" aria-pressed="${d === days}">${d} jours</button>`).join('')}</div>
|
|
||||||
</div>
|
|
||||||
<div class="charts">
|
|
||||||
${kpi('users', 'Utilisateurs', '')}${kpi('clients', 'Clients payants', '')}${kpi('revenue', 'Revenu total', '€')}
|
|
||||||
${figure('bars', 'Prospection par semaine', { weeks: h.weeks })}
|
|
||||||
</div>
|
|
||||||
<details class="small"><summary>Voir les données</summary>
|
|
||||||
<div class="table-wrap"><table><thead><tr><th>Jour</th><th>Utilisateurs</th><th>Clients</th><th>Revenu</th></tr></thead><tbody>
|
|
||||||
${h.daily.map((d) => `<tr><td>${shortDay(d.day)}</td><td>${d.users ?? '–'}</td><td>${d.clients ?? '–'}</td><td>${d.revenue != null ? esc(fmtVal(d.revenue, '€')) : '–'}</td></tr>`).join('') || '<tr><td colspan="4">Aucune photo pour l\'instant.</td></tr>'}
|
|
||||||
</tbody></table>
|
|
||||||
<table><thead><tr><th>Semaine du</th><th>Envoyés</th><th>Réponses</th></tr></thead><tbody>
|
|
||||||
${h.weeks.map((x) => `<tr><td>${shortDay(x.start)}</td><td>${x.sent}</td><td>${x.replies}</td></tr>`).join('')}
|
|
||||||
</tbody></table></div>
|
|
||||||
</details>`;
|
|
||||||
$$('.chart', box).forEach((fig) => { if (fig.querySelector('.plot')) drawChart(fig); });
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('click', (e) => {
|
|
||||||
const b = e.target.closest('[data-days]');
|
|
||||||
if (b) loadHistory(b.closest('.project'), Number(b.dataset.days));
|
|
||||||
});
|
|
||||||
let resizeT;
|
|
||||||
window.addEventListener('resize', () => {
|
|
||||||
clearTimeout(resizeT);
|
|
||||||
resizeT = setTimeout(() => $$('.chart .plot').forEach((p) => drawChart(p.closest('.chart'))), 150);
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---------- Récap ----------
|
// ---------- Récap ----------
|
||||||
async function loadRecap(proj, force = false) {
|
async function loadRecap(proj, force = false) {
|
||||||
const box = $('[data-recap]', proj);
|
const box = $('[data-recap]', proj);
|
||||||
|
|
@ -495,170 +253,30 @@
|
||||||
<div class="kpi"><span>Convertis</span><strong>${s.client || 0}</strong></div>
|
<div class="kpi"><span>Convertis</span><strong>${s.client || 0}</strong></div>
|
||||||
</div>
|
</div>
|
||||||
<p class="muted small">Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
|
<p class="muted small">Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
|
||||||
<button class="btn small" data-recap-refresh>Rafraîchir</button></p>
|
<button class="btn small" data-recap-refresh>Rafraîchir</button></p>`;
|
||||||
<div data-charts></div>`;
|
|
||||||
loadHistory(proj);
|
|
||||||
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Liste des prospects (mini CRM) ----------
|
// ---------- Liste des prospects (mini CRM) ----------
|
||||||
const STATUS = { new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté' };
|
const STATUS = { new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté' };
|
||||||
// Seuls les liens http(s) sont cliquables : un "javascript:" venu d'une page web scrapée ne doit jamais s'exécuter ici
|
$$('details.prospects').forEach((d) => d.addEventListener('toggle', async () => {
|
||||||
const safeUrl = (u) => (/^https?:\/\//i.test(String(u || '')) ? String(u) : '');
|
if (!d.open) return;
|
||||||
const fmtDate = (ts) => new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' });
|
|
||||||
const isoDay = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' }) : '');
|
|
||||||
|
|
||||||
// ---------- Fiche prospect ----------
|
|
||||||
const dlg = $('#prospect-dialog');
|
|
||||||
|
|
||||||
async function openProspect(id) {
|
|
||||||
let d;
|
|
||||||
try { d = await api(`/api/prospects/${id}`); } catch (err) { toast(err.message, 'error'); return; }
|
|
||||||
const p = d.prospect;
|
|
||||||
const site = safeUrl(p.website);
|
|
||||||
const source = safeUrl(p.source);
|
|
||||||
const events = [
|
|
||||||
...d.mails.map((m) => ({
|
|
||||||
at: m.sent_at,
|
|
||||||
html: `<strong>${m.kind === 'followup' ? 'Relance' : 'Premier mail'}</strong>${m.variant ? ` <span class="muted">(objet ${esc(m.variant)})</span>` : ''} : ${esc(m.subject || '')}
|
|
||||||
${m.error ? `<span class="error"> · échec : ${esc(m.error)}</span>` : ''}`,
|
|
||||||
})),
|
|
||||||
...(p.replied_at ? [{ at: p.replied_at, html: `<strong class="ok">Réponse reçue</strong> : ${esc(p.reply_subject || 'sans objet')}` }] : []),
|
|
||||||
].sort((a, b) => a.at - b.at);
|
|
||||||
|
|
||||||
$('[data-dialog-body]', dlg).innerHTML = `
|
|
||||||
<div class="row dlg-head">
|
|
||||||
<div>
|
|
||||||
<h3>${site ? `<a href="${esc(site)}" target="_blank" rel="noopener noreferrer">${esc(p.company)}</a>` : esc(p.company)}</h3>
|
|
||||||
<div class="small muted"><a href="mailto:${esc(p.email)}">${esc(p.email)}</a>${p.city ? ` · ${esc(p.city)}` : ''}${p.sector ? ` · ${esc(p.sector)}` : ''}${p.score ? ` · score ${p.score}/10` : ''} · ${esc(STATUS[p.status] || p.status)}</div>
|
|
||||||
</div>
|
|
||||||
<button type="button" class="btn small" data-close>Fermer</button>
|
|
||||||
</div>
|
|
||||||
${d.optOut ? `<p class="error small">Sur la liste d'opposition (${d.optOut.reason === 'bounce' ? 'adresse invalide' : d.optOut.reason === 'refused' ? 'refus' : 'désinscription'}) : ne plus contacter.</p>` : ''}
|
|
||||||
${p.hook ? `<p class="hook">« ${esc(p.hook)} »</p>` : ''}
|
|
||||||
${source ? `<p class="small muted">Email trouvé sur : <a href="${esc(source)}" target="_blank" rel="noopener noreferrer">${esc(source)}</a></p>` : ''}
|
|
||||||
|
|
||||||
<h4>Historique</h4>
|
|
||||||
${events.length ? `<ol class="timeline">${events.map((e) => `<li><time>${fmtDate(e.at)}</time><div>${e.html}</div></li>`).join('')}</ol>` : '<p class="muted small">Pas encore contacté.</p>'}
|
|
||||||
|
|
||||||
<h4>Prochaine action</h4>
|
|
||||||
<form data-dlg="next" class="inline">
|
|
||||||
<label>Quoi<input name="action" value="${esc(p.next_action || '')}" placeholder="ex. Rappeler après les vacances" maxlength="200"></label>
|
|
||||||
<label>Quand<input type="date" name="day" value="${isoDay(p.next_action_at)}"></label>
|
|
||||||
<button class="btn">Enregistrer</button>
|
|
||||||
${p.next_action ? '<button type="button" class="btn small" data-clear-next>Effacer</button>' : ''}
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<h4>Notes</h4>
|
|
||||||
<form data-dlg="note">
|
|
||||||
<textarea name="body" rows="3" maxlength="2000" placeholder="Ce qu'il a dit, le contexte, ce qu'il faut retenir…"></textarea>
|
|
||||||
<button class="btn">Ajouter la note</button>
|
|
||||||
</form>
|
|
||||||
<ul class="notes">${d.notes.map((n) => `<li><div class="small muted">${fmtDate(n.created_at)} · <button type="button" class="link small" data-del-note="${n.id}">supprimer</button></div><div class="note-body">${esc(n.body)}</div></li>`).join('')}</ul>`;
|
|
||||||
dlg.dataset.id = id;
|
|
||||||
if (!dlg.open) dlg.showModal();
|
|
||||||
}
|
|
||||||
|
|
||||||
function refreshOpenLists() { $$('details.prospects[open]').forEach((d) => loadProspects(d, Number(d.dataset.page) || 1)); }
|
|
||||||
|
|
||||||
if (dlg) {
|
|
||||||
dlg.addEventListener('click', async (e) => {
|
|
||||||
if (e.target === dlg || e.target.closest('[data-close]')) { dlg.close(); return; }
|
|
||||||
const id = dlg.dataset.id;
|
|
||||||
const del = e.target.closest('[data-del-note]');
|
|
||||||
if (del && confirm('Supprimer cette note ?')) {
|
|
||||||
await api(`/api/prospects/${id}/notes/${del.dataset.delNote}/delete`, {}).catch((err) => toast(err.message, 'error'));
|
|
||||||
openProspect(id);
|
|
||||||
}
|
|
||||||
if (e.target.closest('[data-clear-next]')) {
|
|
||||||
await api(`/api/prospects/${id}/next`, { action: '' }).catch((err) => toast(err.message, 'error'));
|
|
||||||
openProspect(id); refreshOpenLists();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
dlg.addEventListener('submit', async (e) => {
|
|
||||||
const form = e.target.closest('form[data-dlg]');
|
|
||||||
if (!form) return;
|
|
||||||
e.preventDefault();
|
|
||||||
const id = dlg.dataset.id;
|
|
||||||
try {
|
|
||||||
if (form.dataset.dlg === 'note') { await api(`/api/prospects/${id}/notes`, formData(form)); toast('Note ajoutée'); }
|
|
||||||
else { await api(`/api/prospects/${id}/next`, formData(form)); toast('Prochaine action enregistrée'); refreshOpenLists(); }
|
|
||||||
openProspect(id);
|
|
||||||
} catch (err) { toast(err.message, 'error'); }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Import CSV : Excel enregistre souvent en Windows-1252, on détecte pour ne pas abîmer les accents
|
|
||||||
document.addEventListener('change', async (e) => {
|
|
||||||
const input = e.target.closest('[data-import]');
|
|
||||||
if (!input?.files?.length) return;
|
|
||||||
const file = input.files[0];
|
|
||||||
input.value = '';
|
|
||||||
const d = input.closest('details.prospects');
|
|
||||||
const report = $('[data-import-report]', d);
|
|
||||||
if (file.size > 1024 * 1024) { toast('Fichier trop gros (1 Mo max, environ 2000 lignes)', 'error'); return; }
|
|
||||||
const buf = await file.arrayBuffer();
|
|
||||||
let csv;
|
|
||||||
try { csv = new TextDecoder('utf-8', { fatal: true }).decode(buf); }
|
|
||||||
catch { csv = new TextDecoder('windows-1252').decode(buf); }
|
|
||||||
try {
|
|
||||||
const r = await api(`/api/projects/${input.dataset.import}/prospects/import`, { csv });
|
|
||||||
report.innerHTML = `<p class="small"><span class="ok">${r.imported} importé(s)</span> sur ${r.total} ·
|
|
||||||
${r.duplicates} déjà présent(s) · ${r.blacklisted} sur liste d'opposition · ${r.invalid.length} invalide(s)</p>
|
|
||||||
${r.invalid.length ? `<details class="small"><summary>Lignes ignorées</summary><ul>${r.invalid.map((x) => `<li>Ligne ${x.line} : ${esc(x.reason)}</li>`).join('')}</ul></details>` : ''}`;
|
|
||||||
toast(`${r.imported} prospect(s) importé(s)`);
|
|
||||||
loadProspects(d);
|
|
||||||
} catch (err) { report.innerHTML = ''; toast(err.message, 'error'); }
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('click', (e) => {
|
|
||||||
const b = e.target.closest('[data-open-prospect]');
|
|
||||||
if (b) openProspect(b.dataset.openProspect);
|
|
||||||
});
|
|
||||||
|
|
||||||
const fmtDay = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' }) : '');
|
|
||||||
|
|
||||||
async function loadProspects(d, page = 1) {
|
|
||||||
const proj = d.closest('.project');
|
const proj = d.closest('.project');
|
||||||
const box = $('[data-prospects]', d);
|
const box = $('[data-prospects]', d);
|
||||||
const filters = formData($('[data-filters]', d));
|
|
||||||
const qs = new URLSearchParams({ ...filters, page });
|
|
||||||
// L'export suit les filtres affichés
|
|
||||||
$('[data-export]', d).href = `/api/projects/${proj.dataset.id}/prospects.csv?${new URLSearchParams(filters)}`;
|
|
||||||
try {
|
try {
|
||||||
const r = await api(`/api/projects/${proj.dataset.id}/prospects?${qs}`);
|
const rows = await api(`/api/projects/${proj.dataset.id}/prospects`);
|
||||||
d.dataset.page = r.page;
|
box.innerHTML = rows.length ? `<div class="table-wrap"><table><thead><tr><th>Entreprise</th><th>Email</th><th>Ville</th><th>Score</th><th>Statut</th></tr></thead><tbody>
|
||||||
box.innerHTML = r.rows.length ? `<div class="table-wrap"><table><thead><tr><th>Entreprise</th><th>Email</th><th>Ville</th><th>Score</th><th>Contacté</th><th>Statut</th></tr></thead><tbody>
|
${rows.map((r) => `<tr><td>${r.website ? `<a href="${esc(r.website)}" target="_blank" rel="noopener noreferrer">${esc(r.company)}</a>` : esc(r.company)}</td>
|
||||||
${r.rows.map((x) => `<tr data-row="${x.id}"><td><button type="button" class="link" data-open-prospect="${x.id}">${esc(x.company)}</button>
|
<td>${esc(r.email)}</td><td>${esc(r.city)}</td><td>${r.score}</td>
|
||||||
${x.next_action ? `<div class="small ${x.next_action_at * 1000 <= Date.now() ? 'warn' : 'muted'}">→ ${esc(x.next_action)} (${fmtDay(x.next_action_at)})</div>` : ''}</td>
|
<td><select data-prospect="${r.id}">${Object.entries(STATUS).map(([k, v]) => `<option value="${k}" ${k === r.status ? 'selected' : ''}>${v}</option>`).join('')}</select></td></tr>`).join('')}
|
||||||
<td>${esc(x.email)}</td><td>${esc(x.city)}</td><td>${x.score ?? ''}</td>
|
</tbody></table></div>` : '<p class="muted small">Aucun prospect.</p>';
|
||||||
<td>${fmtDay(x.sent_at)}${x.followup_at ? ' <span class="muted small">+ relance</span>' : ''}</td>
|
|
||||||
<td><select data-prospect="${x.id}" class="st-${x.status}">${Object.entries(STATUS).map(([k, v]) => `<option value="${k}" ${k === x.status ? 'selected' : ''}>${v}</option>`).join('')}</select></td></tr>`).join('')}
|
|
||||||
</tbody></table></div>` : '<p class="muted small">Aucun prospect ne correspond.</p>';
|
|
||||||
$('[data-pager]', d).innerHTML = r.pages > 1
|
|
||||||
? `<button type="button" class="btn small" data-page="${r.page - 1}" ${r.page <= 1 ? 'disabled' : ''}>←</button>
|
|
||||||
<span class="small muted">Page ${r.page} / ${r.pages} · ${r.total} prospect(s)</span>
|
|
||||||
<button type="button" class="btn small" data-page="${r.page + 1}" ${r.page >= r.pages ? 'disabled' : ''}>→</button>`
|
|
||||||
: `<span class="small muted">${r.total} prospect(s)</span>`;
|
|
||||||
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
||||||
}
|
}));
|
||||||
|
|
||||||
$$('details.prospects').forEach((d) => {
|
|
||||||
d.addEventListener('toggle', () => { if (d.open) loadProspects(d); });
|
|
||||||
const form = $('[data-filters]', d);
|
|
||||||
let t;
|
|
||||||
form.addEventListener('input', (e) => { if (e.target.name === 'q') { clearTimeout(t); t = setTimeout(() => loadProspects(d), 300); } });
|
|
||||||
form.addEventListener('change', (e) => { if (e.target.name !== 'q') loadProspects(d); });
|
|
||||||
form.addEventListener('submit', (e) => { e.preventDefault(); loadProspects(d); });
|
|
||||||
d.addEventListener('click', (e) => {
|
|
||||||
const b = e.target.closest('[data-page]');
|
|
||||||
if (b) loadProspects(d, Number(b.dataset.page));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
document.addEventListener('change', async (e) => {
|
document.addEventListener('change', async (e) => {
|
||||||
const sel = e.target.closest('[data-prospect]');
|
const sel = e.target.closest('[data-prospect]');
|
||||||
if (!sel) return;
|
if (!sel) return;
|
||||||
if (sel.value === 'refused' && !confirm('Marquer en refus ajoute l\'adresse à la liste d\'opposition. Continuer ?')) return;
|
if (sel.value === 'refused' && !confirm('Marquer en refus ajoute l\'adresse à la liste d\'opposition. Continuer ?')) return;
|
||||||
try { await api(`/api/prospects/${sel.dataset.prospect}/status`, { status: sel.value }); sel.className = `st-${sel.value}`; toast('Statut mis à jour'); }
|
try { await api(`/api/prospects/${sel.dataset.prospect}/status`, { status: sel.value }); toast('Statut mis à jour'); }
|
||||||
catch (err) { toast(err.message, 'error'); }
|
catch (err) { toast(err.message, 'error'); }
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|
|
||||||
|
|
@ -19,17 +19,5 @@ for (const f of files) {
|
||||||
try { execFileSync(process.execPath, ['--check', f], { stdio: 'pipe' }); }
|
try { execFileSync(process.execPath, ['--check', f], { stdio: 'pipe' }); }
|
||||||
catch (e) { failed++; console.error(`✗ ${f}\n${e.stderr}`); }
|
catch (e) { failed++; console.error(`✗ ${f}\n${e.stderr}`); }
|
||||||
}
|
}
|
||||||
// Scripts shell : syntaxe bash, + shellcheck s'il est installé
|
console.log(`${files.length - failed}/${files.length} fichiers OK`);
|
||||||
const shells = ['install.sh', 'deploy/aitools-backup.sh', '.githooks/pre-commit'];
|
|
||||||
let hasShellcheck = true;
|
|
||||||
try { execFileSync('shellcheck', ['--version'], { stdio: 'pipe' }); } catch { hasShellcheck = false; }
|
|
||||||
for (const f of shells) {
|
|
||||||
try {
|
|
||||||
execFileSync('bash', ['-n', f], { stdio: 'pipe' });
|
|
||||||
if (hasShellcheck) execFileSync('shellcheck', ['-S', 'warning', '-x', f], { stdio: 'pipe' });
|
|
||||||
} catch (e) { failed++; console.error(`✗ ${f}\n${e.stdout || ''}${e.stderr || ''}`); }
|
|
||||||
}
|
|
||||||
|
|
||||||
const total = files.length + shells.length;
|
|
||||||
console.log(`${total - failed}/${total} fichiers OK${hasShellcheck ? '' : ' (shellcheck absent, syntaxe bash seulement)'}`);
|
|
||||||
process.exit(failed ? 1 : 0);
|
process.exit(failed ? 1 : 0);
|
||||||
|
|
|
||||||
65
src/db.js
65
src/db.js
|
|
@ -3,7 +3,7 @@ import { mkdirSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
|
||||||
// Chaque entrée = une migration. Ne jamais modifier une migration déjà livrée, en ajouter une.
|
// Chaque entrée = une migration. Ne jamais modifier une migration déjà livrée, en ajouter une.
|
||||||
export const MIGRATIONS = [
|
const MIGRATIONS = [
|
||||||
`
|
`
|
||||||
CREATE TABLE sessions (
|
CREATE TABLE sessions (
|
||||||
id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
||||||
|
|
@ -63,69 +63,6 @@ export const MIGRATIONS = [
|
||||||
);
|
);
|
||||||
CREATE INDEX mail_log_day ON mail_log(project_id, sent_at);
|
CREATE INDEX mail_log_day ON mail_log(project_id, sent_at);
|
||||||
`,
|
`,
|
||||||
// 2 — modèles de mail par type (premier mail / relance)
|
|
||||||
`
|
|
||||||
CREATE TABLE templates (
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
kind TEXT NOT NULL CHECK (kind IN ('initial', 'followup')),
|
|
||||||
subject TEXT NOT NULL DEFAULT '', -- relance : vide = "Re: <objet du 1er mail>"
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'draft',
|
|
||||||
updated_at INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY (project_id, kind)
|
|
||||||
);
|
|
||||||
INSERT INTO templates(project_id, kind, subject, body, status, updated_at)
|
|
||||||
SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates;
|
|
||||||
DROP TABLE mail_templates;
|
|
||||||
`,
|
|
||||||
// 3 — suivi des mails envoyés + test A/B de l'objet
|
|
||||||
`
|
|
||||||
ALTER TABLE templates ADD COLUMN subject_b TEXT; -- objet B (premier mail uniquement)
|
|
||||||
ALTER TABLE prospects ADD COLUMN variant TEXT; -- A | B
|
|
||||||
ALTER TABLE mail_log ADD COLUMN kind TEXT NOT NULL DEFAULT 'initial';
|
|
||||||
ALTER TABLE mail_log ADD COLUMN variant TEXT;
|
|
||||||
ALTER TABLE mail_log ADD COLUMN subject TEXT;
|
|
||||||
ALTER TABLE mail_log ADD COLUMN message_id TEXT;
|
|
||||||
CREATE INDEX mail_log_msgid ON mail_log(message_id);
|
|
||||||
`,
|
|
||||||
// 4 — détection des réponses via IMAP
|
|
||||||
`
|
|
||||||
ALTER TABLE prospects ADD COLUMN replied_at INTEGER;
|
|
||||||
ALTER TABLE prospects ADD COLUMN reply_subject TEXT;
|
|
||||||
ALTER TABLE projects ADD COLUMN imap_enc TEXT;
|
|
||||||
ALTER TABLE projects ADD COLUMN inbox_json TEXT; -- état de la dernière lecture IMAP
|
|
||||||
`,
|
|
||||||
// 5 — relance automatique
|
|
||||||
`
|
|
||||||
ALTER TABLE prospects ADD COLUMN followup_at INTEGER;
|
|
||||||
ALTER TABLE projects ADD COLUMN followup_enabled INTEGER NOT NULL DEFAULT 0;
|
|
||||||
ALTER TABLE projects ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7;
|
|
||||||
`,
|
|
||||||
// 6 — jobs programmés (la nuit)
|
|
||||||
`
|
|
||||||
ALTER TABLE jobs ADD COLUMN run_after INTEGER; -- ne pas démarrer avant (epoch s)
|
|
||||||
`,
|
|
||||||
// 7 — fiche prospect : notes et prochaine action
|
|
||||||
`
|
|
||||||
CREATE TABLE prospect_notes (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE,
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at);
|
|
||||||
ALTER TABLE prospects ADD COLUMN next_action TEXT;
|
|
||||||
ALTER TABLE prospects ADD COLUMN next_action_at INTEGER;
|
|
||||||
`,
|
|
||||||
// 8 — historique quotidien des KPI business (pour les courbes)
|
|
||||||
`
|
|
||||||
CREATE TABLE metrics_daily (
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris
|
|
||||||
users REAL, clients REAL, revenue REAL,
|
|
||||||
PRIMARY KEY (project_id, day)
|
|
||||||
);
|
|
||||||
`,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
export function openDb(dataDir) {
|
export function openDb(dataDir) {
|
||||||
|
|
|
||||||
161
src/handlers.js
161
src/handlers.js
|
|
@ -3,24 +3,16 @@ import { now, getSetting } from './db.js';
|
||||||
import { runClaude, extractJson } from './services/claude.js';
|
import { runClaude, extractJson } from './services/claude.js';
|
||||||
import { addUsage } from './services/jobs.js';
|
import { addUsage } from './services/jobs.js';
|
||||||
import { syncRepo } from './services/git.js';
|
import { syncRepo } from './services/git.js';
|
||||||
import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
import { analyzePrompt, prospectPrompt, templatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
||||||
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend } from './services/mailer.js';
|
||||||
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
|
||||||
import { unsubToken } from './crypto.js';
|
import { unsubToken } from './crypto.js';
|
||||||
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
|
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince } from './projects.js';
|
||||||
|
|
||||||
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
||||||
const t = setTimeout(resolve, ms);
|
const t = setTimeout(resolve, ms);
|
||||||
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
|
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Une page web peut tenter de faire enregistrer "javascript:…" : seules les URLs http(s) sont gardées
|
|
||||||
export function httpUrl(v) {
|
|
||||||
const s = String(v ?? '').trim();
|
|
||||||
if (!/^https?:\/\/[^\s<>"]+$/i.test(s)) return null;
|
|
||||||
try { return new URL(s).protocol.startsWith('http') ? s.slice(0, 300) : null; } catch { return null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseProspectLine(line) {
|
export function parseProspectLine(line) {
|
||||||
const m = /^\s*PROSPECT\s+(\{.*\})\s*$/.exec(line);
|
const m = /^\s*PROSPECT\s+(\{.*\})\s*$/.exec(line);
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
|
|
@ -31,8 +23,8 @@ export function parseProspectLine(line) {
|
||||||
const str = (v, max = 300) => (v == null ? null : String(v).slice(0, max));
|
const str = (v, max = 300) => (v == null ? null : String(v).slice(0, max));
|
||||||
const score = Math.max(1, Math.min(10, Math.round(Number(p.score) || 5)));
|
const score = Math.max(1, Math.min(10, Math.round(Number(p.score) || 5)));
|
||||||
return {
|
return {
|
||||||
company: str(p.company, 200), email, website: httpUrl(p.website), city: str(p.city, 100),
|
company: str(p.company, 200), email, website: str(p.website), city: str(p.city, 100),
|
||||||
sector: str(p.sector, 100), hook: str(p.hook, 400), source: httpUrl(p.source), score,
|
sector: str(p.sector, 100), hook: str(p.hook, 400), source: str(p.source), score,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -40,87 +32,6 @@ export function makeHandlers(app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o });
|
const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o });
|
||||||
|
|
||||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
|
||||||
|
|
||||||
// Premier mail ou relance : mêmes plafonds, mêmes délais, même journal
|
|
||||||
async function sendMails(ctx, kind) {
|
|
||||||
// Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé
|
|
||||||
if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true };
|
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
|
||||||
const template = getTemplate(db, project.id, kind, { validatedOnly: true });
|
|
||||||
if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé');
|
|
||||||
if (!project.smtp) throw new Error('SMTP non configuré pour ce projet');
|
|
||||||
|
|
||||||
const day = now() - 86400;
|
|
||||||
const candidates = kind === 'followup'
|
|
||||||
? followupCandidates(db, project)
|
|
||||||
: db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
|
||||||
AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id);
|
|
||||||
const n = allowedToSend({
|
|
||||||
requested: ctx.params.count,
|
|
||||||
available: candidates.length,
|
|
||||||
projectCap: project.dailyMailCap,
|
|
||||||
sentTodayProject: sentSince(db, day, project.id),
|
|
||||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')),
|
|
||||||
sentTodayGlobal: sentSince(db, day),
|
|
||||||
});
|
|
||||||
if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter');
|
|
||||||
|
|
||||||
const transport = (app.createTransport || createTransport)(project.smtp);
|
|
||||||
await transport.verify();
|
|
||||||
const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000;
|
|
||||||
const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000;
|
|
||||||
const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id)
|
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
||||||
const markInitial = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?');
|
|
||||||
const markFollowup = db.prepare('UPDATE prospects SET followup_at = ? WHERE id = ?');
|
|
||||||
const markBounced = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ?");
|
|
||||||
const original = db.prepare("SELECT subject, message_id FROM mail_log WHERE prospect_id = ? AND kind = 'initial' AND error IS NULL ORDER BY id LIMIT 1");
|
|
||||||
const current = db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?');
|
|
||||||
let sent = 0, failed = 0;
|
|
||||||
|
|
||||||
for (const p of candidates.slice(0, n)) {
|
|
||||||
if (ctx.cancelled()) break;
|
|
||||||
if (kind === 'followup' && !inHours()) break; // le reste repartira au prochain créneau
|
|
||||||
// Re-vérifie juste avant l'envoi : désinscription, réponse arrivée pendant le batch…
|
|
||||||
if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
|
||||||
if (kind === 'followup') {
|
|
||||||
const c = current.get(p.id);
|
|
||||||
if (c.status !== 'sent' || c.followup_at) continue;
|
|
||||||
}
|
|
||||||
const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`;
|
|
||||||
let variant = null, subject, inReplyTo;
|
|
||||||
if (kind === 'initial') {
|
|
||||||
variant = pickVariant(db, project.id, template);
|
|
||||||
subject = variant === 'B' ? template.subject_b : template.subject;
|
|
||||||
} else {
|
|
||||||
const orig = original.get(p.id);
|
|
||||||
subject = followupSubject(template, orig);
|
|
||||||
inReplyTo = orig?.message_id;
|
|
||||||
}
|
|
||||||
const mail = buildProspectMail({
|
|
||||||
template, prospect: p, smtp: project.smtp, unsubUrl, subject, inReplyTo,
|
|
||||||
messageId: makeMessageId(project.smtp.fromEmail),
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
await transport.sendMail(mail);
|
|
||||||
log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
|
||||||
if (kind === 'initial') markInitial.run('sent', now(), variant, p.id);
|
|
||||||
else markFollowup.run(now(), p.id);
|
|
||||||
sent++;
|
|
||||||
} catch (e) {
|
|
||||||
log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId);
|
|
||||||
if (/^5\d\d/.test(String(e.responseCode))) markBounced.run(p.id);
|
|
||||||
failed++;
|
|
||||||
}
|
|
||||||
const label = kind === 'followup' ? 'relances envoyées' : 'envoyés';
|
|
||||||
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}` });
|
|
||||||
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
|
||||||
}
|
|
||||||
transport.close();
|
|
||||||
return { sent, failed, total: n };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async analyze(ctx) {
|
async analyze(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id);
|
const project = getProject(app, ctx.job.project_id);
|
||||||
|
|
@ -190,24 +101,60 @@ export function makeHandlers(app) {
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
const t = extractJson(r.text);
|
const t = extractJson(r.text);
|
||||||
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
||||||
saveTemplate(db, project.id, 'initial', { subject: t.subject, body: t.body });
|
db.prepare(`INSERT INTO mail_templates(project_id, subject, body, status, updated_at) VALUES(?, ?, ?, 'draft', ?)
|
||||||
|
ON CONFLICT(project_id) DO UPDATE SET subject = excluded.subject, body = excluded.body, status = 'draft', updated_at = excluded.updated_at`)
|
||||||
|
.run(project.id, t.subject, t.body, now());
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
async followup_template(ctx) {
|
async send(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
||||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
const template = db.prepare("SELECT * FROM mail_templates WHERE project_id = ? AND status = 'validated'").get(project.id);
|
||||||
const { prompt, system } = followupTemplatePrompt({ profile: project.profile, senderName: project.smtp?.fromName });
|
if (!template) throw new Error('Modèle de mail non validé');
|
||||||
const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
if (!project.smtp) throw new Error('SMTP non configuré pour ce projet');
|
||||||
addUsage(ctx, r);
|
|
||||||
const t = extractJson(r.text);
|
|
||||||
if (!t.body) throw new Error('Modèle de relance invalide');
|
|
||||||
saveTemplate(db, project.id, 'followup', { subject: '', body: t.body });
|
|
||||||
return { ok: true };
|
|
||||||
},
|
|
||||||
|
|
||||||
send: (ctx) => sendMails(ctx, 'initial'),
|
const day = now() - 86400;
|
||||||
followup: (ctx) => sendMails(ctx, 'followup'),
|
const candidates = db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
||||||
|
AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id);
|
||||||
|
const n = allowedToSend({
|
||||||
|
requested: ctx.params.count,
|
||||||
|
available: candidates.length,
|
||||||
|
projectCap: project.dailyMailCap,
|
||||||
|
sentTodayProject: sentSince(db, day, project.id),
|
||||||
|
globalCap: Number(getSetting(db, 'global_daily_cap', '100')),
|
||||||
|
sentTodayGlobal: sentSince(db, day),
|
||||||
|
});
|
||||||
|
if (n === 0) throw new Error('Plafond quotidien atteint ou aucun prospect à contacter');
|
||||||
|
|
||||||
|
const transport = (app.createTransport || createTransport)(project.smtp);
|
||||||
|
await transport.verify();
|
||||||
|
const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000;
|
||||||
|
const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000;
|
||||||
|
const log = db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error) VALUES(?, ?, ?, ?, ?)');
|
||||||
|
const mark = db.prepare("UPDATE prospects SET status = ?, sent_at = ? WHERE id = ?");
|
||||||
|
let sent = 0, failed = 0;
|
||||||
|
|
||||||
|
for (const p of candidates.slice(0, n)) {
|
||||||
|
if (ctx.cancelled()) break;
|
||||||
|
// Re-vérifie la blacklist juste avant l'envoi (désinscription pendant le batch)
|
||||||
|
if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
||||||
|
const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`;
|
||||||
|
try {
|
||||||
|
await transport.sendMail(buildProspectMail({ template, prospect: p, smtp: project.smtp, unsubUrl }));
|
||||||
|
log.run(project.id, p.id, p.email, now(), null);
|
||||||
|
mark.run('sent', now(), p.id);
|
||||||
|
sent++;
|
||||||
|
} catch (e) {
|
||||||
|
log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500));
|
||||||
|
if (/^5\d\d/.test(String(e.responseCode))) mark.run('bounced', now(), p.id);
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} envoyés` });
|
||||||
|
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
||||||
|
}
|
||||||
|
transport.close();
|
||||||
|
return { sent, failed, total: n };
|
||||||
|
},
|
||||||
|
|
||||||
async evolution(ctx) {
|
async evolution(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
||||||
|
|
|
||||||
|
|
@ -42,12 +42,12 @@ export function setCookie(res, name, value, { maxAge, httpOnly = true } = {}) {
|
||||||
|
|
||||||
const MAX_BODY = 256 * 1024;
|
const MAX_BODY = 256 * 1024;
|
||||||
|
|
||||||
export async function readBody(req, { max = MAX_BODY } = {}) {
|
export async function readBody(req) {
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let size = 0;
|
let size = 0;
|
||||||
for await (const c of req) {
|
for await (const c of req) {
|
||||||
size += c.length;
|
size += c.length;
|
||||||
if (size > max) throw Object.assign(new Error('Requête trop volumineuse'), { status: 413 });
|
if (size > MAX_BODY) throw Object.assign(new Error('Requête trop volumineuse'), { status: 413 });
|
||||||
chunks.push(c);
|
chunks.push(c);
|
||||||
}
|
}
|
||||||
const raw = Buffer.concat(chunks).toString('utf8');
|
const raw = Buffer.concat(chunks).toString('utf8');
|
||||||
|
|
|
||||||
|
|
@ -7,13 +7,6 @@ export const repoDir = (cfg, id) => join(cfg.dataDir, 'repos', String(id));
|
||||||
|
|
||||||
const parse = (s) => (s ? JSON.parse(s) : null);
|
const parse = (s) => (s ? JSON.parse(s) : null);
|
||||||
|
|
||||||
// Secret illisible (SECRET_KEY changée, donnée abîmée) : on le traite comme absent pour que le
|
|
||||||
// panel reste utilisable, il suffira de le ressaisir.
|
|
||||||
function readSecret(key, payload, what) {
|
|
||||||
try { return decryptJson(key, payload); }
|
|
||||||
catch { console.warn(`[secrets] ${what} illisible (SECRET_KEY changée ?), à ressaisir`); return null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getProject(app, id, { secrets = false } = {}) {
|
export function getProject(app, id, { secrets = false } = {}) {
|
||||||
const p = app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
const p = app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
||||||
if (!p) throw new HttpError(404, 'Projet introuvable');
|
if (!p) throw new HttpError(404, 'Projet introuvable');
|
||||||
|
|
@ -22,15 +15,11 @@ export function getProject(app, id, { secrets = false } = {}) {
|
||||||
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
|
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
|
||||||
target: parse(p.target_json), targetValidated: !!p.target_validated,
|
target: parse(p.target_json), targetValidated: !!p.target_validated,
|
||||||
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
|
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
|
||||||
hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc, hasImap: !!p.imap_enc,
|
hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc,
|
||||||
inbox: parse(p.inbox_json),
|
|
||||||
followupEnabled: !!p.followup_enabled, followupDays: p.followup_days,
|
|
||||||
};
|
};
|
||||||
if (secrets) {
|
if (secrets) {
|
||||||
out.smtp = readSecret(app.cfg.secretKey, p.smtp_enc, `SMTP du projet ${p.id}`);
|
out.smtp = decryptJson(app.cfg.secretKey, p.smtp_enc);
|
||||||
out.dbCfg = readSecret(app.cfg.secretKey, p.db_enc, `accès BDD du projet ${p.id}`);
|
out.dbCfg = decryptJson(app.cfg.secretKey, p.db_enc);
|
||||||
out.imapCfg = readSecret(app.cfg.secretKey, p.imap_enc, `IMAP du projet ${p.id}`);
|
|
||||||
out.imap = imapCredentials(out.imapCfg, out.smtp);
|
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
@ -46,8 +35,8 @@ export function createProject(app, { name, gitUrl }) {
|
||||||
|
|
||||||
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
||||||
export function saveSecretConfig(app, id, column, incoming, secretField) {
|
export function saveSecretConfig(app, id, column, incoming, secretField) {
|
||||||
if (!['smtp_enc', 'db_enc', 'imap_enc'].includes(column)) throw new Error('Colonne invalide');
|
if (!['smtp_enc', 'db_enc'].includes(column)) throw new Error('Colonne invalide');
|
||||||
const current = readSecret(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c, column) || {};
|
const current = decryptJson(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c) || {};
|
||||||
const next = { ...current, ...incoming };
|
const next = { ...current, ...incoming };
|
||||||
if (!incoming[secretField]) next[secretField] = current[secretField];
|
if (!incoming[secretField]) next[secretField] = current[secretField];
|
||||||
app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
||||||
|
|
@ -61,12 +50,11 @@ export function publicConfig(cfg, secretField) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function forgejoToken(app) {
|
export function forgejoToken(app) {
|
||||||
try { return decrypt(app.cfg.secretKey, getSetting(app.db, 'forgejo_token_enc')); }
|
return decrypt(app.cfg.secretKey, getSetting(app.db, 'forgejo_token_enc'));
|
||||||
catch { console.warn('[secrets] token Forgejo illisible, à ressaisir'); return null; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function globalSmtp(app) {
|
export function globalSmtp(app) {
|
||||||
return readSecret(app.cfg.secretKey, getSetting(app.db, 'smtp_enc'), 'SMTP global');
|
return decryptJson(app.cfg.secretKey, getSetting(app.db, 'smtp_enc'));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function prospectStats(db, projectId) {
|
export function prospectStats(db, projectId) {
|
||||||
|
|
@ -82,49 +70,3 @@ export function sentSince(db, since, projectId = null) {
|
||||||
: 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL AND project_id = ?';
|
: 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL AND project_id = ?';
|
||||||
return (projectId == null ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n;
|
return (projectId == null ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant)
|
|
||||||
export function imapCredentials(imap, smtp) {
|
|
||||||
if (!imap?.host) return null;
|
|
||||||
const reuse = !imap.user;
|
|
||||||
const user = reuse ? smtp?.user : imap.user;
|
|
||||||
const pass = reuse ? smtp?.pass : imap.pass;
|
|
||||||
if (!user || !pass) return null;
|
|
||||||
return { host: imap.host, port: Number(imap.port || 993), user, pass, reuseSmtp: reuse };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Modèles de mail ----------
|
|
||||||
export const TEMPLATE_KINDS = ['initial', 'followup'];
|
|
||||||
|
|
||||||
export function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) {
|
|
||||||
const row = db.prepare('SELECT * FROM templates WHERE project_id = ? AND kind = ?').get(projectId, kind);
|
|
||||||
if (!row || (validatedOnly && row.status !== 'validated')) return null;
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) {
|
|
||||||
if (!TEMPLATE_KINDS.includes(kind)) throw new HttpError(400, 'Type de modèle inconnu');
|
|
||||||
db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)
|
|
||||||
ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, subject_b = excluded.subject_b,
|
|
||||||
body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`)
|
|
||||||
.run(projectId, kind, subject, kind === 'initial' ? (subjectB || null) : null, body, status, now());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Objet A ou B : on équilibre les envois (B seulement si un objet B est défini)
|
|
||||||
export function pickVariant(db, projectId, template) {
|
|
||||||
if (!template.subject_b) return 'A';
|
|
||||||
const rows = db.prepare(`SELECT variant, COUNT(*) n FROM mail_log
|
|
||||||
WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND variant IN ('A', 'B') GROUP BY variant`).all(projectId);
|
|
||||||
const count = { A: 0, B: 0 };
|
|
||||||
for (const r of rows) count[r.variant] = r.n;
|
|
||||||
return count.B < count.A ? 'B' : 'A';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Taux de réponse par objet (A/B) sur les premiers mails
|
|
||||||
export function abStats(db, projectId) {
|
|
||||||
const rows = db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied
|
|
||||||
FROM mail_log m JOIN prospects p ON p.id = m.prospect_id
|
|
||||||
WHERE m.project_id = ? AND m.kind = 'initial' AND m.error IS NULL AND m.variant IS NOT NULL
|
|
||||||
GROUP BY m.variant ORDER BY m.variant`).all(projectId);
|
|
||||||
return rows.map((r) => ({ variant: r.v, sent: r.sent, replied: r.replied, rate: r.sent ? r.replied / r.sent : 0 }));
|
|
||||||
}
|
|
||||||
|
|
|
||||||
165
src/routes.js
165
src/routes.js
|
|
@ -8,20 +8,9 @@ import { validateGitUrl, removeRepo } from './services/git.js';
|
||||||
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
||||||
import { allowedToSend, EMAIL_RE } from './services/mailer.js';
|
import { allowedToSend, EMAIL_RE } from './services/mailer.js';
|
||||||
import { cpuTemp } from './services/thermal.js';
|
import { cpuTemp } from './services/thermal.js';
|
||||||
import { checkInbox } from './services/inbox.js';
|
|
||||||
import { followupPlan } from './services/followup.js';
|
|
||||||
import { nextNightSlot } from './services/paris-time.js';
|
|
||||||
import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
|
|
||||||
import { budgetState, AI_JOBS } from './services/budget.js';
|
|
||||||
import { sendWeeklyReport } from './services/report.js';
|
|
||||||
import { exportProspects, importProspects } from './services/csv.js';
|
|
||||||
import { history, saveSnapshot } from './services/metrics.js';
|
|
||||||
import {
|
|
||||||
listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction,
|
|
||||||
} from './services/crm.js';
|
|
||||||
import {
|
import {
|
||||||
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
|
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
|
||||||
prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats,
|
prospectStats, sentSince, repoDir,
|
||||||
} from './projects.js';
|
} from './projects.js';
|
||||||
|
|
||||||
const lines = (s) => String(s || '').split('\n').map((x) => x.trim()).filter(Boolean).slice(0, 20);
|
const lines = (s) => String(s || '').split('\n').map((x) => x.trim()).filter(Boolean).slice(0, 20);
|
||||||
|
|
@ -61,7 +50,7 @@ export function registerRoutes(router, app) {
|
||||||
router.get('/', ({ res, session }) => {
|
router.get('/', ({ res, session }) => {
|
||||||
const projects = listProjects(app).map((p) => {
|
const projects = listProjects(app).map((p) => {
|
||||||
const full = getProject(app, p.id, { secrets: true });
|
const full = getProject(app, p.id, { secrets: true });
|
||||||
return { project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') };
|
return { project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password') };
|
||||||
});
|
});
|
||||||
html(res, dashboardPage({ email: session.email, projects, forgejoHost: getSetting(db, 'forgejo_host') }));
|
html(res, dashboardPage({ email: session.email, projects, forgejoHost: getSetting(db, 'forgejo_host') }));
|
||||||
});
|
});
|
||||||
|
|
@ -77,10 +66,6 @@ export function registerRoutes(router, app) {
|
||||||
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
||||||
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
||||||
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
||||||
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
|
|
||||||
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
|
||||||
budget_month_usd: getSetting(db, 'budget_month_usd', ''),
|
|
||||||
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
|
|
||||||
};
|
};
|
||||||
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
||||||
});
|
});
|
||||||
|
|
@ -98,16 +83,6 @@ export function registerRoutes(router, app) {
|
||||||
setSetting(db, 'send_delay_min', String(dmin));
|
setSetting(db, 'send_delay_min', String(dmin));
|
||||||
setSetting(db, 'send_delay_max', String(dmax));
|
setSetting(db, 'send_delay_max', String(dmax));
|
||||||
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
|
||||||
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
|
||||||
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
|
||||||
setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
|
|
||||||
|
|
||||||
const hook = String(b.discord_webhook || '').trim();
|
|
||||||
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
|
||||||
if (hook) setSetting(db, 'discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
|
||||||
if (b.discord_remove === 'on') setSetting(db, 'discord_webhook_enc', null);
|
|
||||||
setSetting(db, 'discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
|
||||||
|
|
||||||
const prev = globalSmtp(app) || {};
|
const prev = globalSmtp(app) || {};
|
||||||
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
||||||
|
|
@ -116,24 +91,9 @@ export function registerRoutes(router, app) {
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------- API JSON ----------
|
// ---------- API JSON ----------
|
||||||
router.post('/api/report/send', async ({ res }) => {
|
|
||||||
const r = await sendWeeklyReport(app);
|
|
||||||
if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord');
|
|
||||||
json(res, { ok: true, channels: r.channels });
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/api/notify/test', async ({ res }) => {
|
|
||||||
if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
|
||||||
const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });
|
|
||||||
if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)');
|
|
||||||
json(res, { ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/api/system', ({ res }) => {
|
router.get('/api/system', ({ res }) => {
|
||||||
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
const queue = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get().n;
|
||||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
json(res, { temp: cpuTemp(), queue, usage: usageSummary(db), thermalMax: cfg.thermalMax });
|
||||||
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
|
||||||
json(res, { temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects', async ({ req, res }) => {
|
router.post('/api/projects', async ({ req, res }) => {
|
||||||
|
|
@ -162,8 +122,7 @@ export function registerRoutes(router, app) {
|
||||||
router.get('/api/projects/:id/status', ({ res, params }) => {
|
router.get('/api/projects/:id/status', ({ res, params }) => {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
const jobs = latestJobs(db, p.id);
|
const jobs = latestJobs(db, p.id);
|
||||||
const tplOut = (row) => (row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null);
|
const tpl = db.prepare('SELECT subject, body, status, updated_at FROM mail_templates WHERE project_id = ?').get(p.id) || null;
|
||||||
const templates = { initial: tplOut(getTemplate(db, p.id, 'initial')), followup: tplOut(getTemplate(db, p.id, 'followup')) };
|
|
||||||
const stats = prospectStats(db, p.id);
|
const stats = prospectStats(db, p.id);
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const sendMax = allowedToSend({
|
const sendMax = allowedToSend({
|
||||||
|
|
@ -172,10 +131,8 @@ export function registerRoutes(router, app) {
|
||||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: sentSince(db, day),
|
globalCap: Number(getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: sentSince(db, day),
|
||||||
});
|
});
|
||||||
json(res, {
|
json(res, {
|
||||||
jobs, templates, stats, sendMax,
|
jobs, template: tpl, stats, sendMax,
|
||||||
followup: { enabled: p.followupEnabled, days: p.followupDays, ...followupPlan(db, p) },
|
|
||||||
targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp,
|
targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp,
|
||||||
hasImap: p.hasImap, inbox: p.inbox, ab: abStats(db, p.id),
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -199,27 +156,14 @@ export function registerRoutes(router, app) {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
||||||
guard(p, b);
|
guard(p, b);
|
||||||
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b) });
|
||||||
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
json(res, r);
|
||||||
const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
|
||||||
const budget = AI_JOBS.has(type) ? budgetState(db) : null;
|
|
||||||
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
router.post('/api/projects/:id/analyze', jobRoute('analyze'));
|
router.post('/api/projects/:id/analyze', jobRoute('analyze'));
|
||||||
router.post('/api/projects/:id/template', jobRoute('template', () => ({}), (p) => {
|
router.post('/api/projects/:id/template', jobRoute('template', () => ({}), (p) => {
|
||||||
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
||||||
}));
|
}));
|
||||||
router.post('/api/projects/:id/followup_template', jobRoute('followup_template', () => ({}), (p) => {
|
|
||||||
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
|
||||||
}));
|
|
||||||
router.post('/api/projects/:id/followup', async ({ req, res, params }) => {
|
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
const b = await readBody(req);
|
|
||||||
const enabled = b.enabled === true || b.enabled === 'on';
|
|
||||||
db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
|
||||||
json(res, { ok: true });
|
|
||||||
});
|
|
||||||
router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => {
|
router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => {
|
||||||
if (!p.targetValidated) throw new HttpError(400, 'Valide la cible avant de prospecter');
|
if (!p.targetValidated) throw new HttpError(400, 'Valide la cible avant de prospecter');
|
||||||
}));
|
}));
|
||||||
|
|
@ -238,12 +182,11 @@ export function registerRoutes(router, app) {
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const subject = String(b.subject || '').trim().slice(0, 200);
|
const subject = String(b.subject || '').trim().slice(0, 200);
|
||||||
const body = String(b.body || '').trim().slice(0, 5000);
|
const body = String(b.body || '').trim().slice(0, 5000);
|
||||||
const subjectB = String(b.subjectB || '').trim().slice(0, 200) || null;
|
if (!subject || !body) throw new HttpError(400, 'Objet et corps requis');
|
||||||
const kind = b.kind === 'followup' ? 'followup' : 'initial';
|
|
||||||
// Relance : objet facultatif (vide = "Re: <objet du 1er mail>", même fil de discussion)
|
|
||||||
if (!body || (kind === 'initial' && !subject)) throw new HttpError(400, kind === 'initial' ? 'Objet et corps requis' : 'Corps requis');
|
|
||||||
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
||||||
saveTemplate(db, p.id, kind, { subject, subjectB, body, status });
|
db.prepare(`INSERT INTO mail_templates(project_id, subject, body, status, updated_at) VALUES(?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(project_id) DO UPDATE SET subject = excluded.subject, body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`)
|
||||||
|
.run(p.id, subject, body, status, now());
|
||||||
json(res, { ok: true, status });
|
json(res, { ok: true, status });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -259,28 +202,6 @@ export function registerRoutes(router, app) {
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Boîte de réception : on enregistre puis on teste tout de suite la connexion
|
|
||||||
router.post('/api/projects/:id/imap', async ({ req, res, params }) => {
|
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
const b = await readBody(req);
|
|
||||||
const host = String(b.host || '').trim();
|
|
||||||
if (!host) {
|
|
||||||
db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
|
||||||
return json(res, { ok: true, disabled: true });
|
|
||||||
}
|
|
||||||
saveSecretConfig(app, p.id, 'imap_enc', {
|
|
||||||
host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '',
|
|
||||||
}, 'pass');
|
|
||||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
|
||||||
catch (e) { json(res, { ok: false, error: e.message }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/api/projects/:id/inbox/check', async ({ res, params }) => {
|
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
|
||||||
catch (e) { throw new HttpError(502, e.message); }
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/api/projects/:id/db', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/db', async ({ req, res, params }) => {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
|
|
@ -302,43 +223,19 @@ export function registerRoutes(router, app) {
|
||||||
const stats = prospectStats(db, p.id);
|
const stats = prospectStats(db, p.id);
|
||||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
||||||
let business = null, error = null;
|
let business = null, error = null;
|
||||||
try {
|
try { business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') }); }
|
||||||
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
catch (e) { error = e.message; }
|
||||||
saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
|
||||||
} catch (e) { error = e.message; }
|
|
||||||
json(res, { business, error, stats, aiCostUsd: cost });
|
json(res, { business, error, stats, aiCostUsd: cost });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/prospects\\.csv', ({ res, params, url }) => {
|
router.get('/api/projects/:id/prospects', ({ res, params }) => {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
const slug = p.name.normalize('NFD').replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'projet';
|
const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at FROM prospects
|
||||||
const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' });
|
WHERE project_id = ? ORDER BY CASE status WHEN 'new' THEN 0 ELSE 1 END, score DESC, id DESC LIMIT 500`).all(p.id);
|
||||||
res.writeHead(200, {
|
json(res, rows);
|
||||||
'Content-Type': 'text/csv; charset=utf-8',
|
|
||||||
'Content-Disposition': `attachment; filename="prospects-${slug}-${date}.csv"`,
|
|
||||||
'Cache-Control': 'no-store',
|
|
||||||
});
|
|
||||||
res.end(exportProspects(db, p.id, parseFilters(url.searchParams)));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/prospects/import', async ({ req, res, params }) => {
|
const STATUSES = ['new', 'sent', 'replied', 'client', 'refused', 'bounced'];
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
const b = await readBody(req, { max: 1024 * 1024 });
|
|
||||||
try { json(res, importProspects(db, p.id, String(b.csv || ''))); }
|
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/api/projects/:id/history', ({ res, params, url }) => {
|
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
json(res, history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/api/projects/:id/prospects', ({ res, params, url }) => {
|
|
||||||
const p = getProject(app, pid(params));
|
|
||||||
json(res, listProspects(db, p.id, parseFilters(url.searchParams)));
|
|
||||||
});
|
|
||||||
|
|
||||||
const STATUSES = Object.keys(PROSPECT_STATUSES);
|
|
||||||
router.post('/api/prospects/:id/status', async ({ req, res, params }) => {
|
router.post('/api/prospects/:id/status', async ({ req, res, params }) => {
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
||||||
|
|
@ -351,29 +248,5 @@ export function registerRoutes(router, app) {
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------- Fiche prospect ----------
|
|
||||||
const prospectId = (params) => {
|
|
||||||
const id = Number(params.id);
|
|
||||||
if (!db.prepare('SELECT 1 FROM prospects WHERE id = ?').get(id)) throw new HttpError(404, 'Prospect introuvable');
|
|
||||||
return id;
|
|
||||||
};
|
|
||||||
router.get('/api/prospects/:id', ({ res, params }) => json(res, prospectDetail(db, prospectId(params))));
|
|
||||||
router.post('/api/prospects/:id/notes', async ({ req, res, params }) => {
|
|
||||||
const id = prospectId(params);
|
|
||||||
const noteId = addNote(db, id, (await readBody(req)).body);
|
|
||||||
if (!noteId) throw new HttpError(400, 'Note vide');
|
|
||||||
json(res, { ok: true, id: noteId });
|
|
||||||
});
|
|
||||||
router.post('/api/prospects/:id/notes/:nid/delete', ({ res, params }) => {
|
|
||||||
if (!deleteNote(db, prospectId(params), Number(params.nid))) throw new HttpError(404, 'Note introuvable');
|
|
||||||
json(res, { ok: true });
|
|
||||||
});
|
|
||||||
router.post('/api/prospects/:id/next', async ({ req, res, params }) => {
|
|
||||||
const id = prospectId(params);
|
|
||||||
const b = await readBody(req);
|
|
||||||
try { json(res, { ok: true, at: setNextAction(db, id, b.action, b.day) }); }
|
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/api/jobs/:id/cancel', ({ res, params }) => { cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
router.post('/api/jobs/:id/cancel', ({ res, params }) => { cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,6 @@ import { getSession, checkOrigin, purgeExpired } from './auth.js';
|
||||||
import { registerRoutes } from './routes.js';
|
import { registerRoutes } from './routes.js';
|
||||||
import { Worker } from './services/jobs.js';
|
import { Worker } from './services/jobs.js';
|
||||||
import { makeHandlers } from './handlers.js';
|
import { makeHandlers } from './handlers.js';
|
||||||
import { Scheduler } from './services/scheduler.js';
|
|
||||||
import { notify, notifyJob } from './services/notify.js';
|
|
||||||
import { budgetState, AI_JOBS } from './services/budget.js';
|
|
||||||
import { layout } from './views.js';
|
import { layout } from './views.js';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
@ -70,30 +67,14 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
||||||
server.requestTimeout = 30_000;
|
server.requestTimeout = 30_000;
|
||||||
|
|
||||||
let w = null;
|
let w = null;
|
||||||
let scheduler = null;
|
|
||||||
if (worker) {
|
if (worker) {
|
||||||
w = new Worker(db, makeHandlers(app), {
|
w = new Worker(db, makeHandlers(app), { thermalMax: cfg.thermalMax });
|
||||||
thermalMax: cfg.thermalMax,
|
|
||||||
onFinish: (job, r) => notifyJob(app, job, r),
|
|
||||||
budget: () => budgetState(db),
|
|
||||||
isAiJob: (type) => AI_JOBS.has(type),
|
|
||||||
onBudget: (reason) => notify(app, 'budget', {
|
|
||||||
title: 'Budget IA atteint', level: 'warn',
|
|
||||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
|
||||||
}),
|
|
||||||
onThermal: (t) => notify(app, 'thermal', {
|
|
||||||
title: 'Pause thermique', level: 'warn',
|
|
||||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
w.start();
|
w.start();
|
||||||
scheduler = new Scheduler(app);
|
|
||||||
scheduler.start();
|
|
||||||
}
|
}
|
||||||
const purge = setInterval(() => purgeExpired(db), 3600_000);
|
const purge = setInterval(() => purgeExpired(db), 3600_000);
|
||||||
purge.unref();
|
purge.unref();
|
||||||
|
|
||||||
app.close = () => new Promise((r) => { w?.stop(); scheduler?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); });
|
app.close = () => new Promise((r) => { w?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); });
|
||||||
app.server = server;
|
app.server = server;
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
// Budget IA : plafonds glissants 24 h / 30 j, en équivalent $ API remonté par Claude Code.
|
|
||||||
// Avec un abonnement Pro rien n'est facturé en plus : c'est un garde-fou pour ne pas épuiser le quota.
|
|
||||||
import { getSetting, now } from '../db.js';
|
|
||||||
|
|
||||||
// Jobs qui appellent Claude (les envois et relances n'en consomment pas)
|
|
||||||
export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_template', 'evolution']);
|
|
||||||
|
|
||||||
const usd = (n) => `${n.toFixed(2)} $`;
|
|
||||||
|
|
||||||
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit)
|
|
||||||
function spentSince(db, since) {
|
|
||||||
return db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(since).c;
|
|
||||||
}
|
|
||||||
|
|
||||||
function limit(db, key) {
|
|
||||||
const v = Number(getSetting(db, key, ''));
|
|
||||||
return Number.isFinite(v) && v > 0 ? v : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {{day: {used:number, limit:number|null}, month: {used:number, limit:number|null}, blocked: boolean, reason: string|null}} */
|
|
||||||
export function budgetState(db, { at = now() } = {}) {
|
|
||||||
const day = { used: spentSince(db, at - 86400), limit: limit(db, 'budget_day_usd') };
|
|
||||||
const month = { used: spentSince(db, at - 30 * 86400), limit: limit(db, 'budget_month_usd') };
|
|
||||||
const over = (x) => x.limit != null && x.used >= x.limit;
|
|
||||||
const reason = over(day) ? `budget IA des dernières 24 h atteint (${usd(day.used)} / ${usd(day.limit)})`
|
|
||||||
: over(month) ? `budget IA des 30 derniers jours atteint (${usd(month.used)} / ${usd(month.limit)})`
|
|
||||||
: null;
|
|
||||||
return { day, month, blocked: !!reason, reason };
|
|
||||||
}
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
// Prospects : filtres, tri, pagination, fiche détaillée. Partagé par la liste et l'export CSV.
|
|
||||||
import { now } from '../db.js';
|
|
||||||
import { parisTime, parisParts } from './paris-time.js';
|
|
||||||
|
|
||||||
export const STATUSES = {
|
|
||||||
new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté',
|
|
||||||
};
|
|
||||||
|
|
||||||
const SORTS = {
|
|
||||||
score: 'score DESC, id DESC',
|
|
||||||
recent: 'created_at DESC, id DESC',
|
|
||||||
contacted: 'COALESCE(sent_at, 0) DESC, id DESC',
|
|
||||||
company: 'company COLLATE NOCASE, id',
|
|
||||||
};
|
|
||||||
|
|
||||||
const int = (v, min, max, def) => {
|
|
||||||
const n = Math.floor(Number(v));
|
|
||||||
return Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : def;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Filtres depuis une query string (valeurs inconnues ignorées, jamais injectées dans le SQL). */
|
|
||||||
export function parseFilters(sp) {
|
|
||||||
return {
|
|
||||||
q: String(sp.get('q') || '').trim().slice(0, 100),
|
|
||||||
status: Object.hasOwn(STATUSES, sp.get('status')) ? sp.get('status') : '',
|
|
||||||
minScore: int(sp.get('minScore'), 0, 10, 0),
|
|
||||||
sort: Object.hasOwn(SORTS, sp.get('sort')) ? sp.get('sort') : 'score',
|
|
||||||
todo: sp.get('todo') === '1',
|
|
||||||
page: int(sp.get('page'), 1, 100_000, 1),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function filterWhere(projectId, f) {
|
|
||||||
const where = ['project_id = ?'];
|
|
||||||
const args = [projectId];
|
|
||||||
if (f.q) {
|
|
||||||
const like = `%${f.q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
|
||||||
where.push("(company LIKE ? ESCAPE '\\' OR email LIKE ? ESCAPE '\\' OR city LIKE ? ESCAPE '\\' OR sector LIKE ? ESCAPE '\\')");
|
|
||||||
args.push(like, like, like, like);
|
|
||||||
}
|
|
||||||
if (f.status) { where.push('status = ?'); args.push(f.status); }
|
|
||||||
if (f.minScore) { where.push('score >= ?'); args.push(f.minScore); }
|
|
||||||
if (f.todo) { where.push('next_action_at IS NOT NULL AND next_action_at <= ?'); args.push(f.at ?? now()); }
|
|
||||||
return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
|
||||||
const { sql, args, order } = filterWhere(projectId, f);
|
|
||||||
const total = db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args).n;
|
|
||||||
const pages = Math.max(1, Math.ceil(total / limit));
|
|
||||||
const page = Math.min(f.page, pages);
|
|
||||||
const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
|
|
||||||
next_action, next_action_at
|
|
||||||
FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit);
|
|
||||||
return { total, page, pages, rows };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Fiche prospect ----------
|
|
||||||
|
|
||||||
/** Tout ce qu'on sait d'un prospect : infos, mails envoyés, réponse, notes. */
|
|
||||||
export function prospectDetail(db, id) {
|
|
||||||
const p = db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
|
|
||||||
if (!p) return null;
|
|
||||||
const mails = db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
|
|
||||||
WHERE prospect_id = ? ORDER BY sent_at, id`).all(id);
|
|
||||||
const notes = db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
|
|
||||||
const optOut = db.prepare('SELECT reason, created_at FROM blacklist WHERE email = ?').get(p.email) || null;
|
|
||||||
return { prospect: p, mails, notes, optOut };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function addNote(db, prospectId, body) {
|
|
||||||
const text = String(body || '').trim().slice(0, 2000);
|
|
||||||
if (!text) return null;
|
|
||||||
return Number(db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now()).lastInsertRowid);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deleteNote(db, prospectId, noteId) {
|
|
||||||
return db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId).changes > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Prochaine action : texte + jour (AAAA-MM-JJ, rappel à 9h heure de Paris). Vide = effacer. */
|
|
||||||
export function setNextAction(db, prospectId, action, day) {
|
|
||||||
const text = String(action || '').trim().slice(0, 200);
|
|
||||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ''));
|
|
||||||
if (!text) {
|
|
||||||
db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (!m) throw new Error('Date attendue au format AAAA-MM-JJ');
|
|
||||||
const date = parisTime(+m[1], +m[2], +m[3], 9);
|
|
||||||
// 2026-02-31 deviendrait le 3 mars sans prévenir : on refuse
|
|
||||||
if (parisParts(date).day !== +m[3]) throw new Error('Date invalide');
|
|
||||||
const at = Math.floor(date.getTime() / 1000);
|
|
||||||
db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
|
|
||||||
return at;
|
|
||||||
}
|
|
||||||
|
|
@ -1,124 +0,0 @@
|
||||||
// Import / export CSV des prospects. Format Excel FR : ";" + BOM UTF-8.
|
|
||||||
import { now } from '../db.js';
|
|
||||||
import { EMAIL_RE } from './mailer.js';
|
|
||||||
import { httpUrl } from '../handlers.js';
|
|
||||||
import { filterWhere, STATUSES } from './crm.js';
|
|
||||||
|
|
||||||
// ---------- Écriture ----------
|
|
||||||
|
|
||||||
// Excel exécute une cellule qui commence par = + - @ : on la neutralise (OWASP CSV injection)
|
|
||||||
const FORMULA = /^[=+\-@\t\r]/;
|
|
||||||
|
|
||||||
export function csvCell(v) {
|
|
||||||
let s = v == null ? '' : String(v);
|
|
||||||
if (FORMULA.test(s)) s = `'${s}`;
|
|
||||||
return /[";\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function toCsv(header, rows) {
|
|
||||||
return '' + [header, ...rows].map((r) => r.map(csvCell).join(';')).join('\r\n') + '\r\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
const day = (ts) => (ts ? new Date(ts * 1000).toLocaleString('sv-SE', { timeZone: 'Europe/Paris' }).slice(0, 16) : '');
|
|
||||||
|
|
||||||
export function exportProspects(db, projectId, filters) {
|
|
||||||
const { sql, args, order } = filterWhere(projectId, filters);
|
|
||||||
const rows = db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args);
|
|
||||||
const header = ['Entreprise', 'Email', 'Site', 'Ville', 'Secteur', 'Score', 'Statut', 'Ajouté le', 'Contacté le', 'Objet',
|
|
||||||
'Relancé le', 'Répondu le', 'Prochaine action', 'Échéance', 'Source', 'Accroche'];
|
|
||||||
return toCsv(header, rows.map((p) => [
|
|
||||||
p.company, p.email, p.website, p.city, p.sector, p.score, STATUSES[p.status] || p.status, day(p.created_at), day(p.sent_at),
|
|
||||||
p.variant, day(p.followup_at), day(p.replied_at), p.next_action, day(p.next_action_at), p.source, p.hook,
|
|
||||||
]));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Lecture ----------
|
|
||||||
|
|
||||||
/** CSV RFC 4180 : guillemets, "" échappés, retours à la ligne dans les cellules, séparateur ; , ou tab. */
|
|
||||||
export function parseCsv(text) {
|
|
||||||
const src = String(text).replace(/^/, '');
|
|
||||||
const firstLine = src.slice(0, src.search(/\r?\n|$/));
|
|
||||||
const count = (c) => firstLine.split(c).length - 1;
|
|
||||||
const sep = [';', ',', '\t'].sort((a, b) => count(b) - count(a))[0];
|
|
||||||
const rows = [];
|
|
||||||
let row = [], cell = '', quoted = false;
|
|
||||||
for (let i = 0; i < src.length; i++) {
|
|
||||||
const c = src[i];
|
|
||||||
if (quoted) {
|
|
||||||
if (c === '"' && src[i + 1] === '"') { cell += '"'; i++; }
|
|
||||||
else if (c === '"') quoted = false;
|
|
||||||
else cell += c;
|
|
||||||
} else if (c === '"' && cell === '') quoted = true;
|
|
||||||
else if (c === sep) { row.push(cell); cell = ''; }
|
|
||||||
else if (c === '\n' || c === '\r') {
|
|
||||||
if (c === '\r' && src[i + 1] === '\n') i++;
|
|
||||||
row.push(cell); rows.push(row); row = []; cell = '';
|
|
||||||
} else cell += c;
|
|
||||||
}
|
|
||||||
if (cell !== '' || row.length) { row.push(cell); rows.push(row); }
|
|
||||||
return rows.filter((r) => r.some((x) => x.trim() !== ''));
|
|
||||||
}
|
|
||||||
|
|
||||||
const norm = (s) => String(s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z]/g, '');
|
|
||||||
const ALIASES = {
|
|
||||||
company: ['entreprise', 'societe', 'company', 'nom', 'raisonsociale', 'name', 'enseigne'],
|
|
||||||
email: ['email', 'mail', 'courriel', 'adresseemail', 'adressemail', 'emailaddress'],
|
|
||||||
website: ['site', 'website', 'url', 'siteweb', 'siteinternet'],
|
|
||||||
city: ['ville', 'city', 'commune', 'localite'],
|
|
||||||
sector: ['secteur', 'sector', 'activite', 'metier', 'categorie'],
|
|
||||||
score: ['score', 'note', 'pertinence'],
|
|
||||||
source: ['source', 'origine'],
|
|
||||||
hook: ['accroche', 'hook'],
|
|
||||||
};
|
|
||||||
const MAX_ROWS = 2000;
|
|
||||||
|
|
||||||
// Notre propre export préfixe les formules par ' : on l'enlève à la relecture
|
|
||||||
const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s);
|
|
||||||
|
|
||||||
export function importProspects(db, projectId, text, { at = now() } = {}) {
|
|
||||||
const rows = parseCsv(text);
|
|
||||||
if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête');
|
|
||||||
const header = rows[0].map(norm);
|
|
||||||
const col = {};
|
|
||||||
for (const [field, names] of Object.entries(ALIASES)) {
|
|
||||||
const i = header.findIndex((h) => names.includes(h));
|
|
||||||
if (i >= 0) col[field] = i;
|
|
||||||
}
|
|
||||||
if (col.email === undefined) throw new Error('Colonne email introuvable (attendu : "email", "mail" ou "courriel")');
|
|
||||||
const data = rows.slice(1);
|
|
||||||
if (data.length > MAX_ROWS) throw new Error(`Maximum ${MAX_ROWS} lignes par import (${data.length} dans le fichier)`);
|
|
||||||
|
|
||||||
const dateLabel = new Date(at * 1000).toLocaleDateString('fr-FR', { timeZone: 'Europe/Paris' });
|
|
||||||
const exists = db.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?');
|
|
||||||
const optOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
|
||||||
const insert = db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at)
|
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
||||||
const res = { total: data.length, imported: 0, duplicates: 0, blacklisted: 0, invalid: [] };
|
|
||||||
const seen = new Set();
|
|
||||||
const get = (r, k, max = 200) => (col[k] === undefined ? '' : unformula(String(r[col[k]] ?? '').trim()).slice(0, max));
|
|
||||||
|
|
||||||
db.exec('BEGIN');
|
|
||||||
try {
|
|
||||||
data.forEach((r, i) => {
|
|
||||||
const line = i + 2;
|
|
||||||
const email = get(r, 'email').toLowerCase();
|
|
||||||
if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); return; }
|
|
||||||
if (seen.has(email) || exists.get(projectId, email)) { res.duplicates++; return; }
|
|
||||||
seen.add(email);
|
|
||||||
if (optOut.get(email)) { res.blacklisted++; return; }
|
|
||||||
const s = Number(get(r, 'score'));
|
|
||||||
insert.run(
|
|
||||||
projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null,
|
|
||||||
get(r, 'sector', 100) || null, Number.isFinite(s) && s > 0 ? Math.max(1, Math.min(10, Math.round(s))) : null,
|
|
||||||
// RGPD : on garde toujours l'origine de la donnée
|
|
||||||
httpUrl(get(r, 'source', 300)) || get(r, 'source', 300) || `Import CSV du ${dateLabel}`, get(r, 'hook', 400) || null, at,
|
|
||||||
);
|
|
||||||
res.imported++;
|
|
||||||
});
|
|
||||||
db.exec('COMMIT');
|
|
||||||
} catch (e) {
|
|
||||||
db.exec('ROLLBACK');
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
// Relance automatique : qui relancer, quand, et ce qui bloque.
|
|
||||||
import { now } from '../db.js';
|
|
||||||
import { getTemplate } from '../projects.js';
|
|
||||||
|
|
||||||
const INBOX_MAX_AGE = 2 * 3600; // la boîte doit avoir été lue il y a moins de 2 h
|
|
||||||
|
|
||||||
// Lundi-vendredi, 9h-18h heure de Paris : une relance à 3h du matin sent le robot
|
|
||||||
export function isBusinessHours(date = new Date(), timeZone = 'Europe/Paris') {
|
|
||||||
const parts = Object.fromEntries(
|
|
||||||
new Intl.DateTimeFormat('en-GB', { timeZone, weekday: 'short', hour: 'numeric', hour12: false })
|
|
||||||
.formatToParts(date).map((p) => [p.type, p.value]),
|
|
||||||
);
|
|
||||||
const hour = Number(parts.hour) % 24;
|
|
||||||
return !['Sat', 'Sun'].includes(parts.weekday) && hour >= 9 && hour < 18;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CANDIDATES_SQL = `FROM prospects WHERE project_id = ? AND status = 'sent' AND followup_at IS NULL
|
|
||||||
AND sent_at <= ? AND email NOT IN (SELECT email FROM blacklist)`;
|
|
||||||
|
|
||||||
export function followupCandidates(db, project, { at = now(), limit = 100 } = {}) {
|
|
||||||
const cutoff = at - project.followupDays * 86400;
|
|
||||||
return db.prepare(`SELECT * ${CANDIDATES_SQL} ORDER BY sent_at, id LIMIT ?`).all(project.id, cutoff, limit);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {{due: number, blockers: string[], inHours: boolean, ready: boolean}} */
|
|
||||||
export function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) {
|
|
||||||
const blockers = [];
|
|
||||||
if (!project.followupEnabled) blockers.push('relance désactivée');
|
|
||||||
if (!getTemplate(db, project.id, 'followup', { validatedOnly: true })) blockers.push('modèle de relance à valider');
|
|
||||||
if (!project.hasSmtp) blockers.push('SMTP à configurer');
|
|
||||||
// Sans lecture de la boîte, on relancerait des gens qui ont déjà répondu
|
|
||||||
const inbox = project.inbox || {};
|
|
||||||
if (!project.hasImap) blockers.push('boîte IMAP à connecter');
|
|
||||||
else if (inbox.lastError || !inbox.lastOk || at - inbox.lastOk > INBOX_MAX_AGE) blockers.push('boîte non vérifiée récemment');
|
|
||||||
|
|
||||||
const cutoff = at - project.followupDays * 86400;
|
|
||||||
const due = db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff).n;
|
|
||||||
const inHours = isBusinessHours(date);
|
|
||||||
return { due, blockers, inHours, ready: !blockers.length && inHours && due > 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Objet de la relance : vide = "Re: <objet du premier mail>" pour rester dans le même fil
|
|
||||||
export function followupSubject(template, original) {
|
|
||||||
if (template.subject) return template.subject;
|
|
||||||
const s = original?.subject || 'notre échange';
|
|
||||||
return /^re\s*:/i.test(s) ? s : `Re: ${s}`;
|
|
||||||
}
|
|
||||||
|
|
@ -1,175 +0,0 @@
|
||||||
// Lecture de la boîte de réception (IMAP) : rattache les réponses et les bounces aux prospects.
|
|
||||||
// Aucun token Claude : uniquement des en-têtes de mails.
|
|
||||||
import { now } from '../db.js';
|
|
||||||
import { getProject } from '../projects.js';
|
|
||||||
import { notify } from './notify.js';
|
|
||||||
|
|
||||||
// Webmails grand public : une réponse d'un autre @gmail.com ne dit rien sur l'entreprise
|
|
||||||
const GENERIC_DOMAINS = new Set([
|
|
||||||
'gmail.com', 'googlemail.com', 'yahoo.fr', 'yahoo.com', 'hotmail.fr', 'hotmail.com', 'outlook.fr', 'outlook.com',
|
|
||||||
'live.fr', 'live.com', 'msn.com', 'icloud.com', 'me.com', 'orange.fr', 'wanadoo.fr', 'free.fr', 'sfr.fr', 'neuf.fr',
|
|
||||||
'laposte.net', 'bbox.fr', 'gmx.fr', 'gmx.com', 'aol.com', 'protonmail.com', 'proton.me',
|
|
||||||
]);
|
|
||||||
|
|
||||||
const MSGID_RE = /<[^<>\s@]+@[^<>\s]+>/g;
|
|
||||||
const ids = (s) => String(s || '').match(MSGID_RE) || [];
|
|
||||||
const HEADER_FIELDS = ['references', 'auto-submitted', 'x-autoreply', 'x-autorespond', 'precedence', 'content-type'];
|
|
||||||
|
|
||||||
// En-têtes bruts (Buffer) → { nom: valeur } avec les lignes repliées dépliées
|
|
||||||
export function parseHeaders(raw) {
|
|
||||||
const out = {};
|
|
||||||
const text = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw || '');
|
|
||||||
for (const line of text.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) {
|
|
||||||
const i = line.indexOf(':');
|
|
||||||
if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {{type: 'reply'|'auto'|'bounce', from: string, ids: string[]}} */
|
|
||||||
export function classify(msg) {
|
|
||||||
const h = msg.headers || {};
|
|
||||||
const from = String(msg.from || '').toLowerCase();
|
|
||||||
const subject = String(msg.subject || '').trim();
|
|
||||||
const refs = [...new Set([...ids(msg.inReplyTo), ...ids(h.references)])];
|
|
||||||
|
|
||||||
const bounce = /^(mailer-daemon|postmaster)@/.test(from)
|
|
||||||
|| /report-type=["']?delivery-status/i.test(h['content-type'] || '')
|
|
||||||
|| /^(undeliver|delivery status notification|mail delivery failed|returned mail|non remis|échec de (la )?remise)/i.test(subject);
|
|
||||||
if (bounce) return { type: 'bounce', from, ids: [...new Set([...refs, ...ids(msg.body)])] };
|
|
||||||
|
|
||||||
const auto = (h['auto-submitted'] && !/^no$/i.test(h['auto-submitted']))
|
|
||||||
|| h['x-autoreply'] || h['x-autorespond']
|
|
||||||
|| /^(auto_reply|bulk|junk|list)$/i.test(h.precedence || '')
|
|
||||||
|| /^(absence|out of office|automatic reply|réponse automatique|auto:|autoreply|abwesend)/i.test(subject);
|
|
||||||
if (auto) return { type: 'auto', from, ids: refs };
|
|
||||||
|
|
||||||
return { type: 'reply', from, ids: refs };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Applique une liste de messages aux prospects du projet. Idempotent. */
|
|
||||||
export function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
|
||||||
const res = { replies: 0, bounces: 0, ignored: 0 };
|
|
||||||
const byMsgId = db.prepare('SELECT prospect_id FROM mail_log WHERE project_id = ? AND message_id = ? AND prospect_id IS NOT NULL LIMIT 1');
|
|
||||||
const byEmail = db.prepare('SELECT id FROM prospects WHERE project_id = ? AND email = ? LIMIT 1');
|
|
||||||
const byDomain = db.prepare("SELECT id FROM prospects WHERE project_id = ? AND status = 'sent' AND substr(email, instr(email, '@') + 1) = ?");
|
|
||||||
const markReply = db.prepare("UPDATE prospects SET status = 'replied', replied_at = ?, reply_subject = ? WHERE id = ? AND status = 'sent'");
|
|
||||||
const markBounce = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ? AND status = 'sent'");
|
|
||||||
const blacklist = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) SELECT email, 'bounce', ? FROM prospects WHERE id = ?");
|
|
||||||
|
|
||||||
const fromIds = (list) => {
|
|
||||||
for (const id of list) { const r = byMsgId.get(projectId, id); if (r) return r.prospect_id; }
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const msg of messages) {
|
|
||||||
const c = classify(msg);
|
|
||||||
if (c.type === 'bounce') {
|
|
||||||
const pid = fromIds(c.ids);
|
|
||||||
if (pid && markBounce.run(pid).changes) { blacklist.run(at, pid); res.bounces++; } else res.ignored++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (c.type === 'auto') { res.ignored++; continue; }
|
|
||||||
|
|
||||||
// Réponse : 1) fil de discussion, 2) même adresse, 3) même domaine pro (un seul prospect en attente dessus)
|
|
||||||
let pid = fromIds(c.ids) ?? byEmail.get(projectId, c.from)?.id ?? null;
|
|
||||||
if (!pid) {
|
|
||||||
const domain = c.from.split('@')[1];
|
|
||||||
if (domain && !GENERIC_DOMAINS.has(domain)) {
|
|
||||||
const rows = byDomain.all(projectId, domain);
|
|
||||||
if (rows.length === 1) pid = rows[0].id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (pid && markReply.run(at, String(msg.subject || '').slice(0, 300), pid).changes) res.replies++;
|
|
||||||
else res.ignored++;
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lit les nouveaux messages de INBOX depuis le dernier UID vu. */
|
|
||||||
export async function fetchInbox(creds, state, { since, max = 500 }) {
|
|
||||||
const { ImapFlow } = await import('imapflow');
|
|
||||||
const client = new ImapFlow({
|
|
||||||
host: creds.host, port: creds.port, secure: creds.port === 993,
|
|
||||||
auth: { user: creds.user, pass: creds.pass }, logger: false,
|
|
||||||
socketTimeout: 60_000, connectionTimeout: 15_000,
|
|
||||||
});
|
|
||||||
// Sans écouteur, une erreur réseau tardive (timeout après un échec d'auth) ferait planter tout le serveur
|
|
||||||
client.on('error', () => {});
|
|
||||||
try {
|
|
||||||
await client.connect();
|
|
||||||
} catch (e) {
|
|
||||||
client.close();
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
const out = { messages: [], uidValidity: null, lastUid: 0 };
|
|
||||||
let lock;
|
|
||||||
try {
|
|
||||||
lock = await client.getMailboxLock('INBOX');
|
|
||||||
const uidValidity = String(client.mailbox.uidValidity);
|
|
||||||
let lastUid = state?.uidValidity === uidValidity ? Number(state.lastUid || 0) : 0;
|
|
||||||
const found = lastUid
|
|
||||||
? await client.search({ uid: `${lastUid + 1}:*` }, { uid: true })
|
|
||||||
: await client.search({ since }, { uid: true });
|
|
||||||
// "N:*" renvoie toujours au moins le dernier message, même déjà vu
|
|
||||||
const uids = (found || []).filter((u) => u > lastUid).sort((a, b) => a - b).slice(-max);
|
|
||||||
|
|
||||||
if (uids.length) {
|
|
||||||
// Pas d'autre commande IMAP possible pendant cette boucle
|
|
||||||
for await (const m of client.fetch(uids.join(','), { uid: true, envelope: true, headers: HEADER_FIELDS }, { uid: true })) {
|
|
||||||
out.messages.push({
|
|
||||||
uid: m.uid,
|
|
||||||
from: m.envelope?.from?.[0]?.address || '',
|
|
||||||
subject: m.envelope?.subject || '',
|
|
||||||
inReplyTo: m.envelope?.inReplyTo || '',
|
|
||||||
headers: parseHeaders(m.headers),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Les bounces citent notre Message-ID dans le corps : on lit seulement leur début
|
|
||||||
for (const msg of out.messages) {
|
|
||||||
if (classify(msg).type !== 'bounce') continue;
|
|
||||||
const full = await client.fetchOne(String(msg.uid), { source: { maxLength: 100_000 } }, { uid: true });
|
|
||||||
msg.body = full?.source ? full.source.toString('utf8') : '';
|
|
||||||
}
|
|
||||||
lastUid = Math.max(lastUid, ...uids);
|
|
||||||
}
|
|
||||||
out.uidValidity = uidValidity;
|
|
||||||
out.lastUid = lastUid;
|
|
||||||
} finally {
|
|
||||||
lock?.release();
|
|
||||||
await client.logout().catch(() => {});
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Vérifie la boîte d'un projet et mémorise l'état (dernier UID, erreurs, compteurs). */
|
|
||||||
export async function checkInbox(app, projectId) {
|
|
||||||
const { db } = app;
|
|
||||||
const project = getProject(app, projectId, { secrets: true });
|
|
||||||
if (!project.imap) throw new Error('Boîte IMAP non configurée');
|
|
||||||
const state = project.inbox || {};
|
|
||||||
const firstSent = db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id).t;
|
|
||||||
const since = new Date(((firstSent || now()) - 86400) * 1000);
|
|
||||||
const at = now();
|
|
||||||
const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id);
|
|
||||||
try {
|
|
||||||
const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since });
|
|
||||||
const res = applyMessages(db, project.id, r.messages, { at });
|
|
||||||
save({
|
|
||||||
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
|
||||||
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
|
||||||
});
|
|
||||||
if (res.replies) {
|
|
||||||
const who = db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
|
||||||
await notify(app, 'reply', {
|
|
||||||
title: `${project.name} · ${res.replies} réponse(s) de prospect`, level: 'ok',
|
|
||||||
description: who.map((p) => `**${p.company}** (${p.email}) : ${p.reply_subject || 'sans objet'}`).join('\n'),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
} catch (e) {
|
|
||||||
const msg = String(e.responseText || e.message || e).slice(0, 300);
|
|
||||||
save({ ...state, lastCheck: at, lastError: msg });
|
|
||||||
throw new Error(`IMAP : ${msg}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,13 +2,13 @@
|
||||||
import { now } from '../db.js';
|
import { now } from '../db.js';
|
||||||
import { waitCool } from './thermal.js';
|
import { waitCool } from './thermal.js';
|
||||||
|
|
||||||
export function enqueue(db, { projectId, type, params = {}, runAfter = null }) {
|
export function enqueue(db, { projectId, type, params = {} }) {
|
||||||
const running = db.prepare(
|
const running = db.prepare(
|
||||||
"SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')"
|
"SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')"
|
||||||
).get(projectId ?? null, type);
|
).get(projectId ?? null, type);
|
||||||
if (running) return { id: running.id, existing: true };
|
if (running) return { id: running.id, existing: true };
|
||||||
const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?)')
|
const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at) VALUES(?, ?, ?, ?)')
|
||||||
.run(projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
.run(projectId ?? null, type, JSON.stringify(params), now());
|
||||||
return { id: Number(r.lastInsertRowid), existing: false };
|
return { id: Number(r.lastInsertRowid), existing: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -32,21 +32,14 @@ export function latestJobs(db, projectId) {
|
||||||
id: r.id, status: r.status, error: r.error,
|
id: r.id, status: r.status, error: r.error,
|
||||||
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
|
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
|
||||||
result: r.result_json ? JSON.parse(r.result_json) : null,
|
result: r.result_json ? JSON.parse(r.result_json) : null,
|
||||||
createdAt: r.created_at, finishedAt: r.finished_at, runAfter: r.run_after,
|
createdAt: r.created_at, finishedAt: r.finished_at,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Worker {
|
export class Worker {
|
||||||
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal, budget, isAiJob, onBudget } = {}) {
|
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console } = {}) {
|
||||||
this.clock = clock;
|
|
||||||
this.budget = budget; // () => {blocked, reason}
|
|
||||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget atteint
|
|
||||||
this.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
|
||||||
this.budgetBlocked = false;
|
|
||||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
|
||||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
|
||||||
this.db = db;
|
this.db = db;
|
||||||
this.handlers = handlers;
|
this.handlers = handlers;
|
||||||
this.thermalMax = thermalMax;
|
this.thermalMax = thermalMax;
|
||||||
|
|
@ -64,12 +57,6 @@ export class Worker {
|
||||||
|
|
||||||
stop() { this.stopped = true; this.current?.abort(); }
|
stop() { this.stopped = true; this.current?.abort(); }
|
||||||
|
|
||||||
// Les callbacks ne doivent jamais bloquer ni faire tomber le worker
|
|
||||||
emit(name, ...args) {
|
|
||||||
try { Promise.resolve(this[name]?.(...args)).catch((e) => this.log.error(`[${name}]`, e.message)); }
|
|
||||||
catch (e) { this.log.error(`[${name}]`, e.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
isCancelled(jobId) {
|
isCancelled(jobId) {
|
||||||
return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled';
|
return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled';
|
||||||
}
|
}
|
||||||
|
|
@ -82,26 +69,7 @@ export class Worker {
|
||||||
}
|
}
|
||||||
|
|
||||||
async tick() {
|
async tick() {
|
||||||
const due = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
const job = this.db.prepare("SELECT * FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1").get();
|
||||||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
|
||||||
if (!due.length) return false;
|
|
||||||
|
|
||||||
// Budget atteint : les jobs IA restent en file (pas perdus), les autres passent devant
|
|
||||||
const budget = this.budget?.() || { blocked: false };
|
|
||||||
let job = null;
|
|
||||||
let waiting = false;
|
|
||||||
for (const j of due) {
|
|
||||||
if (budget.blocked && this.isAiJob?.(j.type)) {
|
|
||||||
waiting = true;
|
|
||||||
const msg = JSON.stringify({ message: `En attente : ${budget.reason}` });
|
|
||||||
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
job = j;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
|
||||||
this.budgetBlocked = waiting;
|
|
||||||
if (!job) return false;
|
if (!job) return false;
|
||||||
const handler = this.handlers[job.type];
|
const handler = this.handlers[job.type];
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
|
|
@ -109,13 +77,7 @@ export class Worker {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
let warned = false;
|
await waitCool(this.thermalMax, { onWait: (t) => setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` }) });
|
||||||
await waitCool(this.thermalMax, {
|
|
||||||
onWait: (t) => {
|
|
||||||
setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
|
||||||
if (!warned) { warned = true; this.emit('onThermal', t); }
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
||||||
const ctrl = new AbortController();
|
const ctrl = new AbortController();
|
||||||
|
|
@ -136,14 +98,12 @@ export class Worker {
|
||||||
if (!this.isCancelled(job.id)) {
|
if (!this.isCancelled(job.id)) {
|
||||||
this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||||
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||||
this.emit('onFinish', job, { status: 'done', result });
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
||||||
if (!this.isCancelled(job.id)) {
|
if (!this.isCancelled(job.id)) {
|
||||||
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||||
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||||
this.emit('onFinish', job, { status: 'error', error: e.message });
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
clearInterval(watch);
|
clearInterval(watch);
|
||||||
|
|
@ -160,11 +120,10 @@ export function addUsage(ctx, r) {
|
||||||
ctx.usage.tokensOut += r.tokensOut || 0;
|
ctx.usage.tokensOut += r.tokensOut || 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
// Conso des 30 derniers jours, pour la jauge
|
||||||
export function usageSummary(db) {
|
export function usageSummary(db) {
|
||||||
const since = now() - 30 * 86400;
|
const since = now() - 30 * 86400;
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const q = (s) => db.prepare(`SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n
|
const q = (s) => db.prepare('SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n FROM jobs WHERE created_at > ?').get(s);
|
||||||
FROM jobs WHERE COALESCE(finished_at, created_at) > ?`).get(s);
|
|
||||||
return { month: q(since), day: q(day) };
|
return { month: q(since), day: q(day) };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
|
|
||||||
export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
|
export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
|
||||||
|
|
||||||
|
|
@ -21,13 +20,7 @@ export function fillTemplate(text, vars) {
|
||||||
return String(text).replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => vars[k] ?? '');
|
return String(text).replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => vars[k] ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message-ID maîtrisé : c'est lui qui permet de rattacher une réponse au bon prospect
|
export function buildProspectMail({ template, prospect, smtp, unsubUrl }) {
|
||||||
export function makeMessageId(fromEmail) {
|
|
||||||
const domain = String(fromEmail || '').split('@')[1] || 'aitools.local';
|
|
||||||
return `<${Date.now().toString(36)}.${randomBytes(9).toString('base64url')}@${domain}>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildProspectMail({ template, prospect, smtp, unsubUrl, subject = template.subject, messageId, inReplyTo }) {
|
|
||||||
const vars = {
|
const vars = {
|
||||||
entreprise: prospect.company,
|
entreprise: prospect.company,
|
||||||
ville: prospect.city || '',
|
ville: prospect.city || '',
|
||||||
|
|
@ -44,10 +37,8 @@ export function buildProspectMail({ template, prospect, smtp, unsubUrl, subject
|
||||||
return {
|
return {
|
||||||
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
|
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
|
||||||
to: prospect.email,
|
to: prospect.email,
|
||||||
subject: fillTemplate(subject, vars).trim(),
|
subject: fillTemplate(template.subject, vars).trim(),
|
||||||
text: body + '\n' + footer,
|
text: body + '\n' + footer,
|
||||||
...(messageId ? { messageId } : {}),
|
|
||||||
...(inReplyTo ? { inReplyTo, references: [inReplyTo] } : {}),
|
|
||||||
headers: {
|
headers: {
|
||||||
'List-Unsubscribe': `<${unsubUrl}>`,
|
'List-Unsubscribe': `<${unsubUrl}>`,
|
||||||
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
||||||
|
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
// Historique : photo quotidienne des KPI business (la BDD des projets ne les historise pas)
|
|
||||||
// + prospection recalculée depuis nos propres journaux (rien à stocker en plus).
|
|
||||||
import { now } from '../db.js';
|
|
||||||
import { getProject } from '../projects.js';
|
|
||||||
import { fetchRecap } from './recap.js';
|
|
||||||
import { parisParts, parisTime, addParisDays } from './paris-time.js';
|
|
||||||
|
|
||||||
const pad = (n) => String(n).padStart(2, '0');
|
|
||||||
export const parisDay = (date = new Date()) => { const p = parisParts(date); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; };
|
|
||||||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
||||||
|
|
||||||
export function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
|
||||||
db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
|
||||||
ON CONFLICT(project_id, day) DO UPDATE SET users = excluded.users, clients = excluded.clients, revenue = excluded.revenue`)
|
|
||||||
.run(projectId, parisDay(date), num(business.users), num(business.clients), num(business.revenue));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Une photo par projet et par jour, appelée par le planificateur (toutes les 15 min, ne fait rien si déjà prise). */
|
|
||||||
export async function snapshotAll(app, { date = new Date(), log = console } = {}) {
|
|
||||||
const day = parisDay(date);
|
|
||||||
const todo = app.db.prepare(`SELECT id FROM projects WHERE db_enc IS NOT NULL
|
|
||||||
AND id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
|
||||||
let n = 0;
|
|
||||||
for (const { id } of todo) {
|
|
||||||
try {
|
|
||||||
const p = getProject(app, id, { secrets: true });
|
|
||||||
saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
|
||||||
n++;
|
|
||||||
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
|
||||||
}
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lundi (heure de Paris) de la semaine qui contient cet instant
|
|
||||||
function weekStart(date) {
|
|
||||||
const p = parisParts(date);
|
|
||||||
const back = ({ Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 })[p.weekday];
|
|
||||||
const d = addParisDays(date, -back);
|
|
||||||
return `${d.year}-${pad(d.month)}-${pad(d.day)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Séries pour les graphiques : jours (KPI business) et semaines (envois / réponses). */
|
|
||||||
export function history(db, projectId, { days = 30, at = now() } = {}) {
|
|
||||||
const fromDay = parisDay(new Date((at - (days - 1) * 86400) * 1000));
|
|
||||||
const daily = db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
|
||||||
.all(projectId, fromDay);
|
|
||||||
|
|
||||||
const nWeeks = Math.ceil(days / 7);
|
|
||||||
const weeks = [];
|
|
||||||
let cursor = new Date(at * 1000);
|
|
||||||
for (let i = 0; i < nWeeks; i++) {
|
|
||||||
weeks.unshift({ start: weekStart(cursor), sent: 0, replies: 0 });
|
|
||||||
cursor = new Date(cursor.getTime() - 7 * 86_400_000);
|
|
||||||
}
|
|
||||||
const first = weeks[0].start.split('-').map(Number);
|
|
||||||
const since = Math.floor(parisTime(first[0], first[1], first[2], 0).getTime() / 1000);
|
|
||||||
const bucket = (ts) => weeks.find((w) => w.start === weekStart(new Date(ts * 1000)));
|
|
||||||
for (const r of db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
|
||||||
const w = bucket(r.sent_at); if (w) w.sent++;
|
|
||||||
}
|
|
||||||
for (const r of db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
|
||||||
const w = bucket(r.replied_at); if (w) w.replies++;
|
|
||||||
}
|
|
||||||
return { daily, weeks };
|
|
||||||
}
|
|
||||||
|
|
@ -1,84 +0,0 @@
|
||||||
// Notifications Discord via webhook (pas de bot, pas de process permanent : une requête HTTP).
|
|
||||||
import { getSetting } from '../db.js';
|
|
||||||
import { decrypt } from '../crypto.js';
|
|
||||||
|
|
||||||
// Uniquement de vraies URLs de webhook Discord : jamais d'envoi vers une adresse arbitraire
|
|
||||||
export const WEBHOOK_RE = /^https:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d{5,25}\/[\w-]{20,120}$/;
|
|
||||||
|
|
||||||
export const EVENTS = {
|
|
||||||
job_done: 'Recherche, analyse, envoi ou évolutions terminés',
|
|
||||||
job_error: 'Job en erreur',
|
|
||||||
reply: 'Réponse d\'un prospect',
|
|
||||||
followup: 'Relances envoyées',
|
|
||||||
thermal: 'Pause thermique du Pi',
|
|
||||||
budget: 'Budget IA atteint',
|
|
||||||
weekly: 'Rapport hebdo',
|
|
||||||
};
|
|
||||||
|
|
||||||
const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c };
|
|
||||||
|
|
||||||
export function notifyConfig(app) {
|
|
||||||
let url = null;
|
|
||||||
try { url = decrypt(app.cfg.secretKey, getSetting(app.db, 'discord_webhook_enc')); }
|
|
||||||
catch { url = null; }
|
|
||||||
const raw = getSetting(app.db, 'discord_events');
|
|
||||||
const events = raw ? JSON.parse(raw) : Object.keys(EVENTS);
|
|
||||||
return { url, events };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Envoie une notif si le webhook est configuré et l'événement activé. Ne lève jamais d'erreur. */
|
|
||||||
export async function notify(app, event, { title, description = '', level = 'info', fields = [] }, { force = false } = {}) {
|
|
||||||
const { url, events } = notifyConfig(app);
|
|
||||||
if (!url || (!force && !events.includes(event))) return false;
|
|
||||||
const body = {
|
|
||||||
username: 'AiTools',
|
|
||||||
allowed_mentions: { parse: [] }, // un "@everyone" dans un nom d'entreprise ne pingera personne
|
|
||||||
embeds: [{
|
|
||||||
title: String(title).slice(0, 256),
|
|
||||||
description: String(description).slice(0, 4000),
|
|
||||||
color: COLORS[level] ?? COLORS.info,
|
|
||||||
fields: fields.slice(0, 10).map((f) => ({
|
|
||||||
name: String(f.name).slice(0, 256), value: String(f.value ?? '-').slice(0, 1024) || '-', inline: f.inline ?? true,
|
|
||||||
})),
|
|
||||||
url: app.cfg.appUrl || undefined,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
const r = await (app.fetch || fetch)(url, {
|
|
||||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(body), signal: AbortSignal.timeout(10_000),
|
|
||||||
});
|
|
||||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
console.warn('[discord]', e.message);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fin de job → notif (seulement pour les jobs longs, ceux qu'on lance et qu'on oublie)
|
|
||||||
const DONE = {
|
|
||||||
analyze: () => ({ title: 'Fiche projet à jour', level: 'ok' }),
|
|
||||||
prospect: (r) => ({ title: 'Recherche de prospects terminée', description: `${r?.found ?? 0} nouveau(x) prospect(s) sur ${r?.requested ?? '?'} demandés.`, level: 'ok' }),
|
|
||||||
send: (r) => ({ title: 'Envoi terminé', description: `${r?.sent ?? 0} mail(s) envoyé(s), ${r?.failed ?? 0} échec(s).`, level: r?.failed ? 'warn' : 'ok' }),
|
|
||||||
evolution: (r) => ({ title: 'Évolutions prêtes', description: `Envoyées à ${r?.sentTo ?? 'ta boîte'}.`, level: 'ok' }),
|
|
||||||
};
|
|
||||||
const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de mail', followup_template: 'Modèle de relance', send: 'Envoi', followup: 'Relances', evolution: 'Évolutions' };
|
|
||||||
|
|
||||||
export function notifyJob(app, job, { status, result, error }) {
|
|
||||||
const project = job.project_id ? app.db.prepare('SELECT name FROM projects WHERE id = ?').get(job.project_id)?.name : null;
|
|
||||||
const prefix = project ? `${project} · ` : '';
|
|
||||||
if (status === 'error') {
|
|
||||||
return notify(app, 'job_error', { title: `${prefix}${LABEL[job.type] || job.type} en échec`, description: String(error || '').slice(0, 500), level: 'error' });
|
|
||||||
}
|
|
||||||
if (status !== 'done') return Promise.resolve(false);
|
|
||||||
if (job.type === 'followup') {
|
|
||||||
if (!result?.sent) return Promise.resolve(false);
|
|
||||||
return notify(app, 'followup', { title: `${prefix}Relances envoyées`, description: `${result.sent} relance(s), ${result.failed} échec(s).`, level: 'info' });
|
|
||||||
}
|
|
||||||
const make = DONE[job.type];
|
|
||||||
if (!make) return Promise.resolve(false);
|
|
||||||
const n = make(result);
|
|
||||||
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}` });
|
|
||||||
}
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
// Heures "murales" de Paris, changements d'heure compris. Aucune dépendance.
|
|
||||||
const TZ = 'Europe/Paris';
|
|
||||||
|
|
||||||
const partsFmt = new Intl.DateTimeFormat('en-GB', {
|
|
||||||
timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
||||||
hour: '2-digit', minute: '2-digit', weekday: 'short', hourCycle: 'h23',
|
|
||||||
});
|
|
||||||
const offsetFmt = new Intl.DateTimeFormat('en-US', { timeZone: TZ, timeZoneName: 'shortOffset' });
|
|
||||||
|
|
||||||
/** @returns {{year:number, month:number, day:number, hour:number, minute:number, weekday:string}} */
|
|
||||||
export function parisParts(date = new Date()) {
|
|
||||||
const p = Object.fromEntries(partsFmt.formatToParts(date).map((x) => [x.type, x.value]));
|
|
||||||
return { year: +p.year, month: +p.month, day: +p.day, hour: +p.hour % 24, minute: +p.minute, weekday: p.weekday };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Décalage de Paris par rapport à UTC à un instant donné, en minutes (+60 l'hiver, +120 l'été)
|
|
||||||
function offsetMinutes(date) {
|
|
||||||
const name = offsetFmt.formatToParts(date).find((x) => x.type === 'timeZoneName')?.value || 'GMT';
|
|
||||||
const m = /GMT([+-])(\d{1,2})(?::(\d{2}))?/.exec(name);
|
|
||||||
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3] || 0)) : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Heure murale à Paris → instant. */
|
|
||||||
export function parisTime(year, month, day, hour, minute = 0) {
|
|
||||||
const guess = Date.UTC(year, month - 1, day, hour, minute);
|
|
||||||
let t = guess - offsetMinutes(new Date(guess)) * 60_000;
|
|
||||||
t = guess - offsetMinutes(new Date(t)) * 60_000; // 2e passe : correct autour du changement d'heure
|
|
||||||
return new Date(t);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Même heure murale, N jours plus tard. */
|
|
||||||
export function addParisDays(date, days) {
|
|
||||||
const p = parisParts(date);
|
|
||||||
const noon = parisTime(p.year, p.month, p.day, 12);
|
|
||||||
const q = parisParts(new Date(noon.getTime() + days * 86_400_000));
|
|
||||||
return { year: q.year, month: q.month, day: q.day };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Créneau de nuit : le Pi est au frais et le quota Claude n'est pas utilisé par toi
|
|
||||||
export const NIGHT = { start: 1, end: 6 };
|
|
||||||
|
|
||||||
/** Prochain début de créneau de nuit (ou maintenant si on y est déjà). */
|
|
||||||
export function nextNightSlot(date = new Date()) {
|
|
||||||
const p = parisParts(date);
|
|
||||||
if (p.hour >= NIGHT.start && p.hour < NIGHT.end) return date;
|
|
||||||
const d = p.hour < NIGHT.start ? p : addParisDays(date, 1);
|
|
||||||
return parisTime(d.year, d.month, d.day, NIGHT.start);
|
|
||||||
}
|
|
||||||
|
|
@ -69,23 +69,6 @@ Réponds UNIQUEMENT avec : {"subject":"...","body":"..."}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function followupTemplatePrompt({ profile, senderName }) {
|
|
||||||
return {
|
|
||||||
system: SYSTEM_FR,
|
|
||||||
prompt: `Rédige un mail de RELANCE B2B très court (60 mots max), envoyé dans le même fil que le premier mail resté sans réponse.
|
|
||||||
Produit : ${profile.resume}
|
|
||||||
Valeur : ${profile.proposition_valeur}
|
|
||||||
Ton : ${profile.ton || 'direct et chaleureux'}
|
|
||||||
Expéditeur : ${senderName || '{{expediteur}}'}
|
|
||||||
|
|
||||||
Règles : rappelle en une phrase l'intérêt pour {{entreprise}}, pose une question simple qui appelle une réponse courte (oui/non),
|
|
||||||
aucune culpabilisation ("je me permets de revenir vers vous" interdit), pas de proposition d'appel ni de visio.
|
|
||||||
Variables disponibles : {{entreprise}}, {{ville}}, {{expediteur}}.
|
|
||||||
Ne mets PAS de lien de désinscription (ajouté automatiquement).
|
|
||||||
Réponds UNIQUEMENT avec : {"body":"..."}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const LEVELS = {
|
export const LEVELS = {
|
||||||
rapide: { model: 'haiku', maxTurns: 12, files: 8 },
|
rapide: { model: 'haiku', maxTurns: 12, files: 8 },
|
||||||
normal: { model: 'sonnet', maxTurns: 20, files: 15 },
|
normal: { model: 'sonnet', maxTurns: 20, files: 15 },
|
||||||
|
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
// Rapport hebdo : lundi 8h (Paris), par mail + résumé Discord. Aucun token Claude.
|
|
||||||
import { now, getSetting, setSetting } from '../db.js';
|
|
||||||
import { abStats, globalSmtp } from '../projects.js';
|
|
||||||
import { createTransport } from './mailer.js';
|
|
||||||
import { notify } from './notify.js';
|
|
||||||
import { parisParts, parisTime } from './paris-time.js';
|
|
||||||
|
|
||||||
const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '-');
|
|
||||||
const usd = (n) => `${n.toFixed(2)} $`;
|
|
||||||
const day = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' });
|
|
||||||
|
|
||||||
export function weeklyStats(db, { at = now() } = {}) {
|
|
||||||
const from = at - 7 * 86400;
|
|
||||||
const one = (sql, ...a) => db.prepare(sql).get(...a).n;
|
|
||||||
const projects = db.prepare('SELECT id, name FROM projects ORDER BY name COLLATE NOCASE').all().map((p) => {
|
|
||||||
const sent = one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at > ?", p.id, from);
|
|
||||||
const ab = abStats(db, p.id);
|
|
||||||
return {
|
|
||||||
name: p.name,
|
|
||||||
found: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
|
|
||||||
sent,
|
|
||||||
followups: one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
|
|
||||||
replies: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
|
|
||||||
clients: one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
|
|
||||||
bounces: one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
|
|
||||||
WHERE x.project_id = ? AND b.reason = 'bounce' AND b.created_at > ?`, p.id, from),
|
|
||||||
cost: db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from).c,
|
|
||||||
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(from).c;
|
|
||||||
const sum = (k) => projects.reduce((t, p) => t + p[k], 0);
|
|
||||||
return { from, to: at, projects, totals: { found: sum('found'), sent: sum('sent'), followups: sum('followups'), replies: sum('replies'), cost } };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function weeklyText(st) {
|
|
||||||
const lines = [`AiTools · semaine du ${day(st.from)} au ${day(st.to)}`, ''];
|
|
||||||
const t = st.totals;
|
|
||||||
lines.push(`Total : ${t.found} prospect(s) trouvé(s), ${t.sent} mail(s) + ${t.followups} relance(s), ${t.replies} réponse(s) (${pct(t.replies, t.sent)}), IA ${usd(t.cost)}`, '');
|
|
||||||
for (const p of st.projects) {
|
|
||||||
const quiet = !p.found && !p.sent && !p.followups && !p.replies && !p.cost;
|
|
||||||
if (quiet) { lines.push(`${p.name} : rien cette semaine`, ''); continue; }
|
|
||||||
lines.push(p.name);
|
|
||||||
lines.push(` Prospects trouvés : ${p.found}`);
|
|
||||||
lines.push(` Mails envoyés : ${p.sent} (+ ${p.followups} relance(s))`);
|
|
||||||
lines.push(` Réponses : ${p.replies} (taux ${pct(p.replies, p.sent)})`);
|
|
||||||
lines.push(` Clients (total) : ${p.clients}`);
|
|
||||||
if (p.bounces) lines.push(` Adresses invalides: ${p.bounces}`);
|
|
||||||
if (p.bestSubject) lines.push(` Test A/B : l'objet ${p.bestSubject.variant} gagne (${pct(p.bestSubject.replied, p.bestSubject.sent)} de réponses)`);
|
|
||||||
lines.push(` Coût IA : ${usd(p.cost)}`, '');
|
|
||||||
}
|
|
||||||
return lines.join('\n').trimEnd() + '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Envoie le rapport (mail si SMTP global + adresse, Discord si webhook). Retourne les canaux utilisés. */
|
|
||||||
export async function sendWeeklyReport(app, { at = now() } = {}) {
|
|
||||||
const st = weeklyStats(app.db, { at });
|
|
||||||
const text = weeklyText(st);
|
|
||||||
const channels = [];
|
|
||||||
const to = getSetting(app.db, 'notify_email');
|
|
||||||
const smtp = globalSmtp(app);
|
|
||||||
if (to && smtp) {
|
|
||||||
const transport = (app.createTransport || createTransport)(smtp);
|
|
||||||
try {
|
|
||||||
await transport.sendMail({ from: smtp.fromEmail, to, subject: `[AiTools] Rapport du ${day(st.from)} au ${day(st.to)}`, text });
|
|
||||||
channels.push('mail');
|
|
||||||
} finally { transport.close(); }
|
|
||||||
}
|
|
||||||
const t = st.totals;
|
|
||||||
const ok = await notify(app, 'weekly', {
|
|
||||||
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
|
|
||||||
description: st.projects.filter((p) => p.sent || p.found || p.replies)
|
|
||||||
.map((p) => `**${p.name}** : ${p.found} trouvés · ${p.sent} envoyés · ${p.replies} réponses`).join('\n') || 'Rien cette semaine.',
|
|
||||||
fields: [
|
|
||||||
{ name: 'Réponses', value: `${t.replies} (${pct(t.replies, t.sent)})` },
|
|
||||||
{ name: 'Relances', value: String(t.followups) },
|
|
||||||
{ name: 'Coût IA', value: usd(t.cost) },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
if (ok) channels.push('discord');
|
|
||||||
return { channels, text };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Appelé toutes les 15 min : envoie une fois par semaine, le lundi à partir de 8h (Paris). */
|
|
||||||
export async function maybeSendWeekly(app, { date = new Date() } = {}) {
|
|
||||||
if (getSetting(app.db, 'weekly_report', '0') !== '1') return null;
|
|
||||||
const p = parisParts(date);
|
|
||||||
if (p.weekday !== 'Mon' || p.hour < 8) return null;
|
|
||||||
const mondayAt8 = Math.floor(parisTime(p.year, p.month, p.day, 8).getTime() / 1000);
|
|
||||||
if (Number(getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
|
||||||
const at = Math.floor(date.getTime() / 1000);
|
|
||||||
const r = await sendWeeklyReport(app, { at });
|
|
||||||
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
|
|
||||||
if (r.channels.length) setSetting(app.db, 'weekly_report_last', String(at));
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
// Tâches de fond légères (sans Claude), toutes les 15 min :
|
|
||||||
// 1. lecture des boîtes IMAP (réponses, bounces)
|
|
||||||
// 2. puis seulement ensuite, mise en file des relances dues
|
|
||||||
// 3. rapport hebdo le lundi à 8h
|
|
||||||
// 4. photo quotidienne des KPI business (pour les courbes)
|
|
||||||
import { checkInbox } from './inbox.js';
|
|
||||||
import { followupPlan } from './followup.js';
|
|
||||||
import { enqueue } from './jobs.js';
|
|
||||||
import { getProject } from '../projects.js';
|
|
||||||
import { maybeSendWeekly } from './report.js';
|
|
||||||
import { snapshotAll } from './metrics.js';
|
|
||||||
|
|
||||||
export class Scheduler {
|
|
||||||
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
|
|
||||||
this.app = app;
|
|
||||||
this.everyMs = everyMs;
|
|
||||||
this.log = log;
|
|
||||||
this.running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
start() {
|
|
||||||
this.timer = setInterval(() => this.tick(), this.everyMs);
|
|
||||||
this.timer.unref();
|
|
||||||
// Premier passage peu après le démarrage
|
|
||||||
this.first = setTimeout(() => this.tick(), 60_000);
|
|
||||||
this.first.unref();
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() { clearInterval(this.timer); clearTimeout(this.first); }
|
|
||||||
|
|
||||||
async tick() {
|
|
||||||
if (this.running) return;
|
|
||||||
this.running = true;
|
|
||||||
try {
|
|
||||||
const projects = this.app.db.prepare('SELECT id FROM projects WHERE imap_enc IS NOT NULL').all();
|
|
||||||
for (const { id } of projects) {
|
|
||||||
try { await checkInbox(this.app, id); }
|
|
||||||
catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
|
|
||||||
}
|
|
||||||
this.queueFollowups();
|
|
||||||
try { await maybeSendWeekly(this.app); }
|
|
||||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
|
||||||
await snapshotAll(this.app, { log: this.log });
|
|
||||||
} finally { this.running = false; }
|
|
||||||
}
|
|
||||||
|
|
||||||
queueFollowups(opts) {
|
|
||||||
const { db } = this.app;
|
|
||||||
const queued = [];
|
|
||||||
for (const { id } of db.prepare('SELECT id FROM projects WHERE followup_enabled = 1').all()) {
|
|
||||||
const plan = followupPlan(db, getProject(this.app, id), opts);
|
|
||||||
if (plan.ready) queued.push({ id, ...enqueue(db, { projectId: id, type: 'followup', params: { count: plan.due } }) });
|
|
||||||
}
|
|
||||||
return queued;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
101
src/views.js
101
src/views.js
|
|
@ -1,5 +1,4 @@
|
||||||
import { esc } from './http.js';
|
import { esc } from './http.js';
|
||||||
import { STATUSES } from './services/crm.js';
|
|
||||||
|
|
||||||
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
||||||
|
|
||||||
|
|
@ -57,7 +56,7 @@ function targetForm(p) {
|
||||||
</form>`;
|
</form>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function configForms(p, smtp, dbCfg, imap) {
|
function configForms(p, smtp, dbCfg) {
|
||||||
return `<details class="config"><summary>Configuration du projet</summary>
|
return `<details class="config"><summary>Configuration du projet</summary>
|
||||||
<form data-action="smtp" data-id="${p.id}" class="cfg">
|
<form data-action="smtp" data-id="${p.id}" class="cfg">
|
||||||
<h4>SMTP d'envoi</h4>
|
<h4>SMTP d'envoi</h4>
|
||||||
|
|
@ -72,17 +71,6 @@ function configForms(p, smtp, dbCfg, imap) {
|
||||||
<label>Plafond mails / 24 h (max 200)<input name="dailyCap" type="number" min="1" max="200" value="${p.dailyMailCap}"></label>
|
<label>Plafond mails / 24 h (max 200)<input name="dailyCap" type="number" min="1" max="200" value="${p.dailyMailCap}"></label>
|
||||||
<button class="btn">Enregistrer SMTP</button>
|
<button class="btn">Enregistrer SMTP</button>
|
||||||
</form>
|
</form>
|
||||||
<form data-action="imap" data-id="${p.id}" class="cfg">
|
|
||||||
<h4>Boîte de réception (IMAP)</h4>
|
|
||||||
<p class="muted small">Sert à détecter les réponses et les adresses invalides. Utilisateur vide = mêmes identifiants que le SMTP. Hôte vide = désactivé.</p>
|
|
||||||
<div class="grid3">
|
|
||||||
<label>Hôte IMAP<input name="host" value="${esc(imap.host)}" placeholder="imap.mondomaine.fr"></label>
|
|
||||||
<label>Port<input name="port" type="number" value="${esc(imap.port || 993)}"></label>
|
|
||||||
<label>Utilisateur<input name="user" value="${esc(imap.user)}" placeholder="identique au SMTP" autocomplete="off"></label>
|
|
||||||
<label>Mot de passe<input name="pass" type="password" placeholder="${imap.passSet ? '•••••• (inchangé)' : 'identique au SMTP'}" autocomplete="new-password"></label>
|
|
||||||
</div>
|
|
||||||
<button class="btn">Enregistrer et tester</button>
|
|
||||||
</form>
|
|
||||||
<form data-action="db" data-id="${p.id}" class="cfg">
|
<form data-action="db" data-id="${p.id}" class="cfg">
|
||||||
<h4>Base de données (récapitulatif)</h4>
|
<h4>Base de données (récapitulatif)</h4>
|
||||||
<p class="muted small">Utilise un compte en lecture seule. Chaque requête doit renvoyer un seul nombre.</p>
|
<p class="muted small">Utilise un compte en lecture seule. Chaque requête doit renvoyer un seul nombre.</p>
|
||||||
|
|
@ -106,25 +94,7 @@ function configForms(p, smtp, dbCfg, imap) {
|
||||||
</details>`;
|
</details>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function templateForm(p, kind) {
|
function projectItem(p, smtp, dbCfg) {
|
||||||
const initial = kind === 'initial';
|
|
||||||
const job = initial ? 'template' : 'followup_template';
|
|
||||||
return `<form data-action="template" data-kind="${kind}" data-id="${p.id}" class="tpl">
|
|
||||||
<div class="row"><h4>${initial ? 'Modèle de mail' : 'Modèle de relance'} <span data-tpl-state></span></h4>
|
|
||||||
<button type="button" class="btn small" data-run="${job}" data-id="${p.id}">Générer avec l'IA</button></div>
|
|
||||||
<p class="muted small">Variables : {{entreprise}} {{ville}}${initial ? ' {{accroche}}' : ''} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.</p>
|
|
||||||
<label>Objet${initial ? '' : ' <span class="muted small">(vide = « Re: » + objet du premier mail, dans le même fil)</span>'}<input name="subject"></label>
|
|
||||||
${initial ? '<label>Objet B <span class="muted small">(optionnel : test A/B, les envois alternent entre les deux objets)</span><input name="subjectB"></label>' : ''}
|
|
||||||
<label>Corps<textarea name="body" rows="${initial ? 9 : 5}"></textarea></label>
|
|
||||||
<div class="row">
|
|
||||||
<button class="btn" name="mode" value="save">Enregistrer</button>
|
|
||||||
<button class="btn primary" name="mode" value="validate">Valider le modèle</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
<div class="job" data-job="${job}"></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function projectItem(p, smtp, dbCfg, imap) {
|
|
||||||
const profile = p.profile;
|
const profile = p.profile;
|
||||||
return `<details class="project card" data-id="${p.id}">
|
return `<details class="project card" data-id="${p.id}">
|
||||||
<summary><span class="pname">${esc(p.name)}</span><span class="pstate" data-state></span></summary>
|
<summary><span class="pname">${esc(p.name)}</span><span class="pstate" data-state></span></summary>
|
||||||
|
|
@ -152,12 +122,22 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
<section class="panel" data-panel-body="prospect" hidden>
|
<section class="panel" data-panel-body="prospect" hidden>
|
||||||
<form data-action="prospect" data-id="${p.id}" class="inline">
|
<form data-action="prospect" data-id="${p.id}" class="inline">
|
||||||
<label>Prospects à chercher<input name="count" type="number" min="1" max="50" value="10"></label>
|
<label>Prospects à chercher<input name="count" type="number" min="1" max="50" value="10"></label>
|
||||||
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
|
|
||||||
<button class="btn primary">Lancer la recherche</button>
|
<button class="btn primary">Lancer la recherche</button>
|
||||||
</form>
|
</form>
|
||||||
<div class="job" data-job="prospect"></div>
|
<div class="job" data-job="prospect"></div>
|
||||||
|
|
||||||
${templateForm(p, 'initial')}
|
<form data-action="template" data-id="${p.id}" class="tpl">
|
||||||
|
<div class="row"><h4>Modèle de mail <span data-tpl-state></span></h4>
|
||||||
|
<button type="button" class="btn small" data-run="template" data-id="${p.id}">Générer avec l'IA</button></div>
|
||||||
|
<p class="muted small">Variables : {{entreprise}} {{ville}} {{accroche}} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.</p>
|
||||||
|
<label>Objet<input name="subject"></label>
|
||||||
|
<label>Corps<textarea name="body" rows="9"></textarea></label>
|
||||||
|
<div class="row">
|
||||||
|
<button class="btn" name="mode" value="save">Enregistrer</button>
|
||||||
|
<button class="btn primary" name="mode" value="validate">Valider le modèle</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div class="job" data-job="template"></div>
|
||||||
|
|
||||||
<form data-action="send" data-id="${p.id}" class="inline send">
|
<form data-action="send" data-id="${p.id}" class="inline send">
|
||||||
<label>Mails à envoyer<input name="count" type="number" min="1" value="10"></label>
|
<label>Mails à envoyer<input name="count" type="number" min="1" value="10"></label>
|
||||||
|
|
@ -165,36 +145,9 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
<span class="muted small" data-send-info></span>
|
<span class="muted small" data-send-info></span>
|
||||||
</form>
|
</form>
|
||||||
<div class="job" data-job="send"></div>
|
<div class="job" data-job="send"></div>
|
||||||
<p class="inbox small" data-inbox></p>
|
|
||||||
|
|
||||||
<section class="followup">
|
|
||||||
<h4>Relance automatique</h4>
|
|
||||||
<form data-action="followup" data-id="${p.id}" class="inline">
|
|
||||||
<label class="check"><input type="checkbox" name="enabled" ${p.followupEnabled ? 'checked' : ''}> Relancer une fois les prospects sans réponse</label>
|
|
||||||
<label>Après (jours)<input name="days" type="number" min="2" max="30" value="${p.followupDays}"></label>
|
|
||||||
<button class="btn">Enregistrer</button>
|
|
||||||
</form>
|
|
||||||
<p class="muted small" data-followup-info></p>
|
|
||||||
${templateForm(p, 'followup')}
|
|
||||||
<div class="job" data-job="followup"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<details class="prospects"><summary>Prospects <span data-count></span></summary>
|
<details class="prospects"><summary>Prospects <span data-count></span></summary>
|
||||||
<form class="pfilters" data-filters>
|
|
||||||
<input type="search" name="q" placeholder="Rechercher : entreprise, email, ville, secteur" aria-label="Rechercher">
|
|
||||||
<select name="status" aria-label="Statut"><option value="">Tous les statuts</option>${Object.entries(STATUSES).map(([k, l]) => `<option value="${k}">${l}</option>`).join('')}</select>
|
|
||||||
<select name="minScore" aria-label="Score minimum"><option value="0">Tous les scores</option><option value="5">Score ≥ 5</option><option value="7">Score ≥ 7</option><option value="9">Score ≥ 9</option></select>
|
|
||||||
<label class="check todo"><input type="checkbox" name="todo" value="1"> Actions à faire</label>
|
|
||||||
<select name="sort" aria-label="Tri"><option value="score">Tri : score</option><option value="recent">Plus récents</option><option value="contacted">Dernier contact</option><option value="company">Entreprise A → Z</option></select>
|
|
||||||
</form>
|
|
||||||
<div class="row csv">
|
|
||||||
<a class="btn small" data-export href="/api/projects/${p.id}/prospects.csv" download>Exporter (CSV)</a>
|
|
||||||
<label class="btn small file">Importer un CSV<input type="file" accept=".csv,text/csv" data-import="${p.id}" hidden></label>
|
|
||||||
<span class="muted small">Colonnes reconnues : entreprise, email, site, ville, secteur, score, source, accroche.</span>
|
|
||||||
</div>
|
|
||||||
<div data-import-report></div>
|
|
||||||
<div data-prospects></div>
|
<div data-prospects></div>
|
||||||
<div class="pager" data-pager></div>
|
|
||||||
</details>
|
</details>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
@ -206,7 +159,6 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
<option value="normal" selected>Normal (Sonnet)</option>
|
<option value="normal" selected>Normal (Sonnet)</option>
|
||||||
<option value="approfondi">Approfondi (Opus, coûteux)</option>
|
<option value="approfondi">Approfondi (Opus, coûteux)</option>
|
||||||
</select></label>
|
</select></label>
|
||||||
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
|
|
||||||
<button class="btn primary">Chercher et envoyer par mail</button>
|
<button class="btn primary">Chercher et envoyer par mail</button>
|
||||||
</form>
|
</form>
|
||||||
<div class="job" data-job="evolution"></div>
|
<div class="job" data-job="evolution"></div>
|
||||||
|
|
@ -216,7 +168,7 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
<div class="recap" data-recap><p class="muted">Chargement…</p></div>
|
<div class="recap" data-recap><p class="muted">Chargement…</p></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
${configForms(p, smtp, dbCfg, imap)}
|
${configForms(p, smtp, dbCfg)}
|
||||||
</div>
|
</div>
|
||||||
</details>`;
|
</details>`;
|
||||||
}
|
}
|
||||||
|
|
@ -236,9 +188,8 @@ export function dashboardPage({ email, projects, forgejoHost }) {
|
||||||
<button class="btn primary">Créer et analyser</button>
|
<button class="btn primary">Créer et analyser</button>
|
||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
<dialog class="prospect-dialog" id="prospect-dialog" aria-label="Fiche prospect"><div data-dialog-body></div></dialog>
|
|
||||||
<div class="projects">
|
<div class="projects">
|
||||||
${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg, x.imap)).join('\n') : '<p class="muted">Aucun projet pour l\'instant.</p>'}
|
${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg)).join('\n') : '<p class="muted">Aucun projet pour l\'instant.</p>'}
|
||||||
</div>`,
|
</div>`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -250,9 +201,7 @@ export function settingsPage({ email, s, saved }) {
|
||||||
${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
||||||
<form method="post" action="/settings" class="card cfg">
|
<form method="post" action="/settings" class="card cfg">
|
||||||
<h4>Notifications</h4>
|
<h4>Notifications</h4>
|
||||||
<label>Email de réception (évolutions, rapport hebdo)<input name="notify_email" type="email" value="${esc(s.notify_email)}"></label>
|
<label>Email de réception (évolutions)<input name="notify_email" type="email" value="${esc(s.notify_email)}"></label>
|
||||||
<label class="check"><input type="checkbox" name="weekly_report" ${s.weekly_report ? 'checked' : ''}> Rapport hebdo le lundi à 8h (mail + Discord)</label>
|
|
||||||
<button type="button" class="btn small" data-report-send>Envoyer le rapport maintenant</button>
|
|
||||||
|
|
||||||
<h4>Forgejo</h4>
|
<h4>Forgejo</h4>
|
||||||
<div class="grid2">
|
<div class="grid2">
|
||||||
|
|
@ -269,28 +218,12 @@ ${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
||||||
<label>Expéditeur<input name="smtp_fromEmail" type="email" value="${esc(s.smtp.fromEmail)}"></label>
|
<label>Expéditeur<input name="smtp_fromEmail" type="email" value="${esc(s.smtp.fromEmail)}"></label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h4>Notifications Discord</h4>
|
|
||||||
<p class="muted small">Salon Discord › Modifier › Intégrations › Webhooks › Nouveau webhook › Copier l'URL.</p>
|
|
||||||
<label>URL du webhook<input name="discord_webhook" type="password" placeholder="${s.discord.set ? '•••••• (inchangé)' : 'https://discord.com/api/webhooks/…'}" autocomplete="off"></label>
|
|
||||||
${s.discord.set ? '<label class="check"><input type="checkbox" name="discord_remove"> Supprimer le webhook</label>' : ''}
|
|
||||||
<div class="checks">
|
|
||||||
${Object.entries(s.discord.all).map(([k, label]) => `<label class="check"><input type="checkbox" name="ev_${k}" ${s.discord.events.includes(k) ? 'checked' : ''}> ${esc(label)}</label>`).join('')}
|
|
||||||
</div>
|
|
||||||
${s.discord.set ? '<button type="button" class="btn small" data-notify-test>Envoyer une notification de test</button>' : ''}
|
|
||||||
|
|
||||||
<h4>Garde-fous</h4>
|
<h4>Garde-fous</h4>
|
||||||
<div class="grid3">
|
<div class="grid3">
|
||||||
<label>Plafond global mails / 24 h (max 300)<input name="global_daily_cap" type="number" min="1" max="300" value="${esc(s.global_daily_cap)}"></label>
|
<label>Plafond global mails / 24 h (max 300)<input name="global_daily_cap" type="number" min="1" max="300" value="${esc(s.global_daily_cap)}"></label>
|
||||||
<label>Délai min entre 2 mails (s)<input name="send_delay_min" type="number" min="5" value="${esc(s.send_delay_min)}"></label>
|
<label>Délai min entre 2 mails (s)<input name="send_delay_min" type="number" min="5" value="${esc(s.send_delay_min)}"></label>
|
||||||
<label>Délai max (s)<input name="send_delay_max" type="number" min="5" value="${esc(s.send_delay_max)}"></label>
|
<label>Délai max (s)<input name="send_delay_max" type="number" min="5" value="${esc(s.send_delay_max)}"></label>
|
||||||
</div>
|
</div>
|
||||||
<h4>Budget IA</h4>
|
|
||||||
<p class="muted small">En équivalent $ API remonté par Claude Code (ton abonnement Pro ne facture rien en plus : c'est un garde-fou pour ton quota).
|
|
||||||
Au-delà, les jobs IA attendent sans être perdus ; envois et relances continuent. Vide = pas de limite.</p>
|
|
||||||
<div class="grid2">
|
|
||||||
<label>Plafond sur 24 h glissantes ($)<input name="budget_day_usd" inputmode="decimal" value="${esc(s.budget_day_usd)}" placeholder="ex. 2"></label>
|
|
||||||
<label>Plafond sur 30 jours glissants ($)<input name="budget_month_usd" inputmode="decimal" value="${esc(s.budget_month_usd)}" placeholder="ex. 30"></label>
|
|
||||||
</div>
|
|
||||||
<label>Modèle pour la prospection<select name="prospect_model">
|
<label>Modèle pour la prospection<select name="prospect_model">
|
||||||
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
||||||
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
||||||
|
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
|
||||||
import { budgetState, AI_JOBS } from '../src/services/budget.js';
|
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
|
||||||
const spend = (usd, finishedAgo) => db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(1, 'prospect', 'done', ?, ?, ?)")
|
|
||||||
.run(usd, now() - finishedAgo - 60, now() - finishedAgo);
|
|
||||||
return { db, spend };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', () => {
|
|
||||||
const s = setup();
|
|
||||||
s.spend(1.5, 3600); // il y a 1 h
|
|
||||||
s.spend(10, 5 * 86400); // il y a 5 jours
|
|
||||||
s.spend(99, 40 * 86400); // hors fenêtre
|
|
||||||
let b = budgetState(s.db);
|
|
||||||
assert.equal(b.blocked, false);
|
|
||||||
assert.equal(b.day.used, 1.5);
|
|
||||||
assert.equal(b.month.used, 11.5);
|
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '2');
|
|
||||||
assert.equal(budgetState(s.db).blocked, false);
|
|
||||||
setSetting(s.db, 'budget_day_usd', '1.5');
|
|
||||||
b = budgetState(s.db);
|
|
||||||
assert.equal(b.blocked, true);
|
|
||||||
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '');
|
|
||||||
setSetting(s.db, 'budget_month_usd', '10');
|
|
||||||
assert.match(budgetState(s.db).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
|
||||||
assert.equal(budgetState(s.db, { at: now() + 30 * 86400 }).blocked, false, 'la fenêtre glisse');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('les envois et relances ne consomment pas d\'IA', () => {
|
|
||||||
for (const t of ['send', 'followup']) assert.equal(AI_JOBS.has(t), false);
|
|
||||||
for (const t of ['analyze', 'prospect', 'template', 'followup_template', 'evolution']) assert.equal(AI_JOBS.has(t), true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
|
||||||
const s = setup();
|
|
||||||
s.spend(5, 600);
|
|
||||||
setSetting(s.db, 'budget_day_usd', '3');
|
|
||||||
const ran = [];
|
|
||||||
const alerts = [];
|
|
||||||
const h = (name) => async () => { ran.push(name); };
|
|
||||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
|
||||||
thermalMax: 999, log: { error() {} },
|
|
||||||
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
|
||||||
});
|
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
|
||||||
enqueue(s.db, { projectId: 1, type: 'send' });
|
|
||||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
|
||||||
|
|
||||||
assert.equal(await w.tick(), true);
|
|
||||||
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
|
||||||
assert.equal(await w.tick(), false);
|
|
||||||
assert.equal(await w.tick(), false);
|
|
||||||
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
|
||||||
const jobs = latestJobs(s.db, 1);
|
|
||||||
assert.equal(jobs.prospect.status, 'queued');
|
|
||||||
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
|
||||||
await w.tick(); await w.tick();
|
|
||||||
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '1');
|
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
|
||||||
await w.tick();
|
|
||||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
|
||||||
});
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
||||||
import { openDb, getSetting, setSetting, MIGRATIONS } from '../src/db.js';
|
import { openDb, getSetting, setSetting } from '../src/db.js';
|
||||||
import { Router, esc } from '../src/http.js';
|
import { Router, esc } from '../src/http.js';
|
||||||
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
||||||
|
|
||||||
|
|
@ -27,38 +27,12 @@ test('token de désinscription', () => {
|
||||||
|
|
||||||
test('migrations et settings', () => {
|
test('migrations et settings', () => {
|
||||||
const db = openDb(':memory:');
|
const db = openDb(':memory:');
|
||||||
assert.equal(db.prepare('PRAGMA user_version').get().user_version, MIGRATIONS.length);
|
assert.equal(db.prepare('PRAGMA user_version').get().user_version, 1);
|
||||||
setSetting(db, 'a', '1'); setSetting(db, 'a', '2');
|
setSetting(db, 'a', '1'); setSetting(db, 'a', '2');
|
||||||
assert.equal(getSetting(db, 'a'), '2');
|
assert.equal(getSetting(db, 'a'), '2');
|
||||||
assert.equal(getSetting(db, 'nope', 'x'), 'x');
|
assert.equal(getSetting(db, 'nope', 'x'), 'x');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('migration 2 : les modèles existants deviennent des modèles "initial"', async () => {
|
|
||||||
const { DatabaseSync } = await import('node:sqlite');
|
|
||||||
const { mkdtempSync, rmSync } = await import('node:fs');
|
|
||||||
const { join } = await import('node:path');
|
|
||||||
const { tmpdir } = await import('node:os');
|
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
|
||||||
// Base en version 1 avec un modèle déjà validé
|
|
||||||
let raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
raw.exec(`CREATE TABLE projects (id INTEGER PRIMARY KEY);
|
|
||||||
CREATE TABLE mail_templates (project_id INTEGER PRIMARY KEY, subject TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', updated_at INTEGER NOT NULL);
|
|
||||||
INSERT INTO projects VALUES (1); INSERT INTO mail_templates VALUES (1, 'Objet', 'Corps', 'validated', 123);
|
|
||||||
PRAGMA user_version = 1;`);
|
|
||||||
raw.close();
|
|
||||||
// On rejoue seulement la migration 2 (les autres tables v1 sont absentes de ce mini-schéma)
|
|
||||||
raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
const { MIGRATIONS } = await import('../src/db.js');
|
|
||||||
raw.exec(MIGRATIONS[1]);
|
|
||||||
const t = raw.prepare('SELECT * FROM templates').get();
|
|
||||||
assert.equal(t.kind, 'initial');
|
|
||||||
assert.equal(t.subject, 'Objet');
|
|
||||||
assert.equal(t.status, 'validated');
|
|
||||||
assert.equal(raw.prepare("SELECT COUNT(*) n FROM sqlite_master WHERE name = 'mail_templates'").get().n, 0);
|
|
||||||
raw.close();
|
|
||||||
rmSync(dir, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
test('router avec paramètres', () => {
|
test('router avec paramètres', () => {
|
||||||
const r = new Router();
|
const r = new Router();
|
||||||
r.get('/projects/:id', () => 'ok');
|
r.get('/projects/:id', () => 'ok');
|
||||||
|
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { openDb, now } from '../src/db.js';
|
|
||||||
import { parseFilters, listProspects } from '../src/services/crm.js';
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
|
||||||
const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at)
|
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now());
|
|
||||||
add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
|
||||||
add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 });
|
|
||||||
add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 });
|
|
||||||
add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 });
|
|
||||||
add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 });
|
|
||||||
return db;
|
|
||||||
}
|
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
|
||||||
const names = (r) => r.rows.map((x) => x.company);
|
|
||||||
|
|
||||||
test('parseFilters ignore tout ce qui n\'est pas prévu', () => {
|
|
||||||
assert.deepEqual(f({ status: 'drop table', sort: 'id; --', minScore: '99', page: '-3', q: ' zen ' }),
|
|
||||||
{ q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
|
|
||||||
});
|
|
||||||
|
|
||||||
test('recherche, filtres, tri, et isolation entre projets', () => {
|
|
||||||
const db = setup();
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker');
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']);
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']);
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']);
|
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']);
|
|
||||||
assert.equal(listProspects(db, 2, f()).total, 1, 'jamais les prospects d\'un autre projet');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('pagination', () => {
|
|
||||||
const db = setup();
|
|
||||||
for (let i = 0; i < 250; i++) db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now());
|
|
||||||
const p1 = listProspects(db, 1, f());
|
|
||||||
assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 });
|
|
||||||
const p3 = listProspects(db, 1, f({ page: '3' }));
|
|
||||||
assert.equal(p3.rows.length, 54);
|
|
||||||
assert.equal(listProspects(db, 1, f({ page: '99' })).page, 3, 'page trop grande ramenée à la dernière');
|
|
||||||
const ids = new Set([...p1.rows, ...listProspects(db, 1, f({ page: '2' })).rows, ...p3.rows].map((x) => x.id));
|
|
||||||
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('fiche : historique des mails, réponse, opposition', async () => {
|
|
||||||
const { prospectDetail } = await import('../src/services/crm.js');
|
|
||||||
const db = setup();
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
|
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
|
|
||||||
const d = prospectDetail(db, 1);
|
|
||||||
assert.equal(d.prospect.company, 'Le Fournil');
|
|
||||||
assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
|
|
||||||
assert.equal(d.optOut.reason, 'unsubscribe');
|
|
||||||
assert.equal(prospectDetail(db, 999), null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
|
|
||||||
const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
|
|
||||||
const db = setup();
|
|
||||||
assert.equal(addNote(db, 1, ' '), null, 'note vide refusée');
|
|
||||||
const n1 = addNote(db, 1, 'A rappelé, intéressé');
|
|
||||||
const n2 = addNote(db, 1, 'x'.repeat(5000));
|
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].id, n2, 'plus récente en premier');
|
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].body.length, 2000, 'tronquée à 2000');
|
|
||||||
assert.equal(deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
|
|
||||||
assert.equal(deleteNote(db, 1, n1), true);
|
|
||||||
db.prepare('DELETE FROM prospects WHERE id = 1').run();
|
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospect_notes').get().n, 0, 'supprimées avec le prospect');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
|
|
||||||
const { setNextAction } = await import('../src/services/crm.js');
|
|
||||||
const db = setup();
|
|
||||||
assert.equal(setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
|
|
||||||
assert.equal(setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
|
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
|
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
|
|
||||||
const todo = (at) => names(listProspects(db, 1, { ...f({ todo: '1' }), at }));
|
|
||||||
assert.deepEqual(todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
|
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
|
|
||||||
assert.equal(setNextAction(db, 1, '', ''), null);
|
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
|
|
||||||
});
|
|
||||||
|
|
@ -1,80 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { openDb, now } from '../src/db.js';
|
|
||||||
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
|
||||||
import { parseFilters } from '../src/services/crm.js';
|
|
||||||
|
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
|
||||||
return db;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('cellules : guillemets, ; et retours à la ligne échappés, formules neutralisées', () => {
|
|
||||||
assert.equal(csvCell('Le "Fournil"; Rennes'), '"Le ""Fournil""; Rennes"');
|
|
||||||
assert.equal(csvCell('ligne 1\nligne 2'), '"ligne 1\nligne 2"');
|
|
||||||
assert.equal(csvCell('=HYPERLINK("http://evil","clic")'), '"\'=HYPERLINK(""http://evil"",""clic"")"');
|
|
||||||
for (const s of ['+33612', '-2+3', '@SUM(A1)']) assert.equal(csvCell(s)[0] === '"' ? csvCell(s)[1] : csvCell(s)[0], "'", s);
|
|
||||||
assert.equal(csvCell(null), '');
|
|
||||||
assert.equal(csvCell(7), '7');
|
|
||||||
assert.ok(toCsv(['a'], [['b']]).startsWith('a\r\nb'), 'BOM + CRLF pour Excel');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('parseCsv : séparateur détecté, guillemets, retours à la ligne, BOM, lignes vides', () => {
|
|
||||||
assert.deepEqual(parseCsv('a;b\r\n1;"x;y"\r\n\r\n2;"multi\nligne ""ok"""\n'), [['a', 'b'], ['1', 'x;y'], ['2', 'multi\nligne "ok"']]);
|
|
||||||
assert.deepEqual(parseCsv('email,company\nx@y.fr,"Dupont, fils"'), [['email', 'company'], ['x@y.fr', 'Dupont, fils']]);
|
|
||||||
assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', () => {
|
|
||||||
const db = setup();
|
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now());
|
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now());
|
|
||||||
const csv = [
|
|
||||||
'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine',
|
|
||||||
'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI',
|
|
||||||
';sans-nom@atelier.fr;javascript:alert(1);;;;',
|
|
||||||
'Déjà;deja@la.fr;;;;;',
|
|
||||||
'Doublon;contact@tybreizh.bzh;;;;;',
|
|
||||||
'Stop;stop@moi.fr;;;;;',
|
|
||||||
'Cassé;pas-un-email;;;;;',
|
|
||||||
"Formule;f@x.fr;;'=1+1;;99;",
|
|
||||||
].join('\r\n');
|
|
||||||
const r = importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 });
|
|
||||||
assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] });
|
|
||||||
const get = (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email);
|
|
||||||
const ty = get('contact@tybreizh.bzh');
|
|
||||||
assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']);
|
|
||||||
const sn = get('sans-nom@atelier.fr');
|
|
||||||
assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine');
|
|
||||||
assert.equal(sn.website, null, 'javascript: rejeté');
|
|
||||||
assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée');
|
|
||||||
assert.equal(get('f@x.fr').city, '=1+1', 'apostrophe de notre export retirée');
|
|
||||||
assert.equal(get('f@x.fr').score, 10, 'score borné');
|
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get().n, 0, 'rien dans l\'autre projet');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('import : erreurs claires', () => {
|
|
||||||
const db = setup();
|
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n'), /vide ou sans en-tête/);
|
|
||||||
assert.throws(() => importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/);
|
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('export puis réimport dans un autre projet : aller-retour sans perte', () => {
|
|
||||||
const db = setup();
|
|
||||||
db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at)
|
|
||||||
VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now());
|
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now());
|
|
||||||
const all = exportProspects(db, 1, f());
|
|
||||||
assert.match(all, /^Entreprise;Email;Site/);
|
|
||||||
assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/);
|
|
||||||
assert.match(all, /'=Votre pain/, 'formule neutralisée');
|
|
||||||
assert.match(all, /;A répondu;/, 'statut lisible');
|
|
||||||
assert.equal(exportProspects(db, 1, f({ minScore: '5' })).trim().split('\r\n').length, 2, 'l\'export suit les filtres');
|
|
||||||
const r = importProspects(db, 2, all);
|
|
||||||
assert.equal(r.imported, 2);
|
|
||||||
const back = db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get();
|
|
||||||
assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 });
|
|
||||||
});
|
|
||||||
1
test/fixtures/fake-claude.js
vendored
1
test/fixtures/fake-claude.js
vendored
|
|
@ -6,7 +6,6 @@ out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
||||||
if (prompt.includes('CRASH')) process.exit(3);
|
if (prompt.includes('CRASH')) process.exit(3);
|
||||||
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
||||||
const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
||||||
: prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}']
|
|
||||||
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
||||||
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
||||||
: prompt.includes('prospects')
|
: prompt.includes('prospects')
|
||||||
|
|
|
||||||
|
|
@ -1,169 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import { join, resolve } from 'node:path';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
|
||||||
import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js';
|
|
||||||
import { Worker, latestJobs } from '../src/services/jobs.js';
|
|
||||||
import { Scheduler } from '../src/services/scheduler.js';
|
|
||||||
import { makeHandlers } from '../src/handlers.js';
|
|
||||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
|
||||||
|
|
||||||
const paris = (iso) => new Date(iso); // ISO avec décalage explicite
|
|
||||||
|
|
||||||
test('heures ouvrées à Paris, y compris autour du passage à l\'heure d\'hiver', () => {
|
|
||||||
assert.equal(isBusinessHours(paris('2026-10-21T10:00:00+02:00')), true, 'mercredi 10h');
|
|
||||||
assert.equal(isBusinessHours(paris('2026-10-21T08:59:00+02:00')), false, 'mercredi 8h59');
|
|
||||||
assert.equal(isBusinessHours(paris('2026-10-21T18:00:00+02:00')), false, 'mercredi 18h');
|
|
||||||
assert.equal(isBusinessHours(paris('2026-10-24T11:00:00+02:00')), false, 'samedi');
|
|
||||||
assert.equal(isBusinessHours(paris('2026-10-25T11:00:00+01:00')), false, 'dimanche');
|
|
||||||
// Lundi 26/10 : Paris est passé en UTC+1 la veille
|
|
||||||
assert.equal(isBusinessHours(new Date('2026-10-26T08:30:00Z')), true, '8h30 UTC = 9h30 Paris');
|
|
||||||
assert.equal(isBusinessHours(new Date('2026-10-26T07:30:00Z')), false, '7h30 UTC = 8h30 Paris');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('objet de la relance : même fil par défaut', () => {
|
|
||||||
assert.equal(followupSubject({ subject: '' }, { subject: 'Une idée pour Fournil' }), 'Re: Une idée pour Fournil');
|
|
||||||
assert.equal(followupSubject({ subject: '' }, { subject: 'RE: déjà' }), 'RE: déjà');
|
|
||||||
assert.equal(followupSubject({ subject: 'Petite question' }, { subject: 'x' }), 'Petite question');
|
|
||||||
assert.equal(followupSubject({ subject: '' }, null), 'Re: notre échange');
|
|
||||||
});
|
|
||||||
|
|
||||||
const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000);
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const sentMails = [];
|
|
||||||
const app = {
|
|
||||||
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
|
||||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
|
||||||
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
|
||||||
};
|
|
||||||
setSetting(db, 'send_delay_min', '0');
|
|
||||||
setSetting(db, 'send_delay_max', '0');
|
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
|
||||||
saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
|
||||||
saveSecretConfig(app, id, 'imap_enc', { host: 'imap.x', port: 993 }, 'pass');
|
|
||||||
const inboxOk = (at = now(), extra = {}) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?')
|
|
||||||
.run(JSON.stringify({ lastOk: at, lastCheck: at, lastError: null, ...extra }), id);
|
|
||||||
inboxOk();
|
|
||||||
db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'Toujours partant, {{entreprise}} ?', 'validated', ?)").run(id, now());
|
|
||||||
db.prepare('UPDATE projects SET followup_enabled = 1, followup_days = 7 WHERE id = ?').run(id);
|
|
||||||
const add = (email, daysAgo, status = 'sent') => {
|
|
||||||
const t = now() - daysAgo * 86400;
|
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
|
||||||
.run(id, email.split('@')[1], email, status, t, t).lastInsertRowid);
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, message_id) VALUES(?, ?, ?, ?, 'initial', ?, ?)")
|
|
||||||
.run(id, pid, email, t, `Une idée pour ${email}`, `<orig-${pid}@codebzh.fr>`);
|
|
||||||
return pid;
|
|
||||||
};
|
|
||||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } });
|
|
||||||
const scheduler = new Scheduler(app, { log: { error() {} } });
|
|
||||||
return { tmp, db, app, id, add, inboxOk, worker, scheduler, sentMails };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
const due = s.add('contact@fournil.fr', 8);
|
|
||||||
const tooEarly = s.add('hello@zen.fr', 3);
|
|
||||||
const replied = s.add('jean@atelier.fr', 10, 'replied');
|
|
||||||
const blacklisted = s.add('stop@ferme.fr', 9);
|
|
||||||
s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now());
|
|
||||||
|
|
||||||
const plan = followupPlan(s.db, getProject(s.app, s.id), { date: new Date(WED_10H * 1000) });
|
|
||||||
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
|
||||||
|
|
||||||
const queued = s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
|
||||||
assert.equal(queued.length, 1);
|
|
||||||
await s.worker.tick();
|
|
||||||
const job = latestJobs(s.db, s.id).followup;
|
|
||||||
assert.equal(job.status, 'done', job.error);
|
|
||||||
assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 });
|
|
||||||
|
|
||||||
const m = s.sentMails[0];
|
|
||||||
assert.equal(m.to, 'contact@fournil.fr');
|
|
||||||
assert.equal(m.subject, 'Re: Une idée pour contact@fournil.fr');
|
|
||||||
assert.equal(m.inReplyTo, `<orig-${due}@codebzh.fr>`);
|
|
||||||
assert.match(m.text, /Toujours partant, fournil\.fr \?/);
|
|
||||||
assert.match(m.text, /Pour ne plus être contacté/);
|
|
||||||
const log = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all();
|
|
||||||
assert.equal(log.length, 1);
|
|
||||||
assert.equal(log[0].message_id, m.messageId);
|
|
||||||
|
|
||||||
const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid);
|
|
||||||
assert.ok(st(due).followup_at > 0);
|
|
||||||
assert.equal(st(due).status, 'sent', 'reste "contacté" : une réponse à la relance sera détectée normalement');
|
|
||||||
for (const pid of [tooEarly, replied, blacklisted]) assert.equal(st(pid).followup_at, null);
|
|
||||||
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 0, 'jamais 2 relances');
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end, désactivée, modèle non validé', () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
s.add('contact@fournil.fr', 8);
|
|
||||||
const plan = (o = {}) => followupPlan(s.db, getProject(s.app, s.id), o);
|
|
||||||
const sat = new Date('2026-10-24T11:00:00+02:00');
|
|
||||||
assert.equal(plan({ date: sat }).ready, false);
|
|
||||||
assert.equal(plan({ date: sat }).inHours, false);
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: sat }).length, 0, 'pas le week-end');
|
|
||||||
|
|
||||||
s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' });
|
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
|
||||||
s.inboxOk(now() - 3 * 3600);
|
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
|
||||||
s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id);
|
|
||||||
assert.deepEqual(plan().blockers, ['boîte IMAP à connecter']);
|
|
||||||
s.db.prepare("UPDATE templates SET status = 'draft' WHERE kind = 'followup'").run();
|
|
||||||
s.db.prepare('UPDATE projects SET followup_enabled = 0 WHERE id = ?').run(s.id);
|
|
||||||
assert.deepEqual(plan().blockers, ['relance désactivée', 'modèle de relance à valider', 'boîte IMAP à connecter']);
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('réponse arrivée entre la mise en file et l\'envoi : pas de relance', async () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1);
|
|
||||||
s.db.prepare("UPDATE prospects SET status = 'replied' WHERE id = ?").run(pid);
|
|
||||||
await s.worker.tick();
|
|
||||||
assert.equal(s.sentMails.length, 0);
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('relance en file mais heures ouvrées dépassées : reportée, rien n\'est envoyé', async () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
|
||||||
s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
|
||||||
s.app.isBusinessHours = () => false;
|
|
||||||
await s.worker.tick();
|
|
||||||
assert.equal(s.sentMails.length, 0);
|
|
||||||
assert.equal(latestJobs(s.db, s.id).followup.result.postponed, true);
|
|
||||||
assert.equal(s.db.prepare('SELECT followup_at FROM prospects WHERE id = ?').get(pid).followup_at, null, 'toujours due');
|
|
||||||
s.app.isBusinessHours = () => true;
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1, 'reprogrammée au créneau suivant');
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('génération du modèle de relance par l\'IA', async () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id);
|
|
||||||
s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run();
|
|
||||||
const { enqueue } = await import('../src/services/jobs.js');
|
|
||||||
enqueue(s.db, { projectId: s.id, type: 'followup_template' });
|
|
||||||
await s.worker.tick();
|
|
||||||
const job = latestJobs(s.db, s.id).followup_template;
|
|
||||||
assert.equal(job.status, 'done', job.error);
|
|
||||||
const t = s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get();
|
|
||||||
assert.equal(t.status, 'draft');
|
|
||||||
assert.equal(t.subject, '');
|
|
||||||
assert.match(t.body, /relance/i);
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, now } from '../src/db.js';
|
import { openDb, setSetting, now } from '../src/db.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats } from '../src/projects.js';
|
||||||
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
||||||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
|
|
@ -64,7 +64,7 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
const noValid = await run(s, 'send', { count: 5 });
|
const noValid = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noValid.error, /non validé/);
|
assert.match(noValid.error, /non validé/);
|
||||||
|
|
||||||
s.db.prepare("UPDATE templates SET status = 'validated' WHERE project_id = ? AND kind = 'initial'").run(s.id);
|
s.db.prepare("UPDATE mail_templates SET status = 'validated' WHERE project_id = ?").run(s.id);
|
||||||
const noSmtp = await run(s, 'send', { count: 5 });
|
const noSmtp = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noSmtp.error, /SMTP/);
|
assert.match(noSmtp.error, /SMTP/);
|
||||||
|
|
||||||
|
|
@ -97,14 +97,6 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('parseProspectLine ne garde que des URLs http(s)', () => {
|
|
||||||
const p = parseProspectLine('PROSPECT {"company":"X","email":"a@b.fr","website":"javascript:alert(1)","source":"https://ok.fr/contact"}');
|
|
||||||
assert.equal(p.website, null);
|
|
||||||
assert.equal(p.source, 'https://ok.fr/contact');
|
|
||||||
assert.equal(parseProspectLine('PROSPECT {"company":"X","email":"a@b.fr","website":"https://a.fr\\" onclick=x"}').website, null);
|
|
||||||
assert.equal(parseProspectLine('PROSPECT {"company":"X","email":"a@b.fr","website":"data:text/html,x"}').website, null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('parseProspectLine filtre les lignes invalides', () => {
|
test('parseProspectLine filtre les lignes invalides', () => {
|
||||||
assert.equal(parseProspectLine('blabla'), null);
|
assert.equal(parseProspectLine('blabla'), null);
|
||||||
assert.equal(parseProspectLine('PROSPECT {cassé'), null);
|
assert.equal(parseProspectLine('PROSPECT {cassé'), null);
|
||||||
|
|
@ -154,33 +146,3 @@ test('URL Git Forgejo', () => {
|
||||||
assert.throws(() => validateGitUrl('https://github.com/Tony/A.git', 'git.tony-averty.dev'), /doit être/);
|
assert.throws(() => validateGitUrl('https://github.com/Tony/A.git', 'git.tony-averty.dev'), /doit être/);
|
||||||
assert.throws(() => validateGitUrl('https://git.tony-averty.dev/a/b/c/d'), /Format/);
|
assert.throws(() => validateGitUrl('https://git.tony-averty.dev/a/b/c/d'), /Format/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
|
||||||
const s = setup();
|
|
||||||
try {
|
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
|
||||||
s.db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at)
|
|
||||||
VALUES(?, 'initial', 'Objet A {{entreprise}}', 'Objet B {{entreprise}}', 'Bonjour', 'validated', ?)`).run(s.id, now());
|
|
||||||
for (const n of [1, 2, 3, 4]) {
|
|
||||||
s.db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?)").run(s.id, `Ent${n}`, `c${n}@ent${n}.fr`, 10 - n, now());
|
|
||||||
}
|
|
||||||
const job = await run(s, 'send', { count: 4 });
|
|
||||||
assert.equal(job.status, 'done', job.error);
|
|
||||||
assert.deepEqual(s.sentMails.map((m) => m.subject), ['Objet A Ent1', 'Objet B Ent2', 'Objet A Ent3', 'Objet B Ent4']);
|
|
||||||
const logs = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'initial' ORDER BY id").all();
|
|
||||||
assert.equal(logs.length, 4);
|
|
||||||
for (const [i, l] of logs.entries()) {
|
|
||||||
assert.equal(l.message_id, s.sentMails[i].messageId);
|
|
||||||
assert.match(l.message_id, /^<[^@\s]+@codebzh\.fr>$/);
|
|
||||||
assert.equal(l.subject, s.sentMails[i].subject);
|
|
||||||
}
|
|
||||||
assert.equal(new Set(logs.map((l) => l.message_id)).size, 4, 'Message-ID uniques');
|
|
||||||
assert.deepEqual(s.db.prepare('SELECT variant FROM prospects ORDER BY id').all().map((r) => r.variant), ['A', 'B', 'A', 'B']);
|
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('sans objet B : tout part en A', () => {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -144,105 +144,3 @@ test('désinscription : GET confirme, POST blackliste, token forgé refusé', as
|
||||||
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressaisir', async () => {
|
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
|
||||||
app.db.prepare('UPDATE projects SET smtp_enc = ? WHERE id = ?').run('v1:AAAA:BBBB:CCCC', id);
|
|
||||||
const warn = console.warn; console.warn = () => {};
|
|
||||||
try {
|
|
||||||
let r = await get('/');
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
r = await get('/settings');
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
r = await get(`/api/projects/${id}/status`);
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
assert.equal((await r.json()).hasSmtp, true, 'la colonne existe toujours');
|
|
||||||
r = await post(`/api/projects/${id}/smtp`, { host: 'smtp.x', user: 'u', pass: 'nouveau', fromEmail: 'a@x.fr' });
|
|
||||||
assert.equal(r.status, 200, 'on peut ressaisir');
|
|
||||||
} finally { console.warn = warn; }
|
|
||||||
});
|
|
||||||
|
|
||||||
test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
|
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
|
||||||
const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
const job = app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
|
|
||||||
const { parisParts } = await import('../src/services/paris-time.js');
|
|
||||||
const p = parisParts(new Date(job.run_after * 1000));
|
|
||||||
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
|
|
||||||
const sys = await (await get('/api/system')).json();
|
|
||||||
assert.ok(job.run_after > now() ? sys.scheduled >= 1 : true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('réglages Discord : URL validée, chiffrée, événements enregistrés', async () => {
|
|
||||||
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
|
||||||
let r = await post('/settings', { ...base, discord_webhook: 'https://evil.com/api/webhooks/1/x' }, { form: true });
|
|
||||||
assert.equal(r.status, 400);
|
|
||||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
|
||||||
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
|
||||||
assert.equal(r.status, 303);
|
|
||||||
const enc = app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value;
|
|
||||||
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
|
||||||
assert.deepEqual(JSON.parse(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_events'").get().value), ['job_error', 'reply']);
|
|
||||||
r = await get('/settings');
|
|
||||||
const page = await r.text();
|
|
||||||
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
|
||||||
assert.match(page, /data-notify-test/);
|
|
||||||
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
|
||||||
assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
|
||||||
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
|
||||||
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
|
||||||
assert.equal(r.status, 303);
|
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
|
||||||
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
|
||||||
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
|
||||||
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
|
||||||
const sys = await (await get('/api/system')).json();
|
|
||||||
assert.equal(sys.budget.blocked, true);
|
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
|
||||||
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
|
||||||
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
|
||||||
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
test('fiche prospect : routes notes et prochaine action', async () => {
|
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
|
||||||
const id = Number(app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now()).lastInsertRowid);
|
|
||||||
let r = await post(`/api/prospects/${id}/notes`, { body: '<script>x</script>' });
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
r = await post(`/api/prospects/${id}/notes`, { body: '' });
|
|
||||||
assert.equal(r.status, 400);
|
|
||||||
r = await post(`/api/prospects/${id}/next`, { action: 'Rappeler', day: '2026-02-31' });
|
|
||||||
assert.equal(r.status, 400);
|
|
||||||
r = await post(`/api/prospects/${id}/next`, { action: 'Rappeler', day: '2026-11-03' });
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
const d = await (await get(`/api/prospects/${id}`)).json();
|
|
||||||
assert.equal(d.notes[0].body, '<script>x</script>', 'stocké brut, échappé à l\'affichage');
|
|
||||||
assert.equal(d.prospect.next_action, 'Rappeler');
|
|
||||||
r = await get('/api/prospects/999999');
|
|
||||||
assert.equal(r.status, 404);
|
|
||||||
r = await post(`/api/prospects/${id}/notes/${d.notes[0].id}/delete`, {}, { origin: 'https://evil.com' });
|
|
||||||
assert.equal(r.status, 403, 'CSRF bloqué');
|
|
||||||
const list = await (await get(`/api/projects/${pid}/prospects?q=atelier`)).json();
|
|
||||||
assert.equal(list.rows[0].next_action, 'Rappeler');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('CSV : export en pièce jointe, import via l\'API', async () => {
|
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
|
||||||
let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`);
|
|
||||||
assert.equal(r.status, 200);
|
|
||||||
assert.match(r.headers.get('content-type'), /text\/csv/);
|
|
||||||
assert.match(r.headers.get('content-disposition'), /attachment; filename="prospects-mep-\d{4}-\d{2}-\d{2}\.csv"/);
|
|
||||||
assert.match(await r.text(), /a@atelier\.fr/);
|
|
||||||
r = await post(`/api/projects/${pid}/prospects/import`, { csv: 'email;entreprise\nnouveau@client.fr;Nouveau' });
|
|
||||||
assert.deepEqual(await r.json(), { total: 1, imported: 1, duplicates: 0, blacklisted: 0, invalid: [] });
|
|
||||||
r = await post(`/api/projects/${pid}/prospects/import`, { csv: 'nom\nx' });
|
|
||||||
assert.equal(r.status, 400);
|
|
||||||
r = await fetch(`${base}/api/projects/${pid}/prospects.csv`);
|
|
||||||
assert.equal(r.status, 401, 'pas d\'export sans session');
|
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
// Test de bout en bout contre un vrai serveur IMAP. Ignoré par défaut.
|
|
||||||
// IMAP_TEST=host:port:user:pass npm test (la boîte doit contenir les 4 mails de test, cf. README)
|
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb, now } from '../src/db.js';
|
|
||||||
import { checkInbox } from '../src/services/inbox.js';
|
|
||||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
|
||||||
|
|
||||||
const live = process.env.IMAP_TEST;
|
|
||||||
|
|
||||||
test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => {
|
|
||||||
const [host, port, user, pass] = live.split(':');
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
|
||||||
saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
|
||||||
saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
|
||||||
const add = (email, msgId) => {
|
|
||||||
const pid = Number(db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)")
|
|
||||||
.run(id, email, now() - 86400 * 30, now()).lastInsertRowid);
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
|
||||||
.run(id, pid, email, now() - 86400 * 30, msgId);
|
|
||||||
return pid;
|
|
||||||
};
|
|
||||||
const fournil = add('contact@fournil.fr', '<m1@codebzh.fr>');
|
|
||||||
const zen = add('hello@zen.fr', '<m2@codebzh.fr>');
|
|
||||||
const ferme = add('contact@ferme.fr', '<m3@codebzh.fr>');
|
|
||||||
|
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 1, bounces: 1, ignored: 2 });
|
|
||||||
const st = (pid) => db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid).status;
|
|
||||||
assert.equal(st(fournil), 'replied');
|
|
||||||
assert.equal(st(zen), 'sent', 'une absence n\'est pas une réponse');
|
|
||||||
assert.equal(st(ferme), 'bounced');
|
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
|
||||||
assert.equal(getProject(app, id).inbox.lastUid, 4);
|
|
||||||
});
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb, now } from '../src/db.js';
|
|
||||||
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
|
||||||
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
|
||||||
const add = (company, email, msgId, status = 'sent') => {
|
|
||||||
const r = db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
|
||||||
.run(id, company, email, status, now(), now());
|
|
||||||
const pid = Number(r.lastInsertRowid);
|
|
||||||
if (msgId) {
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
|
||||||
.run(id, pid, email, now(), msgId);
|
|
||||||
}
|
|
||||||
return pid;
|
|
||||||
};
|
|
||||||
const status = (pid) => db.prepare('SELECT status, replied_at, reply_subject FROM prospects WHERE id = ?').get(pid);
|
|
||||||
return { db, app, id, add, status };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('parseHeaders déplie les en-têtes multi-lignes', () => {
|
|
||||||
const h = parseHeaders(Buffer.from('References: <a@x>\r\n <b@x>\r\nAuto-Submitted: auto-replied\r\n\r\n'));
|
|
||||||
assert.equal(h.references, '<a@x> <b@x>');
|
|
||||||
assert.equal(h['auto-submitted'], 'auto-replied');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('classify : réponse, réponse automatique, bounce', () => {
|
|
||||||
assert.equal(classify({ from: 'Jean@Fournil.fr', subject: 'Re: Idée', inReplyTo: '<1@codebzh.fr>' }).type, 'reply');
|
|
||||||
assert.deepEqual(classify({ from: 'a@b.fr', inReplyTo: '<1@x.fr>', headers: { references: '<0@x.fr> <1@x.fr>' } }).ids, ['<1@x.fr>', '<0@x.fr>']);
|
|
||||||
assert.equal(classify({ from: 'a@b.fr', subject: 'Absence du 12 au 20', headers: {} }).type, 'auto');
|
|
||||||
assert.equal(classify({ from: 'a@b.fr', subject: 'Re: x', headers: { 'auto-submitted': 'auto-replied' } }).type, 'auto');
|
|
||||||
assert.equal(classify({ from: 'a@b.fr', subject: 'Re: x', headers: { 'auto-submitted': 'no' } }).type, 'reply');
|
|
||||||
assert.equal(classify({ from: 'a@b.fr', subject: 'Out of Office: Re: x', headers: {} }).type, 'auto');
|
|
||||||
const b = classify({ from: 'MAILER-DAEMON@mx.orange.fr', subject: 'Undelivered Mail', body: 'Original-Message-ID: <42@codebzh.fr>' });
|
|
||||||
assert.equal(b.type, 'bounce');
|
|
||||||
assert.deepEqual(b.ids, ['<42@codebzh.fr>']);
|
|
||||||
assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', () => {
|
|
||||||
const s = setup();
|
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@codebzh.fr>');
|
|
||||||
const r = applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '<m1@codebzh.fr>' }]);
|
|
||||||
assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 });
|
|
||||||
assert.equal(s.status(p).status, 'replied');
|
|
||||||
assert.equal(s.status(p).reply_subject, 'Re: Une idée');
|
|
||||||
assert.ok(s.status(p).replied_at > 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('réponse rattachée par adresse puis par domaine pro', () => {
|
|
||||||
const s = setup();
|
|
||||||
const byMail = s.add('Zen', 'hello@zen.fr', null);
|
|
||||||
const byDomain = s.add('Atelier', 'contact@atelier-bois.fr', null);
|
|
||||||
const r = applyMessages(s.db, s.id, [
|
|
||||||
{ from: 'Hello@Zen.fr', subject: 'Intéressé' },
|
|
||||||
{ from: 'marc@atelier-bois.fr', subject: 'Re: votre message' },
|
|
||||||
]);
|
|
||||||
assert.equal(r.replies, 2);
|
|
||||||
assert.equal(s.status(byMail).status, 'replied');
|
|
||||||
assert.equal(s.status(byDomain).status, 'replied');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', () => {
|
|
||||||
const s = setup();
|
|
||||||
const g = s.add('Perso', 'boulanger.rennes@gmail.com', null);
|
|
||||||
const a1 = s.add('Groupe A', 'rennes@groupe.fr', null);
|
|
||||||
const a2 = s.add('Groupe B', 'nantes@groupe.fr', null);
|
|
||||||
const client = s.add('Déjà client', 'boss@client.fr', null, 'client');
|
|
||||||
const r = applyMessages(s.db, s.id, [
|
|
||||||
{ from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas
|
|
||||||
{ from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine
|
|
||||||
{ from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} },
|
|
||||||
{ from: 'boss@client.fr', subject: 'Merci' }, // déjà client : on ne rétrograde pas
|
|
||||||
{ from: 'inconnu@ailleurs.fr', subject: 'Spam' },
|
|
||||||
]);
|
|
||||||
assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 });
|
|
||||||
for (const pid of [g, a1, a2]) assert.equal(s.status(pid).status, 'sent');
|
|
||||||
assert.equal(s.status(client).status, 'client');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', () => {
|
|
||||||
const s = setup();
|
|
||||||
const p = s.add('Fermé', 'contact@ferme-definitivement.fr', '<m9@codebzh.fr>');
|
|
||||||
const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: <m9@codebzh.fr>\n550 user unknown' };
|
|
||||||
assert.equal(applyMessages(s.db, s.id, [bounce]).bounces, 1);
|
|
||||||
assert.equal(s.status(p).status, 'bounced');
|
|
||||||
assert.equal(s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get().reason, 'bounce');
|
|
||||||
assert.deepEqual(applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 });
|
|
||||||
});
|
|
||||||
|
|
||||||
test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
|
||||||
const smtp = { user: 'tony@x.fr', pass: 'smtp' };
|
|
||||||
assert.deepEqual(imapCredentials({ host: 'imap.x.fr' }, smtp), { host: 'imap.x.fr', port: 993, user: 'tony@x.fr', pass: 'smtp', reuseSmtp: true });
|
|
||||||
assert.equal(imapCredentials({ host: 'imap.x.fr', user: 'autre', pass: 'p', port: '143' }, smtp).port, 143);
|
|
||||||
assert.equal(imapCredentials({ host: '' }, smtp), null);
|
|
||||||
assert.equal(imapCredentials({ host: 'imap.x.fr' }, null), null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => {
|
|
||||||
const s = setup();
|
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass');
|
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@x.fr>');
|
|
||||||
const calls = [];
|
|
||||||
s.app.fetchInbox = async (creds, state) => {
|
|
||||||
calls.push({ creds, state });
|
|
||||||
if (calls.length === 3) throw Object.assign(new Error('x'), { responseText: 'AUTHENTICATIONFAILED' });
|
|
||||||
return calls.length === 1
|
|
||||||
? { uidValidity: '7', lastUid: 12, messages: [{ uid: 12, from: 'contact@fournil.fr', subject: 'Re: idée' }] }
|
|
||||||
: { uidValidity: '7', lastUid: 12, messages: [] };
|
|
||||||
};
|
|
||||||
assert.deepEqual(await checkInbox(s.app, s.id), { replies: 1, bounces: 0, ignored: 0 });
|
|
||||||
assert.equal(calls[0].creds.user, 'u', 'identifiants SMTP réutilisés');
|
|
||||||
await checkInbox(s.app, s.id);
|
|
||||||
assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 });
|
|
||||||
await assert.rejects(checkInbox(s.app, s.id), /AUTHENTICATIONFAILED/);
|
|
||||||
const inbox = getProject(s.app, s.id).inbox;
|
|
||||||
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
|
||||||
assert.equal(inbox.replies, 1);
|
|
||||||
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
|
||||||
assert.equal(s.status(p).status, 'replied');
|
|
||||||
});
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Tests des fonctions d'install.sh qui écrivent des fichiers (lancé en root dans un bac à sable).
|
|
||||||
# shellcheck disable=SC2034 # variables lues par les fonctions sourcées
|
|
||||||
set -uo pipefail
|
|
||||||
cd "$(dirname "$0")/.." || exit 1
|
|
||||||
# shellcheck source=../install.sh
|
|
||||||
source ./install.sh
|
|
||||||
set +e; trap - ERR
|
|
||||||
fail=0
|
|
||||||
check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fail=1; fi; }
|
|
||||||
|
|
||||||
APP_DIR_REAL=$APP_DIR
|
|
||||||
[[ $APP_DIR_REAL == /opt/aitools && ! -e /opt/aitools/.env ]] || { echo "Bac à sable requis (/opt/aitools vide)"; exit 1; }
|
|
||||||
id aitools &>/dev/null || useradd --system --create-home --shell /usr/sbin/nologin aitools
|
|
||||||
mkdir -p /opt/aitools
|
|
||||||
|
|
||||||
# 1. .env neuf
|
|
||||||
DOMAIN=ai.test.dev ALLOWED=a@b.fr GOOGLE_ID=cid GOOGLE_SECRET='s3c=ret' THERMAL=72 DATA_DIR=/srv/t/data KEEP_ENV=0
|
|
||||||
write_env
|
|
||||||
check ".env créé en 600 pour aitools" '[[ $(stat -c "%a %U" /opt/aitools/.env) == "600 aitools" ]]'
|
|
||||||
check "APP_URL" 'grep -qx "APP_URL=https://ai.test.dev" /opt/aitools/.env'
|
|
||||||
check "secret avec = conservé" 'grep -qx "GOOGLE_CLIENT_SECRET=s3c=ret" /opt/aitools/.env'
|
|
||||||
check "SECRET_KEY 64 hex" 'grep -qE "^SECRET_KEY=[0-9a-f]{64}$" /opt/aitools/.env'
|
|
||||||
check "config complète" 'config_complete'
|
|
||||||
check ".env lisible par node --env-file" 'node --env-file=/opt/aitools/.env -e "process.exit(process.env.THERMAL_MAX===\"72\"&&process.env.GOOGLE_CLIENT_SECRET===\"s3c=ret\"?0:1)"'
|
|
||||||
|
|
||||||
# 2. set_env : remplacement, ajout, caractères spéciaux
|
|
||||||
set_env CLAUDE_CODE_OAUTH_TOKEN 'sk-ant-oat01-a/b&c|d\e'
|
|
||||||
set_env THERMAL_MAX 70
|
|
||||||
check "token avec & | / \\ intact" 'grep -qxF "CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-a/b&c|d\e" /opt/aitools/.env'
|
|
||||||
check "remplacement sans doublon" '[[ $(grep -c "^THERMAL_MAX=" /opt/aitools/.env) == 1 ]] && grep -qx "THERMAL_MAX=70" /opt/aitools/.env'
|
|
||||||
check "droits conservés après set_env" '[[ $(stat -c "%a %U" /opt/aitools/.env) == "600 aitools" ]]'
|
|
||||||
|
|
||||||
# 3. config conservée + nouveau disque → migration détectée
|
|
||||||
set_env DATA_DIR ./data
|
|
||||||
check "old_data_dir relatif → absolu" '[[ $(old_data_dir) == /opt/aitools/data ]]'
|
|
||||||
KEEP_ENV=1 DATA_DIR=/srv/t/data
|
|
||||||
write_env
|
|
||||||
check "KEEP_ENV : DATA_DIR mis à jour, secret gardé" 'grep -qx "DATA_DIR=/srv/t/data" /opt/aitools/.env && grep -qx "GOOGLE_CLIENT_SECRET=s3c=ret" /opt/aitools/.env'
|
|
||||||
mkdir -p /opt/aitools/data/repos/1 /srv/t/data && echo db > /opt/aitools/data/aitools.sqlite && chown -R aitools: /opt/aitools/data
|
|
||||||
migrate_data /opt/aitools/data
|
|
||||||
check "migration des données" '[[ -f /srv/t/data/aitools.sqlite && -d /srv/t/data/repos/1 && $(stat -c %U /srv/t/data/aitools.sqlite) == aitools ]]'
|
|
||||||
|
|
||||||
# 4. Rendu de l'unit systemd
|
|
||||||
systemctl() { :; }
|
|
||||||
BACKUPS=1 BACKUP_DIR=/srv/t/backups
|
|
||||||
install_units
|
|
||||||
u=/etc/systemd/system/aitools.service
|
|
||||||
check "unit sans placeholder" '! grep -q "@" $u'
|
|
||||||
check "RequiresMountsFor = disque de données" 'grep -qx "RequiresMountsFor=/srv/t/data" $u'
|
|
||||||
check "ReadWritePaths" 'grep -qx "ReadWritePaths=/srv/t/data /home/aitools" $u'
|
|
||||||
check "timer de sauvegarde" 'grep -q "aitools-backup /srv/t/data/aitools.sqlite /srv/t/backups 14" /etc/systemd/system/aitools-backup.service'
|
|
||||||
|
|
||||||
# 5. Sauvegarde SQLite réelle
|
|
||||||
if command -v sqlite3 >/dev/null; then
|
|
||||||
rm -f /srv/t/data/aitools.sqlite
|
|
||||||
sqlite3 /srv/t/data/aitools.sqlite "PRAGMA journal_mode=WAL; CREATE TABLE t(x); INSERT INTO t VALUES (42);" >/dev/null
|
|
||||||
touch -d '20 days ago' /srv/t/backups/aitools-2000-01-01.sqlite 2>/dev/null || { mkdir -p /srv/t/backups; touch -d '20 days ago' /srv/t/backups/aitools-2000-01-01.sqlite; }
|
|
||||||
/usr/local/sbin/aitools-backup /srv/t/data/aitools.sqlite /srv/t/backups 14 >/dev/null
|
|
||||||
check "sauvegarde du jour lisible" '[[ $(sqlite3 /srv/t/backups/aitools-$(date +%F).sqlite "select x from t") == 42 ]]'
|
|
||||||
check "rotation > 14 jours" '[[ ! -e /srv/t/backups/aitools-2000-01-01.sqlite ]]'
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 6. Padding UTF-8
|
|
||||||
check "pad compte les caractères accentués" '[[ $(pad "Données" 10) == "Données " ]]'
|
|
||||||
|
|
||||||
exit $fail
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb } from '../src/db.js';
|
|
||||||
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
|
||||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
|
||||||
|
|
||||||
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
|
||||||
const id = createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
|
||||||
return { db, app, id };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('jour de Paris, même à 23h30 UTC', () => {
|
|
||||||
assert.equal(parisDay(new Date('2026-10-21T22:30:00Z')), '2026-10-22');
|
|
||||||
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', () => {
|
|
||||||
const s = setup();
|
|
||||||
const d = new Date('2026-10-21T10:00:00Z');
|
|
||||||
saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
|
||||||
saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
|
||||||
const rows = s.db.prepare('SELECT * FROM metrics_daily').all();
|
|
||||||
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
|
||||||
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
|
||||||
});
|
|
||||||
|
|
||||||
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
|
||||||
const s = setup();
|
|
||||||
const other = createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
|
||||||
createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
|
||||||
for (const id of [s.id, other]) saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
|
||||||
let calls = 0;
|
|
||||||
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
|
||||||
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
|
||||||
const date = new Date('2026-10-21T10:00:00Z');
|
|
||||||
assert.equal(await snapshotAll(s.app, { date, log }), 1);
|
|
||||||
assert.match(log.errors[0], /BDD injoignable/);
|
|
||||||
assert.equal(calls, 2, 'le projet sans BDD n\'est pas interrogé');
|
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
|
||||||
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
|
||||||
assert.equal(s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id).n, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', () => {
|
|
||||||
const s = setup();
|
|
||||||
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
|
||||||
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
|
||||||
assert.deepEqual(history(s.db, s.id, { days: 30, at }).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
|
||||||
assert.equal(history(s.db, s.id, { days: 90, at }).daily.length, 3);
|
|
||||||
|
|
||||||
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
|
||||||
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
|
||||||
log('2026-10-18T23:30:00+02:00'); // dimanche soir : semaine du 12
|
|
||||||
log('2026-10-20T10:00:00+02:00');
|
|
||||||
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
|
||||||
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
|
||||||
s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
|
||||||
const w = history(s.db, s.id, { days: 30, at }).weeks;
|
|
||||||
assert.equal(w.length, 5);
|
|
||||||
assert.equal(w.at(-1).start, '2026-10-19');
|
|
||||||
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
|
||||||
});
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
|
||||||
import { openDb, now } from '../src/db.js';
|
|
||||||
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
|
||||||
|
|
||||||
const iso = (d) => d.toISOString();
|
|
||||||
|
|
||||||
test('parisParts / parisTime : aller-retour, été comme hiver', () => {
|
|
||||||
assert.deepEqual(parisParts(new Date('2026-10-21T13:34:00Z')), { year: 2026, month: 10, day: 21, hour: 15, minute: 34, weekday: 'Wed' });
|
|
||||||
assert.equal(iso(parisTime(2026, 7, 14, 9)), '2026-07-14T07:00:00.000Z', 'été : UTC+2');
|
|
||||||
assert.equal(iso(parisTime(2026, 12, 25, 9)), '2026-12-25T08:00:00.000Z', 'hiver : UTC+1');
|
|
||||||
assert.deepEqual(addParisDays(new Date('2026-12-31T22:00:00Z'), 1), { year: 2027, month: 1, day: 1 }, 'passage d\'année');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('prochain créneau de nuit (1h-6h Paris)', () => {
|
|
||||||
const at = (s) => iso(nextNightSlot(new Date(s)));
|
|
||||||
assert.equal(at('2026-10-21T15:30:00+02:00'), '2026-10-21T23:00:00.000Z', 'après-midi → 1h le lendemain');
|
|
||||||
assert.equal(at('2026-10-22T00:30:00+02:00'), '2026-10-21T23:00:00.000Z', '0h30 → 1h le même jour');
|
|
||||||
assert.equal(at('2026-10-22T03:00:00+02:00'), '2026-10-22T01:00:00.000Z', 'déjà dans le créneau → tout de suite');
|
|
||||||
assert.equal(at('2026-10-22T06:00:00+02:00'), '2026-10-22T23:00:00.000Z', '6h pile → nuit suivante');
|
|
||||||
assert.equal(at('2026-10-24T22:00:00+02:00'), '2026-10-24T23:00:00.000Z', 'nuit du passage à l\'heure d\'hiver');
|
|
||||||
assert.equal(at('2027-03-27T20:00:00+01:00'), '2027-03-28T00:00:00.000Z', 'nuit du passage à l\'heure d\'été');
|
|
||||||
assert.equal(at('2026-12-31T23:59:00+01:00'), '2027-01-01T00:00:00.000Z', 'Saint-Sylvestre');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('le worker ne démarre pas un job programmé avant son heure', async () => {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
let clock = now();
|
|
||||||
const ran = [];
|
|
||||||
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
|
||||||
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
|
||||||
enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
|
||||||
enqueue(db, { projectId: 1, type: 'evolution' });
|
|
||||||
assert.equal(await w.tick(), true);
|
|
||||||
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
|
||||||
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
|
||||||
assert.equal(latestJobs(db, 1).prospect.runAfter, clock + 3600);
|
|
||||||
clock += 3601;
|
|
||||||
assert.equal(await w.tick(), true);
|
|
||||||
assert.deepEqual(ran, ['evolution', 'prospect']);
|
|
||||||
});
|
|
||||||
|
|
@ -1,104 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
|
||||||
import { encrypt } from '../src/crypto.js';
|
|
||||||
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
|
||||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
|
||||||
import { checkInbox } from '../src/services/inbox.js';
|
|
||||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
|
||||||
|
|
||||||
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
|
||||||
|
|
||||||
function setup({ events } = {}) {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const sent = [];
|
|
||||||
const app = {
|
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
|
||||||
fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; },
|
|
||||||
};
|
|
||||||
setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
|
||||||
if (events) setSetting(db, 'discord_events', JSON.stringify(events));
|
|
||||||
const id = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
|
||||||
return { db, app, sent, id };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('validation stricte de l\'URL de webhook', () => {
|
|
||||||
assert.ok(WEBHOOK_RE.test(HOOK));
|
|
||||||
assert.ok(WEBHOOK_RE.test(HOOK.replace('discord.com', 'discordapp.com')));
|
|
||||||
for (const bad of ['http://discord.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz', 'https://evil.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz',
|
|
||||||
'https://discord.com.evil.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz', `${HOOK}?wait=true`, 'https://discord.com/api/webhooks/1/a']) {
|
|
||||||
assert.ok(!WEBHOOK_RE.test(bad), bad);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('notif : forme du message, aucune mention possible', async () => {
|
|
||||||
const s = setup();
|
|
||||||
assert.equal(await notify(s.app, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
|
||||||
const b = s.sent[0].body;
|
|
||||||
assert.equal(s.sent[0].url, HOOK);
|
|
||||||
assert.deepEqual(b.allowed_mentions, { parse: [] });
|
|
||||||
assert.equal(b.embeds[0].title, '@everyone Boulangerie');
|
|
||||||
assert.equal(b.embeds[0].color, 0x15803d);
|
|
||||||
assert.equal(b.embeds[0].fields[0].value, '-');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
|
||||||
const s = setup({ events: ['job_error'] });
|
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }), false);
|
|
||||||
assert.equal(s.sent.length, 0);
|
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
|
||||||
const warn = console.warn; console.warn = () => {};
|
|
||||||
try {
|
|
||||||
s.app.fetch = async () => ({ ok: false, status: 404 });
|
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
|
||||||
s.app.fetch = async () => { throw new Error('réseau'); };
|
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
|
||||||
} finally { console.warn = warn; }
|
|
||||||
setSetting(s.db, 'discord_webhook_enc', null);
|
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
|
||||||
const s = setup();
|
|
||||||
const job = (type) => ({ type, project_id: s.id });
|
|
||||||
await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } });
|
|
||||||
await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' });
|
|
||||||
await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 3, failed: 0 } });
|
|
||||||
await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 0, postponed: true } });
|
|
||||||
await notifyJob(s.app, job('template'), { status: 'done', result: {} });
|
|
||||||
assert.deepEqual(s.sent.map((x) => x.body.embeds[0].title), [
|
|
||||||
'MonEspacePro · Recherche de prospects terminée',
|
|
||||||
'MonEspacePro · Envoi en échec',
|
|
||||||
'MonEspacePro · Relances envoyées',
|
|
||||||
]);
|
|
||||||
assert.match(s.sent[0].body.embeds[0].description, /7 nouveau\(x\) prospect\(s\) sur 10/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => {
|
|
||||||
const s = setup();
|
|
||||||
const seen = [];
|
|
||||||
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
|
||||||
thermalMax: 999, log: { error() {} },
|
|
||||||
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
|
||||||
});
|
|
||||||
enqueue(s.db, { projectId: s.id, type: 'prospect' });
|
|
||||||
enqueue(s.db, { projectId: s.id, type: 'evolution' });
|
|
||||||
await w.tick(); await w.tick();
|
|
||||||
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
|
||||||
assert.equal(s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get().n, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('nouvelles réponses détectées → une notif avec les entreprises', async () => {
|
|
||||||
const s = setup();
|
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
|
||||||
s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now());
|
|
||||||
s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] });
|
|
||||||
await checkInbox(s.app, s.id);
|
|
||||||
assert.equal(s.sent.length, 1);
|
|
||||||
assert.equal(s.sent[0].body.embeds[0].title, 'MonEspacePro · 1 réponse(s) de prospect');
|
|
||||||
assert.match(s.sent[0].body.embeds[0].description, /\*\*Le Fournil\*\* \(contact@fournil\.fr\) : Re: idée/);
|
|
||||||
await checkInbox(s.app, s.id);
|
|
||||||
assert.equal(s.sent.length, 1, 'pas de notif quand rien de neuf');
|
|
||||||
});
|
|
||||||
|
|
@ -1,80 +0,0 @@
|
||||||
import { test } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { randomBytes } from 'node:crypto';
|
|
||||||
import { openDb, now, setSetting, getSetting } from '../src/db.js';
|
|
||||||
import { encrypt, encryptJson } from '../src/crypto.js';
|
|
||||||
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
|
||||||
import { createProject } from '../src/projects.js';
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const db = openDb(':memory:');
|
|
||||||
const mails = [], hooks = [];
|
|
||||||
const app = {
|
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
|
||||||
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
|
||||||
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
|
||||||
};
|
|
||||||
const mep = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
|
||||||
createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
|
||||||
const t = now() - 2 * 86400;
|
|
||||||
for (let i = 0; i < 20; i++) {
|
|
||||||
const v = i % 2 ? 'B' : 'A';
|
|
||||||
const replied = (v === 'B' && i < 10) || i === 0;
|
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
|
|
||||||
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t).lastInsertRowid);
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
|
|
||||||
}
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
|
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
|
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 0.42, ?, ?)").run(mep, t, t);
|
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 9, ?, ?)").run(mep, t - 30 * 86400, t - 30 * 86400);
|
|
||||||
return { db, app, mails, hooks };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('statistiques de la semaine', () => {
|
|
||||||
const s = setup();
|
|
||||||
const st = weeklyStats(s.db);
|
|
||||||
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
|
||||||
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
|
|
||||||
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
|
|
||||||
});
|
|
||||||
assert.equal(st.totals.cost, 0.42, 'le job d\'il y a 30 jours ne compte pas');
|
|
||||||
const txt = weeklyText(st);
|
|
||||||
assert.match(txt, /^AiTools · semaine du \d\d\/\d\d au \d\d\/\d\d/);
|
|
||||||
assert.match(txt, /Réponses {10}: 6 \(taux 30 %\)/);
|
|
||||||
assert.match(txt, /l'objet B gagne \(50 % de réponses\)/);
|
|
||||||
assert.match(txt, /GoSortir : rien cette semaine/);
|
|
||||||
});
|
|
||||||
|
|
||||||
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
|
|
||||||
|
|
||||||
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
|
|
||||||
const s = setup();
|
|
||||||
setSetting(s.db, 'notify_email', 'moi@x.fr');
|
|
||||||
setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
|
||||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
|
||||||
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: MON_0830 }), null, 'désactivé par défaut');
|
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
|
||||||
|
|
||||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
|
||||||
assert.deepEqual(r.channels, ['mail', 'discord']);
|
|
||||||
assert.equal(s.mails[0].to, 'moi@x.fr');
|
|
||||||
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
|
|
||||||
assert.match(s.hooks[0].embeds[0].description, /\*\*MonEspacePro\*\* : 20 trouvés · 20 envoyés · 6 réponses/);
|
|
||||||
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
|
|
||||||
assert.notEqual(await maybeSendWeekly(s.app, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
|
|
||||||
assert.equal(s.mails.length, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
|
||||||
const s = setup();
|
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
|
||||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
|
||||||
assert.deepEqual(r.channels, []);
|
|
||||||
assert.equal(getSetting(s.db, 'weekly_report_last'), null);
|
|
||||||
});
|
|
||||||
Loading…
Reference in a new issue