@mostajs/achats 0.0.0-stage → 0.1.1
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 +32 -0
- package/LICENSE +15 -0
- package/README.md +143 -2
- package/exemples/01-quantite-proposee.mjs +31 -0
- package/exemples/02-cycle-commande.mjs +74 -0
- package/exemples/03-reprise-apres-panne.mjs +56 -0
- package/exemples/tous.mjs +19 -0
- package/llms.txt +105 -0
- package/package.json +82 -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/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
|
+
}
|