Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c77d479344 | |||
| 0a285776c7 | |||
| f39ba44f59 | |||
| ece3879c8d | |||
| 68d98e8b40 | |||
| dc020d94d2 | |||
| 20b0363767 | |||
| 6c75929e21 | |||
| e6662aac18 | |||
| 4029566063 | |||
| 3988e328eb | |||
| dd3e07311d | |||
| 279e1b54cc | |||
| da3c3abb52 | |||
| 383a5bc6b4 |
@@ -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.
|
||||
@@ -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: 12 KiB |
Binary file not shown.
@@ -529,9 +529,10 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String((newAppointment as any)._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (newAppointment.id) {
|
||||
if (notification && newAppointment.id) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
@@ -574,7 +575,6 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//Envio la notificacion al profesional.
|
||||
await NotificationsManager.sendSystemNotification({
|
||||
@@ -2240,13 +2240,7 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
const systemSubject = `Turno reservado en ${data.companyName}`;
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "creation",
|
||||
appointmentStart: data.appointmentStart,
|
||||
payload: {
|
||||
const payload = {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
@@ -2258,7 +2252,22 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
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.jobService.createReminderJobs({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "reminder",
|
||||
appointmentStart: data.appointmentStart,
|
||||
reminderPayload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -67,6 +67,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 +500,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 +616,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 +682,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 +742,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 +815,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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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,140 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
} from "../../Models/Ratings/Ratings.Interface";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ratingRateLimiter } from "../../middleware/ratelimiter";
|
||||
import { RatingsService } from "./Ratings.Service";
|
||||
|
||||
@Route("ratings/create")
|
||||
@Middlewares([ratingRateLimiter, authenticateMiddleware])
|
||||
export class CreateRatingController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Calificación creada con éxito")
|
||||
@Post()
|
||||
public async createRating(@Body() requestBody: CreateRatingParams): Promise<ApiVoidResult | ApiValidationError> {
|
||||
try {
|
||||
await new RatingsService().createRating(requestBody);
|
||||
this.setStatus(200);
|
||||
return { message: "Done", success: true };
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/pending-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class PendingRatingsByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async pendingByUser(
|
||||
@Body() requestBody: PendingRatingsByUserParams
|
||||
): Promise<PendingRatingItem[] | ApiValidationError> {
|
||||
try {
|
||||
const pendingRatings = await new RatingsService().pendingByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return pendingRatings;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/count-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class CountRatingsByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async countByUser(
|
||||
@Body() requestBody: CountRatingsByUserParams
|
||||
): Promise<CountRatingsByUserResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingsCount = await new RatingsService().countByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingsCount;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/professional-summary-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class ProfessionalRatingSummaryByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async professionalSummaryByUser(
|
||||
@Body() requestBody: ProfessionalRatingSummaryByUserParams
|
||||
): Promise<RatingTargetSummaryResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingSummary = await new RatingsService().professionalSummaryByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingSummary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/target-summary")
|
||||
export class RatingTargetSummaryController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async summaryByTarget(
|
||||
@Body() requestBody: RatingTargetSummaryParams
|
||||
): Promise<RatingTargetSummaryResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingSummary = await new RatingsService().summaryByTarget(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingSummary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/target-reviews")
|
||||
export class RatingTargetReviewsController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async reviewsByTarget(
|
||||
@Body() requestBody: RatingTargetReviewsParams
|
||||
): Promise<RatingTargetReviewsResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingReviews = await new RatingsService().reviewsByTarget(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingReviews;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { connect } from "mongoose";
|
||||
import RatingsList from "../../Models/Ratings/Ratings";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
IRating,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
} from "../../Models/Ratings/Ratings.Interface";
|
||||
|
||||
export class RatingsService {
|
||||
public async createRating(data: CreateRatingParams): Promise<IRating> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.createRating(data);
|
||||
}
|
||||
|
||||
public async pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.pendingByUser(data);
|
||||
}
|
||||
|
||||
public async countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.countByUser(data);
|
||||
}
|
||||
|
||||
public async professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.professionalSummaryByUser(data);
|
||||
}
|
||||
|
||||
public async summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.summaryByTarget(data);
|
||||
}
|
||||
|
||||
public async reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.reviewsByTarget(data);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import {
|
||||
CreateSchedulesEnabledParams,
|
||||
DeleteSchedulesEnabledParams,
|
||||
EnableScheduleParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
FindSchedulesEnabledParams,
|
||||
ISchedulesEnabled,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
SchedulesEnabledView,
|
||||
} from "../../Models/SchedulesEnabled/SchedulesEnabled.Interface";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
@@ -150,3 +153,45 @@ export class DisableSchedulesEnabledController extends Controller {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("schedules-enabled/reservation-periods/summary")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ReservationPeriodsSummaryController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async summarizeReservationPeriods(
|
||||
@Body() requestBody: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary | ApiValidationError> {
|
||||
try {
|
||||
const summary = await new SchedulesEnabledService().summarizeReservationPeriods(requestBody);
|
||||
this.setStatus(200);
|
||||
return summary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("schedules-enabled/reservation-periods/extend")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ExtendReservationPeriodsController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async extendReservationPeriods(
|
||||
@Body() requestBody: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary | ApiValidationError> {
|
||||
try {
|
||||
const summary = await new SchedulesEnabledService().extendReservationPeriods(requestBody);
|
||||
this.setStatus(200);
|
||||
return summary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
FindSchedulesEnabledParams,
|
||||
SchedulesEnabledView,
|
||||
EnableScheduleParams,
|
||||
ReservationPeriodsSummaryParams,
|
||||
ReservationPeriodsSummary,
|
||||
ExtendReservationPeriodsParams,
|
||||
} from "../../Models/SchedulesEnabled/SchedulesEnabled.Interface";
|
||||
|
||||
export class SchedulesEnabledService {
|
||||
@@ -52,4 +55,18 @@ export class SchedulesEnabledService {
|
||||
|
||||
return schedulesEnabled;
|
||||
}
|
||||
|
||||
public async summarizeReservationPeriods(
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return SchedulesEnabledList.summarizeReservationPeriods(data);
|
||||
}
|
||||
|
||||
public async extendReservationPeriods(
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return SchedulesEnabledList.extendReservationPeriods(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,13 +46,6 @@ app.use(
|
||||
|
||||
app.use(json());
|
||||
|
||||
app.use((req, _res, next) => {
|
||||
if (req.path === '/companies/create') {
|
||||
require('fs').writeFileSync('request_log.json', JSON.stringify({ body: req.body, headers: req.headers }, null, 2));
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
RegisterRoutes(app);
|
||||
|
||||
app.use(function errorHandler(
|
||||
|
||||
@@ -2,6 +2,10 @@ import { Request, Response, NextFunction } from "express";
|
||||
import { ApiValidationError } from "../Models/Server.Error.model";
|
||||
|
||||
const ipLastRequest = new Map<string, number>();
|
||||
const ratingIpRequests = new Map<string, number[]>();
|
||||
|
||||
const RATING_RATE_LIMIT_WINDOW_MS = 60000;
|
||||
const RATING_RATE_LIMIT_MAX_REQUESTS = 20;
|
||||
|
||||
// Limpia las IPs cada hora
|
||||
setInterval(() => {
|
||||
@@ -10,6 +14,14 @@ setInterval(() => {
|
||||
ipLastRequest.forEach((time, ip) => {
|
||||
if (now - time > timeLimit) ipLastRequest.delete(ip);
|
||||
});
|
||||
ratingIpRequests.forEach((times, ip) => {
|
||||
const recentTimes = times.filter((time) => now - time <= RATING_RATE_LIMIT_WINDOW_MS);
|
||||
if (recentTimes.length === 0) {
|
||||
ratingIpRequests.delete(ip);
|
||||
return;
|
||||
}
|
||||
ratingIpRequests.set(ip, recentTimes);
|
||||
});
|
||||
}, 3600000);
|
||||
|
||||
export async function rateLimiter(
|
||||
@@ -31,3 +43,25 @@ export async function rateLimiter(
|
||||
ipLastRequest.set(ip, currentTime);
|
||||
next();
|
||||
}
|
||||
|
||||
export async function ratingRateLimiter(
|
||||
request: Request,
|
||||
response: Response,
|
||||
next: NextFunction
|
||||
): Promise<void | Response | ApiValidationError> {
|
||||
const ip = request.ip;
|
||||
const currentTime = Date.now();
|
||||
const windowStart = currentTime - RATING_RATE_LIMIT_WINDOW_MS;
|
||||
const recentRequests = (ratingIpRequests.get(ip) || []).filter((time) => time > windowStart);
|
||||
|
||||
if (recentRequests.length >= RATING_RATE_LIMIT_MAX_REQUESTS) {
|
||||
response
|
||||
.status(429)
|
||||
.json(new ApiValidationError(429, "Demasiadas solicitudes. Por favor espere!"));
|
||||
return;
|
||||
}
|
||||
|
||||
recentRequests.push(currentTime);
|
||||
ratingIpRequests.set(ip, recentRequests);
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ export interface MyOranizationsView {
|
||||
templateEmailCancellationId: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
}
|
||||
|
||||
export type CreateCompanyParams = {
|
||||
@@ -93,6 +96,9 @@ export type UpdateCompanyParams = {
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type DeleteCompanyParams = {
|
||||
@@ -158,6 +164,9 @@ export interface ICompany {
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export type PublicOrganizationViewParams = {
|
||||
@@ -184,6 +193,9 @@ export type PublicOrganizationView = {
|
||||
longitude: number;
|
||||
appointmentAlert: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
};
|
||||
|
||||
export type SetNotificationAutoParams = {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
export type PublicCompanyEmployeeView = {
|
||||
employeeId: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
|
||||
export type FindPublicCompanyEmployeesParams = {
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
export type FindPublicEmployeeParams = {
|
||||
employeeId: string;
|
||||
};
|
||||
|
||||
export type PublicEmployeeView = {
|
||||
employeeId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
export enum RatingTargetType {
|
||||
COMPANY = "company",
|
||||
SERVICE = "service",
|
||||
EMPLOYEE = "employee",
|
||||
}
|
||||
|
||||
export const RATING_COMMENT_MAX_LENGTH = 1000;
|
||||
|
||||
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: string;
|
||||
author: {
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsResult = {
|
||||
reviews: RatingTargetReviewItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export interface PendingRatingItem {
|
||||
appointmentId: string;
|
||||
appointmentDate: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
targetName: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
serviceName: string;
|
||||
}
|
||||
@@ -18,6 +18,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: string | null;
|
||||
daysRemaining: number | null;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummary = {
|
||||
companyId: string;
|
||||
status: "missing" | "expired" | "near-ending" | "open";
|
||||
worstDaysRemaining: number | null;
|
||||
currentOpenUntil: string | null;
|
||||
nearEndingThresholdDays: number;
|
||||
employees: ReservationPeriodEmployeeSummary[];
|
||||
};
|
||||
|
||||
export interface SchedulesEnabledView {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
|
||||
@@ -13,12 +13,26 @@ export class ApiValidationError implements IServerError {
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends ApiValidationError {
|
||||
export class ApiError extends Error implements IServerError {
|
||||
readonly code: number;
|
||||
readonly desc: string;
|
||||
|
||||
constructor(code: number, desc: string) {
|
||||
super(code, desc);
|
||||
const message = desc || "No pudimos completar la operación.";
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.code = code;
|
||||
this.desc = message;
|
||||
}
|
||||
|
||||
format = (): string => {
|
||||
return `Atención: ${this.desc}`;
|
||||
};
|
||||
|
||||
toJSON = () => ({
|
||||
name: this.name,
|
||||
code: this.code,
|
||||
desc: this.desc,
|
||||
message: this.message,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ export type CreateServiceParams = {
|
||||
originalPrice: number;
|
||||
limit: number;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type UpdateServiceParams = {
|
||||
@@ -36,6 +38,8 @@ export type UpdateServiceParams = {
|
||||
fontColor?: string;
|
||||
fontShadowColor?: string;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type PaginateServicesParams = {
|
||||
@@ -110,6 +114,8 @@ export interface PublicServiceView {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface PublicOrganizationServiceView {
|
||||
@@ -132,6 +138,8 @@ export interface IService {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
}
|
||||
|
||||
export interface CompanyServiceView {
|
||||
@@ -153,4 +161,6 @@ export interface CompanyServiceView {
|
||||
fontShadowColor: string;
|
||||
published: SERVICE_PUBLISHED_STATUS;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,26 @@ import { ApiError } from "@models/Server.Error.model";
|
||||
import axios from "@config/axios.config";
|
||||
|
||||
class ApiService {
|
||||
private normalizeError(error: unknown): ApiError {
|
||||
if (error && typeof error === "object" && "response" in error) {
|
||||
const response = (error as { response?: { data?: any; status?: number } }).response;
|
||||
const data = response?.data;
|
||||
|
||||
if (data) {
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data) || "No pudimos completar la operación.";
|
||||
return new ApiError(data.code || response?.status || 500, msg);
|
||||
}
|
||||
|
||||
return new ApiError(response?.status || 500, "No pudimos comunicarnos con el servidor.");
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ApiError(500, error.message);
|
||||
}
|
||||
|
||||
return new ApiError(500, "No pudimos comunicarnos con el servidor.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a HTTP POST request to the specified endpoint with the provided data
|
||||
* and returns a promise that resolves to the response data.
|
||||
@@ -19,14 +39,7 @@ class ApiService {
|
||||
resolve(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
try {
|
||||
const data = error.response.data;
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
||||
reject(new ApiError(data.code || error.response.status || 500, msg));
|
||||
} catch {
|
||||
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
||||
reject(new ApiError(500, errorMessage));
|
||||
}
|
||||
reject(this.normalizeError(error));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -44,16 +57,7 @@ class ApiService {
|
||||
resolve(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
try {
|
||||
console.error("Full API Error:", error.response?.data);
|
||||
const data = error.response.data;
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
||||
reject(new ApiError(data.code || error.response.status || 500, msg));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
||||
reject(new ApiError(500, errorMessage));
|
||||
}
|
||||
reject(this.normalizeError(error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ApiError } from "@core/Models/Server.Error.model";
|
||||
import {
|
||||
FindPublicCompanyEmployeesParams,
|
||||
FindPublicEmployeeParams,
|
||||
PublicCompanyEmployeeView,
|
||||
PublicEmployeeView,
|
||||
} from "@core/Models/Employees.model";
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import * as Yup from "yup";
|
||||
|
||||
const schemaFindPublicCompanyEmployees = Yup.object().shape({
|
||||
companyId: Yup.string().required("No se ha proporcionado la organización."),
|
||||
});
|
||||
|
||||
const schemaFindPublicEmployee = Yup.object().shape({
|
||||
employeeId: Yup.string().required("No se ha proporcionado el profesional."),
|
||||
});
|
||||
|
||||
export const findPublicCompanyEmployees = async (
|
||||
data: FindPublicCompanyEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> => {
|
||||
return new Promise<PublicCompanyEmployeeView[]>((resolve, reject) => {
|
||||
schemaFindPublicCompanyEmployees
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PublicCompanyEmployeeView[]>("employees/public-by-company", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const findPublicEmployee = async (
|
||||
data: FindPublicEmployeeParams
|
||||
): Promise<PublicEmployeeView> => {
|
||||
return new Promise<PublicEmployeeView>((resolve, reject) => {
|
||||
schemaFindPublicEmployee
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PublicEmployeeView>("employees/public-by-id", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import { ApiVoidResult } from "@core/Models/Api.VoidResult.type";
|
||||
import { ApiError } from "@core/Models/Server.Error.model";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "@core/Models/Ratings.model";
|
||||
import * as Yup from "yup";
|
||||
|
||||
const schemaPendingRatingsByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tus calificaciones pendientes debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaCountRatingsByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tus opiniones realizadas debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaProfessionalRatingSummaryByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tu puntaje profesional debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaCreateRating = Yup.object().shape({
|
||||
appointmentId: Yup.string().required("No se ha proporcionado el turno."),
|
||||
targetType: Yup.string()
|
||||
.oneOf(Object.values(RatingTargetType), "El tipo de calificación no es válido.")
|
||||
.required("No se ha proporcionado el tipo de calificación."),
|
||||
targetId: Yup.string().required("No se ha proporcionado el item a calificar."),
|
||||
score: Yup.number().integer().min(1).max(5).required("Selecciona una calificación."),
|
||||
comment: Yup.string().max(RATING_COMMENT_MAX_LENGTH, `El comentario no puede superar los ${RATING_COMMENT_MAX_LENGTH} caracteres.`),
|
||||
sessionUser: Yup.string().required("Para calificar debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaRatingTargetSummary = Yup.object().shape({
|
||||
targetType: Yup.string()
|
||||
.oneOf(Object.values(RatingTargetType), "El tipo de calificación no es válido.")
|
||||
.required("No se ha proporcionado el tipo de calificación."),
|
||||
targetId: Yup.string().required("No se ha proporcionado el item calificado."),
|
||||
});
|
||||
|
||||
const schemaRatingTargetReviews = schemaRatingTargetSummary.shape({
|
||||
page: Yup.number().integer().min(1),
|
||||
pageSize: Yup.number().integer().min(1).max(20),
|
||||
limit: Yup.number().integer().min(1).max(20),
|
||||
});
|
||||
|
||||
export const pendingRatingsByUser = async (data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> => {
|
||||
return new Promise<PendingRatingItem[]>((resolve, reject) => {
|
||||
schemaPendingRatingsByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PendingRatingItem[]>("ratings/pending-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const countRatingsByUser = async (data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> => {
|
||||
return new Promise<CountRatingsByUserResult>((resolve, reject) => {
|
||||
schemaCountRatingsByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<CountRatingsByUserResult>("ratings/count-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const professionalRatingSummaryByUser = async (
|
||||
data: ProfessionalRatingSummaryByUserParams
|
||||
): Promise<RatingTargetSummaryResult> => {
|
||||
return new Promise<RatingTargetSummaryResult>((resolve, reject) => {
|
||||
schemaProfessionalRatingSummaryByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetSummaryResult>("ratings/professional-summary-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const createRating = async (data: CreateRatingParams): Promise<ApiVoidResult> => {
|
||||
return new Promise<ApiVoidResult>((resolve, reject) => {
|
||||
schemaCreateRating
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<ApiVoidResult>("ratings/create", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const ratingTargetSummary = async (data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> => {
|
||||
return new Promise<RatingTargetSummaryResult>((resolve, reject) => {
|
||||
schemaRatingTargetSummary
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetSummaryResult>("ratings/target-summary", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const ratingTargetReviews = async (data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> => {
|
||||
return new Promise<RatingTargetReviewsResult>((resolve, reject) => {
|
||||
schemaRatingTargetReviews
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetReviewsResult>("ratings/target-reviews", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -8,7 +8,10 @@ import { ApiVoidResult } from "@models/Api.VoidResult.type";
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import {
|
||||
EnableScheduleParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
FindSchedulesEnabledParams,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
SchedulesEnabledView,
|
||||
} from "@models/SchedulesEnabled.type";
|
||||
import {
|
||||
@@ -56,6 +59,18 @@ export const disableSchedule = async (data: EnableScheduleParams): Promise<ApiVo
|
||||
return ApiRequest.post<ApiVoidResult>("schedules-enabled/disable", data);
|
||||
};
|
||||
|
||||
export const summarizeReservationPeriods = async (
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> => {
|
||||
return ApiRequest.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/summary", data);
|
||||
};
|
||||
|
||||
export const extendReservationPeriods = async (
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> => {
|
||||
return ApiRequest.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/extend", data);
|
||||
};
|
||||
|
||||
export const uploadHeaderImage = async (data: FormData): Promise<ApiVoidResult> => {
|
||||
return ApiRequest.postFile<ApiVoidResult>("companies/upload-header", data);
|
||||
};
|
||||
|
||||
@@ -11,12 +11,14 @@ import OrgConfigIcon from "@mui/icons-material/SettingsOutlined";
|
||||
import Textbox from "@components/Textbox/Textbox";
|
||||
import TextPhone from "@components/TextPhone/TextPhone";
|
||||
import MaterialAlert from "@mui/material/Alert";
|
||||
import Checkbox from "@mui/material/Checkbox";
|
||||
import * as Yup from "yup";
|
||||
import {
|
||||
loadOrganizationsById,
|
||||
savePublishedStatus,
|
||||
updateOrganizationsById,
|
||||
} from "../Org.Service";
|
||||
import { loadServicesByCompany, updateService } from "../services/Services.Service";
|
||||
import {
|
||||
COMPANY_PUBLISHED_STATUS,
|
||||
MyOranizationsView,
|
||||
@@ -35,6 +37,7 @@ import { useConfirmStore } from "@core/Store/Confirm.Store";
|
||||
import Switch from "@core/app/components/Switch/Switch";
|
||||
import { FindTemplatesParams } from "@core/Models/Templates.model";
|
||||
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
|
||||
import { CompanyServiceView } from "@models/Service.model";
|
||||
|
||||
type UrlData = {
|
||||
id: string;
|
||||
@@ -57,6 +60,14 @@ export default function OrganizationEdit() {
|
||||
const [cancellationTime, setCancellationTime] = useState("");
|
||||
const [appointmentAlert, setAppointmentAlert] = useState("");
|
||||
const [orgSlug, setOrgSlug] = useState("");
|
||||
const [showPublicScores, setShowPublicScores] = useState(true);
|
||||
const [showPublicOpinions, setShowPublicOpinions] = useState(true);
|
||||
const [showPublicProfessionals, setShowPublicProfessionals] = useState(true);
|
||||
const [servicesShowPublicScores, setServicesShowPublicScores] = useState(true);
|
||||
const [servicesShowPublicOpinions, setServicesShowPublicOpinions] = useState(true);
|
||||
const [originalServicesShowPublicScores, setOriginalServicesShowPublicScores] = useState(true);
|
||||
const [originalServicesShowPublicOpinions, setOriginalServicesShowPublicOpinions] = useState(true);
|
||||
const [services, setServices] = useState<CompanyServiceView[]>([]);
|
||||
|
||||
const [orgPublished, setOrgPublished] = useState<COMPANY_PUBLISHED_STATUS | undefined>(
|
||||
undefined
|
||||
@@ -65,6 +76,8 @@ export default function OrganizationEdit() {
|
||||
const [savePublishedStatusAvailable, setSavePublishedStatusAvailable] = useState(false);
|
||||
|
||||
const [combosLoaded, setCombosLoaded] = useState<boolean>(false);
|
||||
const ownerSubscription = SessionInfo.organizationSubscriptions[id];
|
||||
const canEditPublicVisibilityFlags = (ownerSubscription?.plan.price || 0) > 0;
|
||||
|
||||
const [categoryFilterContent] = useState<TextObjectModalContent>({
|
||||
header: (
|
||||
@@ -210,28 +223,53 @@ export default function OrganizationEdit() {
|
||||
useEffect(() => {
|
||||
if (combosLoaded) {
|
||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||
loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId })
|
||||
.then((response: MyOranizationsView) => {
|
||||
setOrgName(response.name);
|
||||
setOrgDescription(response.description);
|
||||
setHeatMapFraction(response.heatMapFraction.toString());
|
||||
setAppointmentTime(response.appointmentTime.toString());
|
||||
setCancellationTime(response.cancellationTime.toString());
|
||||
setAppointmentAlert(response.appointmentAlert);
|
||||
setAreaCode(response.phoneAreaCode);
|
||||
setPhone(response.phoneNumber);
|
||||
setCategoryId(response.categoryId.toString());
|
||||
setOrgSlug(getSlug(response.name));
|
||||
setOrgPublished(response.published);
|
||||
Promise.all([
|
||||
loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId }),
|
||||
loadServicesByCompany(id),
|
||||
])
|
||||
.then((response) => {
|
||||
const [organization, loadedServices] = response;
|
||||
|
||||
setOrgName(organization.name);
|
||||
setOrgDescription(organization.description);
|
||||
setHeatMapFraction(organization.heatMapFraction.toString());
|
||||
setAppointmentTime(organization.appointmentTime.toString());
|
||||
setCancellationTime(organization.cancellationTime.toString());
|
||||
setAppointmentAlert(organization.appointmentAlert);
|
||||
setAreaCode(organization.phoneAreaCode);
|
||||
setPhone(organization.phoneNumber);
|
||||
setCategoryId(organization.categoryId.toString());
|
||||
setOrgSlug(getSlug(organization.name));
|
||||
setOrgPublished(organization.published);
|
||||
setShowPublicScores(organization.showPublicScores !== undefined ? organization.showPublicScores : true);
|
||||
setShowPublicOpinions(organization.showPublicOpinions !== undefined ? organization.showPublicOpinions : true);
|
||||
setShowPublicProfessionals(
|
||||
organization.showPublicProfessionals !== undefined
|
||||
? organization.showPublicProfessionals
|
||||
: true
|
||||
);
|
||||
setServices(loadedServices);
|
||||
setServicesShowPublicScores(
|
||||
loadedServices.every((service) => service.showPublicScores !== false)
|
||||
);
|
||||
setServicesShowPublicOpinions(
|
||||
loadedServices.every((service) => service.showPublicOpinions !== false)
|
||||
);
|
||||
setOriginalServicesShowPublicScores(
|
||||
loadedServices.every((service) => service.showPublicScores !== false)
|
||||
);
|
||||
setOriginalServicesShowPublicOpinions(
|
||||
loadedServices.every((service) => service.showPublicOpinions !== false)
|
||||
);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTemplateWapNotifId(response.templateWapNotifId);
|
||||
setTemplateWapAltaId(response.templateWapAltaId);
|
||||
setTemplateWapCancellationId(response.templateWapCancellationId);
|
||||
setTemplateWapNotifId(organization.templateWapNotifId);
|
||||
setTemplateWapAltaId(organization.templateWapAltaId);
|
||||
setTemplateWapCancellationId(organization.templateWapCancellationId);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
alert.showError(error.format());
|
||||
.catch((error: ApiError | Error) => {
|
||||
alert.showError(error instanceof ApiError ? error.format() : error.message);
|
||||
})
|
||||
.finally(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -270,6 +308,13 @@ export default function OrganizationEdit() {
|
||||
templateWapNotifId: templateWapNotifId === "" ? undefined : templateWapNotifId,
|
||||
templateWapAltaId: templateWapAltaId === "" ? undefined : templateWapAltaId,
|
||||
templateWapCancellationId: templateWapCancellationId === "" ? undefined : templateWapCancellationId,
|
||||
...(canEditPublicVisibilityFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
showPublicProfessionals,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
const schema = Yup.object().shape({
|
||||
@@ -335,10 +380,61 @@ export default function OrganizationEdit() {
|
||||
.then(() => {
|
||||
updateOrganizationsById(data)
|
||||
.then(() => {
|
||||
alert.showSuccess("Organizacion actualizada!");
|
||||
const servicesShowPublicScoresChanged =
|
||||
originalServicesShowPublicScores !== servicesShowPublicScores;
|
||||
const servicesShowPublicOpinionsChanged =
|
||||
originalServicesShowPublicOpinions !== servicesShowPublicOpinions;
|
||||
const changedServices =
|
||||
canEditPublicVisibilityFlags &&
|
||||
(servicesShowPublicScoresChanged || servicesShowPublicOpinionsChanged)
|
||||
? services
|
||||
: [];
|
||||
|
||||
return Promise.all(
|
||||
changedServices.map((service) =>
|
||||
updateService({
|
||||
id: service.id,
|
||||
companyId: id,
|
||||
name: service.name,
|
||||
description: service.description,
|
||||
originalPrice: service.originalPrice,
|
||||
limit: service.limit,
|
||||
length: service.length,
|
||||
color: service.color,
|
||||
fontColor: service.fontColor,
|
||||
fontShadowColor: service.fontShadowColor,
|
||||
sessionUser: SessionInfo.userId,
|
||||
showPublicScores: servicesShowPublicScoresChanged
|
||||
? servicesShowPublicScores
|
||||
: service.showPublicScores !== undefined
|
||||
? service.showPublicScores
|
||||
: true,
|
||||
showPublicOpinions: servicesShowPublicOpinionsChanged
|
||||
? servicesShowPublicOpinions
|
||||
: service.showPublicOpinions !== undefined
|
||||
? service.showPublicOpinions
|
||||
: true,
|
||||
})
|
||||
.catch((error: ApiError) => {
|
||||
alert.showError(error.format());
|
||||
)
|
||||
).then(() => {
|
||||
const updatedServices = services.map((service) => ({
|
||||
...service,
|
||||
showPublicScores: servicesShowPublicScoresChanged
|
||||
? servicesShowPublicScores
|
||||
: service.showPublicScores,
|
||||
showPublicOpinions: servicesShowPublicOpinionsChanged
|
||||
? servicesShowPublicOpinions
|
||||
: service.showPublicOpinions,
|
||||
}));
|
||||
|
||||
setServices(updatedServices);
|
||||
setOriginalServicesShowPublicScores(servicesShowPublicScores);
|
||||
setOriginalServicesShowPublicOpinions(servicesShowPublicOpinions);
|
||||
alert.showSuccess("Organizacion actualizada!");
|
||||
});
|
||||
})
|
||||
.catch((error: ApiError | Error) => {
|
||||
alert.showError(error instanceof ApiError ? error.format() : error.message);
|
||||
})
|
||||
.finally(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -484,6 +580,99 @@ export default function OrganizationEdit() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública:</b> Elegí si querés mostrar puntuaciones, opiniones y profesionales en el perfil público y las páginas de reserva. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<MaterialAlert severity="warning" sx={{ marginTop: "10px" }}>
|
||||
Para modificar las opciones de visibilidad pública de opiniones, puntuaciones y profesionales de esta organización y sus servicios, el propietario de la organización necesita un plan pago.
|
||||
</MaterialAlert>
|
||||
)}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "10px" }}>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicScores}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicScores(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicOpinions}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicOpinions(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicProfessionals}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicProfessionals(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar profesionales en el perfil público
|
||||
</label>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Disponible para planes pagos.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{services.length > 0 && (
|
||||
<>
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública de servicios:</b> Configurá si se muestran puntuaciones y opiniones en todos los servicios. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "10px",
|
||||
marginTop: "10px",
|
||||
}}
|
||||
>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={servicesShowPublicScores}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setServicesShowPublicScores(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas de los servicios
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={servicesShowPublicOpinions}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setServicesShowPublicOpinions(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas de los servicios
|
||||
</label>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Para cambiar la visibilidad pública de los servicios necesitás un plan pago.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TextObjectFilter
|
||||
placeholder="Categoría"
|
||||
content={categoryFilterContent}
|
||||
|
||||
@@ -12,14 +12,12 @@ import { disableSchedule, enableSchedule, loadSchedulesEnabled } from "../Org.Se
|
||||
import WeekInput from "@core/app/components/WeekInput/WeekInput";
|
||||
import dayjs from "dayjs";
|
||||
import "dayjs/locale/es";
|
||||
import weekday from "dayjs/plugin/weekday";
|
||||
import "dayjs/locale/es";
|
||||
import { SchedulesEnabledView } from "@models/SchedulesEnabled.type";
|
||||
import Avatar from "@components/Avatar/Avatar";
|
||||
import Button from "@core/app/components/Button/Button";
|
||||
import { useConfirmStore } from "@core/Store/Confirm.Store";
|
||||
import { getMondayWeekStart } from "@core/helpers/week";
|
||||
|
||||
dayjs.extend(weekday);
|
||||
dayjs.locale("es");
|
||||
|
||||
type UrlData = {
|
||||
@@ -34,7 +32,7 @@ export default function Schedules() {
|
||||
const SessionInfo = useSessionStore();
|
||||
const alert = useAlert();
|
||||
const confirm = useConfirmStore();
|
||||
const [startDate, setStartDate] = useState<dayjs.Dayjs>(dayjs().weekday(0));
|
||||
const [startDate, setStartDate] = useState<dayjs.Dayjs>(getMondayWeekStart());
|
||||
const [collaborators, setCollaborators] = useState<SchedulesEnabledView[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+51
@@ -72,6 +72,8 @@ export default function OrganizationService() {
|
||||
const [serviceColor, setServiceColor] = useState("");
|
||||
const [serviceFontColor, setServiceFontColor] = useState("");
|
||||
const [serviceFontShadowColor, setServiceFontShadowColor] = useState("");
|
||||
const [showPublicScores, setShowPublicScores] = useState(true);
|
||||
const [showPublicOpinions, setShowPublicOpinions] = useState(true);
|
||||
|
||||
const [serviceDiscountType, setServiceDiscountType] = useState<string | undefined>(undefined);
|
||||
const [serviceDiscountValue, setServiceDiscountValue] = useState<number | undefined>(undefined);
|
||||
@@ -116,6 +118,8 @@ export default function OrganizationService() {
|
||||
|
||||
const [discountsFilterData, setDiscountsFilterData] = useState<TextObjectFilterResult[]>([]);
|
||||
const [discountId, setDiscountId] = useState<string>("");
|
||||
const ownerSubscription = SessionInfo.organizationSubscriptions[id];
|
||||
const canEditPublicRatingFlags = (ownerSubscription?.plan.price || 0) > 0;
|
||||
|
||||
useEffect(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -200,6 +204,12 @@ export default function OrganizationService() {
|
||||
limit: parseInt(serviceLimit),
|
||||
length: parseInt(serviceLength),
|
||||
sessionUser: SessionInfo.userId,
|
||||
...(canEditPublicRatingFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.then(() => {
|
||||
alert.showSuccess("Servicio creado");
|
||||
@@ -225,6 +235,12 @@ export default function OrganizationService() {
|
||||
fontColor: serviceFontColor,
|
||||
fontShadowColor: serviceFontShadowColor,
|
||||
sessionUser: SessionInfo.userId,
|
||||
...(canEditPublicRatingFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.then(() => {
|
||||
alert.showSuccess("Servicio Actualizado");
|
||||
@@ -255,6 +271,8 @@ export default function OrganizationService() {
|
||||
setServiceDiscountType(response.discountType);
|
||||
setServiceDiscountValue(response.discountValue);
|
||||
setServiceDiscountName(response.discountName);
|
||||
setShowPublicScores(response.showPublicScores !== undefined ? response.showPublicScores : true);
|
||||
setShowPublicOpinions(response.showPublicOpinions !== undefined ? response.showPublicOpinions : true);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
@@ -486,6 +504,39 @@ export default function OrganizationService() {
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública:</b> Elegí si querés mostrar puntuaciones y opiniones de este servicio en páginas públicas. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "10px" }}>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Switch
|
||||
checked={showPublicScores}
|
||||
disabled={!canEditPublicRatingFlags}
|
||||
onChange={(checked) => {
|
||||
setShowPublicScores(checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Switch
|
||||
checked={showPublicOpinions}
|
||||
disabled={!canEditPublicRatingFlags}
|
||||
onChange={(checked) => {
|
||||
setShowPublicOpinions(checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas
|
||||
</label>
|
||||
{!canEditPublicRatingFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Disponible para planes pagos.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Textbox
|
||||
name="servicePrice"
|
||||
placeholder="Precio del servicio"
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useNavigation } from "@hooks/goto";
|
||||
import { useAlert } from "@core/Store/Alert.Store";
|
||||
import currency from "currency.js";
|
||||
import { getServiceImage } from "@core/helpers/getServiceImage";
|
||||
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
|
||||
|
||||
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
|
||||
import Dialog from "@mui/material/Dialog";
|
||||
@@ -113,6 +114,7 @@ export default function Org() {
|
||||
<div className={style.serviceInfo}>
|
||||
<h1>{data.name}</h1>
|
||||
<p>{data.description}</p>
|
||||
<ServiceRatingSummary serviceId={data.id} variant="row" showOpinionCount={false} />
|
||||
</div>
|
||||
<div className={style.serviceActions}>
|
||||
<span className={style.servicePrice}>{formatPrice(data.price)}</span>
|
||||
|
||||
@@ -85,6 +85,10 @@ export default function OrganizationEdit() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (wapView?.botSession === "ok") {
|
||||
return;
|
||||
}
|
||||
|
||||
wapServerBotGetQR({
|
||||
companyId: id,
|
||||
sessionUser: SessionInfo.userId,
|
||||
|
||||
@@ -15,7 +15,12 @@ import EventRepeatIcon from "@mui/icons-material/EventRepeat";
|
||||
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
|
||||
import ColorLensIcon from '@mui/icons-material/ColorLens';
|
||||
import PinDropIcon from '@mui/icons-material/PinDrop';
|
||||
import ReviewsIcon from '@mui/icons-material/Reviews';
|
||||
import NotificationsIcon from '@mui/icons-material/Notifications';
|
||||
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
|
||||
import QrCode2Icon from '@mui/icons-material/QrCode2';
|
||||
import API from "@services/Api.Service";
|
||||
import { ReservationPeriodsSummary } from "@models/SchedulesEnabled.type";
|
||||
|
||||
|
||||
type FlowDefinition = {
|
||||
@@ -65,6 +70,42 @@ const AVAILABLE_FLOWS: FlowDefinition[] = [
|
||||
keywords: ["telefono", "contacto", "email", "whatsapp", "redes", "celular"],
|
||||
icon: AddCircleOutlineIcon
|
||||
},
|
||||
{
|
||||
id: "public-visibility",
|
||||
flowId: "public-visibility",
|
||||
title: "Visibilidad Pública",
|
||||
description: "Configura opiniones, puntuaciones y profesionales visibles para tus clientes.",
|
||||
category: "Negocio",
|
||||
keywords: ["opiniones", "puntuaciones", "calificaciones", "profesionales", "visibilidad", "reseñas", "publico"],
|
||||
icon: ReviewsIcon
|
||||
},
|
||||
{
|
||||
id: "public-link",
|
||||
flowId: "public-link",
|
||||
title: "Link Público y QR",
|
||||
description: "Obtén el enlace público de tu organización y un código QR para compartirlo.",
|
||||
category: "Negocio",
|
||||
keywords: ["link", "enlace", "url", "slug", "qr", "codigo qr", "publico", "reservas"],
|
||||
icon: QrCode2Icon
|
||||
},
|
||||
{
|
||||
id: "notifications",
|
||||
flowId: "notifications",
|
||||
title: "Notificaciones",
|
||||
description: "Configura canales de notificación, recordatorios y horario silencioso para la organización o un cliente.",
|
||||
category: "Comunicación",
|
||||
keywords: ["notificaciones", "canales", "whatsapp", "email", "sistema", "recordatorio", "silencioso", "cliente"],
|
||||
icon: NotificationsIcon
|
||||
},
|
||||
{
|
||||
id: "whatsapp-bot",
|
||||
flowId: "whatsapp-bot",
|
||||
title: "WhatsApp",
|
||||
description: "Configura tu bot de WhatsApp para enviar notificaciones automáticas a tus clientes.",
|
||||
category: "Comunicación",
|
||||
keywords: ["whatsapp", "bot", "notificaciones", "wap", "mensajes", "automatico", "qr"],
|
||||
icon: WhatsAppIcon
|
||||
},
|
||||
{
|
||||
id: "new-service",
|
||||
flowId: "onboarding-service&action=new-service",
|
||||
@@ -83,6 +124,15 @@ const AVAILABLE_FLOWS: FlowDefinition[] = [
|
||||
keywords: ["horarios", "disponibilidad", "semana", "apertura", "cierre", "jornada"],
|
||||
icon: CalendarMonthIcon
|
||||
},
|
||||
{
|
||||
id: "open-reservation-periods",
|
||||
flowId: "open-reservation-periods",
|
||||
title: "Extender Reservas",
|
||||
description: "Abrir más semanas para que tus clientes puedan reservar turnos.",
|
||||
category: "Horarios",
|
||||
keywords: ["reservas", "periodo", "agenda", "extender", "habilitar", "semanas"],
|
||||
icon: EventBusyIcon
|
||||
},
|
||||
{
|
||||
id: "override-schedule",
|
||||
flowId: "override-schedule",
|
||||
@@ -125,6 +175,7 @@ export default function AssistantHome() {
|
||||
|
||||
const [incompleteOrgs, setIncompleteOrgs] = React.useState<IncompleteOrgData[]>([]);
|
||||
const [incompleteCollaborators, setIncompleteCollaborators] = React.useState<any[]>([]);
|
||||
const [reservationPeriodAlerts, setReservationPeriodAlerts] = React.useState<Array<{ org: any; summary: ReservationPeriodsSummary }>>([]);
|
||||
const [isLoadingFlow, setIsLoadingFlow] = React.useState(true);
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
|
||||
@@ -134,9 +185,25 @@ export default function AssistantHome() {
|
||||
const response = await API.post<any[]>("companies/get-by-user", { sessionUser: SessionInfo.userId });
|
||||
const orgs = response || [];
|
||||
const newIncompleteOrgs: IncompleteOrgData[] = [];
|
||||
const reservationAlerts: Array<{ org: any; summary: ReservationPeriodsSummary }> = [];
|
||||
|
||||
if (orgs.length > 0) {
|
||||
for (const org of orgs) {
|
||||
if (org.isAdmin) {
|
||||
try {
|
||||
const summary = await API.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/summary", {
|
||||
companyId: org.id || org._id,
|
||||
sessionUser: SessionInfo.userId
|
||||
});
|
||||
|
||||
if (summary && summary.status !== "open") {
|
||||
reservationAlerts.push({ org, summary });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error checking reservation periods", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (org.onboardingCompleted) continue;
|
||||
|
||||
const isNameMissing = !org.name || org.name.trim() === "";
|
||||
@@ -199,6 +266,7 @@ export default function AssistantHome() {
|
||||
}
|
||||
|
||||
setIncompleteOrgs(newIncompleteOrgs);
|
||||
setReservationPeriodAlerts(reservationAlerts);
|
||||
} else {
|
||||
setIncompleteOrgs([{
|
||||
org: null,
|
||||
@@ -206,6 +274,7 @@ export default function AssistantHome() {
|
||||
currentStepName: "Detalles del Negocio",
|
||||
flowToTrigger: "onboarding-org"
|
||||
}]);
|
||||
setReservationPeriodAlerts([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching organizations:", error);
|
||||
@@ -215,6 +284,7 @@ export default function AssistantHome() {
|
||||
currentStepName: "Detalles del Negocio",
|
||||
flowToTrigger: "onboarding-org"
|
||||
}]);
|
||||
setReservationPeriodAlerts([]);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -233,7 +303,7 @@ export default function AssistantHome() {
|
||||
}, [SessionInfo.metrics, SessionInfo.userId, router]);
|
||||
|
||||
const isSetupIncomplete = () => {
|
||||
return incompleteOrgs.length > 0 || incompleteCollaborators.length > 0;
|
||||
return incompleteOrgs.length > 0 || incompleteCollaborators.length > 0 || reservationPeriodAlerts.length > 0;
|
||||
};
|
||||
|
||||
const handleStartFlow = (flowId: string, companyId?: string) => {
|
||||
@@ -357,6 +427,46 @@ export default function AssistantHome() {
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{reservationPeriodAlerts.map(({ org, summary }, index) => {
|
||||
const orgId = org.id || org._id;
|
||||
const reservationPeriodCopy = summary.status === "missing"
|
||||
? {
|
||||
title: "Falta abrir el período de reservas",
|
||||
description: "Uno o más colaboradores todavía no tienen un período abierto para recibir reservas. Abrilo para que tus clientes puedan sacar turnos.",
|
||||
}
|
||||
: summary.status === "expired"
|
||||
? {
|
||||
title: "El período de reservas está vencido",
|
||||
description: "Uno o más colaboradores tienen el período de reservas vencido. Extendelo para que tus clientes puedan volver a reservar turnos.",
|
||||
}
|
||||
: {
|
||||
title: "El período de reservas está por finalizar",
|
||||
description: "El período abierto para reservas de uno o más colaboradores está por llegar a su fin. Extendelo para que tus clientes puedan seguir reservando turnos.",
|
||||
};
|
||||
|
||||
return (
|
||||
<div key={`reservation-period-${orgId || index}`} className={style.onboardingCard}>
|
||||
<div className={style.onboardingContent}>
|
||||
<div className={style.onboardingIcon}>
|
||||
<EventBusyIcon fontSize="large" style={{ color: "#fff" }} />
|
||||
</div>
|
||||
<div className={style.onboardingTexts} style={{ flex: 1 }}>
|
||||
<h3>{reservationPeriodCopy.title}</h3>
|
||||
<p>{reservationPeriodCopy.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<AssistantButton
|
||||
text={isLoadingFlow ? "Cargando..." : "Extender período"}
|
||||
onClick={() => {
|
||||
if (!isLoadingFlow) {
|
||||
handleStartFlow("open-reservation-periods", orgId);
|
||||
}
|
||||
}}
|
||||
style={{ width: "100%", marginTop: "20px", height: "48px" }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
animation: overlayFadeIn 0.25s ease-out;
|
||||
}
|
||||
|
||||
@keyframes overlayFadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from { transform: translateY(100%); }
|
||||
to { transform: translateY(0); }
|
||||
}
|
||||
|
||||
.sheet {
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
max-height: min(80vh, 600px);
|
||||
background: linear-gradient(160deg, var(--wine-superdark) 0%, #1a0a2e 100%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
animation: sheetIn 0.3s ease-out;
|
||||
color: white;
|
||||
}
|
||||
|
||||
@keyframes sheetIn {
|
||||
from { opacity: 0; transform: scale(0.97) translateY(8px); }
|
||||
to { opacity: 1; transform: scale(1) translateY(0); }
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px 20px 16px 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
letter-spacing: -0.01em;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s, transform 0.25s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.closeButton:hover {
|
||||
background: rgba(255, 42, 127, 0.15);
|
||||
color: var(--wine-red);
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.searchWrap {
|
||||
position: relative;
|
||||
margin: 0 20px 14px 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 12px 44px 12px 44px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: white;
|
||||
font-size: 15px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color 0.25s, box-shadow 0.25s, background 0.25s;
|
||||
}
|
||||
|
||||
.searchInput::placeholder {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.searchInput:focus {
|
||||
border-color: var(--wine-red);
|
||||
box-shadow: 0 0 0 3px rgba(255, 42, 127, 0.18);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.clearButton {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-radius: 50%;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: color 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.clearButton:hover {
|
||||
color: white;
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.results {
|
||||
flex: 1 1 auto;
|
||||
overflow-y: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
padding: 4px 14px 18px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
|
||||
}
|
||||
|
||||
.results::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.results::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.clientCard {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-family: inherit;
|
||||
transition: transform 0.2s, border-color 0.2s, box-shadow 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.clientCard:hover,
|
||||
.clientCard:focus-visible {
|
||||
transform: translateY(-1px);
|
||||
border-color: rgba(255, 255, 255, 0.18);
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.clientCardSelected {
|
||||
border-color: var(--wine-red);
|
||||
background: rgba(255, 42, 127, 0.08);
|
||||
box-shadow: 0 0 24px rgba(255, 42, 127, 0.2), inset 0 0 0 1px rgba(255, 42, 127, 0.25);
|
||||
}
|
||||
|
||||
.clientCardSelected:hover,
|
||||
.clientCardSelected:focus-visible {
|
||||
background: rgba(255, 42, 127, 0.12);
|
||||
border-color: var(--wine-red);
|
||||
}
|
||||
|
||||
.avatarWrap {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.avatarFallback {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
letter-spacing: 0.02em;
|
||||
background: linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%);
|
||||
}
|
||||
|
||||
.avatarImg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fullName {
|
||||
color: white;
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.bannedChip {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: #ffd1cc;
|
||||
background: rgba(255, 42, 42, 0.16);
|
||||
border: 1px solid rgba(255, 42, 42, 0.32);
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.subLine {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.checkWrap {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
background: linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%);
|
||||
box-shadow: 0 0 14px rgba(255, 42, 127, 0.45);
|
||||
}
|
||||
|
||||
.centerState {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
margin: 0;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.emptyText {
|
||||
margin: 0;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
.clearCta {
|
||||
margin-top: 6px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 42, 127, 0.4);
|
||||
background: rgba(255, 42, 127, 0.1);
|
||||
color: white;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
.clearCta:hover {
|
||||
background: rgba(255, 42, 127, 0.2);
|
||||
border-color: var(--wine-red);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid rgba(255, 255, 255, 0.18);
|
||||
border-top-color: var(--wine-red);
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Mobile: bottom sheet */
|
||||
@media (max-width: 600px) {
|
||||
.overlay {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.sheet {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
max-height: 82vh;
|
||||
border-radius: 24px 24px 0 0;
|
||||
border-left: none;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
animation: slideUp 0.3s ease-out;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 18px 18px 12px 18px;
|
||||
}
|
||||
|
||||
.searchWrap {
|
||||
margin: 0 14px 12px 14px;
|
||||
}
|
||||
|
||||
.results {
|
||||
padding: 4px 10px 22px 10px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import style from "./ClientPicker.module.css";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import SearchIcon from "@mui/icons-material/Search";
|
||||
import CheckIcon from "@mui/icons-material/Check";
|
||||
import PersonOffOutlined from "@mui/icons-material/PersonOffOutlined";
|
||||
import { OrganizationClientView } from "@models/Clients.model";
|
||||
|
||||
export interface ClientPickerProps {
|
||||
open: boolean;
|
||||
clients: OrganizationClientView[];
|
||||
selectedId: string | null;
|
||||
onSelect: (id: string) => void;
|
||||
onClose: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function formatPhone(c: OrganizationClientView): string {
|
||||
const parts = [c.phoneCountryCode, c.phoneAreaCode, c.phoneNumber]
|
||||
.filter(p => p != null && String(p).trim() !== "");
|
||||
if (parts.length === 0) return "";
|
||||
const joined = parts.map(p => String(p).trim()).join(" ");
|
||||
return joined.startsWith("+") ? joined : `+${joined}`;
|
||||
}
|
||||
|
||||
function getInitials(c: OrganizationClientView): string {
|
||||
const f = (c.firstName?.[0] || "").toUpperCase();
|
||||
const l = (c.lastName?.[0] || "").toUpperCase();
|
||||
return `${f}${l}` || "?";
|
||||
}
|
||||
|
||||
export default function ClientPicker({
|
||||
open,
|
||||
clients,
|
||||
selectedId,
|
||||
onSelect,
|
||||
onClose,
|
||||
loading,
|
||||
}: ClientPickerProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
setQuery("");
|
||||
const t = setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}, 80);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
clearTimeout(t);
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return clients;
|
||||
return clients.filter(c =>
|
||||
(c.firstName || "").toLowerCase().includes(q) ||
|
||||
(c.lastName || "").toLowerCase().includes(q) ||
|
||||
(c.fullName || "").toLowerCase().includes(q)
|
||||
);
|
||||
}, [clients, query]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const hasClients = clients.length > 0;
|
||||
const noResults = hasClients && filtered.length === 0 && query.trim() !== "";
|
||||
const searching = query.trim() !== "";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={style.overlay}
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Seleccionar cliente"
|
||||
>
|
||||
<div
|
||||
className={style.sheet}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className={style.header}>
|
||||
<h2>Selecciona un cliente</h2>
|
||||
<button
|
||||
type="button"
|
||||
className={style.closeButton}
|
||||
onClick={onClose}
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<CloseIcon style={{ fontSize: 20 }} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className={style.searchWrap}>
|
||||
<SearchIcon
|
||||
style={{
|
||||
fontSize: 22,
|
||||
position: "absolute",
|
||||
left: "14px",
|
||||
top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
color: "rgba(255,255,255,0.5)",
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
className={style.searchInput}
|
||||
placeholder="Buscar por nombre o apellido..."
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
aria-label="Buscar cliente"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{searching && (
|
||||
<button
|
||||
type="button"
|
||||
className={style.clearButton}
|
||||
onClick={() => setQuery("")}
|
||||
aria-label="Limpiar búsqueda"
|
||||
>
|
||||
<CloseIcon style={{ fontSize: 16 }} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={style.results}>
|
||||
{loading ? (
|
||||
<div className={style.centerState}>
|
||||
<div className={style.spinner} />
|
||||
<p className={style.emptyText}>Cargando clientes…</p>
|
||||
</div>
|
||||
) : !hasClients ? (
|
||||
<div className={style.centerState}>
|
||||
<PersonOffOutlined style={{ fontSize: 46, color: "rgba(255,255,255,0.35)" }} />
|
||||
<p className={style.emptyTitle}>Sin clientes todavía</p>
|
||||
<p className={style.emptyText}>
|
||||
No hay clientes para esta organización todavía. Cuando alguien reserve un turno, aparecerá acá.
|
||||
</p>
|
||||
</div>
|
||||
) : noResults ? (
|
||||
<div className={style.centerState}>
|
||||
<p className={style.emptyTitle}>No encontramos clientes con ese nombre.</p>
|
||||
<button
|
||||
type="button"
|
||||
className={style.clearCta}
|
||||
onClick={() => setQuery("")}
|
||||
>
|
||||
Limpiar búsqueda
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
filtered.map(c => {
|
||||
const isSelected = c.id === selectedId;
|
||||
const sub = (c.email && c.email.trim() !== "") ? c.email : formatPhone(c);
|
||||
const avatar = c.avatar && c.avatar.trim() !== "";
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className={`${style.clientCard} ${isSelected ? style.clientCardSelected : ""}`}
|
||||
onClick={() => onSelect(c.id)}
|
||||
>
|
||||
<div className={style.avatarWrap}>
|
||||
<div className={style.avatarFallback}>{getInitials(c)}</div>
|
||||
{avatar && (
|
||||
<img
|
||||
src={c.avatar}
|
||||
alt={c.fullName}
|
||||
className={style.avatarImg}
|
||||
onError={(e) => {
|
||||
(e.currentTarget as HTMLImageElement).style.opacity = "0";
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={style.cardBody}>
|
||||
<div className={style.cardTitle}>
|
||||
<span className={style.fullName}>{c.fullName}</span>
|
||||
{c.banned && (
|
||||
<span className={style.bannedChip}>Suspendido</span>
|
||||
)}
|
||||
</div>
|
||||
{sub && <span className={style.subLine}>{sub}</span>}
|
||||
</div>
|
||||
|
||||
{isSelected && (
|
||||
<span className={style.checkWrap} aria-label="Seleccionado">
|
||||
<CheckIcon style={{ fontSize: 18 }} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+38
@@ -0,0 +1,38 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function OrganizationPicker({ allOrganizations, loadOrganizationContext }: Props) {
|
||||
return (
|
||||
<QuestionCard
|
||||
isActive={true}
|
||||
title="Selecciona la Organización"
|
||||
description="¿A qué negocio deseas aplicar estos cambios?"
|
||||
onNext={() => {}}
|
||||
disableNext={true}
|
||||
nextLabel=""
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
{allOrganizations.map((org: any) => (
|
||||
<div
|
||||
key={org.id || org._id}
|
||||
onClick={() => loadOrganizationContext(org)}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
border: '2px solid transparent',
|
||||
color: 'white', transition: 'all 0.2s ease',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center'
|
||||
}}
|
||||
onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--wine-red)'}
|
||||
onMouseLeave={(e) => e.currentTarget.style.borderColor = 'transparent'}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>{org.name}</h4>
|
||||
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>{org.street} {org.streetNumber}, {org.city}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import React from "react";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function SuccessScreen(props: Props) {
|
||||
const { action, flowId, isStandaloneAction, router } = props;
|
||||
|
||||
const getSuccessMessage = () => {
|
||||
if (action === "new-service") return "Has agregado tu nuevo servicio exitosamente.";
|
||||
if (action === "edit-schedule") return "Tus horarios se han actualizado exitosamente.";
|
||||
if (action === "edit-location") return "La ubicación de tu negocio ha sido actualizada.";
|
||||
if (action === "edit-contact") return "Tus datos de contacto han sido actualizados.";
|
||||
if (action === "edit-appearance") return "La apariencia de tu negocio ha sido actualizada.";
|
||||
if (flowId === "override-schedule" || flowId === "disable-schedule") return "El horario especial ha sido guardado exitosamente.";
|
||||
if (flowId === "new-collaborator") return "El colaborador fue invitado exitosamente.";
|
||||
if (flowId === "setup-collaborator") return "El colaborador ha sido configurado exitosamente y ya puede comenzar a recibir reservas.";
|
||||
if (flowId === "notifications") return "La configuración de notificaciones se ha guardado exitosamente.";
|
||||
if (flowId === "whatsapp-bot") return "Tu bot de WhatsApp está configurado y funcionando. Tus clientes recibirán notificaciones automáticas por WhatsApp.";
|
||||
if (flowId === "open-reservation-periods") return "El período de reservas fue extendido exitosamente.";
|
||||
if (isStandaloneAction) return "Tus cambios se han guardado exitosamente.";
|
||||
return "Has configurado exitosamente tu negocio. Todo está listo para que empieces a recibir reservas y gestionar tu agenda como un profesional.";
|
||||
};
|
||||
|
||||
const successButtonStyle: React.CSSProperties = {
|
||||
padding: '16px 40px', fontSize: '18px', fontWeight: 'bold',
|
||||
background: 'white', color: 'var(--wine-red)', border: 'none',
|
||||
borderRadius: '30px', cursor: 'pointer',
|
||||
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
|
||||
transition: 'transform 0.2s, box-shadow 0.2s'
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh',
|
||||
background: 'linear-gradient(135deg, #1a0515 0%, #300018 100%)',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
zIndex: 9999, overflow: 'hidden', padding: '20px', boxSizing: 'border-box'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '120px', height: '120px', borderRadius: '50%', background: 'rgba(255,255,255,0.1)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '30px',
|
||||
boxShadow: '0 0 50px rgba(255, 255, 255, 0.2)',
|
||||
animation: 'pulse 2s infinite ease-in-out'
|
||||
}}>
|
||||
<span style={{ fontSize: '60px' }}>🎉</span>
|
||||
</div>
|
||||
<h1 style={{ color: 'white', fontSize: '32px', marginBottom: '15px', textAlign: 'center', textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}>
|
||||
¡Felicitaciones!
|
||||
</h1>
|
||||
<p style={{ color: 'rgba(255,255,255,0.8)', fontSize: '18px', maxWidth: '500px', textAlign: 'center', marginBottom: '40px', lineHeight: '1.5' }}>
|
||||
{getSuccessMessage()}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isStandaloneAction) router.push("/admin/assistant");
|
||||
else window.location.href = "/landing/dashboard";
|
||||
}}
|
||||
style={successButtonStyle}
|
||||
onMouseOver={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(-2px)';
|
||||
e.currentTarget.style.boxShadow = '0 6px 20px rgba(255,255,255,0.3)';
|
||||
}}
|
||||
onMouseOut={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(0)';
|
||||
e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
|
||||
}}
|
||||
>
|
||||
{isStandaloneAction ? "Volver al Menú Principal" : "Ir a mi Panel de Control"}
|
||||
</button>
|
||||
<style>{`
|
||||
@keyframes pulse {
|
||||
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
|
||||
70% { transform: scale(1.05); box-shadow: 0 0 0 30px rgba(255, 255, 255, 0); }
|
||||
100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||
|
||||
export const NOTIF_CHANNELS: { key: NotificationChannel; label: string; description: string }[] = [
|
||||
{ key: "whatsapp", label: "WhatsApp", description: "Mensajes automáticos por WhatsApp." },
|
||||
{ key: "email", label: "Email", description: "Correos electrónicos al cliente." },
|
||||
{ key: "system", label: "Sistema", description: "Notificaciones dentro de la plataforma." }
|
||||
];
|
||||
|
||||
export const NOTIF_REMINDER_PRESETS: { minutes: number; label: string }[] = [
|
||||
{ minutes: 60, label: "1 hora antes" },
|
||||
{ minutes: 180, label: "3 horas antes" },
|
||||
{ minutes: 360, label: "6 horas antes" },
|
||||
{ minutes: 720, label: "12 horas antes" },
|
||||
{ minutes: 1440, label: "1 día antes" },
|
||||
{ minutes: 2880, label: "2 días antes" }
|
||||
];
|
||||
|
||||
export const ALL_NOTIF_CHANNELS: NotificationChannel[] = ["whatsapp", "email", "system"];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ReservationPeriodDuration } from "@models/SchedulesEnabled.type";
|
||||
|
||||
export const reservationPeriodOptions: Array<ReservationPeriodDuration & { label: string }> = [
|
||||
{ unit: "week", value: 1, label: "1 semana" },
|
||||
{ unit: "week", value: 2, label: "2 semanas" },
|
||||
{ unit: "week", value: 3, label: "3 semanas" },
|
||||
{ unit: "month", value: 1, label: "1 mes" },
|
||||
{ unit: "month", value: 2, label: "2 meses" },
|
||||
];
|
||||
@@ -0,0 +1,292 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function DisableScheduleFlow(props: Props) {
|
||||
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Cerrar Agenda"
|
||||
description="¿A quiénes quieres aplicar esta inhabilitación de agenda?"
|
||||
onNext={() => {
|
||||
if (scheduleScope === "specific" && !targetEmployeeId) {
|
||||
alert("Por favor selecciona un colaborador.");
|
||||
return;
|
||||
}
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setScheduleScope("me")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("specific")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("all")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
|
||||
</div>
|
||||
|
||||
{scheduleScope === "specific" && (
|
||||
<div style={{ marginTop: '15px', width: '100%' }}>
|
||||
<select
|
||||
value={targetEmployeeId || ""}
|
||||
onChange={(e) => setTargetEmployeeId(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '12px', borderRadius: '8px',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
|
||||
outline: 'none', fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
|
||||
{allEmployees.map((emp: any) => (
|
||||
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
|
||||
{emp.firstName} {emp.lastName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="Duración del Cierre"
|
||||
description="¿Por cuánto tiempo se cerrará la agenda?"
|
||||
onNext={handleNext}
|
||||
disableNext={!disableDuration}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
|
||||
<div
|
||||
onClick={() => setDisableDuration("one-day")}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: disableDuration === "one-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${disableDuration === "one-day" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Solo por un día
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setDisableDuration("multi-day")}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: disableDuration === "multi-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${disableDuration === "multi-day" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Por varios días
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
{disableDuration === "one-day" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="Fecha del Cierre"
|
||||
description="Selecciona la fecha en la que no se recibirán turnos."
|
||||
onNext={handleNext}
|
||||
disableNext={!disableStartDate}
|
||||
>
|
||||
<div style={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
|
||||
<input
|
||||
type="date"
|
||||
value={disableStartDate}
|
||||
onChange={(e) => setDisableStartDate(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="Rango Horario"
|
||||
description="¿Esta inhabilitación aplica para todo el día o solo en una franja horaria?"
|
||||
onNext={() => {
|
||||
if (isFullDayDisabled) {
|
||||
handleDisableScheduleSubmit();
|
||||
} else if (disableStartTime && disableEndTime) {
|
||||
handleDisableScheduleSubmit();
|
||||
}
|
||||
}}
|
||||
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
|
||||
disableNext={(!isFullDayDisabled && (!disableStartTime || !disableEndTime)) || isCreating}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setIsFullDayDisabled(true)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: isFullDayDisabled === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${isFullDayDisabled === true ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Todo el día
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setIsFullDayDisabled(false)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: isFullDayDisabled === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${isFullDayDisabled === false ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Franja Específica
|
||||
</div>
|
||||
</div>
|
||||
{!isFullDayDisabled && (
|
||||
<div style={{ display: 'flex', gap: '20px' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Desde (Hora)</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableStartTime}
|
||||
onChange={(e) => setDisableStartTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hasta (Hora)</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableEndTime}
|
||||
onChange={(e) => setDisableEndTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
)}
|
||||
|
||||
{disableDuration === "multi-day" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="¿Cuándo inicia?"
|
||||
description="Selecciona la fecha y hora de inicio de la inhabilitación."
|
||||
onNext={handleNext}
|
||||
disableNext={!disableStartDate || !disableStartTime}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Inicio</label>
|
||||
<input
|
||||
type="date"
|
||||
value={disableStartDate}
|
||||
onChange={(e) => setDisableStartDate(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Inicio</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableStartTime}
|
||||
onChange={(e) => setDisableStartTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="¿Cuándo termina?"
|
||||
description="Selecciona la fecha y hora en la que finaliza el cierre."
|
||||
onNext={handleDisableScheduleSubmit}
|
||||
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
|
||||
disableNext={!disableEndDate || !disableEndTime || isCreating}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Fin</label>
|
||||
<input
|
||||
type="date"
|
||||
value={disableEndDate}
|
||||
onChange={(e) => setDisableEndDate(e.target.value)}
|
||||
min={disableStartDate}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Fin</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableEndTime}
|
||||
onChange={(e) => setDisableEndTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import React from "react";
|
||||
import ReactAvatar from "react-avatar";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
import QuestionInput from "../../QuestionCard/QuestionInput";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function NewCollaboratorFlow(props: Props) {
|
||||
const { currentStepIndex, inviteEmail, setInviteEmail, inviteEmailError, setInviteEmailError, isSearchingEmail, handleSearchCollaboratorEmail, handleKeyDown, inviteCollaborator, inviteRole, setInviteRole, handleNext, handleCreateCollaborator, isCreating, createdCompanyId, router, resetInviteFlow, inviteFlowNotice, isUpgradeRequired } = props;
|
||||
|
||||
return (
|
||||
<>
|
||||
<QuestionCard isActive={currentStepIndex === 1} title="Buscar Colaborador" description="Ingresa el e-mail del usuario. Importante: debe estar registrado previamente en TurnosXpress." onNext={handleSearchCollaboratorEmail} disableNext={!inviteEmail || !inviteEmail.includes("@") || isSearchingEmail} nextLabel={isSearchingEmail ? "Buscando..." : "Buscar"}>
|
||||
<QuestionInput
|
||||
placeholder="ejemplo@correo.com"
|
||||
value={inviteEmail}
|
||||
onChange={(e) => { setInviteEmail(e.target.value); setInviteEmailError(""); }}
|
||||
onKeyDown={(e) => {
|
||||
if (inviteEmail.includes("@") && !isSearchingEmail) handleKeyDown(e, handleSearchCollaboratorEmail);
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
{inviteEmailError && (
|
||||
<div style={{ marginTop: '15px', padding: '15px', background: 'rgba(255,0,0,0.1)', border: '1px solid rgba(255,0,0,0.3)', borderRadius: '8px', color: '#ff9999', fontSize: '13px' }}>
|
||||
<b>No encontramos este e-mail.</b><br />
|
||||
Asegúrate de que la persona ya haya creado una cuenta en TurnosXpress con este correo. Pídele que se registre primero y vuelve a intentarlo.
|
||||
</div>
|
||||
)}
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 2} title="Configurar Rol" description={`¿Qué permisos quieres darle a ${inviteCollaborator?.firstName || inviteCollaborator?.fullName}?`} onNext={handleNext}>
|
||||
{inviteCollaborator && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: '20px' }}>
|
||||
{inviteCollaborator.avatar ? (
|
||||
<img src={inviteCollaborator.avatar} alt="Avatar" style={{ width: 60, height: 60, borderRadius: '50%', marginBottom: '10px', objectFit: 'cover' }} />
|
||||
) : (
|
||||
<ReactAvatar name={inviteCollaborator.fullName} size="60" round color="#600018" style={{ marginBottom: '10px' }} />
|
||||
)}
|
||||
<div style={{ color: 'white', fontWeight: 'bold' }}>{inviteCollaborator.fullName}</div>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<div onClick={() => setInviteRole("colaborador")} style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
|
||||
<div style={{ fontWeight: 'bold' }}>Colaborador</div>
|
||||
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Solo podrá ver y gestionar su propia agenda de turnos.</div>
|
||||
</div>
|
||||
<div onClick={() => setInviteRole("admin")} style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
|
||||
<div style={{ fontWeight: 'bold' }}>Administrador</div>
|
||||
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Tendrá acceso total para modificar horarios, servicios y otros colaboradores de esta organización.</div>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 3 && !isUpgradeRequired} title="Confirmar Invitación" description={`Se enviará una invitación a ${inviteCollaborator?.email}. El usuario deberá aceptarla para comenzar.`} onNext={handleCreateCollaborator} disableNext={isCreating} nextLabel={isCreating ? "Enviando..." : "Enviar Invitación"}>{null}</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 4} title="Invitación Enviada" description="¿Cómo quieres continuar?">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Agrega otra persona a tu equipo." />
|
||||
<ActionCard onClick={() => router.push(`/admin/assistant?flow=update-schedule${createdCompanyId ? `&companyId=${createdCompanyId}` : ""}`)} title="Configurar mis horarios" description="Define tus horarios personales de atención." />
|
||||
<ActionCard onClick={() => router.push("/admin/assistant")} title="Terminar" description="Volver a la home del asistente." />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 5} title="Invitación Pendiente" description={inviteFlowNotice || "No pudimos enviar la invitación en este momento."}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Busca otra persona para sumar al equipo." />
|
||||
<ActionCard onClick={() => router.push("/admin/assistant")} title="Volver al asistente" description="Regresar a la home del asistente." />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 6} title="El usuario ya pertenece" description={inviteFlowNotice || "Este usuario ya pertenece a la compañía."}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Busca otra persona para sumar al equipo." />
|
||||
<ActionCard onClick={() => router.push("/admin/assistant")} title="Volver al asistente" description="Regresar a la home del asistente." />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === 3 && isUpgradeRequired} title="¡Haz crecer tu equipo!" description="Parece que has alcanzado el límite de colaboradores de tu plan actual. Actualiza tu suscripción para seguir sumando profesionales a tu negocio." onNext={() => window.location.href = "/landing/pricing"} nextLabel="Ver Planes y Mejorar">
|
||||
<div style={{ padding: '20px', background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', border: '1px solid var(--wine-red)', borderRadius: '15px', color: 'white', textAlign: 'center', margin: '15px 0' }}>
|
||||
<div style={{ fontSize: '40px', marginBottom: '10px' }}>🚀</div>
|
||||
<h4 style={{ margin: '0 0 10px 0', fontSize: '18px' }}>Beneficios de expandirte</h4>
|
||||
<ul style={{ textAlign: 'left', margin: '0', padding: '0 0 0 20px', opacity: 0.9, fontSize: '14px', lineHeight: '1.6' }}>
|
||||
<li>Agendas ilimitadas para todo tu equipo.</li>
|
||||
<li>Aumento exponencial de tus reservas diarias.</li>
|
||||
<li>Control total sobre los permisos de cada integrante.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionCard({ onClick, title, description }: Props) {
|
||||
return (
|
||||
<div onClick={onClick} style={{ padding: '15px', borderRadius: '12px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.2)', cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
|
||||
<div style={{ fontWeight: 'bold' }}>{title}</div>
|
||||
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>{description}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
// @ts-nocheck
|
||||
import React from "react";
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
import ClientPicker from "../../ClientPicker/ClientPicker";
|
||||
import Switch from "@components/Switch/Switch";
|
||||
import TextTime from "@components/TextTime/TextTime";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function NotificationsFlow(props: Props) {
|
||||
const { currentStepIndex, notificationsScope, setNotificationsScope, handleNext, notifLoading, NOTIF_CHANNELS, NOTIF_REMINDER_PRESETS, notifChannels, notifReminderRules, toggleNotifReminder, notifQuietHoursActive, setNotifQuietHoursActive, dayjsFromHHmm, notifQuietHoursFrom, setNotifQuietHoursFrom, notifQuietHoursTo, setNotifQuietHoursTo, handleSaveNotifications, isCreating, notifSelectedClientId, setNotifSelectedClientId, notifClients, notifClientPickerOpen, setNotifClientPickerOpen, setNotifChannels, toggleNotifChannel, handleSelectNotifScope } = props;
|
||||
const renderNotificationsChannelToggle = (channel: NotificationChannel) => (
|
||||
<div
|
||||
key={channel}
|
||||
style={{
|
||||
display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||
padding: "14px 16px", borderRadius: "12px",
|
||||
background: "rgba(255,255,255,0.05)",
|
||||
border: `1px solid ${notifChannels.includes(channel) ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
|
||||
color: "white", transition: "all 0.2s ease"
|
||||
}}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
|
||||
<span style={{ fontWeight: 700 }}>{NOTIF_CHANNELS.find(c => c.key === channel)?.label}</span>
|
||||
<span style={{ fontSize: "13px", color: "rgba(255,255,255,0.65)" }}>
|
||||
{NOTIF_CHANNELS.find(c => c.key === channel)?.description}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={notifChannels.includes(channel)}
|
||||
onChange={() => toggleNotifChannel(channel)}
|
||||
disabled={notifLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (() => {
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Configurar Notificaciones"
|
||||
description="Te ayudamos a definir cómo y cuándo reciben notificaciones tus clientes. Primero elegí a qué querés aplicarle esta configuración."
|
||||
onNext={() => {
|
||||
if (!notificationsScope) return;
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!notificationsScope}
|
||||
nextLabel="Siguiente"
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
|
||||
<div
|
||||
onClick={() => handleSelectNotifScope("org")}
|
||||
style={{
|
||||
padding: "18px", borderRadius: "12px", cursor: "pointer",
|
||||
background: notificationsScope === "org" ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
|
||||
border: `2px solid ${notificationsScope === "org" ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
|
||||
color: "white", textAlign: "center", transition: "all 0.2s ease"
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: notificationsScope === "org" ? "bold" : "normal" }}>
|
||||
A la organización en general
|
||||
</h4>
|
||||
<p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>
|
||||
Configura canales, recordatorios y horario silencioso para todos los clientes.
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => handleSelectNotifScope("client")}
|
||||
style={{
|
||||
padding: "18px", borderRadius: "12px", cursor: "pointer",
|
||||
background: notificationsScope === "client" ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
|
||||
border: `2px solid ${notificationsScope === "client" ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
|
||||
color: "white", textAlign: "center", transition: "all 0.2s ease"
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: notificationsScope === "client" ? "bold" : "normal" }}>
|
||||
A un cliente específico
|
||||
</h4>
|
||||
<p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>
|
||||
Elige un cliente y define qué canales de notificación recibe.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: "18px", padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5 }}>
|
||||
Estos ajustes se sincronizan con la página de notificaciones de tu organización, así que después podés seguir ajustándolos desde ahí.
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
{notificationsScope === "org" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="1. Canales de notificación"
|
||||
description="Elige los canales por los cuales se enviarán las notificaciones automáticas a tus clientes."
|
||||
onNext={handleNext}
|
||||
disableNext={notifLoading}
|
||||
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", width: "100%" }}>
|
||||
{NOTIF_CHANNELS.map(c => renderNotificationsChannelToggle(c.key))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="2. Reglas de recordatorio"
|
||||
description="Activá los momentos en los que se enviará un recordatorio antes del turno. Podés elegir varios."
|
||||
onNext={handleNext}
|
||||
disableNext={notifLoading}
|
||||
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
|
||||
>
|
||||
<div style={{ display: "flex", flexWrap: "wrap", gap: "10px", justifyContent: "center", width: "100%" }}>
|
||||
{NOTIF_REMINDER_PRESETS.map(preset => {
|
||||
const isActive = notifReminderRules.some(r => r.offset === preset.minutes);
|
||||
return (
|
||||
<div
|
||||
key={preset.minutes}
|
||||
onClick={() => toggleNotifReminder(preset.minutes)}
|
||||
style={{
|
||||
padding: "10px 18px", borderRadius: "999px", cursor: "pointer",
|
||||
background: isActive ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
|
||||
border: `1px solid ${isActive ? "var(--wine-red)" : "rgba(255,255,255,0.15)"}`,
|
||||
color: "white",
|
||||
fontWeight: isActive ? "bold" : "normal",
|
||||
transition: "all 0.2s ease",
|
||||
fontSize: "14px"
|
||||
}}
|
||||
>
|
||||
{preset.label}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div style={{ marginTop: "18px", color: "rgba(255,255,255,0.55)", fontSize: "13px", textAlign: "center" }}>
|
||||
{notifReminderRules.length === 0
|
||||
? "No hay recordatorios activos todavía."
|
||||
: `Recordatorios activos: ${notifReminderRules.length}.`}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="3. Horario silencioso"
|
||||
description="Durante este rango horario no se enviarán notificaciones. Activá la opción solo si querés definirlo."
|
||||
onNext={handleNext}
|
||||
disableNext={notifLoading}
|
||||
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "20px", width: "100%", alignItems: "center" }}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||
padding: "14px 16px", borderRadius: "12px", width: "100%", maxWidth: "400px",
|
||||
background: "rgba(255,255,255,0.05)",
|
||||
border: `1px solid ${notifQuietHoursActive ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
|
||||
color: "white", transition: "all 0.2s ease"
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 700 }}>Activar horario silencioso</span>
|
||||
<Switch
|
||||
checked={notifQuietHoursActive}
|
||||
onChange={(checked) => setNotifQuietHoursActive(checked)}
|
||||
disabled={notifLoading}
|
||||
/>
|
||||
</div>
|
||||
{notifQuietHoursActive && (
|
||||
<div style={{ display: "flex", gap: "16px", width: "100%", maxWidth: "500px" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<TextTime
|
||||
placeholder="Desde"
|
||||
width="100%"
|
||||
value={dayjsFromHHmm(notifQuietHoursFrom)}
|
||||
onChange={(v) => setNotifQuietHoursFrom(v.format("HH:mm"))}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<TextTime
|
||||
placeholder="Hasta"
|
||||
width="100%"
|
||||
value={dayjsFromHHmm(notifQuietHoursTo)}
|
||||
onChange={(v) => setNotifQuietHoursTo(v.format("HH:mm"))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="Resumen"
|
||||
description="Revisá la configuración antes de guardarla."
|
||||
onNext={handleSaveNotifications}
|
||||
disableNext={isCreating || notifLoading}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)" }}>
|
||||
<div>
|
||||
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Canales activos</div>
|
||||
<div style={{ color: "white", fontWeight: 700 }}>
|
||||
{notifChannels.length > 0
|
||||
? notifChannels.map(c => NOTIF_CHANNELS.find(nc => nc.key === c)?.label).join(", ")
|
||||
: "Ninguno"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Recordatorios</div>
|
||||
<div style={{ color: "white", fontWeight: 700 }}>
|
||||
{notifReminderRules.length > 0
|
||||
? notifReminderRules.map(r => NOTIF_REMINDER_PRESETS.find(p => p.minutes === r.offset)?.label || `${r.offset} min`).join(", ")
|
||||
: "Ninguno"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Horario silencioso</div>
|
||||
<div style={{ color: "white", fontWeight: 700 }}>
|
||||
{notifQuietHoursActive ? `De ${notifQuietHoursFrom} a ${notifQuietHoursTo}` : "Desactivado"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
)}
|
||||
|
||||
{notificationsScope === "client" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="1. Selecciona el cliente"
|
||||
description="Elegí a qué cliente de la organización querés aplicarle esta configuración de canales."
|
||||
onNext={() => {
|
||||
if (!notifSelectedClientId) return;
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!notifSelectedClientId || notifLoading}
|
||||
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
|
||||
>
|
||||
<div style={{ width: "100%", display: "flex", flexDirection: "column", gap: "12px" }}>
|
||||
{notifClients.length === 0 ? (
|
||||
<div style={{ color: "rgba(255,255,255,0.7)", textAlign: "center", padding: "24px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)" }}>
|
||||
No hay clientes para esta organización todavía. Cuando alguien reserve un turno, aparecerá acá.
|
||||
</div>
|
||||
) : notifSelectedClientId ? (() => {
|
||||
const sc = notifClients.find(c => c.id === notifSelectedClientId);
|
||||
const sub = sc ? ((sc.email && sc.email.trim() !== "") ? sc.email : [sc.phoneCountryCode, sc.phoneAreaCode, sc.phoneNumber].filter(p => p && String(p).trim() !== "").map(p => String(p).trim()).join(" ")).replace(/^(?!\+)/, "+") : "";
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNotifClientPickerOpen(true)}
|
||||
style={{
|
||||
display: "flex", alignItems: "center", gap: "12px", width: "100%",
|
||||
padding: "12px", borderRadius: "14px",
|
||||
background: "rgba(255,42,127,0.08)",
|
||||
border: "1px solid var(--wine-red)",
|
||||
boxShadow: "0 0 24px rgba(255,42,127,0.18)",
|
||||
cursor: "pointer", color: "white", textAlign: "left",
|
||||
fontFamily: "inherit",
|
||||
transition: "background 0.2s, box-shadow 0.2s",
|
||||
}}
|
||||
>
|
||||
<div style={{ position: "relative", width: "44px", height: "44px", borderRadius: "50%", overflow: "hidden", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "14px", fontWeight: 700, color: "white", background: "linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%)" }}>
|
||||
{(sc?.avatar && sc.avatar.trim() !== "") ? (
|
||||
<img
|
||||
src={sc.avatar}
|
||||
alt={sc?.fullName || ""}
|
||||
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
|
||||
onError={(e) => { (e.currentTarget as HTMLImageElement).style.opacity = "0"; }}
|
||||
/>
|
||||
) : null}
|
||||
{sc ? `${(sc.firstName?.[0] || "").toUpperCase()}${(sc.lastName?.[0] || "").toUpperCase()}` : "?"}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: "2px" }}>
|
||||
<span style={{ color: "white", fontWeight: 700, fontSize: "15px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||
{sc?.fullName || "—"}
|
||||
</span>
|
||||
{sub && (
|
||||
<span style={{ color: "rgba(255,255,255,0.55)", fontSize: "12px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span style={{ color: "var(--wine-red)", fontSize: "13px", fontWeight: 600, flexShrink: 0 }}>Cambiar</span>
|
||||
</button>
|
||||
);
|
||||
})() : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNotifClientPickerOpen(true)}
|
||||
style={{
|
||||
display: "flex", alignItems: "center", justifyContent: "center", gap: "10px", width: "100%",
|
||||
padding: "14px", borderRadius: "14px",
|
||||
background: "rgba(255,255,255,0.05)",
|
||||
border: "1px solid rgba(255,255,255,0.14)",
|
||||
cursor: "pointer", color: "white",
|
||||
fontFamily: "inherit", fontSize: "15px", fontWeight: 600,
|
||||
transition: "border-color 0.2s, background 0.2s, box-shadow 0.2s",
|
||||
}}
|
||||
>
|
||||
<SearchIcon style={{ fontSize: 20, color: "var(--wine-red)" }} />
|
||||
Buscar y seleccionar cliente
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="2. Canales de notificación"
|
||||
description="Activá los canales por los que este cliente recibirá notificaciones de la organización. Los desactivados se silencian."
|
||||
onNext={handleNext}
|
||||
disableNext={!notifSelectedClientId || notifLoading}
|
||||
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", width: "100%" }}>
|
||||
{NOTIF_CHANNELS.map(c => renderNotificationsChannelToggle(c.key))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="Resumen"
|
||||
description="Revisá la configuración antes de guardarla."
|
||||
onNext={handleSaveNotifications}
|
||||
disableNext={isCreating || notifLoading}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)" }}>
|
||||
<div>
|
||||
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Cliente</div>
|
||||
<div style={{ color: "white", fontWeight: 700 }}>
|
||||
{notifClients.find(c => c.id === notifSelectedClientId)?.fullName || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Canales activos</div>
|
||||
<div style={{ color: "white", fontWeight: 700 }}>
|
||||
{notifChannels.length > 0
|
||||
? notifChannels.map(c => NOTIF_CHANNELS.find(nc => nc.key === c)?.label).join(", ")
|
||||
: "Ninguno"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<ClientPicker
|
||||
open={notifClientPickerOpen}
|
||||
clients={notifClients}
|
||||
selectedId={notifSelectedClientId}
|
||||
loading={notifLoading}
|
||||
onSelect={(id) => {
|
||||
setNotifChannels([]);
|
||||
setNotifSelectedClientId(id);
|
||||
setNotifClientPickerOpen(false);
|
||||
}}
|
||||
onClose={() => setNotifClientPickerOpen(false)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})();
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
import React from "react";
|
||||
import ReactAvatar from "react-avatar";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
import QuestionInput from "../../QuestionCard/QuestionInput";
|
||||
import OnboardingPhone from "../../OnboardingPhone/OnboardingPhone";
|
||||
import OnboardingLocation from "../../OnboardingLocation/OnboardingLocation";
|
||||
import SelectLocationMap from "@core/app/components/SelectLocationMap/SelectLocationMap";
|
||||
import { validatePhone } from "@core/helpers/validatePhone";
|
||||
import categories from "@models/Categories.type";
|
||||
import style from "../StepEngine.module.css";
|
||||
|
||||
type OnboardingOrgFlowProps = {
|
||||
currentStepIndex: any;
|
||||
SessionInfo: any;
|
||||
imageError: any;
|
||||
setImageError: any;
|
||||
handleNext: any;
|
||||
handleNextName: any;
|
||||
orgName: any;
|
||||
setOrgName: any;
|
||||
nameError: any;
|
||||
setNameError: any;
|
||||
isCheckingName: any;
|
||||
categoryId: any;
|
||||
setCategoryId: any;
|
||||
handleCreateCompany: any;
|
||||
isCreating: any;
|
||||
orgDescription: any;
|
||||
setOrgDescription: any;
|
||||
handleKeyDown: any;
|
||||
handleUpdateLocation: any;
|
||||
isStandaloneAction: any;
|
||||
street: any;
|
||||
streetNumber: any;
|
||||
builingFloor: any;
|
||||
buildingApartament: any;
|
||||
state: any;
|
||||
city: any;
|
||||
block: any;
|
||||
zipCode: any;
|
||||
latitude: any;
|
||||
longitude: any;
|
||||
setStreet: any;
|
||||
setStreetNumber: any;
|
||||
setBuilingFloor: any;
|
||||
setBuildingApartament: any;
|
||||
setState: any;
|
||||
setCity: any;
|
||||
setBlock: any;
|
||||
setZipCode: any;
|
||||
setLatitude: any;
|
||||
setLongitude: any;
|
||||
handleUpdateContact: any;
|
||||
phoneAreaCode: any;
|
||||
phoneNumber: any;
|
||||
setPhoneAreaCode: any;
|
||||
setPhoneNumber: any;
|
||||
handleUpdateRules: any;
|
||||
heatMapFraction: any;
|
||||
setHeatMapFraction: any;
|
||||
appointmentTime: any;
|
||||
setAppointmentTime: any;
|
||||
cancellationTime: any;
|
||||
setCancellationTime: any;
|
||||
handleUploadHeader: any;
|
||||
headerColor: any;
|
||||
setHeaderColor: any;
|
||||
headerFontColor: any;
|
||||
setHeaderFontColor: any;
|
||||
headerImage: any;
|
||||
setHeaderImage: any;
|
||||
};
|
||||
|
||||
export default function OnboardingOrgFlow(props: OnboardingOrgFlowProps) {
|
||||
const { currentStepIndex, SessionInfo, imageError, setImageError, handleNext, handleNextName, orgName, setOrgName, nameError, setNameError, isCheckingName, categoryId, setCategoryId, handleCreateCompany, isCreating, orgDescription, setOrgDescription, handleKeyDown, handleUpdateLocation, isStandaloneAction, street, streetNumber, builingFloor, buildingApartament, state, city, block, zipCode, latitude, longitude, setStreet, setStreetNumber, setBuilingFloor, setBuildingApartament, setState, setCity, setBlock, setZipCode, setLatitude, setLongitude, handleUpdateContact, phoneAreaCode, phoneNumber, setPhoneAreaCode, setPhoneNumber, handleUpdateRules, heatMapFraction, setHeatMapFraction, appointmentTime, setAppointmentTime, cancellationTime, setCancellationTime, handleUploadHeader, headerColor, setHeaderColor, headerFontColor, setHeaderFontColor, headerImage, setHeaderImage } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title={`¡Bienvenido a TurnosXpress, ${SessionInfo.userFullName.split(" ")[0]}!`}
|
||||
description="Vamos a configurar tu negocio en solo unos minutos. Relájate, yo te guiaré paso a paso para que todo quede perfecto."
|
||||
onNext={handleNext}
|
||||
nextLabel="Empezar ahora"
|
||||
topAccessory={
|
||||
SessionInfo.avatar && !imageError ? (
|
||||
<img
|
||||
src={SessionInfo.avatar}
|
||||
alt="Avatar"
|
||||
style={{ width: 90, height: 90, borderRadius: '50%', objectFit: 'cover' }}
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
) : (
|
||||
<ReactAvatar
|
||||
name={SessionInfo.userFullName || "Usuario"}
|
||||
size="90"
|
||||
round={true}
|
||||
textSizeRatio={2.5}
|
||||
maxInitials={2}
|
||||
color="#600018"
|
||||
/>
|
||||
)
|
||||
}
|
||||
>
|
||||
{null}
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="1. Identidad de tu Negocio"
|
||||
description="Para empezar, ¿cuál es el nombre de tu organización o emprendimiento?"
|
||||
onNext={handleNextName}
|
||||
disableNext={orgName.trim().length < 3 || isCheckingName}
|
||||
nextLabel={isCheckingName ? "Validando..." : "Siguiente"}
|
||||
>
|
||||
<QuestionInput
|
||||
placeholder="Ej. Salón de Belleza VIP"
|
||||
value={orgName}
|
||||
onChange={(e) => {
|
||||
setOrgName(e.target.value);
|
||||
if (nameError) setNameError("");
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (orgName.trim().length >= 3) {
|
||||
handleKeyDown(e, handleNextName);
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
error={nameError}
|
||||
/>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="2. ¿A qué te dedicas?"
|
||||
description="Elige la categoría que mejor describa los servicios que ofreces."
|
||||
onNext={handleNext}
|
||||
disableNext={categoryId === null}
|
||||
>
|
||||
<div className={style.categoryGrid}>
|
||||
{categories.filter(c => c.id !== 0).map(cat => (
|
||||
<div
|
||||
key={cat.id}
|
||||
className={`${style.categoryItem} ${categoryId === cat.id ? style.categorySelected : ''}`}
|
||||
onClick={() => {
|
||||
setCategoryId(cat.id);
|
||||
setTimeout(handleNext, 400);
|
||||
}}
|
||||
>
|
||||
<div className={style.categoryIcon}>✧</div>
|
||||
<div className={style.categoryName}>{cat.name}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="3. Una breve descripción"
|
||||
description={`Cuentanos un poco sobre "${orgName}". Esta descripción la verán tus clientes.`}
|
||||
onNext={handleCreateCompany}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Creando..." : "Guardar Organización"}
|
||||
>
|
||||
<QuestionInput
|
||||
placeholder="Ej. Ofrecemos los mejores cortes..."
|
||||
value={orgDescription}
|
||||
onChange={(e) => setOrgDescription(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (orgDescription.trim().length >= 10) {
|
||||
handleKeyDown(e, handleCreateCompany);
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</QuestionCard>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="4. Ubicación de tu Negocio"
|
||||
description={`¿Dónde queda "${orgName}"? Esto es crucial para que tus clientes te encuentren.`}
|
||||
onNext={handleUpdateLocation}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<OnboardingLocation
|
||||
data={{
|
||||
street, streetNumber, builingFloor, buildingApartament, state, city, block, zipCode, latitude, longitude
|
||||
}}
|
||||
onChange={(newData) => {
|
||||
if (newData.street !== undefined) setStreet(newData.street);
|
||||
if (newData.streetNumber !== undefined) setStreetNumber(newData.streetNumber);
|
||||
if (newData.builingFloor !== undefined) setBuilingFloor(newData.builingFloor);
|
||||
if (newData.buildingApartament !== undefined) setBuildingApartament(newData.buildingApartament);
|
||||
if (newData.state !== undefined) setState(newData.state);
|
||||
if (newData.city !== undefined) setCity(newData.city);
|
||||
if (newData.block !== undefined) setBlock(newData.block);
|
||||
if (newData.zipCode !== undefined) setZipCode(newData.zipCode);
|
||||
if (newData.latitude !== undefined) setLatitude(newData.latitude);
|
||||
if (newData.longitude !== undefined) setLongitude(newData.longitude);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 5}
|
||||
title="5. Ubica tu local en el mapa (Opcional)"
|
||||
description={`Para que los clientes encuentren "${orgName}" con exactitud. Por favor, haz el máximo zoom posible y arrastra el marcador a tu ubicación exacta.`}
|
||||
onNext={handleUpdateLocation}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar Ubicación"}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{ width: '100%', borderRadius: '8px', overflow: 'hidden' }}>
|
||||
<SelectLocationMap
|
||||
initialCoordinates={{ latitude, longitude }}
|
||||
height="350px"
|
||||
onChange={(loc) => {
|
||||
setLatitude(loc.latitude);
|
||||
setLongitude(loc.longitude);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
marginTop: '10px',
|
||||
fontSize: '13px',
|
||||
color: 'rgba(255,255,255,0.6)',
|
||||
cursor: 'pointer',
|
||||
textDecoration: 'underline'
|
||||
}}
|
||||
onClick={() => {
|
||||
if (!isCreating) handleUpdateLocation();
|
||||
}}
|
||||
>
|
||||
Omitir este paso
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 6}
|
||||
title="6. Contacto"
|
||||
description="¿Cómo pueden contactarte tus clientes? Ingresa el número de teléfono (preferiblemente WhatsApp)."
|
||||
onNext={handleUpdateContact}
|
||||
disableNext={!validatePhone(phoneAreaCode, phoneNumber).isValid || isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
|
||||
<OnboardingPhone
|
||||
value={phoneAreaCode + phoneNumber}
|
||||
onChange={(area, num, full) => {
|
||||
setPhoneAreaCode(area);
|
||||
setPhoneNumber(num);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (validatePhone(phoneAreaCode, phoneNumber).isValid) {
|
||||
handleKeyDown(e, handleUpdateContact);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 7}
|
||||
title="7. Reglas de Negocio"
|
||||
description="Configura los tiempos de tu agenda. Esto determinará cómo se muestran los turnos a tus clientes."
|
||||
onNext={handleUpdateRules}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : "Siguiente: Crear Servicio"}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
|
||||
<div>
|
||||
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Fracción de la Agenda (Minutos)</div>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
|
||||
{[15, 30, 45, 60, 120].map(val => (
|
||||
<div
|
||||
key={val}
|
||||
onClick={() => setHeatMapFraction(val)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
fontWeight: heatMapFraction === val ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{val}m
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para reservar (Horas)</div>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
|
||||
{[1, 2, 12, 24, 48].map(val => (
|
||||
<div
|
||||
key={val}
|
||||
onClick={() => setAppointmentTime(val)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
fontWeight: appointmentTime === val ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{val}h
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para cancelar (Horas)</div>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
|
||||
{[1, 2, 12, 24, 48].map(val => (
|
||||
<div
|
||||
key={val}
|
||||
onClick={() => setCancellationTime(val)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
fontWeight: cancellationTime === val ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{val}h
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 8}
|
||||
title="8. Apariencia"
|
||||
description="Sube una foto de portada para tu negocio y elige tus colores corporativos. Esto es lo primero que verán tus clientes."
|
||||
onNext={handleUploadHeader}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{
|
||||
display: 'flex', gap: '20px', width: '100%', maxWidth: '500px',
|
||||
justifyContent: 'center', background: 'rgba(255,255,255,0.05)',
|
||||
padding: '15px', borderRadius: '12px'
|
||||
}}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
|
||||
<label style={{ color: 'white', fontSize: '13px' }}>Color de Fondo</label>
|
||||
<input
|
||||
type="color"
|
||||
value={headerColor}
|
||||
onChange={(e) => setHeaderColor(e.target.value)}
|
||||
style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
|
||||
<label style={{ color: 'white', fontSize: '13px' }}>Color del Texto</label>
|
||||
<input
|
||||
type="color"
|
||||
value={headerFontColor}
|
||||
onChange={(e) => setHeaderFontColor(e.target.value)}
|
||||
style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PREVIEW BOX */}
|
||||
<div style={{ width: '100%', maxWidth: '500px', marginTop: '10px' }}>
|
||||
<div style={{ color: 'rgba(255,255,255,0.7)', fontSize: '13px', marginBottom: '8px', textAlign: 'left' }}>
|
||||
Vista previa:
|
||||
</div>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: '120px',
|
||||
backgroundColor: headerColor,
|
||||
borderRadius: '12px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
|
||||
position: 'relative',
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
{headerImage && (
|
||||
<img
|
||||
src={URL.createObjectURL(headerImage)}
|
||||
style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.4 }}
|
||||
alt="Preview"
|
||||
/>
|
||||
)}
|
||||
<div style={{
|
||||
color: headerFontColor,
|
||||
fontSize: '24px',
|
||||
fontWeight: 'bold',
|
||||
position: 'relative',
|
||||
zIndex: 1,
|
||||
textShadow: '0 2px 4px rgba(0,0,0,0.5)'
|
||||
}}>
|
||||
{orgName || "Tu Negocio"}
|
||||
</div>
|
||||
<div style={{
|
||||
color: headerFontColor,
|
||||
fontSize: '14px',
|
||||
position: 'relative',
|
||||
zIndex: 1,
|
||||
opacity: 0.9,
|
||||
marginTop: '5px'
|
||||
}}>
|
||||
Categoría seleccionada
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label style={{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
maxWidth: '500px',
|
||||
height: '200px',
|
||||
border: '2px dashed rgba(255, 255, 255, 0.3)',
|
||||
borderRadius: '12px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
overflow: 'hidden',
|
||||
cursor: 'pointer',
|
||||
background: headerImage ? 'transparent' : 'rgba(255,255,255,0.05)'
|
||||
}}>
|
||||
{headerImage ? (
|
||||
<img
|
||||
src={URL.createObjectURL(headerImage)}
|
||||
alt="Preview"
|
||||
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={(e) => {
|
||||
if (e.target.files && e.target.files.length > 0) {
|
||||
setHeaderImage(e.target.files[0]);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
opacity: 0,
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type OnboardingScheduleFlowProps = {
|
||||
currentStepIndex: any;
|
||||
handleNext: any;
|
||||
doesProvideServices: any;
|
||||
setDoesProvideServices: any;
|
||||
createdCompanyId: any;
|
||||
router: any;
|
||||
workingDaysMode: any;
|
||||
setWorkingDaysMode: any;
|
||||
openTime: any;
|
||||
setOpenTime: any;
|
||||
closeTime: any;
|
||||
setCloseTime: any;
|
||||
hasBreak: any;
|
||||
setHasBreak: any;
|
||||
breakStart: any;
|
||||
setBreakStart: any;
|
||||
breakEnd: any;
|
||||
setBreakEnd: any;
|
||||
handleCreateSchedule: any;
|
||||
isCreating: any;
|
||||
headerColor: any;
|
||||
headerImage: any;
|
||||
headerFontColor: any;
|
||||
orgName: any;
|
||||
previewServices: any;
|
||||
setServiceName: any;
|
||||
setServiceDescription: any;
|
||||
setServiceLength: any;
|
||||
setServicePrice: any;
|
||||
setServiceLimit: any;
|
||||
setServiceImage: any;
|
||||
setCreatedServiceId: any;
|
||||
setIsAddingAnotherService: any;
|
||||
setCurrentStepIndex: any;
|
||||
};
|
||||
|
||||
export default function OnboardingScheduleFlow(props: OnboardingScheduleFlowProps) {
|
||||
const { currentStepIndex, handleNext, doesProvideServices, setDoesProvideServices, createdCompanyId, router, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, handleCreateSchedule, isCreating, headerColor, headerImage, headerFontColor, orgName, previewServices, setServiceName, setServiceDescription, setServiceLength, setServicePrice, setServiceLimit, setServiceImage, setCreatedServiceId, setIsAddingAnotherService, setCurrentStepIndex } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Configura tus Horarios"
|
||||
description="El último paso. Vamos a definir cuándo estás disponible para recibir clientes."
|
||||
onNext={handleNext}
|
||||
nextLabel="Comenzar"
|
||||
>
|
||||
<div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
|
||||
Con esta información, tu agenda online comenzará a aceptar reservas automáticamente.
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="Atención al Cliente"
|
||||
description="¿Brindas tú mismo los servicios que configuraste?"
|
||||
onNext={() => {
|
||||
if (doesProvideServices === null) return;
|
||||
if (!doesProvideServices) {
|
||||
const query = createdCompanyId ? `&companyId=${createdCompanyId}` : "";
|
||||
router.push(`/admin/assistant?flow=new-collaborator${query}`);
|
||||
} else {
|
||||
handleNext();
|
||||
}
|
||||
}}
|
||||
disableNext={doesProvideServices === null}
|
||||
nextLabel={doesProvideServices === false ? "Invitar colaborador" : "Siguiente"}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '15px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
|
||||
<div
|
||||
onClick={() => setDoesProvideServices(true)}
|
||||
style={{
|
||||
padding: '20px 24px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
background: doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
|
||||
color: 'white',
|
||||
transition: 'all 0.2s ease',
|
||||
textAlign: 'center',
|
||||
flex: '1',
|
||||
minWidth: '200px'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === true ? 'bold' : 'normal' }}>Sí, yo atiendo a los clientes</h4>
|
||||
<p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Asignaremos los servicios a tu nombre.</p>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setDoesProvideServices(false)}
|
||||
style={{
|
||||
padding: '20px 24px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
background: doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
|
||||
color: 'white',
|
||||
transition: 'all 0.2s ease',
|
||||
textAlign: 'center',
|
||||
flex: '1',
|
||||
minWidth: '200px'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === false ? 'bold' : 'normal' }}>No, tengo un equipo</h4>
|
||||
<p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Te guiaremos para invitar al primer colaborador.</p>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="1. Días Laborables"
|
||||
description="¿Qué días de la semana atiendes?"
|
||||
onNext={handleNext}
|
||||
disableNext={!workingDaysMode}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
|
||||
{[
|
||||
{ value: "mon-fri", label: "Lunes a Viernes" },
|
||||
{ value: "mon-sat", label: "Lunes a Sábado" },
|
||||
{ value: "mon-sun", label: "Lunes a Domingo" },
|
||||
].map(opt => (
|
||||
<div
|
||||
key={opt.value}
|
||||
onClick={() => setWorkingDaysMode(opt.value)}
|
||||
style={{
|
||||
padding: '12px 24px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
background: workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
|
||||
color: 'white',
|
||||
fontWeight: workingDaysMode === opt.value ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
{opt.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="2. Horario General"
|
||||
description="¿A qué hora abres y cierras tu negocio?"
|
||||
onNext={handleNext}
|
||||
disableNext={!openTime || !closeTime}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<span style={{ color: 'white', fontSize: '14px' }}>Apertura</span>
|
||||
<input
|
||||
type="time"
|
||||
value={openTime}
|
||||
onChange={(e) => setOpenTime(e.target.value)}
|
||||
style={{
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
color: 'white',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span style={{ color: 'white', fontSize: '18px' }}>a</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<span style={{ color: 'white', fontSize: '14px' }}>Cierre</span>
|
||||
<input
|
||||
type="time"
|
||||
value={closeTime}
|
||||
onChange={(e) => setCloseTime(e.target.value)}
|
||||
style={{
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
color: 'white',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="3. Horario Cortado"
|
||||
description="¿Cierras tu negocio al mediodía para descansar?"
|
||||
onNext={handleNext}
|
||||
disableNext={hasBreak === null}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', gap: '10px' }}>
|
||||
<div
|
||||
onClick={() => setHasBreak(true)}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
Sí, tengo descanso
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setHasBreak(false)}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
No, horario corrido
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasBreak && (
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center', marginTop: '10px' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<span style={{ color: 'white', fontSize: '14px' }}>Inicia el descanso</span>
|
||||
<input
|
||||
type="time"
|
||||
value={breakStart}
|
||||
onChange={(e) => setBreakStart(e.target.value)}
|
||||
style={{
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
color: 'white',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span style={{ color: 'white', fontSize: '18px' }}>a</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<span style={{ color: 'white', fontSize: '14px' }}>Termina</span>
|
||||
<input
|
||||
type="time"
|
||||
value={breakEnd}
|
||||
onChange={(e) => setBreakEnd(e.target.value)}
|
||||
style={{
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
color: 'white',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 5}
|
||||
title="Resumen Final y Vista Previa"
|
||||
description="Revisa cómo se verá tu negocio. Al finalizar, será publicado automáticamente."
|
||||
onNext={handleCreateSchedule}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Publicando..." : "Publicar y Activar Agenda"}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
|
||||
{/* Mockup visual */}
|
||||
<div style={{
|
||||
width: '100%', maxWidth: '500px', borderRadius: '12px', overflow: 'hidden',
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.5)', background: '#1e1e1e', border: '1px solid rgba(255,255,255,0.1)'
|
||||
}}>
|
||||
{/* Cabecera Mockup */}
|
||||
<div style={{
|
||||
background: headerColor,
|
||||
height: '120px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
position: 'relative'
|
||||
}}>
|
||||
{/* Simular imagen de cabecera si hay Archivo */}
|
||||
{headerImage && (
|
||||
<img src={URL.createObjectURL(headerImage)} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.6 }} />
|
||||
)}
|
||||
<h2 style={{ color: headerFontColor, margin: 0, zIndex: 1, textShadow: '0 2px 4px rgba(0,0,0,0.5)' }}>{orgName || "Tu Negocio"}</h2>
|
||||
</div>
|
||||
|
||||
{/* Cuerpo Mockup (Servicios y Horarios) */}
|
||||
<div style={{ padding: '20px' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
|
||||
<h4 style={{ margin: 0, color: 'white' }}>Servicios ({previewServices.length})</h4>
|
||||
<button
|
||||
onClick={() => {
|
||||
setServiceName("");
|
||||
setServiceDescription("");
|
||||
setServiceLength(null);
|
||||
setServicePrice("");
|
||||
setServiceLimit(1);
|
||||
setServiceImage(null);
|
||||
setCreatedServiceId(null);
|
||||
setIsAddingAnotherService(true);
|
||||
setCurrentStepIndex(1); // Service creation starts at step 1
|
||||
}}
|
||||
style={{
|
||||
background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
|
||||
color: 'white', borderRadius: '15px', padding: '4px 12px', fontSize: '12px',
|
||||
cursor: 'pointer', transition: 'background 0.2s'
|
||||
}}
|
||||
onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.2)'}
|
||||
onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
|
||||
>
|
||||
+ Agregar otro
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '20px' }}>
|
||||
{previewServices.map((s: any, idx: number) => (
|
||||
<div key={idx} style={{ background: 'rgba(255,255,255,0.05)', padding: '10px', borderRadius: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column' }}>
|
||||
<span style={{ color: 'white', fontWeight: 'bold', fontSize: '14px' }}>{s.name}</span>
|
||||
<span style={{ color: 'rgba(255,255,255,0.6)', fontSize: '12px' }}>{s.length} min</span>
|
||||
</div>
|
||||
<span style={{ color: 'var(--wine-red)', fontWeight: 'bold' }}>${s.originalPrice}</span>
|
||||
</div>
|
||||
))}
|
||||
{previewServices.length === 0 && (
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: '14px' }}>Sin servicios configurados aún.</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h4 style={{ margin: '0 0 10px 0', color: 'white' }}>Horario Laboral</h4>
|
||||
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '15px', borderRadius: '8px' }}>
|
||||
<div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
|
||||
<strong>Días:</strong> {workingDaysMode === "mon-fri" ? "Lunes a Viernes" : (workingDaysMode === "mon-sat" ? "Lunes a Sábado" : "Lunes a Domingo")}
|
||||
</div>
|
||||
<div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
|
||||
<strong>Horario:</strong> {openTime} a {closeTime}
|
||||
</div>
|
||||
{hasBreak && (
|
||||
<div style={{ color: 'white', fontSize: '14px' }}>
|
||||
<strong>Descanso:</strong> {breakStart} a {breakEnd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advertencia Explícita */}
|
||||
<div style={{
|
||||
background: 'rgba(255, 60, 60, 0.1)',
|
||||
borderLeft: '4px solid #ff3c3c',
|
||||
padding: '15px',
|
||||
borderRadius: '0 8px 8px 0',
|
||||
width: '100%',
|
||||
maxWidth: '500px'
|
||||
}}>
|
||||
<h4 style={{ margin: '0 0 5px 0', color: '#ff3c3c', fontSize: '16px' }}>🚨 Aviso de Publicación</h4>
|
||||
<p style={{ margin: 0, color: 'rgba(255,255,255,0.8)', fontSize: '13px', lineHeight: '1.4' }}>
|
||||
Al hacer clic en <strong>Publicar y Activar Agenda</strong>, tu organización, servicios y esta primera jornada laboral serán publicados en TurnosXpress.
|
||||
<br/><br/>
|
||||
¡Tus clientes podrán empezar a reservar turnos de inmediato! Podrás editar todo más tarde desde tu panel.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
import QuestionInput from "../../QuestionCard/QuestionInput";
|
||||
|
||||
type OnboardingServiceFlowProps = {
|
||||
heatMapFraction: any;
|
||||
currentStepIndex: any;
|
||||
handleNext: any;
|
||||
serviceName: any;
|
||||
setServiceName: any;
|
||||
serviceDescription: any;
|
||||
setServiceDescription: any;
|
||||
handleKeyDown: any;
|
||||
serviceLength: any;
|
||||
setServiceLength: any;
|
||||
handleCreateService: any;
|
||||
isCreating: any;
|
||||
servicePrice: any;
|
||||
setServicePrice: any;
|
||||
serviceLimit: any;
|
||||
setServiceLimit: any;
|
||||
handleUploadServiceImage: any;
|
||||
serviceImage: any;
|
||||
setServiceImage: any;
|
||||
};
|
||||
|
||||
export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps) {
|
||||
const { heatMapFraction, currentStepIndex, handleNext, serviceName, setServiceName, serviceDescription, setServiceDescription, handleKeyDown, serviceLength, setServiceLength, handleCreateService, isCreating, servicePrice, setServicePrice, serviceLimit, setServiceLimit, handleUploadServiceImage, serviceImage, setServiceImage } = props;
|
||||
const fraction = heatMapFraction || 60;
|
||||
const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4];
|
||||
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Configura tus Servicios"
|
||||
description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
|
||||
onNext={handleNext}
|
||||
nextLabel="Comenzar"
|
||||
>
|
||||
<div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
|
||||
Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil!
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="1. Nombre y Descripción"
|
||||
description="Elige un nombre atractivo y describe de qué trata el servicio."
|
||||
onNext={handleNext}
|
||||
disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
|
||||
<QuestionInput
|
||||
placeholder="Ej. Corte clásico con lavado"
|
||||
value={serviceName}
|
||||
onChange={(e) => setServiceName(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
<QuestionInput
|
||||
placeholder="Breve descripción del servicio..."
|
||||
value={serviceDescription}
|
||||
onChange={(e) => setServiceDescription(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (serviceName.trim().length >= 3 && serviceDescription.trim().length >= 5) {
|
||||
handleKeyDown(e, handleNext);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="2. Duración del Servicio"
|
||||
description={`Elige cuánto tiempo tomará. Las opciones están basadas en tu fracción de agenda (${fraction} min).`}
|
||||
onNext={handleNext}
|
||||
disableNext={!serviceLength}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
|
||||
{durationOptions.map(val => {
|
||||
const hours = Math.floor(val / 60);
|
||||
const minutes = val % 60;
|
||||
const label = hours > 0
|
||||
? `${hours}h ${minutes > 0 ? minutes + 'm' : ''}`.trim()
|
||||
: `${minutes} min`;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={val}
|
||||
onClick={() => setServiceLength(val)}
|
||||
style={{
|
||||
padding: '12px 24px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
background: serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
|
||||
color: 'white',
|
||||
fontWeight: serviceLength === val ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="3. Precio y Cupos"
|
||||
description="¿Cuánto cuesta y a cuántas personas puedes atender a la vez en este servicio?"
|
||||
onNext={handleCreateService}
|
||||
disableNext={isCreating || !servicePrice}
|
||||
nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
|
||||
<div>
|
||||
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Precio Original</div>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<span style={{ position: 'absolute', left: '15px', top: '50%', transform: 'translateY(-50%)', color: 'white', fontSize: '18px' }}>$</span>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="0.00"
|
||||
value={servicePrice}
|
||||
onChange={(e) => setServicePrice(e.target.value)}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '15px 15px 15px 35px',
|
||||
borderRadius: '12px',
|
||||
border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
color: 'white',
|
||||
fontSize: '18px',
|
||||
outline: 'none'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Cupos Simultáneos (Por defecto 1)</div>
|
||||
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
|
||||
{[1, 2, 3, 5, 10].map(val => (
|
||||
<div
|
||||
key={val}
|
||||
onClick={() => setServiceLimit(val)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
background: serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
|
||||
border: `1px solid ${serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
|
||||
color: 'white',
|
||||
fontWeight: serviceLimit === val ? 'bold' : 'normal',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{val}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="4. Imagen del Servicio"
|
||||
description="Sube una foto representativa para que los clientes sepan qué ofreces. (Opcional)"
|
||||
onNext={handleUploadServiceImage}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Subiendo..." : (serviceImage ? "Subir y Finalizar" : "Omitir por ahora")}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: '150px',
|
||||
border: '2px dashed rgba(255,255,255,0.3)',
|
||||
borderRadius: '12px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
cursor: 'pointer',
|
||||
background: serviceImage ? 'transparent' : 'rgba(255,255,255,0.05)'
|
||||
}}>
|
||||
{serviceImage ? (
|
||||
<img
|
||||
src={URL.createObjectURL(serviceImage)}
|
||||
alt="Preview"
|
||||
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={(e) => {
|
||||
if (e.target.files && e.target.files.length > 0) {
|
||||
setServiceImage(e.target.files[0]);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
opacity: 0,
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function OverrideScheduleFlow(props: Props) {
|
||||
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, overrideDate, setOverrideDate, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Horario Especial"
|
||||
description="¿A quiénes quieres aplicar este horario especial?"
|
||||
onNext={() => {
|
||||
if (scheduleScope === "specific" && !targetEmployeeId) {
|
||||
alert("Por favor selecciona un colaborador.");
|
||||
return;
|
||||
}
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setScheduleScope("me")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("specific")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("all")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
|
||||
</div>
|
||||
|
||||
{scheduleScope === "specific" && (
|
||||
<div style={{ marginTop: '15px', width: '100%' }}>
|
||||
<select
|
||||
value={targetEmployeeId || ""}
|
||||
onChange={(e) => setTargetEmployeeId(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '12px', borderRadius: '8px',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
|
||||
outline: 'none', fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
|
||||
{allEmployees.map((emp: any) => (
|
||||
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
|
||||
{emp.firstName} {emp.lastName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="Fecha de la Excepción"
|
||||
description="¿En qué fecha deseas aplicar este horario distinto?"
|
||||
onNext={handleNext}
|
||||
disableNext={!overrideDate}
|
||||
>
|
||||
<div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
|
||||
<input
|
||||
type="date"
|
||||
value={overrideDate}
|
||||
onChange={(e) => setOverrideDate(e.target.value)}
|
||||
style={{
|
||||
padding: '12px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="Horario Especial"
|
||||
description="¿A qué hora empieza y termina la jornada para este día en particular?"
|
||||
onNext={handleNext}
|
||||
disableNext={!openTime || !closeTime}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
|
||||
<input
|
||||
type="time"
|
||||
value={openTime}
|
||||
onChange={(e) => setOpenTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
|
||||
<input
|
||||
type="time"
|
||||
value={closeTime}
|
||||
onChange={(e) => setCloseTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="Descansos"
|
||||
description="¿Habrá algún horario de descanso en este día especial?"
|
||||
onNext={() => {
|
||||
if (hasBreak) {
|
||||
handleNext();
|
||||
} else {
|
||||
handleOverrideScheduleSubmit();
|
||||
}
|
||||
}}
|
||||
disableNext={hasBreak === null}
|
||||
nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Excepción")}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
|
||||
<div
|
||||
onClick={() => setHasBreak(true)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Sí, hay descanso
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setHasBreak(false)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
No, de corrido
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="Horario de Descanso"
|
||||
description="¿De qué hora a qué hora no estarán disponibles en este día?"
|
||||
onNext={handleOverrideScheduleSubmit}
|
||||
disableNext={!breakStart || !breakEnd || isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar Excepción"}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
|
||||
<input
|
||||
type="time"
|
||||
value={breakStart}
|
||||
onChange={(e) => setBreakStart(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
|
||||
<input
|
||||
type="time"
|
||||
value={breakEnd}
|
||||
onChange={(e) => setBreakEnd(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import React from "react";
|
||||
import QrCode2Icon from "@mui/icons-material/QrCode2";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type PublicLinkFlowProps = {
|
||||
options: any;
|
||||
getPublicLink: any;
|
||||
getPublicLinkQrUrl: any;
|
||||
getSelectedOrganizationSlug: any;
|
||||
setShowOnboardingPublicLink: any;
|
||||
setIsSuccess: any;
|
||||
router: any;
|
||||
selectedOrganization: any;
|
||||
orgName: any;
|
||||
handleCopyPublicLink: any;
|
||||
publicLinkCopied: any;
|
||||
};
|
||||
|
||||
export default function PublicLinkFlow(props: PublicLinkFlowProps) {
|
||||
const { options, getPublicLink, getPublicLinkQrUrl, getSelectedOrganizationSlug, setShowOnboardingPublicLink, setIsSuccess, router, selectedOrganization, orgName, handleCopyPublicLink, publicLinkCopied } = props;
|
||||
const isOnboardingCompletion = options?.onboardingCompletion === true;
|
||||
const publicLink = getPublicLink();
|
||||
const publicLinkQrUrl = getPublicLinkQrUrl();
|
||||
const orgSlug = getSelectedOrganizationSlug();
|
||||
|
||||
return (
|
||||
<QuestionCard
|
||||
isActive={true}
|
||||
title="Link público y código QR"
|
||||
description="Compartí este enlace para que tus clientes entren directo a la página pública de reservas de la organización. También podés usar el código QR en redes, vidriera o piezas impresas."
|
||||
onNext={() => {
|
||||
if (isOnboardingCompletion) {
|
||||
setShowOnboardingPublicLink(false);
|
||||
setIsSuccess(true);
|
||||
return;
|
||||
}
|
||||
|
||||
router.push("/admin/assistant");
|
||||
}}
|
||||
nextLabel={isOnboardingCompletion ? "Finalizar" : "Volver al asistente"}
|
||||
topAccessory={<QrCode2Icon style={{ fontSize: 52, color: "var(--wine-red)" }} />}
|
||||
>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "18px", width: "100%", maxWidth: "560px", margin: "0 auto" }}>
|
||||
<div style={{ padding: "16px", borderRadius: "14px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.75)", lineHeight: 1.5, fontSize: "14px" }}>
|
||||
Organización: <strong style={{ color: "white" }}>{selectedOrganization?.name || orgName || "Sin organización seleccionada"}</strong>
|
||||
{orgSlug && (
|
||||
<div style={{ marginTop: "6px", color: "rgba(255,255,255,0.62)", fontSize: "13px" }}>
|
||||
Slug público: <strong style={{ color: "white" }}>{orgSlug}</strong>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{publicLink ? (
|
||||
<>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", padding: "16px", borderRadius: "14px", background: "rgba(255,42,127,0.08)", border: "1px solid rgba(255,42,127,0.32)", boxShadow: "0 0 24px rgba(255,42,127,0.12)" }}>
|
||||
<span style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px", fontWeight: 600 }}>Link público</span>
|
||||
<a href={publicLink} target="_blank" rel="noopener noreferrer" style={{ color: "white", fontWeight: 700, wordBreak: "break-all", textDecoration: "none", fontSize: "16px" }}>
|
||||
{publicLink}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", gap: "10px", flexWrap: "wrap" }}>
|
||||
<button type="button" onClick={handleCopyPublicLink} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "var(--wine-red)", border: "1px solid var(--wine-red)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>
|
||||
{publicLinkCopied ? "Link copiado" : "Copiar link"}
|
||||
</button>
|
||||
<button type="button" onClick={() => window.open(publicLink, "_blank", "noopener,noreferrer")} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>
|
||||
Abrir link
|
||||
</button>
|
||||
<a href={`${publicLinkQrUrl}&download=1`} download={`turnosxpress-${orgSlug}-qr.png`} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit", textAlign: "center", textDecoration: "none", boxSizing: "border-box" }}>
|
||||
Descargar QR
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px", padding: "18px", borderRadius: "16px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)" }}>
|
||||
<div style={{ padding: "14px", borderRadius: "12px", background: "white", boxShadow: "0 4px 20px rgba(0,0,0,0.3)" }}>
|
||||
<img src={publicLinkQrUrl} width={260} height={260} alt={`Código QR para ${publicLink}`} style={{ display: "block", maxWidth: "100%", height: "auto" }} />
|
||||
</div>
|
||||
<span style={{ color: "rgba(255,255,255,0.62)", fontSize: "13px", textAlign: "center", lineHeight: 1.45 }}>
|
||||
Este QR apunta al mismo link público. Si cambiás el nombre o slug de la organización, generá y compartí el QR actualizado.
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div style={{ padding: "18px", borderRadius: "14px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.72)", textAlign: "center", lineHeight: 1.5 }}>
|
||||
No encontramos un slug para esta organización. Revisá el nombre de la organización en la configuración del perfil y volvé a intentar.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function PublicVisibilityFlow(props: Props) {
|
||||
const { isSelectedOrganizationPaidPlan, router, createdCompanyId, selectedOrganization, handleSavePublicVisibility, isCreating, orgShowPublicScores, setOrgShowPublicScores, orgShowPublicOpinions, setOrgShowPublicOpinions, orgShowPublicProfessionals, setOrgShowPublicProfessionals, servicesShowPublicScores, setServicesShowPublicScores, servicesShowPublicOpinions, setServicesShowPublicOpinions } = props;
|
||||
const renderVisibilityCheckbox = (label: string, description: string, checked: boolean, onChange: (checked: boolean) => void) => (
|
||||
<label style={{
|
||||
display: 'flex', gap: '12px', alignItems: 'flex-start', padding: '14px', borderRadius: '12px',
|
||||
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', cursor: 'pointer'
|
||||
}}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
style={{ width: '18px', height: '18px', marginTop: '2px', accentColor: 'var(--wine-red)', cursor: 'pointer' }}
|
||||
/>
|
||||
<span style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
<span style={{ color: 'white', fontWeight: 700 }}>{label}</span>
|
||||
<span style={{ color: 'rgba(255,255,255,0.65)', fontSize: '13px', lineHeight: 1.4 }}>{description}</span>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (() => {
|
||||
if (!isSelectedOrganizationPaidPlan()) {
|
||||
return (
|
||||
<QuestionCard
|
||||
isActive={true}
|
||||
title="Esta configuración requiere un plan pago"
|
||||
description="La visibilidad pública de opiniones, puntuaciones y profesionales está disponible para organizaciones con plan pago activo. El flujo seguirá visible para que puedas volver cuando actualices tu plan."
|
||||
onNext={() => router.push(createdCompanyId ? `/landing/upgrade-plan?org=${createdCompanyId}` : "/landing/pricing")}
|
||||
nextLabel="Ver planes"
|
||||
>
|
||||
<div style={{
|
||||
color: 'rgba(255,255,255,0.75)', textAlign: 'center', padding: '18px', borderRadius: '16px',
|
||||
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', lineHeight: 1.5
|
||||
}}>
|
||||
Estás configurando {selectedOrganization?.name ? <strong>{selectedOrganization.name}</strong> : "esta organización"}. Para cambiar qué opiniones, puntuaciones y profesionales se muestran públicamente, el dueño de esta organización necesita un plan pago.
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<QuestionCard
|
||||
isActive={true}
|
||||
title="Configura la visibilidad pública"
|
||||
description="Elige qué información verán tus clientes en la página pública de la organización y sus servicios. Si un valor nunca fue configurado, se considera visible por defecto."
|
||||
onNext={handleSavePublicVisibility}
|
||||
disableNext={isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '18px', width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
|
||||
<h3 style={{ color: 'white', margin: 0, fontSize: '16px' }}>Organización</h3>
|
||||
{renderVisibilityCheckbox("Mostrar puntuación pública", "Permite que los clientes vean la puntuación promedio de la organización.", orgShowPublicScores, setOrgShowPublicScores)}
|
||||
{renderVisibilityCheckbox("Mostrar opiniones públicas", "Permite que los clientes vean las opiniones recibidas por la organización.", orgShowPublicOpinions, setOrgShowPublicOpinions)}
|
||||
{renderVisibilityCheckbox("Mostrar profesionales públicos", "Permite que los clientes vean la lista de profesionales de la organización.", orgShowPublicProfessionals, setOrgShowPublicProfessionals)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
|
||||
<h3 style={{ color: 'white', margin: 0, fontSize: '16px' }}>Servicios</h3>
|
||||
{renderVisibilityCheckbox("Mostrar puntuación pública de servicios", "Aplica este valor a todos los servicios de la organización.", servicesShowPublicScores, setServicesShowPublicScores)}
|
||||
{renderVisibilityCheckbox("Mostrar opiniones públicas de servicios", "Aplica este valor a todos los servicios de la organización.", servicesShowPublicOpinions, setServicesShowPublicOpinions)}
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
})();
|
||||
|
||||
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import React from "react";
|
||||
import dayjs from "dayjs";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function ReservationPeriodFlow(props: Props) {
|
||||
const { reservationPeriodEmployeesLoading, currentStepIndex, reservationPeriodEmployeesError, allEmployees, reservationPeriodScope, setReservationPeriodScope, targetEmployeeId, setTargetEmployeeId, reservationPeriodSummary, handleNext, reservationPeriodDuration, setReservationPeriodDuration, reservationPeriodOptions, handleExtendReservationPeriods, isCreating, selectedOrganization, orgName } = props;
|
||||
|
||||
if (reservationPeriodEmployeesLoading) {
|
||||
return <QuestionCard isActive={currentStepIndex === 0} title="Cargando colaboradores" description="Estamos buscando los colaboradores disponibles para extender el período de reservas." disableNext nextLabel="Cargando..."><div /></QuestionCard>;
|
||||
}
|
||||
|
||||
if (reservationPeriodEmployeesError || allEmployees.length === 0) {
|
||||
return <QuestionCard isActive={currentStepIndex === 0} title="No pudimos preparar la extensión" description={reservationPeriodEmployeesError || "No encontramos colaboradores activos para extender el período de reservas."} disableNext nextLabel="Extensión bloqueada"><div /></QuestionCard>;
|
||||
}
|
||||
|
||||
const needsEmployeeSelection = allEmployees.length > 1 && reservationPeriodScope === "employee";
|
||||
const selectedEmployee = allEmployees.find((employee: any) => String(employee.id || employee._id || employee.employeeId) === String(targetEmployeeId));
|
||||
const reservationPeriodEmployees = reservationPeriodSummary?.employees || [];
|
||||
const getReservationPeriodEmployeeSummary = (employee: any) => {
|
||||
const employeeKey = employee.id || employee._id || employee.employeeId;
|
||||
return reservationPeriodEmployees.find((summary: any) => String(summary.employeeId) === String(employeeKey));
|
||||
};
|
||||
const getReservationPeriodStatus = (employee: any) => {
|
||||
const summary = getReservationPeriodEmployeeSummary(employee);
|
||||
const daysRemaining = summary?.daysRemaining;
|
||||
const safeDaysRemaining = typeof daysRemaining === "number" ? Math.max(daysRemaining, 0) : 0;
|
||||
const progress = Math.min(Math.round((safeDaysRemaining / 30) * 100), 100);
|
||||
const color = !summary?.isOpen || safeDaysRemaining === 0 ? "#ef4444" : safeDaysRemaining <= 7 ? "#f59e0b" : "#22c55e";
|
||||
|
||||
let label = "Sin período abierto";
|
||||
if (summary?.isOpen && typeof daysRemaining === "number") {
|
||||
if (daysRemaining < 0) label = "Vencido";
|
||||
else if (daysRemaining === 1) label = "1 día restante";
|
||||
else label = `${daysRemaining} días restantes`;
|
||||
} else if (typeof daysRemaining === "number" && daysRemaining < 0) {
|
||||
label = "Vencido";
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
color,
|
||||
progress,
|
||||
openUntilLabel: summary?.currentOpenUntil ? `Abierto hasta ${dayjs(summary.currentOpenUntil).format("D [de] MMMM")}` : null
|
||||
};
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{allEmployees.length > 1 && (
|
||||
<QuestionCard isActive={currentStepIndex === 0} title="Elegí a quién extenderle el período" description="Podés abrir reservas para todos los colaboradores o para uno específico." onNext={handleNext} disableNext={!reservationPeriodScope || (needsEmployeeSelection && !targetEmployeeId)} nextLabel="Siguiente">
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
|
||||
<SelectionCard selected={reservationPeriodScope === "all"} onClick={() => { setReservationPeriodScope("all"); setTargetEmployeeId(null); }} title="Todos los colaboradores" description="Extiende el período de reservas para todo el equipo." />
|
||||
<SelectionCard selected={reservationPeriodScope === "employee"} onClick={() => setReservationPeriodScope("employee")} title="Un colaborador específico" description="Elige una persona del equipo." />
|
||||
{needsEmployeeSelection && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "8px", marginTop: "8px" }}>
|
||||
{allEmployees.map((employee: any) => {
|
||||
const employeeKey = employee.id || employee._id || employee.employeeId;
|
||||
const isSelected = String(targetEmployeeId) === String(employeeKey);
|
||||
const periodStatus = getReservationPeriodStatus(employee);
|
||||
return (
|
||||
<div key={employeeKey} onClick={() => setTargetEmployeeId(employeeKey)} style={{ padding: "12px 14px", borderRadius: "10px", cursor: "pointer", background: isSelected ? "rgba(255,42,127,0.18)" : "rgba(255,255,255,0.04)", border: `1px solid ${isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white" }}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", gap: "12px", alignItems: "flex-start" }}>
|
||||
<span style={{ fontWeight: 600 }}>{employee.fullName || `${employee.firstName || ""} ${employee.lastName || ""}`.trim() || employee.email || "Colaborador"}</span>
|
||||
<span style={{ color: periodStatus.color, fontSize: "12px", fontWeight: 700, whiteSpace: "nowrap" }}>{periodStatus.label}</span>
|
||||
</div>
|
||||
<div style={{ height: "7px", borderRadius: "999px", background: "rgba(255,255,255,0.12)", overflow: "hidden" }}>
|
||||
<div style={{ width: `${periodStatus.progress}%`, minWidth: periodStatus.progress > 0 ? "8px" : 0, height: "100%", borderRadius: "999px", background: periodStatus.color, transition: "width 0.2s ease" }} />
|
||||
</div>
|
||||
{periodStatus.openUntilLabel && <span style={{ color: "rgba(255,255,255,0.62)", fontSize: "12px" }}>{periodStatus.openUntilLabel}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
)}
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === (allEmployees.length > 1 ? 1 : 0)} title="Elegí cuánto extender" description="Abriremos un nuevo bloque continuo desde el último día actualmente disponible." onNext={handleNext} disableNext={!reservationPeriodDuration} nextLabel="Siguiente">
|
||||
<div style={{ display: "flex", gap: "10px", flexWrap: "wrap", width: "100%", justifyContent: "center" }}>
|
||||
{reservationPeriodOptions.map((option: any) => {
|
||||
const isSelected = reservationPeriodDuration?.unit === option.unit && reservationPeriodDuration.value === option.value;
|
||||
return <div key={`${option.unit}-${option.value}`} onClick={() => setReservationPeriodDuration({ unit: option.unit, value: option.value })} style={{ padding: "12px 24px", borderRadius: "12px", cursor: "pointer", background: isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.05)", border: `2px solid ${isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white", fontWeight: isSelected ? "bold" : "normal", transition: "all 0.2s ease", fontSize: "16px" }}>{option.label}</div>;
|
||||
})}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={currentStepIndex === (allEmployees.length > 1 ? 2 : 1)} title="Confirmar extensión" description="Revisá la selección antes de abrir el nuevo período de reservas." onNext={handleExtendReservationPeriods} disableNext={isCreating || reservationPeriodEmployeesLoading || Boolean(reservationPeriodEmployeesError) || allEmployees.length === 0 || !reservationPeriodScope || !reservationPeriodDuration || (reservationPeriodScope === "employee" && !targetEmployeeId)} nextLabel={isCreating ? "Extendiendo..." : "Extender período"}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)", color: "white" }}>
|
||||
<SummaryLine label="Organización" value={selectedOrganization?.name || orgName} />
|
||||
<SummaryLine label="Aplicar a" value={reservationPeriodScope === "all" ? "Todos los colaboradores" : (selectedEmployee?.fullName || selectedEmployee?.email || "Colaborador seleccionado")} />
|
||||
<SummaryLine label="Duración" value={reservationPeriodOptions.find((option: any) => option.unit === reservationPeriodDuration?.unit && option.value === reservationPeriodDuration.value)?.label} />
|
||||
{reservationPeriodSummary?.worstDaysRemaining !== null && reservationPeriodSummary?.worstDaysRemaining !== undefined && (
|
||||
<div style={{ color: "rgba(255,255,255,0.7)", fontSize: "13px" }}>Menor disponibilidad actual: {reservationPeriodSummary.worstDaysRemaining} días restantes.</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectionCard({ selected, onClick, title, description }: Props) {
|
||||
return <div onClick={onClick} style={{ padding: "18px", borderRadius: "12px", cursor: "pointer", background: selected ? "var(--wine-red)" : "rgba(255,255,255,0.05)", border: `2px solid ${selected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white", textAlign: "center", transition: "all 0.2s ease" }}><h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: selected ? "bold" : "normal" }}>{title}</h4><p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>{description}</p></div>;
|
||||
}
|
||||
|
||||
function SummaryLine({ label, value }: Props) {
|
||||
return <div><div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>{label}</div><div style={{ fontWeight: 700 }}>{value}</div></div>;
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
import QuestionInput from "../../QuestionCard/QuestionInput";
|
||||
import style from "../StepEngine.module.css";
|
||||
|
||||
type Props = any;
|
||||
|
||||
const DAY_LABELS = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
|
||||
const getDayLabel = (day: number) => DAY_LABELS[day];
|
||||
|
||||
export default function SetupCollaboratorFlow(props: Props) {
|
||||
const { currentStepIndex, collaboratorToSetup, setupMissingServices, setupMissingSchedules, setupSelectedServices, setSetupSelectedServices, setupAvailableServices, workingDaysMode, setWorkingDaysMode, customDays, setCustomDays, unifiedCustomSchedule, setUnifiedCustomSchedule, customSchedulesMap, setCustomSchedulesMap, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleSetupIntroNext, handleSetupServicesNext, handleSetupSchedulesNext } = props;
|
||||
|
||||
const canProceed = () => {
|
||||
if (!workingDaysMode) return false;
|
||||
if (workingDaysMode === "custom") {
|
||||
if (customDays.length === 0) return false;
|
||||
if (unifiedCustomSchedule === null) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
if (currentStepIndex === 0) {
|
||||
return (
|
||||
<QuestionCard isActive={true} title="Configuración de Colaborador" description={`El colaborador ${collaboratorToSetup?.name || ""} requiere tu atención para comenzar a recibir reservas.`} step={1} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={handleSetupIntroNext} nextLabel="Comenzar Configuración">
|
||||
<div style={{ padding: "30px", background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', border: '1px solid var(--wine-red)', borderRadius: '15px', color: 'white', textAlign: 'center', margin: '15px 0' }}>
|
||||
<div style={{ fontSize: '40px', marginBottom: '10px' }}>⚠️</div>
|
||||
<p style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '15px' }}>Hemos detectado que a este colaborador le falta:</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', alignItems: 'center', marginBottom: '20px' }}>
|
||||
{setupMissingServices && <MissingBadge icon="✂️" label="Servicios asignados" />}
|
||||
{setupMissingSchedules && <MissingBadge icon="🕒" label="Horarios de atención" />}
|
||||
</div>
|
||||
<p style={{ opacity: 0.8, fontSize: '14px' }}>Te guiaremos paso a paso para configurarlo rápidamente.</p>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
|
||||
if (currentStepIndex === 1) {
|
||||
return (
|
||||
<QuestionCard isActive={true} title="Asignación de Servicios" description="Selecciona los servicios que este colaborador podrá realizar." step={2} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={handleSetupServicesNext} nextLabel="Guardar y Continuar" disableNext={isCreating}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
|
||||
{setupAvailableServices.map((service: any) => {
|
||||
const serviceId = service.id || service._id;
|
||||
const selected = setupSelectedServices.includes(serviceId);
|
||||
return (
|
||||
<div key={serviceId} onClick={() => setSetupSelectedServices((prev: string[]) => prev.includes(serviceId) ? prev.filter(i => i !== serviceId) : [...prev, serviceId])} style={{ padding: "15px", borderRadius: "10px", background: selected ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${selected ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<div>
|
||||
<div style={{ color: "#fff", fontWeight: "bold" }}>{service.name}</div>
|
||||
<div style={{ color: "rgba(255,255,255,0.6)", fontSize: "13px" }}>{service.duration} min - ${service.price}</div>
|
||||
</div>
|
||||
{selected && <div style={{ color: "#fff" }}>✓</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{setupAvailableServices.length === 0 && <div style={{ color: "rgba(255,255,255,0.6)" }}>No hay servicios creados en la organización.</div>}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
|
||||
if (currentStepIndex === 2) {
|
||||
return (
|
||||
<QuestionCard isActive={true} title="Horarios de Atención" description="¿En qué días y horarios trabajará este colaborador?" step={setupMissingServices ? 3 : 2} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={() => handleSetupSchedulesNext(canProceed)} nextLabel="Guardar Horarios" disableNext={isCreating || !canProceed()}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginBottom: "20px" }}>
|
||||
<ModeCard active={workingDaysMode === "mon-fri"} onClick={() => setWorkingDaysMode("mon-fri")} title="Lunes a Viernes" description="Horario comercial estándar" />
|
||||
<ModeCard active={workingDaysMode === "mon-sat"} onClick={() => setWorkingDaysMode("mon-sat")} title="Lunes a Sábado" description="Jornada extendida" />
|
||||
<ModeCard active={workingDaysMode === "mon-sun"} onClick={() => setWorkingDaysMode("mon-sun")} title="Todos los días" description="Lunes a Domingo" />
|
||||
<ModeCard active={workingDaysMode === "custom"} onClick={() => setWorkingDaysMode("custom")} title="Otros / Personalizado" description="Selecciona días específicos y horarios variables" />
|
||||
</div>
|
||||
|
||||
{workingDaysMode === "custom" && (
|
||||
<div style={{ marginBottom: "25px", padding: "20px", background: "rgba(0,0,0,0.2)", borderRadius: "15px" }}>
|
||||
<h4 style={{ color: "white", marginBottom: "15px" }}>Selecciona los días:</h4>
|
||||
<div style={{ display: "flex", flexWrap: "wrap", gap: "10px", marginBottom: "20px" }}>
|
||||
{[1,2,3,4,5,6,0].map(day => (
|
||||
<div key={day} onClick={() => setCustomDays((prev: number[]) => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day].sort())} style={{ padding: "8px 16px", borderRadius: "20px", cursor: "pointer", background: customDays.includes(day) ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white", fontWeight: customDays.includes(day) ? "bold" : "normal", transition: "all 0.2s", border: `1px solid ${customDays.includes(day) ? "var(--wine-red)" : "transparent"}` }}>
|
||||
{getDayLabel(day)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{customDays.length > 0 && (
|
||||
<div style={{ marginTop: "20px" }}>
|
||||
<h4 style={{ color: "white", marginBottom: "15px", fontSize: "15px" }}>¿Utiliza el mismo horario para todos estos días?</h4>
|
||||
<div style={{ display: "flex", gap: "10px" }}>
|
||||
<button className={style.primaryButton} style={{ flex: 1, background: unifiedCustomSchedule === true ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }} onClick={() => setUnifiedCustomSchedule(true)}>Sí, el mismo</button>
|
||||
<button className={style.primaryButton} style={{ flex: 1, background: unifiedCustomSchedule === false ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }} onClick={() => setUnifiedCustomSchedule(false)}>No, personalizar por día</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{((workingDaysMode && workingDaysMode !== "custom") || (workingDaysMode === "custom" && unifiedCustomSchedule === true && customDays.length > 0)) && (
|
||||
<TimeSettings openTime={openTime} setOpenTime={setOpenTime} closeTime={closeTime} setCloseTime={setCloseTime} hasBreak={hasBreak} setHasBreak={setHasBreak} breakStart={breakStart} setBreakStart={setBreakStart} breakEnd={breakEnd} setBreakEnd={setBreakEnd} />
|
||||
)}
|
||||
|
||||
{workingDaysMode === "custom" && unifiedCustomSchedule === false && customDays.length > 0 && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
|
||||
{customDays.map((day: number) => {
|
||||
const ds = customSchedulesMap[day] || { openTime: "09:00", closeTime: "18:00", hasBreak: false, breakStart: "13:00", breakEnd: "14:00" };
|
||||
const updateDS = (updates: any) => setCustomSchedulesMap((prev: any) => ({...prev, [day]: { ...ds, ...updates } }));
|
||||
return <CustomDaySettings key={day} day={day} ds={ds} updateDS={updateDS} />;
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function MissingBadge({ icon, label }: Props) {
|
||||
return <div style={{ background: 'rgba(0,0,0,0.3)', padding: '10px 20px', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '10px' }}><span>{icon}</span> {label}</div>;
|
||||
}
|
||||
|
||||
function ModeCard({ active, onClick, title, description }: Props) {
|
||||
return <div style={{ padding: "15px", borderRadius: "10px", background: active ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${active ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }} onClick={onClick}><h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>{title}</h4><p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>{description}</p></div>;
|
||||
}
|
||||
|
||||
function TimeSettings(props: Props) {
|
||||
const { openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd } = props;
|
||||
return (
|
||||
<div className={style.timeSettingsContainer}>
|
||||
<h4 style={{ color: "rgba(255,255,255,0.9)", marginBottom: "15px" }}>Horario de apertura y cierre</h4>
|
||||
<div style={{ display: "flex", gap: "20px", marginBottom: "20px" }}>
|
||||
<QuestionInput label="Hora de Apertura" type="time" value={openTime} onChange={(e) => setOpenTime(e.target.value)} />
|
||||
<QuestionInput label="Hora de Cierre" type="time" value={closeTime} onChange={(e) => setCloseTime(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "20px" }}>
|
||||
<input type="checkbox" id="hasBreak" checked={hasBreak === true} onChange={(e) => setHasBreak(e.target.checked)} style={{ width: "18px", height: "18px" }} />
|
||||
<label htmlFor="hasBreak" style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer" }}>Tiene horario de descanso (almuerzo)</label>
|
||||
</div>
|
||||
{hasBreak && <div style={{ display: "flex", gap: "20px", marginBottom: "20px", padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "10px" }}><QuestionInput label="Inicio de Descanso" type="time" value={breakStart} onChange={(e) => setBreakStart(e.target.value)} /><QuestionInput label="Fin de Descanso" type="time" value={breakEnd} onChange={(e) => setBreakEnd(e.target.value)} /></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomDaySettings({ day, ds, updateDS }: Props) {
|
||||
return (
|
||||
<div style={{ padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "15px", border: "1px solid rgba(255,255,255,0.1)" }}>
|
||||
<h4 style={{ color: "white", marginBottom: "15px", borderBottom: "1px solid rgba(255,255,255,0.1)", paddingBottom: "10px" }}>Configuración para {getDayLabel(day)}</h4>
|
||||
<div style={{ display: "flex", gap: "20px", marginBottom: "15px" }}>
|
||||
<QuestionInput label="Apertura" type="time" value={ds.openTime} onChange={(e) => updateDS({ openTime: e.target.value })} />
|
||||
<QuestionInput label="Cierre" type="time" value={ds.closeTime} onChange={(e) => updateDS({ closeTime: e.target.value })} />
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "15px" }}>
|
||||
<input type="checkbox" id={`hasBreak_${day}`} checked={ds.hasBreak === true} onChange={(e) => updateDS({ hasBreak: e.target.checked })} style={{ width: "18px", height: "18px" }} />
|
||||
<label htmlFor={`hasBreak_${day}`} style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer", fontSize: "14px" }}>Descanso</label>
|
||||
</div>
|
||||
{ds.hasBreak && <div style={{ display: "flex", gap: "20px", padding: "10px", background: "rgba(0,0,0,0.3)", borderRadius: "10px" }}><QuestionInput label="Inicio" type="time" value={ds.breakStart} onChange={(e) => updateDS({ breakStart: e.target.value })} /><QuestionInput label="Fin" type="time" value={ds.breakEnd} onChange={(e) => updateDS({ breakEnd: e.target.value })} /></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function UpdateScheduleFlow(props: Props) {
|
||||
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Actualizar Horarios"
|
||||
description="¿A quiénes quieres aplicar esta nueva rutina de horarios?"
|
||||
onNext={() => {
|
||||
if (scheduleScope === "specific" && !targetEmployeeId) {
|
||||
alert("Por favor selecciona un colaborador.");
|
||||
return;
|
||||
}
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setScheduleScope("me")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
|
||||
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina únicamente a tus horarios.</p>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("specific")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
|
||||
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina a un integrante específico de tu equipo.</p>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("all")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
|
||||
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Sobrescribe masivamente los horarios de todo tu equipo.</p>
|
||||
</div>
|
||||
|
||||
{scheduleScope === "specific" && (
|
||||
<div style={{ marginTop: '15px', width: '100%' }}>
|
||||
<label style={{ color: 'white', display: 'block', marginBottom: '8px', fontSize: '14px' }}>Selecciona el colaborador:</label>
|
||||
<select
|
||||
value={targetEmployeeId || ""}
|
||||
onChange={(e) => setTargetEmployeeId(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '12px', borderRadius: '8px',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
|
||||
outline: 'none', fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
|
||||
{allEmployees.map((emp: any) => (
|
||||
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
|
||||
{emp.firstName} {emp.lastName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="Días de Trabajo"
|
||||
description="¿Qué días aplicará esta rutina?"
|
||||
onNext={handleNext}
|
||||
disableNext={!workingDaysMode}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
{[
|
||||
{ id: 'mon-fri', label: 'Lunes a Viernes' },
|
||||
{ id: 'mon-sat', label: 'Lunes a Sábado' },
|
||||
{ id: 'mon-sun', label: 'Todos los días' }
|
||||
].map(mode => (
|
||||
<div
|
||||
key={mode.id}
|
||||
onClick={() => setWorkingDaysMode(mode.id)}
|
||||
style={{
|
||||
padding: '15px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
background: workingDaysMode === mode.id ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${workingDaysMode === mode.id ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white',
|
||||
textAlign: 'center',
|
||||
transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{mode.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="Horario Comercial"
|
||||
description="¿A qué hora empieza y termina la jornada laboral?"
|
||||
onNext={handleNext}
|
||||
disableNext={!openTime || !closeTime}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
|
||||
<input
|
||||
type="time"
|
||||
value={openTime}
|
||||
onChange={(e) => setOpenTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
|
||||
<input
|
||||
type="time"
|
||||
value={closeTime}
|
||||
onChange={(e) => setCloseTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="Descansos"
|
||||
description="¿Tienen un horario de corte al mediodía o descanso?"
|
||||
onNext={() => {
|
||||
if (hasBreak) {
|
||||
handleNext();
|
||||
} else {
|
||||
handleUpdateScheduleSubmit();
|
||||
}
|
||||
}}
|
||||
disableNext={hasBreak === null}
|
||||
nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Horarios")}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
|
||||
<div
|
||||
onClick={() => setHasBreak(true)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Sí, hay descanso
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setHasBreak(false)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
No, horario corrido
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 4}
|
||||
title="Horario de Descanso"
|
||||
description="¿De qué hora a qué hora no estarán disponibles?"
|
||||
onNext={handleUpdateScheduleSubmit}
|
||||
disableNext={!breakStart || !breakEnd || isCreating}
|
||||
nextLabel={isCreating ? "Guardando..." : "Guardar Horarios"}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
|
||||
<input
|
||||
type="time"
|
||||
value={breakStart}
|
||||
onChange={(e) => setBreakStart(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
|
||||
<input
|
||||
type="time"
|
||||
value={breakEnd}
|
||||
onChange={(e) => setBreakEnd(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import React from "react";
|
||||
import WhatsAppIcon from "@mui/icons-material/WhatsApp";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type WhatsAppBotFlowProps = {
|
||||
wapPhase: any;
|
||||
wapAction: any;
|
||||
wapView: any;
|
||||
wapQr: any;
|
||||
wapError: any;
|
||||
createdCompanyId: any;
|
||||
router: any;
|
||||
loadWapView: any;
|
||||
handleWapAssignServer: any;
|
||||
handleWapCreateBot: any;
|
||||
handleWapQuitServer: any;
|
||||
handleWapStartBot: any;
|
||||
handleWapDeleteBot: any;
|
||||
handleWapVerifyQr: any;
|
||||
handleWapStopBot: any;
|
||||
getImageFromBase64: any;
|
||||
setIsSuccess: any;
|
||||
setWapPhase: any;
|
||||
setWapError: any;
|
||||
};
|
||||
|
||||
export default function WhatsAppBotFlow(props: WhatsAppBotFlowProps) {
|
||||
const { wapPhase, wapAction, wapView, wapQr, wapError, createdCompanyId, router, loadWapView, handleWapAssignServer, handleWapCreateBot, handleWapQuitServer, handleWapStartBot, handleWapDeleteBot, handleWapVerifyQr, handleWapStopBot, getImageFromBase64, setIsSuccess, setWapPhase, setWapError } = props;
|
||||
|
||||
return (
|
||||
<>
|
||||
<QuestionCard isActive={wapPhase === "intro"} title="Bot de WhatsApp" description="Vamos a configurar tu bot de WhatsApp. Esto te permitirá enviar notificaciones automáticas a tus clientes. Primero verificamos el estado actual de tu organización." onNext={loadWapView} nextLabel="Verificar estado" topAccessory={<WhatsAppIcon style={{ fontSize: 48, color: "#25D366" }} />}>
|
||||
{null}
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "plan-required"} title="Plan no compatible" description="Tu plan actual no incluye notificaciones por WhatsApp. Necesitás un plan que incluya esta funcionalidad para configurar el bot." onNext={() => router.push(`/landing/upgrade-plan?org=${createdCompanyId}`)} nextLabel="Ver planes" topAccessory={<div style={{ fontSize: 48 }}>📦</div>}>
|
||||
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5 }}>
|
||||
Actualizá tu plan para desbloquear notificaciones por WhatsApp y mejorar la comunicación con tus clientes.
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "assign-server"} title="Asignar servidor" description="Tu organización necesita un servidor de WhatsApp. Vamos a asignar uno automáticamente." onNext={handleWapAssignServer} disableNext={wapAction !== null} nextLabel={wapAction === "assign" ? "Asignando servidor..." : "Asignar servidor"} topAccessory={<div style={{ fontSize: 48 }}>🖥️</div>}>
|
||||
{wapAction === "assign" && <LoadingMessage label="Asignando servidor..." />}
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "create-bot"} title="Crear bot de WhatsApp" description={`Servidor asignado: ${wapView?.serverName || "disponible"}. Ahora vamos a crear tu bot de WhatsApp.`} onNext={handleWapCreateBot} disableNext={wapAction !== null} nextLabel={wapAction === "create" ? "Creando bot..." : "Crear bot de WhatsApp"} topAccessory={<div style={{ fontSize: 48 }}>🤖</div>}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
|
||||
{wapAction === "create" && <LoadingMessage label="Creando bot..." />}
|
||||
<SecondaryButton onClick={handleWapQuitServer} disabled={wapAction !== null} loading={wapAction === "quit"} loadingLabel="Desasignando servidor..." label="Desasignar servidor" />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "start-bot"} title="Iniciar bot" description="Tu bot de WhatsApp está creado pero detenido. Vamos a iniciarlo." onNext={handleWapStartBot} disableNext={wapAction !== null} nextLabel={wapAction === "start" ? "Iniciando bot..." : "Iniciar bot"} topAccessory={<div style={{ fontSize: 48 }}>▶️</div>}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
|
||||
{wapAction === "start" && <LoadingMessage label="Iniciando bot..." />}
|
||||
<SecondaryButton onClick={handleWapDeleteBot} disabled={wapAction !== null} loading={wapAction === "delete"} loadingLabel="Eliminando bot..." label="Eliminar bot" />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "scan-qr"} title="Escanear código QR" description="Tu bot está funcionando. Ahora necesitás vincular tu número de WhatsApp escaneando este código QR con tu teléfono." onNext={handleWapVerifyQr} disableNext={wapAction !== null} nextLabel={wapAction === "verify" ? "Verificando..." : "Ya escaneé el código"} topAccessory={<div style={{ fontSize: 48 }}>📱</div>}>
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "16px", width: "100%" }}>
|
||||
{wapQr ? (
|
||||
<div style={{ padding: "16px", borderRadius: "12px", background: "white", boxShadow: "0 4px 20px rgba(0,0,0,0.3)" }}>
|
||||
<img src={getImageFromBase64(wapQr)} width={250} height={250} alt="Escaneá el código QR" style={{ display: "block" }} />
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ width: 250, height: 250, borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "2px dashed rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", color: "rgba(255,255,255,0.5)", fontSize: "14px" }}>Cargando QR...</div>
|
||||
)}
|
||||
<div style={{ padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5, textAlign: "center", maxWidth: "350px" }}>
|
||||
Abrí WhatsApp en tu teléfono → <strong style={{ color: "white" }}>Configuración</strong> → <strong style={{ color: "white" }}>Dispositivos vinculados</strong> → <strong style={{ color: "white" }}>Vincular dispositivo</strong>
|
||||
</div>
|
||||
{wapError && <div style={{ padding: "12px 16px", borderRadius: "10px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", textAlign: "center", maxWidth: "350px" }}>{wapError}</div>}
|
||||
<SecondaryButton onClick={handleWapStopBot} disabled={wapAction !== null} loading={wapAction === "stop"} loadingLabel="Deteniendo bot..." label="Detener bot" />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "bot-ready"} title="¡Bot funcionando!" description="Tu bot de WhatsApp está conectado y funcionando correctamente. Ya puede enviar notificaciones a tus clientes." onNext={() => setIsSuccess(true)} nextLabel="Finalizar" topAccessory={<div style={{ fontSize: 48 }}>✅</div>}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
|
||||
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(74,222,128,0.08)", border: "1px solid rgba(74,222,128,0.2)", color: "#4ade80", fontSize: "13px", textAlign: "center", fontWeight: 600 }}>
|
||||
Sesión de WhatsApp activa — Bot operativo
|
||||
</div>
|
||||
<SecondaryButton onClick={handleWapStopBot} disabled={wapAction !== null} loading={wapAction === "stop"} loadingLabel="Deteniendo bot..." label="Detener bot" />
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard isActive={wapPhase === "error"} title="Error" description={wapError || "Ocurrió un error inesperado. Por favor, intentá nuevamente."} onNext={() => { setWapPhase("intro"); setWapError(null); }} nextLabel="Reintentar" topAccessory={<div style={{ fontSize: 48 }}>⚠️</div>}>
|
||||
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", lineHeight: 1.5 }}>
|
||||
Si el problema persiste, contactá al soporte de TurnosXpress.
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingMessage({ label }: { label: string }) {
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px", padding: "20px 0" }}>
|
||||
<Spinner size={36} borderWidth={3} />
|
||||
<span style={{ color: "rgba(255,255,255,0.7)", fontSize: "14px" }}>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SecondaryButton({ onClick, disabled, loading, loadingLabel, label }: any) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} disabled={disabled} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "8px", padding: "12px 20px", borderRadius: "10px", width: "100%", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.15)", color: "rgba(255,255,255,0.7)", cursor: "pointer", fontSize: "14px", fontWeight: 600, fontFamily: "inherit", transition: "all 0.2s ease", marginTop: "4px" }}>
|
||||
{loading ? <><Spinner size={18} borderWidth={2} />{loadingLabel}</> : label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function Spinner({ size, borderWidth }: { size: number; borderWidth: number }) {
|
||||
return <div style={{ width: size, height: size, border: `${borderWidth}px solid rgba(255,255,255,0.2)`, borderTopColor: "var(--wine-red)", borderRadius: "50%", animation: "spin 1s linear infinite" }} />;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export const getEmployeeId = (employee: any) => employee.id || employee._id || employee.employeeId;
|
||||
|
||||
export const getEmployeeUserId = (employee: any) => employee.userId?._id || employee.userId?.id || employee.userId;
|
||||
|
||||
export const getTargetEmployees = (
|
||||
allEmployees: any[],
|
||||
scheduleScope: "me" | "specific" | "all" | null,
|
||||
targetEmployeeId: string | null,
|
||||
sessionUserId: string
|
||||
) => {
|
||||
if (scheduleScope === "me") {
|
||||
const me = allEmployees.find((employee: any) => String(getEmployeeUserId(employee)) === String(sessionUserId));
|
||||
return me ? [me] : [];
|
||||
}
|
||||
|
||||
if (scheduleScope === "specific") {
|
||||
const specific = allEmployees.find((employee: any) => String(getEmployeeId(employee)) === String(targetEmployeeId));
|
||||
return specific ? [specific] : [];
|
||||
}
|
||||
|
||||
if (scheduleScope === "all") {
|
||||
return [...allEmployees];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export const getImageFromBase64 = (base64: string): string => {
|
||||
const base64Data = base64.includes("base64,") ? base64.split(",")[1] : base64;
|
||||
const byteCharacters = atob(base64Data);
|
||||
const byteArray = new Uint8Array(byteCharacters.length);
|
||||
for (let i = 0; i < byteCharacters.length; i++) {
|
||||
byteArray[i] = byteCharacters.charCodeAt(i);
|
||||
}
|
||||
const blob = new Blob([byteArray], { type: "image/png" });
|
||||
return URL.createObjectURL(blob);
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { getSlug } from "@core/app/helpers/Slug";
|
||||
|
||||
export const getSelectedOrganizationSlug = (selectedOrganization: any, orgName: string) => {
|
||||
return selectedOrganization?.slug || getSlug(selectedOrganization?.name || orgName || "");
|
||||
};
|
||||
|
||||
export const getPublicLink = (selectedOrganization: any, orgName: string) => {
|
||||
const slug = getSelectedOrganizationSlug(selectedOrganization, orgName);
|
||||
const publicBaseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://turnosxpress.com.ar";
|
||||
return slug ? `${publicBaseUrl.replace(/\/$/, "")}/${slug}` : "";
|
||||
};
|
||||
|
||||
export const getPublicLinkQrUrl = (selectedOrganization: any, orgName: string) => {
|
||||
const publicLink = getPublicLink(selectedOrganization, orgName);
|
||||
return publicLink ? `https://api.qrserver.com/v1/create-qr-code/?size=260x260&format=png&data=${encodeURIComponent(publicLink)}` : "";
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
type ScheduleBlock = { from: string; to: string; disabled: boolean };
|
||||
|
||||
export const getWorkingDays = (workingDaysMode: string, customDays: number[] = []) => {
|
||||
if (workingDaysMode === "mon-fri") return [1, 2, 3, 4, 5];
|
||||
if (workingDaysMode === "mon-sat") return [1, 2, 3, 4, 5, 6];
|
||||
if (workingDaysMode === "mon-sun") return [1, 2, 3, 4, 5, 6, 0];
|
||||
if (workingDaysMode === "custom") return customDays;
|
||||
return [];
|
||||
};
|
||||
|
||||
export const buildScheduleBlocks = (
|
||||
openTime: string,
|
||||
closeTime: string,
|
||||
hasBreak: boolean | null,
|
||||
breakStart: string,
|
||||
breakEnd: string
|
||||
): ScheduleBlock[] => {
|
||||
if (hasBreak) {
|
||||
return [
|
||||
{ from: openTime, to: breakStart, disabled: false },
|
||||
{ from: breakEnd, to: closeTime, disabled: false }
|
||||
];
|
||||
}
|
||||
|
||||
return [{ from: openTime, to: closeTime, disabled: false }];
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export const dayjsFromHHmm = (hhmm: string) => {
|
||||
const [h, m] = (hhmm || "00:00").split(":").map(Number);
|
||||
return dayjs().hour(h || 0).minute(m || 0).second(0).millisecond(0);
|
||||
};
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import API from "@services/Api.Service";
|
||||
|
||||
type UseNewCollaboratorHandlersDeps = {
|
||||
inviteEmail: string;
|
||||
inviteCollaborator: any | null;
|
||||
inviteRole: "admin" | "colaborador";
|
||||
createdCompanyId: string | null;
|
||||
sessionUserId: string;
|
||||
setInviteEmail: (value: string) => void;
|
||||
setInviteCollaborator: (value: any | null) => void;
|
||||
setInviteEmailError: (value: string) => void;
|
||||
setInviteRole: (value: "admin" | "colaborador") => void;
|
||||
setIsSearchingEmail: (value: boolean) => void;
|
||||
setIsCreating: (value: boolean) => void;
|
||||
setIsUpgradeRequired: (value: boolean) => void;
|
||||
setInviteFlowNotice: (value: string) => void;
|
||||
setCurrentStepIndex: (value: number) => void;
|
||||
handleNext: () => void;
|
||||
};
|
||||
|
||||
export function useNewCollaboratorHandlers({
|
||||
inviteEmail,
|
||||
inviteCollaborator,
|
||||
inviteRole,
|
||||
createdCompanyId,
|
||||
sessionUserId,
|
||||
setInviteEmail,
|
||||
setInviteCollaborator,
|
||||
setInviteEmailError,
|
||||
setInviteRole,
|
||||
setIsSearchingEmail,
|
||||
setIsCreating,
|
||||
setIsUpgradeRequired,
|
||||
setInviteFlowNotice,
|
||||
setCurrentStepIndex,
|
||||
handleNext
|
||||
}: UseNewCollaboratorHandlersDeps) {
|
||||
const handleSearchCollaboratorEmail = async () => {
|
||||
if (!inviteEmail || !inviteEmail.includes("@")) return;
|
||||
setIsSearchingEmail(true);
|
||||
setInviteEmailError("");
|
||||
setInviteCollaborator(null);
|
||||
try {
|
||||
const data = await API.post<any>("users/get-by-email", { email: inviteEmail.trim().toLowerCase() });
|
||||
if (data && (data.id || data._id)) {
|
||||
if ((data.id || data._id) === sessionUserId) {
|
||||
setInviteEmailError("No puedes invitarte a ti mismo.");
|
||||
setIsSearchingEmail(false);
|
||||
return;
|
||||
}
|
||||
setInviteCollaborator(data);
|
||||
handleNext();
|
||||
} else {
|
||||
setInviteEmailError("Usuario no registrado");
|
||||
}
|
||||
} catch (error: any) {
|
||||
setInviteEmailError("Usuario no registrado");
|
||||
} finally {
|
||||
setIsSearchingEmail(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateCollaborator = async () => {
|
||||
if (!inviteCollaborator || !createdCompanyId) return;
|
||||
setIsCreating(true);
|
||||
setInviteFlowNotice("");
|
||||
try {
|
||||
await API.post<any>("employees/create", {
|
||||
companyId: createdCompanyId,
|
||||
userId: inviteCollaborator.id || inviteCollaborator._id,
|
||||
roles: inviteRole === "admin" ? ["admin"] : [],
|
||||
hostOk: true,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
handleNext();
|
||||
} catch (error: any) {
|
||||
const errorMessage = error.desc || error.message || "Error al invitar al colaborador";
|
||||
const normalizedErrorMessage = errorMessage.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||||
if (normalizedErrorMessage.includes("limite")) {
|
||||
setIsUpgradeRequired(true);
|
||||
} else if (normalizedErrorMessage.includes("invitacion") && normalizedErrorMessage.includes("pendiente")) {
|
||||
setInviteFlowNotice("Ya se envió una invitación para que este usuario forme parte de la compañía y todavía no respondió.");
|
||||
setCurrentStepIndex(5);
|
||||
} else if (normalizedErrorMessage.includes("ya pertenece")) {
|
||||
setInviteFlowNotice("Este usuario ya pertenece a la compañía.");
|
||||
setCurrentStepIndex(6);
|
||||
} else {
|
||||
setInviteFlowNotice(errorMessage);
|
||||
setCurrentStepIndex(5);
|
||||
}
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetInviteFlow = () => {
|
||||
setInviteEmail("");
|
||||
setInviteCollaborator(null);
|
||||
setInviteEmailError("");
|
||||
setInviteRole("colaborador");
|
||||
setIsUpgradeRequired(false);
|
||||
setInviteFlowNotice("");
|
||||
setCurrentStepIndex(1);
|
||||
};
|
||||
|
||||
return {
|
||||
handleSearchCollaboratorEmail,
|
||||
handleCreateCollaborator,
|
||||
resetInviteFlow
|
||||
};
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import API from "@services/Api.Service";
|
||||
import type React from "react";
|
||||
import { NotificationChannel, ReminderRule } from "@models/NotificationPreferences.model";
|
||||
import { ALL_NOTIF_CHANNELS } from "../constants/notifications";
|
||||
|
||||
type UseNotificationsHandlersDeps = {
|
||||
createdCompanyId: string | null;
|
||||
sessionUserId: string;
|
||||
isCreating: boolean;
|
||||
notificationsScope: "org" | "client" | null;
|
||||
notifChannels: NotificationChannel[];
|
||||
notifQuietHoursActive: boolean;
|
||||
notifQuietHoursFrom: string;
|
||||
notifQuietHoursTo: string;
|
||||
notifReminderRules: ReminderRule[];
|
||||
notifSelectedClientId: string | null;
|
||||
setNotificationsScope: (value: "org" | "client") => void;
|
||||
setNotifChannels: React.Dispatch<React.SetStateAction<NotificationChannel[]>>;
|
||||
setNotifQuietHoursActive: (value: boolean) => void;
|
||||
setNotifQuietHoursFrom: (value: string) => void;
|
||||
setNotifQuietHoursTo: (value: string) => void;
|
||||
setNotifReminderRules: React.Dispatch<React.SetStateAction<ReminderRule[]>>;
|
||||
setNotifSelectedClientId: (value: string | null) => void;
|
||||
setIsCreating: (value: boolean) => void;
|
||||
handleActionSuccess: () => void;
|
||||
};
|
||||
|
||||
export function useNotificationsHandlers({
|
||||
createdCompanyId,
|
||||
sessionUserId,
|
||||
isCreating,
|
||||
notificationsScope,
|
||||
notifChannels,
|
||||
notifQuietHoursActive,
|
||||
notifQuietHoursFrom,
|
||||
notifQuietHoursTo,
|
||||
notifReminderRules,
|
||||
notifSelectedClientId,
|
||||
setNotificationsScope,
|
||||
setNotifChannels,
|
||||
setNotifQuietHoursActive,
|
||||
setNotifQuietHoursFrom,
|
||||
setNotifQuietHoursTo,
|
||||
setNotifReminderRules,
|
||||
setNotifSelectedClientId,
|
||||
setIsCreating,
|
||||
handleActionSuccess
|
||||
}: UseNotificationsHandlersDeps) {
|
||||
const toggleNotifChannel = (channel: NotificationChannel) => {
|
||||
setNotifChannels(prev =>
|
||||
prev.includes(channel) ? prev.filter(c => c !== channel) : [...prev, channel]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleNotifReminder = (minutes: number) => {
|
||||
const exists = notifReminderRules.some(r => r.offset === minutes);
|
||||
if (exists) {
|
||||
setNotifReminderRules(prev => prev.filter(r => r.offset !== minutes));
|
||||
} else {
|
||||
setNotifReminderRules(prev => [...prev, { offset: minutes, enabled: true }]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectNotifScope = (scope: "org" | "client") => {
|
||||
setNotificationsScope(scope);
|
||||
setNotifChannels([]);
|
||||
setNotifQuietHoursActive(false);
|
||||
setNotifQuietHoursFrom("22:00");
|
||||
setNotifQuietHoursTo("08:00");
|
||||
setNotifReminderRules([]);
|
||||
setNotifSelectedClientId(null);
|
||||
};
|
||||
|
||||
const handleSaveNotifications = async () => {
|
||||
if (!createdCompanyId || isCreating) return;
|
||||
if (notificationsScope === "client" && !notifSelectedClientId) return;
|
||||
setIsCreating(true);
|
||||
try {
|
||||
if (notificationsScope === "org") {
|
||||
const quietHours = notifQuietHoursActive
|
||||
? { from: notifQuietHoursFrom, to: notifQuietHoursTo }
|
||||
: null;
|
||||
await API.post<any>("notifications/policy/save", {
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId,
|
||||
defaultChannels: notifChannels,
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
quietHours: quietHours || undefined,
|
||||
reminderRules: notifReminderRules
|
||||
});
|
||||
} else if (notificationsScope === "client") {
|
||||
const preferredChannels = notifChannels as NotificationChannel[];
|
||||
const mutedChannels = ALL_NOTIF_CHANNELS.filter(c => !preferredChannels.includes(c));
|
||||
await API.post<any>("notifications/override/save", {
|
||||
clientId: notifSelectedClientId,
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId,
|
||||
preferredChannels,
|
||||
mutedChannels
|
||||
});
|
||||
}
|
||||
handleActionSuccess();
|
||||
} catch (error: any) {
|
||||
console.error("Error guardando notificaciones:", error);
|
||||
alert(error?.message || "Hubo un error al guardar las notificaciones.");
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
toggleNotifChannel,
|
||||
toggleNotifReminder,
|
||||
handleSelectNotifScope,
|
||||
handleSaveNotifications
|
||||
};
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import API from "@services/Api.Service";
|
||||
import { ReservationPeriodDuration, ReservationPeriodsSummary } from "@models/SchedulesEnabled.type";
|
||||
|
||||
type UseReservationPeriodHandlersDeps = {
|
||||
createdCompanyId: string | null;
|
||||
sessionUserId: string;
|
||||
isCreating: boolean;
|
||||
reservationPeriodScope: "employee" | "all" | null;
|
||||
reservationPeriodDuration: ReservationPeriodDuration | null;
|
||||
reservationPeriodEmployeesLoading: boolean;
|
||||
reservationPeriodEmployeesError: string | null;
|
||||
allEmployees: any[];
|
||||
targetEmployeeId: string | null;
|
||||
setIsCreating: (value: boolean) => void;
|
||||
setIsSuccess: (value: boolean) => void;
|
||||
};
|
||||
|
||||
export function useReservationPeriodHandlers({
|
||||
createdCompanyId,
|
||||
sessionUserId,
|
||||
isCreating,
|
||||
reservationPeriodScope,
|
||||
reservationPeriodDuration,
|
||||
reservationPeriodEmployeesLoading,
|
||||
reservationPeriodEmployeesError,
|
||||
allEmployees,
|
||||
targetEmployeeId,
|
||||
setIsCreating,
|
||||
setIsSuccess
|
||||
}: UseReservationPeriodHandlersDeps) {
|
||||
const handleExtendReservationPeriods = async () => {
|
||||
if (!createdCompanyId || !reservationPeriodScope || !reservationPeriodDuration || isCreating) return;
|
||||
if (reservationPeriodEmployeesLoading || reservationPeriodEmployeesError || allEmployees.length === 0) return;
|
||||
if (reservationPeriodScope === "employee" && !targetEmployeeId) return;
|
||||
|
||||
setIsCreating(true);
|
||||
try {
|
||||
await API.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/extend", {
|
||||
companyId: createdCompanyId,
|
||||
scope: reservationPeriodScope,
|
||||
employeeId: reservationPeriodScope === "employee" ? targetEmployeeId : undefined,
|
||||
duration: reservationPeriodDuration,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
setIsSuccess(true);
|
||||
} catch (error: any) {
|
||||
console.error("Error extendiendo período de reservas:", error);
|
||||
alert(error?.message || "Hubo un error al extender el período de reservas.");
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { handleExtendReservationPeriods };
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import API from "@services/Api.Service";
|
||||
|
||||
type UseWhatsAppBotHandlersDeps = {
|
||||
createdCompanyId: string | null;
|
||||
sessionUserId: string;
|
||||
organizationSubscriptions: any;
|
||||
wapAction: string | null;
|
||||
setWapAction: (value: string | null) => void;
|
||||
setWapError: (value: string | null) => void;
|
||||
setWapPhase: (value: string) => void;
|
||||
setWapQr: (value: string | null) => void;
|
||||
setWapView: (value: any) => void;
|
||||
setIsSuccess: (value: boolean) => void;
|
||||
};
|
||||
|
||||
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
export function useWhatsAppBotHandlers({
|
||||
createdCompanyId,
|
||||
sessionUserId,
|
||||
organizationSubscriptions,
|
||||
wapAction,
|
||||
setWapAction,
|
||||
setWapError,
|
||||
setWapPhase,
|
||||
setWapQr,
|
||||
setWapView,
|
||||
setIsSuccess
|
||||
}: UseWhatsAppBotHandlersDeps) {
|
||||
const loadWapView = async () => {
|
||||
if (!createdCompanyId) return;
|
||||
setWapAction("load");
|
||||
setWapError(null);
|
||||
try {
|
||||
const view = await API.post<any>("views/wap-server-view", {
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
setWapView(view);
|
||||
|
||||
const hasPlan = organizationSubscriptions?.[createdCompanyId]?.plan?.wapNotifications;
|
||||
if (!hasPlan) {
|
||||
setWapPhase("plan-required");
|
||||
} else if (!view?.serverId) {
|
||||
setWapPhase("assign-server");
|
||||
} else if (!view?.exists) {
|
||||
setWapPhase("create-bot");
|
||||
} else if (view?.runningState && !String(view.runningState).includes("Up")) {
|
||||
setWapPhase("start-bot");
|
||||
} else if (view?.runningState && String(view.runningState).includes("Up") && view?.botSession !== "ok") {
|
||||
setWapPhase("scan-qr");
|
||||
try {
|
||||
const qrData = await API.post<string>("wapserver/qr", {
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
setWapQr(qrData);
|
||||
} catch {
|
||||
setWapQr(null);
|
||||
}
|
||||
} else if (view?.runningState && String(view.runningState).includes("Up") && view?.botSession === "ok") {
|
||||
setWapPhase("bot-ready");
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error("Error loading WAP view:", err);
|
||||
setWapError(err?.message || "Error al verificar el estado del bot.");
|
||||
setWapPhase("error");
|
||||
} finally {
|
||||
setWapAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const runWapAction = async (actionName: string, endpoint: string, delayMs: number, errorMessage: string) => {
|
||||
if (!createdCompanyId || wapAction) return;
|
||||
setWapAction(actionName);
|
||||
setWapError(null);
|
||||
try {
|
||||
await API.post<any>(endpoint, {
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
await wait(delayMs);
|
||||
await loadWapView();
|
||||
} catch (err: any) {
|
||||
console.error(`Error ${actionName} WAP bot:`, err);
|
||||
setWapError(err?.message || errorMessage);
|
||||
setWapPhase("error");
|
||||
} finally {
|
||||
setWapAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleWapVerifyQr = async () => {
|
||||
if (!createdCompanyId) return;
|
||||
setWapAction("verify");
|
||||
try {
|
||||
const view = await API.post<any>("views/wap-server-view", {
|
||||
companyId: createdCompanyId,
|
||||
sessionUser: sessionUserId
|
||||
});
|
||||
setWapView(view);
|
||||
if (view?.botSession === "ok") {
|
||||
setIsSuccess(true);
|
||||
} else {
|
||||
setWapError("Aún no se detectó la conexión. Asegurate de haber escaneado el QR y volvé a intentar.");
|
||||
}
|
||||
} catch (err: any) {
|
||||
setWapError(err?.message || "Error al verificar la conexión.");
|
||||
} finally {
|
||||
setWapAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
loadWapView,
|
||||
handleWapAssignServer: () => runWapAction("assign", "wapserver/assign", 2000, "Error al asignar el servidor."),
|
||||
handleWapCreateBot: () => runWapAction("create", "wapserver/create", 5000, "Error al crear el bot."),
|
||||
handleWapStartBot: () => runWapAction("start", "wapserver/start", 3000, "Error al iniciar el bot."),
|
||||
handleWapStopBot: () => runWapAction("stop", "wapserver/stop", 2000, "Error al detener el bot."),
|
||||
handleWapDeleteBot: () => runWapAction("delete", "wapserver/delete", 3000, "Error al eliminar el bot."),
|
||||
handleWapQuitServer: () => runWapAction("quit", "wapserver/quit", 2000, "Error al desasignar el servidor."),
|
||||
handleWapVerifyQr
|
||||
};
|
||||
}
|
||||
@@ -10,7 +10,8 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.organizationHeader div {
|
||||
.organizationHeaderBanner {
|
||||
position: relative;
|
||||
border: solid 1px var(--gray-dark);
|
||||
border-radius: 0px;
|
||||
width: 100%;
|
||||
@@ -30,6 +31,51 @@
|
||||
padding-left: 15px;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
.organizationRatingSummary {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
max-width: calc(100% - 24px);
|
||||
padding: 8px 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.42);
|
||||
border-radius: 18px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.84), rgba(255, 255, 255, 0.62));
|
||||
box-shadow: 0px 10px 26px rgba(0, 0, 0, 0.22);
|
||||
color: var(--wine-black);
|
||||
white-space: nowrap;
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.organizationRatingStars :global(.MuiRating-iconFilled),
|
||||
.organizationRatingStars :global(.MuiRating-iconHover) {
|
||||
color: #f5b83b;
|
||||
filter: drop-shadow(0px 1px 1px rgba(82, 43, 0, 0.3));
|
||||
}
|
||||
|
||||
.organizationRatingText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.organizationRatingText strong {
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.organizationRatingText span {
|
||||
color: rgba(35, 26, 31, 0.72);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 801px) {
|
||||
@@ -44,7 +90,8 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.organizationHeader div {
|
||||
.organizationHeaderBanner {
|
||||
position: relative;
|
||||
border: solid 1px var(--gray-dark);
|
||||
border-radius: 5px;
|
||||
width: 100%;
|
||||
@@ -62,4 +109,48 @@
|
||||
padding-left: 20px;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
.organizationRatingSummary {
|
||||
position: absolute;
|
||||
right: 24px;
|
||||
bottom: 18px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 11px 15px 11px 14px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.42);
|
||||
border-radius: 20px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.84), rgba(255, 255, 255, 0.6));
|
||||
box-shadow: 0px 14px 34px rgba(0, 0, 0, 0.22);
|
||||
color: var(--wine-black);
|
||||
white-space: nowrap;
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.organizationRatingStars :global(.MuiRating-iconFilled),
|
||||
.organizationRatingStars :global(.MuiRating-iconHover) {
|
||||
color: #f5b83b;
|
||||
filter: drop-shadow(0px 1px 1px rgba(82, 43, 0, 0.32));
|
||||
}
|
||||
|
||||
.organizationRatingText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.organizationRatingText strong {
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
.organizationRatingText span {
|
||||
color: rgba(35, 26, 31, 0.72);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
import { PublicOrganizationView } from "@core/Models/Company.model";
|
||||
import style from "./OrganizationHeader.module.css";
|
||||
import { useNavigation } from "@core/app/hooks/goto";
|
||||
import { Rating } from "@mui/material";
|
||||
import { RatingTargetSummaryResult, RatingTargetType } from "@core/Models/Ratings.model";
|
||||
import { ratingTargetSummary } from "@services/Ratings.Service";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface OrganizationHeaderProps {
|
||||
organization: PublicOrganizationView;
|
||||
@@ -10,12 +14,38 @@ export interface OrganizationHeaderProps {
|
||||
export default function OrganizationHeader(props: OrganizationHeaderProps) {
|
||||
const { organization } = props;
|
||||
const { goTo } = useNavigation();
|
||||
const [ratingSummary, setRatingSummary] = useState<RatingTargetSummaryResult>({ averageScore: 0, totalCount: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
if (organization.showPublicScores === false) {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!organization.id) {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
ratingTargetSummary({
|
||||
targetType: RatingTargetType.COMPANY,
|
||||
targetId: organization.id,
|
||||
})
|
||||
.then((response) => {
|
||||
setRatingSummary(response);
|
||||
})
|
||||
.catch(() => {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
});
|
||||
}, [organization.id, organization.showPublicScores]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={style.organizationHeader}
|
||||
onClick={() => goTo("/landing/org/" + organization.id)}
|
||||
>
|
||||
<div
|
||||
className={style.organizationHeaderBanner}
|
||||
style={{
|
||||
...(organization.headerFile ? { backgroundImage: `url(${organization.headerFile})` } : {}),
|
||||
backgroundColor: organization.headerColor || 'transparent',
|
||||
@@ -42,6 +72,23 @@ export default function OrganizationHeader(props: OrganizationHeaderProps) {
|
||||
>
|
||||
{organization.description}
|
||||
</p>
|
||||
{organization.showPublicScores !== false && ratingSummary.totalCount > 0 && (
|
||||
<div className={style.organizationRatingSummary}>
|
||||
<Rating
|
||||
className={style.organizationRatingStars}
|
||||
value={ratingSummary.averageScore}
|
||||
precision={0.1}
|
||||
readOnly
|
||||
size="small"
|
||||
/>
|
||||
<div className={style.organizationRatingText}>
|
||||
<strong>{ratingSummary.averageScore.toFixed(1)}</strong>
|
||||
<span>
|
||||
{ratingSummary.totalCount} {ratingSummary.totalCount === 1 ? "opinión" : "opiniones"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
.professionals {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
margin: 4px 0 30px;
|
||||
}
|
||||
|
||||
.header {
|
||||
margin: 0 10px 5px;
|
||||
}
|
||||
|
||||
.header h2 {
|
||||
margin: 0;
|
||||
padding-bottom: 10px;
|
||||
color: #241f1b;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.header p {
|
||||
max-width: 620px;
|
||||
margin: 0 0 10px;
|
||||
color: #6d6258;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.scroller {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
width: 100%;
|
||||
padding: 0 10px 12px;
|
||||
overflow-x: auto;
|
||||
cursor: grab;
|
||||
scroll-padding-left: 10px;
|
||||
scroll-snap-type: x mandatory;
|
||||
scrollbar-width: thin;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.dragging {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
flex: 0 0 min(300px, calc(100vw - 40px));
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: 116px;
|
||||
padding: 20px;
|
||||
border: 1px solid rgba(45, 29, 21, 0.1);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
box-shadow: 0 10px 24px rgba(45, 29, 21, 0.06);
|
||||
color: inherit;
|
||||
scroll-snap-align: start;
|
||||
text-decoration: none;
|
||||
transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
border-color: rgba(116, 35, 59, 0.28);
|
||||
box-shadow: 0 14px 30px rgba(45, 29, 21, 0.1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cardBody h3 {
|
||||
overflow: hidden;
|
||||
margin: 0 0 10px;
|
||||
color: #342d27;
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rating {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.stars {
|
||||
color: #e8a533;
|
||||
font-size: 1.25rem;
|
||||
letter-spacing: 0.06em;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.score {
|
||||
color: #342d27;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.emptyRating {
|
||||
margin: 0;
|
||||
color: #8b8178;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.card {
|
||||
flex-basis: calc(100vw - 40px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type PointerEvent, type ReactElement } from "react";
|
||||
import classNames from "classnames";
|
||||
import Link from "next/link";
|
||||
import Avatar from "@components/Avatar/Avatar";
|
||||
import { PublicCompanyEmployeeView } from "@core/Models/Employees.model";
|
||||
import { RatingTargetSummaryResult, RatingTargetType } from "@core/Models/Ratings.model";
|
||||
import { findPublicCompanyEmployees } from "@services/Employees.Service";
|
||||
import { ratingTargetSummary } from "@services/Ratings.Service";
|
||||
import style from "./OrganizationProfessionals.module.css";
|
||||
|
||||
interface OrganizationProfessionalsProps {
|
||||
companyId: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
type ProfessionalWithRating = PublicCompanyEmployeeView & {
|
||||
rating: RatingTargetSummaryResult | null;
|
||||
};
|
||||
|
||||
const renderStars = (score: number): string => {
|
||||
const normalizedScore = Math.min(Math.max(Math.round(score), 1), 5);
|
||||
return "★".repeat(normalizedScore) + "☆".repeat(5 - normalizedScore);
|
||||
};
|
||||
|
||||
const formatScore = (score: number): string => score.toFixed(1);
|
||||
|
||||
const getFullName = (professional: PublicCompanyEmployeeView): string => {
|
||||
return [professional.firstName, professional.lastName].filter(Boolean).join(" ").trim();
|
||||
};
|
||||
|
||||
export default function OrganizationProfessionals({
|
||||
companyId,
|
||||
title = "Profesionales de la organización",
|
||||
subtitle = "Conocé a quienes atienden y sus opiniones.",
|
||||
className,
|
||||
}: OrganizationProfessionalsProps): ReactElement | null {
|
||||
const [professionals, setProfessionals] = useState<ProfessionalWithRating[]>([]);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const scrollerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
findPublicCompanyEmployees({ companyId })
|
||||
.then(async (employees) => {
|
||||
const employeesWithRatings = await Promise.all(
|
||||
employees.map(async (employee) => {
|
||||
try {
|
||||
const rating = await ratingTargetSummary({
|
||||
targetType: RatingTargetType.EMPLOYEE,
|
||||
targetId: employee.employeeId,
|
||||
});
|
||||
|
||||
return { ...employee, rating };
|
||||
} catch {
|
||||
return { ...employee, rating: null };
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
if (active) {
|
||||
setProfessionals(employeesWithRatings);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setProfessionals([]);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [companyId]);
|
||||
|
||||
const handlePointerDown = () => {
|
||||
setIsDragging(true);
|
||||
};
|
||||
|
||||
const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const scroller = scrollerRef.current;
|
||||
|
||||
if (!isDragging || !scroller) {
|
||||
return;
|
||||
}
|
||||
|
||||
scroller.scrollLeft -= event.movementX;
|
||||
};
|
||||
|
||||
const stopDragging = () => {
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
if (professionals.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={classNames(style.professionals, className)} aria-label="Profesionales">
|
||||
<div className={style.header}>
|
||||
<h2>{title}</h2>
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
<div
|
||||
ref={scrollerRef}
|
||||
className={classNames(style.scroller, { [style.dragging]: isDragging })}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={stopDragging}
|
||||
onPointerLeave={stopDragging}
|
||||
>
|
||||
{professionals.map((professional) => {
|
||||
const fullName = getFullName(professional) || "Profesional";
|
||||
const hasRating = Boolean(professional.rating && professional.rating.totalCount > 0);
|
||||
|
||||
return (
|
||||
<Link
|
||||
className={style.card}
|
||||
href={`/landing/reviews?targetType=employee&targetId=${professional.employeeId}`}
|
||||
key={professional.employeeId}
|
||||
>
|
||||
<Avatar
|
||||
name={`professional-${professional.employeeId}`}
|
||||
src={professional.avatarUrl || fullName}
|
||||
alt={`Avatar de ${fullName}`}
|
||||
size="medium"
|
||||
border="none"
|
||||
/>
|
||||
<div className={style.cardBody}>
|
||||
<h3>{fullName}</h3>
|
||||
{hasRating ? (
|
||||
<div
|
||||
className={style.rating}
|
||||
aria-label={`${formatScore(professional.rating!.averageScore)} de 5 estrellas`}
|
||||
>
|
||||
<span className={style.stars} aria-hidden="true">
|
||||
{renderStars(professional.rating!.averageScore)}
|
||||
</span>
|
||||
<span className={style.score}>
|
||||
{formatScore(professional.rating!.averageScore)}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<p className={style.emptyRating}>Sin opiniones aún</p>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
.bannerContainer {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2rem;
|
||||
background: linear-gradient(135deg, var(--white) 0%, var(--white-dark) 100%);
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
|
||||
border: 1px solid var(--wine-lighterX2);
|
||||
margin: 2rem auto;
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.popupContainer {
|
||||
position: fixed;
|
||||
bottom: 2rem;
|
||||
right: 2rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
padding: 1.5rem;
|
||||
background: var(--white);
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 10px 40px rgba(51, 0, 128, 0.15);
|
||||
border: 1px solid var(--wine-lighterX2);
|
||||
width: 100%;
|
||||
max-width: 350px;
|
||||
z-index: 1000;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--gray-dark);
|
||||
cursor: pointer;
|
||||
padding: 5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.closeButton:hover {
|
||||
background: var(--white-dark);
|
||||
color: var(--black);
|
||||
}
|
||||
|
||||
.contentWrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
padding-right: 1.5rem;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
color: var(--wine-red);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
color: var(--wine-superdark);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.description {
|
||||
font-size: 0.95rem;
|
||||
color: var(--gray-dark);
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.ctaButton {
|
||||
display: inline-block;
|
||||
padding: 10px 24px;
|
||||
background: linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%);
|
||||
color: var(--white);
|
||||
border-radius: 12px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
font-size: 0.95rem;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
box-shadow: 0 4px 15px rgba(255, 42, 127, 0.3);
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ctaButton:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(255, 42, 127, 0.4);
|
||||
color: var(--white);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.bannerContainer {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
text-align: left;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.popupContainer {
|
||||
bottom: 1rem;
|
||||
right: 1rem;
|
||||
left: 1rem;
|
||||
max-width: calc(100% - 2rem);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useSessionStore } from "@core/Store/Sesion.Store";
|
||||
import { pendingRatingsByUser } from "@services/Ratings.Service";
|
||||
import style from "./PendingRatingsBanner.module.css";
|
||||
|
||||
interface PendingRatingsBannerProps {
|
||||
variant?: "banner" | "popup";
|
||||
delay?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PendingRatingsBanner({
|
||||
variant = "banner",
|
||||
delay = 3000,
|
||||
className = "",
|
||||
}: PendingRatingsBannerProps) {
|
||||
const SessionInfo = useSessionStore();
|
||||
const [hasPendingRatings, setHasPendingRatings] = useState(false);
|
||||
const [isVisible, setIsVisible] = useState(variant === "banner");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
if (!SessionInfo.userId) {
|
||||
setHasPendingRatings(false);
|
||||
return;
|
||||
}
|
||||
|
||||
pendingRatingsByUser({ sessionUser: SessionInfo.userId })
|
||||
.then((ratings) => {
|
||||
if (!cancelled) {
|
||||
setHasPendingRatings(ratings.length > 0);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) {
|
||||
setHasPendingRatings(false);
|
||||
}
|
||||
console.error(error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [SessionInfo.userId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasPendingRatings) {
|
||||
setIsVisible(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (variant === "banner") {
|
||||
setIsVisible(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setIsVisible(true);
|
||||
}, delay);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [variant, delay, hasPendingRatings]);
|
||||
|
||||
if (!SessionInfo.userId || !hasPendingRatings) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const containerClassName = [variant === "banner" ? style.bannerContainer : style.popupContainer, className]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<button onClick={() => setIsVisible(false)} className={style.closeButton} aria-label="Cerrar">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<div className={style.contentWrapper}>
|
||||
<span className={style.eyebrow}>Calificaciones pendientes</span>
|
||||
<h3 className={style.title}>Tenés experiencias pendientes para calificar</h3>
|
||||
<p className={style.description}>Tu opinión ayuda a mejorar las recomendaciones.</p>
|
||||
</div>
|
||||
<Link href="/landing/pending-ratings" className={style.ctaButton}>
|
||||
Calificar ahora
|
||||
</Link>
|
||||
</>
|
||||
);
|
||||
|
||||
if (variant === "banner") {
|
||||
return isVisible ? <div className={containerClassName}>{content}</div> : null;
|
||||
}
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isVisible && (
|
||||
<motion.div
|
||||
className={containerClassName}
|
||||
initial={{ opacity: 0, y: 50, scale: 0.95 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: 50, scale: 0.95 }}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 25 }}
|
||||
>
|
||||
{content}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { PublicServiceView } from "@models/Service.model";
|
||||
|
||||
import style from "./style.module.css";
|
||||
import { getServiceImage } from "@core/helpers/getServiceImage";
|
||||
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
|
||||
|
||||
export type FindResultsViewMode = "grid" | "card";
|
||||
|
||||
@@ -45,6 +46,7 @@ export default function ProductItem(props: ProductItemProps) {
|
||||
goTo(`/landing/service/${product.id}`);
|
||||
}}
|
||||
>
|
||||
<div className={style.cardImageWrap}>
|
||||
<img
|
||||
src={getServiceImage(product.image)}
|
||||
alt={product.name}
|
||||
@@ -53,17 +55,20 @@ export default function ProductItem(props: ProductItemProps) {
|
||||
width: "100%",
|
||||
height: "auto",
|
||||
borderRadius: "10px",
|
||||
display: "block",
|
||||
}}
|
||||
/>
|
||||
<h3
|
||||
style={{
|
||||
fontSize: "1.2rem",
|
||||
margin: "10px 0",
|
||||
textTransform: "capitalize",
|
||||
}}
|
||||
>
|
||||
{product.name}
|
||||
</h3>
|
||||
<ServiceRatingSummary
|
||||
serviceId={product.id}
|
||||
variant="card"
|
||||
displayMode="compact"
|
||||
showOpinionCount={false}
|
||||
enabled={product.showPublicScores !== false}
|
||||
/>
|
||||
</div>
|
||||
<div className={style.cardHeader}>
|
||||
<h3 className={style.cardTitle}>{product.name}</h3>
|
||||
</div>
|
||||
<p style={{ fontSize: "0.9rem", color: "#555" }}>{product.description}</p>
|
||||
<span
|
||||
style={{
|
||||
@@ -119,8 +124,16 @@ export default function ProductItem(props: ProductItemProps) {
|
||||
margin: "10px",
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<div className={style.itemContent}>
|
||||
<div className={style.itemHeader}>
|
||||
<h3 className={style.itemTitle}>{product.name}</h3>
|
||||
<ServiceRatingSummary
|
||||
serviceId={product.id}
|
||||
variant="row"
|
||||
showOpinionCount={false}
|
||||
enabled={product.showPublicScores !== false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
className={style.itemDescription}
|
||||
|
||||
@@ -1,3 +1,43 @@
|
||||
.cardImageWrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cardImageWrap > :not(img) {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
}
|
||||
|
||||
.cardHeader {
|
||||
margin: 10px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
font-size: 1.2rem;
|
||||
margin: 0;
|
||||
text-transform: capitalize;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.itemContent {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.itemHeader {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
margin: 10px 30px 0 0;
|
||||
}
|
||||
|
||||
.itemHeader .itemTitle {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 851px) {
|
||||
.itemTitle {
|
||||
font-size: 1rem;
|
||||
@@ -5,6 +45,10 @@
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.itemHeader .itemTitle {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.itemDescription {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
@@ -21,6 +65,10 @@
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.itemHeader .itemTitle {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.itemDescription {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
.reviewsCarousel {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
margin: 25px 0 22px;
|
||||
}
|
||||
|
||||
.header {
|
||||
margin: 0 10px 5px;
|
||||
}
|
||||
|
||||
.titleRow {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.header h2 {
|
||||
margin: 0;
|
||||
padding-bottom: 10px;
|
||||
color: #241f1b;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.viewMore {
|
||||
flex: 0 0 auto;
|
||||
margin-top: 4px;
|
||||
color: var(--wine-red);
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.viewMore:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.header p {
|
||||
max-width: 620px;
|
||||
margin: 0 0 10px;
|
||||
color: #6d6258;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.scroller {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
width: 100%;
|
||||
padding: 0 10px 12px;
|
||||
overflow-x: auto;
|
||||
cursor: grab;
|
||||
scroll-padding-left: 10px;
|
||||
scroll-snap-type: x mandatory;
|
||||
scrollbar-width: thin;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.dragging {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.reviewCard {
|
||||
display: flex;
|
||||
flex: 0 0 min(360px, calc(100vw - 40px));
|
||||
flex-direction: column;
|
||||
gap: 13px;
|
||||
min-height: 176px;
|
||||
padding: 20px;
|
||||
border: 1px solid rgba(45, 29, 21, 0.1);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
box-shadow: 0 10px 24px rgba(45, 29, 21, 0.06);
|
||||
scroll-snap-align: start;
|
||||
}
|
||||
|
||||
.rating {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.stars {
|
||||
color: #e8a533;
|
||||
font-size: 1.35rem;
|
||||
letter-spacing: 0.06em;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.score {
|
||||
color: #342d27;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.comment {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
color: #2f2924;
|
||||
font-size: 0.98rem;
|
||||
line-height: 1.58;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
color: #8b8178;
|
||||
font-size: 0.86rem;
|
||||
}
|
||||
|
||||
.authorBlock {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.author {
|
||||
overflow: hidden;
|
||||
color: #342d27;
|
||||
font-weight: 700;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.titleRow {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.reviewCard {
|
||||
flex-basis: calc(100vw - 40px);
|
||||
}
|
||||
|
||||
.footer {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type PointerEvent, type ReactElement } from "react";
|
||||
import classNames from "classnames";
|
||||
import Link from "next/link";
|
||||
import Avatar from "@components/Avatar/Avatar";
|
||||
import { RatingTargetReviewItem, RatingTargetType } from "@core/Models/Ratings.model";
|
||||
import { ratingTargetReviews } from "@services/Ratings.Service";
|
||||
import style from "./ReviewsCarousel.module.css";
|
||||
|
||||
interface ReviewsCarouselProps {
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
className?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT = 20;
|
||||
|
||||
const formatReviewDate = (date: string): string => {
|
||||
return new Intl.DateTimeFormat("es-AR", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
}).format(new Date(date));
|
||||
};
|
||||
|
||||
const renderStars = (score: number): string => {
|
||||
const normalizedScore = Math.min(Math.max(Math.round(score), 1), 5);
|
||||
return "★".repeat(normalizedScore) + "☆".repeat(5 - normalizedScore);
|
||||
};
|
||||
|
||||
const formatScore = (score: number): string => score.toFixed(1);
|
||||
|
||||
const sortReviewsByScore = (reviews: RatingTargetReviewItem[]): RatingTargetReviewItem[] => {
|
||||
return [...reviews].sort((firstReview, secondReview) => {
|
||||
if (secondReview.score !== firstReview.score) {
|
||||
return secondReview.score - firstReview.score;
|
||||
}
|
||||
|
||||
return new Date(secondReview.createdAt).getTime() - new Date(firstReview.createdAt).getTime();
|
||||
});
|
||||
};
|
||||
|
||||
export default function ReviewsCarousel({
|
||||
targetType,
|
||||
targetId,
|
||||
title = "Lo que dicen quienes ya reservaron",
|
||||
subtitle,
|
||||
className,
|
||||
limit = DEFAULT_LIMIT,
|
||||
}: ReviewsCarouselProps): ReactElement | null {
|
||||
const [reviews, setReviews] = useState<RatingTargetReviewItem[]>([]);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const scrollerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
ratingTargetReviews({ targetType, targetId, limit })
|
||||
.then((targetReviewsResult) => {
|
||||
if (active) {
|
||||
setReviews(sortReviewsByScore(targetReviewsResult.reviews.filter((review) => review.comment.trim().length > 0)));
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setReviews([]);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [targetType, targetId, limit]);
|
||||
|
||||
const handlePointerDown = () => {
|
||||
setIsDragging(true);
|
||||
};
|
||||
|
||||
const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const scroller = scrollerRef.current;
|
||||
|
||||
if (!isDragging || !scroller) {
|
||||
return;
|
||||
}
|
||||
|
||||
scroller.scrollLeft -= event.movementX;
|
||||
};
|
||||
|
||||
const stopDragging = () => {
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
if (reviews.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={classNames(style.reviewsCarousel, className)} aria-label="Opiniones">
|
||||
<div className={style.header}>
|
||||
<div className={style.titleRow}>
|
||||
<h2>{title}</h2>
|
||||
<Link className={style.viewMore} href={`/landing/reviews?targetType=${targetType}&targetId=${targetId}`}>
|
||||
Ver más
|
||||
</Link>
|
||||
</div>
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
<div
|
||||
ref={scrollerRef}
|
||||
className={classNames(style.scroller, { [style.dragging]: isDragging })}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={stopDragging}
|
||||
onPointerLeave={stopDragging}
|
||||
>
|
||||
{reviews.map((review) => (
|
||||
<article className={style.reviewCard} key={review.id}>
|
||||
<div className={style.rating} aria-label={`${formatScore(review.score)} de 5 estrellas`}>
|
||||
<span className={style.stars} aria-hidden="true">
|
||||
{renderStars(review.score)}
|
||||
</span>
|
||||
<span className={style.score}>{formatScore(review.score)}</span>
|
||||
</div>
|
||||
<p className={style.comment}>“{review.comment}”</p>
|
||||
<div className={style.footer}>
|
||||
<div className={style.authorBlock}>
|
||||
<Avatar
|
||||
name={`review-author-${review.id}`}
|
||||
src={review.author.avatarUrl || review.author.displayName}
|
||||
alt={`Avatar de ${review.author.displayName}`}
|
||||
size="small"
|
||||
border="none"
|
||||
/>
|
||||
<span className={style.author}>{review.author.displayName}</span>
|
||||
</div>
|
||||
<time dateTime={review.createdAt}>{formatReviewDate(review.createdAt)}</time>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -63,6 +63,15 @@
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
text-align: left;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.serviceHeader {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.selectableServiceItem p {
|
||||
@@ -78,3 +87,11 @@
|
||||
font-weight: 700;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.selectableServiceItem > div {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.selectableServiceItem > .serviceHeader {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import style from "./SelectableServiceItem.module.css";
|
||||
import { formatPrice } from "@helpers/Numbers";
|
||||
import { useState } from "react";
|
||||
import classNames from "classnames";
|
||||
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
|
||||
|
||||
export interface SelectableServiceItemProps {
|
||||
data: CollaboratorServiceItems;
|
||||
@@ -39,7 +40,10 @@ export default function SelectableServiceItem(
|
||||
return (
|
||||
<>
|
||||
<div className={getClassesNames()} onClick={handleClick}>
|
||||
<div className={style.serviceHeader}>
|
||||
<h1>{props.data.name}</h1>
|
||||
<ServiceRatingSummary serviceId={props.data.id} variant="row" showOpinionCount={false} />
|
||||
</div>
|
||||
<p>{props.data.description}</p>
|
||||
<span>{formatPrice(props.data.price)}</span>
|
||||
</div>
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
margin-top: auto;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
padding-top: 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.collaboratorInfo {
|
||||
|
||||
@@ -6,6 +6,7 @@ import dayjs from "dayjs";
|
||||
import "dayjs/locale/es";
|
||||
import { testContrast } from "@core/app/theme/scheduleView";
|
||||
import { formatDateLarge, formatTimeInterval } from "@core/helpers/format";
|
||||
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
|
||||
|
||||
dayjs.locale("es");
|
||||
|
||||
@@ -36,6 +37,8 @@ export default function ServiceItem(props: ServiceItemProps): React.ReactElement
|
||||
<div className={style.serviceDescription}>{props.data.serviceDescription}</div>
|
||||
)}
|
||||
|
||||
<ServiceRatingSummary serviceId={props.data.serviceId} variant="card" />
|
||||
|
||||
<div className={style.cardFooter}>
|
||||
<div className={style.collaboratorInfo}>
|
||||
<Avatar
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
.serviceRatingSummary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: fit-content;
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
border-radius: 18px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.68));
|
||||
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.12);
|
||||
color: var(--wine-black);
|
||||
white-space: nowrap;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.card {
|
||||
margin-top: 10px;
|
||||
padding: 5px 9px;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.row {
|
||||
padding: 5px 9px;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.serviceRatingStars :global(.MuiRating-iconFilled),
|
||||
.serviceRatingStars :global(.MuiRating-iconHover) {
|
||||
color: #f5b83b;
|
||||
filter: drop-shadow(0 1px 1px rgba(82, 43, 0, 0.26));
|
||||
}
|
||||
|
||||
.card .serviceRatingStars :global(.MuiRating-iconFilled),
|
||||
.card .serviceRatingStars :global(.MuiRating-iconHover),
|
||||
.row .serviceRatingStars :global(.MuiRating-iconFilled),
|
||||
.row .serviceRatingStars :global(.MuiRating-iconHover) {
|
||||
filter: none;
|
||||
}
|
||||
|
||||
.serviceRatingText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 1px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.serviceRatingText strong {
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.serviceRatingText span {
|
||||
color: rgba(35, 26, 31, 0.72);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.compact {
|
||||
gap: 4px;
|
||||
margin-top: 0;
|
||||
padding: 3px 7px 3px 6px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.58);
|
||||
background: rgba(255, 255, 255, 0.68);
|
||||
box-shadow: none;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.compact strong {
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.compactStar {
|
||||
color: #f5b83b;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
import { Rating } from "@mui/material";
|
||||
import { RatingTargetSummaryResult, RatingTargetType } from "@core/Models/Ratings.model";
|
||||
import { ratingTargetSummary } from "@services/Ratings.Service";
|
||||
import { useEffect, useState } from "react";
|
||||
import style from "./ServiceRatingSummary.module.css";
|
||||
|
||||
export interface ServiceRatingSummaryProps {
|
||||
serviceId?: string;
|
||||
variant?: "card" | "row";
|
||||
displayMode?: "default" | "compact";
|
||||
showOpinionCount?: boolean;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export default function ServiceRatingSummary(props: ServiceRatingSummaryProps): React.ReactElement | null {
|
||||
const { serviceId, variant = "card", displayMode = "default", showOpinionCount = true, enabled = true } = props;
|
||||
const [ratingSummary, setRatingSummary] = useState<RatingTargetSummaryResult>({ averageScore: 0, totalCount: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!serviceId) {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
let isMounted = true;
|
||||
|
||||
ratingTargetSummary({
|
||||
targetType: RatingTargetType.SERVICE,
|
||||
targetId: serviceId,
|
||||
})
|
||||
.then((response) => {
|
||||
if (isMounted) {
|
||||
setRatingSummary(response);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (isMounted) {
|
||||
setRatingSummary({ averageScore: 0, totalCount: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [serviceId, enabled]);
|
||||
|
||||
if (!enabled || ratingSummary.totalCount <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (displayMode === "compact") {
|
||||
return (
|
||||
<div className={`${style.serviceRatingSummary} ${style[variant]} ${style.compact}`}>
|
||||
<span className={style.compactStar} aria-hidden="true">★</span>
|
||||
<strong>{ratingSummary.averageScore.toFixed(1)}</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`${style.serviceRatingSummary} ${style[variant]}`}>
|
||||
<Rating
|
||||
className={style.serviceRatingStars}
|
||||
value={ratingSummary.averageScore}
|
||||
precision={0.1}
|
||||
readOnly
|
||||
size="small"
|
||||
/>
|
||||
<div className={style.serviceRatingText}>
|
||||
<strong>{ratingSummary.averageScore.toFixed(1)}</strong>
|
||||
{showOpinionCount && (
|
||||
<span>
|
||||
{ratingSummary.totalCount} {ratingSummary.totalCount === 1 ? "opinión" : "opiniones"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,13 +5,15 @@ import MuiSwitch from "@mui/material/Switch";
|
||||
interface SwitchProps {
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export default function Switch({ checked, onChange }: SwitchProps) {
|
||||
export default function Switch({ checked, onChange, disabled = false }: SwitchProps) {
|
||||
return (
|
||||
<ThemeProvider theme={turnosXpressTheme}>
|
||||
<MuiSwitch
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
onChange(event.target.checked);
|
||||
}}
|
||||
|
||||
@@ -96,6 +96,27 @@
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.professionalRating {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.professionalRating strong {
|
||||
font-size: 15px;
|
||||
letter-spacing: 1px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.professionalRating small {
|
||||
color: #4b5563;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.userMenuOptionsContainer {
|
||||
flex-grow: 1;
|
||||
overflow-y: auto;
|
||||
|
||||
@@ -18,6 +18,8 @@ import dayjs from "dayjs";
|
||||
import { loadOrganizationsByUser } from "@core/app/admin/org/Org.Service";
|
||||
import { MyOranizationsView } from "@core/Models/Company.model";
|
||||
import SelectOrganizationPopup from "./SelectOrganizationPopup";
|
||||
import { professionalRatingSummaryByUser } from "@core/Services/Ratings.Service";
|
||||
import { RatingTargetSummaryResult } from "@core/Models/Ratings.model";
|
||||
|
||||
export default function UserMenu(): React.ReactElement {
|
||||
const router = useRouter();
|
||||
@@ -33,6 +35,10 @@ export default function UserMenu(): React.ReactElement {
|
||||
const [clientSocket, setClientSocket] = useState<Socket | undefined>(undefined);
|
||||
const [showOrgPopup, setShowOrgPopup] = useState(false);
|
||||
const [userOrgs, setUserOrgs] = useState<MyOranizationsView[]>([]);
|
||||
const [professionalRating, setProfessionalRating] = useState<RatingTargetSummaryResult>({
|
||||
averageScore: 0,
|
||||
totalCount: 0,
|
||||
});
|
||||
useEffect(() => {
|
||||
try {
|
||||
//TODO: Comprobar si se arregla el problema...
|
||||
@@ -100,6 +106,17 @@ export default function UserMenu(): React.ReactElement {
|
||||
};
|
||||
}, [clientSocket]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SessionInfo.loged || !SessionInfo.userId) {
|
||||
setProfessionalRating({ averageScore: 0, totalCount: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
professionalRatingSummaryByUser({ sessionUser: SessionInfo.userId })
|
||||
.then(setProfessionalRating)
|
||||
.catch(() => setProfessionalRating({ averageScore: 0, totalCount: 0 }));
|
||||
}, [SessionInfo.loged, SessionInfo.userId]);
|
||||
|
||||
const toggleMenu = () => {
|
||||
menuState.setVisible(!menuState.visible);
|
||||
};
|
||||
@@ -157,6 +174,11 @@ export default function UserMenu(): React.ReactElement {
|
||||
return "/anonimus-avatar.svg";
|
||||
};
|
||||
|
||||
const getRatingStars = (score: number) => {
|
||||
const roundedScore = Math.round(score);
|
||||
return Array.from({ length: 5 }, (_, index) => (index < roundedScore ? "★" : "☆")).join("");
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={classBackgroundData} onClick={toggleMenu}></div>
|
||||
@@ -173,6 +195,14 @@ export default function UserMenu(): React.ReactElement {
|
||||
<div>
|
||||
<h1>{getUserName()}</h1>
|
||||
<span>{getUserEmail()}</span>
|
||||
{professionalRating.totalCount > 0 && (
|
||||
<div className={style.professionalRating} aria-label={`Puntaje profesional ${professionalRating.averageScore.toFixed(1)} de 5`}>
|
||||
<strong>{getRatingStars(professionalRating.averageScore)}</strong>
|
||||
<small>
|
||||
{professionalRating.averageScore.toFixed(1)} ({professionalRating.totalCount})
|
||||
</small>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={style.userMenuOptionsContainer}>
|
||||
|
||||
@@ -5,10 +5,9 @@ import ArrowForwardIcon from "@mui/icons-material/ArrowForwardIos";
|
||||
import ArrowBackwardIcon from "@mui/icons-material/ArrowBackIos";
|
||||
import HouseIcon from "@mui/icons-material/House";
|
||||
import dayjs from "dayjs";
|
||||
import weekday from "dayjs/plugin/weekday";
|
||||
import "dayjs/locale/es";
|
||||
import { getMondayWeekStart, getSundayWeekEnd } from "@core/helpers/week";
|
||||
|
||||
dayjs.extend(weekday);
|
||||
dayjs.locale("es");
|
||||
|
||||
export interface WeekInputProps {
|
||||
@@ -25,15 +24,15 @@ const WeekInput = (props: WeekInputProps) => {
|
||||
const { setStartDate } = props;
|
||||
const [fechas, setFechas] = useState<WeekInputData>({
|
||||
currentDate: dayjs().clone(),
|
||||
lunes: dayjs().clone().weekday(0),
|
||||
domingo: dayjs().clone().weekday(6),
|
||||
lunes: getMondayWeekStart(),
|
||||
domingo: getSundayWeekEnd(),
|
||||
});
|
||||
|
||||
const updateFechas = (fecha: dayjs.Dayjs) => {
|
||||
setFechas({
|
||||
currentDate: dayjs().clone(),
|
||||
lunes: fecha.clone().weekday(0),
|
||||
domingo: fecha.clone().weekday(6),
|
||||
lunes: getMondayWeekStart(fecha),
|
||||
domingo: getSundayWeekEnd(fecha),
|
||||
});
|
||||
//setStartDate(fechas.lunes.clone());
|
||||
};
|
||||
@@ -53,8 +52,8 @@ const WeekInput = (props: WeekInputProps) => {
|
||||
const fecha = dayjs().clone();
|
||||
setFechas({
|
||||
currentDate: fecha,
|
||||
lunes: fecha.clone().weekday(0),
|
||||
domingo: fecha.clone().weekday(6),
|
||||
lunes: getMondayWeekStart(fecha),
|
||||
domingo: getSundayWeekEnd(fecha),
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import AutoAwesomeIcon from "@mui/icons-material/AutoAwesome";
|
||||
import FinancialWidget from "@components/FinancialWidget/FinancialWidget";
|
||||
import PlanMetricsWidget from "@components/PlanMetricsWidget/PlanMetricsWidget";
|
||||
import PendingRepeatsCard from "@core/app/components/PendingRepeatsCard/PendingRepeatsCard";
|
||||
import PendingRatingsBanner from "@components/PendingRatingsBanner/PendingRatingsBanner";
|
||||
|
||||
function DashboardContent() {
|
||||
const { goTo } = useNavigation();
|
||||
@@ -367,6 +368,7 @@ function DashboardContent() {
|
||||
{SessionInfo.userId != "" && !displayedPlan && (
|
||||
<div className="homeCentered">No tiene una suscripción activa.</div>
|
||||
)}
|
||||
{displayedPlan && <PendingRatingsBanner variant="banner" />}
|
||||
{displayedPlan && (
|
||||
<div className={style.dashboardGrid}>
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import { ScrollToTop } from "@core/app/components/ScrollTop";
|
||||
import PendingRepeatsCard from "@core/app/components/PendingRepeatsCard/PendingRepeatsCard";
|
||||
import HeaderConfProvider from "@core/app/components/HeaderConfProvider/HeaderConfProvider";
|
||||
import EvangelizeBanner from "@components/EvangelizeBanner/EvangelizeBanner";
|
||||
import PendingRatingsBanner from "@components/PendingRatingsBanner/PendingRatingsBanner";
|
||||
import { Button, Tabs, Tab, Box } from "@mui/material";
|
||||
import { ThemeProvider } from "@emotion/react";
|
||||
import turnosXpressTheme from "@core/app/theme/turnosXpress";
|
||||
@@ -295,6 +296,8 @@ export default function MyAppointmentsPage() {
|
||||
|
||||
<EvangelizeBanner />
|
||||
|
||||
<PendingRatingsBanner />
|
||||
|
||||
<Box sx={{ width: "100%", mt: 4 }}>
|
||||
{collaboratorAppointments.length > 0 ? (
|
||||
<>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user