Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 57c5deb3bd | |||
| c5217aa7c8 | |||
| 48ed64eb87 | |||
| 95b3e3698b | |||
| ee9da60b3b | |||
| f00e258819 | |||
| 33743f12b9 | |||
| b6399d28fc | |||
| e4441fa476 | |||
| c8029a6762 | |||
| 18fa523fbe | |||
| 63a85e8aab | |||
| e82d2a0ece | |||
| ff733296c8 | |||
| ef044522b4 | |||
| e6686597f0 | |||
| 9e090c465a | |||
| b7bbef8035 | |||
| 28295e346c | |||
| 9efb1792c7 | |||
| 4ffb6a281f | |||
| 6e7bf6e835 | |||
| ebd8096112 | |||
| a93681357f | |||
| 3b56d00fcb | |||
| f34b99b87b | |||
| 3145beca65 | |||
| 69a443dcfb | |||
| 446c65ff37 | |||
| cb830fcf01 | |||
| 146770a55d | |||
| 781310e36c | |||
| 446968c03f | |||
| 2a33f636a0 | |||
| 3d8911c093 | |||
| 0eb2e91e15 | |||
| c77d479344 | |||
| 0a285776c7 | |||
| f39ba44f59 | |||
| ece3879c8d | |||
| 68d98e8b40 | |||
| dc020d94d2 | |||
| 20b0363767 | |||
| 6c75929e21 | |||
| e6662aac18 | |||
| 4029566063 | |||
| 3988e328eb | |||
| dd3e07311d | |||
| 279e1b54cc | |||
| da3c3abb52 | |||
| 383a5bc6b4 |
+10
@@ -24,6 +24,16 @@ server/*.local
|
||||
server/build
|
||||
# server/uploads
|
||||
|
||||
# txadmin Electron app
|
||||
txadmin/node_modules
|
||||
txadmin/dist
|
||||
txadmin/dist-electron
|
||||
txadmin/release
|
||||
txadmin/release-portable
|
||||
txadmin/*.local
|
||||
txadmin/*.tsbuildinfo
|
||||
txadmin/node_modules/.tmp
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
name: tx-admin-endpoint
|
||||
description: "Trigger: crear colección, nueva colección, crear endpoint, nuevo endpoint, Models, api, turnosxpress admin. Reglas para crear colecciones y endpoints del backend admin de turnosxpress."
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: gentleman-programming
|
||||
version: "1.0"
|
||||
---
|
||||
|
||||
## Activation Contract
|
||||
|
||||
Load this skill when creating a new collection or a new endpoint in the `server` backend of the turnosxpress admin (the API consumed by admins/employees, not the public client app). Applies to both the data layer (`server/src/Models`) and the HTTP layer (`server/src/api`). Example to imitate: `Clients`, `Posts`, `SchedulesDisabled`.
|
||||
|
||||
## Hard Rules
|
||||
|
||||
- Use the ACTUAL paths: collections live in `server/src/Models/<Name>/`, endpoints in `server/src/api/<Name>/`. The folder name is the collection name (e.g. `Clients`, `Posts`).
|
||||
- A collection is ALWAYS exactly 3 files with separated responsibilities (never collapse them):
|
||||
|
||||
| File | Owns | Forbidden here |
|
||||
|------|------|-----------------|
|
||||
| `<Name>.Interface.ts` | All TS types: `*Params` (Create/Update/Delete/Find), `IX`, `IXDocument` re-export, `IXAdapter`, `IXManager`, view/result types. | No Mongoose, no business logic. |
|
||||
| `<Name>.Adapter.Mongoose.ts` | Mongoose ONLY: `Schema`, `IXDocument extends IX & Document`, `model()`, and pure DB ops (`create`, `delete`, `find`, `findOne`, `paginate`). Implements `IXAdapter`. | No business rules, NO security checks. |
|
||||
| `<Name>.ts` | Business rules AND security. A `<Name>Manager implements IXManager` class that instantiates the adapter in the constructor; exported as a singleton (`const XList = new ...Manager(); export default XList;`). | No Schema, no `model()`. |
|
||||
|
||||
- SECURITY STANDARD (mandatory, even though `Clients.ts` inlines it — that is legacy): use the shared helpers from `server/src/helpers/check.ts`:
|
||||
- `validateSessionUser({ sessionUser })` — confirm the session user exists. Call FIRST in any method that receives `sessionUser`.
|
||||
- `validatePermissionsByCompany({ companyId, sessionUser })` — confirm the company exists AND the session user has ADMIN role. Call whenever a `companyId` is involved.
|
||||
- Modern reference: `server/src/Models/Posts/Posts.ts`, `server/src/Models/SchedulesDisabled/SchedulesDisabled.ts`.
|
||||
- Role checks beyond ADMIN (EMPLOYEE, etc.) go through `EmployeesList.checkPermission` / `checkRoleById`.
|
||||
- An endpoint is ALWAYS 2 files:
|
||||
- `<Name>.Controller.ts` — tsoa decorators. One controller class per `@Route("resource/action")`. Each handler `@Post()`, takes `@Body()`, sets status, wraps in try/catch and returns `new ApiValidationError(500, message)` on error. Import `ApiValidationError` from `../../Models/Server.Error.model`.
|
||||
- `<Name>.Service.ts` — thin: each method `await connect(process.env.DATABASE_CONNECTION)` then delegates to the manager singleton. No business logic here.
|
||||
- `authenticationMiddleware` (from `server/src/middleware/authentication.ts`) MUST be applied with `@Middlewares(authenticateMiddleware)` on EVERY controller, UNLESS the endpoint is intentionally public. Never omit it without explicit confirmation (see Ask Before Building).
|
||||
- 99% of endpoints use `@Post()`. Default to POST; use GET/other only with a concrete, justified reason.
|
||||
- After adding/changing controllers, regenerate the tsoa routes/spec: `npm run routes` (binds `tsoa spec-and-routes`); compile with `npm run build`.
|
||||
|
||||
## Decision Gates
|
||||
|
||||
| Situation | Decision |
|
||||
|-----------|----------|
|
||||
| Does the method take `sessionUser`? | Call `validateSessionUser` first. |
|
||||
| Does the method act on a `companyId`? | Then `validatePermissionsByCompany`. |
|
||||
| Endpoint exposed in the admin backend? | Default: `@Middlewares(authenticateMiddleware)`. |
|
||||
| Endpoint hits WhatsApp notification / public recovery / ratings or another abuse-prone path? | Consider `rateLimiter` (or `ratingRateLimiter`) from `server/src/middleware/ratelimiter.ts`. When both apply: `@Middlewares([rateLimiter, authenticateMiddleware])`. |
|
||||
| Internal/system-only endpoint? | Use `systemTokenMiddleware` instead of/with the above. |
|
||||
| Doubt about middleware, role, or method? | STOP and ask. See Ask Before Building. |
|
||||
|
||||
## Ask Before Building (HARD — security first)
|
||||
|
||||
STOP and ask the user BEFORE writing security or middleware code whenever there is ANY doubt. Never guess on these:
|
||||
|
||||
1. Which validations/roles/plan features the new method requires (ADMIN vs EMPLOYEE vs extra feature gates).
|
||||
2. Whether the endpoint should be public (no `authenticateMiddleware`) or authenticated. A missing auth middleware is a security hole — when unsure, default to KEEPING `authenticateMiddleware` and confirm.
|
||||
3. Whether `rateLimiter` should be applied to a given endpoint. Do NOT add it by default; ask when the endpoint could be abuse-prone.
|
||||
4. Whether a non-POST method is genuinely needed.
|
||||
|
||||
Ask at most a couple of focused questions, then wait. Do not proceed by assumption on security.
|
||||
|
||||
## Execution Steps
|
||||
|
||||
Creating a collection:
|
||||
|
||||
1. Create `server/src/Models/<Name>/<Name>.Interface.ts` — define all params, `IX`, `IXAdapter`, `IXManager`, view/result types.
|
||||
2. Create `server/src/Models/<Name>/<Name>.Adapter.Mongoose.ts` — schema, `IXDocument`, `model()`, pure DB ops implementing `IXAdapter`.
|
||||
3. Create `server/src/Models/<Name>/<Name>.ts` — `<Name>Manager implements IXManager`; instantiate the adapter in the constructor; put business rules; call `validateSessionUser` / `validatePermissionsByCompany` at the top of each secured method; export a singleton default.
|
||||
4. Re-check Ask Before Building for any unconfirmed security requirement.
|
||||
|
||||
Creating an endpoint:
|
||||
|
||||
1. Create `server/src/api/<Name>/<Name>.Service.ts` — one method per action, `connect(process.env.DATABASE_CONNECTION)` then delegate to the manager singleton.
|
||||
2. Create `server/src/api/<Name>/<Name>.Controller.ts` — one controller class per `@Route`; `@Middlewares(authenticateMiddleware)` unless confirmed public; `@Post()` + `@Body()`; try/catch returning `ApiValidationError`.
|
||||
3. Apply Decision Gates (rateLimiter? system token? method?).
|
||||
4. Regenerate routes: `npm run routes` then `npm run build`.
|
||||
|
||||
## Output Contract
|
||||
|
||||
Return: files created, the singletons/middlewares wired, any security decision that was confirmed with the user, and whether `npm run routes` / `npm run build` were run.
|
||||
|
||||
## References
|
||||
|
||||
- `server/src/Models/Clients/Clients.ts`, `Clients.Interface.ts`, `Clients.Adapter.Mongoose.ts` — canonical 3-file collection example (note: Clients inlines security; do NOT copy that part).
|
||||
- `server/src/Models/Posts/Posts.ts` — modern security pattern using the shared helpers.
|
||||
- `server/src/helpers/check.ts` — `validateSessionUser`, `validatePermissionsByCompany`, `validatePermissionsByClient`.
|
||||
- `server/src/api/Clients/Clients.Controller.ts`, `Clients.Service.ts` — endpoint pattern (Controller + Service).
|
||||
- `server/src/middleware/authentication.ts`, `server/src/middleware/ratelimiter.ts` — middleware sources.
|
||||
- `server/tsoa.json`, `server/package.json` (`npm run routes`) — route generation.
|
||||
+116
-19
@@ -1,9 +1,17 @@
|
||||
package com.hdrdevs.turnosxpress;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import android.Manifest;
|
||||
import android.os.Bundle;
|
||||
import android.os.Build;
|
||||
import android.os.Message;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.media.MediaScannerConnection;
|
||||
import android.net.Uri;
|
||||
import android.util.Log;
|
||||
import android.view.KeyEvent;
|
||||
@@ -31,6 +39,7 @@ import android.content.ContentResolver;
|
||||
public class MainActivity extends AppCompatActivity {
|
||||
|
||||
private static final int LOGIN_REQUEST_CODE = 1;
|
||||
private static final int STORAGE_PERMISSION_REQUEST_CODE = 2;
|
||||
private WebView webView;
|
||||
private ValueCallback<Uri[]> fileChooserCallback;
|
||||
|
||||
@@ -41,6 +50,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
tokenResult = "";
|
||||
requestLegacyStoragePermissionIfNeeded();
|
||||
|
||||
// For Android Emulator, use 10.0.2.2 to access localhost on your development machine.
|
||||
// If testing on a physical device, replace 10.0.2.2 with your development machine's actual local IP address.
|
||||
@@ -70,11 +80,10 @@ public class MainActivity extends AppCompatActivity {
|
||||
webView.setWebViewClient(new WebViewClient() {
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView vw, WebResourceRequest request) {
|
||||
if (request.getUrl().toString().contains(home.getHost())) {
|
||||
if (shouldLoadInsideApp(request.getUrl(), home)) {
|
||||
vw.loadUrl(request.getUrl().toString());
|
||||
} else {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
|
||||
vw.getContext().startActivity(intent);
|
||||
openExternalUri(request.getUrl());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -95,7 +104,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
|
||||
@Override
|
||||
public boolean onShowFileChooser(WebView vw, ValueCallback<Uri[]> filePathCallback,
|
||||
FileChooserParams fileChooserParams) {
|
||||
FileChooserParams fileChooserParams) {
|
||||
if (fileChooserCallback != null) {
|
||||
fileChooserCallback.onReceiveValue(null);
|
||||
}
|
||||
@@ -112,6 +121,25 @@ public class MainActivity extends AppCompatActivity {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
|
||||
WebView popupWebView = new WebView(MainActivity.this);
|
||||
popupWebView.setWebViewClient(new WebViewClient() {
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView popupView, WebResourceRequest request) {
|
||||
openExternalUri(request.getUrl());
|
||||
popupWebView.destroy();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
|
||||
transport.setWebView(popupWebView);
|
||||
resultMsg.sendToTarget();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
webView.setOnKeyListener((v, keyCode, event) ->
|
||||
@@ -163,13 +191,65 @@ public class MainActivity extends AppCompatActivity {
|
||||
|
||||
private void handleURI(String uri) {
|
||||
if (uri != null) {
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(uri.replaceFirst("^blob:", "")));
|
||||
|
||||
startActivity(i);
|
||||
openExternalUri(Uri.parse(uri.replaceFirst("^blob:", "")));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldLoadInsideApp(Uri uri, Uri home) {
|
||||
return uri != null
|
||||
&& uri.getHost() != null
|
||||
&& uri.getHost().equals(home.getHost())
|
||||
&& ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()));
|
||||
}
|
||||
|
||||
private void openExternalUri(Uri uri) {
|
||||
if (uri == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Intent intent;
|
||||
|
||||
if ("intent".equals(uri.getScheme())) {
|
||||
intent = Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME);
|
||||
intent.addCategory(Intent.CATEGORY_BROWSABLE);
|
||||
intent.setComponent(null);
|
||||
} else {
|
||||
intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
}
|
||||
|
||||
startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Log.w("WEBVIEW", "No app can handle URI: " + uri, e);
|
||||
Toast.makeText(this, "No hay una aplicación disponible para abrir este enlace", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception e) {
|
||||
Log.e("WEBVIEW", "Error opening URI: " + uri, e);
|
||||
Toast.makeText(this, "No se pudo abrir el enlace", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void requestLegacyStoragePermissionIfNeeded() {
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P
|
||||
&& ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_REQUEST_CODE);
|
||||
}
|
||||
}
|
||||
|
||||
private String safePdfFilename(String filename) {
|
||||
String safeName = filename == null ? "reporte.pdf" : filename.trim();
|
||||
safeName = safeName.replaceAll("[\\\\/:*?\"<>|]", "_");
|
||||
|
||||
if (safeName.length() == 0) {
|
||||
safeName = "reporte.pdf";
|
||||
}
|
||||
|
||||
if (!safeName.toLowerCase().endsWith(".pdf")) {
|
||||
safeName += ".pdf";
|
||||
}
|
||||
|
||||
return safeName;
|
||||
}
|
||||
|
||||
public class WebAppInterface {
|
||||
@JavascriptInterface
|
||||
public void startGoogleLogin() {
|
||||
@@ -185,16 +265,20 @@ public class MainActivity extends AppCompatActivity {
|
||||
|
||||
@JavascriptInterface
|
||||
public void savePdf(String base64Data, String filename) {
|
||||
String safeFilename = safePdfFilename(filename);
|
||||
|
||||
try {
|
||||
byte[] pdfAsBytes = Base64.decode(base64Data, 0);
|
||||
String normalizedBase64 = base64Data == null ? "" : base64Data.replaceFirst("^data:application/pdf;base64,", "");
|
||||
byte[] pdfAsBytes = Base64.decode(normalizedBase64, Base64.DEFAULT);
|
||||
boolean isSaved = false;
|
||||
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
ContentResolver resolver = getContentResolver();
|
||||
ContentValues contentValues = new ContentValues();
|
||||
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename);
|
||||
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, safeFilename);
|
||||
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
|
||||
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
|
||||
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
|
||||
|
||||
Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
|
||||
|
||||
@@ -203,18 +287,31 @@ public class MainActivity extends AppCompatActivity {
|
||||
outputStream.write(pdfAsBytes);
|
||||
isSaved = true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
Log.e("WEBVIEW", "Error writing PDF to MediaStore: " + safeFilename, e);
|
||||
resolver.delete(uri, null, null);
|
||||
}
|
||||
|
||||
if (isSaved) {
|
||||
ContentValues completedValues = new ContentValues();
|
||||
completedValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
|
||||
resolver.update(uri, completedValues, null, null);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
|
||||
File file = new File(path, filename);
|
||||
|
||||
try (FileOutputStream os = new FileOutputStream(file)) {
|
||||
os.write(pdfAsBytes);
|
||||
isSaved = true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
if (!path.exists() && !path.mkdirs()) {
|
||||
Log.e("WEBVIEW", "Could not create Downloads directory: " + path.getAbsolutePath());
|
||||
} else {
|
||||
File file = new File(path, safeFilename);
|
||||
|
||||
try (FileOutputStream os = new FileOutputStream(file)) {
|
||||
os.write(pdfAsBytes);
|
||||
isSaved = true;
|
||||
MediaScannerConnection.scanFile(MainActivity.this, new String[]{file.getAbsolutePath()}, new String[]{"application/pdf"}, null);
|
||||
} catch (IOException e) {
|
||||
Log.e("WEBVIEW", "Error writing PDF to Downloads: " + safeFilename, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,7 +322,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Log.e("WEBVIEW", "Error saving PDF: " + safeFilename, e);
|
||||
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,14 +29,8 @@ COPY --from=builder /app/dist ./dist
|
||||
# Copiar archivos de entorno a la raíz /app
|
||||
COPY --from=builder /app/.env* ./
|
||||
|
||||
# Instalar bash y cron
|
||||
RUN apk add --no-cache bash curl
|
||||
|
||||
# Crear carpeta de logs
|
||||
RUN mkdir -p /app/logs
|
||||
|
||||
# Agregar tarea de cron: todos los días a las (9-3)UTF = 6AM GMT-3
|
||||
RUN echo "0 9 * * * cd /app && NODE_ENV=production NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node dist/index.js >> /app/logs/cron.log 2>&1" > /etc/crontabs/root
|
||||
|
||||
# Mantener cron en primer plano
|
||||
CMD ["crond", "-f", "-L", "/app/logs/cron.log"]
|
||||
# Ejecutar el worker continuo de jobs de notificaciones
|
||||
CMD ["node", "dist/index.js"]
|
||||
|
||||
Generated
+26
@@ -20,6 +20,7 @@
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/mongoose": "^5.11.96",
|
||||
"@types/node": "^24.3.3",
|
||||
"cross-env": "^10.1.0",
|
||||
"jest": "^30.4.2",
|
||||
"ts-jest": "^29.4.11",
|
||||
"ts-node": "^10.9.2",
|
||||
@@ -600,6 +601,13 @@
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@epic-web/invariant": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
|
||||
"integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@isaacs/cliui": {
|
||||
"version": "8.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
||||
@@ -2322,6 +2330,24 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cross-env": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",
|
||||
"integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@epic-web/invariant": "^1.0.0",
|
||||
"cross-spawn": "^7.0.6"
|
||||
},
|
||||
"bin": {
|
||||
"cross-env": "dist/bin/cross-env.js",
|
||||
"cross-env-shell": "dist/bin/cross-env-shell.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node --loader ts-node/esm src/index.ts",
|
||||
"dev": "cross-env NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node --loader ts-node/esm src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"test": "jest --config jest.config.cjs"
|
||||
@@ -18,6 +18,7 @@
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/mongoose": "^5.11.96",
|
||||
"@types/node": "^24.3.3",
|
||||
"cross-env": "^10.1.0",
|
||||
"jest": "^30.4.2",
|
||||
"ts-jest": "^29.4.11",
|
||||
"ts-node": "^10.9.2",
|
||||
|
||||
@@ -91,12 +91,17 @@ export async function dispatchEmail(params: {
|
||||
systemToken: string;
|
||||
type: string;
|
||||
email: string;
|
||||
subject: string;
|
||||
message: string;
|
||||
subject?: string;
|
||||
message?: string;
|
||||
templateId?: string;
|
||||
context?: Record<string, unknown>;
|
||||
}): Promise<DispatchResult> {
|
||||
try {
|
||||
if (!params.email.trim() || !params.subject.trim() || !params.message.trim()) {
|
||||
return { success: false, error: "Email dispatch requires email, subject, and message" };
|
||||
const hasContent = Boolean(params.subject?.trim() && params.message?.trim());
|
||||
const hasTemplate = Boolean(params.templateId?.trim() && params.context);
|
||||
|
||||
if (!params.email.trim() || (!hasContent && !hasTemplate)) {
|
||||
return { success: false, error: "Email dispatch requires email and either subject/message or templateId/context" };
|
||||
}
|
||||
|
||||
// Send worker-rendered content directly so cancellation jobs survive appointment deletion.
|
||||
@@ -106,8 +111,10 @@ export async function dispatchEmail(params: {
|
||||
{
|
||||
systemToken: params.systemToken,
|
||||
email: params.email,
|
||||
subject: params.subject,
|
||||
message: params.message,
|
||||
...(params.subject ? { subject: params.subject } : {}),
|
||||
...(params.message ? { message: params.message } : {}),
|
||||
...(params.templateId ? { templateId: params.templateId } : {}),
|
||||
...(params.context ? { context: params.context } : {}),
|
||||
},
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
|
||||
@@ -9,6 +9,7 @@ const BASE_RETRY_DELAY_MS = 5000;
|
||||
const MAX_JITTER_MS = 3000;
|
||||
const THROTTLE_RETRY_DELAY_MS = 8000;
|
||||
const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const CLEANUP_RETENTION_DAYS = 7;
|
||||
const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]);
|
||||
|
||||
function resolveCleanupIntervalMs(): number {
|
||||
@@ -41,6 +42,12 @@ export function buildStartOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
export function buildCleanupCutoff(now: Date): Date {
|
||||
const cutoff = buildStartOfDay(now);
|
||||
cutoff.setDate(cutoff.getDate() - CLEANUP_RETENTION_DAYS);
|
||||
return cutoff;
|
||||
}
|
||||
|
||||
function getJobId(job: { id?: unknown; _id?: unknown; appointmentId?: unknown; channel?: unknown; get?: (path: string) => unknown }): string {
|
||||
const value = job.id || job._id || job.get?.("_id");
|
||||
if (value) return String(value);
|
||||
@@ -91,7 +98,7 @@ export class JobProcessor {
|
||||
}
|
||||
|
||||
private async cleanupOldJobs(now = new Date()): Promise<void> {
|
||||
const cutoff = buildStartOfDay(now);
|
||||
const cutoff = buildCleanupCutoff(now);
|
||||
|
||||
try {
|
||||
const deletedCount = await this.jobModel.deleteBeforeScheduledAt(cutoff);
|
||||
@@ -195,6 +202,8 @@ export class JobProcessor {
|
||||
email: content.email || "",
|
||||
subject: content.subject,
|
||||
message: content.message,
|
||||
templateId: content.emailTemplateId,
|
||||
context: content.emailContext,
|
||||
});
|
||||
break;
|
||||
case "system":
|
||||
|
||||
@@ -45,6 +45,8 @@ export interface ResolvedNotificationContent {
|
||||
companyOwnerId?: string;
|
||||
subject: string;
|
||||
message: string;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const appointmentSchema = new Schema(
|
||||
@@ -147,7 +149,7 @@ export function buildNotificationText(params: {
|
||||
}
|
||||
|
||||
export async function resolveNotificationContent(job: INotificationJobDocument): Promise<ResolvedNotificationContent> {
|
||||
if ((job.type === "creation" || job.type === "reminder" || job.type === "cancellation") && job.payload) {
|
||||
if ((job.type === "creation" || job.type === "reminder" || job.type === "update" || job.type === "cancellation") && job.payload) {
|
||||
const { email, phoneNumber, userId, companyOwnerId } = job.payload;
|
||||
const subject = job.channel === "email"
|
||||
? job.payload.emailSubject
|
||||
@@ -169,6 +171,8 @@ export async function resolveNotificationContent(job: INotificationJobDocument):
|
||||
companyOwnerId: companyOwnerId ? String(companyOwnerId) : undefined,
|
||||
subject: fallbackSubject.trim(),
|
||||
message: fallbackMessage.trim(),
|
||||
emailTemplateId: job.payload.emailTemplateId?.trim(),
|
||||
emailContext: job.payload.emailContext,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ export type NotificationChannel = "whatsapp" | "email" | "system";
|
||||
export type NotificationJobStatus = "pending" | "processing" | "sent" | "failed" | "cancelled";
|
||||
export type NotificationJobType = "creation" | "reminder" | "update" | "cancellation";
|
||||
|
||||
export const DELETABLE_NOTIFICATION_JOB_STATUSES: NotificationJobStatus[] = ["sent", "failed", "cancelled"];
|
||||
|
||||
export interface NotificationJobPayload {
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
@@ -13,6 +15,8 @@ export interface NotificationJobPayload {
|
||||
message?: string;
|
||||
emailSubject?: string;
|
||||
emailMessage?: string;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
wapMessage?: string;
|
||||
systemSubject?: string;
|
||||
systemMessage?: string;
|
||||
@@ -106,6 +110,7 @@ export class NotificationJobModel {
|
||||
async deleteBeforeScheduledAt(cutoff: Date): Promise<number> {
|
||||
const result = await this.notificationJobList.deleteMany({
|
||||
scheduledAt: { $lt: cutoff },
|
||||
status: { $in: DELETABLE_NOTIFICATION_JOB_STATUSES },
|
||||
}).exec();
|
||||
|
||||
return result.deletedCount || 0;
|
||||
|
||||
@@ -43,6 +43,30 @@ describe("ChannelDispatchers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("sends email template data when provided", async () => {
|
||||
await dispatchEmail({
|
||||
appointmentId: "appointment-1",
|
||||
systemToken: "system-token",
|
||||
type: "reminder",
|
||||
email: "client@example.com",
|
||||
templateId: "template-1",
|
||||
context: { username: "Client Name" },
|
||||
});
|
||||
|
||||
expect(mockedAxios.post).toHaveBeenCalledWith(
|
||||
"https://api.example.com/notifications/send-email",
|
||||
{
|
||||
systemToken: "system-token",
|
||||
email: "client@example.com",
|
||||
templateId: "template-1",
|
||||
context: { username: "Client Name" },
|
||||
},
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it("sends the job type in the WhatsApp system notification payload", async () => {
|
||||
await dispatchWhatsApp({
|
||||
companyId: "company-1",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js";
|
||||
import { buildPendingJobQuery, buildStartOfDay, calculateNextRetryAt, JobProcessor } from "../JobProcessor.js";
|
||||
import { buildCleanupCutoff, buildPendingJobQuery, buildStartOfDay, calculateNextRetryAt, JobProcessor } from "../JobProcessor.js";
|
||||
import { DELETABLE_NOTIFICATION_JOB_STATUSES, NotificationJobModel } from "../NotificationJob.Adapter.Mongoose.js";
|
||||
import { resolveNotificationContent } from "../NotificationContentResolver.js";
|
||||
|
||||
jest.mock("../ChannelDispatchers.js", () => ({
|
||||
@@ -103,7 +104,7 @@ describe("JobProcessor", () => {
|
||||
});
|
||||
|
||||
describe("old job cleanup", () => {
|
||||
it("deletes jobs scheduled before the start of the current day", async () => {
|
||||
it("deletes jobs scheduled before the 7-day retention cutoff", async () => {
|
||||
const deleteBeforeScheduledAt = jest.fn().mockResolvedValue(3);
|
||||
const now = new Date(2026, 6, 21, 15, 30, 0, 0);
|
||||
|
||||
@@ -112,7 +113,30 @@ describe("JobProcessor", () => {
|
||||
now
|
||||
);
|
||||
|
||||
expect(deleteBeforeScheduledAt).toHaveBeenCalledWith(new Date(2026, 6, 21, 0, 0, 0, 0));
|
||||
expect(deleteBeforeScheduledAt).toHaveBeenCalledWith(new Date(2026, 6, 14, 0, 0, 0, 0));
|
||||
});
|
||||
|
||||
it("builds the 7-day retention cutoff from the start of the local day", () => {
|
||||
expect(buildCleanupCutoff(new Date(2026, 6, 21, 15, 30, 0, 0))).toEqual(
|
||||
new Date(2026, 6, 14, 0, 0, 0, 0)
|
||||
);
|
||||
});
|
||||
|
||||
it("deletes only terminal statuses and never pending or processing jobs", async () => {
|
||||
const exec = jest.fn().mockResolvedValue({ deletedCount: 3 });
|
||||
const deleteMany = jest.fn(() => ({ exec }));
|
||||
const model = Object.create(NotificationJobModel.prototype) as NotificationJobModel;
|
||||
(model as any).notificationJobList = { deleteMany };
|
||||
const cutoff = new Date("2026-07-14T00:00:00.000Z");
|
||||
|
||||
await model.deleteBeforeScheduledAt(cutoff);
|
||||
|
||||
expect(deleteMany).toHaveBeenCalledWith({
|
||||
scheduledAt: { $lt: cutoff },
|
||||
status: { $in: ["sent", "failed", "cancelled"] },
|
||||
});
|
||||
expect(DELETABLE_NOTIFICATION_JOB_STATUSES).not.toContain("pending");
|
||||
expect(DELETABLE_NOTIFICATION_JOB_STATUSES).not.toContain("processing");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -158,6 +158,111 @@ describe("NotificationContentResolver", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for email jobs without requiring appointment lookup", async () => {
|
||||
const appointmentLookup = jest.spyOn(mongoose.models.Appointment, "findOne");
|
||||
|
||||
const result = await resolveNotificationContent({
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
channel: "email",
|
||||
type: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Email update subject",
|
||||
message: "Email update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for WhatsApp jobs without requiring appointment lookup", async () => {
|
||||
const appointmentLookup = jest.spyOn(mongoose.models.Appointment, "findOne");
|
||||
|
||||
const result = await resolveNotificationContent({
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
channel: "whatsapp",
|
||||
type: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "WAP update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for system jobs without requiring appointment lookup", async () => {
|
||||
const appointmentLookup = jest.spyOn(mongoose.models.Appointment, "findOne");
|
||||
|
||||
const result = await resolveNotificationContent({
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
channel: "system",
|
||||
type: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "System update subject",
|
||||
message: "System update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses WhatsApp cancellation payload content for WhatsApp jobs", async () => {
|
||||
const result = await resolveNotificationContent({
|
||||
appointmentId: "deleted-appointment-1",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
mO9PXuuYR05od8cMVCIXEw
|
||||
@@ -0,0 +1,67 @@
|
||||
server {
|
||||
server_name turnosxpress.com.ar www.turnosxpress.com.ar;
|
||||
|
||||
root /var/www/turnosxpress.com.ar;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
#Sirvo el favicon desde la pagina de working
|
||||
location = /favicon.ico {
|
||||
root /var/www/working-web;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
|
||||
# Sitio web de Produccion
|
||||
location / {
|
||||
proxy_pass http://localhost:3021;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
client_max_body_size 5M;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
# Sitio web de Mantenimiento
|
||||
#location / {
|
||||
# root /var/www/working-web;
|
||||
# index index.html;
|
||||
# try_files $uri $uri/ /index.html;
|
||||
# #Desactivar caché en los navegadores
|
||||
# add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
|
||||
# add_header Pragma "no-cache" always;
|
||||
# add_header Expires 0 always;
|
||||
#}
|
||||
|
||||
|
||||
listen 443 ssl; # managed by Certbot
|
||||
ssl_certificate /etc/letsencrypt/live/turnosxpress.com.ar/fullchain.pem; # managed by Certbot
|
||||
ssl_certificate_key /etc/letsencrypt/live/turnosxpress.com.ar/privkey.pem; # managed by Certbot
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
|
||||
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
if ($host = www.turnosxpress.com.ar) {
|
||||
return 301 https://$host$request_uri;
|
||||
} # managed by Certbot
|
||||
|
||||
|
||||
if ($host = turnosxpress.com.ar) {
|
||||
return 301 https://$host$request_uri;
|
||||
} # managed by Certbot
|
||||
|
||||
|
||||
listen 80;
|
||||
server_name turnosxpress.com.ar www.turnosxpress.com.ar;
|
||||
return 404; # managed by Certbot
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Frx8us2W@
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
ngrok config add-authtoken 3I94dMHXyh3wjRjGBu0oGQ8D8h4_2yBusck6ZWHJBx7WcbBFf
|
||||
|
||||
ngrok http 3000
|
||||
@@ -0,0 +1,274 @@
|
||||
# TurnosXpress — contenido actualizado para tríptico
|
||||
|
||||
## 1. Mensaje principal
|
||||
|
||||
**TurnosXpress es una plataforma para gestionar turnos, clientes, servicios, pagos y comunicación desde un solo lugar.**
|
||||
|
||||
Pensada para profesionales, equipos y negocios que trabajan con reservas, permite ordenar la agenda diaria, publicar servicios online y facilitar que los clientes soliciten turnos desde cualquier dispositivo.
|
||||
|
||||
### Frases sugeridas
|
||||
|
||||
- **Tu agenda online, simple y organizada.**
|
||||
- **Reservá, administrá y comunicá mejor tus turnos.**
|
||||
- **Menos mensajes sueltos. Más control sobre tu agenda.**
|
||||
- **Turnos online para negocios que quieren trabajar mejor.**
|
||||
|
||||
## 2. Qué es TurnosXpress
|
||||
|
||||
TurnosXpress ayuda a negocios y profesionales a administrar sus reservas sin depender todo el tiempo del teléfono, los mensajes manuales o una agenda en papel.
|
||||
|
||||
Con la plataforma, el negocio puede:
|
||||
|
||||
- Crear su perfil público.
|
||||
- Publicar servicios.
|
||||
- Configurar días y horarios disponibles.
|
||||
- Administrar turnos por fecha, servicio, cliente y profesional.
|
||||
- Organizar clientes, pagos, caja y cuenta corriente.
|
||||
- Configurar notificaciones y comunicación por WhatsApp según el plan disponible.
|
||||
- Trabajar con colaboradores o profesionales dentro de una misma organización.
|
||||
- Mostrar información pública, opiniones, puntajes y profesionales cuando corresponda.
|
||||
|
||||
El objetivo es que cada negocio tenga una agenda digital clara, una presencia online más profesional y herramientas de administración que acompañen el crecimiento.
|
||||
|
||||
## 3. Público al que está dirigido
|
||||
|
||||
TurnosXpress está pensado para cualquier actividad que trabaje con citas, reservas o atención por horarios.
|
||||
|
||||
Ejemplos de rubros posibles:
|
||||
|
||||
- Centros de estética y belleza.
|
||||
- Peluquerías y barberías.
|
||||
- Consultorios y profesionales independientes.
|
||||
- Clases particulares, talleres y capacitaciones.
|
||||
- Estudios, centros de bienestar y servicios personalizados.
|
||||
- Equipos con varios colaboradores que necesitan coordinar agendas.
|
||||
|
||||
La plataforma sirve tanto para profesionales que trabajan solos como para organizaciones que necesitan distribuir servicios, horarios y turnos entre varias personas.
|
||||
|
||||
## 4. Propuesta de valor
|
||||
|
||||
### Reservas online para tus clientes
|
||||
|
||||
Tus clientes pueden encontrar tus servicios y solicitar turnos desde el celular, la computadora o cualquier dispositivo conectado.
|
||||
|
||||
### Agenda digital siempre ordenada
|
||||
|
||||
Centralizá los turnos del negocio en una agenda clara, consultable por fecha, cliente, servicio y profesional.
|
||||
|
||||
### Menos coordinación manual
|
||||
|
||||
Reducí llamadas, mensajes repetidos y cruces de horarios. El sistema muestra disponibilidad según la configuración del negocio.
|
||||
|
||||
### Administración del negocio
|
||||
|
||||
Además de los turnos, TurnosXpress permite gestionar clientes, pagos, caja, descuentos y cuenta corriente.
|
||||
|
||||
### Comunicación por WhatsApp
|
||||
|
||||
La plataforma cuenta con herramientas para conectar WhatsApp y configurar avisos o notificaciones según las funciones disponibles en cada plan.
|
||||
|
||||
### Presencia pública configurable
|
||||
|
||||
Cada negocio puede publicar su perfil, servicios e información visible para clientes. También puede configurar la visibilidad de opiniones, puntajes y profesionales cuando el plan y la configuración lo permiten.
|
||||
|
||||
### Planes para distintas etapas
|
||||
|
||||
TurnosXpress ofrece un plan gratuito/base para comenzar y planes pagos para negocios que necesitan más capacidad, más herramientas o funciones avanzadas.
|
||||
|
||||
## 5. Funciones principales
|
||||
|
||||
### Agenda y turnos
|
||||
|
||||
- Agenda digital por día.
|
||||
- Creación, edición, cancelación y movimiento de turnos.
|
||||
- Turnos asociados a clientes, servicios y profesionales.
|
||||
- Consulta de turnos próximos e históricos.
|
||||
- Soporte para turnos recurrentes según el plan disponible.
|
||||
|
||||
### Servicios
|
||||
|
||||
- Publicación de servicios con nombre, descripción, duración y precio.
|
||||
- Servicios públicos o privados.
|
||||
- Imagen, color y datos de ubicación.
|
||||
- Configuración de cupos o límites cuando corresponde.
|
||||
|
||||
### Horarios y disponibilidad
|
||||
|
||||
- Configuración de días y rangos horarios.
|
||||
- Horarios por organización o por colaborador/profesional.
|
||||
- Disponibilidad por servicio.
|
||||
- Control para que los clientes reserven dentro de los horarios habilitados.
|
||||
|
||||
### Clientes
|
||||
|
||||
- Registro y administración de clientes.
|
||||
- Historial de turnos por cliente.
|
||||
- Datos de contacto y preferencias.
|
||||
- Cuenta corriente y movimientos asociados.
|
||||
|
||||
### Pagos, caja y cuenta corriente
|
||||
|
||||
- Registro de pagos vinculados a turnos.
|
||||
- Estados de pago: pendiente, aprobado o rechazado.
|
||||
- Métodos como efectivo, transferencia, crédito, débito, cuenta corriente u otros.
|
||||
- Caja con movimientos, filtros y balance.
|
||||
- Cuenta corriente para controlar saldos y movimientos de clientes.
|
||||
|
||||
### Colaboradores y profesionales
|
||||
|
||||
- Administración de colaboradores dentro de una organización.
|
||||
- Roles y permisos.
|
||||
- Horarios y servicios asignados por profesional.
|
||||
- Visibilidad pública de profesionales cuando corresponde.
|
||||
|
||||
### Notificaciones y WhatsApp
|
||||
|
||||
- Configuración de notificaciones del negocio.
|
||||
- Preferencias generales y por cliente.
|
||||
- WhatsApp como canal principal para automatizar avisos según el plan y la configuración.
|
||||
- Asistente guiado para conectar y administrar WhatsApp.
|
||||
|
||||
> Nota comercial: conviene comunicar WhatsApp como herramienta de conexión y avisos de la plataforma, no como integración oficial de WhatsApp Business API.
|
||||
|
||||
### Opiniones y reputación
|
||||
|
||||
- Opiniones verificadas vinculadas a organización, servicio o profesional.
|
||||
- Configuración para mostrar u ocultar opiniones y puntajes.
|
||||
- Herramientas para fortalecer la presencia pública del negocio.
|
||||
|
||||
### Planes y MercadoPago
|
||||
|
||||
- Plan gratuito/base para comenzar.
|
||||
- Planes pagos con mayor capacidad y funciones avanzadas.
|
||||
- Gestión de contratación o actualización de plan.
|
||||
- Pagos de planes procesados con MercadoPago.
|
||||
|
||||
> Nota comercial: MercadoPago está confirmado para pagos de planes/suscripciones. No prometer cobro online de turnos a clientes salvo que se verifique esa funcionalidad para la campaña específica.
|
||||
|
||||
## 6. Cómo empezar
|
||||
|
||||
### Paso 1 — Registrate
|
||||
|
||||
Creá tu cuenta en TurnosXpress y accedé al panel para comenzar a configurar tu negocio.
|
||||
|
||||
URL sugerida:
|
||||
|
||||
`https://turnosxpress.com.ar/landing/signup`
|
||||
|
||||
### Paso 2 — Elegí tu plan
|
||||
|
||||
Podés comenzar con el plan gratuito/base o elegir un plan pago según el tamaño y las necesidades de tu negocio.
|
||||
|
||||
URL sugerida:
|
||||
|
||||
`https://turnosxpress.com.ar/landing/pricing`
|
||||
|
||||
### Paso 3 — Configurá tu negocio
|
||||
|
||||
Creá el perfil de tu organización, cargá tus servicios, definí horarios y configurá colaboradores si trabajás con un equipo.
|
||||
|
||||
### Paso 4 — Compartí tu enlace
|
||||
|
||||
Publicá tu perfil o compartí el enlace de reserva para que tus clientes puedan solicitar turnos online.
|
||||
|
||||
### Paso 5 — Administrá todo desde el panel
|
||||
|
||||
Consultá la agenda, gestioná clientes, registrá pagos, revisá caja, configurá notificaciones y mantené el negocio organizado.
|
||||
|
||||
## 7. Flujo de uso resumido
|
||||
|
||||
1. El profesional o negocio se registra.
|
||||
2. Selecciona un plan.
|
||||
3. Crea el perfil de la organización.
|
||||
4. Carga servicios, horarios y colaboradores.
|
||||
5. Comparte su enlace o publica su perfil.
|
||||
6. El cliente elige servicio, día y horario disponible.
|
||||
7. El turno queda registrado en la agenda.
|
||||
8. El negocio administra la atención, los pagos y la comunicación desde el panel.
|
||||
|
||||
## 8. Contenido sugerido para cara exterior del tríptico
|
||||
|
||||
### Portada
|
||||
|
||||
**TurnosXpress**
|
||||
|
||||
**Tu agenda online, simple y organizada.**
|
||||
|
||||
Gestioná turnos, clientes, servicios, pagos y comunicación desde una plataforma pensada para negocios que trabajan con reservas.
|
||||
|
||||
**Probá TurnosXpress y empezá a ordenar tu agenda hoy.**
|
||||
|
||||
### Panel de beneficios
|
||||
|
||||
**Reservas online**
|
||||
Tus clientes pueden solicitar turnos desde cualquier dispositivo.
|
||||
|
||||
**Agenda digital**
|
||||
Visualizá y administrá tus turnos de forma clara.
|
||||
|
||||
**Clientes y pagos**
|
||||
Centralizá información, movimientos, caja y cuenta corriente.
|
||||
|
||||
**WhatsApp y notificaciones**
|
||||
Configurá avisos y comunicación según tu plan.
|
||||
|
||||
**Perfil público**
|
||||
Mostrá tus servicios, profesionales, opiniones y puntajes cuando corresponda.
|
||||
|
||||
### Llamado a la acción
|
||||
|
||||
**Empezá gratis y configurá tu negocio en pocos pasos.**
|
||||
|
||||
Sitio web: `https://turnosxpress.com.ar`
|
||||
Email: `info@turnosxpress.com.ar`
|
||||
Teléfono: `11-2390-2059`
|
||||
|
||||
## 9. Contenido sugerido para cara interior del tríptico
|
||||
|
||||
### Título interior
|
||||
|
||||
**Todo lo que necesitás para administrar tus turnos en un solo lugar**
|
||||
|
||||
### Bloque 1 — Configurá tu negocio
|
||||
|
||||
Creá tu organización, cargá los servicios que ofrecés, definí duración, precio, ubicación y horarios disponibles.
|
||||
|
||||
### Bloque 2 — Publicá y recibí reservas
|
||||
|
||||
Compartí tu perfil o enlace de reserva para que tus clientes puedan elegir un servicio y solicitar un turno online.
|
||||
|
||||
### Bloque 3 — Administrá tu día a día
|
||||
|
||||
Consultá la agenda, gestioná clientes, registrá pagos, revisá caja y mantené el historial del negocio ordenado.
|
||||
|
||||
### Bloque 4 — Sumá comunicación y visibilidad
|
||||
|
||||
Configurá WhatsApp, notificaciones, opiniones, puntajes y profesionales visibles según el plan y la configuración de tu organización.
|
||||
|
||||
### Bloque 5 — Crecé con planes flexibles
|
||||
|
||||
Comenzá con el plan gratuito/base y pasá a un plan superior cuando necesites más capacidad o funciones avanzadas.
|
||||
|
||||
## 10. Llamados a la acción recomendados
|
||||
|
||||
- **Probá TurnosXpress gratis.**
|
||||
- **Creá tu agenda online hoy.**
|
||||
- **Compartí tus servicios y empezá a recibir reservas.**
|
||||
- **Ordená turnos, clientes y pagos desde un solo panel.**
|
||||
- **Digitalizá tu negocio sin complicarte.**
|
||||
|
||||
## 11. Mensajes que conviene evitar o matizar
|
||||
|
||||
- Evitar prometer SMS como función disponible actualmente.
|
||||
- Evitar decir “automatización multicanal completa” sin aclarar alcance por plan y configuración.
|
||||
- Evitar presentar WhatsApp como integración oficial de WhatsApp Business API.
|
||||
- Evitar prometer cobro online de turnos con MercadoPago si la campaña no verifica esa función específica.
|
||||
- Evitar enfocar el folleto en herramientas internas de sysadmin; no son beneficios directos para el negocio final.
|
||||
|
||||
## 12. Resumen comercial
|
||||
|
||||
TurnosXpress ya no es solamente una agenda online. Es una plataforma de gestión para negocios con turnos: permite publicar servicios, organizar disponibilidad, recibir reservas, administrar clientes, registrar pagos, controlar caja, trabajar con colaboradores y mejorar la comunicación con herramientas como WhatsApp y notificaciones configurables.
|
||||
|
||||
El mensaje actualizado debe transmitir una idea central:
|
||||
|
||||
**TurnosXpress ayuda a que el negocio trabaje más ordenado, atienda mejor y dependa menos de la coordinación manual.**
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
Binary file not shown.
+6
-1
@@ -45,7 +45,7 @@ MP_SUBSCRIPTION_FIND_URL = https://api.mercadopago.com/preapproval/
|
||||
MP_ACCESS_TOKEN = APP_USR-8753424836448507-121412-731599daea1ffa0b278b5dcc78aa1ec8-1611134648
|
||||
MP_BACK_URL = https://turnosxpress.com.ar/landing/dashboard
|
||||
MP_CHECK_PAYMENT_MINUTES = 1
|
||||
MP_WEBHOOK_URL = https://9300-186-132-200-176.ngrok-free.app/mercadopago/webhook
|
||||
MP_WEBHOOK_URL = https://30e1-186-132-147-13.ngrok-free.app/mercadopago/webhook
|
||||
|
||||
DEFAULT_BOT_ADMIN_PORT = 3005
|
||||
|
||||
@@ -69,3 +69,8 @@ FILE_SERVER_URL = http://localhost:4000/
|
||||
FILE_SERVER_URL_prod = https://files.turnosxpress.com.ar/
|
||||
|
||||
SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key
|
||||
ARCA_ENVIRONMENT=homologation
|
||||
ARCA_WSAA_URL=https://wsaahomo.afip.gov.ar/ws/services/LoginCms
|
||||
ARCA_WSFE_URL=https://wswhomo.afip.gov.ar/wsfev1/service.asmx
|
||||
|
||||
ARCA_CREDENTIALS_MASTER_KEY=ZmFrZS1kZXYtYXJjYS1tYXN0ZXIta2V5LTEyMzQ1Njc=
|
||||
|
||||
@@ -67,3 +67,8 @@ SYSTEM_KEY = ad7c956a-76bf-45hdr60-8a50-2ca7b2180997
|
||||
FILE_SERVER_URL = https://files.turnosxpress.com.ar/
|
||||
|
||||
SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key
|
||||
ARCA_ENVIRONMENT=production
|
||||
ARCA_WSAA_URL=https://wsaa.afip.gov.ar/ws/services/LoginCms
|
||||
ARCA_WSFE_URL=https://servicios1.afip.gov.ar/wsfev1/service.asmx
|
||||
|
||||
ARCA_CREDENTIALS_MASTER_KEY=ZmFrZS1kZXYtYXJjYS1tYXN0ZXIta2V5LTEyMzQ1Njc=
|
||||
|
||||
Generated
+21
-36
@@ -20,6 +20,7 @@
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"mongoose": "8.8.3",
|
||||
"multer": "^1.4.5-lts.2",
|
||||
"node-forge": "^1.4.0",
|
||||
"nodemailer": "^6.10.1",
|
||||
"sanitize-html": "^2.17.6",
|
||||
"sharp": "^0.33.5",
|
||||
@@ -33,6 +34,7 @@
|
||||
"@types/express": "^4.17.25",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nodemailer": "^6.4.24",
|
||||
"@types/sanitize-html": "^2.16.1",
|
||||
"@types/socket.io": "^3.0.2",
|
||||
@@ -775,9 +777,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -794,9 +793,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -813,9 +809,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -832,9 +825,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -851,9 +841,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -870,9 +857,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -889,9 +873,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -914,9 +895,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -939,9 +917,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -964,9 +939,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -989,9 +961,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1014,9 +983,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2119,6 +2085,16 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz",
|
||||
"integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw=="
|
||||
},
|
||||
"node_modules/@types/node-forge": {
|
||||
"version": "1.3.14",
|
||||
"resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
|
||||
"integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/nodemailer": {
|
||||
"version": "6.4.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.24.tgz",
|
||||
@@ -6892,6 +6868,15 @@
|
||||
"url": "https://opencollective.com/node-fetch"
|
||||
}
|
||||
},
|
||||
"node_modules/node-forge": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz",
|
||||
"integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==",
|
||||
"license": "(BSD-3-Clause OR GPL-2.0)",
|
||||
"engines": {
|
||||
"node": ">= 6.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-int64": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@types/express": "^4.17.25",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nodemailer": "^6.4.24",
|
||||
"@types/sanitize-html": "^2.16.1",
|
||||
"@types/socket.io": "^3.0.2",
|
||||
@@ -42,6 +43,7 @@
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"mongoose": "8.8.3",
|
||||
"multer": "^1.4.5-lts.2",
|
||||
"node-forge": "^1.4.0",
|
||||
"nodemailer": "^6.10.1",
|
||||
"sanitize-html": "^2.17.6",
|
||||
"sharp": "^0.33.5",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ScheduleItem } from "../Schedules/Schedules.Interface";
|
||||
import { ISchedulesDisabled } from "../SchedulesDisabled/SchedulesDisabled.Interface";
|
||||
import { ISchedulesOverrides } from "../SchedulesOverrides/SchedulesOverrides.Interface";
|
||||
|
||||
export type CollaboratorScheduleDetailsParams = {
|
||||
companyId: string;
|
||||
employeeId: string;
|
||||
sessionUser: string;
|
||||
fromDate?: Date;
|
||||
};
|
||||
|
||||
export type CollaboratorScheduleDetailsCollaborator = {
|
||||
employeeId: string;
|
||||
fullName: string;
|
||||
email: string;
|
||||
avatar: string;
|
||||
userId: string;
|
||||
};
|
||||
|
||||
export type CollaboratorWeeklySchedule = {
|
||||
companyId: string;
|
||||
employeeId: string;
|
||||
weekDay: number;
|
||||
scheduleId: string;
|
||||
schedules: ScheduleItem[];
|
||||
};
|
||||
|
||||
export type CollaboratorScheduleServiceSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type CollaboratorScheduleDetailsView = {
|
||||
collaborator: CollaboratorScheduleDetailsCollaborator;
|
||||
servicesById: Record<string, CollaboratorScheduleServiceSummary>;
|
||||
weeklySchedules: CollaboratorWeeklySchedule[];
|
||||
futureDisabledSchedules: ISchedulesDisabled[];
|
||||
futureOverrides: ISchedulesOverrides[];
|
||||
};
|
||||
|
||||
export interface IAdminAssistantManager {
|
||||
getCollaboratorScheduleDetails(
|
||||
data: CollaboratorScheduleDetailsParams
|
||||
): Promise<CollaboratorScheduleDetailsView>;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import dayjs from "dayjs";
|
||||
import EmployeesList from "../Employees/Employee";
|
||||
import ServicesList from "../Services/Service";
|
||||
import SchedulesList from "../Schedules/Schedules";
|
||||
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
||||
import SchedulesOverridesList from "../SchedulesOverrides/SchedulesOverrides";
|
||||
import UsersManager from "../Users/Users";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { joinStrings } from "../../helpers/String";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
import {
|
||||
CollaboratorScheduleDetailsParams,
|
||||
CollaboratorScheduleDetailsView,
|
||||
IAdminAssistantManager,
|
||||
} from "./AdminAssistant.Interface";
|
||||
|
||||
class AdminAssistantManager implements IAdminAssistantManager {
|
||||
public async getCollaboratorScheduleDetails(
|
||||
data: CollaboratorScheduleDetailsParams
|
||||
): Promise<CollaboratorScheduleDetailsView> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
const employee = await EmployeesList.employees.findOne({
|
||||
_id: data.employeeId,
|
||||
companyId: data.companyId,
|
||||
});
|
||||
|
||||
if (!employee) {
|
||||
throw new Error("El colaborador no existe o no pertenece a la organización.");
|
||||
}
|
||||
|
||||
const user = await UsersManager.users.findOne({ _id: String(employee.userId) });
|
||||
const snapshot = employee.profileSnapshot || {};
|
||||
const fullName = user
|
||||
? joinStrings([user.firstName, user.lastName], " ")
|
||||
: joinStrings([snapshot.firstName, snapshot.lastName], " ");
|
||||
const email = user?.email || snapshot.email || "";
|
||||
const avatar = user
|
||||
? getAvatar(String(user.id), user.avatar, fullName)
|
||||
: getAvatar(String(employee.userId), snapshot.avatar || "", fullName);
|
||||
const fromDate = data.fromDate ? dayjs(data.fromDate).startOf("day").toDate() : dayjs().startOf("day").toDate();
|
||||
|
||||
const weeklySchedules = await SchedulesList.find({
|
||||
companyId: data.companyId,
|
||||
employeeId: data.employeeId,
|
||||
});
|
||||
const futureDisabledSchedules = await SchedulesDisabledList.find({
|
||||
companyId: data.companyId,
|
||||
employeeId: data.employeeId,
|
||||
endDate: { $gte: fromDate } as any,
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
const futureOverrides = await SchedulesOverridesList.find({
|
||||
companyId: data.companyId,
|
||||
employeeId: data.employeeId,
|
||||
date: { $gte: fromDate } as any,
|
||||
});
|
||||
const companyServices = await ServicesList.findByCompanyId({ companyId: data.companyId });
|
||||
const servicesById = companyServices.reduce((index, service) => {
|
||||
index[service.id] = {
|
||||
id: service.id,
|
||||
name: service.name,
|
||||
};
|
||||
return index;
|
||||
}, {} as CollaboratorScheduleDetailsView["servicesById"]);
|
||||
|
||||
return {
|
||||
collaborator: {
|
||||
employeeId: String(employee.id || employee._id),
|
||||
fullName: fullName || email || "Colaborador",
|
||||
email,
|
||||
avatar,
|
||||
userId: String(employee.userId),
|
||||
},
|
||||
servicesById,
|
||||
weeklySchedules: weeklySchedules
|
||||
.sort((a, b) => a.weekDay - b.weekDay)
|
||||
.map((schedule) => ({
|
||||
companyId: String(schedule.companyId),
|
||||
employeeId: String(schedule.employeeId),
|
||||
scheduleId: String(schedule.id || (schedule as any)._id || ""),
|
||||
weekDay: schedule.weekDay,
|
||||
schedules: schedule.schedules || [],
|
||||
})),
|
||||
futureDisabledSchedules: futureDisabledSchedules.sort((a, b) =>
|
||||
new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
|
||||
),
|
||||
futureOverrides: futureOverrides.sort((a, b) =>
|
||||
new Date(a.date).getTime() - new Date(b.date).getTime()
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const AdminAssistantList = new AdminAssistantManager();
|
||||
|
||||
export default AdminAssistantList;
|
||||
@@ -46,6 +46,7 @@ export type SendAppointmentNotificationParams = {
|
||||
systemToken?: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
channel?: "whatsapp" | "email";
|
||||
allowClientCancellation?: boolean;
|
||||
};
|
||||
|
||||
export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||
@@ -54,6 +55,15 @@ export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
};
|
||||
|
||||
export type AppointmentNotificationPreviewParams = CreateImmediateAppointmentNotificationJobsParams;
|
||||
|
||||
export type AppointmentNotificationPreviewResult = {
|
||||
subject: string;
|
||||
message: string;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
};
|
||||
|
||||
export type MoveAppointmentParams = {
|
||||
id: string;
|
||||
companyId: string;
|
||||
@@ -194,6 +204,8 @@ export interface AppointmentNotificationIntent {
|
||||
message: string;
|
||||
checkClient: IClientDocument;
|
||||
companyCheck: ICompanyDocument;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface IAppointment {
|
||||
@@ -328,6 +340,7 @@ export interface IAppointmentsManager {
|
||||
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
|
||||
getAppointmentNotificationPreview(data: AppointmentNotificationPreviewParams): Promise<AppointmentNotificationPreviewResult>;
|
||||
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
||||
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
||||
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AppointmentEvent,
|
||||
AppointmentEventByClient,
|
||||
AppointmentNotificationIntent,
|
||||
AppointmentNotificationPreviewResult,
|
||||
ChangeEmployeeToOwnerParams,
|
||||
CountAppointmentsByMonthParams,
|
||||
CreateAppointmentParams,
|
||||
@@ -286,6 +287,23 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
return parseInt(`${process.env.CANCELLATION_TIME}`) || 24;
|
||||
}
|
||||
|
||||
private formatAppointmentDuration(startHour: number, endHour: number): string {
|
||||
const durationHours = endHour >= startHour ? endHour - startHour : endHour + 24 - startHour;
|
||||
const durationMinutes = Math.round(durationHours * 60);
|
||||
const hours = Math.floor(durationMinutes / 60);
|
||||
const minutes = durationMinutes % 60;
|
||||
|
||||
if (hours > 0 && minutes > 0) {
|
||||
return `${hours} ${hours === 1 ? "hora" : "horas"} y ${minutes} minutos`;
|
||||
}
|
||||
|
||||
if (hours > 0) {
|
||||
return `${hours} ${hours === 1 ? "hora" : "horas"}`;
|
||||
}
|
||||
|
||||
return `${minutes} minutos`;
|
||||
}
|
||||
|
||||
private validateCancellationTime(aTime: number | undefined, start: string | Date): boolean {
|
||||
let cancellationTime = this.getCancellationTime(aTime);
|
||||
|
||||
@@ -516,7 +534,7 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
|
||||
await this.updateHeatMap(availabilityConfig);
|
||||
|
||||
await this.tryApplyDiscounts(newAppointment);
|
||||
await this.tryApplyDiscounts(newAppointment, String(companyCheck.ownerId));
|
||||
|
||||
if (notification && checkClient.userId) {
|
||||
//Envio la notificacion al cliente.
|
||||
@@ -529,51 +547,22 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String((newAppointment as any)._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (newAppointment.id) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(checkClient);
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createCreationNotificationJobs({
|
||||
appointmentId: String(newAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
});
|
||||
}
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (this.shouldCreateCustomerNotificationJobs(notification, data.repeatId) && newAppointment.id) {
|
||||
await this.createAppointmentNotificationJobs({
|
||||
appointmentId: String(newAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
client: checkClient,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
notification,
|
||||
});
|
||||
}
|
||||
|
||||
//Envio la notificacion al profesional.
|
||||
@@ -603,7 +592,7 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async tryApplyDiscounts(appointment: IAppointment) {
|
||||
private async tryApplyDiscounts(appointment: IAppointment, sessionUser: string) {
|
||||
//Intenta aplicar un descuento al turno si esta especificado en DiscountsEmail
|
||||
// y la fecha coincide con el rango especificado.
|
||||
|
||||
@@ -643,7 +632,7 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
appointmentId: String(appointment.id),
|
||||
discountId: String(existDiscount.discountId),
|
||||
companyId: String(appointment.companyId),
|
||||
sessionUser: String(appointment.userId),
|
||||
sessionUser: sessionUser,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
@@ -698,6 +687,47 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
// Update both heatmaps
|
||||
await this.updateHeatMap(originalConfig);
|
||||
await this.updateHeatMap(newConfig);
|
||||
|
||||
// Reprogram pending notification jobs for the new date/time. The appointment
|
||||
// was already saved, so tryToSendNotification reads the new start date and
|
||||
// builds the reminder content (email template included) from it.
|
||||
try {
|
||||
// Cancel the jobs scheduled for the original date/time so they don't fire late.
|
||||
await this.jobService.cancelByAppointment(String(appointment._id));
|
||||
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(appointment._id),
|
||||
sessionUser: data.sessionUser || "",
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(appointment._id),
|
||||
sessionUser: data.sessionUser || "",
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createReminderNotificationJobs({
|
||||
appointmentId: String(appointment._id),
|
||||
companyId: String(appointment.companyId),
|
||||
clientId: String(appointment.clientId),
|
||||
clientUserId: reminderEmailContent.checkClient.userId
|
||||
? String(reminderEmailContent.checkClient.userId)
|
||||
: undefined,
|
||||
clientEmail: reminderEmailContent.checkClient.email,
|
||||
clientPhoneNumber: await this.getOptionalClientWapNumber(reminderEmailContent.checkClient),
|
||||
companyOwnerId: String(reminderEmailContent.companyCheck.ownerId),
|
||||
companyName: reminderEmailContent.companyCheck.name,
|
||||
appointmentStart: appointment.start,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
reminderEmailTemplateId: reminderEmailContent.emailTemplateId,
|
||||
reminderEmailContext: reminderEmailContent.emailContext,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log("Error reprogramming notification jobs after move:", error);
|
||||
}
|
||||
}
|
||||
|
||||
public async changeServiceForce(data: ChangeServiceParams): Promise<void> {
|
||||
@@ -2196,6 +2226,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
emailMessage: string;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
wapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno cancelado en ${data.companyName}`;
|
||||
@@ -2215,6 +2247,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Turno cancelado",
|
||||
emailMessage: data.emailMessage,
|
||||
emailTemplateId: data.emailTemplateId,
|
||||
emailContext: data.emailContext,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
@@ -2234,31 +2268,138 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
appointmentStart: Date;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
reminderEmailMessage: string;
|
||||
reminderWapMessage: string;
|
||||
reminderEmailTemplateId?: string;
|
||||
reminderEmailContext?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno reservado en ${data.companyName}`;
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
const payload = {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Alta de turno",
|
||||
emailMessage: data.emailMessage,
|
||||
emailTemplateId: data.emailTemplateId,
|
||||
emailContext: data.emailContext,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
};
|
||||
|
||||
await this.jobService.createMandatoryCreationJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
await this.createReminderNotificationJobs(data);
|
||||
}
|
||||
|
||||
private shouldCreateCustomerNotificationJobs(notification: boolean, repeatId?: string): boolean {
|
||||
return notification || Boolean(repeatId);
|
||||
}
|
||||
|
||||
private async createAppointmentNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
client: IClientDocument;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
notification: boolean;
|
||||
}): Promise<void> {
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(data.client);
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const notificationJobData = {
|
||||
appointmentId: data.appointmentId,
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
clientUserId: data.clientUserId,
|
||||
clientEmail: data.clientEmail,
|
||||
clientPhoneNumber,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
companyName: data.companyName,
|
||||
appointmentStart: data.appointmentStart,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderEmailTemplateId: reminderEmailContent.emailTemplateId,
|
||||
reminderEmailContext: reminderEmailContent.emailContext,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
};
|
||||
|
||||
if (!data.notification) {
|
||||
await this.createReminderNotificationJobs(notificationJobData);
|
||||
return;
|
||||
}
|
||||
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createCreationNotificationJobs({
|
||||
...notificationJobData,
|
||||
emailMessage: emailContent.message,
|
||||
emailTemplateId: emailContent.emailTemplateId,
|
||||
emailContext: emailContent.emailContext,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
|
||||
private async createReminderNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
reminderEmailMessage: string;
|
||||
reminderWapMessage: string;
|
||||
reminderEmailTemplateId?: string;
|
||||
reminderEmailContext?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createReminderJobs({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "reminder",
|
||||
appointmentStart: data.appointmentStart,
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Alta de turno",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
reminderPayload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
@@ -2268,6 +2409,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
message: data.reminderEmailMessage,
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: data.reminderEmailMessage,
|
||||
emailTemplateId: data.reminderEmailTemplateId,
|
||||
emailContext: data.reminderEmailContext,
|
||||
wapMessage: data.reminderWapMessage,
|
||||
systemSubject: reminderSystemSubject,
|
||||
systemMessage: data.reminderEmailMessage,
|
||||
@@ -2424,12 +2567,14 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "email",
|
||||
allowClientCancellation: true,
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment._id),
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "whatsapp",
|
||||
allowClientCancellation: true,
|
||||
});
|
||||
|
||||
await this.createCancellationNotificationJobs({
|
||||
@@ -2442,6 +2587,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
emailMessage: emailContent.message,
|
||||
emailTemplateId: emailContent.emailTemplateId,
|
||||
emailContext: emailContent.emailContext,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
@@ -2583,6 +2730,14 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("La compañia no existe");
|
||||
}
|
||||
|
||||
const checkClient = await ClientsManager.clients.findOne({
|
||||
_id: String(checkAppointment.clientId),
|
||||
});
|
||||
|
||||
if (!checkClient) {
|
||||
throw new Error("El cliente no existe");
|
||||
}
|
||||
|
||||
const hasSystemToken = this.hasValidSystemToken(data.systemToken);
|
||||
|
||||
if (!hasSystemToken) {
|
||||
@@ -2590,19 +2745,19 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
||||
const isAuthorizedClientCancellation =
|
||||
data.allowClientCancellation === true &&
|
||||
data.type === APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION &&
|
||||
String(checkClient.userId) === data.sessionUser;
|
||||
|
||||
if (
|
||||
!isAuthorizedClientCancellation &&
|
||||
!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))
|
||||
) {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
}
|
||||
|
||||
const checkClient = await ClientsManager.clients.findOne({
|
||||
_id: String(checkAppointment.clientId),
|
||||
});
|
||||
|
||||
if (!checkClient) {
|
||||
throw new Error("El cliente no existe");
|
||||
}
|
||||
|
||||
const checkEmployee = await EmployeesList.employees.findOne({
|
||||
_id: String(checkAppointment.employeeId),
|
||||
});
|
||||
@@ -2628,6 +2783,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
let wapMessage = "";
|
||||
let emailTemplateId: string | undefined;
|
||||
let emailContext: Record<string, unknown> | undefined;
|
||||
|
||||
if (data.type == APPOINTMENT_NOTIFICATION_TYPE.REMINDER) {
|
||||
if (companyCheck.templateWapNotifId) {
|
||||
@@ -2671,6 +2828,19 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
|
||||
emailTemplateId = "6a86ef631898c6948d0f5308";
|
||||
emailContext = {
|
||||
username: ClientsManager.getClientFullName(checkClient),
|
||||
nombre_organizacion: companyCheck.name,
|
||||
fecha_turno: dayjs(checkAppointment.start).format("DD/MM/YYYY"),
|
||||
hora_turno: dayjs(checkAppointment.start).format("HH:mm") + "hs.",
|
||||
nombre_servicio: checkService.name,
|
||||
nombre_profesional: UsersManager.getUserFullName(checkEmployeeUser),
|
||||
duracion: this.formatAppointmentDuration(checkAppointment.startHour, checkAppointment.endHour),
|
||||
precio: formatCurrency(checkAppointment.price),
|
||||
direccion: CompaniesManager.getCompanyAddress(companyCheck),
|
||||
};
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
const templateId = data.channel === "email"
|
||||
? companyCheck.templateEmailAltaId || companyCheck.templateWapAltaId
|
||||
@@ -2720,6 +2890,19 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
|
||||
emailTemplateId = "6a86f55e3edd051e8a04c711";
|
||||
emailContext = {
|
||||
username: ClientsManager.getClientFullName(checkClient),
|
||||
nombre_organizacion: companyCheck.name,
|
||||
fecha_turno: dayjs(checkAppointment.start).format("DD/MM/YYYY"),
|
||||
hora_turno: dayjs(checkAppointment.start).format("HH:mm") + "hs.",
|
||||
nombre_servicio: checkService.name,
|
||||
nombre_profesional: UsersManager.getUserFullName(checkEmployeeUser),
|
||||
duracion: this.formatAppointmentDuration(checkAppointment.startHour, checkAppointment.endHour),
|
||||
precio: formatCurrency(checkAppointment.price),
|
||||
direccion: CompaniesManager.getCompanyAddress(companyCheck),
|
||||
};
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION || data.type == APPOINTMENT_NOTIFICATION_TYPE.UPDATE) {
|
||||
const isUpdate = data.type == APPOINTMENT_NOTIFICATION_TYPE.UPDATE;
|
||||
const templateId = data.channel === "email"
|
||||
@@ -2775,12 +2958,29 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
|
||||
emailTemplateId = isUpdate
|
||||
? "6a86febf6713e0bdd104c7ca"
|
||||
: "6a86f77d376a7371170b21c5";
|
||||
emailContext = {
|
||||
username: ClientsManager.getClientFullName(checkClient),
|
||||
nombre_organizacion: companyCheck.name,
|
||||
fecha_turno: dayjs(checkAppointment.start).format("DD/MM/YYYY"),
|
||||
hora_turno: dayjs(checkAppointment.start).format("HH:mm") + "hs.",
|
||||
nombre_servicio: checkService.name,
|
||||
nombre_profesional: UsersManager.getUserFullName(checkEmployeeUser),
|
||||
duracion: this.formatAppointmentDuration(checkAppointment.startHour, checkAppointment.endHour),
|
||||
precio: formatCurrency(checkAppointment.price),
|
||||
direccion: CompaniesManager.getCompanyAddress(companyCheck),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
message: wapMessage,
|
||||
checkClient: checkClient,
|
||||
companyCheck: companyCheck,
|
||||
emailTemplateId,
|
||||
emailContext,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2799,7 +2999,7 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
const { message, checkClient, companyCheck, emailTemplateId, emailContext } = await this.tryToSendNotification({
|
||||
...data,
|
||||
channel: "email",
|
||||
});
|
||||
@@ -2836,6 +3036,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
email: clientEmail,
|
||||
subject: subjectEmail,
|
||||
message: message,
|
||||
templateId: emailTemplateId,
|
||||
context: emailContext,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2887,6 +3089,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
message: emailContent.message,
|
||||
emailSubject: isCreation ? "TurnosXpress :: Alta de turno" : "TurnosXpress :: Recordatorio",
|
||||
emailMessage: emailContent.message,
|
||||
emailTemplateId: emailContent.emailTemplateId,
|
||||
emailContext: emailContent.emailContext,
|
||||
wapMessage: wapContent.message,
|
||||
systemSubject,
|
||||
systemMessage: emailContent.message,
|
||||
@@ -2894,6 +3098,52 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
public async getAppointmentNotificationPreview(data: CreateImmediateAppointmentNotificationJobsParams): Promise<AppointmentNotificationPreviewResult> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
|
||||
if (![APPOINTMENT_NOTIFICATION_TYPE.CREATION, APPOINTMENT_NOTIFICATION_TYPE.REMINDER].includes(data.type)) {
|
||||
throw new Error("El tipo de notificación no es válido para esta acción");
|
||||
}
|
||||
|
||||
const checkAppointment = await this.Appointments.findOne({
|
||||
_id: data.appointmentId,
|
||||
});
|
||||
|
||||
if (!checkAppointment) {
|
||||
throw new Error("El turno no existe");
|
||||
}
|
||||
|
||||
await validatePermissionsByCompany({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const isCreation = data.type === APPOINTMENT_NOTIFICATION_TYPE.CREATION;
|
||||
const subject = isCreation
|
||||
? `Turno reservado en ${emailContent.companyCheck.name}`
|
||||
: `Recordatorio de turno en ${emailContent.companyCheck.name}`;
|
||||
|
||||
return {
|
||||
subject,
|
||||
message: emailContent.message,
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
};
|
||||
}
|
||||
|
||||
public async sendWapNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
|
||||
@@ -421,6 +421,8 @@ describe("cancellation notification jobs", () => {
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
@@ -563,6 +565,8 @@ describe("creation notification jobs", () => {
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
@@ -649,7 +653,7 @@ describe("creation notification jobs", () => {
|
||||
reminderWapMessage: "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createJob).toHaveBeenCalledWith(
|
||||
expect((AppointmentsList as any).jobService.createMandatoryCreationJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "creation",
|
||||
payload: expect.objectContaining({
|
||||
@@ -659,6 +663,11 @@ describe("creation notification jobs", () => {
|
||||
systemSubject: "Turno reservado en clases llavallol",
|
||||
systemMessage: "EMAIL ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.",
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect((AppointmentsList as any).jobService.createReminderJobs).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "reminder",
|
||||
reminderPayload: expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
@@ -672,6 +681,73 @@ describe("creation notification jobs", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("routes customer notification jobs for creation, repeat reminder-only, and disabled notifications", () => {
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(true, undefined)).toBe(true);
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(false, "repeat-001")).toBe(true);
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(false, undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("creates reminder-only jobs without rendering Alta content for repeat-created appointments", async () => {
|
||||
const tryToSendNotificationSpy = jest
|
||||
.spyOn(AppointmentsList as any, "tryToSendNotification")
|
||||
.mockImplementation(({ type, channel }: any) => {
|
||||
if (type === APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
throw new Error("Creation content should not be rendered");
|
||||
}
|
||||
|
||||
return Promise.resolve({
|
||||
message: channel === "email" ? "EMAIL REMINDER Ada Lovelace" : "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
});
|
||||
const getOptionalClientWapNumberSpy = jest
|
||||
.spyOn(AppointmentsList as any, "getOptionalClientWapNumber")
|
||||
.mockResolvedValue("5491112345678");
|
||||
|
||||
try {
|
||||
await (AppointmentsList as any).createAppointmentNotificationJobs({
|
||||
appointmentId: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
clientUserId: "client-user-001",
|
||||
clientEmail: "ada@example.com",
|
||||
client: { _id: "client-001" },
|
||||
companyOwnerId: "owner-001",
|
||||
companyName: "clases llavallol",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
notification: false,
|
||||
});
|
||||
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledTimes(2);
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER, channel: "email" })
|
||||
);
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER, channel: "whatsapp" })
|
||||
);
|
||||
expect((AppointmentsList as any).jobService.createMandatoryCreationJob).not.toHaveBeenCalled();
|
||||
expect((AppointmentsList as any).jobService.createReminderJobs).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "reminder",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
reminderPayload: expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "client-user-001",
|
||||
companyOwnerId: "owner-001",
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
wapMessage: "WAP REMINDER Ada Lovelace",
|
||||
systemSubject: "Recordatorio de turno en clases llavallol",
|
||||
systemMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
}),
|
||||
})
|
||||
);
|
||||
} finally {
|
||||
tryToSendNotificationSpy.mockRestore();
|
||||
getOptionalClientWapNumberSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to organization WAP Alta template for email when email Alta is absent", async () => {
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "company-001",
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { TextObjectFilterResult } from "../TextObjectFilter.model";
|
||||
|
||||
export type ArcaActivity = {
|
||||
code: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export const ARCA_ACTIVITIES: ArcaActivity[] = [
|
||||
{ code: "011111", description: "Cultivo de arroz" },
|
||||
{ code: "011112", description: "Cultivo de trigo" },
|
||||
{ code: "011119", description: "Cultivo de cereales n.c.p., excepto los de uso forrajero" },
|
||||
{ code: "011121", description: "Cultivo de maíz" },
|
||||
{ code: "011129", description: "Cultivo de cereales de uso forrajero n.c.p." },
|
||||
{ code: "011130", description: "Cultivo de oleaginosas, excepto soja" },
|
||||
{ code: "011140", description: "Cultivo de pastos de uso forrajero" },
|
||||
{ code: "011211", description: "Cultivo de papa, batata y mandioca" },
|
||||
{ code: "011221", description: "Cultivo de tomate" },
|
||||
{ code: "011229", description: "Cultivo de bulbos, brotes, raíces y hortalizas de fruto n.c.p." },
|
||||
{ code: "011240", description: "Cultivo de legumbres" },
|
||||
{ code: "012110", description: "Cultivo de vid para vinificar" },
|
||||
{ code: "012121", description: "Cultivo de uva de mesa" },
|
||||
{ code: "012200", description: "Cultivo de frutas cítricas" },
|
||||
{ code: "012311", description: "Cultivo de manzana y pera" },
|
||||
{ code: "012320", description: "Cultivo de frutas de carozo" },
|
||||
{ code: "012410", description: "Cultivo de frutas tropicales y subtropicales" },
|
||||
{ code: "012510", description: "Cultivo de frutas secas" },
|
||||
{ code: "013011", description: "Producción de semillas híbridas de cereales y oleaginosas" },
|
||||
{ code: "013019", description: "Producción de semillas varietales o autofecundadas de cereales, oleaginosas, y forrajeras" },
|
||||
{ code: "014113", description: "Cría de ganado bovino, excepto la realizada en cabañas y para la producción de leche" },
|
||||
{ code: "014114", description: "Invernada de ganado bovino excepto el engorde en corrales (feed-lot)" },
|
||||
{ code: "014115", description: "Engorde en corrales (feed-lot)" },
|
||||
{ code: "014211", description: "Cría de ganado equino, excepto la realizada en haras" },
|
||||
{ code: "014300", description: "Cría de ganado camélido" },
|
||||
{ code: "014410", description: "Cría de ganado ovino, excepto en cabañas y para la producción de lana" },
|
||||
{ code: "014420", description: "Cría de ganado ovino realizada en cabañas" },
|
||||
{ code: "014430", description: "Cría de ganado ovino para la producción de lana" },
|
||||
{ code: "014510", description: "Cría de ganado porcino, excepto la realizada en cabañas" },
|
||||
{ code: "014520", description: "Cría de ganado porcino realizada en cabañas" },
|
||||
{ code: "014610", description: "Producción de leche bovina" },
|
||||
{ code: "014620", description: "Producción de leche de oveja y de cabra" },
|
||||
{ code: "014710", description: "Producción de huevos" },
|
||||
{ code: "014720", description: "Cría de aves para producción de carnes" },
|
||||
{ code: "014740", description: "Producción de pollitos BB" },
|
||||
{ code: "014810", description: "Cría de abejas" },
|
||||
{ code: "014820", description: "Producción de pelos de ganado" },
|
||||
{ code: "014910", description: "Cría de animales para la obtención de pieles y cueros" },
|
||||
{ code: "014990", description: "Cría de animales y obtención de productos de origen animal n.c.p." },
|
||||
{ code: "016111", description: "Servicios de labranza, siembra, transplante y cuidados culturales" },
|
||||
{ code: "016112", description: "Servicios de pulverización, desinfección y fumigación terrestre" },
|
||||
{ code: "016113", description: "Servicios de pulverización, desinfección y fumigación aérea" },
|
||||
{ code: "016119", description: "Servicios de maquinaria agrícola n.c.p., excepto los de cosecha mecánica" },
|
||||
{ code: "016120", description: "Servicios de cosecha mecánica" },
|
||||
{ code: "016130", description: "Servicios de contratistas de mano de obra agrícola" },
|
||||
{ code: "016140", description: "Servicios de post cosecha" },
|
||||
{ code: "016150", description: "Servicios de procesamiento de semillas para su siembra" },
|
||||
{ code: "016190", description: "Servicios de apoyo agrícolas n.c.p." },
|
||||
{ code: "016210", description: "Inseminación artificial y servicios n.c.p. para mejorar la reproducción de los animales y el rendimiento de sus productos" },
|
||||
{ code: "016220", description: "Servicios de contratistas de mano de obra pecuaria" },
|
||||
{ code: "016230", description: "Servicios de esquila de animales" },
|
||||
{ code: "016291", description: "Servicios para el control de plagas, baños parasiticidas, etc." },
|
||||
{ code: "016292", description: "Albergue y cuidado de animales de terceros" },
|
||||
{ code: "016299", description: "Servicios de apoyo pecuarios n.c.p." },
|
||||
{ code: "551010", description: "Servicios de alojamiento por hora" },
|
||||
{ code: "551021", description: "Servicios de alojamiento en pensiones" },
|
||||
{ code: "551022", description: "Servicios de alojamiento en hoteles, hosterías y residenciales similares, excepto por hora, que incluyen servicio de restaurante al público" },
|
||||
{ code: "551023", description: "Servicios de alojamiento en hoteles, hosterías y residenciales similares, excepto por hora, que no incluyen servicio de restaurante al público" },
|
||||
{ code: "561011", description: "Servicios de restaurantes y cantinas sin espectáculo" },
|
||||
{ code: "561012", description: "Servicios de restaurantes y cantinas con espectáculo" },
|
||||
{ code: "561013", description: "Servicios de fast food y locales de venta de comidas y bebidas al paso" },
|
||||
{ code: "561014", description: "Servicios de expendio de bebidas en bares" },
|
||||
{ code: "561019", description: "Servicios de expendio de comidas y bebidas en establecimientos con servicio de mesa y/o en mostrador n.c.p." },
|
||||
{ code: "620100", description: "Servicios de consultores en informática y suministros de programas de informática" },
|
||||
{ code: "620200", description: "Servicios de consultores en equipo de informática" },
|
||||
{ code: "620300", description: "Servicios de consultores en tecnología de la información" },
|
||||
{ code: "620900", description: "Servicios de informática n.c.p." },
|
||||
{ code: "681098", description: "Servicios inmobiliarios realizados por cuenta propia, con bienes urbanos propios o arrendados n.c.p." },
|
||||
{ code: "681099", description: "Servicios inmobiliarios realizados por cuenta propia, con bienes rurales propios o arrendados n.c.p." },
|
||||
{ code: "691001", description: "Servicios jurídicos" },
|
||||
{ code: "692000", description: "Servicios de contabilidad, auditoría y asesoría fiscal" },
|
||||
{ code: "702091", description: "Servicios de asesoramiento, dirección y gestión empresarial realizados por integrantes de los órganos de administración y/o fiscalización en sociedades anónimas" },
|
||||
{ code: "702092", description: "Servicios de asesoramiento, dirección y gestión empresarial realizados por integrantes de cuerpos de dirección en sociedades excepto las anónimas" },
|
||||
{ code: "702099", description: "Servicios de asesoramiento, dirección y gestión empresarial n.c.p." },
|
||||
{ code: "749009", description: "Actividades profesionales, científicas y técnicas n.c.p." },
|
||||
{ code: "851010", description: "Guarderías y jardines maternales" },
|
||||
{ code: "851020", description: "Enseñanza inicial, jardín de infantes y primaria" },
|
||||
{ code: "852100", description: "Enseñanza secundaria de formación general" },
|
||||
{ code: "852200", description: "Enseñanza secundaria de formación técnica y profesional" },
|
||||
{ code: "853100", description: "Enseñanza terciaria" },
|
||||
{ code: "853201", description: "Enseñanza universitaria excepto formación de posgrado" },
|
||||
{ code: "853300", description: "Formación de posgrado" },
|
||||
{ code: "854910", description: "Enseñanza de idiomas" },
|
||||
{ code: "854920", description: "Enseñanza de cursos relacionados con informática" },
|
||||
{ code: "854930", description: "Enseñanza para adultos, excepto discapacitados" },
|
||||
{ code: "854940", description: "Enseñanza especial y para discapacitados" },
|
||||
{ code: "854950", description: "Enseñanza de gimnasia, deportes y actividades físicas" },
|
||||
{ code: "854960", description: "Enseñanza artística" },
|
||||
{ code: "854990", description: "Servicios de enseñanza n.c.p." },
|
||||
{ code: "855000", description: "Servicios de apoyo a la educación" },
|
||||
{ code: "861010", description: "Servicios de internación" },
|
||||
{ code: "862110", description: "Servicios de consulta médica" },
|
||||
{ code: "862120", description: "Servicios de atención médica en dispensarios, salitas, vacunatorios y otros locales de atención primaria de la salud" },
|
||||
{ code: "862130", description: "Servicios de atención médica en otros establecimientos n.c.p." },
|
||||
{ code: "862200", description: "Servicios odontológicos" },
|
||||
{ code: "869010", description: "Servicios de prácticas de diagnóstico en laboratorios" },
|
||||
{ code: "869090", description: "Servicios relacionados con la salud humana n.c.p." },
|
||||
{ code: "900011", description: "Producción de espectáculos teatrales y musicales" },
|
||||
{ code: "900021", description: "Composición y representación de obras teatrales, musicales y artísticas" },
|
||||
{ code: "931010", description: "Servicios de organización, dirección y gestión de prácticas deportivas y explotación de las instalaciones" },
|
||||
{ code: "931020", description: "Servicios prestados por profesionales y técnicos para la realización de prácticas deportivas" },
|
||||
{ code: "960201", description: "Servicios de peluquería" },
|
||||
{ code: "960202", description: "Servicios de tratamiento de belleza, excepto los de peluquería" },
|
||||
{ code: "960990", description: "Servicios personales n.c.p." },
|
||||
];
|
||||
|
||||
export const findArcaActivityByCode = (code: string): ArcaActivity | undefined => {
|
||||
return ARCA_ACTIVITIES.find((activity) => activity.code === code.trim());
|
||||
};
|
||||
|
||||
export const filterArcaActivities = (name?: string): TextObjectFilterResult[] => {
|
||||
const normalizedFilter = (name || "").trim().toLowerCase();
|
||||
|
||||
return ARCA_ACTIVITIES.filter((activity) => {
|
||||
if (!normalizedFilter) return true;
|
||||
|
||||
return (
|
||||
activity.code.includes(normalizedFilter) ||
|
||||
activity.description.toLowerCase().includes(normalizedFilter)
|
||||
);
|
||||
}).map((activity) => ({
|
||||
id: activity.code,
|
||||
name: activity.description,
|
||||
description: activity.code,
|
||||
}));
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
ARCA_CREDENTIAL_STATUS,
|
||||
CreateArcaCredentialParams,
|
||||
FindArcaCredentialsParams,
|
||||
IArcaCredential,
|
||||
IArcaCredentialsAdapter,
|
||||
UpdateArcaCredentialParams,
|
||||
} from "./ArcaCredentials.Interface";
|
||||
|
||||
export interface IArcaCredentialDocument extends Omit<IArcaCredential, "id">, Document {}
|
||||
|
||||
export class ArcaCredentialsAdapterMongoose implements IArcaCredentialsAdapter {
|
||||
schema: Schema;
|
||||
arcaCredentialList: Model<IArcaCredentialDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema({
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
unique: true,
|
||||
index: true,
|
||||
},
|
||||
csrPem: { type: String, required: false },
|
||||
certificatePem: { type: String, required: false },
|
||||
encryptedPrivateKey: { type: String, required: true },
|
||||
privateKeyIv: { type: String, required: true },
|
||||
privateKeyAuthTag: { type: String, required: true },
|
||||
encryptionKeyVersion: { type: String, required: false, default: "v1" },
|
||||
status: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(ARCA_CREDENTIAL_STATUS),
|
||||
index: true,
|
||||
},
|
||||
certificateValidFrom: { type: Date, required: false },
|
||||
certificateValidTo: { type: Date, required: false },
|
||||
lastValidationError: { type: String, required: false },
|
||||
createdAt: { type: Date, required: true, default: Date.now },
|
||||
updatedAt: { type: Date, required: true, default: Date.now },
|
||||
});
|
||||
|
||||
this.arcaCredentialList = model<IArcaCredentialDocument>("ArcaCredential", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: CreateArcaCredentialParams): Promise<IArcaCredential> {
|
||||
return await this.arcaCredentialList.create(data);
|
||||
}
|
||||
|
||||
private buildSearchCriteria(filters: FindArcaCredentialsParams): FilterQuery<IArcaCredential> {
|
||||
const searchCriteria: FilterQuery<IArcaCredential> = {};
|
||||
|
||||
if (filters.id) searchCriteria._id = filters.id;
|
||||
if (filters.companyId) searchCriteria.companyId = filters.companyId;
|
||||
if (filters.status) searchCriteria.status = filters.status;
|
||||
|
||||
return searchCriteria;
|
||||
}
|
||||
|
||||
public async find(filters: FindArcaCredentialsParams): Promise<IArcaCredential[]> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.arcaCredentialList.find(searchCriteria).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
public async findOne(filters: FindArcaCredentialsParams): Promise<IArcaCredentialDocument | null> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.arcaCredentialList.findOne(searchCriteria).exec();
|
||||
}
|
||||
|
||||
public async update(data: UpdateArcaCredentialParams): Promise<IArcaCredentialDocument | null> {
|
||||
const { id, companyId, sessionUser, ...updateData } = data;
|
||||
|
||||
if (!id && !companyId) {
|
||||
throw new Error("Se requiere un identificador para actualizar las credenciales ARCA");
|
||||
}
|
||||
|
||||
return this.arcaCredentialList
|
||||
.findOneAndUpdate(this.buildSearchCriteria({ id, companyId, sessionUser }), updateData, { new: true })
|
||||
.exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { IArcaCredentialDocument } from "./ArcaCredentials.Adapter.Mongoose";
|
||||
import { ARCA_WSAA_ENVIRONMENT, ARCA_WSAA_SERVICE } from "../ArcaWsaaTokens/ArcaWsaaTokens.Interface";
|
||||
|
||||
export enum ARCA_CREDENTIAL_STATUS {
|
||||
CSR_GENERATED = "CSR_GENERATED",
|
||||
CERTIFICATE_UPLOADED = "CERTIFICATE_UPLOADED",
|
||||
READY = "READY",
|
||||
INVALID = "INVALID",
|
||||
DISABLED = "DISABLED",
|
||||
}
|
||||
|
||||
export type GenerateArcaCredentialCsrParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type UploadArcaCredentialCertificateParams = {
|
||||
companyId: string;
|
||||
certificatePem: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type TestArcaWsaaLoginParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ArcaWsaaLoginTestResult = {
|
||||
status: "cached" | "created";
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
endpoints: ArcaEndpointMetadata;
|
||||
expirationTime: Date;
|
||||
cached: boolean;
|
||||
};
|
||||
|
||||
export type ArcaWsfeLastVoucherParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ArcaWsfeLastVoucherResult = {
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
endpoints: ArcaEndpointMetadata;
|
||||
pointOfSale: number;
|
||||
voucherType: 11;
|
||||
lastVoucherNumber: number;
|
||||
};
|
||||
|
||||
export type ArcaWsfeIssueFacturaCParams = {
|
||||
companyId: string;
|
||||
amount: number;
|
||||
billingDate: Date;
|
||||
servicePeriodFrom: Date;
|
||||
servicePeriodTo: Date;
|
||||
paymentDueDate: Date;
|
||||
receiverDocumentType?: number | string;
|
||||
receiverDocumentNumber?: number | string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ArcaWsfeIssueFacturaCResult = {
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
endpoints: ArcaEndpointMetadata;
|
||||
pointOfSale: number;
|
||||
voucherType: 11;
|
||||
voucherNumber: number;
|
||||
cae: string;
|
||||
caeExpiresAt: Date;
|
||||
};
|
||||
|
||||
export type ArcaWsfeIssueFacturaCAttempt = {
|
||||
pointOfSale: number;
|
||||
voucherType: 11;
|
||||
voucherNumber: number;
|
||||
};
|
||||
|
||||
export type ArcaWsfeDiagnosticsParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ArcaEndpointMetadata = {
|
||||
wsaaHost?: string;
|
||||
wsfeHost?: string;
|
||||
};
|
||||
|
||||
export type ArcaWsfeDiagnosticsResult = {
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
endpoints: ArcaEndpointMetadata;
|
||||
dummy: {
|
||||
ok: boolean;
|
||||
appServer?: string;
|
||||
dbServer?: string;
|
||||
authServer?: string;
|
||||
error?: string;
|
||||
};
|
||||
voucherTypes: {
|
||||
ok: boolean;
|
||||
count?: number;
|
||||
includesFacturaC?: boolean;
|
||||
error?: string;
|
||||
};
|
||||
pointsOfSale: {
|
||||
ok: boolean;
|
||||
points?: number[];
|
||||
includesConfiguredPointOfSale?: boolean;
|
||||
configuredPointOfSale: number;
|
||||
error?: string;
|
||||
};
|
||||
lastVoucher: {
|
||||
ok: boolean;
|
||||
pointOfSale: number;
|
||||
voucherType: 11;
|
||||
lastVoucherNumber?: number;
|
||||
error?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type FindArcaCredentialsParams = {
|
||||
id?: string;
|
||||
companyId?: string;
|
||||
status?: ARCA_CREDENTIAL_STATUS;
|
||||
sessionUser?: string;
|
||||
};
|
||||
|
||||
export type CreateArcaCredentialParams = {
|
||||
companyId: string;
|
||||
csrPem?: string;
|
||||
certificatePem?: string;
|
||||
encryptedPrivateKey: string;
|
||||
privateKeyIv: string;
|
||||
privateKeyAuthTag: string;
|
||||
encryptionKeyVersion?: string;
|
||||
status: ARCA_CREDENTIAL_STATUS;
|
||||
certificateValidFrom?: Date;
|
||||
certificateValidTo?: Date;
|
||||
lastValidationError?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type UpdateArcaCredentialParams = FindArcaCredentialsParams & {
|
||||
csrPem?: string;
|
||||
certificatePem?: string;
|
||||
encryptedPrivateKey?: string;
|
||||
privateKeyIv?: string;
|
||||
privateKeyAuthTag?: string;
|
||||
encryptionKeyVersion?: string;
|
||||
status?: ARCA_CREDENTIAL_STATUS;
|
||||
certificateValidFrom?: Date;
|
||||
certificateValidTo?: Date;
|
||||
lastValidationError?: string;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export interface IArcaCredential {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
csrPem?: string;
|
||||
certificatePem?: string;
|
||||
encryptedPrivateKey: string;
|
||||
privateKeyIv: string;
|
||||
privateKeyAuthTag: string;
|
||||
encryptionKeyVersion?: string;
|
||||
status: ARCA_CREDENTIAL_STATUS;
|
||||
certificateValidFrom?: Date;
|
||||
certificateValidTo?: Date;
|
||||
lastValidationError?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export type ArcaCredentialView = Omit<
|
||||
IArcaCredential,
|
||||
"encryptedPrivateKey" | "privateKeyIv" | "privateKeyAuthTag"
|
||||
>;
|
||||
|
||||
export interface IArcaCredentialsAdapter {
|
||||
create(data: CreateArcaCredentialParams): Promise<IArcaCredential>;
|
||||
find(filters: FindArcaCredentialsParams): Promise<IArcaCredential[]>;
|
||||
findOne(filters: FindArcaCredentialsParams): Promise<IArcaCredentialDocument | null>;
|
||||
update(data: UpdateArcaCredentialParams): Promise<IArcaCredentialDocument | null>;
|
||||
}
|
||||
|
||||
export interface IArcaCredentialsManager {
|
||||
arcaCredentials: IArcaCredentialsAdapter;
|
||||
generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView>;
|
||||
uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView>;
|
||||
testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult>;
|
||||
getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult>;
|
||||
issueFacturaC(data: ArcaWsfeIssueFacturaCParams): Promise<ArcaWsfeIssueFacturaCResult>;
|
||||
getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult>;
|
||||
find(data: FindArcaCredentialsParams): Promise<ArcaCredentialView[]>;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,97 @@
|
||||
import { Document, FilterQuery, Model, Schema, model, models } from "mongoose";
|
||||
import {
|
||||
ARCA_WSAA_ENVIRONMENT,
|
||||
ARCA_WSAA_SERVICE,
|
||||
ArcaWsaaTokenLookupParams,
|
||||
CreateArcaWsaaTokenParams,
|
||||
IArcaWsaaToken,
|
||||
IArcaWsaaTokensAdapter,
|
||||
UpdateArcaWsaaTokenParams,
|
||||
} from "./ArcaWsaaTokens.Interface";
|
||||
|
||||
export interface IArcaWsaaTokenDocument extends Omit<IArcaWsaaToken, "id">, Document {}
|
||||
|
||||
export class ArcaWsaaTokensAdapterMongoose implements IArcaWsaaTokensAdapter {
|
||||
schema: Schema;
|
||||
arcaWsaaTokenList: Model<IArcaWsaaTokenDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema({
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
index: true,
|
||||
},
|
||||
service: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(ARCA_WSAA_SERVICE),
|
||||
index: true,
|
||||
},
|
||||
environment: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(ARCA_WSAA_ENVIRONMENT),
|
||||
index: true,
|
||||
},
|
||||
token: { type: String, required: true },
|
||||
sign: { type: String, required: true },
|
||||
generationTime: { type: Date, required: false },
|
||||
expirationTime: { type: Date, required: true, index: true },
|
||||
createdAt: { type: Date, required: true, default: Date.now },
|
||||
updatedAt: { type: Date, required: true, default: Date.now },
|
||||
});
|
||||
|
||||
this.schema.index({ companyId: 1, service: 1, environment: 1 }, { unique: true });
|
||||
|
||||
this.arcaWsaaTokenList =
|
||||
models.ArcaWsaaToken || model<IArcaWsaaTokenDocument>("ArcaWsaaToken", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
|
||||
return await this.arcaWsaaTokenList.create(data);
|
||||
}
|
||||
|
||||
private buildSearchCriteria(
|
||||
filters: Partial<ArcaWsaaTokenLookupParams>
|
||||
): FilterQuery<IArcaWsaaToken> {
|
||||
const searchCriteria: FilterQuery<IArcaWsaaToken> = {};
|
||||
|
||||
if (filters.companyId) searchCriteria.companyId = filters.companyId;
|
||||
if (filters.service) searchCriteria.service = filters.service;
|
||||
if (filters.environment) searchCriteria.environment = filters.environment;
|
||||
|
||||
return searchCriteria;
|
||||
}
|
||||
|
||||
public async find(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaToken[]> {
|
||||
return this.arcaWsaaTokenList.find(this.buildSearchCriteria(filters)).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: Partial<ArcaWsaaTokenLookupParams>
|
||||
): Promise<IArcaWsaaTokenDocument | null> {
|
||||
return this.arcaWsaaTokenList.findOne(this.buildSearchCriteria(filters)).exec();
|
||||
}
|
||||
|
||||
public async update(data: UpdateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null> {
|
||||
const { companyId, service, environment, ...updateData } = data;
|
||||
return this.arcaWsaaTokenList
|
||||
.findOneAndUpdate(this.buildSearchCriteria({ companyId, service, environment }), updateData, {
|
||||
new: true,
|
||||
})
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async upsert(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null> {
|
||||
const { companyId, service, environment, createdAt, ...updateData } = data;
|
||||
return this.arcaWsaaTokenList
|
||||
.findOneAndUpdate(
|
||||
this.buildSearchCriteria({ companyId, service, environment }),
|
||||
{ $set: updateData, $setOnInsert: { companyId, service, environment, createdAt } },
|
||||
{ new: true, upsert: true }
|
||||
)
|
||||
.exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { IArcaWsaaTokenDocument } from "./ArcaWsaaTokens.Adapter.Mongoose";
|
||||
|
||||
export enum ARCA_WSAA_SERVICE {
|
||||
WSFE = "wsfe",
|
||||
}
|
||||
|
||||
export enum ARCA_WSAA_ENVIRONMENT {
|
||||
HOMOLOGATION = "homologation",
|
||||
PRODUCTION = "production",
|
||||
}
|
||||
|
||||
export type ArcaWsaaTokenLookupParams = {
|
||||
companyId: string;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
};
|
||||
|
||||
export type CreateArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
|
||||
token: string;
|
||||
sign: string;
|
||||
generationTime?: Date;
|
||||
expirationTime: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type UpdateArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
|
||||
token?: string;
|
||||
sign?: string;
|
||||
generationTime?: Date;
|
||||
expirationTime?: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type UpsertArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
|
||||
token: string;
|
||||
sign: string;
|
||||
generationTime?: Date;
|
||||
expirationTime: Date;
|
||||
};
|
||||
|
||||
export interface IArcaWsaaToken {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
service: ARCA_WSAA_SERVICE;
|
||||
environment: ARCA_WSAA_ENVIRONMENT;
|
||||
token: string;
|
||||
sign: string;
|
||||
generationTime?: Date;
|
||||
expirationTime: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface IArcaWsaaTokensAdapter {
|
||||
create(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
|
||||
find(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaToken[]>;
|
||||
findOne(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaTokenDocument | null>;
|
||||
update(data: UpdateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null>;
|
||||
upsert(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null>;
|
||||
}
|
||||
|
||||
export interface IArcaWsaaTokensManager {
|
||||
arcaWsaaTokens: IArcaWsaaTokensAdapter;
|
||||
getValidToken(data: ArcaWsaaTokenLookupParams): Promise<IArcaWsaaToken | null>;
|
||||
saveToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
|
||||
upsertToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ArcaWsaaTokensAdapterMongoose } from "./ArcaWsaaTokens.Adapter.Mongoose";
|
||||
import {
|
||||
ArcaWsaaTokenLookupParams,
|
||||
IArcaWsaaToken,
|
||||
IArcaWsaaTokensManager,
|
||||
UpsertArcaWsaaTokenParams,
|
||||
} from "./ArcaWsaaTokens.Interface";
|
||||
|
||||
const TOKEN_REUSE_SKEW_MS = 10 * 60 * 1000;
|
||||
|
||||
class ArcaWsaaTokensManager implements IArcaWsaaTokensManager {
|
||||
arcaWsaaTokens: ArcaWsaaTokensAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.arcaWsaaTokens = new ArcaWsaaTokensAdapterMongoose();
|
||||
}
|
||||
|
||||
public async getValidToken(data: ArcaWsaaTokenLookupParams): Promise<IArcaWsaaToken | null> {
|
||||
const existingToken = await this.arcaWsaaTokens.findOne(data);
|
||||
|
||||
if (!existingToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const reuseUntil = Date.now() + TOKEN_REUSE_SKEW_MS;
|
||||
if (new Date(existingToken.expirationTime).getTime() <= reuseUntil) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return existingToken;
|
||||
}
|
||||
|
||||
public async saveToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
|
||||
const now = new Date();
|
||||
return await this.arcaWsaaTokens.create({
|
||||
...data,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
public async upsertToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
|
||||
const now = new Date();
|
||||
const token = await this.arcaWsaaTokens.upsert({
|
||||
...data,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
throw new Error("No se pudo guardar el token WSAA de ARCA");
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
export default new ArcaWsaaTokensManager();
|
||||
@@ -67,6 +67,9 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
|
||||
fixedPostIds: { type: Array, required: false },
|
||||
banned: { type: Boolean, required: false, default: false },
|
||||
showPublicScores: { type: Boolean, required: false, default: true },
|
||||
showPublicOpinions: { type: Boolean, required: false, default: true },
|
||||
showPublicProfessionals: { type: Boolean, required: false, default: true },
|
||||
});
|
||||
|
||||
this.companyList = model<ICompanyDocument>("Company", this.schema);
|
||||
@@ -235,6 +238,18 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.banned = data.banned;
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined) {
|
||||
updateCompany.showPublicScores = data.showPublicScores;
|
||||
}
|
||||
|
||||
if (data.showPublicOpinions !== undefined) {
|
||||
updateCompany.showPublicOpinions = data.showPublicOpinions;
|
||||
}
|
||||
|
||||
if (data.showPublicProfessionals !== undefined) {
|
||||
updateCompany.showPublicProfessionals = data.showPublicProfessionals;
|
||||
}
|
||||
|
||||
updateCompany.save();
|
||||
|
||||
//actualizo los campos correspondientes a la localizacion de los servicios de la organizacion.
|
||||
|
||||
@@ -54,6 +54,9 @@ export type UpdateCompanyParams = {
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type SetCompanyFileParams = {
|
||||
@@ -154,6 +157,9 @@ export interface ICompany {
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface MyOranizationsView {
|
||||
@@ -203,6 +209,9 @@ export interface MyOranizationsView {
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface ClientOrganizationView {
|
||||
@@ -255,6 +264,75 @@ export type SysAdminSetCompanyBannedParams = {
|
||||
banned: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminCompanyInsightsParams = {
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
export type SysAdminCompanyInsightsResult = {
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
categoryId: number;
|
||||
banned: boolean;
|
||||
published?: COMPANY_PUBLISHED_STATUS;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
};
|
||||
owner: {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
verificated?: boolean;
|
||||
phoneCountryCode?: string;
|
||||
phoneAreaCode?: string;
|
||||
phoneNumber?: string;
|
||||
} | null;
|
||||
collaborators: {
|
||||
id: string;
|
||||
userId?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
fullName?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
removed?: boolean;
|
||||
active: boolean;
|
||||
avatar?: string;
|
||||
}[];
|
||||
subscription: {
|
||||
id: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
isActive: boolean;
|
||||
autoRenew: boolean;
|
||||
mpStatus?: string;
|
||||
pendingPaymentType?: "extension" | "upgrade";
|
||||
plan: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
price: number;
|
||||
limitOrganizations: number;
|
||||
limitEmployees: number;
|
||||
limitServices: number;
|
||||
limitAppointments: number;
|
||||
limitClients: number;
|
||||
} | null;
|
||||
} | null;
|
||||
stats: {
|
||||
employeesCount: number;
|
||||
activeEmployeesCount: number;
|
||||
servicesCount: number;
|
||||
activeServicesCount: number;
|
||||
clientsCount: number;
|
||||
activeClientsCount: number;
|
||||
reservationsLast30Days: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type FixCompanyPostParams = {
|
||||
companyId: string;
|
||||
postId: string;
|
||||
@@ -301,4 +379,5 @@ export interface ICompaniesManager {
|
||||
sysAdminPaginate(data: SysAdminPaginateCompaniesParams): Promise<PaginateCompaniesResults>;
|
||||
sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>;
|
||||
sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>;
|
||||
sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult>;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
SysAdminPaginateCompaniesParams,
|
||||
SysAdminUpdateCompanyParams,
|
||||
SysAdminSetCompanyBannedParams,
|
||||
SysAdminCompanyInsightsParams,
|
||||
SysAdminCompanyInsightsResult,
|
||||
} from "./Companies.Interface";
|
||||
import UsersManager from "../Users/Users";
|
||||
import EmployeesList from "../Employees/Employee";
|
||||
@@ -54,11 +56,14 @@ import ClientAccount from "../ClientAccounts/ClientAccount";
|
||||
import Payments from "../Payments/Payments";
|
||||
import Discounts from "../Discounts/Discounts";
|
||||
import Templates from "../Templates/Templates";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import PlansList from "../Plans/Plans";
|
||||
|
||||
import Posts from "../Posts/Posts";
|
||||
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
||||
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
|
||||
class CompaniesManager implements ICompaniesManager {
|
||||
companies: ICompaniesAdapter;
|
||||
@@ -67,6 +72,17 @@ class CompaniesManager implements ICompaniesManager {
|
||||
this.companies = new CompaniesAdapterMongoose();
|
||||
}
|
||||
|
||||
private async validatePublicRatingFlagsPlan(ownerId: string): Promise<void> {
|
||||
const { default: PlanSubscriptionsList } = await import("../PlanSubscriptions/PlanSubscriptons");
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: ownerId,
|
||||
});
|
||||
|
||||
if (!subscription || subscription.plan.price === 0) {
|
||||
throw new Error("Esta configuración está disponible solo para planes pagos.");
|
||||
}
|
||||
}
|
||||
|
||||
public async toggleFixedPost(data: FixCompanyPostParams): Promise<void> {
|
||||
await validateSessionUser({
|
||||
sessionUser: data.sessionUser,
|
||||
@@ -489,6 +505,14 @@ class CompaniesManager implements ICompaniesManager {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
|
||||
if (
|
||||
data.showPublicScores !== undefined ||
|
||||
data.showPublicOpinions !== undefined ||
|
||||
data.showPublicProfessionals !== undefined
|
||||
) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
let updateData = {
|
||||
...data,
|
||||
};
|
||||
@@ -597,6 +621,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -660,7 +687,11 @@ class CompaniesManager implements ICompaniesManager {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isAdmin = await EmployeesList.checkPermission(companyDoc, employ.id, EmployeeRoles.ADMIN);
|
||||
const isAdmin = await EmployeesList.checkPermission(
|
||||
companyDoc,
|
||||
data.sessionUser,
|
||||
EmployeeRoles.ADMIN
|
||||
);
|
||||
|
||||
returnData.push({
|
||||
id: isNull<string>(company.id, ""),
|
||||
@@ -716,6 +747,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -786,6 +820,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1053,6 +1090,137 @@ class CompaniesManager implements ICompaniesManager {
|
||||
sessionUser: "" // sysadmin override
|
||||
});
|
||||
}
|
||||
|
||||
public async sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult> {
|
||||
const company = await this.companies.findOne({ _id: data.companyId });
|
||||
if (!company) {
|
||||
throw new Error("La compañia no existe");
|
||||
}
|
||||
|
||||
const [ownerResult, subscriptionResult] = await Promise.allSettled([
|
||||
UsersManager.users.findOne({ _id: String(company.ownerId) }),
|
||||
PlanSubscriptionsList.planSuscriptions.planSuscriptionList
|
||||
.findOne({ userId: String(company.ownerId) })
|
||||
.sort({ endDate: -1 })
|
||||
.exec(),
|
||||
]);
|
||||
const owner = ownerResult.status === "fulfilled" ? ownerResult.value : null;
|
||||
const subscription = subscriptionResult.status === "fulfilled" ? subscriptionResult.value : null;
|
||||
const collaboratorsResult = await Promise.allSettled([
|
||||
EmployeesList.employees.employeeList.find({ companyId: data.companyId }).exec(),
|
||||
]);
|
||||
const employeeDocs = collaboratorsResult[0]?.status === "fulfilled" ? collaboratorsResult[0].value : [];
|
||||
const collaboratorUserResults = await Promise.allSettled(
|
||||
employeeDocs.map((employee) => employee.userId
|
||||
? UsersManager.users.findOne({ _id: String(employee.userId) })
|
||||
: Promise.resolve(null))
|
||||
);
|
||||
const collaborators = employeeDocs.map((employee, index) => {
|
||||
const userResult = collaboratorUserResults[index];
|
||||
const user = userResult?.status === "fulfilled" ? userResult.value : null;
|
||||
const firstName = user?.firstName || employee.profileSnapshot?.firstName;
|
||||
const lastName = user?.lastName || employee.profileSnapshot?.lastName;
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(" ");
|
||||
const avatar = user?.avatar
|
||||
? getAvatar(String(user.id || user._id), user.avatar, fullName)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: String(employee.id || employee._id),
|
||||
userId: employee.userId ? String(employee.userId) : undefined,
|
||||
firstName,
|
||||
lastName,
|
||||
fullName: fullName || undefined,
|
||||
email: user?.email || employee.profileSnapshot?.email,
|
||||
roles: employee.roles || [],
|
||||
removed: employee.removed ?? false,
|
||||
active: !(employee.removed ?? false),
|
||||
avatar: avatar !== fullName ? avatar : undefined,
|
||||
};
|
||||
});
|
||||
const planResult = subscription
|
||||
? await Promise.allSettled([PlansList.plans.planList.findOne({ _id: String(subscription.planId) }).exec()])
|
||||
: [];
|
||||
const plan = planResult[0]?.status === "fulfilled" ? planResult[0].value : null;
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setUTCDate(thirtyDaysAgo.getUTCDate() - 30);
|
||||
thirtyDaysAgo.setUTCHours(0, 0, 0, 0);
|
||||
|
||||
const [
|
||||
employeesCount,
|
||||
activeEmployeesCount,
|
||||
servicesCount,
|
||||
activeServicesCount,
|
||||
clientsCount,
|
||||
activeClientsCount,
|
||||
reservationsLast30Days,
|
||||
] = (await Promise.allSettled([
|
||||
EmployeesList.employees.employeeList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
EmployeesList.employees.employeeList.countDocuments({ companyId: data.companyId, removed: { $ne: true } }).exec(),
|
||||
ServiceList.services.serviceList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
ServiceList.services.serviceList.countDocuments({ companyId: data.companyId, banned: { $ne: true } }).exec(),
|
||||
ClientsList.clients.clientList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
ClientsList.clients.clientList.countDocuments({ companyId: data.companyId, status: true, banned: { $ne: true } }).exec(),
|
||||
AppointmentList.Appointments.AppointmentList.countDocuments({
|
||||
companyId: data.companyId,
|
||||
start: { $gte: thirtyDaysAgo },
|
||||
}).exec(),
|
||||
])).map((result) => result.status === "fulfilled" ? result.value : 0);
|
||||
|
||||
return {
|
||||
organization: {
|
||||
id: String(company.id || company._id),
|
||||
name: company.name,
|
||||
slug: company.slug,
|
||||
description: company.description,
|
||||
categoryId: company.categoryId,
|
||||
banned: company.banned ?? false,
|
||||
published: company.published,
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
},
|
||||
owner: owner ? {
|
||||
id: String(owner.id || owner._id),
|
||||
firstName: owner.firstName,
|
||||
lastName: owner.lastName,
|
||||
email: owner.email,
|
||||
verificated: owner.verificated,
|
||||
phoneCountryCode: owner.phoneCountryCode,
|
||||
phoneAreaCode: owner.phoneAreaCode,
|
||||
phoneNumber: owner.phoneNumber,
|
||||
} : null,
|
||||
collaborators,
|
||||
subscription: subscription ? {
|
||||
id: String(subscription.id || subscription._id),
|
||||
startDate: subscription.startDate,
|
||||
endDate: subscription.endDate,
|
||||
isActive: subscription.isActive,
|
||||
autoRenew: subscription.autoRenew,
|
||||
mpStatus: subscription.mpStatus,
|
||||
pendingPaymentType: subscription.pendingPaymentType,
|
||||
plan: plan ? {
|
||||
id: String(plan.id || plan._id),
|
||||
name: plan.name,
|
||||
code: plan.code,
|
||||
price: plan.price,
|
||||
limitOrganizations: plan.limitOrganizations,
|
||||
limitEmployees: plan.limitEmployees,
|
||||
limitServices: plan.limitServices,
|
||||
limitAppointments: plan.limitAppointments,
|
||||
limitClients: plan.limitClients,
|
||||
} : null,
|
||||
} : null,
|
||||
stats: {
|
||||
employeesCount,
|
||||
activeEmployeesCount,
|
||||
servicesCount,
|
||||
activeServicesCount,
|
||||
clientsCount,
|
||||
activeClientsCount,
|
||||
reservationsLast30Days,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const CompaniesList = new CompaniesManager();
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
PaginateEmployeesParams,
|
||||
PaginateEmployeesResults,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesParams,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
@@ -442,6 +445,71 @@ class EmployeeManager implements IEmployeesManager {
|
||||
return view;
|
||||
}
|
||||
|
||||
public async findPublicByCompanyId(
|
||||
data: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> {
|
||||
const employees = await this.employees.find({
|
||||
companyId: data.companyId,
|
||||
guestOk: true,
|
||||
hostOk: true,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
const view = await Promise.all(
|
||||
employees.map(async (employee) => {
|
||||
const userData = await UsersManager.users.findOne({ _id: employee.userId });
|
||||
|
||||
if (!userData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const strFirstName = isNull<string>(userData.firstName, "");
|
||||
const strLastName = isNull<string>(userData.lastName, "");
|
||||
const strFullName = joinStrings([strFirstName, strLastName], " ");
|
||||
|
||||
return {
|
||||
employeeId: isNull<string>(employee.id, ""),
|
||||
userId: employee.userId,
|
||||
firstName: strFirstName,
|
||||
lastName: strLastName,
|
||||
avatarUrl: getAvatar(userData.id, userData.avatar, strFullName),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return view.filter((employee): employee is PublicCompanyEmployeeView => employee !== null);
|
||||
}
|
||||
|
||||
public async findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView> {
|
||||
const employee = await this.employees.findOne({
|
||||
_id: data.employeeId,
|
||||
guestOk: true,
|
||||
hostOk: true,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employee) {
|
||||
throw new Error("El colaborador no existe");
|
||||
}
|
||||
|
||||
const userData = await UsersManager.users.findOne({ _id: employee.userId });
|
||||
|
||||
if (!userData) {
|
||||
throw new Error("El colaborador no existe");
|
||||
}
|
||||
|
||||
const strFirstName = isNull<string>(userData.firstName, "");
|
||||
const strLastName = isNull<string>(userData.lastName, "");
|
||||
const strFullName = joinStrings([strFirstName, strLastName], " ");
|
||||
|
||||
return {
|
||||
employeeId: isNull<string>(employee.id, ""),
|
||||
firstName: strFirstName,
|
||||
lastName: strLastName,
|
||||
avatarUrl: getAvatar(userData.id, userData.avatar, strFullName),
|
||||
};
|
||||
}
|
||||
|
||||
public async findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView> {
|
||||
const employee = await this.employees.findOne({ _id: data.id });
|
||||
|
||||
|
||||
@@ -119,6 +119,25 @@ export interface CompanyEmployeesView {
|
||||
};
|
||||
}
|
||||
|
||||
export interface PublicCompanyEmployeeView {
|
||||
employeeId: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
}
|
||||
|
||||
export interface FindPublicEmployeeParams {
|
||||
employeeId: string;
|
||||
}
|
||||
|
||||
export interface PublicEmployeeView {
|
||||
employeeId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
}
|
||||
|
||||
export interface IncompleteCollaboratorView {
|
||||
employeeId: string;
|
||||
companyId: string;
|
||||
@@ -143,6 +162,8 @@ export interface IEmployeesManager {
|
||||
updateEmployeeRoles(data: UpdateEmployeeRolesParams): Promise<void>;
|
||||
update(data: UpdateEmployeeParams): Promise<void>;
|
||||
findByCompanyId(data: FindEmployeesParams): Promise<CompanyEmployeesView[]>;
|
||||
findPublicByCompanyId(data: FindEmployeesParams): Promise<PublicCompanyEmployeeView[]>;
|
||||
findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView>;
|
||||
findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView>;
|
||||
textObjectFilter(data: FindEmployeesParams): Promise<TextObjectFilterResult[]>;
|
||||
deleteEmployeesByCompany(data: DeleteEmployeesByCompany): Promise<void>;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
CreateInvoiceParams,
|
||||
FindInvoicesParams,
|
||||
IInvoice,
|
||||
IInvoicesAdapter,
|
||||
INVOICE_STATUS,
|
||||
INVOICE_TYPE,
|
||||
UpdateInvoiceParams,
|
||||
} from "./Invoices.Interface";
|
||||
|
||||
export interface IInvoiceDocument extends Omit<IInvoice, "id">, Document {}
|
||||
|
||||
export class InvoicesAdapterMongoose implements IInvoicesAdapter {
|
||||
schema: Schema;
|
||||
invoiceList: Model<IInvoiceDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema({
|
||||
cashMovementId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "CashFlow",
|
||||
unique: true,
|
||||
index: true,
|
||||
},
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
index: true,
|
||||
},
|
||||
clientId: { type: Schema.Types.ObjectId, required: false, ref: "Client" },
|
||||
paymentId: { type: Schema.Types.ObjectId, required: false, ref: "Payment" },
|
||||
clientAccountMovementId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: false,
|
||||
ref: "ClientAccountMovement",
|
||||
},
|
||||
appointmentId: { type: Schema.Types.ObjectId, required: false, ref: "Appointment" },
|
||||
amount: { type: Number, required: true },
|
||||
type: { type: String, required: true, enum: Object.values(INVOICE_TYPE) },
|
||||
status: { type: String, required: true, enum: Object.values(INVOICE_STATUS), index: true },
|
||||
billingDate: { type: Date, required: true },
|
||||
servicePeriodFrom: { type: Date, required: true },
|
||||
servicePeriodTo: { type: Date, required: true },
|
||||
paymentDueDate: { type: Date, required: true },
|
||||
activityCode: { type: String, required: true },
|
||||
activityDescription: { type: String, required: true },
|
||||
receiverIvaCondition: { type: Number, required: true, default: 5 },
|
||||
receiverDocumentType: { type: Schema.Types.Mixed, required: false },
|
||||
receiverDocumentNumber: { type: Schema.Types.Mixed, required: false },
|
||||
receiverName: { type: String, required: false },
|
||||
receiverAddress: { type: String, required: false },
|
||||
receiverEmail: { type: String, required: false },
|
||||
saleCondition: { type: String, required: true },
|
||||
itemDescription: { type: String, required: true },
|
||||
itemQuantity: { type: Number, required: true, default: 1 },
|
||||
itemUnit: { type: String, required: false },
|
||||
itemUnitPrice: { type: Number, required: true },
|
||||
itemDiscountPercent: { type: Number, required: true, default: 0 },
|
||||
itemDiscountAmount: { type: Number, required: true, default: 0 },
|
||||
itemSubtotal: { type: Number, required: true },
|
||||
cae: { type: String, required: false },
|
||||
caeExpiresAt: { type: Date, required: false },
|
||||
pointOfSale: { type: Number, required: false },
|
||||
voucherNumber: { type: Number, required: false },
|
||||
voucherType: { type: String, required: false },
|
||||
arcaErrorCode: { type: String, required: false },
|
||||
arcaErrorMessage: { type: String, required: false },
|
||||
createdAt: { type: Date, required: true, default: Date.now },
|
||||
updatedAt: { type: Date, required: true, default: Date.now },
|
||||
});
|
||||
|
||||
this.invoiceList = model<IInvoiceDocument>("Invoice", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: CreateInvoiceParams): Promise<IInvoice> {
|
||||
return await this.invoiceList.create(data);
|
||||
}
|
||||
|
||||
private buildSearchCriteria(filters: FindInvoicesParams): FilterQuery<IInvoice> {
|
||||
const searchCriteria: FilterQuery<IInvoice> = {};
|
||||
|
||||
if (filters.id) searchCriteria._id = filters.id;
|
||||
if (filters.cashMovementId) searchCriteria.cashMovementId = filters.cashMovementId;
|
||||
if (filters.cashMovementIds && filters.cashMovementIds.length > 0) {
|
||||
searchCriteria.cashMovementId = { $in: filters.cashMovementIds };
|
||||
}
|
||||
if (filters.companyId) searchCriteria.companyId = filters.companyId;
|
||||
if (filters.status) searchCriteria.status = filters.status;
|
||||
|
||||
return searchCriteria;
|
||||
}
|
||||
|
||||
public async find(filters: FindInvoicesParams): Promise<IInvoice[]> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.invoiceList.find(searchCriteria).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
public async findOne(filters: FindInvoicesParams): Promise<IInvoiceDocument | null> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.invoiceList.findOne(searchCriteria).exec();
|
||||
}
|
||||
|
||||
public async update(data: UpdateInvoiceParams): Promise<IInvoiceDocument | null> {
|
||||
const { sessionUser, id, cashMovementId, cashMovementIds, companyId, ...updateData } = data;
|
||||
const searchCriteria = this.buildSearchCriteria({ id, cashMovementId, companyId });
|
||||
return this.invoiceList.findOneAndUpdate(searchCriteria, updateData, { new: true }).exec();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { IInvoiceDocument } from "./Invoices.Adapter.Mongoose";
|
||||
|
||||
export enum INVOICE_TYPE {
|
||||
FACTURA_C = "FACTURA_C",
|
||||
}
|
||||
|
||||
export enum INVOICE_STATUS {
|
||||
PENDING_ARCA = "PENDING_ARCA",
|
||||
APPROVED = "APPROVED",
|
||||
PENDING_VERIFICATION = "PENDING_VERIFICATION",
|
||||
REJECTED = "REJECTED",
|
||||
FAILED = "FAILED",
|
||||
}
|
||||
|
||||
export enum INVOICE_SALE_CONDITION {
|
||||
CASH = "cash",
|
||||
CONTADO = "contado",
|
||||
BANK_TRANSFER = "bank_transfer",
|
||||
CREDIT_CARD = "credit_card",
|
||||
DEBIT_CARD = "debit_card",
|
||||
CURRENT_ACCOUNT = "current_account",
|
||||
CHECK = "check",
|
||||
OTHER = "other",
|
||||
ELECTRONIC_PAYMENT = "electronic_payment",
|
||||
}
|
||||
|
||||
export const FINAL_CONSUMER_IVA_CONDITION_ID = 5;
|
||||
|
||||
export type CreateInvoiceFromCashMovementParams = {
|
||||
cashMovementId: string;
|
||||
billingDate: Date | string;
|
||||
servicePeriodFrom: Date | string;
|
||||
servicePeriodTo: Date | string;
|
||||
paymentDueDate: Date | string;
|
||||
activityCode: string;
|
||||
activityDescription: string;
|
||||
receiverIvaCondition?: 5;
|
||||
receiverDocumentType?: number | string;
|
||||
receiverDocumentNumber?: number | string;
|
||||
receiverName?: string;
|
||||
receiverAddress?: string;
|
||||
receiverEmail?: string;
|
||||
saleCondition: INVOICE_SALE_CONDITION | string;
|
||||
itemDescription: string;
|
||||
itemQuantity?: number;
|
||||
itemUnit?: string;
|
||||
itemUnitPrice: number;
|
||||
itemDiscountPercent?: number;
|
||||
itemDiscountAmount?: number;
|
||||
itemSubtotal: number;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type FindInvoicesParams = {
|
||||
id?: string;
|
||||
cashMovementId?: string;
|
||||
cashMovementIds?: string[];
|
||||
companyId?: string;
|
||||
status?: INVOICE_STATUS;
|
||||
sessionUser?: string;
|
||||
};
|
||||
|
||||
export type CreateInvoiceParams = {
|
||||
cashMovementId: string;
|
||||
companyId: string;
|
||||
clientId?: string;
|
||||
paymentId?: string;
|
||||
clientAccountMovementId?: string;
|
||||
appointmentId?: string;
|
||||
amount: number;
|
||||
type: INVOICE_TYPE;
|
||||
status: INVOICE_STATUS;
|
||||
billingDate: Date;
|
||||
servicePeriodFrom: Date;
|
||||
servicePeriodTo: Date;
|
||||
paymentDueDate: Date;
|
||||
activityCode: string;
|
||||
activityDescription: string;
|
||||
receiverIvaCondition: 5;
|
||||
receiverDocumentType?: number | string;
|
||||
receiverDocumentNumber?: number | string;
|
||||
receiverName?: string;
|
||||
receiverAddress?: string;
|
||||
receiverEmail?: string;
|
||||
saleCondition: INVOICE_SALE_CONDITION | string;
|
||||
itemDescription: string;
|
||||
itemQuantity: number;
|
||||
itemUnit?: string;
|
||||
itemUnitPrice: number;
|
||||
itemDiscountPercent: number;
|
||||
itemDiscountAmount: number;
|
||||
itemSubtotal: number;
|
||||
cae?: string;
|
||||
caeExpiresAt?: Date;
|
||||
pointOfSale?: number;
|
||||
voucherNumber?: number;
|
||||
voucherType?: string;
|
||||
arcaErrorCode?: string;
|
||||
arcaErrorMessage?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type UpdateInvoiceParams = FindInvoicesParams & Partial<CreateInvoiceParams>;
|
||||
|
||||
export interface IInvoice {
|
||||
id?: string;
|
||||
cashMovementId: string;
|
||||
companyId: string;
|
||||
clientId?: string;
|
||||
paymentId?: string;
|
||||
clientAccountMovementId?: string;
|
||||
appointmentId?: string;
|
||||
amount: number;
|
||||
type: INVOICE_TYPE;
|
||||
status: INVOICE_STATUS;
|
||||
billingDate: Date;
|
||||
servicePeriodFrom: Date;
|
||||
servicePeriodTo: Date;
|
||||
paymentDueDate: Date;
|
||||
activityCode: string;
|
||||
activityDescription: string;
|
||||
receiverIvaCondition: 5;
|
||||
receiverDocumentType?: number | string;
|
||||
receiverDocumentNumber?: number | string;
|
||||
receiverName?: string;
|
||||
receiverAddress?: string;
|
||||
receiverEmail?: string;
|
||||
saleCondition: INVOICE_SALE_CONDITION | string;
|
||||
itemDescription: string;
|
||||
itemQuantity: number;
|
||||
itemUnit?: string;
|
||||
itemUnitPrice: number;
|
||||
itemDiscountPercent: number;
|
||||
itemDiscountAmount: number;
|
||||
itemSubtotal: number;
|
||||
cae?: string;
|
||||
caeExpiresAt?: Date;
|
||||
pointOfSale?: number;
|
||||
voucherNumber?: number;
|
||||
voucherType?: string;
|
||||
arcaErrorCode?: string;
|
||||
arcaErrorMessage?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface IInvoicesAdapter {
|
||||
create(data: CreateInvoiceParams): Promise<IInvoice>;
|
||||
find(filters: FindInvoicesParams): Promise<IInvoice[]>;
|
||||
findOne(filters: FindInvoicesParams): Promise<IInvoiceDocument | null>;
|
||||
update(data: UpdateInvoiceParams): Promise<IInvoiceDocument | null>;
|
||||
}
|
||||
|
||||
export interface IInvoicesManager {
|
||||
invoices: IInvoicesAdapter;
|
||||
createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice>;
|
||||
find(data: FindInvoicesParams): Promise<IInvoice[]>;
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
import CashFlow from "../CashFlow/CashFlow";
|
||||
import { CLIENT_ACCOUNT_MOVEMENT_TYPES } from "../ClientAccountMovements/ClientAccountMovements.Interface";
|
||||
import CompaniesList from "../Companies/Companies";
|
||||
import OrganizationFiscalProfiles from "../OrganizationFiscalProfiles/OrganizationFiscalProfiles";
|
||||
import { ORGANIZATION_FISCAL_PROFILE_STATUS } from "../OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
|
||||
import ArcaCredentials, { ArcaWsfeIssueFacturaCError } from "../ArcaCredentials/ArcaCredentials";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import { PlanFeatures } from "../Plans/Plans.interface";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
import { InvoicesAdapterMongoose } from "./Invoices.Adapter.Mongoose";
|
||||
import {
|
||||
CreateInvoiceFromCashMovementParams,
|
||||
CreateInvoiceParams,
|
||||
FindInvoicesParams,
|
||||
FINAL_CONSUMER_IVA_CONDITION_ID,
|
||||
IInvoice,
|
||||
IInvoicesManager,
|
||||
INVOICE_SALE_CONDITION,
|
||||
INVOICE_STATUS,
|
||||
INVOICE_TYPE,
|
||||
} from "./Invoices.Interface";
|
||||
|
||||
const FACTURA_C_VOUCHER_TYPE = "11";
|
||||
const ARGENTINA_TIME_ZONE = "America/Argentina/Buenos_Aires";
|
||||
const TEXT_MAX_LENGTH = 500;
|
||||
const RECEIVER_TEXT_MAX_LENGTH = 200;
|
||||
const CENTS_TOLERANCE = 0.01;
|
||||
const YYYY_MM_DD_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const DNI_DOCUMENT_TYPE = 96;
|
||||
const FINAL_CONSUMER_DOCUMENT_TYPE = 99;
|
||||
const FINAL_CONSUMER_DOCUMENT_NUMBER = 0;
|
||||
const FINAL_CONSUMER_COMPATIBLE_DOCUMENT_TYPES = new Set([DNI_DOCUMENT_TYPE, FINAL_CONSUMER_DOCUMENT_TYPE]);
|
||||
|
||||
class InvoicesManager implements IInvoicesManager {
|
||||
invoices: InvoicesAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.invoices = new InvoicesAdapterMongoose();
|
||||
}
|
||||
|
||||
private isDuplicateKeyError(error: unknown): boolean {
|
||||
return typeof error === "object" && error !== null && "code" in error && error.code === 11000;
|
||||
}
|
||||
|
||||
private async validatePaymentsPlan(companyId: string): Promise<void> {
|
||||
const company = await CompaniesList.companies.findOne({ _id: companyId });
|
||||
|
||||
if (!company) {
|
||||
throw new Error("No se ha encontrado la organización");
|
||||
}
|
||||
|
||||
const canAccess = await PlanSubscriptionsList.checkFeature({
|
||||
userId: String(company.ownerId),
|
||||
feature: PlanFeatures.PAYMENTS,
|
||||
});
|
||||
|
||||
if (!canAccess) {
|
||||
throw new Error("La organizacion no tiene un plan que soporte el módulo de pagos");
|
||||
}
|
||||
}
|
||||
|
||||
private formatArgentinaCalendarDate(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: ARGENTINA_TIME_ZONE,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value || "";
|
||||
const month = parts.find((part) => part.type === "month")?.value || "";
|
||||
const day = parts.find((part) => part.type === "day")?.value || "";
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
private parseArgentinaCalendarDate(dateValue: Date | string, requiredMessage: string, invalidMessage: string): Date {
|
||||
if (!dateValue) {
|
||||
throw new Error(requiredMessage);
|
||||
}
|
||||
|
||||
let parsedDate: Date;
|
||||
|
||||
if (typeof dateValue === "string") {
|
||||
const localDateMatch = dateValue.match(YYYY_MM_DD_PATTERN);
|
||||
|
||||
if (!localDateMatch) {
|
||||
throw new Error(invalidMessage);
|
||||
}
|
||||
|
||||
const [, year, month, day] = localDateMatch;
|
||||
const yearNumber = Number(year);
|
||||
const monthNumber = Number(month);
|
||||
const dayNumber = Number(day);
|
||||
parsedDate = new Date(Date.UTC(yearNumber, monthNumber - 1, dayNumber, 12));
|
||||
|
||||
if (
|
||||
parsedDate.getUTCFullYear() !== yearNumber ||
|
||||
parsedDate.getUTCMonth() !== monthNumber - 1 ||
|
||||
parsedDate.getUTCDate() !== dayNumber
|
||||
) {
|
||||
throw new Error(invalidMessage);
|
||||
}
|
||||
} else {
|
||||
parsedDate = dateValue;
|
||||
}
|
||||
|
||||
if (Number.isNaN(parsedDate.getTime())) {
|
||||
throw new Error(invalidMessage);
|
||||
}
|
||||
|
||||
return parsedDate;
|
||||
}
|
||||
|
||||
private parseBillingDate(billingDate: Date | string): Date {
|
||||
const parsedDate = this.parseArgentinaCalendarDate(
|
||||
billingDate,
|
||||
"Se requiere la fecha del comprobante",
|
||||
"La fecha del comprobante no es válida"
|
||||
);
|
||||
|
||||
const selectedDate = this.formatArgentinaCalendarDate(parsedDate);
|
||||
const todayDate = this.formatArgentinaCalendarDate(new Date());
|
||||
|
||||
if (selectedDate > todayDate) {
|
||||
throw new Error("La fecha del comprobante no puede ser futura");
|
||||
}
|
||||
|
||||
return parsedDate;
|
||||
}
|
||||
|
||||
private validateSaleCondition(saleCondition: string): INVOICE_SALE_CONDITION {
|
||||
if (!Object.values(INVOICE_SALE_CONDITION).includes(saleCondition as INVOICE_SALE_CONDITION)) {
|
||||
throw new Error("La condición de venta de la factura no es válida");
|
||||
}
|
||||
|
||||
return saleCondition as INVOICE_SALE_CONDITION;
|
||||
}
|
||||
|
||||
private trimOptional(value?: string): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
private parseReceiverDocumentCode(value: number | string, fieldName: string): number {
|
||||
if (typeof value === "string" && value.trim() === "") {
|
||||
throw new Error(`${fieldName} del receptor no es válido`);
|
||||
}
|
||||
|
||||
const parsedValue = typeof value === "string" ? Number(value.trim()) : value;
|
||||
|
||||
if (!Number.isInteger(parsedValue) || !Number.isFinite(parsedValue) || parsedValue < 0) {
|
||||
throw new Error(`${fieldName} del receptor no es válido`);
|
||||
}
|
||||
|
||||
return parsedValue;
|
||||
}
|
||||
|
||||
private validateReceiverDocumentPair(data: CreateInvoiceFromCashMovementParams): {
|
||||
receiverDocumentType: number;
|
||||
receiverDocumentNumber: number;
|
||||
} {
|
||||
const hasDocumentType = data.receiverDocumentType !== undefined && data.receiverDocumentType !== null && data.receiverDocumentType !== "";
|
||||
const hasDocumentNumber = data.receiverDocumentNumber !== undefined && data.receiverDocumentNumber !== null && data.receiverDocumentNumber !== "";
|
||||
|
||||
if (hasDocumentType !== hasDocumentNumber) {
|
||||
throw new Error("Tipo y número de documento del receptor deben informarse juntos");
|
||||
}
|
||||
|
||||
if (!hasDocumentType && !hasDocumentNumber) {
|
||||
return {
|
||||
receiverDocumentType: FINAL_CONSUMER_DOCUMENT_TYPE,
|
||||
receiverDocumentNumber: FINAL_CONSUMER_DOCUMENT_NUMBER,
|
||||
};
|
||||
}
|
||||
|
||||
const receiverDocumentType = this.parseReceiverDocumentCode(data.receiverDocumentType as number | string, "El tipo de documento");
|
||||
const receiverDocumentNumber = this.parseReceiverDocumentCode(data.receiverDocumentNumber as number | string, "El número de documento");
|
||||
|
||||
if (!FINAL_CONSUMER_COMPATIBLE_DOCUMENT_TYPES.has(receiverDocumentType)) {
|
||||
throw new Error("El tipo de documento del receptor no es compatible con Consumidor Final");
|
||||
}
|
||||
|
||||
if (receiverDocumentType === FINAL_CONSUMER_DOCUMENT_TYPE && receiverDocumentNumber !== FINAL_CONSUMER_DOCUMENT_NUMBER) {
|
||||
throw new Error("El número de documento debe ser 0 cuando el tipo es Consumidor Final");
|
||||
}
|
||||
|
||||
return {
|
||||
receiverDocumentType,
|
||||
receiverDocumentNumber,
|
||||
};
|
||||
}
|
||||
|
||||
public async createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
|
||||
if (!data.cashMovementId || !data.cashMovementId.trim()) {
|
||||
throw new Error("Se requiere un movimiento de caja para emitir la factura");
|
||||
}
|
||||
|
||||
const billingDate = this.parseBillingDate(data.billingDate);
|
||||
const servicePeriodFrom = this.parseArgentinaCalendarDate(
|
||||
data.servicePeriodFrom,
|
||||
"Se requiere la fecha de inicio del período facturado",
|
||||
"La fecha de inicio del período facturado no es válida"
|
||||
);
|
||||
const servicePeriodTo = this.parseArgentinaCalendarDate(
|
||||
data.servicePeriodTo,
|
||||
"Se requiere la fecha de fin del período facturado",
|
||||
"La fecha de fin del período facturado no es válida"
|
||||
);
|
||||
const paymentDueDate = this.parseArgentinaCalendarDate(
|
||||
data.paymentDueDate,
|
||||
"Se requiere el vencimiento de pago",
|
||||
"El vencimiento de pago no es válido"
|
||||
);
|
||||
const servicePeriodFromValue = this.formatArgentinaCalendarDate(servicePeriodFrom);
|
||||
const servicePeriodToValue = this.formatArgentinaCalendarDate(servicePeriodTo);
|
||||
const billingDateValue = this.formatArgentinaCalendarDate(billingDate);
|
||||
const paymentDueDateValue = this.formatArgentinaCalendarDate(paymentDueDate);
|
||||
|
||||
if (servicePeriodFromValue > servicePeriodToValue) {
|
||||
throw new Error("El inicio del período facturado no puede ser posterior al fin");
|
||||
}
|
||||
|
||||
if (paymentDueDateValue < billingDateValue) {
|
||||
throw new Error("El vencimiento de pago no puede ser anterior a la fecha del comprobante");
|
||||
}
|
||||
|
||||
const activityCode = data.activityCode?.trim();
|
||||
const activityDescription = data.activityDescription?.trim();
|
||||
const itemDescription = data.itemDescription?.trim();
|
||||
|
||||
if (!activityCode) {
|
||||
throw new Error("Se requiere el código de actividad");
|
||||
}
|
||||
|
||||
if (!activityDescription) {
|
||||
throw new Error("Se requiere la descripción de la actividad");
|
||||
}
|
||||
|
||||
if (!itemDescription) {
|
||||
throw new Error("Se requiere la descripción del ítem facturado");
|
||||
}
|
||||
|
||||
if ([activityCode, activityDescription, itemDescription].some((value) => value.length > TEXT_MAX_LENGTH)) {
|
||||
throw new Error(`Los datos de actividad e ítem no pueden superar los ${TEXT_MAX_LENGTH} caracteres`);
|
||||
}
|
||||
|
||||
if (!data.saleCondition || !data.saleCondition.trim()) {
|
||||
throw new Error("Se requiere la condición de venta");
|
||||
}
|
||||
|
||||
const saleCondition = this.validateSaleCondition(data.saleCondition.trim());
|
||||
const receiverDocument = this.validateReceiverDocumentPair(data);
|
||||
const itemQuantity = data.itemQuantity ?? 1;
|
||||
const itemDiscountPercent = data.itemDiscountPercent ?? 0;
|
||||
const itemDiscountAmount = data.itemDiscountAmount ?? 0;
|
||||
|
||||
if (!Number.isFinite(data.itemUnitPrice) || !Number.isFinite(data.itemSubtotal)) {
|
||||
throw new Error("El importe del ítem no es válido");
|
||||
}
|
||||
|
||||
if (itemQuantity !== 1 || data.itemUnitPrice <= 0 || itemDiscountPercent !== 0 || itemDiscountAmount !== 0) {
|
||||
throw new Error("El MVP permite un único ítem de servicio sin descuentos por el total del movimiento");
|
||||
}
|
||||
|
||||
const movement = await CashFlow.movements.movementList.findOne({
|
||||
_id: data.cashMovementId,
|
||||
});
|
||||
|
||||
if (!movement) {
|
||||
throw new Error("No se ha encontrado el movimiento de caja");
|
||||
}
|
||||
|
||||
const companyId = String(movement.companyId);
|
||||
await validatePermissionsByCompany({ companyId, sessionUser: data.sessionUser });
|
||||
await this.validatePaymentsPlan(companyId);
|
||||
|
||||
if (movement.type !== CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT || movement.amount <= 0) {
|
||||
throw new Error("El movimiento de caja no es facturable");
|
||||
}
|
||||
|
||||
const expectedSubtotal = Number((itemQuantity * data.itemUnitPrice - itemDiscountAmount).toFixed(2));
|
||||
const sentSubtotal = Number(data.itemSubtotal.toFixed(2));
|
||||
const movementAmount = Number(movement.amount.toFixed(2));
|
||||
|
||||
if (
|
||||
Math.abs(expectedSubtotal - sentSubtotal) > CENTS_TOLERANCE ||
|
||||
Math.abs(sentSubtotal - movementAmount) > CENTS_TOLERANCE
|
||||
) {
|
||||
throw new Error("El total del ítem debe coincidir con el importe del movimiento");
|
||||
}
|
||||
|
||||
const fiscalProfiles = await OrganizationFiscalProfiles.find({
|
||||
companyId,
|
||||
status: ORGANIZATION_FISCAL_PROFILE_STATUS.ACTIVE,
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
if (fiscalProfiles.length === 0) {
|
||||
throw new Error("La organización debe tener un perfil fiscal activo para emitir facturas");
|
||||
}
|
||||
|
||||
const existingInvoice = await this.invoices.findOne({
|
||||
cashMovementId: data.cashMovementId,
|
||||
});
|
||||
|
||||
if (existingInvoice?.status === INVOICE_STATUS.APPROVED) {
|
||||
return existingInvoice;
|
||||
}
|
||||
|
||||
if (existingInvoice?.status === INVOICE_STATUS.PENDING_VERIFICATION) {
|
||||
return existingInvoice;
|
||||
}
|
||||
|
||||
if (existingInvoice?.status === INVOICE_STATUS.PENDING_ARCA && existingInvoice.voucherNumber) {
|
||||
const updatedPendingInvoice = await this.invoices.update({
|
||||
cashMovementId: data.cashMovementId,
|
||||
status: INVOICE_STATUS.PENDING_VERIFICATION,
|
||||
arcaErrorMessage:
|
||||
existingInvoice.arcaErrorMessage ||
|
||||
"La emisión quedó pendiente de verificación en ARCA. Revisá el comprobante antes de reintentar.",
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
return updatedPendingInvoice || existingInvoice;
|
||||
}
|
||||
|
||||
const baseInvoiceData: CreateInvoiceParams = {
|
||||
cashMovementId: data.cashMovementId,
|
||||
companyId,
|
||||
clientId: movement.clientId ? String(movement.clientId) : undefined,
|
||||
paymentId: movement.paymentId ? String(movement.paymentId) : undefined,
|
||||
clientAccountMovementId: movement.clientAccountMovementId
|
||||
? String(movement.clientAccountMovementId)
|
||||
: undefined,
|
||||
appointmentId: movement.appointmentId ? String(movement.appointmentId) : undefined,
|
||||
amount: movement.amount,
|
||||
type: INVOICE_TYPE.FACTURA_C,
|
||||
status: INVOICE_STATUS.PENDING_ARCA,
|
||||
billingDate,
|
||||
servicePeriodFrom,
|
||||
servicePeriodTo,
|
||||
paymentDueDate,
|
||||
activityCode,
|
||||
activityDescription,
|
||||
receiverIvaCondition: FINAL_CONSUMER_IVA_CONDITION_ID,
|
||||
receiverDocumentType: receiverDocument.receiverDocumentType,
|
||||
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
|
||||
receiverName: this.trimOptional(data.receiverName)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
receiverAddress: this.trimOptional(data.receiverAddress)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
receiverEmail: this.trimOptional(data.receiverEmail)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
saleCondition,
|
||||
itemDescription,
|
||||
itemQuantity,
|
||||
itemUnit: this.trimOptional(data.itemUnit),
|
||||
itemUnitPrice: data.itemUnitPrice,
|
||||
itemDiscountPercent,
|
||||
itemDiscountAmount,
|
||||
itemSubtotal: sentSubtotal,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
let invoice: IInvoice | null = existingInvoice;
|
||||
|
||||
if (!invoice) {
|
||||
try {
|
||||
invoice = await this.invoices.create(baseInvoiceData);
|
||||
} catch (error) {
|
||||
if (this.isDuplicateKeyError(error)) {
|
||||
const duplicateInvoice = await this.invoices.findOne({
|
||||
cashMovementId: data.cashMovementId,
|
||||
});
|
||||
|
||||
if (duplicateInvoice) {
|
||||
return duplicateInvoice;
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!invoice) {
|
||||
throw new Error("No se pudo crear el registro local de factura");
|
||||
}
|
||||
|
||||
if (
|
||||
existingInvoice?.status === INVOICE_STATUS.PENDING_ARCA ||
|
||||
existingInvoice?.status === INVOICE_STATUS.REJECTED ||
|
||||
existingInvoice?.status === INVOICE_STATUS.FAILED
|
||||
) {
|
||||
invoice = await this.invoices.update({
|
||||
cashMovementId: data.cashMovementId,
|
||||
billingDate,
|
||||
servicePeriodFrom,
|
||||
servicePeriodTo,
|
||||
paymentDueDate,
|
||||
activityCode,
|
||||
activityDescription,
|
||||
receiverIvaCondition: FINAL_CONSUMER_IVA_CONDITION_ID,
|
||||
receiverDocumentType: receiverDocument.receiverDocumentType,
|
||||
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
|
||||
receiverName: this.trimOptional(data.receiverName)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
receiverAddress: this.trimOptional(data.receiverAddress)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
receiverEmail: this.trimOptional(data.receiverEmail)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
|
||||
saleCondition,
|
||||
itemDescription,
|
||||
itemQuantity,
|
||||
itemUnit: this.trimOptional(data.itemUnit),
|
||||
itemUnitPrice: data.itemUnitPrice,
|
||||
itemDiscountPercent,
|
||||
itemDiscountAmount,
|
||||
itemSubtotal: sentSubtotal,
|
||||
updatedAt: new Date(),
|
||||
}) || invoice;
|
||||
}
|
||||
|
||||
let invoiceData: Pick<
|
||||
CreateInvoiceParams,
|
||||
| "status"
|
||||
| "cae"
|
||||
| "caeExpiresAt"
|
||||
| "pointOfSale"
|
||||
| "voucherNumber"
|
||||
| "voucherType"
|
||||
| "arcaErrorMessage"
|
||||
>;
|
||||
|
||||
try {
|
||||
const arcaInvoice = await ArcaCredentials.issueFacturaC({
|
||||
companyId,
|
||||
amount: movement.amount,
|
||||
billingDate,
|
||||
servicePeriodFrom,
|
||||
servicePeriodTo,
|
||||
paymentDueDate,
|
||||
receiverDocumentType: receiverDocument.receiverDocumentType,
|
||||
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
invoiceData = {
|
||||
status: INVOICE_STATUS.APPROVED,
|
||||
cae: arcaInvoice.cae,
|
||||
caeExpiresAt: arcaInvoice.caeExpiresAt,
|
||||
pointOfSale: arcaInvoice.pointOfSale,
|
||||
voucherNumber: arcaInvoice.voucherNumber,
|
||||
voucherType: String(arcaInvoice.voucherType),
|
||||
arcaErrorMessage: "",
|
||||
};
|
||||
} catch (error) {
|
||||
const errorOccurred = error as Error;
|
||||
const arcaError = error as ArcaWsfeIssueFacturaCError;
|
||||
const hasArcaAttempt = error instanceof ArcaWsfeIssueFacturaCError;
|
||||
invoiceData = {
|
||||
status: hasArcaAttempt
|
||||
? arcaError.isAmbiguous
|
||||
? INVOICE_STATUS.PENDING_VERIFICATION
|
||||
: INVOICE_STATUS.REJECTED
|
||||
: INVOICE_STATUS.FAILED,
|
||||
pointOfSale: hasArcaAttempt ? arcaError.attempt.pointOfSale : undefined,
|
||||
voucherNumber: hasArcaAttempt ? arcaError.attempt.voucherNumber : undefined,
|
||||
voucherType: hasArcaAttempt ? String(arcaError.attempt.voucherType) : FACTURA_C_VOUCHER_TYPE,
|
||||
arcaErrorMessage: errorOccurred.message,
|
||||
};
|
||||
}
|
||||
|
||||
const updatedInvoice = await this.invoices.update({
|
||||
cashMovementId: data.cashMovementId,
|
||||
...invoiceData,
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
if (!updatedInvoice) {
|
||||
return invoice;
|
||||
}
|
||||
|
||||
return updatedInvoice;
|
||||
}
|
||||
|
||||
public async find(data: FindInvoicesParams): Promise<IInvoice[]> {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("Se requiere un usuario autenticado");
|
||||
}
|
||||
|
||||
const sessionUser = data.sessionUser;
|
||||
await validateSessionUser({ sessionUser });
|
||||
|
||||
if (data.companyId) {
|
||||
await validatePermissionsByCompany({
|
||||
companyId: data.companyId,
|
||||
sessionUser,
|
||||
});
|
||||
await this.validatePaymentsPlan(data.companyId);
|
||||
} else if (data.id || data.cashMovementId) {
|
||||
const invoice = await this.invoices.findOne(data);
|
||||
|
||||
if (!invoice) {
|
||||
return [];
|
||||
}
|
||||
|
||||
await validatePermissionsByCompany({
|
||||
companyId: String(invoice.companyId),
|
||||
sessionUser,
|
||||
});
|
||||
await this.validatePaymentsPlan(String(invoice.companyId));
|
||||
|
||||
return [invoice];
|
||||
} else {
|
||||
throw new Error("Se requiere una organización para buscar facturas");
|
||||
}
|
||||
|
||||
return await this.invoices.find(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new InvoicesManager();
|
||||
@@ -157,7 +157,10 @@ export class MetricsAdapterMongoose implements IMetricsAdapter {
|
||||
if (!metrics.repeatsCount) {
|
||||
metrics.repeatsCount = 0;
|
||||
}
|
||||
metrics.repeatsCount += isNull<number>(data.quantity, 1);
|
||||
metrics.repeatsCount = Math.max(
|
||||
0,
|
||||
isNull<number>(metrics.repeatsCount, 0) + isNull<number>(data.quantity, 1)
|
||||
);
|
||||
await metrics.save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ export interface IMetricsAdapter {
|
||||
addService(data: MetricsParams): Promise<void>;
|
||||
addAppointment(data: MetricsParams): Promise<void>;
|
||||
addClient(data: MetricsParams): Promise<void>;
|
||||
addRepeat(data: MetricsParams): Promise<void>;
|
||||
}
|
||||
|
||||
export interface IMetricsManager {
|
||||
@@ -50,6 +51,7 @@ export interface IMetricsManager {
|
||||
reserveAppointment(data: MetricsParams): Promise<boolean>;
|
||||
releaseAppointment(data: MetricsParams): Promise<void>;
|
||||
addClient(data: MetricsParams): Promise<void>;
|
||||
addRepeat(data: MetricsParams): Promise<void>;
|
||||
canAddOrganization(userId: string): Promise<boolean>;
|
||||
canAddEmployee(userId: string): Promise<boolean>;
|
||||
canAddService(userId: string): Promise<boolean>;
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { Document, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
CreateJobParams,
|
||||
DeleteOldJobsParams,
|
||||
DeleteOldJobsResult,
|
||||
INotificationJob,
|
||||
INotificationJobAdapter,
|
||||
NotificationJobStatus,
|
||||
} from "./NotificationJobs.Interface";
|
||||
|
||||
export const NOTIFICATION_JOB_CLEANUP_RETENTION_DAYS = 7;
|
||||
export const NOTIFICATION_JOB_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
|
||||
export const NOTIFICATION_JOB_CLEANUP_STATUSES = [
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
];
|
||||
|
||||
export interface INotificationJobDocument
|
||||
extends Omit<INotificationJob, "id">,
|
||||
Document {}
|
||||
@@ -13,6 +23,7 @@ export interface INotificationJobDocument
|
||||
export class NotificationJobsAdapterMongoose implements INotificationJobAdapter {
|
||||
schema: Schema;
|
||||
notificationJobList: Model<INotificationJobDocument>;
|
||||
private lastCleanupAt?: number;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
@@ -73,6 +84,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async create(data: CreateJobParams): Promise<INotificationJob> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
const doc = await this.notificationJobList.create({
|
||||
...data,
|
||||
status: NotificationJobStatus.PENDING,
|
||||
@@ -111,6 +123,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async cancelByAppointment(appointmentId: string): Promise<void> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
await this.notificationJobList
|
||||
.updateMany(
|
||||
{
|
||||
@@ -123,9 +136,52 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
const docs = await this.notificationJobList
|
||||
.find({ appointmentId })
|
||||
.exec();
|
||||
return docs.map((d) => d.toObject() as INotificationJob);
|
||||
}
|
||||
|
||||
public async deleteOldJobs(
|
||||
data: DeleteOldJobsParams
|
||||
): Promise<DeleteOldJobsResult> {
|
||||
const result = await this.notificationJobList
|
||||
.deleteMany({
|
||||
scheduledAt: { $lt: data.scheduledBefore },
|
||||
status: { $in: data.statuses },
|
||||
})
|
||||
.exec();
|
||||
|
||||
return { deletedCount: result.deletedCount || 0 };
|
||||
}
|
||||
|
||||
public async cleanupOldJobsIfDue(now = new Date()): Promise<void> {
|
||||
if (
|
||||
this.lastCleanupAt !== undefined &&
|
||||
now.getTime() - this.lastCleanupAt < NOTIFICATION_JOB_CLEANUP_INTERVAL_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scheduledBefore = new Date(now.getTime());
|
||||
scheduledBefore.setDate(
|
||||
scheduledBefore.getDate() - NOTIFICATION_JOB_CLEANUP_RETENTION_DAYS
|
||||
);
|
||||
|
||||
await this.deleteOldJobs({
|
||||
scheduledBefore,
|
||||
statuses: NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
});
|
||||
this.lastCleanupAt = now.getTime();
|
||||
}
|
||||
|
||||
private async cleanupOldJobsIfDueSafely(): Promise<void> {
|
||||
try {
|
||||
await this.cleanupOldJobsIfDue();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`Notification jobs cleanup failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface NotificationJobPayload {
|
||||
message?: string;
|
||||
emailSubject?: string;
|
||||
emailMessage?: string;
|
||||
emailTemplateId?: string;
|
||||
emailContext?: Record<string, unknown>;
|
||||
wapMessage?: string;
|
||||
systemSubject?: string;
|
||||
systemMessage?: string;
|
||||
@@ -58,6 +60,15 @@ export interface CreateJobParams {
|
||||
payload?: NotificationJobPayload;
|
||||
}
|
||||
|
||||
export interface DeleteOldJobsParams {
|
||||
scheduledBefore: Date;
|
||||
statuses: NotificationJobStatus[];
|
||||
}
|
||||
|
||||
export interface DeleteOldJobsResult {
|
||||
deletedCount: number;
|
||||
}
|
||||
|
||||
export interface INotificationJobAdapter {
|
||||
create(data: CreateJobParams): Promise<INotificationJob>;
|
||||
findPendingDue(now: Date): Promise<INotificationJob[]>;
|
||||
@@ -68,4 +79,5 @@ export interface INotificationJobAdapter {
|
||||
): Promise<void>;
|
||||
cancelByAppointment(appointmentId: string): Promise<void>;
|
||||
findByAppointment(appointmentId: string): Promise<INotificationJob[]>;
|
||||
deleteOldJobs(data: DeleteOldJobsParams): Promise<DeleteOldJobsResult>;
|
||||
}
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
NotificationJobsAdapterMongoose,
|
||||
} from "../NotificationJobs.Adapter.Mongoose";
|
||||
import { NotificationJobStatus } from "../NotificationJobs.Interface";
|
||||
|
||||
describe("NotificationJobsAdapterMongoose cleanup", () => {
|
||||
const now = new Date("2026-07-21T15:30:00.000Z");
|
||||
|
||||
function buildAdapter() {
|
||||
return Object.create(NotificationJobsAdapterMongoose.prototype) as NotificationJobsAdapterMongoose;
|
||||
}
|
||||
|
||||
it("runs throttled retention cleanup before create on the production adapter path", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
||||
const create = jest.fn().mockResolvedValue({ toObject: () => ({ id: "job-1" }) });
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
(adapter as any).notificationJobList = { create };
|
||||
|
||||
jest.useFakeTimers().setSystemTime(now);
|
||||
|
||||
await adapter.create({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: now,
|
||||
});
|
||||
|
||||
expect(deleteOldJobs).toHaveBeenCalledWith({
|
||||
scheduledBefore: new Date("2026-07-14T15:30:00.000Z"),
|
||||
statuses: NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
});
|
||||
expect(NOTIFICATION_JOB_CLEANUP_STATUSES).toEqual([
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
]);
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: NotificationJobStatus.PENDING,
|
||||
attempts: 0,
|
||||
maxAttempts: 3,
|
||||
}));
|
||||
});
|
||||
|
||||
it("continues creating jobs when production cleanup fails", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest.fn().mockRejectedValue(new Error("database down"));
|
||||
const create = jest.fn().mockResolvedValue({ toObject: () => ({ id: "job-1" }) });
|
||||
const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
(adapter as any).notificationJobList = { create };
|
||||
|
||||
await expect(adapter.create({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: now,
|
||||
})).resolves.toEqual({ id: "job-1" });
|
||||
|
||||
expect(warn).toHaveBeenCalledWith("Notification jobs cleanup failed: database down");
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: NotificationJobStatus.PENDING,
|
||||
}));
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("throttles only after cleanup succeeds", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("database down"))
|
||||
.mockResolvedValueOnce({ deletedCount: 0 })
|
||||
.mockResolvedValueOnce({ deletedCount: 0 });
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
|
||||
await expect(adapter.cleanupOldJobsIfDue(now)).rejects.toThrow("database down");
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 1000));
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 2000));
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 60 * 60 * 1000 + 1000));
|
||||
|
||||
expect(deleteOldJobs).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NotificationJobStatus } from "../NotificationJobs.Interface";
|
||||
|
||||
const mockCreate = jest.fn();
|
||||
const mockCancelByAppointment = jest.fn();
|
||||
const mockFindByAppointment = jest.fn();
|
||||
const mockDeleteOldJobs = jest.fn();
|
||||
|
||||
jest.mock("../NotificationJobs.Adapter.Mongoose", () => ({
|
||||
NotificationJobsAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
create: mockCreate,
|
||||
cancelByAppointment: mockCancelByAppointment,
|
||||
findByAppointment: mockFindByAppointment,
|
||||
deleteOldJobs: mockDeleteOldJobs,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe("NotificationJobManager cleanup", () => {
|
||||
const loadNotificationJobsList = () => {
|
||||
jest.isolateModules(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
require("../NotificationJobs");
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require("../NotificationJobs").default;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-29T12:00:00.000Z"));
|
||||
mockCreate.mockResolvedValue({ id: "job-1" });
|
||||
mockCancelByAppointment.mockResolvedValue(undefined);
|
||||
mockFindByAppointment.mockResolvedValue([]);
|
||||
mockDeleteOldJobs.mockResolvedValue({ deletedCount: 0 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it("deletes only completed old jobs before creating a job", async () => {
|
||||
const NotificationJobsList = loadNotificationJobsList();
|
||||
|
||||
await NotificationJobsList.createJob({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-29T12:30:00.000Z"),
|
||||
});
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledWith({
|
||||
scheduledBefore: new Date("2026-07-22T12:00:00.000Z"),
|
||||
statuses: [
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
],
|
||||
});
|
||||
expect(mockCreate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("throttles cleanup across manager operations", async () => {
|
||||
const NotificationJobsList = loadNotificationJobsList();
|
||||
|
||||
await NotificationJobsList.createJob({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-29T12:30:00.000Z"),
|
||||
});
|
||||
await NotificationJobsList.cancelByAppointment("appointment-1");
|
||||
await NotificationJobsList.findByAppointment("appointment-1");
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledTimes(1);
|
||||
|
||||
jest.setSystemTime(new Date("2026-07-29T13:00:00.000Z"));
|
||||
|
||||
await NotificationJobsList.findByAppointment("appointment-1");
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CreateJobParams,
|
||||
NotificationChannel,
|
||||
} from "../NotificationJobs/NotificationJobs.Interface";
|
||||
import { NotificationJobsAdapterMongoose } from "../NotificationJobs/NotificationJobs.Adapter.Mongoose";
|
||||
import { PolicyResolver, ResolvedPolicy } from "./PolicyResolver";
|
||||
@@ -121,6 +122,79 @@ export class NotificationJobService {
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async createMandatoryCreationJob(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const payloadChannels = this.getPayloadChannels(params.payload);
|
||||
const channels = await this.policyResolver.resolveAvailableChannels(
|
||||
params.companyId,
|
||||
payloadChannels
|
||||
);
|
||||
|
||||
if (channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const scheduledAt = params.scheduledAt || new Date();
|
||||
const jobs: any[] = [];
|
||||
|
||||
for (const channel of channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: "creation",
|
||||
scheduledAt,
|
||||
payload: params.payload,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async createReminderJobs(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const resolvedPolicy = await this.policyResolver.resolve(
|
||||
params.companyId,
|
||||
params.clientId
|
||||
);
|
||||
|
||||
if (!params.appointmentStart || resolvedPolicy.channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const jobs: any[] = [];
|
||||
const enabledReminderRules = (resolvedPolicy.reminderRules || []).filter(
|
||||
(rule) => rule.enabled
|
||||
);
|
||||
|
||||
for (const rule of enabledReminderRules) {
|
||||
const reminderScheduledAt = this.adjustForQuietHours(
|
||||
dayjs(params.appointmentStart).subtract(rule.offset, "minute").toDate(),
|
||||
resolvedPolicy
|
||||
);
|
||||
|
||||
if (reminderScheduledAt < now || reminderScheduledAt >= params.appointmentStart) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const channel of resolvedPolicy.channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: "reminder",
|
||||
scheduledAt: reminderScheduledAt,
|
||||
payload: params.reminderPayload,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all pending jobs for an appointment.
|
||||
* Called when an appointment is deleted or rescheduled.
|
||||
@@ -165,6 +239,24 @@ export class NotificationJobService {
|
||||
return scheduledAt;
|
||||
}
|
||||
|
||||
private getPayloadChannels(payload?: CreateJobParams["payload"]): NotificationChannel[] {
|
||||
const channels: NotificationChannel[] = [];
|
||||
|
||||
if (payload?.email) {
|
||||
channels.push("email");
|
||||
}
|
||||
|
||||
if (payload?.phoneNumber) {
|
||||
channels.push("whatsapp");
|
||||
}
|
||||
|
||||
if (payload?.userId) {
|
||||
channels.push("system");
|
||||
}
|
||||
|
||||
return channels;
|
||||
}
|
||||
|
||||
private isTimeInQuietHours(
|
||||
hour: number,
|
||||
minute: number,
|
||||
|
||||
@@ -93,6 +93,21 @@ export class PolicyResolver {
|
||||
};
|
||||
}
|
||||
|
||||
async resolveAvailableChannels(
|
||||
companyId: string,
|
||||
channels: NotificationChannel[]
|
||||
): Promise<NotificationChannel[]> {
|
||||
const companyPolicy = await this.companyPolicyAdapter.findOne({ companyId });
|
||||
const enabledChannels = companyPolicy
|
||||
? companyPolicy.defaultChannels
|
||||
: SYSTEM_DEFAULT_CHANNELS;
|
||||
const companyEnabledChannels = channels.filter((channel) =>
|
||||
enabledChannels.includes(channel)
|
||||
);
|
||||
|
||||
return this.applyPlanLimits(companyId, companyEnabledChannels);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns muted channels from the winning cascade level only.
|
||||
* Per spec, muted channels are NOT merged across levels.
|
||||
|
||||
@@ -10,6 +10,7 @@ jest.mock("../../NotificationJobs/NotificationJobs.Adapter.Mongoose", () => ({
|
||||
jest.mock("../PolicyResolver", () => ({
|
||||
PolicyResolver: jest.fn().mockImplementation(() => ({
|
||||
resolve: jest.fn(),
|
||||
resolveAvailableChannels: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
@@ -27,6 +28,7 @@ describe("NotificationJobService.createJob", () => {
|
||||
let service: NotificationJobService;
|
||||
let mockJobCreate: jest.Mock;
|
||||
let mockResolverResolve: jest.Mock;
|
||||
let mockResolveAvailableChannels: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -36,6 +38,7 @@ describe("NotificationJobService.createJob", () => {
|
||||
|
||||
mockJobCreate = (service as any).jobAdapter.create as jest.Mock;
|
||||
mockResolverResolve = (service as any).policyResolver.resolve as jest.Mock;
|
||||
mockResolveAvailableChannels = (service as any).policyResolver.resolveAvailableChannels as jest.Mock;
|
||||
});
|
||||
|
||||
it("creates a job with resolved channels", async () => {
|
||||
@@ -219,6 +222,114 @@ describe("NotificationJobService.createJob", () => {
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("creates mandatory creation jobs from available payload destinations without resolving reminder policy", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
mockResolveAvailableChannels.mockResolvedValue(["email", "whatsapp"]);
|
||||
const payload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-1",
|
||||
emailMessage: "Alta email",
|
||||
wapMessage: "Alta WAP",
|
||||
};
|
||||
|
||||
const result = await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(mockResolverResolve).not.toHaveBeenCalled();
|
||||
expect(mockResolveAvailableChannels).toHaveBeenCalledWith("company-1", [
|
||||
"email",
|
||||
"whatsapp",
|
||||
]);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
channel: "whatsapp",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create mandatory creation jobs for channels missing destination data", async () => {
|
||||
mockResolveAvailableChannels.mockResolvedValue([]);
|
||||
|
||||
await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload: {
|
||||
companyOwnerId: "owner-1",
|
||||
emailMessage: "Alta email",
|
||||
wapMessage: "Alta WAP",
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockResolverResolve).not.toHaveBeenCalled();
|
||||
expect(mockResolveAvailableChannels).toHaveBeenCalledWith("company-1", []);
|
||||
expect(mockJobCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not create mandatory creation jobs for unavailable channels", async () => {
|
||||
mockResolveAvailableChannels.mockResolvedValue(["email"]);
|
||||
const payload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-1",
|
||||
};
|
||||
|
||||
const result = await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({ channel: "email", type: "creation", payload }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps reminder jobs policy-aware when resolved channels are empty", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: [],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [{ offset: 30, enabled: true }],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
|
||||
const result = await service.createReminderJobs({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "reminder",
|
||||
appointmentStart: new Date("2026-07-21T15:00:00.000Z"),
|
||||
reminderPayload: { email: "client@example.com" },
|
||||
});
|
||||
|
||||
expect(mockResolverResolve).toHaveBeenCalledWith("company-1", "client-1");
|
||||
expect(mockJobCreate).not.toHaveBeenCalled();
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("adjusts scheduledAt for quiet hours crossing midnight", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system"],
|
||||
|
||||
@@ -309,4 +309,43 @@ describe("PolicyResolver", () => {
|
||||
|
||||
expect(result.channels).toEqual([]);
|
||||
});
|
||||
|
||||
it("resolves available channels from company defaults and plan limits without client preferences", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["whatsapp" as NotificationChannel, "email" as NotificationChannel],
|
||||
mutedChannels: ["email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolveAvailableChannels("company-1", [
|
||||
"whatsapp",
|
||||
"email",
|
||||
"system",
|
||||
]);
|
||||
|
||||
expect(result).toEqual(["whatsapp", "email"]);
|
||||
expect(mockClientPreferencesFindOne).not.toHaveBeenCalled();
|
||||
expect(mockOverrideFindOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes available channels disallowed by the owner plan", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["whatsapp" as NotificationChannel, "email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockImplementation(
|
||||
async (params: { feature: string }) =>
|
||||
params.feature !== PlanFeatures.WAP_NOTIFICATIONS
|
||||
);
|
||||
|
||||
const result = await resolver.resolveAvailableChannels("company-1", [
|
||||
"whatsapp",
|
||||
"email",
|
||||
]);
|
||||
|
||||
expect(result).toEqual(["email"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,13 +3,37 @@ import { INotificationsAdapter, NotificationDataEmail } from "./Notifications.In
|
||||
|
||||
export class NotificationsDonWebAdapter implements INotificationsAdapter<NotificationDataEmail> {
|
||||
async send(data: NotificationDataEmail): Promise<void> {
|
||||
const dataEmail = {
|
||||
if (data.context && data.substitutions) {
|
||||
throw new Error("No se puede enviar un email con context y substitutions al mismo tiempo.");
|
||||
}
|
||||
|
||||
if (!data.templateId && !data.message) {
|
||||
throw new Error("Debe indicarse el contenido del email mediante message o templateId.");
|
||||
}
|
||||
|
||||
const dataEmail: Record<string, unknown> = {
|
||||
from: "norepply@turnosxpress.com.ar",
|
||||
to: data.email,
|
||||
subject: data.subject,
|
||||
html: data.message,
|
||||
};
|
||||
|
||||
if (data.templateId) {
|
||||
dataEmail.templateID = data.templateId;
|
||||
} else {
|
||||
dataEmail.html = data.message;
|
||||
}
|
||||
|
||||
if (data.subject) {
|
||||
dataEmail.subject = data.subject;
|
||||
}
|
||||
|
||||
if (data.context) {
|
||||
dataEmail.context = data.context;
|
||||
}
|
||||
|
||||
if (data.substitutions) {
|
||||
dataEmail.substitutions = data.substitutions;
|
||||
}
|
||||
|
||||
const apiConfig = {
|
||||
method: "post",
|
||||
maxBodyLength: Infinity,
|
||||
|
||||
@@ -6,8 +6,11 @@ export enum NOTIFICATION_TYPES {
|
||||
|
||||
export type NotificationDataEmail = {
|
||||
email: string;
|
||||
subject: string;
|
||||
message: string;
|
||||
subject?: string;
|
||||
message?: string;
|
||||
templateId?: string;
|
||||
context?: Record<string, unknown>;
|
||||
substitutions?: Record<string, string | number | boolean>;
|
||||
};
|
||||
|
||||
export type NotificationDataWap = {
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
CreateOrganizationFiscalProfileParams,
|
||||
FindOrganizationFiscalProfilesParams,
|
||||
IOrganizationFiscalProfile,
|
||||
IOrganizationFiscalProfilesAdapter,
|
||||
ORGANIZATION_FISCAL_PROFILE_STATUS,
|
||||
ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION,
|
||||
UpdateOrganizationFiscalProfileParams,
|
||||
} from "./OrganizationFiscalProfiles.Interface";
|
||||
|
||||
export interface IOrganizationFiscalProfileDocument
|
||||
extends Omit<IOrganizationFiscalProfile, "id">,
|
||||
Document {}
|
||||
|
||||
export class OrganizationFiscalProfilesAdapterMongoose implements IOrganizationFiscalProfilesAdapter {
|
||||
schema: Schema;
|
||||
organizationFiscalProfileList: Model<IOrganizationFiscalProfileDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema({
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
unique: true,
|
||||
index: true,
|
||||
},
|
||||
cuit: { type: String, required: true },
|
||||
legalName: { type: String, required: true },
|
||||
taxCondition: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION),
|
||||
},
|
||||
pointOfSale: { type: Number, required: true },
|
||||
activityCode: { type: String, required: false },
|
||||
activityDescription: { type: String, required: false },
|
||||
status: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(ORGANIZATION_FISCAL_PROFILE_STATUS),
|
||||
index: true,
|
||||
},
|
||||
createdAt: { type: Date, required: true, default: Date.now },
|
||||
updatedAt: { type: Date, required: true, default: Date.now },
|
||||
});
|
||||
|
||||
this.organizationFiscalProfileList = model<IOrganizationFiscalProfileDocument>(
|
||||
"OrganizationFiscalProfile",
|
||||
this.schema
|
||||
);
|
||||
}
|
||||
|
||||
public async create(
|
||||
data: CreateOrganizationFiscalProfileParams
|
||||
): Promise<IOrganizationFiscalProfile> {
|
||||
return await this.organizationFiscalProfileList.create(data);
|
||||
}
|
||||
|
||||
private buildSearchCriteria(
|
||||
filters: FindOrganizationFiscalProfilesParams
|
||||
): FilterQuery<IOrganizationFiscalProfile> {
|
||||
const searchCriteria: FilterQuery<IOrganizationFiscalProfile> = {};
|
||||
|
||||
if (filters.id) searchCriteria._id = filters.id;
|
||||
if (filters.companyId) searchCriteria.companyId = filters.companyId;
|
||||
if (filters.status) searchCriteria.status = filters.status;
|
||||
|
||||
return searchCriteria;
|
||||
}
|
||||
|
||||
public async find(
|
||||
filters: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfile[]> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.organizationFiscalProfileList.find(searchCriteria).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfileDocument | null> {
|
||||
const searchCriteria = this.buildSearchCriteria(filters);
|
||||
return this.organizationFiscalProfileList.findOne(searchCriteria).exec();
|
||||
}
|
||||
|
||||
public async update(
|
||||
data: UpdateOrganizationFiscalProfileParams
|
||||
): Promise<IOrganizationFiscalProfileDocument | null> {
|
||||
const { id, companyId, sessionUser, ...updateData } = data;
|
||||
|
||||
if (!id && !companyId) {
|
||||
throw new Error("Se requiere un identificador para actualizar el perfil fiscal");
|
||||
}
|
||||
|
||||
return this.organizationFiscalProfileList
|
||||
.findOneAndUpdate(this.buildSearchCriteria({ id, companyId, sessionUser }), updateData, {
|
||||
new: true,
|
||||
})
|
||||
.exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { IOrganizationFiscalProfileDocument } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
|
||||
|
||||
export enum ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION {
|
||||
MONOTRIBUTO = "MONOTRIBUTO",
|
||||
EXENTO = "EXENTO",
|
||||
}
|
||||
|
||||
export enum ORGANIZATION_FISCAL_PROFILE_STATUS {
|
||||
PENDING = "PENDING",
|
||||
ACTIVE = "ACTIVE",
|
||||
DISABLED = "DISABLED",
|
||||
}
|
||||
|
||||
export type UpsertOrganizationFiscalProfileParams = {
|
||||
companyId: string;
|
||||
cuit: string;
|
||||
legalName: string;
|
||||
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
|
||||
pointOfSale: number;
|
||||
activityCode?: string;
|
||||
activityDescription?: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type FindOrganizationFiscalProfilesParams = {
|
||||
id?: string;
|
||||
companyId?: string;
|
||||
status?: ORGANIZATION_FISCAL_PROFILE_STATUS;
|
||||
sessionUser?: string;
|
||||
};
|
||||
|
||||
export type CreateOrganizationFiscalProfileParams = {
|
||||
companyId: string;
|
||||
cuit: string;
|
||||
legalName: string;
|
||||
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
|
||||
pointOfSale: number;
|
||||
activityCode?: string;
|
||||
activityDescription?: string;
|
||||
status: ORGANIZATION_FISCAL_PROFILE_STATUS;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type UpdateOrganizationFiscalProfileParams = FindOrganizationFiscalProfilesParams & {
|
||||
cuit?: string;
|
||||
legalName?: string;
|
||||
taxCondition?: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
|
||||
pointOfSale?: number;
|
||||
activityCode?: string;
|
||||
activityDescription?: string;
|
||||
status?: ORGANIZATION_FISCAL_PROFILE_STATUS;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export interface IOrganizationFiscalProfile {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
cuit: string;
|
||||
legalName: string;
|
||||
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
|
||||
pointOfSale: number;
|
||||
activityCode?: string;
|
||||
activityDescription?: string;
|
||||
status: ORGANIZATION_FISCAL_PROFILE_STATUS;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface IOrganizationFiscalProfilesAdapter {
|
||||
create(data: CreateOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfile>;
|
||||
find(filters: FindOrganizationFiscalProfilesParams): Promise<IOrganizationFiscalProfile[]>;
|
||||
findOne(
|
||||
filters: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfileDocument | null>;
|
||||
update(data: UpdateOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfileDocument | null>;
|
||||
}
|
||||
|
||||
export interface IOrganizationFiscalProfilesManager {
|
||||
organizationFiscalProfiles: IOrganizationFiscalProfilesAdapter;
|
||||
upsert(data: UpsertOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfile>;
|
||||
find(data: FindOrganizationFiscalProfilesParams): Promise<IOrganizationFiscalProfile[]>;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
import { findArcaActivityByCode } from "../ArcaActivities/ArcaActivities.Catalog";
|
||||
import { OrganizationFiscalProfilesAdapterMongoose } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
|
||||
import {
|
||||
FindOrganizationFiscalProfilesParams,
|
||||
IOrganizationFiscalProfile,
|
||||
IOrganizationFiscalProfilesManager,
|
||||
ORGANIZATION_FISCAL_PROFILE_STATUS,
|
||||
UpsertOrganizationFiscalProfileParams,
|
||||
} from "./OrganizationFiscalProfiles.Interface";
|
||||
|
||||
class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesManager {
|
||||
organizationFiscalProfiles: OrganizationFiscalProfilesAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.organizationFiscalProfiles = new OrganizationFiscalProfilesAdapterMongoose();
|
||||
}
|
||||
|
||||
private isDuplicateKeyError(error: unknown): boolean {
|
||||
return typeof error === "object" && error !== null && "code" in error && error.code === 11000;
|
||||
}
|
||||
|
||||
private validateProfileFields(data: UpsertOrganizationFiscalProfileParams): void {
|
||||
if (!/^\d{11}$/.test(data.cuit)) {
|
||||
throw new Error("El CUIT debe contener 11 dígitos");
|
||||
}
|
||||
|
||||
if (!data.legalName || !data.legalName.trim()) {
|
||||
throw new Error("La razón social es requerida");
|
||||
}
|
||||
|
||||
if (!data.pointOfSale || data.pointOfSale <= 0) {
|
||||
throw new Error("El punto de venta debe ser mayor a 0");
|
||||
}
|
||||
|
||||
const activityCode = data.activityCode?.trim();
|
||||
|
||||
if (activityCode && !/^\d{6}$/.test(activityCode)) {
|
||||
throw new Error("El código de actividad debe contener 6 dígitos");
|
||||
}
|
||||
|
||||
if (activityCode && !findArcaActivityByCode(activityCode)) {
|
||||
throw new Error("La actividad ARCA/CLAE seleccionada no existe en el catálogo");
|
||||
}
|
||||
}
|
||||
|
||||
private buildProfileData(data: UpsertOrganizationFiscalProfileParams) {
|
||||
const activityCode = data.activityCode?.trim();
|
||||
const activity = activityCode ? findArcaActivityByCode(activityCode) : undefined;
|
||||
|
||||
return {
|
||||
cuit: data.cuit,
|
||||
legalName: data.legalName.trim(),
|
||||
taxCondition: data.taxCondition,
|
||||
pointOfSale: data.pointOfSale,
|
||||
activityCode: activity?.code || "",
|
||||
activityDescription: activity?.description || "",
|
||||
status: ORGANIZATION_FISCAL_PROFILE_STATUS.ACTIVE,
|
||||
};
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
data: UpsertOrganizationFiscalProfileParams
|
||||
): Promise<IOrganizationFiscalProfile> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
|
||||
if (!data.companyId || !data.companyId.trim()) {
|
||||
throw new Error("Se requiere una organización para guardar el perfil fiscal");
|
||||
}
|
||||
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
this.validateProfileFields(data);
|
||||
|
||||
const existingProfile = await this.organizationFiscalProfiles.findOne({
|
||||
companyId: data.companyId,
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
const profileData = this.buildProfileData(data);
|
||||
|
||||
if (existingProfile) {
|
||||
const updatedProfile = await this.organizationFiscalProfiles.update({
|
||||
companyId: data.companyId,
|
||||
...profileData,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
if (!updatedProfile) {
|
||||
throw new Error("No se pudo actualizar el perfil fiscal");
|
||||
}
|
||||
|
||||
return updatedProfile;
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.organizationFiscalProfiles.create({
|
||||
companyId: data.companyId,
|
||||
...profileData,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isDuplicateKeyError(error)) {
|
||||
const updatedProfile = await this.organizationFiscalProfiles.update({
|
||||
companyId: data.companyId,
|
||||
...profileData,
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
if (updatedProfile) {
|
||||
return updatedProfile;
|
||||
}
|
||||
|
||||
const existingProfile = await this.organizationFiscalProfiles.findOne({
|
||||
companyId: data.companyId,
|
||||
});
|
||||
|
||||
if (existingProfile) {
|
||||
return existingProfile;
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(
|
||||
data: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfile[]> {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("Se requiere un usuario autenticado");
|
||||
}
|
||||
|
||||
const sessionUser = data.sessionUser;
|
||||
await validateSessionUser({ sessionUser });
|
||||
|
||||
if (data.companyId) {
|
||||
await validatePermissionsByCompany({
|
||||
companyId: data.companyId,
|
||||
sessionUser,
|
||||
});
|
||||
} else if (data.id) {
|
||||
const profile = await this.organizationFiscalProfiles.findOne(data);
|
||||
|
||||
if (!profile) {
|
||||
return [];
|
||||
}
|
||||
|
||||
await validatePermissionsByCompany({
|
||||
companyId: String(profile.companyId),
|
||||
sessionUser,
|
||||
});
|
||||
|
||||
return [profile];
|
||||
} else {
|
||||
throw new Error("Se requiere una organización para buscar perfiles fiscales");
|
||||
}
|
||||
|
||||
return await this.organizationFiscalProfiles.find(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new OrganizationFiscalProfilesManager();
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Document, Model, Schema, Types, model, models } from "mongoose";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { joinStrings } from "../../helpers/String";
|
||||
import {
|
||||
FindRatingsParams,
|
||||
IRating,
|
||||
IRatingsAdapter,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "./Ratings.Interface";
|
||||
|
||||
export interface IRatingDocument extends Omit<IRating, "id">, Document {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
type RatingReviewDocument = IRatingDocument & {
|
||||
userId?: {
|
||||
_id: Types.ObjectId;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
avatar?: string;
|
||||
};
|
||||
};
|
||||
|
||||
const GENERIC_REVIEW_AUTHOR = "Cliente verificado";
|
||||
|
||||
export class RatingsAdapterMongoose implements IRatingsAdapter {
|
||||
schema: Schema;
|
||||
ratingsList: Model<IRatingDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
appointmentId: { type: Schema.Types.ObjectId, required: true, ref: "Appointment" },
|
||||
userId: { type: Schema.Types.ObjectId, required: true, ref: "User" },
|
||||
companyId: { type: Schema.Types.ObjectId, required: true, ref: "Companie" },
|
||||
serviceId: { type: Schema.Types.ObjectId, required: true, ref: "Service" },
|
||||
employeeId: { type: Schema.Types.ObjectId, required: true, ref: "Employee" },
|
||||
targetType: { type: String, required: true, enum: Object.values(RatingTargetType) },
|
||||
targetId: { type: Schema.Types.ObjectId, required: true },
|
||||
score: { type: Number, required: true, min: 1, max: 5 },
|
||||
comment: { type: String, required: false, default: "", maxlength: RATING_COMMENT_MAX_LENGTH },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
this.schema.index({ userId: 1, targetType: 1, targetId: 1 }, { unique: true });
|
||||
this.ratingsList = (models.Rating as Model<IRatingDocument>) || model<IRatingDocument>("Rating", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: Omit<IRating, "id" | "createdAt" | "updatedAt">): Promise<IRating> {
|
||||
const rating = await this.ratingsList.create(data);
|
||||
return this.mapRating(rating);
|
||||
}
|
||||
|
||||
public async find(filters: FindRatingsParams): Promise<IRating[]> {
|
||||
const ratings = await this.ratingsList.find(filters).exec();
|
||||
return ratings.map((rating) => this.mapRating(rating));
|
||||
}
|
||||
|
||||
public async findOne(filters: FindRatingsParams): Promise<IRating | null> {
|
||||
const rating = await this.ratingsList.findOne(filters).exec();
|
||||
return rating ? this.mapRating(rating) : null;
|
||||
}
|
||||
|
||||
public async count(filters: FindRatingsParams): Promise<number> {
|
||||
return this.ratingsList.countDocuments(filters).exec();
|
||||
}
|
||||
|
||||
public async summaryByTarget(filters: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
const [summary] = await this.ratingsList
|
||||
.aggregate<{ averageScore: number; totalCount: number }>([
|
||||
{
|
||||
$match: {
|
||||
targetType: filters.targetType,
|
||||
targetId: new Types.ObjectId(filters.targetId),
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
averageScore: { $avg: "$score" },
|
||||
totalCount: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
|
||||
return {
|
||||
averageScore: summary?.averageScore || 0,
|
||||
totalCount: summary?.totalCount || 0,
|
||||
};
|
||||
}
|
||||
|
||||
public async summaryByTargets(filters: { targetType: RatingTargetType; targetIds: string[] }): Promise<RatingTargetSummaryResult> {
|
||||
const targetIds = filters.targetIds.filter((targetId) => Types.ObjectId.isValid(targetId));
|
||||
|
||||
if (targetIds.length === 0) {
|
||||
return { averageScore: 0, totalCount: 0 };
|
||||
}
|
||||
|
||||
const [summary] = await this.ratingsList
|
||||
.aggregate<{ averageScore: number; totalCount: number }>([
|
||||
{
|
||||
$match: {
|
||||
targetType: filters.targetType,
|
||||
targetId: { $in: targetIds.map((targetId) => new Types.ObjectId(targetId)) },
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
averageScore: { $avg: "$score" },
|
||||
totalCount: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
|
||||
return {
|
||||
averageScore: summary?.averageScore || 0,
|
||||
totalCount: summary?.totalCount || 0,
|
||||
};
|
||||
}
|
||||
|
||||
public async reviewsByTarget(filters: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
const page = filters.page || 1;
|
||||
const pageSize = filters.pageSize || filters.limit || 20;
|
||||
const targetReviewsFilter = {
|
||||
targetType: filters.targetType,
|
||||
targetId: new Types.ObjectId(filters.targetId),
|
||||
comment: { $regex: /\S/ },
|
||||
};
|
||||
|
||||
const total = await this.ratingsList.countDocuments(targetReviewsFilter).exec();
|
||||
const ratings = await this.ratingsList
|
||||
.find(targetReviewsFilter)
|
||||
.sort({ score: -1, createdAt: -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.select("score comment createdAt userId")
|
||||
.populate("userId", "firstName lastName avatar")
|
||||
.exec();
|
||||
|
||||
const reviews = (ratings as unknown as RatingReviewDocument[]).map((rating) => {
|
||||
const user = rating.userId;
|
||||
const displayName = user ? joinStrings([user.firstName, user.lastName], " ") : "";
|
||||
const authorName = displayName || GENERIC_REVIEW_AUTHOR;
|
||||
|
||||
return {
|
||||
id: rating._id.toString(),
|
||||
score: rating.score,
|
||||
comment: rating.comment || "",
|
||||
createdAt: rating.createdAt,
|
||||
author: {
|
||||
displayName: authorName,
|
||||
avatarUrl: user ? getAvatar(user._id.toString(), user.avatar, "") : "",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
reviews,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
};
|
||||
}
|
||||
|
||||
private mapRating(rating: IRatingDocument): IRating {
|
||||
return {
|
||||
id: rating._id.toString(),
|
||||
appointmentId: rating.appointmentId.toString(),
|
||||
userId: rating.userId.toString(),
|
||||
companyId: rating.companyId.toString(),
|
||||
serviceId: rating.serviceId.toString(),
|
||||
employeeId: rating.employeeId.toString(),
|
||||
targetType: rating.targetType,
|
||||
targetId: rating.targetId.toString(),
|
||||
score: rating.score,
|
||||
comment: rating.comment,
|
||||
createdAt: rating.createdAt,
|
||||
updatedAt: rating.updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
export enum RatingTargetType {
|
||||
COMPANY = "company",
|
||||
SERVICE = "service",
|
||||
EMPLOYEE = "employee",
|
||||
}
|
||||
|
||||
export const RATING_COMMENT_MAX_LENGTH = 1000;
|
||||
|
||||
export type FindRatingsParams = {
|
||||
_id?: string;
|
||||
appointmentId?: string;
|
||||
userId?: string;
|
||||
companyId?: string;
|
||||
serviceId?: string;
|
||||
employeeId?: string;
|
||||
targetType?: RatingTargetType;
|
||||
targetId?: string | { $in: string[] };
|
||||
};
|
||||
|
||||
export type CreateRatingParams = {
|
||||
appointmentId: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
score: number;
|
||||
comment?: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type PendingRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserResult = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type ProfessionalRatingSummaryByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryParams = {
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryResult = {
|
||||
averageScore: number;
|
||||
totalCount: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsParams = RatingTargetSummaryParams & {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewItem = {
|
||||
id: string;
|
||||
score: number;
|
||||
comment: string;
|
||||
createdAt: Date;
|
||||
author: {
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsResult = {
|
||||
reviews: RatingTargetReviewItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export interface IRating {
|
||||
id?: string;
|
||||
appointmentId: string;
|
||||
userId: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
score: number;
|
||||
comment?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface PendingRatingItem {
|
||||
appointmentId: string;
|
||||
appointmentDate: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
targetName: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
serviceName: string;
|
||||
}
|
||||
|
||||
export interface IRatingsAdapter {
|
||||
create(data: Omit<IRating, "id" | "createdAt" | "updatedAt">): Promise<IRating>;
|
||||
find(filters: FindRatingsParams): Promise<IRating[]>;
|
||||
findOne(filters: FindRatingsParams): Promise<IRating | null>;
|
||||
count(filters: FindRatingsParams): Promise<number>;
|
||||
summaryByTarget(filters: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult>;
|
||||
summaryByTargets(filters: { targetType: RatingTargetType; targetIds: string[] }): Promise<RatingTargetSummaryResult>;
|
||||
reviewsByTarget(filters: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult>;
|
||||
}
|
||||
|
||||
export interface IRatingsManager {
|
||||
ratings: IRatingsAdapter;
|
||||
createRating(data: CreateRatingParams): Promise<IRating>;
|
||||
pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]>;
|
||||
countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult>;
|
||||
professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult>;
|
||||
summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult>;
|
||||
reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult>;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import dayjs from "dayjs";
|
||||
import { Types } from "mongoose";
|
||||
import { isNull } from "../../helpers/IsNull";
|
||||
import { joinStrings } from "../../helpers/String";
|
||||
import AppointmentList from "../Appointments/Appointments";
|
||||
import CompaniesManager from "../Companies/Companies";
|
||||
import EmployeesList from "../Employees/Employee";
|
||||
import ServicesManager from "../Services/Service";
|
||||
import UsersManager from "../Users/Users";
|
||||
import { RatingsAdapterMongoose } from "./Ratings.Adapter.Mongoose";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
IRating,
|
||||
IRatingsManager,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "./Ratings.Interface";
|
||||
|
||||
const PENDING_RATINGS_APPOINTMENT_LIMIT = 50;
|
||||
const TARGET_REVIEWS_LIMIT = 20;
|
||||
|
||||
class RatingsManager implements IRatingsManager {
|
||||
ratings: RatingsAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.ratings = new RatingsAdapterMongoose();
|
||||
}
|
||||
|
||||
public async createRating(data: CreateRatingParams): Promise<IRating> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
this.validateScore(data.score);
|
||||
this.validateTargetType(data.targetType);
|
||||
const comment = isNull<string>(data.comment, "").trim();
|
||||
this.validateComment(comment);
|
||||
|
||||
const appointment = await AppointmentList.Appointments.AppointmentList.findOne({
|
||||
_id: data.appointmentId,
|
||||
userId: data.sessionUser,
|
||||
});
|
||||
|
||||
if (!appointment) {
|
||||
throw new Error("No se encontró un turno válido para calificar.");
|
||||
}
|
||||
|
||||
if (!appointment.present || !dayjs(appointment.dateDay).isBefore(dayjs().startOf("day"))) {
|
||||
throw new Error("Solo puedes calificar turnos pasados a los que asististe.");
|
||||
}
|
||||
|
||||
const expectedTargetId = this.getTargetId({
|
||||
targetType: data.targetType,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
});
|
||||
|
||||
if (String(data.targetId) !== expectedTargetId) {
|
||||
throw new Error("La calificación no corresponde al turno seleccionado.");
|
||||
}
|
||||
|
||||
const existingRating = await this.ratings.findOne({
|
||||
userId: data.sessionUser,
|
||||
targetType: data.targetType,
|
||||
targetId: data.targetId,
|
||||
});
|
||||
|
||||
if (existingRating) {
|
||||
throw new Error("Ya calificaste este item.");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.ratings.create({
|
||||
appointmentId: data.appointmentId,
|
||||
userId: data.sessionUser,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
targetType: data.targetType,
|
||||
targetId: data.targetId,
|
||||
score: data.score,
|
||||
comment,
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isDuplicateRatingError(error)) {
|
||||
throw new Error("Ya calificaste este item.");
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
const appointments = await AppointmentList.Appointments.AppointmentList.find({
|
||||
userId: data.sessionUser,
|
||||
present: true,
|
||||
dateDay: { $lt: dayjs().startOf("day").toDate() },
|
||||
})
|
||||
.sort({ start: -1 })
|
||||
.limit(PENDING_RATINGS_APPOINTMENT_LIMIT);
|
||||
|
||||
const pendingItems: PendingRatingItem[] = [];
|
||||
const seenTargets = new Set<string>();
|
||||
const candidateTargetIds = Array.from(
|
||||
new Set(
|
||||
appointments.flatMap((appointment) => [
|
||||
String(appointment.companyId),
|
||||
String(appointment.serviceId),
|
||||
String(appointment.employeeId),
|
||||
])
|
||||
)
|
||||
);
|
||||
const candidateTargetObjectIds = this.toObjectIds(candidateTargetIds);
|
||||
const existingRatings = await this.ratings.find({
|
||||
userId: data.sessionUser,
|
||||
targetId: { $in: candidateTargetIds },
|
||||
});
|
||||
const ratedTargets = new Set(
|
||||
existingRatings.map((rating) => `${rating.targetType}:${String(rating.targetId)}`)
|
||||
);
|
||||
const companies = await CompaniesManager.companies.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const services = await ServicesManager.services.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const employees = await EmployeesList.employees.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const employeeUserIds = Array.from(new Set(employees.map((employee) => String(employee.userId))));
|
||||
const employeeUsers = await UsersManager.users.find({ _id: { $in: this.toObjectIds(employeeUserIds) } } as any);
|
||||
|
||||
const companiesById = new Map(companies.map((company) => [String(company.id), company]));
|
||||
const servicesById = new Map(services.map((service) => [String(service.id), service]));
|
||||
const employeesById = new Map(employees.map((employee) => [String(employee.id), employee]));
|
||||
const employeeUsersById = new Map(employeeUsers.map((user) => [String(user.id), user]));
|
||||
|
||||
for (const appointment of appointments) {
|
||||
const company = companiesById.get(String(appointment.companyId));
|
||||
const service = servicesById.get(String(appointment.serviceId));
|
||||
const employee = employeesById.get(String(appointment.employeeId));
|
||||
|
||||
if (!company || !service || !employee) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const userEmployee = employeeUsersById.get(String(employee.userId));
|
||||
const employeeName = userEmployee
|
||||
? joinStrings([isNull<string>(userEmployee.firstName, ""), isNull<string>(userEmployee.lastName, "")], " ")
|
||||
: "Profesional";
|
||||
|
||||
const candidates = [
|
||||
{ targetType: RatingTargetType.COMPANY, targetId: String(appointment.companyId), targetName: company.name },
|
||||
{ targetType: RatingTargetType.SERVICE, targetId: String(appointment.serviceId), targetName: service.name },
|
||||
{ targetType: RatingTargetType.EMPLOYEE, targetId: String(appointment.employeeId), targetName: employeeName },
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const seenKey = `${candidate.targetType}:${candidate.targetId}`;
|
||||
if (seenTargets.has(seenKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ratedTargets.has(seenKey)) {
|
||||
seenTargets.add(seenKey);
|
||||
continue;
|
||||
}
|
||||
|
||||
pendingItems.push({
|
||||
appointmentId: String(appointment.id),
|
||||
appointmentDate: dayjs(appointment.start).toISOString(),
|
||||
targetType: candidate.targetType,
|
||||
targetId: candidate.targetId,
|
||||
targetName: candidate.targetName,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
serviceName: service.name,
|
||||
});
|
||||
|
||||
seenTargets.add(seenKey);
|
||||
}
|
||||
}
|
||||
|
||||
return pendingItems;
|
||||
}
|
||||
|
||||
public async countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
return {
|
||||
count: await this.ratings.count({ userId: data.sessionUser }),
|
||||
};
|
||||
}
|
||||
|
||||
public async professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
const employees = await EmployeesList.employees.find({
|
||||
userId: data.sessionUser,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
const employeeIds = employees.map((employee) => String(employee.id));
|
||||
|
||||
return this.ratings.summaryByTargets({
|
||||
targetType: RatingTargetType.EMPLOYEE,
|
||||
targetIds: employeeIds,
|
||||
});
|
||||
}
|
||||
|
||||
public async summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
this.validateTargetType(data.targetType);
|
||||
|
||||
if (!Types.ObjectId.isValid(data.targetId)) {
|
||||
throw new Error("No se ha proporcionado un objetivo válido.");
|
||||
}
|
||||
|
||||
return this.ratings.summaryByTarget(data);
|
||||
}
|
||||
|
||||
public async reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
this.validateTargetType(data.targetType);
|
||||
|
||||
if (!Types.ObjectId.isValid(data.targetId)) {
|
||||
throw new Error("No se ha proporcionado un objetivo válido.");
|
||||
}
|
||||
|
||||
const pageSize = Math.min(Math.max(data.pageSize || data.limit || TARGET_REVIEWS_LIMIT, 1), TARGET_REVIEWS_LIMIT);
|
||||
const page = Math.max(data.page || 1, 1);
|
||||
|
||||
return this.ratings.reviewsByTarget({
|
||||
...data,
|
||||
page,
|
||||
pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
}
|
||||
|
||||
private async validateSessionUser(sessionUser: string): Promise<void> {
|
||||
const user = await UsersManager.users.findOne({ _id: sessionUser });
|
||||
|
||||
if (!user) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
}
|
||||
|
||||
private toObjectIds(ids: string[]): Types.ObjectId[] {
|
||||
return ids.filter((id) => Types.ObjectId.isValid(id)).map((id) => new Types.ObjectId(id));
|
||||
}
|
||||
|
||||
private validateScore(score: number): void {
|
||||
if (!Number.isInteger(score) || score < 1 || score > 5) {
|
||||
throw new Error("La calificación debe estar entre 1 y 5.");
|
||||
}
|
||||
}
|
||||
|
||||
private validateTargetType(targetType: RatingTargetType): void {
|
||||
if (!Object.values(RatingTargetType).includes(targetType)) {
|
||||
throw new Error("El tipo de calificación no es válido.");
|
||||
}
|
||||
}
|
||||
|
||||
private validateComment(comment: string): void {
|
||||
if (comment.length > RATING_COMMENT_MAX_LENGTH) {
|
||||
throw new Error(`El comentario no puede superar los ${RATING_COMMENT_MAX_LENGTH} caracteres.`);
|
||||
}
|
||||
}
|
||||
|
||||
private isDuplicateRatingError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && error.code === 11000);
|
||||
}
|
||||
|
||||
private getTargetId(data: {
|
||||
targetType: RatingTargetType;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
}): string {
|
||||
if (data.targetType === RatingTargetType.COMPANY) {
|
||||
return data.companyId;
|
||||
}
|
||||
|
||||
if (data.targetType === RatingTargetType.SERVICE) {
|
||||
return data.serviceId;
|
||||
}
|
||||
|
||||
return data.employeeId;
|
||||
}
|
||||
}
|
||||
|
||||
const RatingsList = new RatingsManager();
|
||||
|
||||
export default RatingsList;
|
||||
@@ -212,6 +212,7 @@ class RepeatsManager implements IRepeatsManager {
|
||||
}
|
||||
|
||||
await this.repeats.delete(data.repeatId);
|
||||
await MetricsList.addRepeat({ userId: String(companyCheck.ownerId), quantity: -1 });
|
||||
}
|
||||
|
||||
public async deleteRepeatsByCompany(data: DeleteRepeatsByCompanyParams): Promise<void> {
|
||||
|
||||
@@ -8,6 +8,34 @@ export type ScheduleItem = {
|
||||
serviceIds?: string[];
|
||||
};
|
||||
|
||||
export type ScheduleConflictStrategy = "reject" | "overwrite-conflicts";
|
||||
|
||||
export type ScheduleConflictDetail = {
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
weekDay: number;
|
||||
weekDayLabel: string;
|
||||
attempted: ScheduleItem;
|
||||
existing: ScheduleItem;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type ScheduleApplyParams = {
|
||||
companyId: string;
|
||||
employeeIds: string[];
|
||||
weekDays: number[];
|
||||
schedules: ScheduleItem[];
|
||||
sessionUser: string;
|
||||
conflictStrategy: ScheduleConflictStrategy;
|
||||
};
|
||||
|
||||
export type ScheduleApplyResult = {
|
||||
valid: boolean;
|
||||
applied: boolean;
|
||||
conflicts: ScheduleConflictDetail[];
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type FindSchedulesParams = {
|
||||
_id?: string;
|
||||
companyId?: string;
|
||||
@@ -100,6 +128,7 @@ export interface ISchedulesManager {
|
||||
findAllSchedulesByCollaborator(data: FindSchedulesParams): Promise<CollaboratorSchedulesView>;
|
||||
delete(data: DeleteScheduleParams): Promise<void>;
|
||||
isAvailable(data: AvailableSchedulesParams): Promise<boolean>;
|
||||
applyScheduleChanges(data: ScheduleApplyParams): Promise<ScheduleApplyResult>;
|
||||
deleteSchedulesByCompany(data: DeleteScheulesByCompanyParams): Promise<void>;
|
||||
deleteSchedulesByEmployee(data: DeleteSchedulesByEmployeeParams): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
DeleteScheulesByCompanyParams,
|
||||
DeleteSchedulesByEmployeeParams,
|
||||
ScheduleItem,
|
||||
ScheduleApplyParams,
|
||||
ScheduleApplyResult,
|
||||
ScheduleConflictDetail,
|
||||
} from "./Schedules.Interface";
|
||||
import { EmployeeRoles } from "../Employees/Employees.Interface";
|
||||
import UsersManager from "../Users/Users";
|
||||
@@ -24,6 +27,9 @@ import { isNull } from "../../helpers/IsNull";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { NotificationsManager } from "../Notifications/Notifications";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
|
||||
const WEEK_DAY_LABELS = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
|
||||
|
||||
class SchedulesManager implements ISchedulesManager {
|
||||
schedules: SchedulesAdapterMongoose;
|
||||
@@ -173,6 +179,169 @@ class SchedulesManager implements ISchedulesManager {
|
||||
return await this.schedules.find(filters);
|
||||
}
|
||||
|
||||
private parseTimeToMinutes(time: string): number {
|
||||
const [hours, minutes] = time.split(":").map((part) => Number(part));
|
||||
|
||||
if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
|
||||
throw new Error("El horario indicado no es válido");
|
||||
}
|
||||
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
private hasTimeOverlap(first: ScheduleItem, second: ScheduleItem): boolean {
|
||||
return this.parseTimeToMinutes(first.from) < this.parseTimeToMinutes(second.to)
|
||||
&& this.parseTimeToMinutes(second.from) < this.parseTimeToMinutes(first.to);
|
||||
}
|
||||
|
||||
private getServiceScope(schedule: ScheduleItem): "all" | "specific" {
|
||||
return schedule.serviceScope || "all";
|
||||
}
|
||||
|
||||
private hasServiceOverlap(first: ScheduleItem, second: ScheduleItem): boolean {
|
||||
const firstScope = this.getServiceScope(first);
|
||||
const secondScope = this.getServiceScope(second);
|
||||
|
||||
if (firstScope === "all" || secondScope === "all") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const secondServices = new Set(second.serviceIds || []);
|
||||
return (first.serviceIds || []).some((serviceId) => secondServices.has(serviceId));
|
||||
}
|
||||
|
||||
private hasScheduleConflict(first: ScheduleItem, second: ScheduleItem): boolean {
|
||||
if (first.disabled || second.disabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.hasTimeOverlap(first, second) && this.hasServiceOverlap(first, second);
|
||||
}
|
||||
|
||||
private formatSchedule(schedule: ScheduleItem): string {
|
||||
if (this.getServiceScope(schedule) === "all") {
|
||||
return `${schedule.from} a ${schedule.to} para todos los servicios`;
|
||||
}
|
||||
|
||||
return `${schedule.from} a ${schedule.to} para servicios específicos`;
|
||||
}
|
||||
|
||||
private getEmployeeName(employee: any): string {
|
||||
const snapshotName = [employee.profileSnapshot?.firstName, employee.profileSnapshot?.lastName].filter(Boolean).join(" ").trim();
|
||||
return snapshotName || employee.fullName || employee.name || String(employee._id);
|
||||
}
|
||||
|
||||
private buildConflict(employee: any, weekDay: number, attempted: ScheduleItem, existing: ScheduleItem): ScheduleConflictDetail {
|
||||
const employeeId = String(employee._id);
|
||||
const employeeName = this.getEmployeeName(employee);
|
||||
const weekDayLabel = WEEK_DAY_LABELS[weekDay] || String(weekDay);
|
||||
|
||||
return {
|
||||
employeeId,
|
||||
employeeName,
|
||||
weekDay,
|
||||
weekDayLabel,
|
||||
attempted,
|
||||
existing,
|
||||
message: `${employeeName} ya tiene un horario el ${weekDayLabel} de ${this.formatSchedule(existing)} que se superpone con ${this.formatSchedule(attempted)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
private async findScheduleDocument(companyId: string, employeeId: string, weekDay: number) {
|
||||
return this.schedules.findOne({ companyId, employeeId, weekDay });
|
||||
}
|
||||
|
||||
public async applyScheduleChanges(data: ScheduleApplyParams): Promise<ScheduleApplyResult> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
if (!Array.isArray(data.employeeIds) || data.employeeIds.length === 0) {
|
||||
throw new Error("Tenés que seleccionar al menos un colaborador.");
|
||||
}
|
||||
|
||||
if (!Array.isArray(data.weekDays) || data.weekDays.length === 0 || data.weekDays.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
|
||||
throw new Error("Tenés que seleccionar días válidos entre 0 y 6.");
|
||||
}
|
||||
|
||||
if (data.conflictStrategy !== "reject" && data.conflictStrategy !== "overwrite-conflicts") {
|
||||
throw new Error("La estrategia de conflictos no es válida.");
|
||||
}
|
||||
|
||||
const employees = await Promise.all(data.employeeIds.map(async (employeeId) => {
|
||||
const employee = await EmployeesList.employees.findOne({ companyId: data.companyId, _id: employeeId });
|
||||
|
||||
if (!employee) {
|
||||
throw new Error("El empleado no existe o no pertenece a la compañia.");
|
||||
}
|
||||
|
||||
return employee;
|
||||
}));
|
||||
|
||||
const conflicts: ScheduleConflictDetail[] = [];
|
||||
|
||||
for (const employee of employees) {
|
||||
const employeeId = String(employee._id);
|
||||
|
||||
for (const weekDay of data.weekDays) {
|
||||
const scheduleDocument = await this.findScheduleDocument(data.companyId, employeeId, weekDay);
|
||||
const existingSchedules = scheduleDocument?.schedules || [];
|
||||
|
||||
for (const attempted of data.schedules) {
|
||||
const existing = existingSchedules.find((schedule) => this.hasScheduleConflict(attempted, schedule));
|
||||
|
||||
if (existing) {
|
||||
conflicts.push(this.buildConflict(employee, weekDay, attempted, existing));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicts.length > 0 && data.conflictStrategy === "reject") {
|
||||
return {
|
||||
valid: false,
|
||||
applied: false,
|
||||
conflicts,
|
||||
message: "Encontramos horarios superpuestos. Revisalos antes de guardar o elegí sobrescribir solo esos conflictos.",
|
||||
};
|
||||
}
|
||||
|
||||
for (const employee of employees) {
|
||||
const employeeId = String(employee._id);
|
||||
|
||||
for (const weekDay of data.weekDays) {
|
||||
const scheduleDocument = await this.findScheduleDocument(data.companyId, employeeId, weekDay);
|
||||
const existingSchedules = scheduleDocument?.schedules || [];
|
||||
const nextSchedules = data.conflictStrategy === "overwrite-conflicts"
|
||||
? existingSchedules.filter((existing) => !data.schedules.some((attempted) => this.hasScheduleConflict(attempted, existing)))
|
||||
: existingSchedules;
|
||||
|
||||
const schedules = [...nextSchedules, ...data.schedules];
|
||||
|
||||
if (scheduleDocument) {
|
||||
scheduleDocument.schedules = schedules;
|
||||
await scheduleDocument.save();
|
||||
} else {
|
||||
await this.schedules.create({
|
||||
companyId: data.companyId,
|
||||
employeeId,
|
||||
weekDay,
|
||||
schedules,
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: conflicts.length === 0,
|
||||
applied: true,
|
||||
conflicts,
|
||||
message: conflicts.length > 0
|
||||
? "Se sobrescribieron solo los horarios en conflicto."
|
||||
: "Los horarios se guardaron correctamente.",
|
||||
};
|
||||
}
|
||||
|
||||
private isScheduleAvailableForService(schedule: ScheduleItem, serviceId?: string): boolean {
|
||||
if (!serviceId || !schedule.serviceScope || schedule.serviceScope === "all") {
|
||||
return true;
|
||||
|
||||
@@ -32,6 +32,12 @@ export class SchedulesDisabledAdapterMongoose implements ISchedulesDisabledAdapt
|
||||
await this.schedulesDisabledList.deleteOne({ _id: id }).exec();
|
||||
}
|
||||
|
||||
public async find(
|
||||
filters: Omit<FindSchedulesDisabledParams, "sessionUser">
|
||||
): Promise<ISchedulesDisabledDocument[]> {
|
||||
return this.schedulesDisabledList.find(filters).exec();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: Omit<FindSchedulesDisabledParams, "sessionUser">
|
||||
): Promise<ISchedulesDisabledDocument | null> {
|
||||
|
||||
@@ -90,6 +90,7 @@ export interface SchedulesDisabledByCollaboratorView {
|
||||
export interface ISchedulesDisabledAdapter {
|
||||
create(data: CreateSchedulesDisabledParams): Promise<ISchedulesDisabled>;
|
||||
delete(id: string): Promise<void>;
|
||||
find(filters: Omit<FindSchedulesDisabledParams, "sessionUser">): Promise<ISchedulesDisabled[]>;
|
||||
findOne(filters: FindSchedulesDisabledParams): Promise<ISchedulesDisabled | null>;
|
||||
}
|
||||
|
||||
@@ -98,6 +99,7 @@ export interface ISchedulesDisabledManager {
|
||||
createSchedulesDisabled(data: CreateSchedulesDisabledParams): Promise<ISchedulesDisabled>;
|
||||
disableSchedule(data: DisableScheduleParams): Promise<void>;
|
||||
enableSchedule(data: DisableScheduleParams): Promise<void>;
|
||||
find(data: FindSchedulesDisabledParams): Promise<ISchedulesDisabled[]>;
|
||||
findOne(data: FindSchedulesDisabledParams): Promise<ISchedulesDisabled | null>;
|
||||
findSchedulesDisabledByCollaborator(
|
||||
data: FindSchedulesDisabledParams
|
||||
|
||||
@@ -271,6 +271,17 @@ class SchedulesDisabledManager implements ISchedulesDisabledManager {
|
||||
return await this.schedulesDisabled.findOne(data);
|
||||
}
|
||||
|
||||
public async find(data: FindSchedulesDisabledParams): Promise<ISchedulesDisabled[]> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({
|
||||
sessionUser: data.sessionUser,
|
||||
companyId: data.companyId,
|
||||
});
|
||||
|
||||
const { sessionUser, ...filters } = data;
|
||||
return await this.schedulesDisabled.find(filters);
|
||||
}
|
||||
|
||||
public async delete(data: DeleteSchedulesDisabledParams): Promise<void> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
|
||||
|
||||
@@ -49,6 +49,49 @@ export type EnableScheduleParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodScope = "employee" | "all";
|
||||
|
||||
export type ReservationPeriodDurationUnit = "week" | "month";
|
||||
|
||||
export type ReservationPeriodDuration = {
|
||||
unit: ReservationPeriodDurationUnit;
|
||||
value: number;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummaryParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ExtendReservationPeriodsParams = {
|
||||
companyId: string;
|
||||
scope: ReservationPeriodScope;
|
||||
employeeId?: string;
|
||||
duration?: ReservationPeriodDuration;
|
||||
weeks?: number;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodEmployeeSummary = {
|
||||
employeeId: string;
|
||||
employeeFullName: string;
|
||||
employeeEmail: string;
|
||||
employeeAvatar: string;
|
||||
employeeUserId: string;
|
||||
isOpen: boolean;
|
||||
currentOpenUntil: Date | null;
|
||||
daysRemaining: number | null;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummary = {
|
||||
companyId: string;
|
||||
status: "missing" | "expired" | "near-ending" | "open";
|
||||
worstDaysRemaining: number | null;
|
||||
currentOpenUntil: Date | null;
|
||||
nearEndingThresholdDays: number;
|
||||
employees: ReservationPeriodEmployeeSummary[];
|
||||
};
|
||||
|
||||
export type DeleteSchedulesEnabledByCompanyParams = {
|
||||
companyId: string;
|
||||
};
|
||||
@@ -94,4 +137,6 @@ export interface ISchedulesEnabledManager {
|
||||
exists(data: CheckSchedulesEnabledParams): Promise<boolean>;
|
||||
deleteSchedulesEnabledByCompany(data: DeleteSchedulesEnabledByCompanyParams): Promise<void>;
|
||||
deleteSchedulesEnabledByEmployee(data: DeleteSchedulesEnabledByEmployeeParams): Promise<void>;
|
||||
summarizeReservationPeriods(data: ReservationPeriodsSummaryParams): Promise<ReservationPeriodsSummary>;
|
||||
extendReservationPeriods(data: ExtendReservationPeriodsParams): Promise<ReservationPeriodsSummary>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
FindSchedulesEnabledParams,
|
||||
ISchedulesEnabled,
|
||||
ISchedulesEnabledManager,
|
||||
ReservationPeriodEmployeeSummary,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
SchedulesEnabledView,
|
||||
} from "./SchedulesEnabled.Interface";
|
||||
import { EmployeeRoles } from "../Employees/Employees.Interface";
|
||||
@@ -21,10 +25,26 @@ import { joinStrings } from "../../helpers/String";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { NotificationsManager } from "../Notifications/Notifications";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import "dayjs/locale/es";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.locale("es");
|
||||
|
||||
const SCHEDULE_BOUNDARY_TIMEZONE = "America/Argentina/Buenos_Aires";
|
||||
const NEAR_ENDING_THRESHOLD_DAYS = 14;
|
||||
const ALLOWED_RESERVATION_PERIOD_DURATIONS = [
|
||||
{ unit: "week", value: 1 },
|
||||
{ unit: "week", value: 2 },
|
||||
{ unit: "week", value: 3 },
|
||||
{ unit: "month", value: 1 },
|
||||
{ unit: "month", value: 2 },
|
||||
] as const;
|
||||
|
||||
class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
schedulesEnabled: SchedulesEnabledAdapterMongoose;
|
||||
|
||||
@@ -73,8 +93,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: data.employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -84,8 +104,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const newEmplyeesEnabled = await this.schedulesEnabled.create({
|
||||
employeeId: data.employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
@@ -125,7 +145,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const employeeCheck = await EmployeesList.employees.findOne({
|
||||
companyId: data.companyId,
|
||||
_id: employeeId,
|
||||
});
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employeeCheck) {
|
||||
continue;
|
||||
@@ -134,8 +155,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -145,8 +166,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
await this.schedulesEnabled.create({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
@@ -185,7 +206,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const employeeCheck = await EmployeesList.employees.findOne({
|
||||
companyId: data.companyId,
|
||||
_id: employeeId,
|
||||
});
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employeeCheck) {
|
||||
continue;
|
||||
@@ -194,8 +216,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -229,11 +251,16 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
}
|
||||
|
||||
public async find(data: FindSchedulesEnabledParams): Promise<SchedulesEnabledView[]> {
|
||||
let employeeFilter: any = { companyId: data.companyId };
|
||||
const rangeStart = this.normalizeScheduleStartDate(data.startDate);
|
||||
const rangeEnd = this.normalizeScheduleEndDate(data.endDate);
|
||||
let employeeFilter: any = {
|
||||
companyId: data.companyId,
|
||||
removed: { $ne: true },
|
||||
};
|
||||
if (data.employeeId) {
|
||||
employeeFilter = {
|
||||
...employeeFilter,
|
||||
employeeId: data.employeeId,
|
||||
_id: data.employeeId,
|
||||
};
|
||||
}
|
||||
const employees = await EmployeesList.employees.find(employeeFilter);
|
||||
@@ -244,8 +271,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabled = await this.schedulesEnabled.schedulesEnabledList.findOne({
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: { $lte: rangeStart },
|
||||
endDate: { $gte: rangeEnd },
|
||||
});
|
||||
|
||||
const employUser = await UsersManager.users.findOne({
|
||||
@@ -297,6 +324,189 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
|
||||
await this.schedulesEnabled.delete(String(data.id));
|
||||
}
|
||||
|
||||
public async summarizeReservationPeriods(
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
return this.buildReservationPeriodsSummary(data.companyId);
|
||||
}
|
||||
|
||||
public async extendReservationPeriods(
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
const duration = data.duration || (data.weeks ? { unit: "week" as const, value: Number(data.weeks) } : null);
|
||||
|
||||
if (!duration || !ALLOWED_RESERVATION_PERIOD_DURATIONS.some(option => option.unit === duration.unit && option.value === Number(duration.value))) {
|
||||
throw new Error("El período seleccionado no es válido");
|
||||
}
|
||||
|
||||
const employees = await EmployeesList.employees.find({
|
||||
companyId: data.companyId,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
let targetEmployees = employees;
|
||||
|
||||
if (data.scope === "employee") {
|
||||
if (!data.employeeId) {
|
||||
throw new Error("Debe seleccionar un colaborador");
|
||||
}
|
||||
|
||||
targetEmployees = employees.filter(employee => String(employee.id) === String(data.employeeId));
|
||||
|
||||
if (targetEmployees.length === 0) {
|
||||
throw new Error("El colaborador no existe o no pertenece a la organización");
|
||||
}
|
||||
} else if (data.scope !== "all") {
|
||||
throw new Error("El alcance seleccionado no es válido");
|
||||
}
|
||||
|
||||
if (targetEmployees.length === 0) {
|
||||
throw new Error("No hay colaboradores disponibles para extender el período de reservas");
|
||||
}
|
||||
|
||||
const today = dayjs().startOf("day");
|
||||
const summary = await this.buildReservationPeriodsSummary(data.companyId);
|
||||
const operations = targetEmployees.flatMap(employee => {
|
||||
const employeeSummary = summary.employees.find(item => String(item.employeeId) === String(employee.id));
|
||||
const startDate = employeeSummary?.currentOpenUntil && !dayjs(employeeSummary.currentOpenUntil).endOf("day").isBefore(today)
|
||||
? this.getNextWeekStartAfter(dayjs(employeeSummary.currentOpenUntil))
|
||||
: this.getWeekStart(today);
|
||||
const weekRanges = this.buildReservationPeriodWeekRanges(startDate, duration);
|
||||
|
||||
return weekRanges.map(range => ({
|
||||
updateOne: {
|
||||
filter: {
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: this.normalizeScheduleStartDate(range.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(range.endDate),
|
||||
},
|
||||
update: {
|
||||
$setOnInsert: {
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: this.normalizeScheduleStartDate(range.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(range.endDate),
|
||||
},
|
||||
},
|
||||
upsert: true,
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
await this.schedulesEnabled.schedulesEnabledList.bulkWrite(operations, { ordered: true });
|
||||
|
||||
return this.buildReservationPeriodsSummary(data.companyId);
|
||||
}
|
||||
|
||||
private getWeekStart(date: dayjs.Dayjs): dayjs.Dayjs {
|
||||
return date.startOf("day").subtract((date.day() + 6) % 7, "day");
|
||||
}
|
||||
|
||||
private getNextWeekStartAfter(date: dayjs.Dayjs): dayjs.Dayjs {
|
||||
const nextDay = date.add(1, "day").startOf("day");
|
||||
const weekStart = this.getWeekStart(nextDay);
|
||||
|
||||
return weekStart.isBefore(nextDay) ? weekStart.add(1, "week") : weekStart;
|
||||
}
|
||||
|
||||
private buildReservationPeriodWeekRanges(
|
||||
startWeek: dayjs.Dayjs,
|
||||
duration: { unit: "week" | "month"; value: number }
|
||||
): { startDate: dayjs.Dayjs; endDate: dayjs.Dayjs }[] {
|
||||
const ranges: { startDate: dayjs.Dayjs; endDate: dayjs.Dayjs }[] = [];
|
||||
const targetEnd = duration.unit === "week"
|
||||
? startWeek.add(Number(duration.value), "week").subtract(1, "day").endOf("day")
|
||||
: startWeek.add(Number(duration.value), "month").subtract(1, "day").endOf("day");
|
||||
let currentWeekStart = startWeek.startOf("day");
|
||||
|
||||
while (!currentWeekStart.isAfter(targetEnd)) {
|
||||
ranges.push({
|
||||
startDate: currentWeekStart,
|
||||
endDate: currentWeekStart.add(6, "day").endOf("day"),
|
||||
});
|
||||
currentWeekStart = currentWeekStart.add(1, "week");
|
||||
}
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
private normalizeScheduleStartDate(date: string | Date | dayjs.Dayjs): Date {
|
||||
return dayjs.tz(this.getScheduleDateOnly(date), SCHEDULE_BOUNDARY_TIMEZONE).startOf("day").toDate();
|
||||
}
|
||||
|
||||
private normalizeScheduleEndDate(date: string | Date | dayjs.Dayjs): Date {
|
||||
return dayjs.tz(this.getScheduleDateOnly(date), SCHEDULE_BOUNDARY_TIMEZONE).endOf("day").toDate();
|
||||
}
|
||||
|
||||
private getScheduleDateOnly(date: string | Date | dayjs.Dayjs): string {
|
||||
if (typeof date === "string") {
|
||||
return date.slice(0, 10);
|
||||
}
|
||||
|
||||
if (dayjs.isDayjs(date)) {
|
||||
return date.format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
private async buildReservationPeriodsSummary(companyId: string): Promise<ReservationPeriodsSummary> {
|
||||
const today = dayjs().startOf("day");
|
||||
const employees = await EmployeesList.findByCompanyId({ companyId });
|
||||
const employeeSummaries: ReservationPeriodEmployeeSummary[] = [];
|
||||
|
||||
for (const employee of employees) {
|
||||
const latestPeriod = await this.schedulesEnabled.schedulesEnabledList
|
||||
.findOne({ companyId, employeeId: employee.id })
|
||||
.sort({ endDate: -1 })
|
||||
.exec();
|
||||
|
||||
const currentOpenUntil = latestPeriod ? latestPeriod.endDate : null;
|
||||
const daysRemaining = currentOpenUntil
|
||||
? dayjs(currentOpenUntil).endOf("day").diff(today, "day")
|
||||
: null;
|
||||
|
||||
employeeSummaries.push({
|
||||
employeeId: employee.id,
|
||||
employeeFullName: employee.fullName,
|
||||
employeeEmail: employee.email,
|
||||
employeeAvatar: employee.avatar,
|
||||
employeeUserId: employee.userId,
|
||||
isOpen: daysRemaining !== null && daysRemaining >= 0,
|
||||
currentOpenUntil,
|
||||
daysRemaining,
|
||||
});
|
||||
}
|
||||
|
||||
const currentOpenUntilDates = employeeSummaries
|
||||
.map(employee => employee.currentOpenUntil)
|
||||
.filter((date): date is Date => Boolean(date));
|
||||
const remainingValues = employeeSummaries
|
||||
.map(employee => employee.daysRemaining)
|
||||
.filter((days): days is number => days !== null);
|
||||
const hasMissing = employeeSummaries.some(employee => employee.currentOpenUntil === null);
|
||||
const hasExpired = employeeSummaries.some(employee => employee.daysRemaining !== null && employee.daysRemaining < 0);
|
||||
const hasNearEnding = employeeSummaries.some(employee => employee.daysRemaining !== null && employee.daysRemaining <= NEAR_ENDING_THRESHOLD_DAYS);
|
||||
|
||||
return {
|
||||
companyId,
|
||||
status: hasMissing ? "missing" : hasExpired ? "expired" : hasNearEnding ? "near-ending" : "open",
|
||||
worstDaysRemaining: remainingValues.length > 0 ? Math.min(...remainingValues) : null,
|
||||
currentOpenUntil: currentOpenUntilDates.length > 0
|
||||
? currentOpenUntilDates.reduce((max, date) => dayjs(date).isAfter(max) ? date : max, currentOpenUntilDates[0])
|
||||
: null,
|
||||
nearEndingThresholdDays: NEAR_ENDING_THRESHOLD_DAYS,
|
||||
employees: employeeSummaries,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const SchedulesEnabledList = new SchedulesEnabledManager();
|
||||
|
||||
@@ -42,6 +42,8 @@ export class ServicesAdapterMongoose implements IServicesAdapter {
|
||||
longitude: { type: Number, required: false, default: 0 },
|
||||
published: { type: String, required: false },
|
||||
banned: { type: Boolean, required: false, default: false },
|
||||
showPublicScores: { type: Boolean, required: false, default: true },
|
||||
showPublicOpinions: { type: Boolean, required: false, default: true },
|
||||
});
|
||||
|
||||
this.serviceList = model<IServiceDocument>("Service", this.schema);
|
||||
@@ -93,6 +95,8 @@ export class ServicesAdapterMongoose implements IServicesAdapter {
|
||||
if (data.latitude) updateService.latitude = data.latitude;
|
||||
if (data.longitude) updateService.longitude = data.longitude;
|
||||
if (data.banned !== undefined) updateService.banned = data.banned;
|
||||
if (data.showPublicScores !== undefined) updateService.showPublicScores = data.showPublicScores;
|
||||
if (data.showPublicOpinions !== undefined) updateService.showPublicOpinions = data.showPublicOpinions;
|
||||
|
||||
await updateService.save();
|
||||
}
|
||||
|
||||
@@ -57,6 +57,8 @@ export type CreateServiceParams = {
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type UpdateServiceParams = {
|
||||
@@ -81,6 +83,8 @@ export type UpdateServiceParams = {
|
||||
longitude?: number;
|
||||
sessionUser: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type PaginatePublicServicesParams = FindServicesParams & {
|
||||
@@ -155,6 +159,8 @@ export interface IService {
|
||||
published?: SERVICE_PUBLISHED_STATUS;
|
||||
discountId?: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
}
|
||||
|
||||
export interface CompanyServiceView {
|
||||
@@ -176,6 +182,8 @@ export interface CompanyServiceView {
|
||||
fontShadowColor: string;
|
||||
published: SERVICE_PUBLISHED_STATUS;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface PublicServiceView {
|
||||
@@ -199,6 +207,8 @@ export interface PublicServiceView {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface FindServicesByCompanyParams {
|
||||
|
||||
@@ -46,6 +46,17 @@ class ServiceManager implements IServicesManager {
|
||||
this.services = new ServicesAdapterMongoose();
|
||||
}
|
||||
|
||||
private async validatePublicRatingFlagsPlan(ownerId: string): Promise<void> {
|
||||
const { default: PlanSubscriptionsList } = await import("../PlanSubscriptions/PlanSubscriptons");
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: ownerId,
|
||||
});
|
||||
|
||||
if (!subscription || subscription.plan.price === 0) {
|
||||
throw new Error("Esta configuración está disponible solo para planes pagos.");
|
||||
}
|
||||
}
|
||||
|
||||
public async setPublishedStatus(data: SetPublishedStatusParams): Promise<void> {
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
@@ -145,6 +156,10 @@ class ServiceManager implements IServicesManager {
|
||||
throw new Error("Ha alcanzado el limite de servicios permitidos de acuerdo a su plan.");
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined || data.showPublicOpinions !== undefined) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
const newService = await this.services.create({
|
||||
...data,
|
||||
...{
|
||||
@@ -190,6 +205,10 @@ class ServiceManager implements IServicesManager {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined || data.showPublicOpinions !== undefined) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
await this.services.update(data);
|
||||
}
|
||||
|
||||
@@ -307,6 +326,8 @@ class ServiceManager implements IServicesManager {
|
||||
service.published,
|
||||
SERVICE_PUBLISHED_STATUS.PRIVATE
|
||||
),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -363,6 +384,8 @@ class ServiceManager implements IServicesManager {
|
||||
fontColor: isNull<string>(service.fontColor, defFontColor),
|
||||
fontShadowColor: isNull<string>(service.fontShadowColor, defFontShadowColor),
|
||||
published: isNull<SERVICE_PUBLISHED_STATUS>(service.published, SERVICE_PUBLISHED_STATUS.PRIVATE),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -486,6 +509,8 @@ class ServiceManager implements IServicesManager {
|
||||
color: isNull<string>(service.color, defColor),
|
||||
fontColor: isNull<string>(service.fontColor, defFontColor),
|
||||
fontShadowColor: isNull<string>(service.fontShadowColor, defFontShadowColor),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -351,6 +351,28 @@ class UsersManager implements IUsersManager {
|
||||
.substring(0, 6);
|
||||
}
|
||||
|
||||
private async sendWelcomeEmail(email: string, firstName?: string): Promise<void> {
|
||||
try {
|
||||
await NotificationsManager.sendEmail({
|
||||
email: cleanEmail(email),
|
||||
templateId: "68139f23f3e003139b08b4f0",
|
||||
context: {
|
||||
username: firstName || cleanEmail(email),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (axios.isAxiosError(e)) {
|
||||
console.error("Error enviando email de bienvenida:", {
|
||||
status: e.response?.status,
|
||||
data: e.response?.data,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.error("Error enviando email de bienvenida:", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async signUp(data: SignUpParams): Promise<IUser> {
|
||||
// Destructure email and password from the data object
|
||||
const {
|
||||
@@ -406,12 +428,13 @@ class UsersManager implements IUsersManager {
|
||||
|
||||
const newUser = await this.users.create(newUserData);
|
||||
|
||||
const signUpUrl = "https://turnosxpress.com.ar/landing/login/verification";
|
||||
|
||||
await NotificationsManager.sendEmail({
|
||||
email: cleanEmail(email),
|
||||
subject: "TurnosXpress :: Bienvenido/a",
|
||||
message: `Hola ${firstName}, Gracias por registrarte en turnosXpress. Primero debes activar tu cuenta ingresando en ${signUpUrl} . Tu código de verificación es: ${verificationCode}`,
|
||||
templateId: "6a85dd644ea98ccfcd05bdc7",
|
||||
context: {
|
||||
username: firstName || cleanEmail(email),
|
||||
verificationcode: verificationCode,
|
||||
},
|
||||
});
|
||||
|
||||
return newUser;
|
||||
@@ -459,8 +482,11 @@ class UsersManager implements IUsersManager {
|
||||
|
||||
await NotificationsManager.sendEmail({
|
||||
email: cleanEmail(data.email),
|
||||
subject: "TurnosXpress :: Recuperación de cuenta",
|
||||
message: `Hola ${user.firstName}, Te enviamos un código de verificación para recuperar tu cuenta. Tu código de verificación es: ${code}. Ingresa https://turnosxpress.com.ar/landing/recover-account/verify para establecer una nueva clave`,
|
||||
templateId: "6a85c7ad96475f2825015277",
|
||||
context: {
|
||||
username: user.firstName || cleanEmail(data.email),
|
||||
verificationcode: code,
|
||||
},
|
||||
});
|
||||
|
||||
return;
|
||||
@@ -515,10 +541,16 @@ class UsersManager implements IUsersManager {
|
||||
throw new Error("El código de verificación es incorrecto");
|
||||
}
|
||||
|
||||
const wasVerificated = Boolean(userTest.verificated);
|
||||
|
||||
userTest.verificated = true;
|
||||
|
||||
await userTest.save();
|
||||
|
||||
if (!wasVerificated) {
|
||||
await this.sendWelcomeEmail(userTest.email, userTest.firstName);
|
||||
}
|
||||
|
||||
try {
|
||||
const freePlan = await PlansList.plans.findOne({ price: 0 });
|
||||
if (freePlan) {
|
||||
@@ -724,11 +756,17 @@ class UsersManager implements IUsersManager {
|
||||
});
|
||||
|
||||
if (userCheck) {
|
||||
const wasVerificated = Boolean(userCheck.verificated);
|
||||
|
||||
userCheck.external_id = googleUserId;
|
||||
userCheck.external_service = "google";
|
||||
userCheck.verificated = true;
|
||||
await userCheck.save();
|
||||
|
||||
if (!wasVerificated) {
|
||||
await this.sendWelcomeEmail(userCheck.email, userCheck.firstName);
|
||||
}
|
||||
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: userCheck.id,
|
||||
});
|
||||
@@ -770,6 +808,8 @@ class UsersManager implements IUsersManager {
|
||||
throw new Error("Error creating user");
|
||||
}
|
||||
|
||||
await this.sendWelcomeEmail(newUser.email, newUser.firstName);
|
||||
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: newUser.id,
|
||||
});
|
||||
@@ -821,11 +861,17 @@ class UsersManager implements IUsersManager {
|
||||
});
|
||||
|
||||
if (userCheck) {
|
||||
const wasVerificated = Boolean(userCheck.verificated);
|
||||
|
||||
userCheck.external_id = googleData.id;
|
||||
userCheck.external_service = "google";
|
||||
userCheck.verificated = true;
|
||||
await userCheck.save();
|
||||
|
||||
if (!wasVerificated) {
|
||||
await this.sendWelcomeEmail(userCheck.email, userCheck.firstName);
|
||||
}
|
||||
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: userCheck.id,
|
||||
});
|
||||
@@ -867,6 +913,8 @@ class UsersManager implements IUsersManager {
|
||||
throw new Error("Error creating user");
|
||||
}
|
||||
|
||||
await this.sendWelcomeEmail(newUser.email, newUser.firstName);
|
||||
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: newUser.id,
|
||||
});
|
||||
|
||||
@@ -55,6 +55,9 @@ export type PublicOrganizationView = {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
appointmentAlert: string;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
};
|
||||
|
||||
export type PublicOrganizationServiceViewParams = {
|
||||
@@ -163,6 +166,9 @@ class Views {
|
||||
services,
|
||||
employees: services,
|
||||
appointmentAlert: isNull<string>(company.appointmentAlert, ""),
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
CreateWapServerParams,
|
||||
FindWapServerParams,
|
||||
IWapServer,
|
||||
IWapServerAdapter,
|
||||
@@ -28,6 +29,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
|
||||
this.serverList = model<IWapServerDocument>("WapServer", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: CreateWapServerParams): Promise<IWapServer> {
|
||||
return await this.serverList.create(data);
|
||||
}
|
||||
|
||||
public async find(data: FindWapServerParams): Promise<IWapServer[]> {
|
||||
return this.serverList.find(data).exec();
|
||||
}
|
||||
@@ -36,6 +41,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
|
||||
return this.serverList.findOne(data).exec();
|
||||
}
|
||||
|
||||
public async delete(id: string): Promise<void> {
|
||||
await this.serverList.deleteOne({ _id: id });
|
||||
}
|
||||
|
||||
private buildSearchCriteria(filters: FindWapServerParams): FilterQuery<IWapServerDocument> {
|
||||
const searchCriteria: FilterQuery<IWapServerDocument> = {};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export type FindWapServerParams = {
|
||||
description?: string;
|
||||
countBots?: number;
|
||||
maxBots?: number;
|
||||
port?: number;
|
||||
active?: boolean;
|
||||
countBotsFrom?: number;
|
||||
countBotsTo?: number;
|
||||
@@ -100,9 +101,29 @@ export interface IWapServer {
|
||||
ipv6: string;
|
||||
countBots: number;
|
||||
maxBots: number;
|
||||
port: number;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export type UpdateWapServerParams = {
|
||||
serverId: string;
|
||||
name?: string;
|
||||
ipv4?: string;
|
||||
port?: number;
|
||||
maxBots?: number;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type CreateWapServerParams = {
|
||||
name: string;
|
||||
ipv4: string;
|
||||
port: number;
|
||||
maxBots: number;
|
||||
ipv6?: string;
|
||||
description?: string;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type PaginateWapServerParams = FindWapServerParams & {
|
||||
page: number;
|
||||
limit: number;
|
||||
@@ -114,13 +135,124 @@ export type PaginateWapServerResults = {
|
||||
pages: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerByIdParams = {
|
||||
serverId: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerAuditParams = SysAdminWapServerByIdParams;
|
||||
|
||||
export type SysAdminWapServerRecalculateCountParams = SysAdminWapServerByIdParams;
|
||||
|
||||
export type SysAdminDeleteWapServerParams = SysAdminWapServerByIdParams & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminDeleteWapServerResult = {
|
||||
serverId: string;
|
||||
deleted: true;
|
||||
force?: boolean;
|
||||
detachedOrganizations?: number;
|
||||
deletedRuntimeBots?: number;
|
||||
skippedRuntimeBots?: number;
|
||||
auditFailed?: boolean;
|
||||
auditMessage?: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerOrganizationActionParams = SysAdminWapServerByIdParams & {
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerQrResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
qr: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerDetachResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
botDeleted: boolean;
|
||||
botAlreadyMissing: boolean;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerDeleteBotResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
assignmentRemains: true;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapAssignedOrganization = {
|
||||
id: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapContainerDto = {
|
||||
id?: string;
|
||||
name?: string;
|
||||
organizationId?: string;
|
||||
image?: string;
|
||||
state?: string;
|
||||
status?: string;
|
||||
ports?: unknown[];
|
||||
created?: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerAuditResult = {
|
||||
serverId: string;
|
||||
assignedOrganizations: SysAdminWapAssignedOrganization[];
|
||||
detectedBots: SysAdminWapContainerDto[];
|
||||
validBots: SysAdminWapContainerDto[];
|
||||
ghostBots: SysAdminWapContainerDto[];
|
||||
missingBots: SysAdminWapAssignedOrganization[];
|
||||
expectedCountBots: number;
|
||||
storedCountBots: number;
|
||||
runtimeCountBots: number;
|
||||
countMismatch: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerRecalculateCountResult = {
|
||||
serverId: string;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminGetWapServerParams = PaginateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminCreateWapServerParams = CreateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminUpdateWapServerParams = UpdateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminAuditWapServerParams = SysAdminWapServerAuditParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminRecalculateWapServerCountParams = SysAdminWapServerRecalculateCountParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminDeleteWapServerRequest = SysAdminDeleteWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerOrganizationActionRequest = SysAdminWapServerOrganizationActionParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export interface IWapServerAdapter {
|
||||
create(data: CreateWapServerParams): Promise<IWapServer>;
|
||||
find(data: FindWapServerParams): Promise<IWapServer[]>;
|
||||
findOne(data: FindWapServerParams): Promise<IWapServerDocument | null>;
|
||||
delete(id: string): Promise<void>;
|
||||
paginate(filters: PaginateWapServerParams): Promise<PaginateWapServerResults>;
|
||||
}
|
||||
|
||||
@@ -140,4 +272,15 @@ export interface IWapServerManager {
|
||||
getQr(data: BotEventParams): Promise<string>;
|
||||
sendMessage(data: SendBotMessageParams): Promise<void>;
|
||||
sysAdminGetWapServers(data: PaginateWapServerParams): Promise<PaginateWapServerResults>;
|
||||
sysAdminCreateWapServer(data: CreateWapServerParams): Promise<IWapServer>;
|
||||
sysAdminUpdateWapServer(data: UpdateWapServerParams): Promise<IWapServer>;
|
||||
sysAdminAuditWapServer(data: SysAdminWapServerAuditParams): Promise<SysAdminWapServerAuditResult>;
|
||||
sysAdminRecalculateWapServerCount(data: SysAdminWapServerRecalculateCountParams): Promise<SysAdminWapServerRecalculateCountResult>;
|
||||
sysAdminDeleteWapServer(data: SysAdminDeleteWapServerParams): Promise<SysAdminDeleteWapServerResult>;
|
||||
sysAdminStartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminStopBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminRestartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminGetQr(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerQrResult>;
|
||||
sysAdminDeleteBot(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerDeleteBotResult>;
|
||||
sysAdminDetachOrganizationServer(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerDetachResult>;
|
||||
}
|
||||
|
||||
@@ -13,20 +13,39 @@ import {
|
||||
BotView,
|
||||
IWapServer,
|
||||
IWapServerManager,
|
||||
SysAdminDeleteWapServerParams,
|
||||
SysAdminDeleteWapServerResult,
|
||||
SysAdminWapContainerDto,
|
||||
SysAdminWapServerAuditParams,
|
||||
SysAdminWapServerAuditResult,
|
||||
SysAdminWapServerRecalculateCountParams,
|
||||
SysAdminWapServerRecalculateCountResult,
|
||||
SysAdminWapServerDetachResult,
|
||||
SysAdminWapServerDeleteBotResult,
|
||||
SysAdminWapServerOrganizationActionParams,
|
||||
SysAdminWapServerQrResult,
|
||||
SendBotMessageParams,
|
||||
ValidateBotEventStatus,
|
||||
BOT_STATE,
|
||||
SERVER_STATE,
|
||||
BOT_SESSION_STATUS,
|
||||
CreateWapServerParams,
|
||||
VALIDATE_BOT_ENVENT_ERRORS,
|
||||
PaginateWapServerResults,
|
||||
PaginateWapServerParams,
|
||||
UpdateWapServerParams,
|
||||
} from "./WapServer.Interface";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import { PlanFeatures } from "../Plans/Plans.interface";
|
||||
import axios, { AxiosError } from "axios";
|
||||
import { isNull } from "../../helpers/IsNull";
|
||||
|
||||
const BOT_ADMIN_ACTION_TIMEOUT_MS = 10000;
|
||||
const BOT_ADMIN_RESTART_STATUS_RETRIES = 5;
|
||||
const BOT_ADMIN_RESTART_STATUS_DELAY_MS = 1000;
|
||||
const MONGO_OBJECT_ID_REGEX = /^[a-fA-F0-9]{24}$/;
|
||||
const WAP_SERVER_METADATA_HOSTS = new Set(["169.254.169.254", "metadata.google.internal"]);
|
||||
|
||||
export interface CreateBotResult {
|
||||
organizationId: string;
|
||||
port: number;
|
||||
@@ -142,10 +161,259 @@ class WapServerManager implements IWapServerManager {
|
||||
return servidores;
|
||||
}
|
||||
|
||||
private normalizeBotAdminApiUrl(url: string): string {
|
||||
const rawUrl = String(url).trim();
|
||||
|
||||
if (!rawUrl) {
|
||||
throw new Error("URL is required");
|
||||
}
|
||||
|
||||
if (/\s|[\x00-\x1F\x7F]/.test(rawUrl)) {
|
||||
throw new Error("URL must not contain whitespace or control characters");
|
||||
}
|
||||
|
||||
const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(rawUrl);
|
||||
const normalizedInput = hasProtocol ? rawUrl : `http://${rawUrl}`;
|
||||
let parsedUrl: URL;
|
||||
|
||||
try {
|
||||
parsedUrl = new URL(normalizedInput);
|
||||
} catch (error) {
|
||||
throw new Error("URL must be a valid HTTP(S) origin");
|
||||
}
|
||||
|
||||
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
|
||||
throw new Error("URL protocol must be http or https");
|
||||
}
|
||||
|
||||
if (!parsedUrl.hostname) {
|
||||
throw new Error("URL host is required");
|
||||
}
|
||||
|
||||
if (parsedUrl.username || parsedUrl.password) {
|
||||
throw new Error("URL must not include credentials");
|
||||
}
|
||||
|
||||
const path = decodeURIComponent(parsedUrl.pathname);
|
||||
if ((parsedUrl.pathname && parsedUrl.pathname !== "/") || path.includes("..")) {
|
||||
throw new Error("URL path is not allowed; use only the origin");
|
||||
}
|
||||
|
||||
if (parsedUrl.search || parsedUrl.hash) {
|
||||
throw new Error("URL must not include query string or hash");
|
||||
}
|
||||
|
||||
if (WAP_SERVER_METADATA_HOSTS.has(parsedUrl.hostname.toLowerCase())) {
|
||||
throw new Error("URL host is not allowed");
|
||||
}
|
||||
|
||||
return `${parsedUrl.origin}/`;
|
||||
}
|
||||
|
||||
private getBotAdminApiUrl(url: string): string {
|
||||
//return `https://${url}:${process.env.DEFAULT_BOT_ADMIN_PORT}/`;
|
||||
//return `https://${url}/`;
|
||||
return url;
|
||||
return this.normalizeBotAdminApiUrl(url);
|
||||
}
|
||||
|
||||
private formatResponseBody(data: unknown): string {
|
||||
if (data === undefined || data === null) {
|
||||
return "empty body";
|
||||
}
|
||||
|
||||
const body = typeof data === "string" ? data : JSON.stringify(data);
|
||||
|
||||
return body.length > 1000 ? `${body.slice(0, 1000)}...` : body;
|
||||
}
|
||||
|
||||
private createBotAdminContainersError(error: unknown, targetUrl: string): Error {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data);
|
||||
const statusText = status ? `status ${status}` : error.code || "no response";
|
||||
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: ${statusText}; body: ${body}`);
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message) {
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: ${error.message}`);
|
||||
}
|
||||
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: unknown error`);
|
||||
}
|
||||
|
||||
private createBotAdminActionError(error: unknown, targetUrl: string): Error {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data);
|
||||
const statusText = status ? `status ${status}` : error.code || "no response";
|
||||
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: ${statusText}; body: ${body}`);
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message) {
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: ${error.message}`);
|
||||
}
|
||||
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: unknown error`);
|
||||
}
|
||||
|
||||
private isBotAdminMissingContainerError(error: unknown): boolean {
|
||||
if (!axios.isAxiosError(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data).toLowerCase();
|
||||
|
||||
// Be conservative: only allow detach to continue for explicit missing-container signals.
|
||||
return status === 404 || body.includes("not found") || body.includes("no such container");
|
||||
}
|
||||
|
||||
private async getSysAdminServerActionTarget(data: SysAdminWapServerOrganizationActionParams): Promise<{
|
||||
server: any;
|
||||
baseUrl: string;
|
||||
encodedOrganizationId: string;
|
||||
}> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!data.organizationId) {
|
||||
throw new Error("Organization id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.organizationId)) {
|
||||
throw new Error("Organization id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
return { server, baseUrl: this.getBotAdminApiUrl(server.ipv4), encodedOrganizationId: encodeURIComponent(data.organizationId) };
|
||||
}
|
||||
|
||||
private async postSysAdminBotAction(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
action: "start" | "stop",
|
||||
): Promise<void> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/${action}`;
|
||||
|
||||
try {
|
||||
const response = await axios.post(targetUrl, {}, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
const result: CreateBotResult = response.data;
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (error) {
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteSysAdminRuntimeBot(
|
||||
baseUrl: string,
|
||||
encodedOrganizationId: string,
|
||||
allowMissingContainer = false,
|
||||
): Promise<{ botDeleted: boolean; botAlreadyMissing: boolean }> {
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}`;
|
||||
|
||||
try {
|
||||
const response = await axios.delete(targetUrl, { timeout: BOT_ADMIN_ACTION_TIMEOUT_MS });
|
||||
const result: CreateBotResult = response.data;
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
return { botDeleted: true, botAlreadyMissing: false };
|
||||
} catch (error) {
|
||||
if (allowMissingContainer && this.isBotAdminMissingContainerError(error)) {
|
||||
return { botDeleted: false, botAlreadyMissing: true };
|
||||
}
|
||||
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForSysAdminBotStopped(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/status`;
|
||||
|
||||
for (let attempt = 0; attempt < BOT_ADMIN_RESTART_STATUS_RETRIES; attempt += 1) {
|
||||
try {
|
||||
const response = await axios.post(targetUrl, {}, { timeout: BOT_ADMIN_ACTION_TIMEOUT_MS });
|
||||
const status = String(response.data?.status || "").toLowerCase();
|
||||
|
||||
if (!status.includes("up")) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.status === 500) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, BOT_ADMIN_RESTART_STATUS_DELAY_MS));
|
||||
}
|
||||
|
||||
throw new Error("Bot did not stop before restart timeout; start was not attempted.");
|
||||
}
|
||||
|
||||
private extractOrganizationIdFromContainer(container: any): string | undefined {
|
||||
const names = Array.isArray(container?.Names) ? container.Names : [];
|
||||
|
||||
for (const rawName of names) {
|
||||
const name = String(rawName || "").replace(/^\//, "");
|
||||
const match = name.match(/^(.+)_bot_\d+$/);
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private sanitizeContainer(container: any): SysAdminWapContainerDto {
|
||||
const names = Array.isArray(container?.Names) ? container.Names : [];
|
||||
const firstName = names.length > 0 ? String(names[0]).replace(/^\//, "") : undefined;
|
||||
|
||||
return {
|
||||
id: container?.Id,
|
||||
name: firstName,
|
||||
organizationId: this.extractOrganizationIdFromContainer(container),
|
||||
image: container?.Image,
|
||||
state: container?.State,
|
||||
status: container?.Status,
|
||||
ports: Array.isArray(container?.Ports) ? container.Ports : [],
|
||||
created: container?.Created,
|
||||
};
|
||||
}
|
||||
|
||||
private async getSysAdminRuntimeContainers(server: any): Promise<SysAdminWapContainerDto[]> {
|
||||
const containersUrl = this.getBotAdminApiUrl(server.ipv4) + "containers";
|
||||
|
||||
try {
|
||||
const response = await axios.get(containersUrl, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
return Array.isArray(response.data)
|
||||
? response.data.map((container: any) => this.sanitizeContainer(container))
|
||||
: [];
|
||||
} catch (error) {
|
||||
throw this.createBotAdminContainersError(error, containersUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public async getAvailableServer(): Promise<IWapServer> {
|
||||
@@ -713,6 +981,345 @@ class WapServerManager implements IWapServerManager {
|
||||
|
||||
return servers;
|
||||
}
|
||||
|
||||
public async sysAdminCreateWapServer(data: CreateWapServerParams): Promise<IWapServer> {
|
||||
if (!data.name || !String(data.name).trim()) {
|
||||
throw new Error("Name is required");
|
||||
}
|
||||
|
||||
if (!data.ipv4 || !String(data.ipv4).trim()) {
|
||||
throw new Error("IPv4 is required");
|
||||
}
|
||||
|
||||
if (!Number.isFinite(data.port) || data.port < 0) {
|
||||
throw new Error("Port must be a finite non-negative number");
|
||||
}
|
||||
|
||||
if (!Number.isFinite(data.maxBots) || data.maxBots < 0) {
|
||||
throw new Error("Max bots must be a finite non-negative number");
|
||||
}
|
||||
|
||||
return await this.servers.create({
|
||||
name: String(data.name).trim(),
|
||||
description: data.description ? String(data.description).trim() : "",
|
||||
ipv4: this.normalizeBotAdminApiUrl(data.ipv4),
|
||||
ipv6: data.ipv6 ? String(data.ipv6).trim() : "",
|
||||
countBots: 0,
|
||||
port: data.port,
|
||||
maxBots: data.maxBots,
|
||||
active: data.active === undefined ? true : Boolean(data.active),
|
||||
} as CreateWapServerParams & { countBots: number });
|
||||
}
|
||||
|
||||
public async sysAdminUpdateWapServer(data: UpdateWapServerParams): Promise<IWapServer> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
if (data.name !== undefined) {
|
||||
server.name = String(data.name).trim();
|
||||
}
|
||||
|
||||
if (data.ipv4 !== undefined) {
|
||||
server.ipv4 = this.normalizeBotAdminApiUrl(data.ipv4);
|
||||
}
|
||||
|
||||
if (data.port !== undefined) {
|
||||
if (!Number.isFinite(data.port) || data.port < 0) {
|
||||
throw new Error("Port must be a finite non-negative number");
|
||||
}
|
||||
|
||||
server.port = data.port;
|
||||
}
|
||||
|
||||
if (data.maxBots !== undefined) {
|
||||
if (!Number.isFinite(data.maxBots) || data.maxBots < 0) {
|
||||
throw new Error("Max bots must be a finite non-negative number");
|
||||
}
|
||||
|
||||
server.maxBots = data.maxBots;
|
||||
}
|
||||
|
||||
if (data.active !== undefined) {
|
||||
server.active = Boolean(data.active);
|
||||
}
|
||||
|
||||
await server.save();
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
public async sysAdminAuditWapServer(data: SysAdminWapServerAuditParams): Promise<SysAdminWapServerAuditResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const assignedOrganizations = assignedCompanies.map((company: any) => ({
|
||||
id: String(company.id || company._id),
|
||||
name: company.name,
|
||||
}));
|
||||
const assignedIds = new Set(assignedOrganizations.map((organization) => organization.id));
|
||||
|
||||
const detectedBots = await this.getSysAdminRuntimeContainers(server);
|
||||
const runtimeOrganizationIds = new Set(
|
||||
detectedBots
|
||||
.map((container) => container.organizationId)
|
||||
.filter((organizationId): organizationId is string => Boolean(organizationId)),
|
||||
);
|
||||
|
||||
const validBots = detectedBots.filter(
|
||||
(container) => container.organizationId && assignedIds.has(container.organizationId),
|
||||
);
|
||||
const ghostBots = detectedBots.filter(
|
||||
(container) => !container.organizationId || !assignedIds.has(container.organizationId),
|
||||
);
|
||||
const missingBots = assignedOrganizations.filter(
|
||||
(organization) => !runtimeOrganizationIds.has(organization.id),
|
||||
);
|
||||
const expectedCountBots = assignedOrganizations.length;
|
||||
const storedCountBots = server.countBots ?? 0;
|
||||
const runtimeCountBots = detectedBots.length;
|
||||
|
||||
return {
|
||||
serverId: String(server.id || server._id),
|
||||
assignedOrganizations,
|
||||
detectedBots,
|
||||
validBots,
|
||||
ghostBots,
|
||||
missingBots,
|
||||
expectedCountBots,
|
||||
storedCountBots,
|
||||
runtimeCountBots,
|
||||
countMismatch: storedCountBots !== expectedCountBots || runtimeCountBots !== expectedCountBots,
|
||||
};
|
||||
}
|
||||
|
||||
public async sysAdminRecalculateWapServerCount(
|
||||
data: SysAdminWapServerRecalculateCountParams,
|
||||
): Promise<SysAdminWapServerRecalculateCountResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const before = server.countBots;
|
||||
const after = assignedCompanies.length;
|
||||
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: String(server.id || server._id), before, after };
|
||||
}
|
||||
|
||||
public async sysAdminDeleteWapServer(data: SysAdminDeleteWapServerParams): Promise<SysAdminDeleteWapServerResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const force = data.force === true;
|
||||
|
||||
if (!force && server.active) {
|
||||
throw new Error("WAP server must be inactive before deletion");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
|
||||
if (!force && assignedCompanies.length > 0) {
|
||||
throw new Error(`WAP server cannot be deleted because it has ${assignedCompanies.length} associated bot(s) in DB`);
|
||||
}
|
||||
|
||||
let detectedBots: SysAdminWapContainerDto[] = [];
|
||||
let auditFailed = false;
|
||||
let auditMessage: string | undefined;
|
||||
|
||||
try {
|
||||
detectedBots = await this.getSysAdminRuntimeContainers(server);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : "unknown error";
|
||||
|
||||
if (!force) {
|
||||
throw new Error(`WAP server cannot be deleted because bot-admin could not be audited. Verify runtime bots manually before deleting. ${message}`);
|
||||
}
|
||||
|
||||
auditFailed = true;
|
||||
auditMessage = message;
|
||||
}
|
||||
|
||||
if (!force && detectedBots.length > 0) {
|
||||
throw new Error(`WAP server cannot be deleted because bot-admin detected ${detectedBots.length} runtime bot(s)`);
|
||||
}
|
||||
|
||||
let deletedRuntimeBots = 0;
|
||||
let skippedRuntimeBots = 0;
|
||||
|
||||
if (force) {
|
||||
const baseUrl = this.getBotAdminApiUrl(server.ipv4);
|
||||
|
||||
for (const bot of detectedBots) {
|
||||
if (!bot.organizationId) {
|
||||
skippedRuntimeBots += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.deleteSysAdminRuntimeBot(baseUrl, encodeURIComponent(bot.organizationId), true);
|
||||
|
||||
if (result.botDeleted) {
|
||||
deletedRuntimeBots += 1;
|
||||
}
|
||||
} catch (_error) {
|
||||
skippedRuntimeBots += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (const company of assignedCompanies) {
|
||||
const companyDocument = company as typeof company & { save: () => Promise<unknown> };
|
||||
|
||||
companyDocument.wapServerId = undefined;
|
||||
await companyDocument.save();
|
||||
}
|
||||
}
|
||||
|
||||
await this.servers.delete(data.serverId);
|
||||
|
||||
return {
|
||||
serverId: data.serverId,
|
||||
deleted: true,
|
||||
...(force
|
||||
? {
|
||||
force: true,
|
||||
detachedOrganizations: assignedCompanies.length,
|
||||
deletedRuntimeBots,
|
||||
skippedRuntimeBots,
|
||||
...(auditFailed ? { auditFailed: true, auditMessage } : {}),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
public async sysAdminStartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "start");
|
||||
}
|
||||
|
||||
public async sysAdminStopBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "stop");
|
||||
}
|
||||
|
||||
public async sysAdminRestartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "stop");
|
||||
await this.waitForSysAdminBotStopped(data);
|
||||
|
||||
try {
|
||||
await this.postSysAdminBotAction(data, "start");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : "unknown error";
|
||||
|
||||
throw new Error(`Bot restart stopped the bot, but start failed. The bot may be stopped. ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async sysAdminGetQr(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerQrResult> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/qr`;
|
||||
|
||||
try {
|
||||
const response = await axios.get(targetUrl, {
|
||||
responseType: "arraybuffer",
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
const qr = Buffer.from(response.data, "binary").toString("base64");
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, qr };
|
||||
} catch (error) {
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public async sysAdminDeleteBot(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDeleteBotResult> {
|
||||
const { server, baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const before = server.countBots ?? 0;
|
||||
|
||||
await this.deleteSysAdminRuntimeBot(baseUrl, encodedOrganizationId);
|
||||
|
||||
// Deleting the runtime bot intentionally keeps the DB assignment; detach is a separate sysadmin action.
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const after = assignedCompanies.length;
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, assignmentRemains: true, before, after };
|
||||
}
|
||||
|
||||
public async sysAdminDetachOrganizationServer(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDetachResult> {
|
||||
const { server, baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const company = await CompaniesManager.companies.findOne({ _id: data.organizationId });
|
||||
|
||||
if (!company) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
|
||||
if (String(company.wapServerId || "") !== data.serverId) {
|
||||
throw new Error("Organization is not assigned to this WAP server");
|
||||
}
|
||||
|
||||
const before = server.countBots ?? 0;
|
||||
const deleteResult = await this.deleteSysAdminRuntimeBot(baseUrl, encodedOrganizationId, true);
|
||||
|
||||
company.wapServerId = undefined;
|
||||
await company.save();
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const after = assignedCompanies.length;
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, ...deleteResult, before, after };
|
||||
}
|
||||
}
|
||||
|
||||
const WapServerList = new WapServerManager();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import {
|
||||
CollaboratorScheduleDetailsParams,
|
||||
CollaboratorScheduleDetailsView,
|
||||
} from "../../Models/AdminAssistant/AdminAssistant.Interface";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { AdminAssistantService } from "./AdminAssistant.Service";
|
||||
|
||||
@Route("admin-assistant/collaborator-schedule-details")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class GetCollaboratorScheduleDetailsController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async getCollaboratorScheduleDetails(
|
||||
@Body() requestBody: CollaboratorScheduleDetailsParams
|
||||
): Promise<CollaboratorScheduleDetailsView | ApiValidationError> {
|
||||
try {
|
||||
const details = await new AdminAssistantService().getCollaboratorScheduleDetails(requestBody);
|
||||
this.setStatus(200);
|
||||
return details;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { connect } from "mongoose";
|
||||
import AdminAssistantList from "../../Models/AdminAssistant/AdminAssistant";
|
||||
import {
|
||||
CollaboratorScheduleDetailsParams,
|
||||
CollaboratorScheduleDetailsView,
|
||||
} from "../../Models/AdminAssistant/AdminAssistant.Interface";
|
||||
|
||||
export class AdminAssistantService {
|
||||
public async getCollaboratorScheduleDetails(
|
||||
data: CollaboratorScheduleDetailsParams
|
||||
): Promise<CollaboratorScheduleDetailsView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
return await AdminAssistantList.getCollaboratorScheduleDetails(data);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
AppointmentNotificationPreviewParams,
|
||||
AppointmentNotificationPreviewResult,
|
||||
DeleteAppointmentParams,
|
||||
FindAppointmentsParams,
|
||||
FindAppointmentSchedulesParams,
|
||||
@@ -368,6 +370,27 @@ export class CreateImmediateAppointmentNotificationJobsController extends Contro
|
||||
}
|
||||
}
|
||||
|
||||
@Route("appointments/notification-preview")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class AppointmentNotificationPreviewController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async getAppointmentNotificationPreview(
|
||||
@Body() requestBody: AppointmentNotificationPreviewParams
|
||||
): Promise<AppointmentNotificationPreviewResult | ApiValidationError> {
|
||||
try {
|
||||
const preview = await new AppointmentService().getAppointmentNotificationPreview(requestBody);
|
||||
this.setStatus(200);
|
||||
return preview;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error; console.error("GET EVENT ERROR:", errorOccurred);
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("appointments/apply-discount")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ApplyAppointmentDiscountContrnoller extends Controller {
|
||||
|
||||
@@ -2,6 +2,8 @@ import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import AppointmentList from "../../Models/Appointments/Appointments";
|
||||
import {
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
AppointmentNotificationPreviewParams,
|
||||
AppointmentNotificationPreviewResult,
|
||||
AppointmentAdminByClientView,
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
@@ -167,6 +169,11 @@ export class AppointmentService {
|
||||
await AppointmentList.createImmediateNotificationJobs(data);
|
||||
}
|
||||
|
||||
public async getAppointmentNotificationPreview(data: AppointmentNotificationPreviewParams): Promise<AppointmentNotificationPreviewResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return AppointmentList.getAppointmentNotificationPreview(data);
|
||||
}
|
||||
|
||||
public async applyDiscount(data: ApplyAppointmentDiscountParams): Promise<void> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
await AppointmentList.applyDiscount(data);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ArcaActivitiesService, FilterArcaActivitiesParams } from "./ArcaActivities.Service";
|
||||
|
||||
@Route("arca-activities/filter-all")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaActivitiesFilterAllController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async allArcaActivities(
|
||||
@Body() requestBody: FilterArcaActivitiesParams
|
||||
): Promise<TextObjectFilterResult[] | ApiValidationError> {
|
||||
try {
|
||||
const activities = await new ArcaActivitiesService().textObjectFilter(requestBody);
|
||||
this.setStatus(200);
|
||||
return activities;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import { filterArcaActivities } from "../../Models/ArcaActivities/ArcaActivities.Catalog";
|
||||
|
||||
export type FilterArcaActivitiesParams = {
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export class ArcaActivitiesService {
|
||||
public async textObjectFilter(data: FilterArcaActivitiesParams): Promise<TextObjectFilterResult[]> {
|
||||
return filterArcaActivities(data.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import {
|
||||
ArcaCredentialView,
|
||||
ArcaWsfeDiagnosticsParams,
|
||||
ArcaWsfeDiagnosticsResult,
|
||||
ArcaWsfeLastVoucherParams,
|
||||
ArcaWsfeLastVoucherResult,
|
||||
ArcaWsaaLoginTestResult,
|
||||
FindArcaCredentialsParams,
|
||||
GenerateArcaCredentialCsrParams,
|
||||
TestArcaWsaaLoginParams,
|
||||
UploadArcaCredentialCertificateParams,
|
||||
} from "../../Models/ArcaCredentials/ArcaCredentials.Interface";
|
||||
import { ArcaCredentialsService } from "./ArcaCredentials.Service";
|
||||
|
||||
@Route("arca-credentials/generate-csr")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsGenerateCsrController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async generateCsr(
|
||||
@Body() requestBody: GenerateArcaCredentialCsrParams
|
||||
): Promise<ArcaCredentialView | ApiValidationError> {
|
||||
try {
|
||||
const credential = await new ArcaCredentialsService().generateCsr(requestBody);
|
||||
this.setStatus(200);
|
||||
return credential;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("arca-credentials/upload-certificate")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsUploadCertificateController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async uploadCertificate(
|
||||
@Body() requestBody: UploadArcaCredentialCertificateParams
|
||||
): Promise<ArcaCredentialView | ApiValidationError> {
|
||||
try {
|
||||
const credential = await new ArcaCredentialsService().uploadCertificate(requestBody);
|
||||
this.setStatus(200);
|
||||
return credential;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("arca-credentials/test-wsaa-login")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsTestWsaaLoginController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async testWsaaLogin(
|
||||
@Body() requestBody: TestArcaWsaaLoginParams
|
||||
): Promise<ArcaWsaaLoginTestResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new ArcaCredentialsService().testWsaaLogin(requestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("arca-credentials/wsfe-last-voucher")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsWsfeLastVoucherController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async getWsfeLastVoucher(
|
||||
@Body() requestBody: ArcaWsfeLastVoucherParams
|
||||
): Promise<ArcaWsfeLastVoucherResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new ArcaCredentialsService().getWsfeLastVoucher(requestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("arca-credentials/wsfe-diagnostics")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsWsfeDiagnosticsController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async getWsfeDiagnostics(
|
||||
@Body() requestBody: ArcaWsfeDiagnosticsParams
|
||||
): Promise<ArcaWsfeDiagnosticsResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new ArcaCredentialsService().getWsfeDiagnostics(requestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("arca-credentials/find")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ArcaCredentialsFindController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async find(
|
||||
@Body() requestBody: FindArcaCredentialsParams
|
||||
): Promise<ArcaCredentialView[] | ApiValidationError> {
|
||||
try {
|
||||
const credentials = await new ArcaCredentialsService().find(requestBody);
|
||||
this.setStatus(200);
|
||||
return credentials;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { connect } from "mongoose";
|
||||
import ArcaCredentials from "../../Models/ArcaCredentials/ArcaCredentials";
|
||||
import {
|
||||
ArcaCredentialView,
|
||||
ArcaWsfeDiagnosticsParams,
|
||||
ArcaWsfeDiagnosticsResult,
|
||||
ArcaWsfeLastVoucherParams,
|
||||
ArcaWsfeLastVoucherResult,
|
||||
ArcaWsaaLoginTestResult,
|
||||
FindArcaCredentialsParams,
|
||||
GenerateArcaCredentialCsrParams,
|
||||
TestArcaWsaaLoginParams,
|
||||
UploadArcaCredentialCertificateParams,
|
||||
} from "../../Models/ArcaCredentials/ArcaCredentials.Interface";
|
||||
|
||||
export class ArcaCredentialsService {
|
||||
public async generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.generateCsr(data);
|
||||
}
|
||||
|
||||
public async uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.uploadCertificate(data);
|
||||
}
|
||||
|
||||
public async testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.testWsaaLogin(data);
|
||||
}
|
||||
|
||||
public async getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.getWsfeLastVoucher(data);
|
||||
}
|
||||
|
||||
public async getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.getWsfeDiagnostics(data);
|
||||
}
|
||||
|
||||
public async find(data: FindArcaCredentialsParams): Promise<ArcaCredentialView[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await ArcaCredentials.find(data);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
PaginateEmployeesResults,
|
||||
ValidateEmployeeParams,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
UpdateEmployeeParams,
|
||||
@@ -117,6 +120,46 @@ export class GetEmployeesByCompanyController extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/public-by-company")
|
||||
export class GetPublicEmployeesByCompanyController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async findPublicByCompanyId(
|
||||
@Body() requestBody: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[] | ApiValidationError> {
|
||||
try {
|
||||
const employees = await new EmployeesService().findPublicByCompanyId(requestBody);
|
||||
this.setStatus(200);
|
||||
return employees;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/public-by-id")
|
||||
export class GetPublicEmployeeByIdController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async findPublicByEmployeeId(
|
||||
@Body() requestBody: FindPublicEmployeeParams
|
||||
): Promise<PublicEmployeeView | ApiValidationError> {
|
||||
try {
|
||||
const employee = await new EmployeesService().findPublicByEmployeeId(requestBody);
|
||||
this.setStatus(200);
|
||||
return employee;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/get-by-id")
|
||||
export class GetEmployeesByIdController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
PaginateEmployeesParams,
|
||||
PaginateEmployeesResults,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
UpdateEmployeeParams,
|
||||
@@ -60,6 +63,24 @@ export class EmployeesService {
|
||||
return employees;
|
||||
}
|
||||
|
||||
public async findPublicByCompanyId(
|
||||
data: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
const employees = await EmployeesList.findPublicByCompanyId(data);
|
||||
|
||||
return employees;
|
||||
}
|
||||
|
||||
public async findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
const employee = await EmployeesList.findPublicByEmployeeId(data);
|
||||
|
||||
return employee;
|
||||
}
|
||||
|
||||
public async findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import {
|
||||
CreateInvoiceFromCashMovementParams,
|
||||
FindInvoicesParams,
|
||||
IInvoice,
|
||||
} from "../../Models/Invoices/Invoices.Interface";
|
||||
import { InvoicesService } from "./Invoices.Service";
|
||||
|
||||
@Route("invoices/create-from-cash-movement")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class InvoicesCreateFromCashMovementController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async createFromCashMovement(
|
||||
@Body() requestBody: CreateInvoiceFromCashMovementParams
|
||||
): Promise<IInvoice | ApiValidationError> {
|
||||
try {
|
||||
const invoice = await new InvoicesService().createFromCashMovement(requestBody);
|
||||
this.setStatus(200);
|
||||
return invoice;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("invoices/find")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class InvoicesFindController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async find(@Body() requestBody: FindInvoicesParams): Promise<IInvoice[] | ApiValidationError> {
|
||||
try {
|
||||
const invoices = await new InvoicesService().find(requestBody);
|
||||
this.setStatus(200);
|
||||
return invoices;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { connect } from "mongoose";
|
||||
import Invoices from "../../Models/Invoices/Invoices";
|
||||
import {
|
||||
CreateInvoiceFromCashMovementParams,
|
||||
FindInvoicesParams,
|
||||
IInvoice,
|
||||
} from "../../Models/Invoices/Invoices.Interface";
|
||||
|
||||
export class InvoicesService {
|
||||
public async createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await Invoices.createFromCashMovement(data);
|
||||
}
|
||||
|
||||
public async find(data: FindInvoicesParams): Promise<IInvoice[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await Invoices.find(data);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ import dayjs from "dayjs";
|
||||
import PlanPaymentsList from "../../Models/PlanPayments/PlanPayments";
|
||||
import { IPlanSuscriptionDocument } from "../../Models/PlanSubscriptions/PlanSubscriptions.Adapter.Mongoose";
|
||||
import { VerifyPendingPlanPaymentResponse } from "../../Models/PlanSubscriptions/PlanSubscriptions.interface";
|
||||
import PlansList from "../../Models/Plans/Plans";
|
||||
import UserList from "../../Models/Users/Users";
|
||||
import { NotificationsManager } from "../../Models/Notifications/Notifications";
|
||||
|
||||
type MercadoPagoPaymentData = {
|
||||
id: string | number;
|
||||
@@ -41,6 +44,66 @@ type MercadoPagoPaymentVerification = {
|
||||
const REJECTED_PAYMENT_STATUSES = ["rejected", "cancelled", "failed"];
|
||||
|
||||
export class MercadoPagoWebhookService {
|
||||
private formatTemplateDate(date: Date): string {
|
||||
return new Intl.DateTimeFormat("es-AR", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
private formatTemplateAmount(amount: number): string {
|
||||
return new Intl.NumberFormat("es-AR", {
|
||||
style: "currency",
|
||||
currency: "ARS",
|
||||
}).format(amount);
|
||||
}
|
||||
|
||||
private async sendApprovedPaidPlanEmail(
|
||||
subscription: IPlanSuscriptionDocument,
|
||||
paymentData: MercadoPagoPaymentData,
|
||||
userId: string,
|
||||
approvedAt: Date,
|
||||
periodStart: Date
|
||||
): Promise<void> {
|
||||
try {
|
||||
const plan = await PlansList.findOne({ _id: String(subscription.planId) });
|
||||
|
||||
if (plan.price <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await UserList.users.findOne({ _id: userId });
|
||||
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
await NotificationsManager.sendEmail({
|
||||
email: user.email,
|
||||
templateId: "6a85ebb1323720a53d0cfd3f",
|
||||
context: {
|
||||
username: user.firstName || user.email,
|
||||
nombre_plan: plan.name,
|
||||
importe: this.formatTemplateAmount(paymentData.transaction_amount || 0),
|
||||
fecha_pago: this.formatTemplateDate(approvedAt),
|
||||
periodo_desde: this.formatTemplateDate(periodStart),
|
||||
periodo_hasta: this.formatTemplateDate(subscription.endDate),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (axios.isAxiosError(e)) {
|
||||
console.error("Error enviando email de pago de plan aprobado:", {
|
||||
status: e.response?.status,
|
||||
data: e.response?.data,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.error("Error enviando email de pago de plan aprobado:", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async handleWebhook(body: any): Promise<void> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
@@ -300,6 +363,9 @@ export class MercadoPagoWebhookService {
|
||||
const periodStart = isExtensionPayment && dayjs(subscription.endDate).isAfter(approvedAt)
|
||||
? subscription.endDate
|
||||
: approvedAt;
|
||||
const transactionId = String(paymentData.id);
|
||||
const existingPayments = await PlanPaymentsList.find({ transactionId });
|
||||
const shouldSendApprovedPaymentEmail = existingPayments.length === 0;
|
||||
|
||||
if (isUpgradePayment && subscription.pendingPaymentPlanId) {
|
||||
subscription.planId = subscription.pendingPaymentPlanId;
|
||||
@@ -342,8 +408,12 @@ export class MercadoPagoWebhookService {
|
||||
paymentDate: approvedAt,
|
||||
paymentMethod: paymentData.payment_method_id || paymentData.payment_type_id || "mercadopago",
|
||||
status: "completed",
|
||||
transactionId: String(paymentData.id),
|
||||
transactionId,
|
||||
});
|
||||
|
||||
if (shouldSendApprovedPaymentEmail) {
|
||||
await this.sendApprovedPaidPlanEmail(subscription, paymentData, userId, approvedAt, periodStart);
|
||||
}
|
||||
}
|
||||
|
||||
private async applyRejectedPayment(
|
||||
|
||||
@@ -7,8 +7,10 @@ import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||
interface SendEmailByContentParams {
|
||||
systemToken: string;
|
||||
email: string;
|
||||
subject: string;
|
||||
message: string;
|
||||
subject?: string;
|
||||
message?: string;
|
||||
templateId?: string;
|
||||
context?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface SendWapByContentParams {
|
||||
@@ -29,6 +31,8 @@ export class SendEmailByContentController extends Controller {
|
||||
email: requestBody.email,
|
||||
subject: requestBody.subject,
|
||||
message: requestBody.message,
|
||||
templateId: requestBody.templateId,
|
||||
context: requestBody.context,
|
||||
});
|
||||
|
||||
this.setStatus(200);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import {
|
||||
FindOrganizationFiscalProfilesParams,
|
||||
IOrganizationFiscalProfile,
|
||||
UpsertOrganizationFiscalProfileParams,
|
||||
} from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
|
||||
import { OrganizationFiscalProfilesService } from "./OrganizationFiscalProfiles.Service";
|
||||
|
||||
@Route("organization-fiscal-profiles/upsert")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class OrganizationFiscalProfilesUpsertController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async upsert(
|
||||
@Body() requestBody: UpsertOrganizationFiscalProfileParams
|
||||
): Promise<IOrganizationFiscalProfile | ApiValidationError> {
|
||||
try {
|
||||
const profile = await new OrganizationFiscalProfilesService().upsert(requestBody);
|
||||
this.setStatus(200);
|
||||
return profile;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("organization-fiscal-profiles/find")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class OrganizationFiscalProfilesFindController extends Controller {
|
||||
@SuccessResponse(200, "Done")
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@Post()
|
||||
public async find(
|
||||
@Body() requestBody: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfile[] | ApiValidationError> {
|
||||
try {
|
||||
const profiles = await new OrganizationFiscalProfilesService().find(requestBody);
|
||||
this.setStatus(200);
|
||||
return profiles;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { connect } from "mongoose";
|
||||
import OrganizationFiscalProfiles from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles";
|
||||
import {
|
||||
FindOrganizationFiscalProfilesParams,
|
||||
IOrganizationFiscalProfile,
|
||||
UpsertOrganizationFiscalProfileParams,
|
||||
} from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
|
||||
|
||||
export class OrganizationFiscalProfilesService {
|
||||
public async upsert(
|
||||
data: UpsertOrganizationFiscalProfileParams
|
||||
): Promise<IOrganizationFiscalProfile> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await OrganizationFiscalProfiles.upsert(data);
|
||||
}
|
||||
|
||||
public async find(
|
||||
data: FindOrganizationFiscalProfilesParams
|
||||
): Promise<IOrganizationFiscalProfile[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await OrganizationFiscalProfiles.find(data);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user