@mostajs/achats 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 +19 -0
- package/LICENSE +15 -0
- package/README.md +126 -2
- package/exemples/reapprovisionner.mjs +60 -0
- package/llms.txt +96 -0
- package/package.json +81 -4
- package/src/adaptateurs.mjs +43 -0
- package/src/codes.mjs +30 -0
- package/src/depot-memoire.mjs +39 -0
- package/src/entiers.mjs +23 -0
- package/src/erreur.mjs +21 -0
- package/src/etats.mjs +30 -0
- package/src/index.mjs +11 -0
- package/src/permissions.mjs +31 -0
- package/src/proposition.mjs +57 -0
- package/src/register.mjs +24 -0
- package/src/schemas.mjs +55 -0
- package/src/service.mjs +347 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog — @mostajs/achats
|
|
2
|
+
|
|
3
|
+
**Auteur** : Dr Hamid MADANI <drmdh@msn.com>
|
|
4
|
+
Format : Keep a Changelog ; versions : SemVer.
|
|
5
|
+
|
|
6
|
+
## [0.1.0] — 2026-11-18
|
|
7
|
+
|
|
8
|
+
### Ajouté
|
|
9
|
+
- `creerAchats({ depots, stock?, fournisseurs?, numeroter?, horloge?, id?, reglages? })` : `creer`, `modifier`, `envoyer`, `recevoir`, `reprendreEntrees`, `solder`, `annuler`, `lire`, `lister`, `receptionsDe`, `aReprendre`, `enCommande`, `proposer`, `brouillonsDepuis`.
|
|
10
|
+
- Cycle de vie `brouillon → envoyee → recue_partiellement → soldee`, et `annulee` (`ETATS`, `TRANSITIONS`), historique tracé dans la commande.
|
|
11
|
+
- Réception partielle, excédent refusé par défaut (sans écriture) ou accepté, refus sur une commande soldée, annulée ou en brouillon ; entrée en stock ligne par ligne par le port `stock.entrer`, reprise après panne sans double entrée (`cle` par ligne).
|
|
12
|
+
- Version optimiste sur la commande : deux réceptions simultanées ne s'additionnent pas (`CONFLIT_VERSION`).
|
|
13
|
+
- `calculerQuantite` : point de commande, stock de sécurité (en unités ou en jours), couverture, arrondi au colis et au minimum, en entiers.
|
|
14
|
+
- Adaptateurs `portStocks` (`@mostajs/stocks` 0.5.0) et `portNumerotation` (`@mostajs/numbering` 0.1.1) ; `@mostajs/fournisseurs` 0.2.0 se branche tel quel.
|
|
15
|
+
- `depotMemoire()` (contrat à prédicat avec version), `schemaCommandeAchat`, `schemaReceptionAchat`, `register(registry)` (`@mostajs/achats/register`).
|
|
16
|
+
- Permissions contribuées `achats:lire`, `achats:proposer`, `achats:commander`, `achats:envoyer`, `achats:recevoir`, `achats:cloturer` et `PERMISSION_PAR_OPERATION` ; aucune attribution à un rôle.
|
|
17
|
+
- 23 codes d'erreur (`ErreurAchats`, `CODES`, `LIBELLES`).
|
|
18
|
+
- Exemple de vérification `exemples/reapprovisionner.mjs`, sur les vrais `stocks`, `fournisseurs` et `numbering`.
|
|
19
|
+
- 22 essais `T-ACH-n` (`@mostajs/mjs-unit`).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
@mostajs/offline-replay
|
|
2
|
+
Copyright (C) 2026 Dr Hamid MADANI <drmdh@msn.com>
|
|
3
|
+
|
|
4
|
+
This program is free software: you can redistribute it and/or modify it under
|
|
5
|
+
the terms of the GNU Affero General Public License as published by the Free
|
|
6
|
+
Software Foundation, either version 3 of the License, or (at your option) any
|
|
7
|
+
later version.
|
|
8
|
+
|
|
9
|
+
This program is distributed in the hope that it will be useful, but WITHOUT
|
|
10
|
+
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
11
|
+
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
12
|
+
details.
|
|
13
|
+
|
|
14
|
+
You should have received a copy of the GNU Affero General Public License
|
|
15
|
+
along with this program. If not, see <https://www.gnu.org/licenses/agpl-3.0.html>.
|
package/README.md
CHANGED
|
@@ -1,3 +1,127 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mostajs/achats
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Auteur** : Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later · N1 · aucune dépendance d'exécution · Node ≥ 20
|
|
4
|
+
|
|
5
|
+
Ce module gère les **commandes fournisseurs**. Il propose la quantité à commander, suit chaque commande jusqu'à sa réception, partielle ou totale, et fait entrer en stock ce qui est reçu.
|
|
6
|
+
|
|
7
|
+
- **Cycle de vie** : `brouillon → envoyee → recue_partiellement → soldee`, et `annulee`. Chaque passage est tracé dans la commande (qui, quand, d'où, vers où, pourquoi).
|
|
8
|
+
- **Quantité proposée** : point de commande (demande pendant le délai + stock de sécurité), niveau cible (couverture), arrondi au colis et au minimum de commande. Tout est calculé en entiers.
|
|
9
|
+
- **Réception** : une ou plusieurs livraisons par commande, ligne par ligne. L'excédent est refusé par défaut et peut être accepté. Une commande soldée ou annulée ne reçoit plus rien.
|
|
10
|
+
- **Entrée en stock** par un port injecté. Si le stock tombe en panne au milieu d'une livraison, `reprendreEntrees` termine le travail sans entrer deux fois la même ligne.
|
|
11
|
+
|
|
12
|
+
Le module ne recode ni le stock, ni le référentiel des fournisseurs, ni la numérotation. Il compose `@mostajs/stocks`, `@mostajs/fournisseurs` et `@mostajs/numbering` par injection, et il n'en dépend pas à l'exécution.
|
|
13
|
+
|
|
14
|
+
## Installer
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @mostajs/achats
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
| Entrée | Contenu |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `@mostajs/achats` | `creerAchats`, `calculerQuantite`, `depotMemoire`, `portStocks`, `portNumerotation`, `ETATS`, `TRANSITIONS`, `CODES`, `LIBELLES`, `ErreurAchats`, `PERMISSIONS`, `PERMISSION_PAR_OPERATION`, `schemaCommandeAchat`, `schemaReceptionAchat` |
|
|
23
|
+
| `@mostajs/achats/register` | `register(registry)` : manifeste, permissions et schémas, pour `@mostajs/socle` |
|
|
24
|
+
|
|
25
|
+
## En 20 lignes
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { createStocks } from '@mostajs/stocks';
|
|
29
|
+
import { creerFournisseurs } from '@mostajs/fournisseurs';
|
|
30
|
+
import { createNumbering } from '@mostajs/numbering';
|
|
31
|
+
import { creerAchats, portStocks, portNumerotation } from '@mostajs/achats';
|
|
32
|
+
|
|
33
|
+
const numbering = createNumbering({ store }); // séquence définie par l'application
|
|
34
|
+
numbering.define({ name: 'commande-achat', format: '[BC]-YYYY-NNNN', resetEvery: 'year' });
|
|
35
|
+
|
|
36
|
+
const achats = creerAchats({
|
|
37
|
+
depots: { commandes: magasin.repo('achats_commandes'), receptions: magasin.repo('achats_receptions') },
|
|
38
|
+
stock: portStocks(createStocks({ repositories })), // entrer, disponible, consommation
|
|
39
|
+
fournisseurs: creerFournisseurs({ depot, depotReferences }), // branché tel quel
|
|
40
|
+
numeroter: portNumerotation(numbering),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const propositions = await achats.proposer({ articles: [{ articleId, delaiJours: 7, stockSecurite: 10, prixUnitaire: 1250 }] });
|
|
44
|
+
const { brouillons } = await achats.brouillonsDepuis(propositions, { par: utilisateur.id }); // à valider par un humain
|
|
45
|
+
const commande = await achats.envoyer(brouillons[0].id, { par: utilisateur.id }); // numéro tiré ici
|
|
46
|
+
await achats.recevoir(commande.id, { par: magasinier.id, lignes: [{ ligne: 1, quantite: 3 }] }); // → recue_partiellement
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
L'exemple complet tourne seul, sur les vrais `stocks`, `fournisseurs` et `numbering` : `npm run exemple`.
|
|
50
|
+
|
|
51
|
+
## La quantité proposée
|
|
52
|
+
|
|
53
|
+
Les calculs sont faits en entiers. La consommation est une quantité observée sur une fenêtre (`fenetreJours`, 30 par défaut), et chaque division est arrondie à l'entier supérieur.
|
|
54
|
+
|
|
55
|
+
| Grandeur | Calcul |
|
|
56
|
+
|---|---|
|
|
57
|
+
| demande pendant le délai | ⌈ consommé × délai / fenêtre ⌉ |
|
|
58
|
+
| stock de sécurité | donné en unités, ou ⌈ consommé × jours de sécurité / fenêtre ⌉ |
|
|
59
|
+
| point de commande | demande pendant le délai + stock de sécurité |
|
|
60
|
+
| position | disponible + reste en commande (commandes envoyées et reçues en partie) |
|
|
61
|
+
| déclenché | position ≤ point de commande |
|
|
62
|
+
| niveau cible | point de commande + ⌈ consommé × couverture / fenêtre ⌉ (couverture : 30 jours par défaut) |
|
|
63
|
+
| quantité | niveau cible − position, au moins un colis, arrondie au colis, au moins le minimum |
|
|
64
|
+
|
|
65
|
+
`proposer` rend aussi `enBrouillon` : ce qui figure déjà dans un brouillon n'est pas « en commande », mais il faut le voir pour ne pas commander deux fois.
|
|
66
|
+
|
|
67
|
+
## La réception, dans l'ordre
|
|
68
|
+
|
|
69
|
+
1. **L'état** : la commande doit être `envoyee` ou `recue_partiellement`. Sinon le module lève `COMMANDE_NON_ENVOYEE`, `COMMANDE_SOLDEE` ou `COMMANDE_ANNULEE`.
|
|
70
|
+
2. **Les lignes** : chaque ligne reçue désigne une ligne de la commande, par son numéro ou par son article (`LIGNE_INCONNUE`, `LIGNE_EN_DOUBLE`), avec une quantité entière positive (`QUANTITE_INVALIDE`).
|
|
71
|
+
3. **L'excédent** : en mode `excedent: 'refuser'` (le défaut), le module lève `RECEPTION_EXCEDENTAIRE` avec le reste et le reçu de chaque ligne en cause, et n'écrit rien. En mode `'accepter'`, l'excédent est enregistré, entre en stock au prix de la commande et est rendu dans `excedents`.
|
|
72
|
+
4. **La commande** est écrite sous version : deux réceptions simultanées donnent `CONFLIT_VERSION` à la seconde, qui n'entre rien en stock.
|
|
73
|
+
5. **Le stock** : chaque ligne appelle `stock.entrer` avec la quantité multipliée par `parColis`, le montant (quantité × prix unitaire), `ref = 'achat:<numéro>'` et `cle = '<réception>:<ligne>'`.
|
|
74
|
+
6. **La panne** : si une entrée échoue, le module lève `ENTREE_STOCK_ECHOUEE` avec `details.receptionId`. `reprendreEntrees(receptionId)` entre les lignes restantes, et elles seules.
|
|
75
|
+
|
|
76
|
+
## Le dépôt
|
|
77
|
+
|
|
78
|
+
Un dépôt par entité, au contrat à prédicat de `@mostajs/repository` :
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
create(doc) → doc · findById(id) → doc | null · find(predicat) → doc[] · update(id, patch, { version }?) → doc | null
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`update` doit rendre `null` si la version stockée n'est pas celle qui est passée. En base, cela s'écrit `UPDATE … WHERE id = ? AND version = ?`. `depotMemoire()` tient ce contrat (copies isolées), pour les essais et les démonstrations. Les tables `achats_commandes` et `achats_receptions` sont déclarées par `register()`.
|
|
85
|
+
|
|
86
|
+
## Les permissions
|
|
87
|
+
|
|
88
|
+
Le module **contribue** six permissions et n'en attribue aucune à un rôle : c'est l'administrateur qui les coche dans la matrice. Il ne les vérifie pas non plus. L'application consulte `PERMISSION_PAR_OPERATION` et vérifie le droit avant d'appeler l'opération.
|
|
89
|
+
|
|
90
|
+
| Permission | Opérations |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `achats:lire` | `lire`, `lister`, `receptionsDe`, `aReprendre`, `enCommande` |
|
|
93
|
+
| `achats:proposer` | `proposer` |
|
|
94
|
+
| `achats:commander` | `creer`, `modifier`, `brouillonsDepuis` |
|
|
95
|
+
| `achats:envoyer` | `envoyer` |
|
|
96
|
+
| `achats:recevoir` | `recevoir`, `reprendreEntrees` |
|
|
97
|
+
| `achats:cloturer` | `solder`, `annuler` |
|
|
98
|
+
|
|
99
|
+
## Réglages
|
|
100
|
+
|
|
101
|
+
| Réglage | Défaut | Rôle |
|
|
102
|
+
|---|---|---|
|
|
103
|
+
| `excedent` | `'refuser'` | politique d'excédent à la réception (`'refuser'` ou `'accepter'`) ; l'appel peut la changer |
|
|
104
|
+
| `fenetreJours` | 30 | fenêtre de consommation observée ; un article peut la changer |
|
|
105
|
+
| `couvertureJours` | 30 | jours couverts au-delà du point de commande ; un article peut la changer |
|
|
106
|
+
|
|
107
|
+
`reglages` est un objet ou une fonction, relue à chaque appel. Les valeurs viennent des Paramètres de l'application.
|
|
108
|
+
|
|
109
|
+
## Ce qu'il ne fait pas
|
|
110
|
+
|
|
111
|
+
| Ne fait pas | Qui le fait |
|
|
112
|
+
|---|---|
|
|
113
|
+
| mouvements, niveaux, seuils, valorisation | `@mostajs/stocks` |
|
|
114
|
+
| référentiel des fournisseurs, références code ↔ matière | `@mostajs/fournisseurs` |
|
|
115
|
+
| facture d'achat, écritures comptables | `@mostajs/compta` |
|
|
116
|
+
| numérotation | `@mostajs/numbering` |
|
|
117
|
+
| recherche d'offres, comparaison de prix | `@mostajs/sourcing` |
|
|
118
|
+
| bon de commande en PDF, envoi par courriel | `@mostajs/file-export`, `@mostajs/mailer` |
|
|
119
|
+
| attribution des permissions | `@mostajs/rbac`, par l'administrateur |
|
|
120
|
+
| écrans | l'application |
|
|
121
|
+
|
|
122
|
+
## Essais
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
npm test # 22 essais T-ACH-n (@mostajs/mjs-unit), sans base ni réseau
|
|
126
|
+
npm run exemple # exemple de vérification sur les vrais stocks, fournisseurs et numbering
|
|
127
|
+
```
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// @mostajs/achats — exemple de vérification : un réapprovisionnement de bout en bout,
|
|
2
|
+
// sur les VRAIS @mostajs/stocks, @mostajs/fournisseurs et @mostajs/numbering (dépendances de développement).
|
|
3
|
+
// Lancer : npm run exemple (code de sortie 0 = chaque vérification a tenu)
|
|
4
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
5
|
+
import assert from 'node:assert/strict';
|
|
6
|
+
import { createStocks } from '@mostajs/stocks';
|
|
7
|
+
import { creerFournisseurs } from '@mostajs/fournisseurs';
|
|
8
|
+
import { createNumbering } from '@mostajs/numbering';
|
|
9
|
+
import { creerAchats, depotMemoire, portStocks, portNumerotation } from '../src/index.mjs';
|
|
10
|
+
|
|
11
|
+
const JOUR = 86400e3;
|
|
12
|
+
let t = Date.UTC(2026, 9, 19, 8);
|
|
13
|
+
const horloge = () => t;
|
|
14
|
+
|
|
15
|
+
// 1. Le stock : 120 cartons entrés, 90 sortis en 30 jours (3 par jour).
|
|
16
|
+
const stocks = createStocks({ repositories: { articles: depotMemoire(), movements: depotMemoire(), reservations: depotMemoire() }, now: () => new Date(t) });
|
|
17
|
+
const carton = await stocks.articles.create({ name: 'Carton 40x30x30', unit: 'u', minThreshold: 40 });
|
|
18
|
+
await stocks.movements.in(carton.id, { qty: 120, amount: 144000 });
|
|
19
|
+
for (let j = 0; j < 30; j++) { t += JOUR; await stocks.movements.out(carton.id, { qty: 3 }); }
|
|
20
|
+
|
|
21
|
+
// 2. Le référentiel : un fournisseur, une référence au colis de 25.
|
|
22
|
+
const fournisseurs = creerFournisseurs({ depot: depotMemoire(), depotReferences: depotMemoire() });
|
|
23
|
+
const f = await fournisseurs.creer({ nom: 'CARTONNERIE EXEMPLE' });
|
|
24
|
+
await fournisseurs.referencer({ fournisseurId: f.id, code: 'CT-40', matiereId: carton.id, parColis: 25, libelle: 'Carton 40 (25)' });
|
|
25
|
+
|
|
26
|
+
// 3. La numérotation sans trou.
|
|
27
|
+
const numbering = createNumbering();
|
|
28
|
+
numbering.define({ name: 'commande-achat', format: '[BC]-YYYY-NNNN', resetEvery: 'year' });
|
|
29
|
+
|
|
30
|
+
const achats = creerAchats({
|
|
31
|
+
depots: { commandes: depotMemoire(), receptions: depotMemoire() },
|
|
32
|
+
stock: portStocks(stocks), fournisseurs, numeroter: portNumerotation(numbering), horloge,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// 4. La proposition : disponible 30 ; point = 3×7 + 10 = 31 ; cible = 31 + 3×30 = 121 ; brute 91 → 4 colis.
|
|
36
|
+
const [p] = await achats.proposer({ articles: [{ articleId: carton.id, delaiJours: 7, stockSecurite: 10, couvertureJours: 30, prixUnitaire: 1250 }] });
|
|
37
|
+
console.log(`proposé : ${p.colis} colis (${p.quantite} unités), point de commande ${p.pointDeCommande}, disponible ${p.disponible}`);
|
|
38
|
+
assert.deepEqual([p.disponible, p.pointDeCommande, p.declenche, p.quantite, p.colis], [30, 31, true, 100, 4]);
|
|
39
|
+
|
|
40
|
+
// 5. Un brouillon validé, envoyé, reçu en deux fois (avec un excédent refusé entre les deux).
|
|
41
|
+
const { brouillons } = await achats.brouillonsDepuis([p], { par: 'responsable' });
|
|
42
|
+
const c = await achats.envoyer(brouillons[0].id, { par: 'responsable' });
|
|
43
|
+
console.log(`envoyée : ${c.numero}, total ${c.total}`);
|
|
44
|
+
assert.equal(c.numero, 'BC-2026-0001');
|
|
45
|
+
t += 5 * JOUR;
|
|
46
|
+
const r1 = await achats.recevoir(c.id, { par: 'magasin', bonLivraison: 'BL-1', lignes: [{ ligne: 1, quantite: 3 }] });
|
|
47
|
+
console.log(`livraison 1 : ${r1.commande.etat}, reliquat ${r1.reliquats[0].reste} colis`);
|
|
48
|
+
await assert.rejects(achats.recevoir(c.id, { par: 'magasin', lignes: [{ ligne: 1, quantite: 2 }] }), (e) => e.code === 'RECEPTION_EXCEDENTAIRE');
|
|
49
|
+
const r2 = await achats.recevoir(c.id, { par: 'magasin', bonLivraison: 'BL-2', lignes: [{ ligne: 1, quantite: 1 }] });
|
|
50
|
+
console.log(`livraison 2 : ${r2.commande.etat}`);
|
|
51
|
+
assert.equal(r2.commande.etat, 'soldee');
|
|
52
|
+
await assert.rejects(achats.recevoir(c.id, { par: 'magasin', lignes: [{ ligne: 1, quantite: 1 }] }), (e) => e.code === 'COMMANDE_SOLDEE');
|
|
53
|
+
|
|
54
|
+
// 6. Le stock a reçu 100 unités, à la référence de la commande.
|
|
55
|
+
const niveau = await stocks.levels.of(carton.id);
|
|
56
|
+
const entrees = (await stocks.movements.list({ articleId: carton.id })).filter((m) => m.ref === 'achat:BC-2026-0001');
|
|
57
|
+
console.log(`stock : ${niveau.qty} unités ; entrées de la commande : ${entrees.map((m) => m.qty).join(' + ')}`);
|
|
58
|
+
assert.equal(niveau.qty, 30 + 100);
|
|
59
|
+
assert.deepEqual(entrees.map((m) => [m.qty, m.amount]), [[75, 3750], [25, 1250]]);
|
|
60
|
+
console.log('✓ exemple vérifié');
|
package/llms.txt
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# @mostajs/achats 0.1.0 — fiche LLM
|
|
2
|
+
> Commandes fournisseurs (brouillon → envoyée → reçue en partie → soldée, et annulée), quantité proposée au point
|
|
3
|
+
> de commande avec stock de sécurité, réception partielle ou excédentaire qui entre en stock par un port injecté.
|
|
4
|
+
|
|
5
|
+
- Niveau: N1 générique, forme moteur · Licence: AGPL-3.0-or-later · Auteur: Dr Hamid MADANI <drmdh@msn.com>
|
|
6
|
+
- Pile: mosta-gestion-stack · Zéro dépendance d'exécution · Node ≥ 20 (ou navigateur : structuredClone, crypto.randomUUID)
|
|
7
|
+
|
|
8
|
+
## RÔLE
|
|
9
|
+
Répond à « que commander, à qui, et qu'en a-t-on reçu ? ». Porte la commande fournisseur et son état, calcule la
|
|
10
|
+
quantité à commander, enregistre les livraisons ligne par ligne et fait entrer en stock ce qui est reçu, par un port.
|
|
11
|
+
Ne recode ni le stock (@mostajs/stocks), ni le référentiel des fournisseurs (@mostajs/fournisseurs), ni la numérotation
|
|
12
|
+
(@mostajs/numbering) : il les COMPOSE par injection.
|
|
13
|
+
|
|
14
|
+
## QUESTION
|
|
15
|
+
Que commander, à qui, et qu'en a-t-on reçu ?
|
|
16
|
+
|
|
17
|
+
## API
|
|
18
|
+
- creerAchats({ depots: { commandes, receptions }, stock?, fournisseurs?, numeroter?, horloge?, id?, reglages? }) → service
|
|
19
|
+
(CONFIG_INVALIDE si un dépôt manque ou si un port porte autre chose que des fonctions)
|
|
20
|
+
creer({ fournisseurId, lignes: [{ articleId, quantite, prixUnitaire, code?, libelle?, parColis? }], reference?, note?, devise?, par })
|
|
21
|
+
→ brouillon ; numero null ; code, libelle, parColis complétés par fournisseurs.fournisseursPourMatiere
|
|
22
|
+
modifier(id, { lignes?, reference?, note?, devise? }, { par }) brouillon seulement (COMMANDE_NON_MODIFIABLE)
|
|
23
|
+
envoyer(id, { par }) brouillon → envoyee ; numero = await numeroter({ type: 'commande-achat', le, fournisseurId })
|
|
24
|
+
recevoir(id, { lignes: [{ ligne | articleId, quantite, lot?, peremption? }], le?, bonLivraison?, excedent?, par })
|
|
25
|
+
→ { commande, reception, excedents: [{ ligne, articleId, excedent }], reliquats: [{ ligne, articleId, reste }] }
|
|
26
|
+
reprendreEntrees(receptionId) après ENTREE_STOCK_ECHOUEE : entre les lignes restantes, elles seules
|
|
27
|
+
solder(id, { motif, par }) recue_partiellement → soldee (reliquat abandonné, tracé)
|
|
28
|
+
annuler(id, { motif, par }) brouillon | envoyee → annulee
|
|
29
|
+
lire(id) · lister({ etat?, fournisseurId?, articleId? }) · receptionsDe(id) · aReprendre() · enCommande(articleId)
|
|
30
|
+
proposer({ articles: [{ articleId, delaiJours, fournisseurId?, stockSecurite? | stockSecuriteJours?, couvertureJours?,
|
|
31
|
+
minimumQuantite?, parColis?, prixUnitaire?, fenetreJours? }] }) → propositions (ne crée rien)
|
|
32
|
+
brouillonsDepuis(propositions, { par }) → { brouillons (un par fournisseur), sansFournisseur: [articleId] }
|
|
33
|
+
- calculerQuantite({ disponible, enCommande?, consommation: { quantite, jours }, delaiJours, stockSecurite? | stockSecuriteJours?,
|
|
34
|
+
couvertureJours?, minimumQuantite?, multiple? })
|
|
35
|
+
→ { declenche, position, demandePendantDelai, stockSecurite, pointDeCommande, niveauCible, quantiteBrute, multiple, quantite, colis }
|
|
36
|
+
- depotMemoire() · portStocks(stocks) · portNumerotation(numbering, { nom = 'commande-achat' })
|
|
37
|
+
- ETATS, TRANSITIONS, CODES, LIBELLES, ErreurAchats(code, message?, details?) { code, message, details }
|
|
38
|
+
- PERMISSIONS, PERMISSION_PAR_OPERATION · schemaCommandeAchat, schemaReceptionAchat
|
|
39
|
+
- '@mostajs/achats/register' → register(registry) : manifeste, permissions, schémas (CommandeAchat, ReceptionAchat)
|
|
40
|
+
|
|
41
|
+
## PORTS
|
|
42
|
+
- stock { entrer({ articleId, quantite, montant, ref, cle, par, lot, peremption }) → { id? },
|
|
43
|
+
disponible(articleId) → entier, consommation(articleId, { depuis, jusqua }) → entier } (ms depuis l'époque)
|
|
44
|
+
portStocks(createStocks(...)) : movements.in (qty, amount, ref, by, lot, expiry), levels.of().free,
|
|
45
|
+
somme des sorties et des consommations de transformation de movements.list({ articleId })
|
|
46
|
+
- fournisseurs { parId(id) → { actif } | null, fournisseursPourMatiere(articleId) → [{ fournisseurId, code, parColis, libelle }] }
|
|
47
|
+
l'objet de creerFournisseurs() de @mostajs/fournisseurs 0.2.0 convient TEL QUEL
|
|
48
|
+
- numeroter ({ type, le, fournisseurId }) → string ; portNumerotation(createNumbering()) ; absent → numero null
|
|
49
|
+
- horloge () → ms | Date (défaut Date.now) · id () → string (défaut crypto.randomUUID)
|
|
50
|
+
- reglages objet ou () → objet : { excedent: 'refuser', fenetreJours: 30, couvertureJours: 30 } (lus à chaque appel)
|
|
51
|
+
|
|
52
|
+
## DÉPÔT
|
|
53
|
+
Contrat à prédicat (@mostajs/repository), un dépôt par entité :
|
|
54
|
+
create(doc) → doc · findById(id) → doc | null · find(predicat) → doc[] · update(id, patch, { version }?) → doc | null
|
|
55
|
+
update rend null si la version stockée diffère de `version` (en base : UPDATE … WHERE id = ? AND version = ?) ;
|
|
56
|
+
le patch porte la nouvelle version. Le module traduit null en CONFLIT_VERSION. depotMemoire() le tient (copies isolées).
|
|
57
|
+
|
|
58
|
+
## ÉTATS
|
|
59
|
+
brouillon → envoyee → recue_partiellement → soldee ; brouillon | envoyee → annulee ; recue_partiellement → soldee (solder)
|
|
60
|
+
Une commande close nomme son état : COMMANDE_SOLDEE, COMMANDE_ANNULEE.
|
|
61
|
+
|
|
62
|
+
## QUANTITÉ PROPOSÉE (entiers, plafonds)
|
|
63
|
+
demandePendantDelai = ⌈q × delaiJours / jours⌉ ; stockSecurite = donné ou ⌈q × stockSecuriteJours / jours⌉
|
|
64
|
+
pointDeCommande = demandePendantDelai + stockSecurite ; position = disponible + enCommande ; declenche = position ≤ point
|
|
65
|
+
niveauCible = point + ⌈q × couvertureJours / jours⌉ ; quantite = max(⌈max(cible − position, 1) / multiple⌉, ⌈minimum / multiple⌉) × multiple
|
|
66
|
+
|
|
67
|
+
## PERMISSIONS (contribuées, jamais attribuées à un rôle ; l'application les vérifie avant l'appel)
|
|
68
|
+
achats:lire · achats:proposer · achats:commander · achats:envoyer · achats:recevoir · achats:cloturer
|
|
69
|
+
|
|
70
|
+
## CODES
|
|
71
|
+
CONFIG_INVALIDE PORT_ABSENT DONNEES_INVALIDES QUANTITE_INVALIDE MONTANT_INVALIDE LIGNES_VIDES LIGNE_EN_DOUBLE LIGNE_INCONNUE
|
|
72
|
+
FOURNISSEUR_INCONNU FOURNISSEUR_INACTIF COMMANDE_INCONNUE COMMANDE_NON_MODIFIABLE COMMANDE_NON_ENVOYEE COMMANDE_SOLDEE
|
|
73
|
+
COMMANDE_ANNULEE TRANSITION_INTERDITE ANNULATION_IMPOSSIBLE MOTIF_REQUIS RECEPTION_VIDE RECEPTION_EXCEDENTAIRE
|
|
74
|
+
RECEPTION_INCONNUE ENTREE_STOCK_ECHOUEE CONFLIT_VERSION
|
|
75
|
+
|
|
76
|
+
## PIÈGES
|
|
77
|
+
- montants et quantités : ENTIERS sûrs (unité monétaire entière, unité de stock entière) ; 12.5 → MONTANT_INVALIDE
|
|
78
|
+
- quantite d'une ligne = en unités de COMMANDE (colis) ; en stock entre quantite × parColis ; montant = quantite × prixUnitaire
|
|
79
|
+
- le numéro est tiré à l'ENVOI : un brouillon ne consomme pas de numéro ; un CONFLIT_VERSION à l'envoi en perd un
|
|
80
|
+
- excédent refusé par défaut, SANS rien écrire (details.lignes : reste et reçu) ; excedent: 'accepter' l'entre au prix de la commande
|
|
81
|
+
- un brouillon n'est PAS « en commande » (enCommande) ; proposer rend enBrouillon pour éviter la double commande
|
|
82
|
+
- après ENTREE_STOCK_ECHOUEE la commande porte déjà la livraison : appeler reprendreEntrees(details.receptionId), jamais recevoir
|
|
83
|
+
- port entrer : `cle` = '<réception>:<ligne>' permet à l'application d'ignorer une entrée rejouée
|
|
84
|
+
- @mostajs/fournisseurs 0.2.0 n'a pas de délai de livraison et son minimumCommande n'a pas d'unité : délai et minimum
|
|
85
|
+
viennent des Paramètres de l'application
|
|
86
|
+
- le module ne vérifie AUCUNE permission : PERMISSION_PAR_OPERATION dit laquelle vérifier ; jamais de rôle dans le code
|
|
87
|
+
|
|
88
|
+
## NE FAIT PAS
|
|
89
|
+
- mouvements, niveaux, seuils, valorisation → @mostajs/stocks
|
|
90
|
+
- référentiel des fournisseurs, références code ↔ matière → @mostajs/fournisseurs
|
|
91
|
+
- facture d'achat, rapprochement facture, écritures → @mostajs/compta (lecture de facture : stocks.approvisionnement)
|
|
92
|
+
- numérotation → @mostajs/numbering
|
|
93
|
+
- recherche d'offres, comparaison de prix → @mostajs/sourcing
|
|
94
|
+
- bon de commande en PDF, envoi par courriel → @mostajs/file-export, @mostajs/mailer
|
|
95
|
+
- attribution des permissions à des rôles → @mostajs/rbac (l'administrateur coche la matrice)
|
|
96
|
+
- écrans → l'application
|
package/package.json
CHANGED
|
@@ -1,6 +1,83 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mostajs/achats",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Commandes fournisseurs : cycle de vie (brouillon, envoyée, reçue en partie, soldée, annulée), quantité proposée au point de commande avec stock de sécurité, réception partielle ou excédentaire qui entre en stock par un port injecté ; montants entiers, horloge et dépôts injectés, erreurs à codes, permissions contribuées.",
|
|
5
|
+
"license": "AGPL-3.0-or-later",
|
|
6
|
+
"author": "Dr Hamid MADANI <drmdh@msn.com>",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "src/index.mjs",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./src/index.mjs",
|
|
11
|
+
"./register": "./src/register.mjs",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"exemples",
|
|
17
|
+
"llms.txt",
|
|
18
|
+
"README.md",
|
|
19
|
+
"CHANGELOG.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "bash test-scripts/run-tests.sh",
|
|
27
|
+
"exemple": "node exemples/reapprovisionner.mjs"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"mostajs",
|
|
31
|
+
"achats",
|
|
32
|
+
"purchasing",
|
|
33
|
+
"purchase-order",
|
|
34
|
+
"commande-fournisseur",
|
|
35
|
+
"reapprovisionnement",
|
|
36
|
+
"reorder-point",
|
|
37
|
+
"point-de-commande",
|
|
38
|
+
"stock-de-securite",
|
|
39
|
+
"reception"
|
|
40
|
+
],
|
|
41
|
+
"dependencies": {},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@mostajs/fournisseurs": "0.2.0",
|
|
44
|
+
"@mostajs/layer-lint": "^0.2.0",
|
|
45
|
+
"@mostajs/mjs-unit": "0.16.1",
|
|
46
|
+
"@mostajs/numbering": "0.1.1",
|
|
47
|
+
"@mostajs/stocks": "0.5.0"
|
|
48
|
+
},
|
|
49
|
+
"mostajs": {
|
|
50
|
+
"niveau": "N1",
|
|
51
|
+
"nature": "generique",
|
|
52
|
+
"reutilisabilite": "transverse",
|
|
53
|
+
"depend_de": [],
|
|
54
|
+
"question": "Que commander, à qui, et qu'en a-t-on reçu ?",
|
|
55
|
+
"forme": "moteur",
|
|
56
|
+
"entites": [
|
|
57
|
+
"CommandeAchat",
|
|
58
|
+
"ReceptionAchat"
|
|
59
|
+
],
|
|
60
|
+
"verbes": [
|
|
61
|
+
"proposer",
|
|
62
|
+
"creer",
|
|
63
|
+
"envoyer",
|
|
64
|
+
"recevoir",
|
|
65
|
+
"solder",
|
|
66
|
+
"annuler"
|
|
67
|
+
],
|
|
68
|
+
"interop": [
|
|
69
|
+
"point de commande et stock de sécurité (méthode classique de réapprovisionnement, politique (s, S))",
|
|
70
|
+
"montants en entiers dans l'unité monétaire (aucun flottant)",
|
|
71
|
+
"contrat de dépôt à prédicat { create, findById, update, find } (@mostajs/repository), avec version optimiste"
|
|
72
|
+
],
|
|
73
|
+
"ne_fait_pas": [
|
|
74
|
+
"aucun mouvement ni niveau de stock → @mostajs/stocks (port stock injecté)",
|
|
75
|
+
"aucun référentiel de fournisseurs ni de références → @mostajs/fournisseurs (port injecté)",
|
|
76
|
+
"aucune facture d'achat ni écriture comptable → @mostajs/compta",
|
|
77
|
+
"aucune numérotation propre → @mostajs/numbering (port numeroter)",
|
|
78
|
+
"aucune recherche d'offres ni comparaison de prix → @mostajs/sourcing",
|
|
79
|
+
"aucun bon de commande en PDF ni envoi au fournisseur → @mostajs/file-export, @mostajs/mailer",
|
|
80
|
+
"aucune attribution de permission à un rôle → @mostajs/rbac (l'administrateur)"
|
|
81
|
+
]
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// @mostajs/achats — adaptateurs des ports aux API RÉELLES des modules voisins.
|
|
2
|
+
// @mostajs/fournisseurs 0.2.0 n'en a pas besoin : `parId` et `fournisseursPourMatiere` s'appellent tels quels.
|
|
3
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
const ms = (t) => (t instanceof Date ? t.getTime() : typeof t === 'number' ? t : new Date(t).getTime());
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Port stock depuis l'objet rendu par createStocks() de @mostajs/stocks 0.5.0.
|
|
9
|
+
* entrer → stocks.movements.in(articleId, { qty, amount, ref, by, lot, expiry })
|
|
10
|
+
* disponible → stocks.levels.of(articleId).free (disponible non réservé)
|
|
11
|
+
* consommation → sorties (kind 'out') et consommations de transformation (lignes négatives) dans [depuis, jusqua]
|
|
12
|
+
*/
|
|
13
|
+
export function portStocks(stocks) {
|
|
14
|
+
return {
|
|
15
|
+
async entrer({ articleId, quantite, montant, ref, par, lot = null, peremption = null }) {
|
|
16
|
+
const m = await stocks.movements.in(articleId, { qty: quantite, amount: montant, ref, by: par ?? null, lot, expiry: peremption });
|
|
17
|
+
return { id: m?.id ?? null };
|
|
18
|
+
},
|
|
19
|
+
async disponible(articleId) {
|
|
20
|
+
const n = await stocks.levels.of(articleId);
|
|
21
|
+
return n.free ?? n.available ?? n.qty;
|
|
22
|
+
},
|
|
23
|
+
async consommation(articleId, { depuis, jusqua }) {
|
|
24
|
+
const de = ms(depuis); const a = ms(jusqua);
|
|
25
|
+
let total = 0;
|
|
26
|
+
for (const m of await stocks.movements.list({ articleId })) {
|
|
27
|
+
const t = ms(m.at ?? m.createdAt);
|
|
28
|
+
if (!(t >= de && t <= a)) continue;
|
|
29
|
+
if (m.kind === 'out' && m.articleId === articleId) total += Number(m.qty) || 0;
|
|
30
|
+
else if (m.kind === 'transform') for (const l of m.lines || []) if (l.articleId === articleId && l.qty < 0) total += -l.qty;
|
|
31
|
+
}
|
|
32
|
+
return total;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Port de numérotation depuis @mostajs/numbering 0.1.1 : la séquence `nom` est définie par l'application
|
|
39
|
+
* (format pris dans ses Paramètres), par exemple numbering.define({ name: 'commande-achat', format: '[BC]-YYYY-NNNN', resetEvery: 'year' }).
|
|
40
|
+
*/
|
|
41
|
+
export function portNumerotation(numbering, { nom = 'commande-achat' } = {}) {
|
|
42
|
+
return ({ le }) => numbering.next(nom, { date: new Date(le) });
|
|
43
|
+
}
|
package/src/codes.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @mostajs/achats — vocabulaire fermé des erreurs, avec leur libellé français.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
export const LIBELLES = Object.freeze({
|
|
5
|
+
CONFIG_INVALIDE: 'Configuration du module invalide (dépôts, ports, horloge).',
|
|
6
|
+
PORT_ABSENT: 'Port requis non branché pour cette opération.',
|
|
7
|
+
DONNEES_INVALIDES: 'Données invalides.',
|
|
8
|
+
QUANTITE_INVALIDE: 'Quantité invalide : un entier strictement positif est attendu.',
|
|
9
|
+
MONTANT_INVALIDE: 'Montant invalide : un entier positif ou nul, dans l\'unité monétaire, est attendu.',
|
|
10
|
+
LIGNES_VIDES: 'Une commande porte au moins une ligne.',
|
|
11
|
+
LIGNE_EN_DOUBLE: 'La même ligne apparaît deux fois.',
|
|
12
|
+
LIGNE_INCONNUE: 'Cette ligne n\'existe pas dans la commande.',
|
|
13
|
+
FOURNISSEUR_INCONNU: 'Fournisseur inconnu du référentiel.',
|
|
14
|
+
FOURNISSEUR_INACTIF: 'Fournisseur désactivé dans le référentiel.',
|
|
15
|
+
COMMANDE_INCONNUE: 'Commande inconnue.',
|
|
16
|
+
COMMANDE_NON_MODIFIABLE: 'Seul un brouillon se modifie.',
|
|
17
|
+
COMMANDE_NON_ENVOYEE: 'La commande n\'a pas été envoyée : rien ne peut être reçu.',
|
|
18
|
+
COMMANDE_SOLDEE: 'La commande est soldée.',
|
|
19
|
+
COMMANDE_ANNULEE: 'La commande est annulée.',
|
|
20
|
+
TRANSITION_INTERDITE: 'Cette opération n\'est pas permise dans l\'état de la commande.',
|
|
21
|
+
ANNULATION_IMPOSSIBLE: 'Une commande déjà reçue en partie ne s\'annule pas : elle se solde.',
|
|
22
|
+
MOTIF_REQUIS: 'Un motif est requis.',
|
|
23
|
+
RECEPTION_VIDE: 'Une réception porte au moins une ligne.',
|
|
24
|
+
RECEPTION_EXCEDENTAIRE: 'Quantité reçue au-delà du reste à recevoir.',
|
|
25
|
+
RECEPTION_INCONNUE: 'Réception inconnue.',
|
|
26
|
+
ENTREE_STOCK_ECHOUEE: 'L\'entrée en stock a échoué ; la réception est à reprendre.',
|
|
27
|
+
CONFLIT_VERSION: 'La commande a changé entre-temps ; relire et recommencer.',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export const CODES = Object.freeze(Object.fromEntries(Object.keys(LIBELLES).map((c) => [c, c])));
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// @mostajs/achats — dépôt en mémoire : le contrat à prédicat, avec version optimiste.
|
|
2
|
+
// Sert aux essais, aux démonstrations, et convient aussi aux dépôts de @mostajs/stocks et @mostajs/fournisseurs.
|
|
3
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Contrat (que tout dépôt en base doit tenir) :
|
|
7
|
+
* create(doc) → doc (doc.id fourni ; sinon tiré)
|
|
8
|
+
* findById(id) → doc | null
|
|
9
|
+
* find(predicat) → doc[] (predicat : une FONCTION)
|
|
10
|
+
* update(id, patch, { version }?) → doc | null
|
|
11
|
+
* null si l'id est inconnu, OU si `version` est donnée et diffère de la version stockée
|
|
12
|
+
* (en base : UPDATE … WHERE id = ? AND version = ?). Le patch porte la nouvelle version.
|
|
13
|
+
* delete(id) → boolean (facultatif pour @mostajs/achats)
|
|
14
|
+
* Les documents rendus sont des COPIES : les modifier ne touche pas au dépôt.
|
|
15
|
+
*/
|
|
16
|
+
export function depotMemoire() {
|
|
17
|
+
const docs = new Map();
|
|
18
|
+
const copie = (d) => structuredClone(d);
|
|
19
|
+
return {
|
|
20
|
+
async create(doc) {
|
|
21
|
+
const d = copie(doc);
|
|
22
|
+
if (d.id === undefined || d.id === null) d.id = globalThis.crypto.randomUUID();
|
|
23
|
+
if (docs.has(d.id)) throw new Error(`depotMemoire : l'identifiant « ${d.id} » existe déjà`);
|
|
24
|
+
docs.set(d.id, d);
|
|
25
|
+
return copie(d);
|
|
26
|
+
},
|
|
27
|
+
async findById(id) { return docs.has(id) ? copie(docs.get(id)) : null; },
|
|
28
|
+
async find(predicat) { return [...docs.values()].map(copie).filter((d) => predicat(d)); },
|
|
29
|
+
async update(id, patch, options = {}) {
|
|
30
|
+
const avant = docs.get(id);
|
|
31
|
+
if (!avant) return null;
|
|
32
|
+
if (options && options.version !== undefined && avant.version !== options.version) return null;
|
|
33
|
+
const apres = { ...avant, ...copie(patch), id };
|
|
34
|
+
docs.set(id, apres);
|
|
35
|
+
return copie(apres);
|
|
36
|
+
},
|
|
37
|
+
async delete(id) { return docs.delete(id); },
|
|
38
|
+
};
|
|
39
|
+
}
|
package/src/entiers.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// @mostajs/achats — arithmétique entière : quantités et montants, sans flottant.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
3
|
+
import { lever } from './erreur.mjs';
|
|
4
|
+
|
|
5
|
+
export const estEntierPositif = (v) => Number.isSafeInteger(v) && v > 0;
|
|
6
|
+
export const estEntierPositifOuNul = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
7
|
+
|
|
8
|
+
/** Produit d'entiers sûrs ; lève `code` si le résultat sort des entiers sûrs. */
|
|
9
|
+
export function produit(a, b, code, champ) {
|
|
10
|
+
const p = a * b;
|
|
11
|
+
if (!Number.isSafeInteger(p)) lever(code, `${champ} : dépasse les entiers sûrs`, { champ });
|
|
12
|
+
return p;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Somme d'entiers sûrs ; lève `code` en cas de dépassement. */
|
|
16
|
+
export function somme(valeurs, code, champ) {
|
|
17
|
+
let s = 0;
|
|
18
|
+
for (const v of valeurs) { s += v; if (!Number.isSafeInteger(s)) lever(code, `${champ} : dépasse les entiers sûrs`, { champ }); }
|
|
19
|
+
return s;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** ⌈a / b⌉ pour a ≥ 0, b > 0, entiers. */
|
|
23
|
+
export const plafond = (a, b) => Math.floor(a / b) + (a % b === 0 ? 0 : 1);
|
package/src/erreur.mjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// @mostajs/achats — une seule classe d'erreur, à vocabulaire fermé.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
3
|
+
import { LIBELLES } from './codes.mjs';
|
|
4
|
+
|
|
5
|
+
export class ErreurAchats extends Error {
|
|
6
|
+
/**
|
|
7
|
+
* @param {string} code un code de CODES (sinon : erreur de programmation, levée telle quelle)
|
|
8
|
+
* @param {string} [message] défaut : le libellé français du code
|
|
9
|
+
* @param {object} [details] données utiles à l'appelant (lignes en cause, identifiants)
|
|
10
|
+
*/
|
|
11
|
+
constructor(code, message, details) {
|
|
12
|
+
if (!Object.prototype.hasOwnProperty.call(LIBELLES, code)) throw new TypeError(`ErreurAchats : code inconnu « ${code} »`);
|
|
13
|
+
super(message || LIBELLES[code]);
|
|
14
|
+
this.name = 'ErreurAchats';
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.details = details ?? null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Raccourci : lever une ErreurAchats. */
|
|
21
|
+
export const lever = (code, message, details) => { throw new ErreurAchats(code, message, details); };
|
package/src/etats.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @mostajs/achats — états d'une commande fournisseur et transitions permises.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
3
|
+
import { lever } from './erreur.mjs';
|
|
4
|
+
|
|
5
|
+
export const ETATS = Object.freeze(['brouillon', 'envoyee', 'recue_partiellement', 'soldee', 'annulee']);
|
|
6
|
+
|
|
7
|
+
/** Pour chaque opération, les états de départ permis. */
|
|
8
|
+
export const TRANSITIONS = Object.freeze({
|
|
9
|
+
modifier: Object.freeze(['brouillon']),
|
|
10
|
+
envoyer: Object.freeze(['brouillon']),
|
|
11
|
+
recevoir: Object.freeze(['envoyee', 'recue_partiellement']),
|
|
12
|
+
solder: Object.freeze(['recue_partiellement']),
|
|
13
|
+
annuler: Object.freeze(['brouillon', 'envoyee']),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Vérifie que `commande` permet `operation`, sinon lève l'erreur la plus parlante :
|
|
18
|
+
* une commande close nomme son état ; sinon un code propre à l'opération ; sinon TRANSITION_INTERDITE.
|
|
19
|
+
*/
|
|
20
|
+
export function exigerEtat(commande, operation) {
|
|
21
|
+
const { etat } = commande;
|
|
22
|
+
if (TRANSITIONS[operation].includes(etat)) return;
|
|
23
|
+
const details = { commandeId: commande.id, etat, operation };
|
|
24
|
+
if (etat === 'soldee') lever('COMMANDE_SOLDEE', undefined, details);
|
|
25
|
+
if (etat === 'annulee') lever('COMMANDE_ANNULEE', undefined, details);
|
|
26
|
+
if (operation === 'modifier') lever('COMMANDE_NON_MODIFIABLE', undefined, details);
|
|
27
|
+
if (operation === 'recevoir' && etat === 'brouillon') lever('COMMANDE_NON_ENVOYEE', undefined, details);
|
|
28
|
+
if (operation === 'annuler' && etat === 'recue_partiellement') lever('ANNULATION_IMPOSSIBLE', undefined, details);
|
|
29
|
+
lever('TRANSITION_INTERDITE', `« ${operation} » n'est pas permis sur une commande « ${etat} »`, details);
|
|
30
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @mostajs/achats — entrée du paquet.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
3
|
+
export { CODES, LIBELLES } from './codes.mjs';
|
|
4
|
+
export { ErreurAchats } from './erreur.mjs';
|
|
5
|
+
export { ETATS, TRANSITIONS } from './etats.mjs';
|
|
6
|
+
export { PERMISSIONS, PERMISSION_PAR_OPERATION } from './permissions.mjs';
|
|
7
|
+
export { calculerQuantite } from './proposition.mjs';
|
|
8
|
+
export { creerAchats } from './service.mjs';
|
|
9
|
+
export { depotMemoire } from './depot-memoire.mjs';
|
|
10
|
+
export { portStocks, portNumerotation } from './adaptateurs.mjs';
|
|
11
|
+
export { schemaCommandeAchat, schemaReceptionAchat } from './schemas.mjs';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @mostajs/achats — permissions CONTRIBUÉES par le module (domaine:action, deux-points).
|
|
2
|
+
// Le module ne les attribue à aucun rôle : l'administrateur coche la matrice (@mostajs/rbac).
|
|
3
|
+
// Il ne les contrôle pas non plus : l'application vérifie le droit avant d'appeler l'opération.
|
|
4
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
5
|
+
|
|
6
|
+
export const PERMISSIONS = Object.freeze({
|
|
7
|
+
'achats:lire': 'Consulter les commandes fournisseurs et les réceptions',
|
|
8
|
+
'achats:proposer': 'Calculer les quantités à commander',
|
|
9
|
+
'achats:commander': 'Préparer et modifier une commande fournisseur',
|
|
10
|
+
'achats:envoyer': 'Envoyer une commande au fournisseur',
|
|
11
|
+
'achats:recevoir': 'Enregistrer une réception et son entrée en stock',
|
|
12
|
+
'achats:cloturer': 'Annuler ou solder une commande',
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/** La permission que l'application vérifie avant chaque opération du service. */
|
|
16
|
+
export const PERMISSION_PAR_OPERATION = Object.freeze({
|
|
17
|
+
creer: 'achats:commander',
|
|
18
|
+
modifier: 'achats:commander',
|
|
19
|
+
brouillonsDepuis: 'achats:commander',
|
|
20
|
+
envoyer: 'achats:envoyer',
|
|
21
|
+
recevoir: 'achats:recevoir',
|
|
22
|
+
reprendreEntrees: 'achats:recevoir',
|
|
23
|
+
solder: 'achats:cloturer',
|
|
24
|
+
annuler: 'achats:cloturer',
|
|
25
|
+
lire: 'achats:lire',
|
|
26
|
+
lister: 'achats:lire',
|
|
27
|
+
receptionsDe: 'achats:lire',
|
|
28
|
+
aReprendre: 'achats:lire',
|
|
29
|
+
enCommande: 'achats:lire',
|
|
30
|
+
proposer: 'achats:proposer',
|
|
31
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// @mostajs/achats — quantité proposée : point de commande, stock de sécurité, couverture, colis, minimum.
|
|
2
|
+
// Fonction PURE, en entiers : la consommation est une quantité sur une durée, chaque division est un plafond.
|
|
3
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
4
|
+
import { lever } from './erreur.mjs';
|
|
5
|
+
import { estEntierPositif, estEntierPositifOuNul, plafond } from './entiers.mjs';
|
|
6
|
+
|
|
7
|
+
const exiger = (ok, champ, valeur) => { if (!ok) lever('DONNEES_INVALIDES', `${champ} : valeur invalide`, { champ, valeur }); };
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {object} p
|
|
11
|
+
* @param {number} p.disponible stock disponible (unités de stock, entier ≥ 0)
|
|
12
|
+
* @param {number} [p.enCommande=0] reste à recevoir sur les commandes ouvertes
|
|
13
|
+
* @param {{quantite:number, jours:number}} p.consommation consommé sur la fenêtre
|
|
14
|
+
* @param {number} p.delaiJours délai de livraison du fournisseur
|
|
15
|
+
* @param {number} [p.stockSecurite] en unités ; exclusif de stockSecuriteJours
|
|
16
|
+
* @param {number} [p.stockSecuriteJours] en jours de consommation
|
|
17
|
+
* @param {number} [p.couvertureJours=0] jours de consommation couverts au-delà du point de commande
|
|
18
|
+
* @param {number} [p.minimumQuantite=0] minimum de commande, en unités
|
|
19
|
+
* @param {number} [p.multiple=1] unités par colis
|
|
20
|
+
*/
|
|
21
|
+
export function calculerQuantite(p) {
|
|
22
|
+
exiger(p && typeof p === 'object', 'paramètres', p);
|
|
23
|
+
const { disponible, enCommande = 0, consommation, delaiJours, stockSecurite, stockSecuriteJours,
|
|
24
|
+
couvertureJours = 0, minimumQuantite = 0, multiple = 1 } = p;
|
|
25
|
+
exiger(estEntierPositifOuNul(disponible), 'disponible', disponible);
|
|
26
|
+
exiger(estEntierPositifOuNul(enCommande), 'enCommande', enCommande);
|
|
27
|
+
exiger(consommation && typeof consommation === 'object', 'consommation', consommation);
|
|
28
|
+
exiger(estEntierPositifOuNul(consommation.quantite), 'consommation.quantite', consommation.quantite);
|
|
29
|
+
exiger(estEntierPositif(consommation.jours), 'consommation.jours', consommation.jours);
|
|
30
|
+
exiger(estEntierPositifOuNul(delaiJours), 'delaiJours', delaiJours);
|
|
31
|
+
exiger(!(stockSecurite !== undefined && stockSecuriteJours !== undefined), 'stockSecurite', 'stockSecurite et stockSecuriteJours sont exclusifs');
|
|
32
|
+
if (stockSecurite !== undefined) exiger(estEntierPositifOuNul(stockSecurite), 'stockSecurite', stockSecurite);
|
|
33
|
+
if (stockSecuriteJours !== undefined) exiger(estEntierPositifOuNul(stockSecuriteJours), 'stockSecuriteJours', stockSecuriteJours);
|
|
34
|
+
exiger(estEntierPositifOuNul(couvertureJours), 'couvertureJours', couvertureJours);
|
|
35
|
+
exiger(estEntierPositifOuNul(minimumQuantite), 'minimumQuantite', minimumQuantite);
|
|
36
|
+
exiger(estEntierPositif(multiple), 'multiple', multiple);
|
|
37
|
+
|
|
38
|
+
const { quantite: q, jours } = consommation;
|
|
39
|
+
const demandeSur = (j, champ) => {
|
|
40
|
+
const n = q * j;
|
|
41
|
+
exiger(Number.isSafeInteger(n), champ, n);
|
|
42
|
+
return plafond(n, jours);
|
|
43
|
+
};
|
|
44
|
+
const demandePendantDelai = demandeSur(delaiJours, 'delaiJours');
|
|
45
|
+
const ss = stockSecurite !== undefined ? stockSecurite : stockSecuriteJours !== undefined ? demandeSur(stockSecuriteJours, 'stockSecuriteJours') : 0;
|
|
46
|
+
const pointDeCommande = demandePendantDelai + ss;
|
|
47
|
+
const position = disponible + enCommande;
|
|
48
|
+
const niveauCible = pointDeCommande + demandeSur(couvertureJours, 'couvertureJours');
|
|
49
|
+
for (const [champ, v] of [['pointDeCommande', pointDeCommande], ['position', position], ['niveauCible', niveauCible]]) exiger(Number.isSafeInteger(v), champ, v);
|
|
50
|
+
|
|
51
|
+
const declenche = position <= pointDeCommande;
|
|
52
|
+
const quantiteBrute = declenche ? Math.max(niveauCible - position, 0) : 0;
|
|
53
|
+
const arrondi = (x) => plafond(x, multiple) * multiple;
|
|
54
|
+
const quantite = declenche ? Math.max(arrondi(Math.max(quantiteBrute, 1)), arrondi(minimumQuantite)) : 0;
|
|
55
|
+
exiger(Number.isSafeInteger(quantite), 'quantite', quantite);
|
|
56
|
+
return { declenche, position, demandePendantDelai, stockSecurite: ss, pointDeCommande, niveauCible, quantiteBrute, multiple, quantite, colis: quantite / multiple };
|
|
57
|
+
}
|
package/src/register.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @mostajs/achats — register(registry) : le module CONTRIBUE ses schémas et ses permissions au socle,
|
|
2
|
+
// en objet simple (aucun import de module-contract), de même forme que @mostajs/stocks/register.
|
|
3
|
+
// Aucune permission n'est attribuée à un rôle : l'administrateur coche la matrice.
|
|
4
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
5
|
+
import { PERMISSIONS } from './permissions.mjs';
|
|
6
|
+
import { schemaCommandeAchat, schemaReceptionAchat } from './schemas.mjs';
|
|
7
|
+
|
|
8
|
+
export function register(registry) {
|
|
9
|
+
registry.register({
|
|
10
|
+
manifest: {
|
|
11
|
+
name: 'achats', package: '@mostajs/achats', version: '0.1.0', type: 'business', priority: 110,
|
|
12
|
+
displayName: 'Achats', description: 'Commandes fournisseurs, quantités proposées, réceptions.',
|
|
13
|
+
icon: 'ShoppingCart', register: './src/register.mjs',
|
|
14
|
+
},
|
|
15
|
+
permissions: {
|
|
16
|
+
permissions: { ...PERMISSIONS },
|
|
17
|
+
definitions: Object.entries(PERMISSIONS).map(([code, name]) => ({ code, name, category: 'achats' })),
|
|
18
|
+
categories: [{ name: 'achats', label: 'Achats', description: 'Commandes fournisseurs et réceptions', order: 45, system: false }],
|
|
19
|
+
},
|
|
20
|
+
schemas: [schemaCommandeAchat, schemaReceptionAchat].map((s) => ({ name: s.name, schema: s })),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export default register;
|
package/src/schemas.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// @mostajs/achats — descriptions d'entités (forme EntitySchema de @mostajs/orm), en objets simples.
|
|
2
|
+
// Les montants et quantités sont des entiers : @mostajs/orm n'a pas de type entier, le module le garantit.
|
|
3
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
4
|
+
import { ETATS } from './etats.mjs';
|
|
5
|
+
|
|
6
|
+
export const schemaCommandeAchat = Object.freeze({
|
|
7
|
+
name: 'CommandeAchat',
|
|
8
|
+
collection: 'achats_commandes',
|
|
9
|
+
fields: {
|
|
10
|
+
numero: { type: 'string', default: null },
|
|
11
|
+
fournisseurId: { type: 'string', required: true },
|
|
12
|
+
etat: { type: 'string', required: true, enum: [...ETATS] },
|
|
13
|
+
devise: { type: 'string', default: null },
|
|
14
|
+
reference: { type: 'string', default: null },
|
|
15
|
+
note: { type: 'text', default: null },
|
|
16
|
+
// [{ ligne, articleId, code, libelle, parColis, quantite, prixUnitaire, montant, quantiteRecue }]
|
|
17
|
+
lignes: { type: 'json', required: true },
|
|
18
|
+
total: { type: 'number', required: true },
|
|
19
|
+
creeLe: { type: 'date' },
|
|
20
|
+
creePar: { type: 'string', default: null },
|
|
21
|
+
envoyeeLe: { type: 'date', default: null },
|
|
22
|
+
soldeeLe: { type: 'date', default: null },
|
|
23
|
+
annuleeLe: { type: 'date', default: null },
|
|
24
|
+
motifCloture: { type: 'text', default: null },
|
|
25
|
+
version: { type: 'number', required: true },
|
|
26
|
+
historique: { type: 'json', default: [] },
|
|
27
|
+
},
|
|
28
|
+
relations: {},
|
|
29
|
+
indexes: [
|
|
30
|
+
{ fields: { numero: 'asc' }, unique: true, sparse: true },
|
|
31
|
+
{ fields: { fournisseurId: 'asc' } },
|
|
32
|
+
{ fields: { etat: 'asc' } },
|
|
33
|
+
],
|
|
34
|
+
timestamps: true,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export const schemaReceptionAchat = Object.freeze({
|
|
38
|
+
name: 'ReceptionAchat',
|
|
39
|
+
collection: 'achats_receptions',
|
|
40
|
+
fields: {
|
|
41
|
+
commandeId: { type: 'string', required: true },
|
|
42
|
+
numeroCommande: { type: 'string', default: null },
|
|
43
|
+
fournisseurId: { type: 'string' },
|
|
44
|
+
le: { type: 'date', required: true },
|
|
45
|
+
par: { type: 'string', default: null },
|
|
46
|
+
bonLivraison: { type: 'string', default: null },
|
|
47
|
+
// [{ ligne, articleId, quantite, quantiteStock, montant, excedent, lot, peremption, entree, mouvementId }]
|
|
48
|
+
lignes: { type: 'json', required: true },
|
|
49
|
+
etat: { type: 'string', required: true, enum: ['a_entrer', 'entree'] },
|
|
50
|
+
creeLe: { type: 'date' },
|
|
51
|
+
},
|
|
52
|
+
relations: {},
|
|
53
|
+
indexes: [{ fields: { commandeId: 'asc' } }, { fields: { etat: 'asc' } }],
|
|
54
|
+
timestamps: true,
|
|
55
|
+
});
|
package/src/service.mjs
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// @mostajs/achats — le service : cycle de vie d'une commande fournisseur, réception, quantités proposées.
|
|
2
|
+
// Tout est injecté : dépôts (contrat à prédicat, version optimiste), ports stock / fournisseurs / numérotation,
|
|
3
|
+
// horloge, générateur d'identifiants, réglages. Aucune lecture d'environnement, aucune écriture sur la console.
|
|
4
|
+
// @author Dr Hamid MADANI <drmdh@msn.com> · AGPL-3.0-or-later
|
|
5
|
+
import { ErreurAchats, lever } from './erreur.mjs';
|
|
6
|
+
import { ETATS, exigerEtat } from './etats.mjs';
|
|
7
|
+
import { estEntierPositif, estEntierPositifOuNul, produit, somme } from './entiers.mjs';
|
|
8
|
+
import { calculerQuantite } from './proposition.mjs';
|
|
9
|
+
|
|
10
|
+
const JOUR = 86400e3;
|
|
11
|
+
const REGLAGES_DEFAUT = Object.freeze({ excedent: 'refuser', fenetreJours: 30, couvertureJours: 30 });
|
|
12
|
+
const POLITIQUES_EXCEDENT = ['refuser', 'accepter'];
|
|
13
|
+
const OUVERTES = ['envoyee', 'recue_partiellement'];
|
|
14
|
+
|
|
15
|
+
const estFonction = (f) => typeof f === 'function';
|
|
16
|
+
const texte = (v) => (v === undefined || v === null ? null : String(v));
|
|
17
|
+
const iso = (t) => new Date(t).toISOString();
|
|
18
|
+
|
|
19
|
+
function verifierConfig({ depots, stock, fournisseurs, numeroter, horloge, id }) {
|
|
20
|
+
const depotOk = (d) => d && ['create', 'findById', 'update', 'find'].every((m) => estFonction(d[m]));
|
|
21
|
+
if (!depots || !depotOk(depots.commandes) || !depotOk(depots.receptions))
|
|
22
|
+
lever('CONFIG_INVALIDE', 'depots.commandes et depots.receptions : { create, findById, update, find } attendus');
|
|
23
|
+
const portOk = (p, methodes) => p === undefined || p === null || (typeof p === 'object' && methodes.every((m) => p[m] === undefined || estFonction(p[m])));
|
|
24
|
+
if (!portOk(stock, ['entrer', 'disponible', 'consommation'])) lever('CONFIG_INVALIDE', 'stock : { entrer, disponible, consommation } (fonctions)');
|
|
25
|
+
if (!portOk(fournisseurs, ['parId', 'fournisseursPourMatiere'])) lever('CONFIG_INVALIDE', 'fournisseurs : { parId, fournisseursPourMatiere } (fonctions)');
|
|
26
|
+
for (const [nom, f] of [['numeroter', numeroter], ['horloge', horloge], ['id', id]])
|
|
27
|
+
if (f !== undefined && f !== null && !estFonction(f)) lever('CONFIG_INVALIDE', `${nom} : une fonction est attendue`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} options
|
|
32
|
+
* @param {{commandes: object, receptions: object}} options.depots
|
|
33
|
+
* @param {{entrer?: Function, disponible?: Function, consommation?: Function}} [options.stock]
|
|
34
|
+
* @param {{parId?: Function, fournisseursPourMatiere?: Function}} [options.fournisseurs]
|
|
35
|
+
* @param {(ctx: {type: string, le: number, fournisseurId: string}) => Promise<string>|string} [options.numeroter]
|
|
36
|
+
* @param {() => number|Date} [options.horloge]
|
|
37
|
+
* @param {() => string} [options.id]
|
|
38
|
+
* @param {object|(() => object)} [options.reglages] { excedent, fenetreJours, couvertureJours }
|
|
39
|
+
*/
|
|
40
|
+
export function creerAchats(options = {}) {
|
|
41
|
+
verifierConfig(options);
|
|
42
|
+
const { depots, stock = null, fournisseurs = null, numeroter = null } = options;
|
|
43
|
+
const horloge = options.horloge ?? Date.now;
|
|
44
|
+
const nouvelId = options.id ?? (() => globalThis.crypto.randomUUID());
|
|
45
|
+
const maintenant = () => {
|
|
46
|
+
const t = horloge();
|
|
47
|
+
const n = t instanceof Date ? t.getTime() : t;
|
|
48
|
+
if (!Number.isFinite(n)) lever('CONFIG_INVALIDE', 'horloge : un instant (ms ou Date) est attendu');
|
|
49
|
+
return n;
|
|
50
|
+
};
|
|
51
|
+
const reglages = () => {
|
|
52
|
+
const r = typeof options.reglages === 'function' ? options.reglages() : options.reglages;
|
|
53
|
+
return { ...REGLAGES_DEFAUT, ...(r || {}) };
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// ── lectures internes ────────────────────────────────────────────────────────────────────
|
|
57
|
+
async function charger(id) {
|
|
58
|
+
const c = await depots.commandes.findById(id);
|
|
59
|
+
if (!c) lever('COMMANDE_INCONNUE', undefined, { commandeId: id });
|
|
60
|
+
return c;
|
|
61
|
+
}
|
|
62
|
+
/** Écrit sous version : le patch porte version + 1 ; un dépôt qui rend null signale un conflit. */
|
|
63
|
+
async function ecrire(c, patch) {
|
|
64
|
+
const r = await depots.commandes.update(c.id, { ...patch, version: c.version + 1 }, { version: c.version });
|
|
65
|
+
if (!r) lever('CONFLIT_VERSION', undefined, { commandeId: c.id, version: c.version });
|
|
66
|
+
return r;
|
|
67
|
+
}
|
|
68
|
+
const trace = (c, { action, par, vers, ...extra }) => [...(c.historique || []), { le: iso(maintenant()), par: par ?? null, action, de: c.etat, vers, ...extra }];
|
|
69
|
+
const reliquatsDe = (lignes) => lignes.filter((l) => l.quantiteRecue < l.quantite).map((l) => ({ ligne: l.ligne, articleId: l.articleId, reste: l.quantite - l.quantiteRecue }));
|
|
70
|
+
|
|
71
|
+
async function verifierFournisseur(fournisseurId) {
|
|
72
|
+
if (!fournisseurs || !estFonction(fournisseurs.parId)) return;
|
|
73
|
+
const f = await fournisseurs.parId(fournisseurId);
|
|
74
|
+
if (!f) lever('FOURNISSEUR_INCONNU', undefined, { fournisseurId });
|
|
75
|
+
if (f.actif === false) lever('FOURNISSEUR_INACTIF', undefined, { fournisseurId });
|
|
76
|
+
}
|
|
77
|
+
async function referencesDe(articleId) {
|
|
78
|
+
if (!fournisseurs || !estFonction(fournisseurs.fournisseursPourMatiere)) return [];
|
|
79
|
+
return (await fournisseurs.fournisseursPourMatiere(articleId)) || [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Valide et complète les lignes d'une commande ; rend { lignes, total }. */
|
|
83
|
+
async function normaliserLignes(fournisseurId, entree) {
|
|
84
|
+
if (!Array.isArray(entree) || entree.length === 0) lever('LIGNES_VIDES');
|
|
85
|
+
const vus = new Set();
|
|
86
|
+
const brutes = entree.map((l, i) => {
|
|
87
|
+
const n = i + 1;
|
|
88
|
+
if (!l || typeof l !== 'object' || typeof l.articleId !== 'string' || !l.articleId.trim()) lever('DONNEES_INVALIDES', `ligne ${n} : articleId requis`, { ligne: n });
|
|
89
|
+
if (!estEntierPositif(l.quantite)) lever('QUANTITE_INVALIDE', `ligne ${n} : quantite`, { ligne: n, quantite: l.quantite });
|
|
90
|
+
if (!estEntierPositifOuNul(l.prixUnitaire)) lever('MONTANT_INVALIDE', `ligne ${n} : prixUnitaire`, { ligne: n, prixUnitaire: l.prixUnitaire });
|
|
91
|
+
if (l.parColis !== undefined && l.parColis !== null && !estEntierPositif(l.parColis)) lever('QUANTITE_INVALIDE', `ligne ${n} : parColis`, { ligne: n, parColis: l.parColis });
|
|
92
|
+
if (vus.has(l.articleId)) lever('LIGNE_EN_DOUBLE', `article ${l.articleId} en double`, { articleId: l.articleId });
|
|
93
|
+
vus.add(l.articleId);
|
|
94
|
+
return l;
|
|
95
|
+
});
|
|
96
|
+
const lignes = [];
|
|
97
|
+
for (const [i, l] of brutes.entries()) {
|
|
98
|
+
const ref = (await referencesDe(l.articleId)).find((r) => r.fournisseurId === fournisseurId) ?? null;
|
|
99
|
+
const parColis = l.parColis ?? ref?.parColis ?? 1;
|
|
100
|
+
if (!estEntierPositif(parColis)) lever('QUANTITE_INVALIDE', `ligne ${i + 1} : parColis du référentiel`, { ligne: i + 1, parColis });
|
|
101
|
+
lignes.push({
|
|
102
|
+
ligne: i + 1, articleId: l.articleId, code: texte(l.code ?? ref?.code), libelle: texte(l.libelle ?? ref?.libelle), parColis,
|
|
103
|
+
quantite: l.quantite, prixUnitaire: l.prixUnitaire, montant: produit(l.quantite, l.prixUnitaire, 'MONTANT_INVALIDE', `ligne ${i + 1} : montant`), quantiteRecue: 0,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return { lignes, total: somme(lignes.map((l) => l.montant), 'MONTANT_INVALIDE', 'total') };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function dateDeReception(le, now) {
|
|
110
|
+
if (le === undefined || le === null) return now;
|
|
111
|
+
let t = NaN;
|
|
112
|
+
if (typeof le === 'number') t = le;
|
|
113
|
+
else if (le instanceof Date) t = le.getTime();
|
|
114
|
+
else if (typeof le === 'string' && /^\d{4}-\d{2}-\d{2}/.test(le)) t = Date.parse(le);
|
|
115
|
+
if (!Number.isFinite(t)) lever('DONNEES_INVALIDES', 'le : date de réception invalide', { le });
|
|
116
|
+
if (t > now) lever('DONNEES_INVALIDES', 'le : une réception ne peut pas être datée du futur', { le });
|
|
117
|
+
return t;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Entre en stock les lignes non encore entrées d'une réception ; la marque au fil de l'eau. */
|
|
121
|
+
async function entrerLignes(reception, ref) {
|
|
122
|
+
const lignes = reception.lignes.map((l) => ({ ...l }));
|
|
123
|
+
for (const l of lignes) {
|
|
124
|
+
if (l.entree) continue;
|
|
125
|
+
try {
|
|
126
|
+
const m = await stock.entrer({ articleId: l.articleId, quantite: l.quantiteStock, montant: l.montant, ref, cle: `${reception.id}:${l.ligne}`, par: reception.par, lot: l.lot, peremption: l.peremption });
|
|
127
|
+
l.entree = true;
|
|
128
|
+
l.mouvementId = m?.id ?? null;
|
|
129
|
+
} catch (e) {
|
|
130
|
+
await depots.receptions.update(reception.id, { lignes });
|
|
131
|
+
throw new ErreurAchats('ENTREE_STOCK_ECHOUEE', undefined, {
|
|
132
|
+
receptionId: reception.id, commandeId: reception.commandeId,
|
|
133
|
+
lignesNonEntrees: lignes.filter((x) => !x.entree).map((x) => x.ligne), cause: e?.message ?? String(e),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return depots.receptions.update(reception.id, { lignes, etat: 'entree' });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const quantiteEnCours = (commandes, articleId, calcul) => commandes
|
|
141
|
+
.flatMap((c) => c.lignes.filter((l) => l.articleId === articleId).map((l) => calcul(l)))
|
|
142
|
+
.reduce((s, n) => s + n, 0);
|
|
143
|
+
|
|
144
|
+
// ── le service ───────────────────────────────────────────────────────────────────────────
|
|
145
|
+
const service = {
|
|
146
|
+
/** Un brouillon. Lignes complétées (code, libellé, parColis) par le référentiel des fournisseurs. */
|
|
147
|
+
async creer({ fournisseurId, lignes, reference = null, note = null, devise = null, par = null } = {}) {
|
|
148
|
+
if (typeof fournisseurId !== 'string' || !fournisseurId.trim()) lever('DONNEES_INVALIDES', 'fournisseurId requis');
|
|
149
|
+
const n = await normaliserLignes(fournisseurId, lignes);
|
|
150
|
+
await verifierFournisseur(fournisseurId);
|
|
151
|
+
const le = iso(maintenant());
|
|
152
|
+
return depots.commandes.create({
|
|
153
|
+
id: nouvelId(), numero: null, fournisseurId, etat: 'brouillon', devise: texte(devise), reference: texte(reference), note: texte(note),
|
|
154
|
+
lignes: n.lignes, total: n.total, creeLe: le, creePar: par, envoyeeLe: null, soldeeLe: null, annuleeLe: null, motifCloture: null,
|
|
155
|
+
version: 1, historique: [{ le, par, action: 'creer', de: null, vers: 'brouillon' }],
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
/** Modifier un brouillon : lignes, référence, note, devise. */
|
|
160
|
+
async modifier(id, patch = {}, { par = null } = {}) {
|
|
161
|
+
const c = await charger(id);
|
|
162
|
+
exigerEtat(c, 'modifier');
|
|
163
|
+
const p = {};
|
|
164
|
+
if (patch.lignes !== undefined) Object.assign(p, await normaliserLignes(c.fournisseurId, patch.lignes));
|
|
165
|
+
for (const k of ['reference', 'note', 'devise']) if (patch[k] !== undefined) p[k] = texte(patch[k]);
|
|
166
|
+
return ecrire(c, { ...p, historique: trace(c, { action: 'modifier', par, vers: 'brouillon' }) });
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
/** Brouillon → envoyée. Le numéro est tiré ici : un brouillon abandonné n'en consomme aucun. */
|
|
170
|
+
async envoyer(id, { par = null } = {}) {
|
|
171
|
+
const c = await charger(id);
|
|
172
|
+
exigerEtat(c, 'envoyer');
|
|
173
|
+
const now = maintenant();
|
|
174
|
+
const numero = numeroter ? texte(await numeroter({ type: 'commande-achat', le: now, fournisseurId: c.fournisseurId })) : null;
|
|
175
|
+
return ecrire(c, { etat: 'envoyee', numero, envoyeeLe: iso(now), historique: trace(c, { action: 'envoyer', par, vers: 'envoyee' }) });
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Une livraison. lignes : [{ ligne | articleId, quantite, lot?, peremption? }].
|
|
180
|
+
* excedent : 'refuser' (défaut du réglage) | 'accepter'. Rend { commande, reception, excedents, reliquats }.
|
|
181
|
+
*/
|
|
182
|
+
async recevoir(id, { lignes, le, bonLivraison = null, excedent, par = null } = {}) {
|
|
183
|
+
if (!stock || !estFonction(stock.entrer)) lever('PORT_ABSENT', 'stock.entrer requis pour recevoir');
|
|
184
|
+
const c = await charger(id);
|
|
185
|
+
exigerEtat(c, 'recevoir');
|
|
186
|
+
const politique = excedent ?? reglages().excedent;
|
|
187
|
+
if (!POLITIQUES_EXCEDENT.includes(politique)) lever('DONNEES_INVALIDES', `excedent : ${POLITIQUES_EXCEDENT.join(' | ')}`, { excedent: politique });
|
|
188
|
+
const now = maintenant();
|
|
189
|
+
const date = dateDeReception(le, now);
|
|
190
|
+
if (!Array.isArray(lignes) || lignes.length === 0) lever('RECEPTION_VIDE');
|
|
191
|
+
|
|
192
|
+
const nouvelles = c.lignes.map((l) => ({ ...l }));
|
|
193
|
+
const vues = new Set();
|
|
194
|
+
const recues = [];
|
|
195
|
+
const trop = [];
|
|
196
|
+
for (const r of lignes) {
|
|
197
|
+
const cible = r && (r.ligne !== undefined ? nouvelles.find((l) => l.ligne === r.ligne) : r.articleId !== undefined ? nouvelles.find((l) => l.articleId === r.articleId) : null);
|
|
198
|
+
if (!cible) lever('LIGNE_INCONNUE', undefined, { ligne: r?.ligne ?? null, articleId: r?.articleId ?? null });
|
|
199
|
+
if (vues.has(cible.ligne)) lever('LIGNE_EN_DOUBLE', `ligne ${cible.ligne} reçue deux fois`, { ligne: cible.ligne });
|
|
200
|
+
vues.add(cible.ligne);
|
|
201
|
+
if (!estEntierPositif(r.quantite)) lever('QUANTITE_INVALIDE', `ligne ${cible.ligne} : quantite`, { ligne: cible.ligne, quantite: r.quantite });
|
|
202
|
+
const reste = Math.max(cible.quantite - cible.quantiteRecue, 0);
|
|
203
|
+
const ex = Math.max(r.quantite - reste, 0);
|
|
204
|
+
if (ex > 0 && politique === 'refuser') trop.push({ ligne: cible.ligne, articleId: cible.articleId, reste, recu: r.quantite });
|
|
205
|
+
recues.push({ cible, quantite: r.quantite, excedent: ex, lot: texte(r.lot), peremption: r.peremption ?? null });
|
|
206
|
+
}
|
|
207
|
+
if (trop.length) lever('RECEPTION_EXCEDENTAIRE', undefined, { commandeId: c.id, lignes: trop });
|
|
208
|
+
|
|
209
|
+
const receptionId = nouvelId();
|
|
210
|
+
const lignesReception = recues.map(({ cible, quantite, excedent: ex, lot, peremption }) => {
|
|
211
|
+
cible.quantiteRecue += quantite;
|
|
212
|
+
return {
|
|
213
|
+
ligne: cible.ligne, articleId: cible.articleId, quantite,
|
|
214
|
+
quantiteStock: produit(quantite, cible.parColis, 'QUANTITE_INVALIDE', `ligne ${cible.ligne} : quantité en stock`),
|
|
215
|
+
montant: produit(quantite, cible.prixUnitaire, 'MONTANT_INVALIDE', `ligne ${cible.ligne} : montant reçu`),
|
|
216
|
+
excedent: ex, lot, peremption, entree: false, mouvementId: null,
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
const etat = nouvelles.every((l) => l.quantiteRecue >= l.quantite) ? 'soldee' : 'recue_partiellement';
|
|
220
|
+
const commande = await ecrire(c, {
|
|
221
|
+
lignes: nouvelles, etat, ...(etat === 'soldee' ? { soldeeLe: iso(now) } : {}),
|
|
222
|
+
historique: trace(c, { action: 'recevoir', par, vers: etat, reception: receptionId }),
|
|
223
|
+
});
|
|
224
|
+
const reception = await depots.receptions.create({
|
|
225
|
+
id: receptionId, commandeId: c.id, numeroCommande: c.numero ?? null, fournisseurId: c.fournisseurId, le: iso(date), par,
|
|
226
|
+
bonLivraison: texte(bonLivraison), lignes: lignesReception, etat: 'a_entrer', creeLe: iso(now),
|
|
227
|
+
});
|
|
228
|
+
const entree = await entrerLignes(reception, `achat:${c.numero ?? c.id}`);
|
|
229
|
+
return {
|
|
230
|
+
commande, reception: entree,
|
|
231
|
+
excedents: lignesReception.filter((l) => l.excedent > 0).map((l) => ({ ligne: l.ligne, articleId: l.articleId, excedent: l.excedent })),
|
|
232
|
+
reliquats: reliquatsDe(nouvelles),
|
|
233
|
+
};
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
/** Après ENTREE_STOCK_ECHOUEE : entre les lignes restantes, et elles seules. */
|
|
237
|
+
async reprendreEntrees(receptionId) {
|
|
238
|
+
if (!stock || !estFonction(stock.entrer)) lever('PORT_ABSENT', 'stock.entrer requis pour reprendre une réception');
|
|
239
|
+
const r = await depots.receptions.findById(receptionId);
|
|
240
|
+
if (!r) lever('RECEPTION_INCONNUE', undefined, { receptionId });
|
|
241
|
+
if (r.etat === 'entree') return r;
|
|
242
|
+
return entrerLignes(r, `achat:${r.numeroCommande ?? r.commandeId}`);
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
/** Reçue en partie → soldée : le reliquat est abandonné, avec son motif. */
|
|
246
|
+
async solder(id, { motif, par = null } = {}) {
|
|
247
|
+
const c = await charger(id);
|
|
248
|
+
exigerEtat(c, 'solder');
|
|
249
|
+
if (typeof motif !== 'string' || !motif.trim()) lever('MOTIF_REQUIS');
|
|
250
|
+
return ecrire(c, {
|
|
251
|
+
etat: 'soldee', soldeeLe: iso(maintenant()), motifCloture: motif.trim(),
|
|
252
|
+
historique: trace(c, { action: 'solder', par, vers: 'soldee', motif: motif.trim(), reliquats: reliquatsDe(c.lignes) }),
|
|
253
|
+
});
|
|
254
|
+
},
|
|
255
|
+
|
|
256
|
+
/** Brouillon ou envoyée sans réception → annulée. */
|
|
257
|
+
async annuler(id, { motif, par = null } = {}) {
|
|
258
|
+
const c = await charger(id);
|
|
259
|
+
exigerEtat(c, 'annuler');
|
|
260
|
+
if (typeof motif !== 'string' || !motif.trim()) lever('MOTIF_REQUIS');
|
|
261
|
+
return ecrire(c, {
|
|
262
|
+
etat: 'annulee', annuleeLe: iso(maintenant()), motifCloture: motif.trim(),
|
|
263
|
+
historique: trace(c, { action: 'annuler', par, vers: 'annulee', motif: motif.trim() }),
|
|
264
|
+
});
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
async lire(id) { return (await depots.commandes.findById(id)) ?? null; },
|
|
268
|
+
|
|
269
|
+
async lister({ etat, fournisseurId, articleId } = {}) {
|
|
270
|
+
const etats = etat === undefined ? null : Array.isArray(etat) ? etat : [etat];
|
|
271
|
+
if (etats) for (const e of etats) if (!ETATS.includes(e)) lever('DONNEES_INVALIDES', `etat inconnu : ${e}`, { etat: e });
|
|
272
|
+
return depots.commandes.find((c) => (!etats || etats.includes(c.etat))
|
|
273
|
+
&& (fournisseurId === undefined || c.fournisseurId === fournisseurId)
|
|
274
|
+
&& (articleId === undefined || c.lignes.some((l) => l.articleId === articleId)));
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
async receptionsDe(commandeId) { return depots.receptions.find((r) => r.commandeId === commandeId); },
|
|
278
|
+
|
|
279
|
+
async aReprendre() { return depots.receptions.find((r) => r.etat === 'a_entrer'); },
|
|
280
|
+
|
|
281
|
+
/** Reste à recevoir sur les commandes ouvertes, en unités de stock. */
|
|
282
|
+
async enCommande(articleId) {
|
|
283
|
+
const ouvertes = await depots.commandes.find((c) => OUVERTES.includes(c.etat));
|
|
284
|
+
return quantiteEnCours(ouvertes, articleId, (l) => Math.max(l.quantite - l.quantiteRecue, 0) * l.parColis);
|
|
285
|
+
},
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Quantités proposées. articles : [{ articleId, delaiJours, fournisseurId?, stockSecurite? | stockSecuriteJours?,
|
|
289
|
+
* couvertureJours?, minimumQuantite?, parColis?, prixUnitaire?, fenetreJours? }]. Ne crée rien.
|
|
290
|
+
*/
|
|
291
|
+
async proposer({ articles } = {}) {
|
|
292
|
+
if (!stock || !estFonction(stock.disponible) || !estFonction(stock.consommation)) lever('PORT_ABSENT', 'stock.disponible et stock.consommation requis pour proposer');
|
|
293
|
+
if (!Array.isArray(articles) || articles.length === 0) lever('DONNEES_INVALIDES', 'articles : au moins un');
|
|
294
|
+
const reg = reglages();
|
|
295
|
+
const now = maintenant();
|
|
296
|
+
const commandes = await depots.commandes.find((c) => OUVERTES.includes(c.etat) || c.etat === 'brouillon');
|
|
297
|
+
const ouvertes = commandes.filter((c) => OUVERTES.includes(c.etat));
|
|
298
|
+
const brouillons = commandes.filter((c) => c.etat === 'brouillon');
|
|
299
|
+
const sortie = [];
|
|
300
|
+
for (const a of articles) {
|
|
301
|
+
if (!a || typeof a.articleId !== 'string' || !a.articleId) lever('DONNEES_INVALIDES', 'articleId requis');
|
|
302
|
+
const fenetreJours = a.fenetreJours ?? reg.fenetreJours;
|
|
303
|
+
if (!estEntierPositif(fenetreJours)) lever('DONNEES_INVALIDES', 'fenetreJours', { fenetreJours });
|
|
304
|
+
const refs = await referencesDe(a.articleId);
|
|
305
|
+
let fournisseurId = a.fournisseurId ?? null;
|
|
306
|
+
let ref = null;
|
|
307
|
+
if (fournisseurId) ref = refs.find((r) => r.fournisseurId === fournisseurId) ?? null;
|
|
308
|
+
else if (refs.length === 1) { ref = refs[0]; fournisseurId = ref.fournisseurId; }
|
|
309
|
+
const parColis = a.parColis ?? ref?.parColis ?? 1;
|
|
310
|
+
const disponible = await stock.disponible(a.articleId);
|
|
311
|
+
const consommation = await stock.consommation(a.articleId, { depuis: now - fenetreJours * JOUR, jusqua: now });
|
|
312
|
+
const enCommande = quantiteEnCours(ouvertes, a.articleId, (l) => Math.max(l.quantite - l.quantiteRecue, 0) * l.parColis);
|
|
313
|
+
const enBrouillon = quantiteEnCours(brouillons, a.articleId, (l) => l.quantite * l.parColis);
|
|
314
|
+
const calcul = calculerQuantite({
|
|
315
|
+
disponible, enCommande, consommation: { quantite: consommation, jours: fenetreJours }, delaiJours: a.delaiJours,
|
|
316
|
+
stockSecurite: a.stockSecurite, stockSecuriteJours: a.stockSecuriteJours, couvertureJours: a.couvertureJours ?? reg.couvertureJours,
|
|
317
|
+
minimumQuantite: a.minimumQuantite ?? 0, multiple: parColis,
|
|
318
|
+
});
|
|
319
|
+
sortie.push({
|
|
320
|
+
articleId: a.articleId, fournisseurId, code: ref?.code ?? null, libelle: ref?.libelle ?? null, parColis,
|
|
321
|
+
prixUnitaire: a.prixUnitaire ?? null, disponible, enCommande, enBrouillon, consommation, fenetreJours, delaiJours: a.delaiJours, ...calcul,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return sortie;
|
|
325
|
+
},
|
|
326
|
+
|
|
327
|
+
/** Un brouillon par fournisseur à partir des propositions déclenchées ; à valider par un humain. */
|
|
328
|
+
async brouillonsDepuis(propositions, { par = null } = {}) {
|
|
329
|
+
if (!Array.isArray(propositions)) lever('DONNEES_INVALIDES', 'propositions : un tableau');
|
|
330
|
+
const groupes = new Map();
|
|
331
|
+
const sansFournisseur = [];
|
|
332
|
+
for (const p of propositions) {
|
|
333
|
+
if (!p || !p.declenche || !(p.quantite > 0)) continue;
|
|
334
|
+
if (!p.fournisseurId) { sansFournisseur.push(p.articleId); continue; }
|
|
335
|
+
if (!groupes.has(p.fournisseurId)) groupes.set(p.fournisseurId, []);
|
|
336
|
+
groupes.get(p.fournisseurId).push({
|
|
337
|
+
articleId: p.articleId, quantite: p.colis, parColis: p.parColis, prixUnitaire: p.prixUnitaire ?? 0,
|
|
338
|
+
code: p.code ?? undefined, libelle: p.libelle ?? undefined,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
const brouillons = [];
|
|
342
|
+
for (const [fournisseurId, lignes] of groupes) brouillons.push(await service.creer({ fournisseurId, lignes, par }));
|
|
343
|
+
return { brouillons, sansFournisseur };
|
|
344
|
+
},
|
|
345
|
+
};
|
|
346
|
+
return service;
|
|
347
|
+
}
|