@begapp/sdk 2.0.0 → 2.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/README.md CHANGED
@@ -2,9 +2,52 @@
2
2
 
3
3
  Librería cliente para consumir los servicios de BegaApp desde cualquier aplicación externa. Permite configurar la API Key y consumir fácilmente endpoints.
4
4
 
5
+ ## Audiencia dinámica
6
+
7
+ Los avisos estáticos mantienen la firma existente:
8
+
9
+ ```js
10
+ await crearNotificacionBegaApp('RECEPCION_CREADA', data);
11
+ ```
12
+
13
+ Para un aviso dinámico, la aplicación origen identifica al destinatario usando
14
+ su identidad externa. Bega resuelve el vínculo y valida que el usuario esté
15
+ autorizado en la definición del aviso:
16
+
17
+ ```js
18
+ await crearNotificacionBegaApp('RECEPCION_ELIMINADA', data, {
19
+ recipients: {
20
+ users: [{ source: 'easy-bodega', externalId: creadorId }]
21
+ },
22
+ context: {
23
+ actor: { source: 'easy-bodega', externalId: usuarioActualId }
24
+ }
25
+ });
26
+ ```
27
+
28
+ Las mismas opciones están disponibles como cuarto argumento de
29
+ `crearNotificacionFileBegaApp(codigoAviso, data, files, options)`.
30
+
31
+ ### Suprimir el correo en una ejecución
32
+
33
+ Si el aviso tiene correo habilitado en Bega, la aplicación origen puede decidir
34
+ que una ejecución concreta se entregue solo por chat y campanita:
35
+
36
+ ```js
37
+ await crearNotificacionBegaApp('RECEPCION_ACTUALIZADA', data, {
38
+ delivery: { email: false }
39
+ });
40
+ ```
41
+
42
+ Omitir `delivery.email` conserva el comportamiento configurado en Bega. Enviar
43
+ `true` no habilita el correo si la definición del aviso lo tiene desactivado.
44
+
45
+ Durante la transición el servidor también acepta el `ObjectId` histórico, pero
46
+ las integraciones nuevas deben usar el código estable configurado en Bega.
47
+
5
48
  ---
6
49
 
7
50
  ## 🚀 Instalación
8
51
 
9
52
  ```bash
10
- npm install @begaapp/sdk
53
+ npm install @begaapp/sdk
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "@begapp/sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "SDK para interactuar con el servicio de notificaciones de Bega App",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
+ "files": [
8
+ "index.js",
9
+ "src",
10
+ "README.md"
11
+ ],
7
12
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
13
+ "test": "node --test"
9
14
  },
10
15
  "keywords": [],
11
16
  "author": "Bega App",
@@ -1,27 +1,42 @@
1
1
  import { getClient } from './client.js';
2
2
 
3
- export async function crearNotificacionBegaApp(id, data) {
4
- try {
5
- if (!id || typeof data !== 'object') {
6
- throw new Error("crearNotificacion requiere un ID y un objeto data.");
7
- }
3
+ function buildNotificationPayload(identifier, data, options = {}) {
4
+ if (!identifier || !data || typeof data !== 'object' || Array.isArray(data)) {
5
+ throw new Error("crearNotificacion requiere un identificador y un objeto data.");
6
+ }
7
+ // `id` se conserva durante la transición para servidores SDK anteriores.
8
+ const payload = { identifier, id: identifier, data };
9
+ if (options.context) payload.context = options.context;
10
+ if (options.recipients) payload.recipients = options.recipients;
11
+ if (options.delivery) payload.delivery = options.delivery;
12
+ if (options.attachments) payload.attachments = options.attachments;
13
+ return payload;
14
+ }
8
15
 
16
+ function sdkError(error) {
17
+ return {
18
+ status: "error",
19
+ code: error.response?.data?.code,
20
+ message: error.response?.data?.message || error.message,
21
+ details: error.response?.data?.details
22
+ };
23
+ }
24
+
25
+ export async function crearNotificacionBegaApp(identifier, data, options = {}) {
26
+ try {
9
27
  const client = getClient();
10
- const res = await client.post("/notification/create-notification", {
11
- id,
12
- data,
13
- });
28
+ const res = await client.post("/notification/create-notification", buildNotificationPayload(identifier, data, options));
14
29
 
15
30
  return { status: "success", data: res.data };
16
31
  } catch (error) {
17
- return { status: "error", message: error.message }
32
+ return sdkError(error);
18
33
  }
19
34
  }
20
35
 
21
- export async function crearNotificacionFileBegaApp(id, data, files) {
36
+ export async function crearNotificacionFileBegaApp(identifier, data, files, options = {}) {
22
37
  try {
23
- if (!id || typeof data !== 'object') {
24
- throw new Error("crearNotificacionFileBegaApp requiere un ID y un objeto data.");
38
+ if (!identifier || typeof data !== 'object') {
39
+ throw new Error("crearNotificacionFileBegaApp requiere un identificador y un objeto data.");
25
40
  }
26
41
 
27
42
  if (!files || files.length <= 0) {
@@ -36,7 +51,7 @@ export async function crearNotificacionFileBegaApp(id, data, files) {
36
51
  const form = new FormData();
37
52
  form.append('file', file, `${name}.pdf`);
38
53
  form.append('meta', JSON.stringify({ generatedAt: new Date().toISOString() }));
39
- form.append('id', id);
54
+ form.append('id', identifier);
40
55
 
41
56
  console.log("ASÍ ESTOY ARMANDO EL FORM: ", form);
42
57
 
@@ -63,14 +78,12 @@ export async function crearNotificacionFileBegaApp(id, data, files) {
63
78
 
64
79
  console.log("ESTE ES MI ATTACHMENTS: ", attachments);
65
80
 
66
- const res = await client.post("/notification/create-notification", {
67
- id,
68
- attachments,
69
- data,
70
- });
81
+ const res = await client.post("/notification/create-notification", buildNotificationPayload(identifier, data, { ...options, attachments }));
71
82
 
72
83
  return { status: "success", data: res.data };
73
84
  } catch (error) {
74
- return { status: "error", message: error.message }
85
+ return sdkError(error);
75
86
  }
76
- }
87
+ }
88
+
89
+ export { buildNotificationPayload };