Spaces:
Running
Running
Create bus.mjs
Browse files- core/bus.mjs +36 -0
core/bus.mjs
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const APCatalog = {
|
| 2 |
+
propuesta_crear: { modes: ['supervisado', 'autonomo'], keys: ['sku', 'reason'], run: p => AP.propose(p) },
|
| 3 |
+
propuesta_decidir: { modes: ['supervisado', 'autonomo'], keys: ['id', 'status'], run: p => AP.decide(p.id, p.status) },
|
| 4 |
+
recepcion_registrar: { modes: ['supervisado'], keys: ['id'], run: p => AP.receive(p.id) },
|
| 5 |
+
pedido_generar: { modes: ['supervisado', 'autonomo'], keys: [], run: () => AP.cycle() },
|
| 6 |
+
};
|
| 7 |
+
const APCmdModes = ['supervisado', 'autonomo'];
|
| 8 |
+
const APCmdStr = (v, min, max, label) => {
|
| 9 |
+
if (typeof v !== 'string' || v.length < min || v.length > max) throw Error(label + ' debe ser texto de ' + min + '..' + max + ' caracteres');
|
| 10 |
+
return v;
|
| 11 |
+
};
|
| 12 |
+
const APBus = {
|
| 13 |
+
async command(spec) {
|
| 14 |
+
const { cmd, payload, actor, mode } = spec || {};
|
| 15 |
+
const entry = APCatalog[String(cmd || '')];
|
| 16 |
+
if (!entry) throw Error('Comando no admitido: ' + String(cmd));
|
| 17 |
+
if (!APCmdModes.includes(AP.mode)) throw Error('Modo activo no reconocido: ' + AP.mode);
|
| 18 |
+
if (mode !== undefined && mode !== AP.mode) throw Error('El modo indicado no corresponde al modo activo (' + AP.mode + ')');
|
| 19 |
+
if (!entry.modes.includes(AP.mode)) throw Error(AP.mode === 'autonomo' && cmd === 'recepcion_registrar' ? 'Aut贸nomo no registra recepciones; cambia a Supervisado para recepcionar' : 'El modo ' + AP.mode + ' no admite ' + cmd);
|
| 20 |
+
if (actor !== undefined) APCmdStr(actor, 1, 80, 'actor');
|
| 21 |
+
let data = payload === undefined || payload === null ? {} : payload;
|
| 22 |
+
if (typeof data !== 'object' || Array.isArray(data)) throw Error('payload debe ser un objeto');
|
| 23 |
+
for (const k of Object.keys(data)) if (!entry.keys.includes(k)) throw Error('payload no admite la clave ' + k + '; v谩lidas: ' + (entry.keys.join(', ') || '(ninguna)'));
|
| 24 |
+
if (cmd === 'propuesta_crear') {
|
| 25 |
+
APCmdStr(data.sku, 1, 128, 'payload.sku');
|
| 26 |
+
if (data.reason !== undefined) APCmdStr(data.reason, 1, 500, 'payload.reason');
|
| 27 |
+
}
|
| 28 |
+
if (cmd === 'propuesta_decidir') {
|
| 29 |
+
APCmdStr(data.id, 1, 64, 'payload.id');
|
| 30 |
+
if (!['aprobada', 'rechazada'].includes(data.status)) throw Error('payload.status debe ser aprobada o rechazada');
|
| 31 |
+
}
|
| 32 |
+
if (cmd === 'recepcion_registrar') APCmdStr(data.id, 1, 64, 'payload.id');
|
| 33 |
+
return entry.run(data);
|
| 34 |
+
},
|
| 35 |
+
};
|
| 36 |
+
globalThis.APBus = APBus;
|