@mostajs/commandes 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog — @mostajs/commandes
2
+
3
+ **Auteur** : Dr Hamid MADANI <drmdh@msn.com>
4
+
5
+ ## 0.1.0 — 29/11/2026
6
+
7
+ Première version (proposition P4 de [Produit] e-commerce, validée le 29/11 ; DPIA #16 ; maquettes P1-P6, F1-F6).
8
+ - Commande sans compte ni carte, « à confirmer », payée à la livraison ; liste blanche des champs ; prix et livraison figés ; totaux calculés.
9
+ - Automate par @mostajs/statemachine : transitions permises seulement, permission injectée, journal de chaque transition.
10
+ - Contrôles : mobile algérien normalisé, doublon sur 24 h, liste noire propre à la boutique, score et signaux nommés, seuil réglable.
11
+ - File de confirmation : sans réponse → rappel à 120 min, au 3e essai « injoignable » ; rappels datés ; tour de rôle, réattribution, charge ; compteurs et taux du jour.
12
+ - Quota : hors quota créée et visible, non confirmable jusqu'au changement de forfait ou au mois suivant.
13
+ - Stock réservé à la confirmation, libéré à l'annulation (port).
14
+ - Commandes abandonnées (brouillons) : rien sans téléphone valide, jamais l'adresse, 7 jours, effacées à l'envoi.
15
+ - Conservation bornée : anonymisation après 24 mois ; effacement à la demande, hors livraison ; événements sans donnée de l'acheteur ; export CSV sans formule.
16
+ - 33 essais, 14 sabotages.
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (c) 2026 Dr Hamid MADANI <drmdh@msn.com>
5
+
6
+ This program is free software: you can redistribute it and/or modify
7
+ it under the terms of the GNU Affero General Public License as published by
8
+ the Free Software Foundation, either version 3 of the License, or
9
+ (at your option) any later version.
10
+
11
+ This program is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU Affero General Public License for more details.
15
+
16
+ You should have received a copy of the GNU Affero General Public License
17
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+
19
+ COMMERCIAL LICENSE
20
+
21
+ For organizations that cannot comply with the AGPL open-source requirements,
22
+ a commercial license is available. Contact: drmdh@msn.com
23
+
24
+ The commercial license allows you to:
25
+ - Use the software in proprietary/closed-source projects
26
+ - Modify without publishing your source code
27
+ - Get priority support and SLA
28
+
29
+ Contact: Dr Hamid MADANI <drmdh@msn.com>
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @mostajs/commandes
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Auteur** : Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
4
+
5
+ La commande payée à la livraison (COD) d'une boutique. Elle naît **« à confirmer »** et n'est **jamais « payée »** à la création ; ses **prix sont figés**. Elle passe par un **automate gardé et journalisé** (`@mostajs/statemachine`) :
6
+ - à confirmer, à rappeler, injoignable ;
7
+ - confirmée ;
8
+ - annulée (avec motif), fausse ;
9
+ - expédiée, livrée, retournée.
10
+
11
+ Le module apporte aussi :
12
+ - les **contrôles** contre les fausses commandes : mobile algérien, doublon, liste noire propre à la boutique, score de risque et signaux nommés ;
13
+ - la **file de confirmation** : rappels datés, essais, tour de rôle, compteurs et taux du jour ;
14
+ - le **quota du forfait**, en mode « hors quota » : rien n'est perdu ;
15
+ - les **commandes abandonnées**, sans adresse, gardées 7 jours ;
16
+ - la **conservation bornée** des données des acheteurs : anonymisation, effacement à la demande.
17
+
18
+ Il est **borné à une boutique** par construction. Le stock (`@mostajs/stocks`), la numérotation (`@mostajs/numbering`), le journal et les événements sont branchés par l'application.
19
+
20
+ ```js
21
+ import { createCommandes, creerDepotsMemoire } from '@mostajs/commandes';
22
+ const cmd = createCommandes({ depots: creerDepotsMemoire(), boutique: 'boutique-a', reglages: { quota: () => 500 } });
23
+ const { commande, controles } = await cmd.creer({
24
+ lignes: [{ produit: 'prd-1', sku: 'ROBE-LIN-M', libelle: 'Robe en lin', valeurs: { taille: 'M' }, prix: 490000, quantite: 1 }],
25
+ acheteur: { nom: 'Amina B.', telephone: '0661 23 45 67', wilaya: '16', commune: 'Bab Ezzouar', adresse: '…' },
26
+ livraison: { mode: 'domicile', prix: 50000 },
27
+ });
28
+ await cmd.sansReponse(commande.id, { par: 'conf-1' }); // rappel dans 120 min
29
+ await cmd.confirmer(commande.id, { par: 'conf-1' }); // stock réservé
30
+ ```
31
+
32
+ Voir `llms.txt` pour l'API complète, les ports et les codes d'erreur.
package/llms.txt ADDED
@@ -0,0 +1,43 @@
1
+ # @mostajs/commandes — fiche LLM
2
+ > La commande COD d'une boutique : née « à confirmer », jamais payée, prix figés ; automate gardé et journalisé ; contrôles anti-fausse-commande ; file de confirmation, rappels, attribution ; hors quota ; commandes abandonnées ; conservation bornée. Borné à UNE boutique.
3
+
4
+ - Version : 0.1.0 · Niveau N2 · Licence AGPL-3.0-or-later · Auteur : Dr Hamid MADANI <drmdh@msn.com>
5
+ - Chemin : mostajs/mosta-commerce-stack/mosta-commandes · Proposition : [Produit] e-commerce, P4 (29/11/2026) ; DPIA #16
6
+ - Dépend de : @mostajs/statemachine (automate, journal immuable). Patron : @mostajs/restauration (prix figés, motif obligatoire), le confirmateur de guerway-api (lu, non repris)
7
+
8
+ ## EXPORTS
9
+ createCommandes({ depots, boutique, reglages?, numeroter?, stock?, journal?, evenements?, confirmateurs?, autoriser?, horloge? }) → Commandes
10
+ creerDepotsMemoire() · creerDepotMemoire(prefixe) · schemasCommandes() · CommandeSchema, ListeNoireSchema, BrouillonSchema
11
+ normaliserTelephone(v, { mobiles? }) → '0XXXXXXXXX' | null (« +213 », « 00213 » acceptés ; mobiles 05/06/07)
12
+ ErreurCommandes { code, details } · ETATS · EN_ATTENTE · TERMINAUX · MOTIFS_DEFAUT · POIDS
13
+
14
+ ## PORTS
15
+ depots { commandes, listeNoire?, brouillons? } : { create, findById, update, delete, find(filtre d'égalité) }
16
+ reglages { devise='DZD', mobiles=['05','06','07'], doublonHeures=24, seuilRisque=60, essaisMax=3, delaiEntreAppelsMinutes=120,
17
+ conservationMois=24, brouillonJours=7, attribution='tour-de-role'|'manuelle', quota: () => n | -1, motifsAnnulation, formatNumero='CMD-NNNNN', decalageMinutes=60 }
18
+ numeroter async () → numéro ← @mostajs/numbering (défaut : CMD-NNNNN par boutique)
19
+ stock { reserver(stockRef, quantite, ref), liberer(ref) } ← @mostajs/stocks (réservé à la confirmation, libéré à l'annulation)
20
+ journal AuditSink { record, list } ← @mostajs/statemachine (défaut : en mémoire)
21
+ evenements { emettre(type, { boutique, id, numero, etat, total, horsQuota }) } — AUCUNE donnée de l'acheteur
22
+ confirmateurs async () → [{ id, nom }] · autoriser async (qui, permission) → bool (commandes:confirmer|appeler|annuler|expedier)
23
+
24
+ ## API
25
+ creer({ lignes, acheteur:{ nom, telephone, wilaya, commune?, adresse? }, livraison:{ mode, prix, bureau? }, reference?, cle?, source?, ip? })
26
+ → { commande, controles:{ doublon, listeNoire, score, niveau:'faible'|'moyen'|'eleve', signaux:[{ code, poids }] }, deja? }
27
+ confirmer(id, { par, modifications?:{ acheteur?, lignes?, livraison? } }) · rappeler(id, { a, par, note? }) · sansReponse(id, { par })
28
+ annuler(id, { motif, precision?, par }) · marquerFausse(id, { motif, listeNoire?, par }) · expedier(id, { colis }) · livrer(id, { codEncaisse? }) · retourner(id, { motif })
29
+ get(id) · historique(id) · liste({ etat?, q?, wilaya?, attribueeA?, page?, parPage? }) → { lignes, total }
30
+ file({ confirmateur? }) → { compteurs, taux, lignes, plusAncienneMinutes } · rappels({ jour? }) · attribuer(id, qui) · reattribuer({ de, a }) · charge()
31
+ listeNoire.{ ajouter(tel, { motif, par }), retirer(tel), liste(), contient(tel) } · quota() → { mois, compte, plafond, horsQuota }
32
+ purger() → { commandes, brouillons } · effacerAcheteur(id, { motif, par }) · exporter({ du?, au? }) → CSV « ; »
33
+ brouillons.{ enregistrer({ cle, lignes, acheteur:{ nom?, telephone, wilaya? }, source? }), liste({ jour? }), convertir(cle, { commande }), purger() }
34
+
35
+ ## SIGNAUX DU SCORE (poids fixés)
36
+ liste-noire → « fausse », 100 · doublon +40 (+20 par commande en plus) · nom-douteux +20 · adresse-vide (domicile) +15 · quantite-inhabituelle (>5) +15 · meme-ip +20
37
+
38
+ ## CODES D'ERREUR
39
+ BOUTIQUE_REQUISE DEPOTS_REQUIS COMMANDE_INCONNUE TELEPHONE_INVALIDE LIGNE_REQUISE LIGNES_TROP_NOMBREUSES QUANTITE_INVALIDE PRIX_INVALIDE ACHETEUR_INCOMPLET
40
+ TRANSITION_REFUSEE PERMISSION_REFUSEE MOTIF_REQUIS MOTIF_INCONNU PRECISION_REQUISE DATE_INVALIDE HORS_QUOTA STOCK_INSUFFISANT COLIS_REQUIS EN_COURS CLE_REQUISE
41
+
42
+ ## NE FAIT PAS
43
+ catalogue → @mostajs/catalogue-produits · stock → @mostajs/stocks · colis chez le transporteur → l'application (L5) · file à guichets → @mostajs/queue · écrans → l'application
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@mostajs/commandes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "La commande COD d'une boutique : née « à confirmer », jamais payée, prix figés ; automate gardé et journalisé (statemachine) ; contrôles anti-fausse-commande (numéro, doublon, liste noire, score) ; file de confirmation, rappels, attribution ; hors quota ; commandes abandonnées ; conservation bornée des données des acheteurs. Borné à une boutique.",
5
+ "author": "Dr Hamid MADANI <drmdh@msn.com>",
6
+ "license": "AGPL-3.0-or-later",
7
+ "type": "module",
8
+ "main": "./src/index.mjs",
9
+ "exports": { ".": "./src/index.mjs" },
10
+ "files": ["src", "README.md", "llms.txt", "LICENSE", "CHANGELOG.md"],
11
+ "engines": { "node": ">=20" },
12
+ "scripts": { "test": "node node_modules/@mostajs/mjs-unit/bin/cli.mjs test-scripts/unit/*.test.mjs --json=test-scripts/.out/report.json --title=\"@mostajs/commandes\"" },
13
+ "keywords": ["mostajs", "commandes", "cod", "confirmation", "e-commerce", "algerie"],
14
+ "mostajs": {
15
+ "niveau": "N2", "nature": "metier", "reutilisabilite": "transverse", "depend_de": ["@mostajs/statemachine"],
16
+ "question": "Cette commande payée à la livraison est-elle vraie, confirmée, à rappeler, et qui l'appelle ?",
17
+ "forme": "moteur", "entites": ["Commande", "ListeNoire", "Brouillon"],
18
+ "verbes": ["createCommandes", "creer", "confirmer", "sansReponse", "file", "purger"],
19
+ "ne_fait_pas": { "catalogue": "@mostajs/catalogue-produits", "stock": "@mostajs/stocks, par le port `stock`", "numérotation": "@mostajs/numbering, par le port `numeroter`",
20
+ "colis chez le transporteur": "l'application (L5)", "file à guichets": "@mostajs/queue", "écrans": "l'application" }
21
+ },
22
+ "dependencies": { "@mostajs/statemachine": "^0.0.1" },
23
+ "devDependencies": { "@mostajs/mjs-unit": "^0.21.0" }
24
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,485 @@
1
+ // @mostajs/commandes — la commande COD d'une boutique (proposition P4 de [Produit], validée le 29/11/2026).
2
+ // Une commande naît « à confirmer », JAMAIS payée ; ses prix sont figés ; elle suit un automate gardé et journalisé
3
+ // (@mostajs/statemachine). Contrôles anti-fausse-commande (numéro, doublon, liste noire, score), file de confirmation,
4
+ // rappels, attribution, quota (« hors quota » : rien n'est perdu), commandes abandonnées, conservation bornée (DPIA).
5
+ // Borné à UNE boutique par construction. Stock, numérotation, journal, événements, temps : des ports.
6
+ // @author Dr Hamid MADANI <drmdh@msn.com>
7
+ // @license AGPL-3.0-or-later
8
+ import { defineMachine, MemoryAuditSink, PermissionDeniedError, StateMachineError } from '@mostajs/statemachine';
9
+
10
+ export class ErreurCommandes extends Error {
11
+ constructor(code, details = {}, message = code) { super(message); this.name = 'ErreurCommandes'; this.code = code; this.details = details; }
12
+ }
13
+ const refus = (code, details = {}, message) => { throw new ErreurCommandes(code, details, message ?? code); };
14
+
15
+ export const ETATS = Object.freeze(['a-confirmer', 'a-rappeler', 'injoignable', 'confirmee', 'annulee', 'fausse', 'expediee', 'livree', 'retournee']);
16
+ export const EN_ATTENTE = Object.freeze(['a-confirmer', 'a-rappeler', 'injoignable']);
17
+ export const TERMINAUX = Object.freeze(['annulee', 'fausse', 'livree', 'retournee']);
18
+ export const MOTIFS_DEFAUT = Object.freeze(['change-avis', 'prix', 'delai', 'doublon', 'hors-zone', 'injoignable', 'autre']);
19
+
20
+ /** Les poids du score (Q5 : fixés en V1, seul le seuil se règle). */
21
+ export const POIDS = Object.freeze({ doublon: 40, doublonEnPlus: 20, nomDouteux: 20, adresseVide: 15, quantiteInhabituelle: 15, memeIp: 20, quantiteMax: 5 });
22
+
23
+ const REGLAGES_DEFAUT = Object.freeze({
24
+ devise: 'DZD', mobiles: ['05', '06', '07'], doublonHeures: 24, seuilRisque: 60, essaisMax: 3, delaiEntreAppelsMinutes: 120,
25
+ conservationMois: 24, brouillonJours: 7, attribution: 'tour-de-role', quota: () => -1, motifsAnnulation: MOTIFS_DEFAUT,
26
+ formatNumero: 'CMD-NNNNN', decalageMinutes: 60, // l'heure d'Alger (UTC+1, sans heure d'été)
27
+ });
28
+
29
+ const copie = (x) => (x === undefined ? undefined : JSON.parse(JSON.stringify(x)));
30
+ const plier = (s) => String(s ?? '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim();
31
+ const chiffres = (s) => String(s ?? '').replace(/\D+/g, '');
32
+ const texte = (v, max = 200) => String(v ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);
33
+ const cellule = (x) => { const s = String(x ?? ''); const sur = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; return /[";\n]/.test(sur) ? `"${sur.replace(/"/g, '""')}"` : sur; };
34
+
35
+ /** Un mobile algérien sous sa forme nationale (0XXXXXXXXX), ou null. « +213 », « 00213 » acceptés. */
36
+ export function normaliserTelephone(v, { mobiles = REGLAGES_DEFAUT.mobiles } = {}) {
37
+ let d = chiffres(v);
38
+ if (d.startsWith('00213')) d = `0${d.slice(5)}`; else if (d.startsWith('213') && d.length === 12) d = `0${d.slice(3)}`;
39
+ if (d.length !== 10 || !mobiles.some((p) => d.startsWith(p))) return null;
40
+ return d;
41
+ }
42
+
43
+ // ── Dépôts en mémoire (essais, démonstrations) ─────────────────────────────────────────────────────────────────
44
+
45
+ /** Un dépôt en mémoire au contrat attendu : create, findById, update, delete, find(filtre d'égalité). */
46
+ export function creerDepotMemoire(prefixe = 'x') {
47
+ const lignes = new Map(); let n = 0;
48
+ return {
49
+ async create(doc) { const id = doc.id ?? `${prefixe}-${++n}`; const d = { ...copie(doc), id }; lignes.set(id, d); return copie(d); },
50
+ async findById(id) { return copie(lignes.get(String(id)) ?? null); },
51
+ async update(id, patch) { const d = lignes.get(String(id)); if (!d) return null; Object.assign(d, copie(patch)); return copie(d); },
52
+ async delete(id) { lignes.delete(String(id)); },
53
+ async find(filtre = {}) { return [...lignes.values()].filter((d) => Object.entries(filtre).every(([k, v]) => d[k] === v)).map(copie); },
54
+ };
55
+ }
56
+ export const creerDepotsMemoire = () => ({ commandes: creerDepotMemoire('cmd'), listeNoire: creerDepotMemoire('ln'), brouillons: creerDepotMemoire('brl') });
57
+
58
+ // ── L'automate ─────────────────────────────────────────────────────────────────────────────────────────────────
59
+
60
+ const DEFINITION = {
61
+ states: ETATS.map((id) => ({ id, initial: id === 'a-confirmer', terminal: TERMINAUX.includes(id) })),
62
+ transitions: [
63
+ { id: 'confirmer', from: ['a-confirmer', 'a-rappeler', 'injoignable'], to: 'confirmee', permission: 'commandes:confirmer' },
64
+ { id: 'rappeler', from: ['a-confirmer', 'a-rappeler', 'injoignable'], to: 'a-rappeler', permission: 'commandes:appeler' },
65
+ { id: 'injoignable', from: ['a-confirmer', 'a-rappeler', 'injoignable'], to: 'injoignable', permission: 'commandes:appeler' },
66
+ { id: 'annuler', from: ['a-confirmer', 'a-rappeler', 'injoignable', 'confirmee'], to: 'annulee', permission: 'commandes:annuler' },
67
+ { id: 'fausse', from: ['a-confirmer', 'a-rappeler', 'injoignable'], to: 'fausse', permission: 'commandes:annuler' },
68
+ { id: 'expedier', from: ['confirmee'], to: 'expediee', permission: 'commandes:expedier' },
69
+ { id: 'livrer', from: ['expediee'], to: 'livree', permission: 'commandes:expedier' },
70
+ { id: 'retourner', from: ['expediee'], to: 'retournee', permission: 'commandes:expedier' },
71
+ ],
72
+ };
73
+
74
+ // ── Les commandes d'une boutique ───────────────────────────────────────────────────────────────────────────────
75
+
76
+ /**
77
+ * @param {object} o
78
+ * @param {object} o.depots { commandes, listeNoire, brouillons } au contrat de creerDepotMemoire
79
+ * @param {string} o.boutique LA boutique (obligatoire) : toute lecture est filtrée par elle, toute écriture la pose
80
+ * @param {object} [o.reglages] voir REGLAGES_DEFAUT ; `quota()` → commandes par mois (-1 : sans limite)
81
+ * @param {Function} [o.numeroter] async () → numéro (port @mostajs/numbering) ; défaut : CMD-NNNNN par boutique
82
+ * @param {object} [o.stock] { reserver(stockRef, qte, ref), liberer(ref) } (port @mostajs/stocks)
83
+ * @param {object} [o.journal] AuditSink de @mostajs/statemachine (défaut : en mémoire)
84
+ * @param {object} [o.evenements] { emettre(type, données) } — aucune donnée de l'acheteur n'y passe
85
+ * @param {Function} [o.confirmateurs] async () → [{ id, nom }] pour le tour de rôle
86
+ * @param {Function} [o.autoriser] async (qui, permission) → booléen
87
+ */
88
+ export function createCommandes({ depots, boutique, reglages = {}, numeroter = null, stock = null, journal = null, evenements = null,
89
+ confirmateurs = null, autoriser = null, horloge = () => new Date() } = {}) {
90
+ if (!boutique || typeof boutique !== 'string') throw new ErreurCommandes('BOUTIQUE_REQUISE', {}, 'createCommandes : `boutique` requis');
91
+ if (!depots?.commandes) throw new ErreurCommandes('DEPOTS_REQUIS');
92
+ const D = { listeNoire: creerDepotMemoire('ln'), brouillons: creerDepotMemoire('brl'), ...depots };
93
+ const R = { ...REGLAGES_DEFAUT, ...reglages };
94
+ const audit = journal ?? new MemoryAuditSink();
95
+ const machine = defineMachine(DEFINITION, { audit, now: horloge, ...(autoriser ? { checkPermission: (qui, p) => autoriser(qui, p) } : {}) });
96
+ const tel = (v) => normaliserTelephone(v, { mobiles: R.mobiles });
97
+ const iso = () => horloge().toISOString();
98
+ const ms = () => horloge().getTime();
99
+ const local = (t) => new Date(Date.parse(t) + R.decalageMinutes * 60_000).toISOString();
100
+ const jourDe = (t) => local(t).slice(0, 10);
101
+ const moisDe = (t) => local(t).slice(0, 7);
102
+ const ref = (id) => ({ entityType: 'commande', entityId: id });
103
+
104
+ // Les écritures passent une à une (quota, numéro, doublon : pas de course entre deux envois simultanés).
105
+ let fileEcriture = Promise.resolve();
106
+ const enFile = (f) => { const p = fileEcriture.then(f, f); fileEcriture = p.catch(() => {}); return p; };
107
+ const emettre = (type, c, plus = {}) => {
108
+ try { evenements?.emettre?.(type, { boutique, id: c.id, numero: c.numero, etat: c.etat, total: c.totaux?.total ?? 0, horsQuota: !!c.horsQuota, ...plus }); } catch { /* un abonné en panne n'annule rien */ }
109
+ };
110
+
111
+ const toutes = () => D.commandes.find({ boutique });
112
+ const sienne = async (id) => { const c = id ? await D.commandes.findById(String(id)) : null; return c && c.boutique === boutique ? c : null; };
113
+ const siennePourEcrire = async (id) => (await sienne(id)) ?? refus('COMMANDE_INCONNUE', { id });
114
+
115
+ // ── la forme d'une commande (liste blanche : rien d'autre n'entre, ni carte ni « payée ») ───────────────────
116
+ const lignesDe = (lignes) => {
117
+ if (!Array.isArray(lignes) || !lignes.length) refus('LIGNE_REQUISE');
118
+ if (lignes.length > 50) refus('LIGNES_TROP_NOMBREUSES');
119
+ return lignes.map((l) => {
120
+ const quantite = Number(l?.quantite);
121
+ if (!Number.isInteger(quantite) || quantite < 1 || quantite > 999) refus('QUANTITE_INVALIDE', { sku: l?.sku });
122
+ const prix = Number(l?.prix);
123
+ if (!Number.isInteger(prix) || prix < 0) refus('PRIX_INVALIDE', { sku: l?.sku });
124
+ const valeurs = {};
125
+ for (const [k, v] of Object.entries(l.valeurs ?? {}).slice(0, 10)) valeurs[texte(k, 40)] = texte(v, 80);
126
+ return { produit: texte(l.produit, 64) || null, combinaison: texte(l.combinaison, 64) || null, sku: texte(l.sku, 64) || null, libelle: texte(l.libelle, 160),
127
+ valeurs, prix, poids: Number.isFinite(Number(l.poids)) ? Math.max(0, Math.round(Number(l.poids))) : 0, quantite, stockRef: texte(l.stockRef, 64) || null };
128
+ });
129
+ };
130
+ const acheteurDe = (a) => {
131
+ const telephone = tel(a?.telephone);
132
+ if (!telephone) refus('TELEPHONE_INVALIDE');
133
+ const x = { nom: texte(a.nom, 120), telephone, wilaya: texte(a.wilaya, 10), commune: texte(a.commune, 80), adresse: texte(a.adresse, 240) };
134
+ if (!x.nom || !x.wilaya) refus('ACHETEUR_INCOMPLET', { manque: !x.nom ? 'nom' : 'wilaya' });
135
+ return x;
136
+ };
137
+ const livraisonDe = (l = {}) => {
138
+ const prix = Number(l.prix ?? 0);
139
+ if (!Number.isInteger(prix) || prix < 0) refus('PRIX_INVALIDE', { livraison: true });
140
+ return { mode: l.mode === 'bureau' ? 'bureau' : 'domicile', prix, bureau: texte(l.bureau, 64) || null };
141
+ };
142
+ const totauxDe = (lignes, livraison) => { const sousTotal = lignes.reduce((s, l) => s + l.prix * l.quantite, 0); return { sousTotal, livraison: livraison.prix, total: sousTotal + livraison.prix }; };
143
+ const sourceDe = (s) => { const o = {}; for (const [k, v] of Object.entries(s ?? {})) if (/^utm_[a-z]+$|^ref$/.test(k)) o[k] = texte(v, 120); return o; };
144
+
145
+ // ── les contrôles (SPEC-ECO-23) ──────────────────────────────────────────────────────────────────────────────
146
+ const surListeNoire = async (t) => (await D.listeNoire.find({ boutique, telephone: t })).length > 0;
147
+ const niveauDe = (score) => (score >= R.seuilRisque ? 'eleve' : score > 0 && score >= R.seuilRisque / 2 ? 'moyen' : 'faible');
148
+ async function controler({ acheteur, lignes, livraison, ip }, existantes) {
149
+ const signaux = [];
150
+ if (await surListeNoire(acheteur.telephone)) {
151
+ return { telephone: 'valide', doublon: 0, listeNoire: true, score: 100, niveau: 'eleve', signaux: [{ code: 'liste-noire', poids: 100 }] };
152
+ }
153
+ const depuis = ms() - R.doublonHeures * 3600_000;
154
+ const doublon = existantes.filter((c) => c.acheteur?.telephone === acheteur.telephone && Date.parse(c.creeeLe) >= depuis).length;
155
+ if (doublon) signaux.push({ code: 'doublon', poids: POIDS.doublon + POIDS.doublonEnPlus * (doublon - 1) });
156
+ const lettres = (acheteur.nom.match(/\p{L}/gu) ?? []).length;
157
+ if (lettres < 3) signaux.push({ code: 'nom-douteux', poids: POIDS.nomDouteux });
158
+ if (livraison.mode === 'domicile' && !acheteur.adresse) signaux.push({ code: 'adresse-vide', poids: POIDS.adresseVide });
159
+ if (lignes.some((l) => l.quantite > POIDS.quantiteMax)) signaux.push({ code: 'quantite-inhabituelle', poids: POIDS.quantiteInhabituelle });
160
+ if (ip && existantes.some((c) => c.ip === ip && c.acheteur?.telephone !== acheteur.telephone && Date.parse(c.creeeLe) >= ms() - 3600_000)) signaux.push({ code: 'meme-ip', poids: POIDS.memeIp });
161
+ const score = Math.min(100, signaux.reduce((s, x) => s + x.poids, 0));
162
+ return { telephone: 'valide', doublon, listeNoire: false, score, niveau: niveauDe(score), signaux };
163
+ }
164
+
165
+ // ── numéro, quota, attribution ───────────────────────────────────────────────────────────────────────────────
166
+ async function numeroSuivant(existantes) {
167
+ if (numeroter) return String(await numeroter());
168
+ const tete = R.formatNumero.replace(/N+$/, ''); const trous = (R.formatNumero.match(/N+$/)?.[0] ?? 'NNNNN').length;
169
+ const max = existantes.reduce((m, c) => (String(c.numero).startsWith(tete) ? Math.max(m, Number(String(c.numero).slice(tete.length)) || 0) : m), 0);
170
+ return `${tete}${String(max + 1).padStart(trous, '0')}`;
171
+ }
172
+ const plafond = async () => { const p = Number(await R.quota()); return Number.isFinite(p) ? p : -1; };
173
+ async function horsQuotaPour(existantes) {
174
+ const p = await plafond(); if (p < 0) return false;
175
+ const mois = moisDe(iso());
176
+ return existantes.filter((c) => c.mois === mois).length >= p;
177
+ }
178
+ async function peutLever(c, existantes) {
179
+ if (c.mois !== moisDe(iso())) return true;
180
+ const p = await plafond(); if (p < 0) return true;
181
+ return existantes.filter((x) => x.mois === c.mois && !x.horsQuota).length < p;
182
+ }
183
+ async function attribution(existantes) {
184
+ if (R.attribution !== 'tour-de-role' || !confirmateurs) return null;
185
+ const equipe = (await confirmateurs()) ?? [];
186
+ if (!equipe.length) return null;
187
+ const charge = (id) => existantes.filter((c) => c.attribueeA === id && EN_ATTENTE.includes(c.etat)).length;
188
+ return equipe.reduce((meilleur, x) => (charge(x.id) < charge(meilleur.id) ? x : meilleur), equipe[0]).id;
189
+ }
190
+
191
+ // ── les transitions ──────────────────────────────────────────────────────────────────────────────────────────
192
+ async function passer(c, vers, { par = null, comment, patch = {}, evenement = null } = {}) {
193
+ try { await machine.transition(ref(c.id), c.etat, vers, { actorId: par ?? undefined, comment }); }
194
+ catch (e) {
195
+ if (e instanceof PermissionDeniedError) refus('PERMISSION_REFUSEE', { de: c.etat, vers });
196
+ if (e instanceof StateMachineError) refus('TRANSITION_REFUSEE', { de: c.etat, vers }, `${c.numero} : ${c.etat} → ${vers} refusé`);
197
+ throw e;
198
+ }
199
+ const x = await D.commandes.update(c.id, { ...patch, etat: vers, majLe: iso() });
200
+ if (evenement) emettre(evenement, x);
201
+ return x;
202
+ }
203
+ const appel = (c, a) => [...(c.appels ?? []), { le: iso(), ...a }];
204
+ const motifDe = (motif, precision) => {
205
+ const m = texte(motif, 40);
206
+ if (!m) refus('MOTIF_REQUIS');
207
+ if (!R.motifsAnnulation.includes(m)) refus('MOTIF_INCONNU', { motif: m });
208
+ if (m === 'autre' && !texte(precision)) refus('PRECISION_REQUISE');
209
+ return m;
210
+ };
211
+ const motifLibre = (motif) => texte(motif, 200) || refus('MOTIF_REQUIS');
212
+ async function verifierPermission(par, permission) {
213
+ if (autoriser && !(await autoriser(par, permission))) refus('PERMISSION_REFUSEE', { permission });
214
+ }
215
+
216
+ // ── les brouillons (commandes abandonnées, Q8) ───────────────────────────────────────────────────────────────
217
+ const brouillonDe = async (cle) => (await D.brouillons.find({ boutique, cle }))[0] ?? null;
218
+ const brouillons = {
219
+ /** Rien tant que le téléphone n'est pas valide ; jamais l'adresse ; idempotent par la clé de page. */
220
+ enregistrer: ({ cle, lignes = [], acheteur = {}, source } = {}) => enFile(async () => {
221
+ const k = texte(cle, 64); if (!k) refus('CLE_REQUISE');
222
+ const telephone = tel(acheteur.telephone); if (!telephone) return null;
223
+ if ((await D.commandes.find({ boutique, cle: k })).length) return null; // déjà envoyée
224
+ const nom = texte(acheteur.nom, 120); const wilaya = texte(acheteur.wilaya, 10);
225
+ const a = { ...(nom ? { nom } : {}), telephone, ...(wilaya ? { wilaya } : {}) };
226
+ const l = (Array.isArray(lignes) ? lignes : []).slice(0, 20).map((x) => ({ produit: texte(x.produit, 64) || null, combinaison: texte(x.combinaison, 64) || null,
227
+ libelle: texte(x.libelle, 160), valeurs: copie(x.valeurs ?? {}), quantite: Math.max(1, Math.min(999, Math.round(Number(x.quantite) || 1))) }));
228
+ const champs = { acheteur: a, lignes: l, source: sourceDe(source), majLe: iso(), expireLe: new Date(ms() + R.brouillonJours * 86_400_000).toISOString() };
229
+ const b = await brouillonDe(k);
230
+ return b ? D.brouillons.update(b.id, champs) : D.brouillons.create({ boutique, cle: k, creeLe: iso(), ...champs });
231
+ }),
232
+ liste: async ({ jour = null } = {}) => (await D.brouillons.find({ boutique }))
233
+ .filter((b) => Date.parse(b.expireLe) > ms() && (!jour || jourDe(b.creeLe) === jour)).sort((a, b) => b.majLe.localeCompare(a.majLe)),
234
+ convertir: (cle, { commande } = {}) => enFile(async () => {
235
+ const b = await brouillonDe(texte(cle, 64)); if (!b) return false;
236
+ if (commande && !(await sienne(commande))) refus('COMMANDE_INCONNUE', { id: commande });
237
+ await D.brouillons.delete(b.id); return true;
238
+ }),
239
+ purger: () => enFile(async () => {
240
+ let n = 0; for (const b of await D.brouillons.find({ boutique })) if (Date.parse(b.expireLe) <= ms()) { await D.brouillons.delete(b.id); n++; }
241
+ return n;
242
+ }),
243
+ };
244
+
245
+ // ── l'anonymisation (DPIA) ───────────────────────────────────────────────────────────────────────────────────
246
+ async function anonymiser(c, { motif, par = null } = {}) {
247
+ const x = await D.commandes.update(c.id, { acheteur: { wilaya: c.acheteur?.wilaya ?? '' }, ip: null,
248
+ appels: (c.appels ?? []).map(({ note, ...a }) => a), anonymiseeLe: iso() });
249
+ await audit.record({ entityType: 'commande', entityId: c.id, fromState: c.etat, toState: c.etat, actorId: par ?? undefined, timestamp: iso(), comment: 'donnees-effacees', transitionId: motif ?? 'conservation' });
250
+ return x;
251
+ }
252
+ const ajouterMois = (t, n) => { const d = new Date(t); d.setUTCMonth(d.getUTCMonth() + n); return d.getTime(); };
253
+
254
+ return {
255
+ /** Crée une commande (page de commande, saisie, connecteur). Référence déjà vue : la MÊME commande. */
256
+ creer: (entree = {}) => enFile(async () => {
257
+ const existantes = await toutes();
258
+ const reference = texte(entree.reference, 80) || null;
259
+ if (reference) { const deja = existantes.find((c) => c.reference === reference); if (deja) return { commande: deja, controles: deja.controles, deja: true }; }
260
+ const lignes = lignesDe(entree.lignes); const acheteur = acheteurDe(entree.acheteur); const livraison = livraisonDe(entree.livraison);
261
+ const ip = texte(entree.ip, 64) || null;
262
+ const controles = await controler({ acheteur, lignes, livraison, ip }, existantes);
263
+ const horsQuota = await horsQuotaPour(existantes);
264
+ const cle = texte(entree.cle, 64) || null;
265
+ const maintenant = iso();
266
+ let c = await D.commandes.create({
267
+ boutique, numero: await numeroSuivant(existantes), reference, cle, etat: 'a-confirmer', paiement: 'a-la-livraison', devise: R.devise,
268
+ lignes, acheteur, livraison, totaux: totauxDe(lignes, livraison), source: sourceDe(entree.source), ip, controles,
269
+ horsQuota, mois: moisDe(maintenant), essais: 0, rappelA: null, attribueeA: await attribution(existantes), appels: [],
270
+ annulation: null, colis: null, creeeLe: maintenant, majLe: maintenant, confirmeeLe: null, clotureeLe: null, anonymiseeLe: null,
271
+ });
272
+ await audit.record({ entityType: 'commande', entityId: c.id, fromState: null, toState: 'a-confirmer', actorId: undefined, timestamp: maintenant, comment: 'creee', transitionId: 'creer' });
273
+ emettre('commande.creee', c);
274
+ if (horsQuota) emettre('commande.hors-quota', c);
275
+ if (controles.listeNoire) c = await passer(c, 'fausse', { comment: 'liste-noire', patch: { clotureeLe: maintenant, annulation: { motif: 'liste-noire', precision: '', par: null } }, evenement: 'commande.fausse' });
276
+ if (cle) { const b = await brouillonDe(cle); if (b) await D.brouillons.delete(b.id); }
277
+ return { commande: c, controles };
278
+ }),
279
+
280
+ get: async (id) => sienne(id),
281
+ historique: async (id) => ((await sienne(id)) ? machine.history(ref(String(id))) : []),
282
+
283
+ confirmer: (id, { par = null, modifications = null } = {}) => enFile(async () => {
284
+ const c = await siennePourEcrire(id);
285
+ if (!EN_ATTENTE.includes(c.etat)) refus('TRANSITION_REFUSEE', { de: c.etat, vers: 'confirmee' });
286
+ if (c.horsQuota && !(await peutLever(c, await toutes()))) refus('HORS_QUOTA', { id: c.id });
287
+ await verifierPermission(par, 'commandes:confirmer');
288
+ const patch = { horsQuota: false };
289
+ if (modifications) {
290
+ const acheteur = modifications.acheteur ? acheteurDe({ ...c.acheteur, ...modifications.acheteur }) : c.acheteur;
291
+ const lignes = modifications.lignes ? lignesDe(modifications.lignes) : c.lignes;
292
+ const livraison = modifications.livraison ? livraisonDe(modifications.livraison) : c.livraison;
293
+ Object.assign(patch, { acheteur, lignes, livraison, totaux: totauxDe(lignes, livraison) });
294
+ }
295
+ const lignes = patch.lignes ?? c.lignes;
296
+ let reserve = false;
297
+ if (stock) {
298
+ try { for (const l of lignes) if (l.stockRef) { reserve = true; await stock.reserver(l.stockRef, l.quantite, `cmd:${c.id}`); } }
299
+ catch (e) { await stock.liberer(`cmd:${c.id}`).catch(() => {}); refus('STOCK_INSUFFISANT', { id: c.id }, e?.message); }
300
+ }
301
+ try {
302
+ return await passer(c, 'confirmee', { par, comment: modifications ? 'modifiee' : undefined, evenement: 'commande.confirmee',
303
+ patch: { ...patch, confirmeeLe: iso(), confirmeePar: par, rappelA: null, appels: appel(c, { issue: 'confirmee', par, ...(modifications ? { modifications: Object.keys(modifications) } : {}) }) } });
304
+ } catch (e) { if (reserve) await stock.liberer(`cmd:${c.id}`).catch(() => {}); throw e; }
305
+ }),
306
+
307
+ rappeler: (id, { a, par = null, note } = {}) => enFile(async () => {
308
+ const c = await siennePourEcrire(id);
309
+ const t = Date.parse(a);
310
+ if (!Number.isFinite(t) || t <= ms()) refus('DATE_INVALIDE');
311
+ const quand = new Date(t).toISOString();
312
+ return passer(c, 'a-rappeler', { par, comment: 'rappel', patch: { rappelA: quand, appels: appel(c, { issue: 'rappel', a: quand, par, ...(note ? { note: texte(note, 500) } : {}) }) } });
313
+ }),
314
+
315
+ /** Sans réponse : un essai de plus ; rappel au délai réglé ; à `essaisMax`, « injoignable » (Q3). */
316
+ sansReponse: (id, { par = null } = {}) => enFile(async () => {
317
+ const c = await siennePourEcrire(id);
318
+ const essais = (c.essais ?? 0) + 1;
319
+ const fin = essais >= R.essaisMax || c.etat === 'injoignable';
320
+ return passer(c, fin ? 'injoignable' : 'a-rappeler', { par, comment: 'sans-reponse',
321
+ patch: { essais, rappelA: fin ? null : new Date(ms() + R.delaiEntreAppelsMinutes * 60_000).toISOString(), appels: appel(c, { issue: 'sans-reponse', essai: essais, sur: R.essaisMax, par }) } });
322
+ }),
323
+
324
+ annuler: (id, { motif, precision = '', par = null } = {}) => enFile(async () => {
325
+ const c = await siennePourEcrire(id);
326
+ const m = motifDe(motif, precision);
327
+ const etaitConfirmee = c.etat === 'confirmee';
328
+ const x = await passer(c, 'annulee', { par, comment: m, evenement: 'commande.annulee',
329
+ patch: { clotureeLe: iso(), rappelA: null, annulation: { motif: m, precision: texte(precision, 300), par }, appels: appel(c, { issue: 'annulee', motif: m, par }) } });
330
+ if (etaitConfirmee && stock) await stock.liberer(`cmd:${c.id}`);
331
+ return x;
332
+ }),
333
+
334
+ marquerFausse: (id, { motif, listeNoire = false, par = null } = {}) => enFile(async () => {
335
+ const c = await siennePourEcrire(id);
336
+ const m = motifLibre(motif);
337
+ const x = await passer(c, 'fausse', { par, comment: 'fausse', evenement: 'commande.fausse',
338
+ patch: { clotureeLe: iso(), rappelA: null, annulation: { motif: 'fausse', precision: m, par }, appels: appel(c, { issue: 'fausse', par }) } });
339
+ if (listeNoire && c.acheteur?.telephone && !(await surListeNoire(c.acheteur.telephone))) {
340
+ await D.listeNoire.create({ boutique, telephone: c.acheteur.telephone, motif: m, par, commande: c.id, ajouteLe: iso() });
341
+ }
342
+ return x;
343
+ }),
344
+
345
+ expedier: (id, { colis, par = null } = {}) => enFile(async () => {
346
+ const c = await siennePourEcrire(id);
347
+ if (c.etat === 'confirmee' && !texte(colis, 64)) refus('COLIS_REQUIS');
348
+ return passer(c, 'expediee', { par, evenement: 'commande.expediee', patch: { colis: texte(colis, 64), expedieeLe: iso() } });
349
+ }),
350
+ livrer: (id, { codEncaisse = null, par = null } = {}) => enFile(async () => {
351
+ const c = await siennePourEcrire(id);
352
+ return passer(c, 'livree', { par, evenement: 'commande.livree', patch: { livreeLe: iso(), clotureeLe: iso(), codEncaisse: Number.isInteger(codEncaisse) ? codEncaisse : null } });
353
+ }),
354
+ retourner: (id, { motif, par = null } = {}) => enFile(async () => {
355
+ const c = await siennePourEcrire(id);
356
+ const m = c.etat === 'expediee' ? motifLibre(motif) : texte(motif, 200);
357
+ return passer(c, 'retournee', { par, comment: 'retour', evenement: 'commande.retournee', patch: { clotureeLe: iso(), retour: { motif: m, par } } });
358
+ }),
359
+
360
+ /** La liste de la console : filtres d'égalité et recherche (numéro, téléphone, nom). */
361
+ liste: async ({ etat = null, q = '', wilaya = null, attribueeA = null, page = 1, parPage = 50 } = {}) => {
362
+ const qq = plier(q); const qd = chiffres(q);
363
+ const l = (await toutes()).filter((c) => (!etat || c.etat === etat) && (!wilaya || c.acheteur?.wilaya === wilaya) && (!attribueeA || c.attribueeA === attribueeA)
364
+ && (!qq || plier(c.numero).includes(qq) || plier(c.acheteur?.nom).includes(qq) || (qd.length >= 4 && chiffres(c.acheteur?.telephone).includes(qd))))
365
+ .sort((a, b) => b.creeeLe.localeCompare(a.creeeLe));
366
+ const n = Math.max(1, Math.min(200, Number(parPage) || 50)); const p = Math.max(1, Number(page) || 1);
367
+ return { lignes: l.slice((p - 1) * n, p * n), total: l.length, page: p, parPage: n };
368
+ },
369
+
370
+ /** La file de confirmation : à appeler maintenant (plus anciennes d'abord, hors quota en dernier) ; compteurs du jour. */
371
+ file: async ({ confirmateur = null } = {}) => {
372
+ const tout = await toutes(); const t = ms(); const jour = jourDe(iso());
373
+ const echeance = (c) => (c.etat === 'a-rappeler' ? Date.parse(c.rappelA) : Date.parse(c.creeeLe));
374
+ const lignes = tout.filter((c) => (c.etat === 'a-confirmer' || (c.etat === 'a-rappeler' && Date.parse(c.rappelA) <= t)) && (!confirmateur || c.attribueeA === confirmateur))
375
+ .sort((a, b) => (Number(a.horsQuota) - Number(b.horsQuota)) || (echeance(a) - echeance(b)));
376
+ const duJour = (champ) => (c) => !!c[champ] && jourDe(c[champ]) === jour;
377
+ const compte = (etat, champ) => tout.filter((c) => c.etat === etat && (!champ || duJour(champ)(c))).length;
378
+ const confirmees = tout.filter(duJour('confirmeeLe')).length;
379
+ const annulees = compte('annulee', 'clotureeLe'); const fausses = compte('fausse', 'clotureeLe');
380
+ const aConfirmer = tout.filter((c) => c.etat === 'a-confirmer');
381
+ const plusAncienne = aConfirmer.reduce((m, c) => Math.min(m, Date.parse(c.creeeLe)), Infinity);
382
+ return {
383
+ compteurs: { aConfirmer: aConfirmer.length, aRappeler: compte('a-rappeler'), injoignables: compte('injoignable'), confirmees, annulees, fausses },
384
+ taux: confirmees + annulees + fausses ? confirmees / (confirmees + annulees + fausses) : null,
385
+ lignes, plusAncienneMinutes: Number.isFinite(plusAncienne) ? Math.floor((t - plusAncienne) / 60_000) : null,
386
+ };
387
+ },
388
+
389
+ /** Les rappels d'un jour (défaut : aujourd'hui), par heure, avec leur retard. */
390
+ rappels: async ({ jour = null } = {}) => {
391
+ const j = jour ?? jourDe(iso()); const t = ms();
392
+ return (await toutes()).filter((c) => c.etat === 'a-rappeler' && c.rappelA && jourDe(c.rappelA) === j)
393
+ .sort((a, b) => a.rappelA.localeCompare(b.rappelA))
394
+ .map((c) => ({ ...c, enRetardMinutes: Math.max(0, Math.floor((t - Date.parse(c.rappelA)) / 60_000)) }));
395
+ },
396
+
397
+ attribuer: (id, confirmateur) => enFile(async () => { const c = await siennePourEcrire(id); return D.commandes.update(c.id, { attribueeA: texte(confirmateur, 64) || null }); }),
398
+ reattribuer: ({ de, a } = {}) => enFile(async () => {
399
+ let n = 0; for (const c of await toutes()) if (c.attribueeA === de && EN_ATTENTE.includes(c.etat)) { await D.commandes.update(c.id, { attribueeA: a ?? null }); n++; }
400
+ return n;
401
+ }),
402
+ /** La charge de l'équipe : en attente, confirmées et traitées du jour, taux. */
403
+ charge: async () => {
404
+ const tout = await toutes(); const jour = jourDe(iso());
405
+ const equipe = confirmateurs ? (await confirmateurs()) ?? [] : [...new Set(tout.map((c) => c.attribueeA).filter(Boolean))].map((id) => ({ id }));
406
+ return equipe.map((x) => {
407
+ const siennes = tout.filter((c) => c.attribueeA === x.id);
408
+ const confirmees = siennes.filter((c) => c.confirmeeLe && jourDe(c.confirmeeLe) === jour).length;
409
+ const closes = siennes.filter((c) => ['annulee', 'fausse'].includes(c.etat) && c.clotureeLe && jourDe(c.clotureeLe) === jour).length;
410
+ return { id: x.id, nom: x.nom ?? null, enAttente: siennes.filter((c) => EN_ATTENTE.includes(c.etat)).length, confirmeesDuJour: confirmees,
411
+ traiteesDuJour: confirmees + closes, taux: confirmees + closes ? confirmees / (confirmees + closes) : null };
412
+ });
413
+ },
414
+
415
+ listeNoire: {
416
+ ajouter: (telephone, { motif, par = null } = {}) => enFile(async () => {
417
+ const t = tel(telephone); if (!t) refus('TELEPHONE_INVALIDE');
418
+ const m = motifLibre(motif);
419
+ const deja = (await D.listeNoire.find({ boutique, telephone: t }))[0];
420
+ return deja ?? D.listeNoire.create({ boutique, telephone: t, motif: m, par, commande: null, ajouteLe: iso() });
421
+ }),
422
+ retirer: (telephone) => enFile(async () => {
423
+ const t = tel(telephone); let n = 0;
424
+ for (const x of t ? await D.listeNoire.find({ boutique, telephone: t }) : []) { await D.listeNoire.delete(x.id); n++; }
425
+ return n > 0;
426
+ }),
427
+ liste: async () => (await D.listeNoire.find({ boutique })).sort((a, b) => b.ajouteLe.localeCompare(a.ajouteLe)),
428
+ contient: async (telephone) => { const t = tel(telephone); return t ? surListeNoire(t) : false; },
429
+ },
430
+
431
+ quota: async () => {
432
+ const mois = moisDe(iso()); const du = (await toutes()).filter((c) => c.mois === mois);
433
+ return { mois, compte: du.length, plafond: await plafond(), horsQuota: du.filter((c) => c.horsQuota).length };
434
+ },
435
+
436
+ /** Conservation bornée (SPEC-ECO-26) : au-delà de `conservationMois` après la dernière étape, l'acheteur est effacé ; et les brouillons expirés. */
437
+ purger: async () => {
438
+ const commandes = await enFile(async () => {
439
+ let n = 0;
440
+ for (const c of await toutes()) if (!c.anonymiseeLe && ajouterMois(c.majLe, R.conservationMois) <= ms()) { await anonymiser(c); n++; }
441
+ return n;
442
+ });
443
+ return { commandes, brouillons: await brouillons.purger() };
444
+ },
445
+
446
+ /** DPIA §6 : effacer à la demande ; pas pendant la livraison (confirmée, expédiée). */
447
+ effacerAcheteur: (id, { motif, par = null } = {}) => enFile(async () => {
448
+ const c = await siennePourEcrire(id);
449
+ if (['confirmee', 'expediee'].includes(c.etat)) refus('EN_COURS', { etat: c.etat });
450
+ return anonymiser(c, { motif: motifLibre(motif), par });
451
+ }),
452
+
453
+ /** L'export CSV (séparateur « ; ») ; aucune cellule n'est une formule. */
454
+ exporter: async ({ du = null, au = null } = {}) => {
455
+ const tete = ['numero', 'date', 'etat', 'client', 'telephone', 'wilaya', 'commune', 'adresse', 'articles', 'sous_total', 'livraison', 'total', 'devise', 'colis'];
456
+ const l = (await toutes()).filter((c) => (!du || jourDe(c.creeeLe) >= du) && (!au || jourDe(c.creeeLe) <= au)).sort((a, b) => a.creeeLe.localeCompare(b.creeeLe));
457
+ const ligne = (c) => [c.numero, local(c.creeeLe).slice(0, 16).replace('T', ' '), c.etat, c.acheteur?.nom, c.acheteur?.telephone, c.acheteur?.wilaya, c.acheteur?.commune, c.acheteur?.adresse,
458
+ c.lignes.map((x) => `${x.quantite} × ${x.libelle}`).join(' | '), c.totaux.sousTotal / 100, c.totaux.livraison / 100, c.totaux.total / 100, c.devise, c.colis];
459
+ return `${[tete, ...l.map(ligne)].map((r) => r.map(cellule).join(';')).join('\n')}\n`;
460
+ },
461
+
462
+ brouillons,
463
+ };
464
+ }
465
+
466
+ // ── Les schémas pour @mostajs/data-plug (EntitySchema) : chaque table porte `boutique`, indexée ─────────────────
467
+
468
+ export const CommandeSchema = { name: 'Commande', collection: 'commandes', timestamps: true,
469
+ fields: { boutique: { type: 'string', required: true }, numero: { type: 'string', required: true }, reference: { type: 'string' }, cle: { type: 'string' },
470
+ etat: { type: 'string', required: true }, paiement: { type: 'string' }, devise: { type: 'string' }, lignes: { type: 'json' }, acheteur: { type: 'json' },
471
+ livraison: { type: 'json' }, totaux: { type: 'json' }, source: { type: 'json' }, ip: { type: 'string' }, controles: { type: 'json' }, horsQuota: { type: 'boolean' },
472
+ mois: { type: 'string' }, essais: { type: 'number' }, rappelA: { type: 'string' }, attribueeA: { type: 'string' }, appels: { type: 'json' }, annulation: { type: 'json' },
473
+ retour: { type: 'json' }, colis: { type: 'string' }, codEncaisse: { type: 'number' }, confirmeePar: { type: 'string' }, creeeLe: { type: 'string' }, majLe: { type: 'string' },
474
+ confirmeeLe: { type: 'string' }, expedieeLe: { type: 'string' }, livreeLe: { type: 'string' }, clotureeLe: { type: 'string' }, anonymiseeLe: { type: 'string' } },
475
+ relations: {}, indexes: [{ fields: { boutique: 'asc' } }, { fields: { boutique: 'asc', numero: 'asc' }, unique: true }, { fields: { boutique: 'asc', etat: 'asc' } },
476
+ { fields: { boutique: 'asc', reference: 'asc' } }] };
477
+ export const ListeNoireSchema = { name: 'CommandeListeNoire', collection: 'commandes_liste_noire', timestamps: true,
478
+ fields: { boutique: { type: 'string', required: true }, telephone: { type: 'string', required: true }, motif: { type: 'string', required: true }, par: { type: 'string' },
479
+ commande: { type: 'string' }, ajouteLe: { type: 'string' } },
480
+ relations: {}, indexes: [{ fields: { boutique: 'asc' } }, { fields: { boutique: 'asc', telephone: 'asc' }, unique: true }] };
481
+ export const BrouillonSchema = { name: 'CommandeBrouillon', collection: 'commandes_brouillons', timestamps: true,
482
+ fields: { boutique: { type: 'string', required: true }, cle: { type: 'string', required: true }, acheteur: { type: 'json' }, lignes: { type: 'json' }, source: { type: 'json' },
483
+ creeLe: { type: 'string' }, majLe: { type: 'string' }, expireLe: { type: 'string' } },
484
+ relations: {}, indexes: [{ fields: { boutique: 'asc' } }, { fields: { boutique: 'asc', cle: 'asc' }, unique: true }] };
485
+ export const schemasCommandes = () => [CommandeSchema, ListeNoireSchema, BrouillonSchema];