20 Commits

Author SHA1 Message Date
horacio 322f1d3f15 feat: agregar validaciones para el módulo ARCA según el plan de la organización 2026-09-15 11:32:11 -03:00
horacio 4460d66f39 feat: agregar validaciones de acceso a pagos y mejorar la estructura del componente de perfil fiscal 2026-09-15 11:07:12 -03:00
horacio 0e7e690ecc feat: agregar formato de fecha y hora en la notificación de actualización de perfil 2026-09-15 10:51:31 -03:00
horacio 35a132a288 feat: mejorar la legibilidad y estructura del componente OnboardingServiceFlow 2026-09-15 10:09:06 -03:00
horacio 28727e2630 feat: agregar botón para ver perfil público del servicio y mejorar el diseño de los íconos de acción 2026-09-15 10:01:20 -03:00
horacio e7a94b93f1 feat: agregar opción "Ver perfil" en el menú de OrganizationHeader 2026-09-15 09:45:43 -03:00
horacio fccaa44e9c feat: mejorar la estructura y legibilidad del componente FinancialWidget 2026-09-15 09:41:07 -03:00
horacio 421a8b5582 feat: agregar funcionalidad de edición de cabecera y colores en OrganizationHeaderEdit 2026-09-14 15:53:08 -03:00
horacio 546b66c972 feat: agregar funcionalidad de edición de imagen en el servicio y mejorar la gestión de permisos de administrador 2026-09-14 15:07:02 -03:00
horacio d96bde5963 feat: ajustar altura del popup en HeaderEditPopup 2026-09-14 14:35:54 -03:00
horacio 69e6e659e0 feat: unificar lógica de verificación de administrador y gestión del botón de edición en OrganizationPublicProfile 2026-09-14 14:26:38 -03:00
horacio 86f5422828 feat: agregar función onRefresh en HeaderEditPopup y actualizar llamada en OrganizationPublicProfile 2026-09-14 13:53:14 -03:00
horacio db6981cad5 feat: llamar a onSaved después de actualizar los colores en HeaderEditPopup 2026-09-14 13:48:06 -03:00
horacio f200f91f93 Implement code changes to enhance functionality and improve performance 2026-09-14 13:43:23 -03:00
horacio 06aac5b126 fix: popup centrado con estilo Confirm (botones sin iconos, titulo 'Personalizar')
- Dialog centrado (no bottom-sheet) con ThemeProvider
- Botones Cancelar/Guardar en texto plano (sin iconos), mismo patrón que Confirm.tsx
- Recibe valores actuales por props para no depender de store global
- Titulo dice 'Personalizar' solamente
- Cierre se hace con icono X en el title bar
2026-09-14 13:01:36 -03:00
horacio 80d9f5d428 feat: permitir a admins personalizar header desde landing pública
- Nuevo endpoint POST /companies/check-admin para verificar rol de admin
- Componente HeaderEditPopup con color pickers e image picker
- Botón flotante de editar sobre el header cuando el usuario es admin
- Popup tipo drawer inferior con formulario de personalización
- Reutiliza APIs existentes: companies/update y companies/upload-header
2026-09-14 12:34:59 -03:00
horacio ad44e775e2 feat: agregar habilidad para sincronizar el proyecto Engram con la nube 2026-09-14 12:02:34 -03:00
horacio cebb34c88a feat: actualizar URL de webhook de Mercado Pago y eliminar conteo de citas en la creación de ciclo de uso de plan 2026-09-14 11:37:42 -03:00
horacio 0095bd884a feat: actualizar la validación del campo de comentarios en el esquema de actualización de citas 2026-09-11 15:03:26 -03:00
horacio c238f28179 feat: ajustar el relleno superior en la página de movimientos y actualizar el z-index en el componente de ubicación 2026-09-11 14:53:32 -03:00
37 changed files with 2013 additions and 630 deletions
@@ -0,0 +1,33 @@
---
name: engram-cloud-sync
description: "Trigger: sync engram cloud, sincronizar memoria, push engram, engram cloud sync. Synchronize local Engram project to remote cloud server."
license: Apache-2.0
metadata:
author: "horacio"
version: "1.0"
---
## Activation Contract
Load this skill whenever the user explicitly asks to synchronize, push, or sync their Engram memory with the cloud.
## Hard Rules
- **Never skip the sync** when requested. Execute `engram sync --cloud --project turnosxpress` every time.
- **Always verify** the cloud server is reachable and the project is enrolled before syncing.
- **Report results to the user**: sessions, observations, prompts, mutations exported.
- **Fail fast** on 403/forbidden errors — that means the project needs enrollment first.
## Execution Steps
1. **Check cloud status:** `engram cloud status --cwd <repo>` (default: current project directory). If `Auth status: ready` and `Sync readiness: pending`, continue.
2. **If project is not enrolled** (`403: forbidden: project is not allowed` or similar), run `engram cloud enroll turnosxpress --cwd <repo>` then re-check status.
3. **Execute sync:** `engram sync --cloud --project turnosxpress --cwd <repo>`.
4. **Report results** — sessions, observations, prompts, mutations count. If sync fails, surface the exact error and suggest running `engram serve` for autosync mode.
## Output Contract
Return:
- Cloud server URL and enrollment status.
- Export counts: sessions, observations, prompts, mutations.
- Confirmation: "Cloud sync complete" or actionable error if it failed.
+1 -1
View File
@@ -45,7 +45,7 @@ MP_SUBSCRIPTION_FIND_URL = https://api.mercadopago.com/preapproval/
MP_ACCESS_TOKEN = APP_USR-8753424836448507-121412-731599daea1ffa0b278b5dcc78aa1ec8-1611134648 MP_ACCESS_TOKEN = APP_USR-8753424836448507-121412-731599daea1ffa0b278b5dcc78aa1ec8-1611134648
MP_BACK_URL = https://turnosxpress.com.ar/landing/dashboard MP_BACK_URL = https://turnosxpress.com.ar/landing/dashboard
MP_CHECK_PAYMENT_MINUTES = 1 MP_CHECK_PAYMENT_MINUTES = 1
MP_WEBHOOK_URL = https://30e1-186-132-147-13.ngrok-free.app/mercadopago/webhook MP_WEBHOOK_URL = https://5f09-186-58-32-217.ngrok-free.app/mercadopago/webhook
DEFAULT_BOT_ADMIN_PORT = 3005 DEFAULT_BOT_ADMIN_PORT = 3005
@@ -2,6 +2,9 @@ import crypto from "crypto";
import axios from "axios"; import axios from "axios";
import forge from "node-forge"; import forge from "node-forge";
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check"; import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
import CompaniesList from "../Companies/Companies";
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
import { PlanFeatures } from "../Plans/Plans.interface";
import ArcaWsaaTokens from "../ArcaWsaaTokens/ArcaWsaaTokens"; import ArcaWsaaTokens from "../ArcaWsaaTokens/ArcaWsaaTokens";
import { import {
ARCA_WSAA_ENVIRONMENT, ARCA_WSAA_ENVIRONMENT,
@@ -123,6 +126,23 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
await validatePermissionsByCompany({ companyId, sessionUser }); await validatePermissionsByCompany({ companyId, sessionUser });
} }
private async requirePaymentsFeature(companyId: string): Promise<void> {
const company = await CompaniesList.companies.findOne({ _id: companyId });
if (!company) {
throw new Error("No se ha encontrado la organización");
}
const canAccessPayments = await PlanSubscriptionsList.checkFeature({
userId: String(company.ownerId),
feature: PlanFeatures.PAYMENTS,
});
if (!canAccessPayments) {
throw new Error("La organización no tiene un plan que soporte el módulo de pagos");
}
}
private async requireActiveFiscalProfile( private async requireActiveFiscalProfile(
companyId: string, companyId: string,
sessionUser: string sessionUser: string
@@ -730,6 +750,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView> { public async generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser); const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const keys = forge.pki.rsa.generateKeyPair(2048); const keys = forge.pki.rsa.generateKeyPair(2048);
@@ -778,6 +799,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView> { public async uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
if (!data.certificatePem || !data.certificatePem.trim()) { if (!data.certificatePem || !data.certificatePem.trim()) {
throw new Error("Se requiere el certificado ARCA"); throw new Error("Se requiere el certificado ARCA");
@@ -836,6 +858,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult> { public async testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const service = ARCA_WSAA_SERVICE.WSFE; const service = ARCA_WSAA_SERVICE.WSFE;
const environment = this.getArcaEnvironment(); const environment = this.getArcaEnvironment();
@@ -853,6 +876,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult> { public async getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser); const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const loginTicket = await this.getWsaaLoginTicket(data.companyId); const loginTicket = await this.getWsaaLoginTicket(data.companyId);
const environment = this.getArcaEnvironment(); const environment = this.getArcaEnvironment();
@@ -886,6 +910,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async issueFacturaC(data: ArcaWsfeIssueFacturaCParams): Promise<ArcaWsfeIssueFacturaCResult> { public async issueFacturaC(data: ArcaWsfeIssueFacturaCParams): Promise<ArcaWsfeIssueFacturaCResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
if (data.amount <= 0) { if (data.amount <= 0) {
throw new Error("El importe de la factura debe ser mayor a cero"); throw new Error("El importe de la factura debe ser mayor a cero");
@@ -961,6 +986,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult> { public async getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser); await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser); const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const loginTicket = await this.getWsaaLoginTicket(data.companyId); const loginTicket = await this.getWsaaLoginTicket(data.companyId);
const environment = this.getArcaEnvironment(); const environment = this.getArcaEnvironment();
@@ -1054,8 +1080,11 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
await validateSessionUser({ sessionUser: data.sessionUser }); await validateSessionUser({ sessionUser: data.sessionUser });
let companyId: string | undefined;
if (data.companyId) { if (data.companyId) {
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser }); await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
companyId = data.companyId;
} else if (data.id) { } else if (data.id) {
const credential = await this.arcaCredentials.findOne(data); const credential = await this.arcaCredentials.findOne(data);
@@ -1067,12 +1096,13 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
companyId: String(credential.companyId), companyId: String(credential.companyId),
sessionUser: data.sessionUser, sessionUser: data.sessionUser,
}); });
companyId = String(credential.companyId);
return [this.sanitizeCredential(credential)];
} else { } else {
throw new Error("Se requiere una organización para buscar credenciales ARCA"); throw new Error("Se requiere una organización para buscar credenciales ARCA");
} }
await this.requirePaymentsFeature(companyId);
const credentials = await this.arcaCredentials.find(data); const credentials = await this.arcaCredentials.find(data);
return credentials.map((credential) => this.sanitizeCredential(credential)); return credentials.map((credential) => this.sanitizeCredential(credential));
} }
@@ -380,4 +380,5 @@ export interface ICompaniesManager {
sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>; sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>;
sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>; sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>;
sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult>; sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult>;
checkCompanyAdmin(data: { companyId: string; sessionUser: string }): Promise<boolean>;
} }
+13
View File
@@ -1221,6 +1221,19 @@ class CompaniesManager implements ICompaniesManager {
}, },
}; };
} }
public async checkCompanyAdmin(data: { companyId: string; sessionUser: string }): Promise<boolean> {
const filterData =
data.companyId.indexOf("-") >= 0 ? { slug: data.companyId } : { _id: data.companyId };
const company = await this.companies.findOne(filterData as any);
if (!company) {
return false;
}
return await EmployeesList.checkPermission(company, data.sessionUser, EmployeeRoles.ADMIN);
}
} }
const CompaniesList = new CompaniesManager(); const CompaniesList = new CompaniesManager();
@@ -1,4 +1,7 @@
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check"; import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
import CompaniesList from "../Companies/Companies";
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
import { PlanFeatures } from "../Plans/Plans.interface";
import { findArcaActivityByCode } from "../ArcaActivities/ArcaActivities.Catalog"; import { findArcaActivityByCode } from "../ArcaActivities/ArcaActivities.Catalog";
import { OrganizationFiscalProfilesAdapterMongoose } from "./OrganizationFiscalProfiles.Adapter.Mongoose"; import { OrganizationFiscalProfilesAdapterMongoose } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
import { import {
@@ -70,6 +73,21 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser }); await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
const company = await CompaniesList.companies.findOne({ _id: data.companyId });
if (!company) {
throw new Error("No se ha encontrado la organización");
}
const canAccessPayments = await PlanSubscriptionsList.checkFeature({
userId: String(company.ownerId),
feature: PlanFeatures.PAYMENTS,
});
if (!canAccessPayments) {
throw new Error("La organización no tiene un plan que soporte el módulo de pagos");
}
this.validateProfileFields(data); this.validateProfileFields(data);
const existingProfile = await this.organizationFiscalProfiles.findOne({ const existingProfile = await this.organizationFiscalProfiles.findOne({
@@ -140,6 +158,18 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
companyId: data.companyId, companyId: data.companyId,
sessionUser, sessionUser,
}); });
const company = await CompaniesList.companies.findOne({ _id: data.companyId });
if (company) {
const canAccessPayments = await PlanSubscriptionsList.checkFeature({
userId: String(company.ownerId),
feature: PlanFeatures.PAYMENTS,
});
if (!canAccessPayments) {
throw new Error("La organización no tiene un plan que soporte el módulo de pagos");
}
}
} else if (data.id) { } else if (data.id) {
const profile = await this.organizationFiscalProfiles.findOne(data); const profile = await this.organizationFiscalProfiles.findOne(data);
@@ -152,6 +182,18 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
sessionUser, sessionUser,
}); });
const company = await CompaniesList.companies.findOne({ _id: String(profile.companyId) });
if (company) {
const canAccessPayments = await PlanSubscriptionsList.checkFeature({
userId: String(company.ownerId),
feature: PlanFeatures.PAYMENTS,
});
if (!canAccessPayments) {
throw new Error("La organización no tiene un plan que soporte el módulo de pagos");
}
}
return [profile]; return [profile];
} else { } else {
throw new Error("Se requiere una organización para buscar perfiles fiscales"); throw new Error("Se requiere una organización para buscar perfiles fiscales");
@@ -112,7 +112,6 @@ export class PlanUsageCycleAdapterMongoose implements IPlanUsageCycleAdapter {
planId: data.planId, planId: data.planId,
cycleStart: data.cycleStart, cycleStart: data.cycleStart,
cycleEnd: data.cycleEnd, cycleEnd: data.cycleEnd,
appointmentsCount: 0,
creationDate: now, creationDate: now,
}, },
$inc: { appointmentsCount: data.quantity }, $inc: { appointmentsCount: data.quantity },
+10 -1
View File
@@ -63,6 +63,7 @@ import ClientsList from "../Clients/Clients";
import RepeatsList from "../Repeats/Repeats"; import RepeatsList from "../Repeats/Repeats";
import { OAuth2Client } from "google-auth-library"; import { OAuth2Client } from "google-auth-library";
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled"; import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
import dayjs from "dayjs";
const cleanEmail = (email: string): string => { const cleanEmail = (email: string): string => {
return email.toLowerCase().trim(); return email.toLowerCase().trim();
@@ -1087,10 +1088,18 @@ class UsersManager implements IUsersManager {
await this.users.update(data); await this.users.update(data);
const fecha = dayjs().format("DD/MM/YYYY");
const hora = dayjs().format("HH:mm");
await NotificationsManager.sendEmail({ await NotificationsManager.sendEmail({
email: cleanEmail(sessionUser.email), email: cleanEmail(sessionUser.email),
subject: "TurnosXpress :: Usuario actualizado", subject: "TurnosXpress :: Usuario actualizado",
message: `Hola ${sessionUser.firstName}, has actualizado tu perfil con éxito`, templateId: "6aa948e050f4bd20460f00a5",
context: {
username: sessionUser.firstName,
fecha,
hora,
},
}); });
} }
@@ -38,7 +38,7 @@ export class ToggleCompanyFixedPostController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async toggleFixedCompanyPost( public async toggleFixedCompanyPost(
@Body() requestBody: FixCompanyPostParams @Body() requestBody: FixCompanyPostParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().toggleFixedPost(requestBody); await new CompaniesService().toggleFixedPost(requestBody);
@@ -62,7 +62,7 @@ export class MoveCompanyFixedPostController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async moveFixedCompanyPost( public async moveFixedCompanyPost(
@Body() requestBody: MoveCompanyFixedPostParams @Body() requestBody: MoveCompanyFixedPostParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().moveFixedPost(requestBody); await new CompaniesService().moveFixedPost(requestBody);
@@ -86,7 +86,7 @@ export class SetNotificationsStatusCompanyController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async setNotificationAuto( public async setNotificationAuto(
@Body() requestBody: SetNotificationAutoParams @Body() requestBody: SetNotificationAutoParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().setNotificationAuto(requestBody); await new CompaniesService().setNotificationAuto(requestBody);
@@ -110,7 +110,7 @@ export class SetPublishedStatusCompanyController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async setPublishedStatus( public async setPublishedStatus(
@Body() requestBody: SetOrganizationPublishedStatusParams @Body() requestBody: SetOrganizationPublishedStatusParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().setPublishedStatus(requestBody); await new CompaniesService().setPublishedStatus(requestBody);
@@ -134,7 +134,7 @@ export class CreateCompanyController extends Controller {
@SuccessResponse(200, "La compañia fue creada con exito") @SuccessResponse(200, "La compañia fue creada con exito")
@Post() @Post()
public async createCompany( public async createCompany(
@Body() requestBody: CreateCompanyParams @Body() requestBody: CreateCompanyParams,
): Promise<ICompany | ApiValidationError> { ): Promise<ICompany | ApiValidationError> {
try { try {
const company = await new CompaniesService().createCompany(requestBody); const company = await new CompaniesService().createCompany(requestBody);
@@ -155,7 +155,7 @@ export class DeleteCompanyController extends Controller {
@SuccessResponse(200, "La compañia fue modificada con exito") @SuccessResponse(200, "La compañia fue modificada con exito")
@Post() @Post()
public async deleteCompany( public async deleteCompany(
@Body() requestBody: DeleteCompanyParams @Body() requestBody: DeleteCompanyParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().deleteCompany(requestBody); await new CompaniesService().deleteCompany(requestBody);
@@ -179,7 +179,7 @@ export class UpdateCompanyController extends Controller {
@SuccessResponse(200, "La compañia fue modificada con exito") @SuccessResponse(200, "La compañia fue modificada con exito")
@Post() @Post()
public async updateCompany( public async updateCompany(
@Body() requestBody: UpdateCompanyParams @Body() requestBody: UpdateCompanyParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().updateCompany(requestBody); await new CompaniesService().updateCompany(requestBody);
@@ -202,7 +202,7 @@ export class GetCompanyByIdController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async getById( public async getById(
@Body() requestBody: OranizationsViewByIdParams @Body() requestBody: OranizationsViewByIdParams,
): Promise<MyOranizationsView | ApiValidationError> { ): Promise<MyOranizationsView | ApiValidationError> {
try { try {
const companies = await new CompaniesService().getById(requestBody); const companies = await new CompaniesService().getById(requestBody);
@@ -222,7 +222,7 @@ export class GetCompanyByUserController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async getByUserId( public async getByUserId(
@Body() requestBody: MyOranizationsViewParams @Body() requestBody: MyOranizationsViewParams,
): Promise<MyOranizationsView[] | ApiValidationError> { ): Promise<MyOranizationsView[] | ApiValidationError> {
try { try {
const companies = await new CompaniesService().getByUserId(requestBody); const companies = await new CompaniesService().getByUserId(requestBody);
@@ -242,7 +242,7 @@ export class PaginateCompanyController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async paginateUsers( public async paginateUsers(
@Body() requestBody: PaginateCompaniesParams @Body() requestBody: PaginateCompaniesParams,
): Promise<PaginateCompaniesResults | ApiValidationError> { ): Promise<PaginateCompaniesResults | ApiValidationError> {
try { try {
const users = await new CompaniesService().paginateCompanies(requestBody); const users = await new CompaniesService().paginateCompanies(requestBody);
@@ -265,7 +265,7 @@ export class UploadCompanyHeaderController extends Controller {
public async uploadHeader( public async uploadHeader(
@FormField() companyId: string, @FormField() companyId: string,
@FormField() sessionUser: string, @FormField() sessionUser: string,
@UploadedFile() file: Express.Multer.File @UploadedFile() file: Express.Multer.File,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().setCompanyHeader({ await new CompaniesService().setCompanyHeader({
@@ -295,7 +295,7 @@ export class UploadCompanyIconController extends Controller {
public async uploadIcon( public async uploadIcon(
@FormField() companyId: string, @FormField() companyId: string,
@FormField() sessionUser: string, @FormField() sessionUser: string,
@UploadedFile() file: Express.Multer.File @UploadedFile() file: Express.Multer.File,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().setCompanyIcon({ await new CompaniesService().setCompanyIcon({
@@ -325,7 +325,7 @@ export class DeleteCompanyHeaderController extends Controller {
@SuccessResponse(200, "El archivo fue cargado con exito") @SuccessResponse(200, "El archivo fue cargado con exito")
@Post() @Post()
public async deleteHeader( public async deleteHeader(
@Body() data: DeleteCompanyFileParams @Body() data: DeleteCompanyFileParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().deleteCompanyHeader(data); await new CompaniesService().deleteCompanyHeader(data);
@@ -349,7 +349,7 @@ export class DeleteCompanyIconController extends Controller {
@SuccessResponse(200, "El archivo fue cargado con exito") @SuccessResponse(200, "El archivo fue cargado con exito")
@Post() @Post()
public async deleteIcon( public async deleteIcon(
@Body() data: DeleteCompanyFileParams @Body() data: DeleteCompanyFileParams,
): Promise<ApiVoidResult | ApiValidationError> { ): Promise<ApiVoidResult | ApiValidationError> {
try { try {
await new CompaniesService().deleteCompanyIcon(data); await new CompaniesService().deleteCompanyIcon(data);
@@ -372,7 +372,7 @@ export class filterAllOrganizationsController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async filterAllOrganizations( public async filterAllOrganizations(
@Body() requestBody: PaginateCompaniesParams @Body() requestBody: PaginateCompaniesParams,
): Promise<TextObjectFilterResult[] | ApiValidationError> { ): Promise<TextObjectFilterResult[] | ApiValidationError> {
try { try {
const clients = await new CompaniesService().filterAll(requestBody); const clients = await new CompaniesService().filterAll(requestBody);
@@ -392,7 +392,7 @@ export class CheckCompanyNameController extends Controller {
@SuccessResponse(200, "Done") @SuccessResponse(200, "Done")
@Post() @Post()
public async checkName( public async checkName(
@Body() requestBody: { name: string } @Body() requestBody: { name: string },
): Promise<{ valid: boolean } | ApiValidationError> { ): Promise<{ valid: boolean } | ApiValidationError> {
try { try {
const valid = await new CompaniesService().checkNameExists(requestBody.name); const valid = await new CompaniesService().checkNameExists(requestBody.name);
@@ -405,3 +405,24 @@ export class CheckCompanyNameController extends Controller {
} }
} }
} }
@Route("companies/check-admin")
@Middlewares(authenticateMiddleware)
export class CheckCompanyAdminController extends Controller {
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@SuccessResponse(200, "Done")
@Post()
public async checkAdmin(
@Body() requestBody: { companyId: string; sessionUser: string },
): Promise<boolean | ApiValidationError> {
try {
const isAdmin = await new CompaniesService().checkCompanyAdmin(requestBody);
this.setStatus(200);
return isAdmin;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@@ -112,4 +112,9 @@ export class CompaniesService {
const isValid = await CompaniestList.isValidName({ name }); const isValid = await CompaniestList.isValidName({ name });
return isValid; return isValid;
} }
public async checkCompanyAdmin(data: { companyId: string; sessionUser: string }): Promise<boolean> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await CompaniestList.checkCompanyAdmin(data);
}
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

@@ -0,0 +1,19 @@
import ApiRequest from "@services/Api.Service";
import { UpdateCompanyParams } from "@models/Company.model";
import { ApiVoidResult } from "@models/Api.VoidResult.type";
export const updateOrganizationColors = async (data: UpdateCompanyParams): Promise<ApiVoidResult> => {
return ApiRequest.post<ApiVoidResult>("companies/update", data);
};
export const uploadHeaderImage = async (data: FormData): Promise<ApiVoidResult> => {
return ApiRequest.postFile<ApiVoidResult>("companies/upload-header", data);
};
export const uploadServiceImage = async (data: FormData): Promise<ApiVoidResult> => {
return ApiRequest.postFile<ApiVoidResult>("services/upload-image", data);
};
export const checkOrgAdmin = async (companyId: string, sessionUser: string): Promise<boolean> => {
return ApiRequest.post<boolean>("companies/check-admin", { companyId, sessionUser });
};
@@ -37,7 +37,7 @@ const schemaAppointmentUpdate = Yup.object().shape({
start: Yup.string().required("Debe seleccionar una fecha."), start: Yup.string().required("Debe seleccionar una fecha."),
price: Yup.number().positive().required("Debe introducir un precio valido."), price: Yup.number().positive().required("Debe introducir un precio valido."),
length: Yup.number().positive().required("Debe introducir una duración."), length: Yup.number().positive().required("Debe introducir una duración."),
comments: Yup.string().required("Debe introducir un comentario."), comments: Yup.string().notRequired(),
sessionUser: Yup.string().required("Para crear un turno debe iniciar sesión."), sessionUser: Yup.string().required("Para crear un turno debe iniciar sesión."),
}); });
@@ -1,5 +1,6 @@
.movementsPage { .movementsPage {
padding: 16px; padding: 16px;
padding-top: 200px;
padding-bottom: 32px; padding-bottom: 32px;
} }
@@ -17,6 +17,7 @@ import ReceiptLongOutlinedIcon from "@mui/icons-material/ReceiptLongOutlined";
import { Grid2 } from "@mui/material"; import { Grid2 } from "@mui/material";
import { ApiError } from "@models/Server.Error.model"; import { ApiError } from "@models/Server.Error.model";
import style from "./page.module.css"; import style from "./page.module.css";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import { import {
findArcaActivities, findArcaActivities,
findOrganizationFiscalProfiles, findOrganizationFiscalProfiles,
@@ -188,123 +189,125 @@ export default function OrganizationFiscalProfileEdit() {
return ( return (
<> <>
<Location /> <Location />
<div className={style.pageContainer}> <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
<section className={style.heroCard}> <div className={style.pageContainer}>
<div className={style.heroIcon}> <section className={style.heroCard}>
<ReceiptLongOutlinedIcon /> <div className={style.heroIcon}>
</div> <ReceiptLongOutlinedIcon />
<div> </div>
<h2>Configuración fiscal</h2> <div>
<p> <h2>Configuración fiscal</h2>
Estos datos se usan para emitir Factura C desde los movimientos de caja y para precargar el asistente ARCA. <p>
</p> Estos datos se usan para emitir Factura C desde los movimientos de caja y para precargar el asistente ARCA.
</div> </p>
</section> </div>
</section>
<section className={style.formSection}> <section className={style.formSection}>
<h3>Datos del emisor</h3> <h3>Datos del emisor</h3>
<Grid2 container spacing={2}> <Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}> <Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox <Textbox
name="cuit" name="cuit"
placeholder="CUIT" placeholder="CUIT"
type="text" type="text"
value={cuit} value={cuit}
width="100%" width="100%"
onChange={(event) => { onChange={(event) => {
setCuit(event.target.value.replace(/\D/g, "")); setCuit(event.target.value.replace(/\D/g, ""));
markNeedsSave(); markNeedsSave();
}} }}
/> />
</Grid2> </Grid2>
<Grid2 size={{ xs: 12, sm: 6 }}> <Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox <Textbox
name="legalName" name="legalName"
placeholder="Razón social" placeholder="Razón social"
type="text" type="text"
value={legalName} value={legalName}
width="100%" width="100%"
onChange={(event) => { onChange={(event) => {
setLegalName(event.target.value); setLegalName(event.target.value);
markNeedsSave(); markNeedsSave();
}} }}
/> />
</Grid2> </Grid2>
</Grid2> </Grid2>
</section> </section>
<section className={style.formSection}> <section className={style.formSection}>
<div className={style.sectionHeader}> <div className={style.sectionHeader}>
<h3>Condición fiscal</h3> <h3>Condición fiscal</h3>
<p>Seleccioná la condición declarada para esta organización.</p> <p>Seleccioná la condición declarada para esta organización.</p>
</div> </div>
<div className={style.optionGroup} role="radiogroup" aria-label="Condición fiscal"> <div className={style.optionGroup} role="radiogroup" aria-label="Condición fiscal">
{fiscalConditionOptions.map((option) => { {fiscalConditionOptions.map((option) => {
const selected = taxCondition === option.id; const selected = taxCondition === option.id;
return ( return (
<button <button
key={option.id} key={option.id}
type="button" type="button"
className={`${style.optionCard} ${selected ? style.optionCardSelected : ""}`} className={`${style.optionCard} ${selected ? style.optionCardSelected : ""}`}
onClick={() => { onClick={() => {
setTaxCondition(option.id); setTaxCondition(option.id);
markNeedsSave(); markNeedsSave();
}} }}
aria-pressed={selected} aria-pressed={selected}
> >
<span className={style.optionTitle}>{option.title}</span> <span className={style.optionTitle}>{option.title}</span>
<span className={style.optionDescription}>{option.description}</span> <span className={style.optionDescription}>{option.description}</span>
</button> </button>
);
})}
</div>
</section>
<section className={style.formSection}>
<h3>Facturación ARCA</h3>
<Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="pointOfSale"
placeholder="Punto de venta"
type="text"
value={pointOfSale}
width="100%"
onChange={(event) => {
setPointOfSale(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
{fiscalDataLoaded && (
<TextObjectFilter
key={`${activityCode}-${arcaActivities.length}`}
placeholder="Actividad ARCA/CLAE"
content={activityFilterContent}
data={arcaActivities}
selectedId={activityCode}
onChange={(selectedActivityCode) => {
const selectedActivity = arcaActivities.find(
(activity) => activity.id === selectedActivityCode
); );
})}
</div>
</section>
setActivityCode(selectedActivity?.id || ""); <section className={style.formSection}>
setActivityDescription(selectedActivity?.name || ""); <h3>Facturación ARCA</h3>
markNeedsSave(); <Grid2 container spacing={2}>
}} <Grid2 size={{ xs: 12, sm: 6 }}>
/> <Textbox
)} name="pointOfSale"
placeholder="Punto de venta"
type="text"
value={pointOfSale}
width="100%"
onChange={(event) => {
setPointOfSale(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
<p className={style.helpText}> {fiscalDataLoaded && (
{activityCode && activityDescription <TextObjectFilter
? `${activityCode} - ${activityDescription}` key={`${activityCode}-${arcaActivities.length}`}
: "Seleccioná la actividad principal declarada en ARCA."} placeholder="Actividad ARCA/CLAE"
</p> content={activityFilterContent}
</section> data={arcaActivities}
</div> selectedId={activityCode}
onChange={(selectedActivityCode) => {
const selectedActivity = arcaActivities.find(
(activity) => activity.id === selectedActivityCode
);
setActivityCode(selectedActivity?.id || "");
setActivityDescription(selectedActivity?.name || "");
markNeedsSave();
}}
/>
)}
<p className={style.helpText}>
{activityCode && activityDescription
? `${activityCode} - ${activityDescription}`
: "Seleccioná la actividad principal declarada en ARCA."}
</p>
</section>
</div>
</SecureByPlan>
</> </>
); );
} }
@@ -16,6 +16,7 @@ import { getServiceImage } from "@core/helpers/getServiceImage";
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary"; import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined"; import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import Dialog from "@mui/material/Dialog"; import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent"; import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle"; import DialogTitle from "@mui/material/DialogTitle";
@@ -118,18 +119,30 @@ export default function Org() {
</div> </div>
<div className={style.serviceActions}> <div className={style.serviceActions}>
<span className={style.servicePrice}>{formatPrice(data.price)}</span> <span className={style.servicePrice}>{formatPrice(data.price)}</span>
<IconButton <div className={style.iconsRow}>
className={style.shareButton} <IconButton
sx={{ position: "absolute", top: "15px", right: "15px" }} onClick={(e) => {
onClick={(e) => { e.stopPropagation();
e.stopPropagation(); goTo(`/landing/service/${data.id}`);
setShareService(data); }}
}} size="small"
size="small" title="Ver perfil público del servicio"
title="Compartir servicio" className={style.iconButton}
> >
<ShareOutlinedIcon fontSize="small" /> <OpenInNewIcon fontSize="small" />
</IconButton> </IconButton>
<IconButton
onClick={(e) => {
e.stopPropagation();
setShareService(data);
}}
size="small"
title="Compartir servicio"
className={style.iconButton}
>
<ShareOutlinedIcon fontSize="small" />
</IconButton>
</div>
</div> </div>
</div> </div>
); );
@@ -71,26 +71,29 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: flex-end; align-items: flex-end;
justify-content: flex-end; /* changed from space-between */ justify-content: center;
min-width: 100px; gap: 12px;
min-width: 60px;
} }
.servicePrice { .servicePrice {
font-size: 18px; font-size: 18px;
font-weight: 800; font-weight: 800;
color: #1e293b; color: #1e293b;
margin-bottom: 0; /* removed bottom margin */
} }
.shareButton { .iconsRow {
display: flex;
align-items: center;
gap: 4px;
}
.iconButton {
color: #94a3b8; color: #94a3b8;
transition: color 0.2s ease; transition: color 0.2s ease;
position: absolute;
top: 15px;
right: 15px;
} }
.shareButton:hover { .iconButton:hover {
color: var(--wine-dark); color: var(--wine-dark);
} }
@@ -206,6 +206,7 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
const [wapError, setWapError] = useState<string | null>(null); const [wapError, setWapError] = useState<string | null>(null);
// State for ARCA onboarding flow // State for ARCA onboarding flow
const [arcaIsBlocked, setArcaIsBlocked] = useState(false);
const [arcaCuit, setArcaCuit] = useState(""); const [arcaCuit, setArcaCuit] = useState("");
const [arcaLegalName, setArcaLegalName] = useState(""); const [arcaLegalName, setArcaLegalName] = useState("");
const [arcaTaxCondition, setArcaTaxCondition] = useState<"MONOTRIBUTO" | "EXENTO">("MONOTRIBUTO"); const [arcaTaxCondition, setArcaTaxCondition] = useState<"MONOTRIBUTO" | "EXENTO">("MONOTRIBUTO");
@@ -277,6 +278,7 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
}; };
const loadOrganizationContext = (org: any) => { const loadOrganizationContext = (org: any) => {
setArcaIsBlocked(false);
setCreatedCompanyId(org.id || org._id); setCreatedCompanyId(org.id || org._id);
setSelectedOrganization(org); setSelectedOrganization(org);
setOrgName(org.name || ""); setOrgName(org.name || "");
@@ -499,6 +501,18 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
setWapQr(null); setWapQr(null);
setWapError(null); setWapError(null);
} else if (flowId === "arca-onboarding") { } else if (flowId === "arca-onboarding") {
const orgSub = SessionInfo.organizationSubscriptions[org.id || org._id];
const planSupportsPayments = orgSub ? orgSub.plan?.payments : false;
if (!planSupportsPayments) {
setArcaIsBlocked(true);
setCurrentStepIndex(0);
setArcaError(null);
setArcaLoading(false);
return;
}
setArcaIsBlocked(false);
setCurrentStepIndex(0); setCurrentStepIndex(0);
setArcaError(null); setArcaError(null);
setArcaLoading(false); setArcaLoading(false);
@@ -527,6 +541,19 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
setArcaStatusLabel(getArcaStatusLabel(credential.status)); setArcaStatusLabel(getArcaStatusLabel(credential.status));
}).catch(console.error); }).catch(console.error);
} else if (flowId === "arca-test-connection") { } else if (flowId === "arca-test-connection") {
const orgSub = SessionInfo.organizationSubscriptions[org.id || org._id];
const planSupportsPayments = orgSub ? orgSub.plan?.payments : false;
if (!planSupportsPayments) {
setArcaIsBlocked(true);
setCurrentStepIndex(0);
setArcaError(null);
setArcaLoading(false);
setArcaTestResult(null);
return;
}
setArcaIsBlocked(false);
setCurrentStepIndex(0); setCurrentStepIndex(0);
setArcaError(null); setArcaError(null);
setArcaLoading(false); setArcaLoading(false);
@@ -2415,8 +2442,42 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
if (flowId === "public-link") return renderPublicLinkFlow(); if (flowId === "public-link") return renderPublicLinkFlow();
if (flowId === "notifications") return renderNotificationsFlow(); if (flowId === "notifications") return renderNotificationsFlow();
if (flowId === "whatsapp-bot") return renderWhatsAppBotFlow(); if (flowId === "whatsapp-bot") return renderWhatsAppBotFlow();
if (flowId === "arca-onboarding") return renderArcaOnboardingFlow(); if (flowId === "arca-onboarding") {
if (flowId === "arca-test-connection") return renderArcaTestConnectionFlow(); if (arcaIsBlocked) {
return (
<QuestionCard
isActive
title="Módulo ARCA no disponible"
description="Este flujo requiere un plan con el módulo de pagos habilitado para emitir Factura C."
onNext={() => router.push("/landing/pricing")}
nextLabel="Ver planes"
>
<div style={{ color: "rgba(255,255,255,0.75)", textAlign: "center", lineHeight: 1.6 }}>
La organización seleccionada necesita un plan con el módulo de pagos activo para usar ARCA. Actualizá tu plan o volvé al asistente y elegí otra opción.
</div>
</QuestionCard>
);
}
return renderArcaOnboardingFlow();
}
if (flowId === "arca-test-connection") {
if (arcaIsBlocked) {
return (
<QuestionCard
isActive
title="Test de conexión ARCA no disponible"
description="Este flujo requiere un plan con el módulo de pagos habilitado para probar la conexión con ARCA."
onNext={() => router.push("/landing/pricing")}
nextLabel="Ver planes"
>
<div style={{ color: "rgba(255,255,255,0.75)", textAlign: "center", lineHeight: 1.6 }}>
La organización seleccionada necesita un plan con el módulo de pagos activo para usar ARCA. Actualizá tu plan o volvé al asistente y elegí otra opción.
</div>
</QuestionCard>
);
}
return renderArcaTestConnectionFlow();
}
if (flowId === "disable-schedule") return renderDisableScheduleFlow(); if (flowId === "disable-schedule") return renderDisableScheduleFlow();
if (flowId === "open-reservation-periods") return renderReservationPeriodFlow(); if (flowId === "open-reservation-periods") return renderReservationPeriodFlow();
if (flowId === "override-schedule") return renderOverrideScheduleFlow(); if (flowId === "override-schedule") return renderOverrideScheduleFlow();
@@ -39,13 +39,47 @@ type OnboardingServiceFlowProps = {
}; };
export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps) { export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps) {
const { heatMapFraction, currentStepIndex, handleNext, serviceName, setServiceName, serviceDescription, setServiceDescription, handleKeyDown, serviceLength, setServiceLength, handleCreateService, isCreating, servicePrice, setServicePrice, serviceLimit, setServiceLimit, serviceCreateError, handleUploadServiceImage, serviceImage, setServiceImage, isStandaloneNewService, handleAssignCreatedServiceToMe, handleShowCollaboratorAssignment, handleToggleServiceCollaborator, handleAssignCreatedServiceToCollaborators, handleFinishWithoutAssignment, serviceAssignmentError, serviceAssignmentWarning, serviceAssignmentMode, serviceAssignmentCollaborators, selectedServiceCollaboratorIds, isLoadingServiceCollaborators } = props; const {
heatMapFraction,
currentStepIndex,
handleNext,
serviceName,
setServiceName,
serviceDescription,
setServiceDescription,
handleKeyDown,
serviceLength,
setServiceLength,
handleCreateService,
isCreating,
servicePrice,
setServicePrice,
serviceLimit,
setServiceLimit,
serviceCreateError,
handleUploadServiceImage,
serviceImage,
setServiceImage,
isStandaloneNewService,
handleAssignCreatedServiceToMe,
handleShowCollaboratorAssignment,
handleToggleServiceCollaborator,
handleAssignCreatedServiceToCollaborators,
handleFinishWithoutAssignment,
serviceAssignmentError,
serviceAssignmentWarning,
serviceAssignmentMode,
serviceAssignmentCollaborators,
selectedServiceCollaboratorIds,
isLoadingServiceCollaborators,
} = props;
const [isCustomDuration, setIsCustomDuration] = React.useState(false); const [isCustomDuration, setIsCustomDuration] = React.useState(false);
const [customDurationValue, setCustomDurationValue] = React.useState(""); const [customDurationValue, setCustomDurationValue] = React.useState("");
const fraction = heatMapFraction || 60; const fraction = heatMapFraction || 60;
const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4]; const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4];
const customDurationMinutes = Number(customDurationValue); const customDurationMinutes = Number(customDurationValue);
const isValidCustomDuration = Number.isInteger(customDurationMinutes) && customDurationMinutes > 0; const isValidCustomDuration =
Number.isInteger(customDurationMinutes) && customDurationMinutes > 0;
const selectDurationOption = (duration: number) => { const selectDurationOption = (duration: number) => {
setIsCustomDuration(false); setIsCustomDuration(false);
@@ -65,390 +99,518 @@ export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps)
}; };
return ( return (
<> <>
<QuestionCard <QuestionCard
isActive={currentStepIndex === 0} isActive={currentStepIndex === 0}
title="Configura tus Servicios" title="Configura tus Servicios"
description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar." description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
onNext={handleNext} onNext={handleNext}
nextLabel="Comenzar" nextLabel="Comenzar"
>
<div
style={{
color: "rgba(255, 255, 255, 0.7)",
textAlign: "center",
padding: "10px",
}}
> >
<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!
Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil! </div>
</div> </QuestionCard>
</QuestionCard>
<QuestionCard <QuestionCard
isActive={currentStepIndex === 1} isActive={currentStepIndex === 1}
title="1. Nombre y Descripción" title="1. Nombre y Descripción"
description="Elige un nombre atractivo y describe de qué trata el servicio." description="Elige un nombre atractivo y describe de qué trata el servicio."
onNext={handleNext} onNext={handleNext}
disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5} disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
>
<div
style={{ display: "flex", flexDirection: "column", gap: "15px", width: "100%" }}
> >
<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 || (isCustomDuration && !isValidCustomDuration)}
>
<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={() => selectDurationOption(val)}
style={{
padding: "12px 24px",
borderRadius: "12px",
cursor: "pointer",
background:
!isCustomDuration && serviceLength === val
? "var(--wine-red)"
: "rgba(255,255,255,0.05)",
border: `2px solid ${!isCustomDuration && serviceLength === val ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white",
fontWeight:
!isCustomDuration && serviceLength === val
? "bold"
: "normal",
transition: "all 0.2s ease",
fontSize: "16px",
}}
>
{label}
</div>
);
})}
<div
onClick={selectCustomDuration}
style={{
padding: "12px 24px",
borderRadius: "12px",
cursor: "pointer",
background: isCustomDuration
? "var(--wine-red)"
: "rgba(255,255,255,0.05)",
border: `2px solid ${isCustomDuration ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white",
fontWeight: isCustomDuration ? "bold" : "normal",
transition: "all 0.2s ease",
fontSize: "16px",
}}
>
Otro
</div>
</div>
{isCustomDuration && (
<div style={{ width: "100%", marginTop: "16px" }}>
<QuestionInput <QuestionInput
placeholder="Ej. Corte clásico con lavado" type="number"
value={serviceName} min="1"
onChange={(e) => setServiceName(e.target.value)} step="1"
autoFocus placeholder="Duración en minutos"
/> value={customDurationValue}
<QuestionInput onChange={(e) => updateCustomDuration(e.target.value)}
placeholder="Breve descripción del servicio..."
value={serviceDescription}
onChange={(e) => setServiceDescription(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (serviceName.trim().length >= 3 && serviceDescription.trim().length >= 5) { if (isValidCustomDuration) {
handleKeyDown(e, handleNext); handleKeyDown(e, handleNext);
} }
}} }}
autoFocus
/> />
</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 || (isCustomDuration && !isValidCustomDuration)}
>
<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={() => selectDurationOption(val)}
style={{
padding: '12px 24px',
borderRadius: '12px',
cursor: 'pointer',
background: !isCustomDuration && serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${!isCustomDuration && serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
fontWeight: !isCustomDuration && serviceLength === val ? 'bold' : 'normal',
transition: 'all 0.2s ease',
fontSize: '16px'
}}
>
{label}
</div>
);
})}
<div <div
onClick={selectCustomDuration}
style={{ style={{
padding: '12px 24px', color: "rgba(255,255,255,0.6)",
borderRadius: '12px', fontSize: "13px",
cursor: 'pointer', marginTop: "8px",
background: isCustomDuration ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', textAlign: "center",
border: `2px solid ${isCustomDuration ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
fontWeight: isCustomDuration ? 'bold' : 'normal',
transition: 'all 0.2s ease',
fontSize: '16px'
}} }}
> >
Otro Ingresá la duración total del servicio expresada en minutos.
</div> </div>
</div> </div>
{isCustomDuration && ( )}
<div style={{ width: '100%', marginTop: '16px' }}> </QuestionCard>
<QuestionInput
type="number" <QuestionCard
min="1" isActive={currentStepIndex === 3}
step="1" title="3. Precio y Cupos"
placeholder="Duración en minutos" description="¿Cuánto cuesta y a cuántas personas puede atender cada profesional a la vez en este servicio?"
value={customDurationValue} onNext={handleCreateService}
onChange={(e) => updateCustomDuration(e.target.value)} disableNext={isCreating}
onKeyDown={(e) => { nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
if (isValidCustomDuration) { >
handleKeyDown(e, handleNext); <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="text"
inputMode="decimal"
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",
}} }}
autoFocus
/> />
<div style={{ color: 'rgba(255,255,255,0.6)', fontSize: '13px', marginTop: '8px', textAlign: 'center' }}> </div>
Ingresá la duración total del servicio expresada en minutos. </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>
{serviceCreateError && (
<div
style={{
padding: "14px 16px",
borderRadius: "12px",
background: "rgba(255, 99, 132, 0.12)",
border: "1px solid rgba(255, 99, 132, 0.35)",
color: "#fecdd3",
fontSize: "14px",
lineHeight: 1.5,
textAlign: "center",
}}
>
{serviceCreateError}
</div> </div>
)} )}
</QuestionCard> </div>
</QuestionCard>
<QuestionCard <QuestionCard
isActive={currentStepIndex === 3} isActive={currentStepIndex === 4}
title="3. Precio y Cupos" title="4. Imagen del Servicio"
description="¿Cuánto cuesta y a cuántas personas puedes atender a la vez en este servicio?" description="Sube una foto representativa para que los clientes sepan qué ofreces. (Opcional)"
onNext={handleCreateService} onNext={handleUploadServiceImage}
disableNext={isCreating} disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Crear Servicio"} nextLabel={
isCreating
? "Subiendo..."
: serviceImage
? isStandaloneNewService
? "Subir y continuar"
: "Subir y Finalizar"
: "Omitir por ahora"
}
>
<div
style={{
display: "flex",
flexDirection: "column",
gap: "20px",
width: "100%",
alignItems: "center",
}}
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}> <div
<div> style={{
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Precio Original</div> width: "100%",
<div style={{ position: 'relative' }}> height: "150px",
<span style={{ position: 'absolute', left: '15px', top: '50%', transform: 'translateY(-50%)', color: 'white', fontSize: '18px' }}>$</span> border: "2px dashed rgba(255,255,255,0.3)",
<input borderRadius: "12px",
type="text" display: "flex",
inputMode="decimal" alignItems: "center",
placeholder="0.00" justifyContent: "center",
value={servicePrice} position: "relative",
onChange={(e) => setServicePrice(e.target.value)} overflow: "hidden",
style={{ cursor: "pointer",
width: '100%', background: serviceImage ? "transparent" : "rgba(255,255,255,0.05)",
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>
{serviceCreateError && (
<div style={{
padding: '14px 16px',
borderRadius: '12px',
background: 'rgba(255, 99, 132, 0.12)',
border: '1px solid rgba(255, 99, 132, 0.35)',
color: '#fecdd3',
fontSize: '14px',
lineHeight: 1.5,
textAlign: 'center'
}}>
{serviceCreateError}
</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 ? (isStandaloneNewService ? "Subir y continuar" : "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>
{serviceCreateError && (
<div style={{
padding: '14px 16px',
borderRadius: '12px',
background: 'rgba(255, 99, 132, 0.12)',
border: '1px solid rgba(255, 99, 132, 0.35)',
color: '#fecdd3',
fontSize: '14px',
lineHeight: 1.5,
textAlign: 'center'
}}>
{serviceCreateError}
</div>
)}
</div>
</QuestionCard>
{isStandaloneNewService && (
<QuestionCard
isActive={currentStepIndex === 5}
title="¿Quién brinda este servicio?"
description="Asigná este servicio a un colaborador para que pueda recibir reservas. Si todavía no querés hacerlo, podés configurarlo después."
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: '14px', width: '100%' }}> {serviceImage ? (
<button <img
type="button" src={URL.createObjectURL(serviceImage)}
onClick={handleAssignCreatedServiceToMe} alt="Preview"
disabled={isCreating} 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>
{serviceCreateError && (
<div
style={{
padding: "14px 16px",
borderRadius: "12px",
background: "rgba(255, 99, 132, 0.12)",
border: "1px solid rgba(255, 99, 132, 0.35)",
color: "#fecdd3",
fontSize: "14px",
lineHeight: 1.5,
textAlign: "center",
}}
>
{serviceCreateError}
</div>
)}
</div>
</QuestionCard>
{isStandaloneNewService && (
<QuestionCard
isActive={currentStepIndex === 5}
title="¿Quién brinda este servicio?"
description="Asigná este servicio a un colaborador para que pueda recibir reservas. Si todavía no querés hacerlo, podés configurarlo después."
>
<div
style={{
display: "flex",
flexDirection: "column",
gap: "14px",
width: "100%",
}}
>
<button
type="button"
onClick={handleAssignCreatedServiceToMe}
disabled={isCreating}
style={{
padding: "14px 18px",
borderRadius: "12px",
border: "1px solid var(--wine-red)",
background: "var(--wine-red)",
color: "white",
fontSize: "16px",
fontWeight: "bold",
cursor: isCreating ? "not-allowed" : "pointer",
opacity: isCreating ? 0.7 : 1,
}}
>
{isCreating ? "Asignando..." : "Yo"}
</button>
<button
type="button"
onClick={handleShowCollaboratorAssignment}
disabled={isCreating || isLoadingServiceCollaborators}
style={{
padding: "14px 18px",
borderRadius: "12px",
border:
serviceAssignmentMode === "collaborators"
? "1px solid var(--wine-red)"
: "1px solid rgba(255,255,255,0.2)",
background:
serviceAssignmentMode === "collaborators"
? "rgba(128, 0, 64, 0.35)"
: "rgba(255,255,255,0.05)",
color: "white",
fontSize: "16px",
cursor:
isCreating || isLoadingServiceCollaborators
? "not-allowed"
: "pointer",
opacity: isCreating || isLoadingServiceCollaborators ? 0.7 : 1,
}}
>
{isLoadingServiceCollaborators
? "Cargando colaboradores..."
: "Uno o más colaboradores"}
</button>
{serviceAssignmentMode === "collaborators" && (
<div
style={{ style={{
padding: '14px 18px', display: "flex",
borderRadius: '12px', flexDirection: "column",
border: '1px solid var(--wine-red)', gap: "10px",
background: 'var(--wine-red)', width: "100%",
color: 'white',
fontSize: '16px',
fontWeight: 'bold',
cursor: isCreating ? 'not-allowed' : 'pointer',
opacity: isCreating ? 0.7 : 1
}} }}
> >
{isCreating ? "Asignando..." : "Yo"} {serviceAssignmentCollaborators.length === 0 &&
</button> !isLoadingServiceCollaborators && (
<button <div
type="button" style={{
onClick={handleShowCollaboratorAssignment} color: "rgba(255,255,255,0.7)",
disabled={isCreating || isLoadingServiceCollaborators} fontSize: "14px",
style={{ textAlign: "center",
padding: '14px 18px', }}
borderRadius: '12px', >
border: serviceAssignmentMode === "collaborators" ? '1px solid var(--wine-red)' : '1px solid rgba(255,255,255,0.2)', No encontramos colaboradores activos para esta
background: serviceAssignmentMode === "collaborators" ? 'rgba(128, 0, 64, 0.35)' : 'rgba(255,255,255,0.05)', organización.
color: 'white', </div>
fontSize: '16px', )}
cursor: isCreating || isLoadingServiceCollaborators ? 'not-allowed' : 'pointer', <CollaboratorPicker
opacity: isCreating || isLoadingServiceCollaborators ? 0.7 : 1 employees={serviceAssignmentCollaborators}
}} selectedIds={selectedServiceCollaboratorIds}
> multiple
{isLoadingServiceCollaborators ? "Cargando colaboradores..." : "Uno o más colaboradores"} disabled={isCreating}
</button> onToggle={handleToggleServiceCollaborator}
{serviceAssignmentMode === "collaborators" && ( />
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}> {serviceAssignmentCollaborators.length > 0 && (
{serviceAssignmentCollaborators.length === 0 && !isLoadingServiceCollaborators && (
<div style={{ color: 'rgba(255,255,255,0.7)', fontSize: '14px', textAlign: 'center' }}>
No encontramos colaboradores activos para esta organización.
</div>
)}
<CollaboratorPicker
employees={serviceAssignmentCollaborators}
selectedIds={selectedServiceCollaboratorIds}
multiple
disabled={isCreating}
onToggle={handleToggleServiceCollaborator}
/>
{serviceAssignmentCollaborators.length > 0 && (
<button
type="button"
onClick={handleAssignCreatedServiceToCollaborators}
disabled={isCreating || selectedServiceCollaboratorIds.length === 0}
style={{
padding: '14px 18px',
borderRadius: '12px',
border: '1px solid var(--wine-red)',
background: 'var(--wine-red)',
color: 'white',
fontSize: '16px',
fontWeight: 'bold',
cursor: isCreating || selectedServiceCollaboratorIds.length === 0 ? 'not-allowed' : 'pointer',
opacity: isCreating || selectedServiceCollaboratorIds.length === 0 ? 0.7 : 1
}}
>
{isCreating ? "Asignando..." : "Asignar servicio"}
</button>
)}
</div>
)}
{!serviceAssignmentWarning && (
<>
<button <button
type="button" type="button"
onClick={handleFinishWithoutAssignment} onClick={handleAssignCreatedServiceToCollaborators}
disabled={isCreating} disabled={
isCreating ||
selectedServiceCollaboratorIds.length === 0
}
style={{ style={{
padding: '14px 18px', padding: "14px 18px",
borderRadius: '12px', borderRadius: "12px",
border: '1px solid rgba(255,255,255,0.2)', border: "1px solid var(--wine-red)",
background: 'rgba(255,255,255,0.05)', background: "var(--wine-red)",
color: 'white', color: "white",
fontSize: '16px', fontSize: "16px",
cursor: isCreating ? 'not-allowed' : 'pointer', fontWeight: "bold",
opacity: isCreating ? 0.7 : 1 cursor:
isCreating ||
selectedServiceCollaboratorIds.length === 0
? "not-allowed"
: "pointer",
opacity:
isCreating ||
selectedServiceCollaboratorIds.length === 0
? 0.7
: 1,
}} }}
> >
Lo configuro después {isCreating ? "Asignando..." : "Asignar servicio"}
</button> </button>
<div style={{ )}
padding: '12px 14px', </div>
borderRadius: '12px', )}
background: 'rgba(245, 158, 11, 0.12)', {!serviceAssignmentWarning && (
border: '1px solid rgba(245, 158, 11, 0.35)', <>
color: '#fde68a', <button
fontSize: '14px', type="button"
onClick={handleFinishWithoutAssignment}
disabled={isCreating}
style={{
padding: "14px 18px",
borderRadius: "12px",
border: "1px solid rgba(255,255,255,0.2)",
background: "rgba(255,255,255,0.05)",
color: "white",
fontSize: "16px",
cursor: isCreating ? "not-allowed" : "pointer",
opacity: isCreating ? 0.7 : 1,
}}
>
Lo configuro después
</button>
<div
style={{
padding: "12px 14px",
borderRadius: "12px",
background: "rgba(245, 158, 11, 0.12)",
border: "1px solid rgba(245, 158, 11, 0.35)",
color: "#fde68a",
fontSize: "14px",
lineHeight: 1.5, lineHeight: 1.5,
textAlign: 'center' textAlign: "center",
}}> }}
Si lo configurás después, el servicio no va a estar disponible para reservas hasta que lo asignes a un colaborador con horarios cargados. >
</div> Si lo configurás después, el servicio no va a estar disponible
</> para reservas hasta que lo asignes a un colaborador con horarios
)} cargados.
{serviceAssignmentError && ( </div>
<div style={{ </>
padding: '12px 14px', )}
borderRadius: '12px', {serviceAssignmentError && (
background: 'rgba(255, 99, 132, 0.12)', <div
border: '1px solid rgba(255, 99, 132, 0.35)', style={{
color: '#fecdd3', padding: "12px 14px",
fontSize: '14px', borderRadius: "12px",
background: "rgba(255, 99, 132, 0.12)",
border: "1px solid rgba(255, 99, 132, 0.35)",
color: "#fecdd3",
fontSize: "14px",
lineHeight: 1.5, lineHeight: 1.5,
textAlign: 'center' textAlign: "center",
}}> }}
{serviceAssignmentError} >
</div> {serviceAssignmentError}
)} </div>
</div> )}
</QuestionCard> </div>
)} </QuestionCard>
</> )}
); </>
);
} }
@@ -1,13 +1,17 @@
"use client"; "use client";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { LineChart } from "@mui/x-charts/LineChart"; import { LineChart } from "@mui/x-charts/LineChart";
import { MyOranizationsView } from "@core/Models/Company.model"; import {
import { DashboardFinancialsResult, getDashboardFinancials } from "../../landing/dashboard/Dashboard.Service"; DashboardFinancialsResult,
getDashboardFinancials,
} from "../../landing/dashboard/Dashboard.Service";
import { loadCollaboratorsByCompanyId } from "../../admin/(organization-profile)/org/profile/[id]/collaborators/Collaborators.Service"; import { loadCollaboratorsByCompanyId } from "../../admin/(organization-profile)/org/profile/[id]/collaborators/Collaborators.Service";
import { CompanyEmployeesView } from "@models/Collaborators.model"; import { CompanyEmployeesView } from "@models/Collaborators.model";
import UnpaidIncomeCard from "../UnpaidIncomeCard/UnpaidIncomeCard"; import UnpaidIncomeCard from "../UnpaidIncomeCard/UnpaidIncomeCard";
import styles from "./FinancialWidget.module.css"; import styles from "./FinancialWidget.module.css";
import dayjs from "dayjs"; import dayjs from "dayjs";
import OpenInNewOutlinedIcon from "@mui/icons-material/OpenInNewOutlined";
import { useNavigation } from "@core/app/hooks/goto";
export interface FinancialWidgetProps { export interface FinancialWidgetProps {
sessionUser: string; sessionUser: string;
@@ -15,7 +19,12 @@ export interface FinancialWidgetProps {
organizationName?: string; organizationName?: string;
} }
export default function FinancialWidget({ sessionUser, selectedOrgId, organizationName }: FinancialWidgetProps) { export default function FinancialWidget({
sessionUser,
selectedOrgId,
organizationName,
}: FinancialWidgetProps) {
const { goTo } = useNavigation();
const [selectedTimeframe, setSelectedTimeframe] = useState<"week" | "month" | "year">("month"); const [selectedTimeframe, setSelectedTimeframe] = useState<"week" | "month" | "year">("month");
const [selectedEmployeeId, setSelectedEmployeeId] = useState<string>(""); const [selectedEmployeeId, setSelectedEmployeeId] = useState<string>("");
const [collaborators, setCollaborators] = useState<CompanyEmployeesView[]>([]); const [collaborators, setCollaborators] = useState<CompanyEmployeesView[]>([]);
@@ -27,10 +36,12 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
useEffect(() => { useEffect(() => {
if (selectedOrgId) { if (selectedOrgId) {
loadCollaboratorsByCompanyId({ companyId: selectedOrgId }).then((res) => { loadCollaboratorsByCompanyId({ companyId: selectedOrgId })
setCollaborators(res); .then((res) => {
setSelectedEmployeeId(""); // reset employee filter when org changes setCollaborators(res);
}).catch(console.error); setSelectedEmployeeId(""); // reset employee filter when org changes
})
.catch(console.error);
} }
}, [selectedOrgId, sessionUser]); }, [selectedOrgId, sessionUser]);
@@ -43,14 +54,17 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
sessionUser, sessionUser,
companyId: selectedOrgId, companyId: selectedOrgId,
timeframe: selectedTimeframe, timeframe: selectedTimeframe,
employeeId: selectedEmployeeId || undefined employeeId: selectedEmployeeId || undefined,
}).then((res) => { })
setFinancials(res); .then((res) => {
}).catch((err) => { setFinancials(res);
const errMsg = err.format ? err.format() : err.message; })
console.warn("Acceso denegado a métricas financieras: ", errMsg); .catch((err) => {
setError("No tienes permisos de administrador para esta organización."); const errMsg = err.format ? err.format() : err.message;
}).finally(() => setLoading(false)); console.warn("Acceso denegado a métricas financieras: ", errMsg);
setError("No tienes permisos de administrador para esta organización.");
})
.finally(() => setLoading(false));
} }
}, [selectedOrgId, selectedTimeframe, selectedEmployeeId, sessionUser]); }, [selectedOrgId, selectedTimeframe, selectedEmployeeId, sessionUser]);
@@ -64,15 +78,22 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
const previous = financials.previousPeriodTotal; const previous = financials.previousPeriodTotal;
if (previous === 0) { if (previous === 0) {
if (current > 0) return <span className={styles.positive}>+100% vs periodo anterior</span>; if (current > 0)
return <span className={styles.positive}>+100% vs periodo anterior</span>;
return <span className={styles.neutral}>Sin datos previos</span>; return <span className={styles.neutral}>Sin datos previos</span>;
} }
const diff = current - previous; const diff = current - previous;
const percent = (diff / previous) * 100; const percent = (diff / previous) * 100;
if (percent > 0) return <span className={styles.positive}>+{percent.toFixed(1)}% vs periodo anterior</span>; if (percent > 0)
if (percent < 0) return <span className={styles.negative}>{percent.toFixed(1)}% vs periodo anterior</span>; return (
<span className={styles.positive}>+{percent.toFixed(1)}% vs periodo anterior</span>
);
if (percent < 0)
return (
<span className={styles.negative}>{percent.toFixed(1)}% vs periodo anterior</span>
);
return <span className={styles.neutral}>0% vs periodo anterior</span>; return <span className={styles.neutral}>0% vs periodo anterior</span>;
}; };
@@ -81,15 +102,46 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
if (error) { if (error) {
return ( return (
<div className={styles.container}> <div className={styles.container}>
<button className={styles.headerButton} type="button" onClick={() => setIsOpen((value) => !value)}> <button
className={styles.headerButton}
type="button"
onClick={() => setIsOpen((value) => !value)}
>
<h3 className={styles.title}> <h3 className={styles.title}>
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ''} Rendimiento Financiero {organizationName ? `- ${organizationName}` : ""}
</h3> </h3>
<span className={styles.toggleIcon}>{isOpen ? "" : "+"}</span> <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<button
type="button"
onClick={() => goTo(`/landing/org/${selectedOrgId}`)}
style={{
display: "inline-flex",
alignItems: "center",
gap: "6px",
padding: "6px 12px",
borderRadius: "999px",
color: "var(--green-darkestX1)",
border: "1px solid var(--green-darkestX1)",
background: "var(--white)",
textDecoration: "none",
fontSize: "14px",
fontWeight: 600,
cursor: "pointer",
transition: "all 0.2s ease",
}}
title="Ver perfil público de la organización"
>
<OpenInNewOutlinedIcon fontSize="small" />
Ver perfil
</button>
<span className={styles.toggleIcon}>{isOpen ? "" : "+"}</span>
</div>
</button> </button>
{isOpen && ( {isOpen && (
<div style={{ padding: '40px 20px', textAlign: 'center', color: '#6b7280' }}> <div style={{ padding: "40px 20px", textAlign: "center", color: "#6b7280" }}>
<p style={{ fontWeight: '600', marginBottom: '8px', color: '#374151' }}>Acceso Restringido</p> <p style={{ fontWeight: "600", marginBottom: "8px", color: "#374151" }}>
Acceso Restringido
</p>
<p>{error}</p> <p>{error}</p>
</div> </div>
)} )}
@@ -98,67 +150,108 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
} }
const chartData = financials?.currentPeriodData || []; const chartData = financials?.currentPeriodData || [];
const xAxisData = chartData.map(d => { const xAxisData = chartData.map((d) => {
// format label nicer depending on timeframe // format label nicer depending on timeframe
if (selectedTimeframe === "year") return dayjs(d.date).format("MMM YYYY"); if (selectedTimeframe === "year") return dayjs(d.date).format("MMM YYYY");
return dayjs(d.date).format("DD/MM"); return dayjs(d.date).format("DD/MM");
}); });
const seriesData = chartData.map(d => d.amount); const seriesData = chartData.map((d) => d.amount);
const hasChartData = chartData.some(d => d.amount > 0); const hasChartData = chartData.some((d) => d.amount > 0);
return ( return (
<div className={styles.container}> <div className={styles.container}>
<button className={styles.headerButton} type="button" onClick={() => setIsOpen((value) => !value)}> <button
className={styles.headerButton}
type="button"
onClick={() => setIsOpen((value) => !value)}
>
<h3 className={styles.title}> <h3 className={styles.title}>
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ''} Rendimiento Financiero {organizationName ? `- ${organizationName}` : ""}
</h3> </h3>
<span className={styles.toggleIcon}>{isOpen ? "" : "+"}</span> <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<button
type="button"
onClick={() => goTo(`/landing/org/${selectedOrgId}`)}
style={{
display: "inline-flex",
alignItems: "center",
gap: "6px",
padding: "6px 12px",
borderRadius: "999px",
color: "var(--green-darkestX1)",
border: "1px solid var(--green-darkestX1)",
background: "var(--white)",
textDecoration: "none",
fontSize: "14px",
fontWeight: 600,
cursor: "pointer",
transition: "all 0.2s ease",
}}
title="Ver perfil público de la organización"
>
<OpenInNewOutlinedIcon fontSize="small" />
Ver perfil
</button>
<span className={styles.toggleIcon}>{isOpen ? "" : "+"}</span>
</div>
</button> </button>
{isOpen && ( {isOpen && (
<> <>
<div className={styles.filters}> <div className={styles.filters}>
<select <select
className={styles.select} className={styles.select}
value={selectedTimeframe} value={selectedTimeframe}
onChange={e => setSelectedTimeframe(e.target.value as "week" | "month" | "year")} onChange={(e) =>
> setSelectedTimeframe(e.target.value as "week" | "month" | "year")
<option value="week">Última Semana</option> }
<option value="month">Último Mes</option> >
<option value="year">Último Año</option> <option value="week">Última Semana</option>
</select> <option value="month">Último Mes</option>
<option value="year">Último Año</option>
</select>
<select <select
className={styles.select} className={styles.select}
value={selectedEmployeeId} value={selectedEmployeeId}
onChange={e => setSelectedEmployeeId(e.target.value)} onChange={(e) => setSelectedEmployeeId(e.target.value)}
> >
<option value="">Todos los Profesionales</option> <option value="">Todos los Profesionales</option>
{collaborators.map(c => ( {collaborators.map((c) => (
<option key={c.id} value={c.id}>{c.fullName}</option> <option key={c.id} value={c.id}>
))} {c.fullName}
</select> </option>
))}
</select>
</div> </div>
<div className={styles.metricsRow}> <div className={styles.metricsRow}>
<div className={styles.metricBox}> <div className={styles.metricBox}>
<span className={styles.metricLabel}>Ingresos del Periodo</span> <span className={styles.metricLabel}>Ingresos del Periodo</span>
<span className={styles.metricValue}> <span className={styles.metricValue}>
{loading ? "..." : formatCurrency(financials?.currentPeriodTotal || 0)} {loading
</span> ? "..."
<div className={styles.metricComparison}> : formatCurrency(financials?.currentPeriodTotal || 0)}
{!loading && renderComparison()} </span>
</div> <div className={styles.metricComparison}>
</div> {!loading && renderComparison()}
</div>
</div>
{financials && ( {financials && <UnpaidIncomeCard value={financials.unpaidToday} />}
<UnpaidIncomeCard value={financials.unpaidToday} />
)}
</div> </div>
{loading && ( {loading && (
<div className={styles.chartContainer}> <div className={styles.chartContainer}>
<div style={{display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', color: '#9ca3af'}}> <div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%",
color: "#9ca3af",
}}
>
Cargando datos... Cargando datos...
</div> </div>
</div> </div>
@@ -168,57 +261,68 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
<div className={styles.chartContainer}> <div className={styles.chartContainer}>
<LineChart <LineChart
height={350} height={350}
xAxis={[{ xAxis={[
scaleType: 'point', {
data: xAxisData, scaleType: "point",
}]} data: xAxisData,
},
]}
series={[ series={[
{ {
data: seriesData, data: seriesData,
color: 'rgb(36, 169, 53)', color: "rgb(36, 169, 53)",
area: true, area: true,
showMark: true, showMark: true,
curve: 'monotoneX', curve: "monotoneX",
valueFormatter: (val: number | null) => val ? formatCurrency(val) : "0", valueFormatter: (val: number | null) =>
val ? formatCurrency(val) : "0",
}, },
]} ]}
grid={{ horizontal: true }} grid={{ horizontal: true }}
margin={{ top: 20, bottom: 40, left: 70, right: 20 }} margin={{ top: 20, bottom: 40, left: 70, right: 20 }}
sx={{ sx={{
'.MuiLineElement-root': { ".MuiLineElement-root": {
strokeWidth: 3, strokeWidth: 3,
}, },
'.MuiAreaElement-root': { ".MuiAreaElement-root": {
fill: 'url(#gradient)', fill: "url(#gradient)",
}, },
'.MuiChartsGrid-line': { ".MuiChartsGrid-line": {
strokeDasharray: '5 5', strokeDasharray: "5 5",
stroke: '#e5e7eb', stroke: "#e5e7eb",
}, },
'.MuiChartsAxis-line': { ".MuiChartsAxis-line": {
stroke: 'transparent', stroke: "transparent",
}, },
'.MuiChartsAxis-tick': { ".MuiChartsAxis-tick": {
stroke: 'transparent', stroke: "transparent",
}, },
'.MuiChartsAxis-tickLabel': { ".MuiChartsAxis-tickLabel": {
fill: '#9ca3af', fill: "#9ca3af",
fontFamily: 'inherit', fontFamily: "inherit",
fontSize: '12px', fontSize: "12px",
fontWeight: 500, fontWeight: 500,
}, },
'.MuiMarkElement-root': { ".MuiMarkElement-root": {
stroke: 'rgb(36, 169, 53)', stroke: "rgb(36, 169, 53)",
strokeWidth: 2, strokeWidth: 2,
fill: '#ffffff', fill: "#ffffff",
scale: '1.2', scale: "1.2",
} },
}} }}
> >
<defs> <defs>
<linearGradient id="gradient" x1="0" y1="0" x2="0" y2="1"> <linearGradient id="gradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="rgb(36, 169, 53)" stopOpacity={0.3}/> <stop
<stop offset="95%" stopColor="rgb(36, 169, 53)" stopOpacity={0.0}/> offset="5%"
stopColor="rgb(36, 169, 53)"
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor="rgb(36, 169, 53)"
stopOpacity={0.0}
/>
</linearGradient> </linearGradient>
</defs> </defs>
</LineChart> </LineChart>
@@ -5,7 +5,7 @@
right: 0px; right: 0px;
height: 70px; height: 70px;
overflow: hidden; overflow: hidden;
z-index: 1; z-index: 100;
pointer-events: none; pointer-events: none;
} }
@@ -17,6 +17,7 @@ import classNames from "classnames";
import { useNavigation } from "@core/app/hooks/goto"; import { useNavigation } from "@core/app/hooks/goto";
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined"; import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import Dialog from "@mui/material/Dialog"; import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent"; import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle"; import DialogTitle from "@mui/material/DialogTitle";
@@ -69,6 +70,14 @@ export default function OrganizationHeader(props: OrganizationHeaderParams): Rea
icon: <ShareOutlinedIcon />, icon: <ShareOutlinedIcon />,
}); });
menu.add({
text: "Ver perfil",
onClick: () => {
goTo(`/landing/org/${props.data.id}`);
},
icon: <OpenInNewIcon />,
});
menu.add({ menu.add({
text: "Notificaciones", text: "Notificaciones",
onClick: () => { onClick: () => {
@@ -0,0 +1,187 @@
"use client";
import { useState, useEffect } from "react";
import { Grid2, IconButton, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import Button from "@mui/material/Button";
import { ThemeProvider } from "@emotion/react";
import { PopoverPicker } from "@components/ColorPicker/ColorPicker";
import ImagePicker from "@components/ImagePicker/ImagePicker";
import { useAlert } from "@core/Store/Alert.Store";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { useOrganizationHeaderStore } from "@core/Store/OrganizationHeader.Store";
import { updateOrganizationColors, uploadHeaderImage } from "@services/Header.Edit.Service";
import { UpdateCompanyParams } from "@models/Company.model";
interface HeaderEditPopupProps {
open: boolean;
onClose: () => void;
companyId: string;
headerColor: string;
headerFontColor: string;
headerFontShadowColor: string;
headerImage: string;
onSaved: () => void;
onRefresh?: () => void;
}
export default function HeaderEditPopup(props: HeaderEditPopupProps) {
const { open, onClose, companyId, headerColor, headerFontColor, headerFontShadowColor, headerImage, onSaved, onRefresh } = props;
const alert = useAlert();
const SessionInfo = useSessionStore();
const organizationHeader = useOrganizationHeaderStore();
const [headerColorState, setHeaderColorState] = useState("");
const [headerFontColorState, setHeaderFontColorState] = useState("");
const [headerFontShadowColorState, setHeaderFontShadowColorState] = useState("");
const [loading, setLoading] = useState(false);
// Sync local state when values change externally
useEffect(() => {
if (open) {
setHeaderColorState(headerColor || "");
setHeaderFontColorState(headerFontColor || "");
setHeaderFontShadowColorState(headerFontShadowColor || "");
setLoading(false);
}
}, [open, headerColor, headerFontColor, headerFontShadowColor]);
const handleSaveColors = async () => {
setLoading(true);
try {
const updData: UpdateCompanyParams = {
id: companyId,
headerColor: headerColorState,
headerFontColor: headerFontColorState,
headerFontShadowColor: headerFontShadowColorState,
sessionUser: SessionInfo.userId,
};
await updateOrganizationColors(updData);
organizationHeader.setHeaderColor(headerColorState);
organizationHeader.setHeaderFontColor(headerFontColorState);
organizationHeader.setHeaderFontShadowColor(headerFontShadowColorState);
alert.showSuccess("Colores actualizados");
onSaved();
onRefresh?.();
} catch (error) {
const formatted = error instanceof Error ? error.message : "Error al guardar los colores";
alert.showError(formatted || "Error al guardar los colores");
} finally {
setLoading(false);
}
};
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setLoading(true);
try {
const formData = new FormData();
formData.append("companyId", companyId);
formData.append("sessionUser", SessionInfo.userId);
formData.append("file", file);
uploadHeaderImage(formData).then(() => {
alert.showSuccess("Imagen actualizada");
onSaved();
onRefresh?.();
}).catch((error) => {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
}).finally(() => {
setLoading(false);
});
} catch (error) {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
setLoading(false);
}
};
return (
<ThemeProvider theme={turnosXpressTheme}>
<Dialog
open={open}
onClose={onClose}
maxWidth="sm"
fullWidth
PaperProps={{
sx: {
borderRadius: 2,
height: 500,
},
}}
>
<DialogTitle sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
Personalizar
<IconButton onClick={onClose} size="small">
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent dividers sx={{ p: 3 }}>
{/* Colores */}
<Grid2 container spacing={1} mb={3}>
<Grid2 size={4}>
<PopoverPicker
placeholder="Fondo"
color={headerColorState}
onChange={(color: string) => {
setHeaderColorState(color);
}}
/>
</Grid2>
<Grid2 size={4}>
<PopoverPicker
placeholder="Fuente"
color={headerFontColorState}
onChange={(color: string) => {
setHeaderFontColorState(color);
}}
/>
</Grid2>
<Grid2 size={4}>
<PopoverPicker
placeholder="Sombra"
color={headerFontShadowColorState}
onChange={(color: string) => {
setHeaderFontShadowColorState(color);
}}
/>
</Grid2>
</Grid2>
{/* Imagen */}
<ImagePicker
src={headerImage}
alt="Cabecera"
style={{ width: "100%", height: 120, borderRadius: 8 }}
readOnly={false}
onChange={handleImageChange}
imageSizeSrc="/org-header-size.webp"
mbLimit={5}
/>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button onClick={onClose}>Cancelar</Button>
<Button
onClick={handleSaveColors}
autoFocus
color="success"
variant="contained"
disabled={loading}
>
Guardar
</Button>
</DialogActions>
</Dialog>
</ThemeProvider>
);
}
@@ -0,0 +1,116 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import HeaderEditPopup from "./HeaderEditPopup";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { checkOrgAdmin } from "@services/Header.Edit.Service";
interface OrganizationHeaderEditProps {
companyId: string;
headerColor?: string;
headerFontColor?: string;
headerFontShadowColor?: string;
headerImage?: string;
}
export default function OrganizationHeaderEdit({
companyId,
headerColor = "",
headerFontColor = "",
headerFontShadowColor = "",
headerImage = "",
}: OrganizationHeaderEditProps) {
const router = useRouter();
const SessionInfo = useSessionStore();
const [isOrgAdmin, setIsOrgAdmin] = useState(false);
const [showEditPopup, setShowEditPopup] = useState(false);
useEffect(() => {
if (!SessionInfo.userId || !companyId) {
setIsOrgAdmin(false);
const existing = document.getElementById("edit-header-btn");
if (existing) existing.remove();
return;
}
let cancelled = false;
checkOrgAdmin(companyId, SessionInfo.userId)
.then((isAdmin) => {
if (cancelled) return;
setIsOrgAdmin(isAdmin);
const wrapper = document.getElementById("header-wrapper");
if (!wrapper) return;
if (isAdmin) {
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
const btn = document.createElement("div");
btn.id = "edit-header-btn";
btn.innerHTML = `
<button style="
position: absolute;
top: 12px;
right: 12px;
width: 40px;
height: 40px;
border-radius: 50%;
background: rgba(0,0,0,0.45);
color: white;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
transition: background 0.2s;
" onmouseover="this.style.background='rgba(0,0,0,0.7)'" onmouseout="this.style.background='rgba(0,0,0,0.45)'">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg>
</button>
`;
btn.querySelector("button")!.addEventListener("click", () =>
setShowEditPopup(true),
);
wrapper.appendChild(btn);
} else {
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
}
})
.catch(() => {
if (cancelled) return;
setIsOrgAdmin(false);
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
});
return () => {
cancelled = true;
const existing = document.getElementById("edit-header-btn");
if (existing) existing.remove();
};
}, [SessionInfo.userId, companyId]);
return (
<>
{isOrgAdmin && (
<HeaderEditPopup
open={showEditPopup}
onClose={() => setShowEditPopup(false)}
companyId={companyId}
headerColor={headerColor}
headerFontColor={headerFontColor}
headerFontShadowColor={headerFontShadowColor}
headerImage={headerImage}
onSaved={() => {
setShowEditPopup(false);
}}
onRefresh={() => router.refresh()}
/>
)}
</>
);
}
@@ -6,6 +6,7 @@ import { PublicServiceView } from "@models/Service.model";
import style from "./style.module.css"; import style from "./style.module.css";
import { getServiceImage } from "@core/helpers/getServiceImage"; import { getServiceImage } from "@core/helpers/getServiceImage";
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary"; import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
import EditIcon from "@mui/icons-material/Edit";
export type FindResultsViewMode = "grid" | "card"; export type FindResultsViewMode = "grid" | "card";
@@ -14,6 +15,8 @@ export interface ProductItemProps {
width?: number | string; width?: number | string;
viewMode?: FindResultsViewMode; viewMode?: FindResultsViewMode;
dragging?: boolean; dragging?: boolean;
isAdmin?: boolean;
onImageEdit?: () => void;
} }
export default function ProductItem(props: ProductItemProps) { export default function ProductItem(props: ProductItemProps) {
@@ -21,6 +24,8 @@ export default function ProductItem(props: ProductItemProps) {
const { product } = props; const { product } = props;
const { viewMode = "card" } = props; const { viewMode = "card" } = props;
const { dragging = false } = props; const { dragging = false } = props;
const { isAdmin = false } = props;
const { onImageEdit } = props;
const { goTo } = useNavigation(); const { goTo } = useNavigation();
return ( return (
@@ -38,7 +43,7 @@ export default function ProductItem(props: ProductItemProps) {
textAlign: "center", textAlign: "center",
padding: "10px", padding: "10px",
border: "solid 1px rgba(0, 0, 0, 0.1)", border: "solid 1px rgba(0, 0, 0, 0.1)",
cursor: "pointer", cursor: isAdmin ? "default" : "pointer",
position: "relative", position: "relative",
}} }}
onClick={() => { onClick={() => {
@@ -58,6 +63,11 @@ export default function ProductItem(props: ProductItemProps) {
display: "block", display: "block",
}} }}
/> />
{isAdmin && (
<span className={style.adminEditButton} onClick={(e) => { e.stopPropagation(); onImageEdit?.(); }}>
<EditIcon fontSize="small" />
</span>
)}
<ServiceRatingSummary <ServiceRatingSummary
serviceId={product.id} serviceId={product.id}
variant="card" variant="card"
@@ -8,6 +8,32 @@
bottom: 8px; bottom: 8px;
} }
.adminEditButton {
position: absolute;
top: 8px;
right: 8px;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.9);
border-radius: 50%;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
z-index: 10;
}
.adminEditButton:hover {
background: var(--wine-red);
transform: scale(1.1);
}
.adminEditButton:hover svg {
color: white !important;
}
.cardHeader { .cardHeader {
margin: 10px 0; margin: 10px 0;
text-align: center; text-align: center;
@@ -0,0 +1,187 @@
"use client";
import { useState, useEffect } from "react";
import { Grid2, IconButton, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import Button from "@mui/material/Button";
import { ThemeProvider } from "@emotion/react";
import { PopoverPicker } from "@components/ColorPicker/ColorPicker";
import ImagePicker from "@components/ImagePicker/ImagePicker";
import { useAlert } from "@core/Store/Alert.Store";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { useOrganizationHeaderStore } from "@core/Store/OrganizationHeader.Store";
import { updateOrganizationColors, uploadHeaderImage } from "@services/Header.Edit.Service";
import { UpdateCompanyParams } from "@models/Company.model";
interface HeaderEditPopupProps {
open: boolean;
onClose: () => void;
companyId: string;
headerColor: string;
headerFontColor: string;
headerFontShadowColor: string;
headerImage: string;
onSaved: () => void;
onRefresh?: () => void;
}
export default function HeaderEditPopup(props: HeaderEditPopupProps) {
const { open, onClose, companyId, headerColor, headerFontColor, headerFontShadowColor, headerImage, onSaved, onRefresh } = props;
const alert = useAlert();
const SessionInfo = useSessionStore();
const organizationHeader = useOrganizationHeaderStore();
const [headerColorState, setHeaderColorState] = useState("");
const [headerFontColorState, setHeaderFontColorState] = useState("");
const [headerFontShadowColorState, setHeaderFontShadowColorState] = useState("");
const [loading, setLoading] = useState(false);
// Sync local state when values change externally
useEffect(() => {
if (open) {
setHeaderColorState(headerColor || "");
setHeaderFontColorState(headerFontColor || "");
setHeaderFontShadowColorState(headerFontShadowColor || "");
setLoading(false);
}
}, [open, headerColor, headerFontColor, headerFontShadowColor]);
const handleSaveColors = async () => {
setLoading(true);
try {
const updData: UpdateCompanyParams = {
id: companyId,
headerColor: headerColorState,
headerFontColor: headerFontColorState,
headerFontShadowColor: headerFontShadowColorState,
sessionUser: SessionInfo.userId,
};
await updateOrganizationColors(updData);
organizationHeader.setHeaderColor(headerColorState);
organizationHeader.setHeaderFontColor(headerFontColorState);
organizationHeader.setHeaderFontShadowColor(headerFontShadowColorState);
alert.showSuccess("Colores actualizados");
onSaved();
onRefresh?.();
} catch (error) {
const formatted = error instanceof Error ? error.message : "Error al guardar los colores";
alert.showError(formatted || "Error al guardar los colores");
} finally {
setLoading(false);
}
};
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setLoading(true);
try {
const formData = new FormData();
formData.append("companyId", companyId);
formData.append("sessionUser", SessionInfo.userId);
formData.append("file", file);
uploadHeaderImage(formData).then(() => {
alert.showSuccess("Imagen actualizada");
onSaved();
onRefresh?.();
}).catch((error) => {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
}).finally(() => {
setLoading(false);
});
} catch (error) {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
setLoading(false);
}
};
return (
<ThemeProvider theme={turnosXpressTheme}>
<Dialog
open={open}
onClose={onClose}
maxWidth="sm"
fullWidth
PaperProps={{
sx: {
borderRadius: 2,
height: 500,
},
}}
>
<DialogTitle sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
Personalizar
<IconButton onClick={onClose} size="small">
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent dividers sx={{ p: 3 }}>
{/* Colores */}
<Grid2 container spacing={1} mb={3}>
<Grid2 size={4}>
<PopoverPicker
placeholder="Fondo"
color={headerColorState}
onChange={(color: string) => {
setHeaderColorState(color);
}}
/>
</Grid2>
<Grid2 size={4}>
<PopoverPicker
placeholder="Fuente"
color={headerFontColorState}
onChange={(color: string) => {
setHeaderFontColorState(color);
}}
/>
</Grid2>
<Grid2 size={4}>
<PopoverPicker
placeholder="Sombra"
color={headerFontShadowColorState}
onChange={(color: string) => {
setHeaderFontShadowColorState(color);
}}
/>
</Grid2>
</Grid2>
{/* Imagen */}
<ImagePicker
src={headerImage}
alt="Cabecera"
style={{ width: "100%", height: 120, borderRadius: 8 }}
readOnly={false}
onChange={handleImageChange}
imageSizeSrc="/org-header-size.webp"
mbLimit={5}
/>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button onClick={onClose}>Cancelar</Button>
<Button
onClick={handleSaveColors}
autoFocus
color="success"
variant="contained"
disabled={loading}
>
Guardar
</Button>
</DialogActions>
</Dialog>
</ThemeProvider>
);
}
@@ -0,0 +1,13 @@
import ApiRequest from "@services/Api.Service";
import { UpdateCompanyParams } from "@models/Company.model";
import { ApiVoidResult } from "@models/Api.VoidResult.type";
export const updateOrganizationsById = async (
data: UpdateCompanyParams
): Promise<ApiVoidResult> => {
return ApiRequest.post<ApiVoidResult>("companies/update", data);
};
export const uploadHeaderImage = async (data: FormData): Promise<ApiVoidResult> => {
return ApiRequest.postFile<ApiVoidResult>("companies/upload-header", data);
};
@@ -45,7 +45,9 @@ export default async function OrganizationPublicProfile({ params, children }: Pr
<div className="homeCentered"> <div className="homeCentered">
{orgData.id && ( {orgData.id && (
<> <>
<OrganizationHeader organization={orgData} /> <div style={{ position: "relative" }} id="header-wrapper">
<OrganizationHeader organization={orgData} />
</div>
<OrganizationDataConnector orgData={orgData} /> <OrganizationDataConnector orgData={orgData} />
<div>{children}</div> <div>{children}</div>
</> </>
+143 -17
View File
@@ -43,7 +43,10 @@ import { useSessionStore } from "@core/Store/Sesion.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@core/Store/EventHandler.Store"; import { EVENT_TYPES, useEventHandlerStore } from "@core/Store/EventHandler.Store";
import { useAlert } from "@core/Store/Alert.Store"; import { useAlert } from "@core/Store/Alert.Store";
import { IPost } from "@core/Models/Posts.model"; import { IPost } from "@core/Models/Posts.model";
import { preprocessQuillHtml, transformQuillContentForDisplay } from "@core/app/helpers/htmlSainitize"; import {
preprocessQuillHtml,
transformQuillContentForDisplay,
} from "@core/app/helpers/htmlSainitize";
import { useSearchParams } from "next/navigation"; import { useSearchParams } from "next/navigation";
import { ThemeProvider } from "@emotion/react"; import { ThemeProvider } from "@emotion/react";
@@ -55,12 +58,14 @@ import DownIcon from "@mui/icons-material/ArrowDownwardRounded";
import PinIcon from "@mui/icons-material/PushPin"; import PinIcon from "@mui/icons-material/PushPin";
import EditIcon from "@mui/icons-material/AutoFixHigh"; import EditIcon from "@mui/icons-material/AutoFixHigh";
import turnosXpressTheme from "@core/app/theme/turnosXpress"; import turnosXpressTheme from "@core/app/theme/turnosXpress";
import { useParams } from "next/navigation"; import { useParams, useRouter } from "next/navigation";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useConfirmStore } from "@core/Store/Confirm.Store"; import { useConfirmStore } from "@core/Store/Confirm.Store";
import ReviewsCarousel from "@core/app/components/ReviewsCarousel/ReviewsCarousel"; import ReviewsCarousel from "@core/app/components/ReviewsCarousel/ReviewsCarousel";
import OrganizationProfessionals from "@core/app/components/OrganizationProfessionals/OrganizationProfessionals"; import OrganizationProfessionals from "@core/app/components/OrganizationProfessionals/OrganizationProfessionals";
import { RatingTargetType } from "@core/Models/Ratings.model"; import { RatingTargetType } from "@core/Models/Ratings.model";
import HeaderEditPopup from "./HeaderEditPopup";
import { checkOrgAdmin } from "./post.service";
enum VIEW { enum VIEW {
POSTS = "posts", POSTS = "posts",
@@ -76,6 +81,7 @@ type UrlData = {
export default function OrganizationPublicProfile() { export default function OrganizationPublicProfile() {
const data = useParams<UrlData>(); const data = useParams<UrlData>();
const oid = data.oid; const oid = data.oid;
const router = useRouter();
const OrganizationData = useOrgDataStore(); const OrganizationData = useOrgDataStore();
const [position, setPosition] = useState<[number, number]>([0, 0]); const [position, setPosition] = useState<[number, number]>([0, 0]);
const [orgData, setOrgData] = useState<PublicOrganizationView>(); const [orgData, setOrgData] = useState<PublicOrganizationView>();
@@ -96,8 +102,85 @@ export default function OrganizationPublicProfile() {
const [posts, setPosts] = useState<IPost[]>([]); const [posts, setPosts] = useState<IPost[]>([]);
const [authorizedUsers, setAuthorizedUsers] = useState<string[]>([]); const [authorizedUsers, setAuthorizedUsers] = useState<string[]>([]);
const [currentPage, setCurrentPage] = useState<number>(1); const [currentPage, setCurrentPage] = useState<number>(1);
const [isOrgAdmin, setIsOrgAdmin] = useState<boolean>(false);
const [showEditPopup, setShowEditPopup] = useState<boolean>(false);
const SessionInfo = useSessionStore(); const SessionInfo = useSessionStore();
// Unified effect: check admin status and manage edit button DOM element
useEffect(() => {
if (!SessionInfo.userId || !oid) {
setIsOrgAdmin(false);
const existing = document.getElementById("edit-header-btn");
if (existing) existing.remove();
return;
}
let cancelled = false;
checkOrgAdmin(oid, SessionInfo.userId)
.then((isAdmin) => {
if (cancelled) return;
console.log("isAdmin:", isAdmin);
setIsOrgAdmin(isAdmin);
// Append or remove button based on the result
const wrapper = document.getElementById("header-wrapper");
if (!wrapper) return;
if (isAdmin) {
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
const btn = document.createElement("div");
btn.id = "edit-header-btn";
btn.innerHTML = `
<button style="
position: absolute;
top: 12px;
right: 12px;
width: 40px;
height: 40px;
border-radius: 50%;
background: rgba(0,0,0,0.45);
color: white;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
transition: background 0.2s;
" onmouseover="this.style.background='rgba(0,0,0,0.7)'" onmouseout="this.style.background='rgba(0,0,0,0.45)'">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg>
</button>
`;
btn.querySelector("button")!.addEventListener("click", () =>
setShowEditPopup(true),
);
wrapper.appendChild(btn);
} else {
// Remove button for non-admin users
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
}
})
.catch(() => {
if (cancelled) return;
setIsOrgAdmin(false);
// Ensure button is removed on error
const existingBtn = document.getElementById("edit-header-btn");
if (existingBtn) existingBtn.remove();
});
// Cleanup: mark as cancelled and remove button
return () => {
cancelled = true;
const existing = document.getElementById("edit-header-btn");
if (existing) existing.remove();
};
}, [SessionInfo.userId, oid]);
const eventHandler = useEventHandlerStore(); const eventHandler = useEventHandlerStore();
const alert = useAlert(); const alert = useAlert();
const confirm = useConfirmStore(); const confirm = useConfirmStore();
@@ -338,7 +421,8 @@ export default function OrganizationPublicProfile() {
return response.data; return response.data;
} }
const newPosts = response.data.filter( const newPosts = response.data.filter(
(newPost) => !prevPosts.some((prevPost) => prevPost._id === newPost._id), (newPost) =>
!prevPosts.some((prevPost) => prevPost._id === newPost._id),
); );
return [...prevPosts, ...newPosts]; return [...prevPosts, ...newPosts];
@@ -508,7 +592,11 @@ export default function OrganizationPublicProfile() {
gap: "10px", gap: "10px",
}} }}
> >
<WhatsappShareButton title={shareTitle} separator=":: " url={window.location.href}> <WhatsappShareButton
title={shareTitle}
separator=":: "
url={window.location.href}
>
<WhatsAppShareIcon size={32} round /> <WhatsAppShareIcon size={32} round />
</WhatsappShareButton> </WhatsappShareButton>
<FacebookShareButton title={shareTitle} url={window.location.href}> <FacebookShareButton title={shareTitle} url={window.location.href}>
@@ -531,6 +619,21 @@ export default function OrganizationPublicProfile() {
return ( return (
<> <>
<HeaderConfProvider /> <HeaderConfProvider />
{isOrgAdmin && oid && orgData && (
<HeaderEditPopup
open={showEditPopup}
onClose={() => setShowEditPopup(false)}
companyId={oid}
headerColor={orgData.headerColor}
headerFontColor={orgData.headerFontColor}
headerFontShadowColor={orgData.headerFontShadowColor}
headerImage={orgData.headerFile}
onSaved={() => {
setShowEditPopup(false);
}}
onRefresh={() => router.refresh()}
/>
)}
{orgData && ( {orgData && (
<div className={style.organizationContent}> <div className={style.organizationContent}>
{showEditor && ( {showEditor && (
@@ -656,7 +759,9 @@ export default function OrganizationPublicProfile() {
)} )}
</div> </div>
{view === VIEW.SERVICES && ( {view === VIEW.SERVICES && (
<div style={{ display: "flex", justifyContent: "flex-end" }}> <div
style={{ display: "flex", justifyContent: "flex-end" }}
>
<ButtonGroup <ButtonGroup
variant="outlined" variant="outlined"
aria-label="Basic button group" aria-label="Basic button group"
@@ -711,7 +816,8 @@ export default function OrganizationPublicProfile() {
<div <div
style={{ style={{
textAlign: "center", textAlign: "center",
backgroundImage: "url(/no-conversation.webp)", backgroundImage:
"url(/no-conversation.webp)",
backgroundRepeat: "no-repeat", backgroundRepeat: "no-repeat",
backgroundPosition: "center center", backgroundPosition: "center center",
backgroundSize: "50% auto", backgroundSize: "50% auto",
@@ -726,7 +832,8 @@ export default function OrganizationPublicProfile() {
<div <div
key={post._id} key={post._id}
style={{ style={{
borderBottom: "1px solid var(--gray-light)", borderBottom:
"1px solid var(--gray-light)",
paddingTop: "5px", paddingTop: "5px",
paddingBottom: "10px", paddingBottom: "10px",
paddingLeft: "30px", paddingLeft: "30px",
@@ -740,7 +847,11 @@ export default function OrganizationPublicProfile() {
justifyContent: "space-between", justifyContent: "space-between",
}} }}
> >
<div style={{ color: "var(--gray-darkest)" }}> <div
style={{
color: "var(--gray-darkest)",
}}
>
{dayjs(post.createdAt).format( {dayjs(post.createdAt).format(
"DD MMMM YYYY HH:mm", "DD MMMM YYYY HH:mm",
)} )}
@@ -780,22 +891,30 @@ export default function OrganizationPublicProfile() {
color: "var(--gray-darkest)", color: "var(--gray-darkest)",
}} }}
> >
<ThemeProvider theme={turnosXpressTheme}> <ThemeProvider
theme={turnosXpressTheme}
>
<MaterialButton <MaterialButton
color="inherit" color="inherit"
startIcon={<ClipIcon />} startIcon={<ClipIcon />}
onClick={() => { onClick={() => {
fijarPost(`${post._id}`); fijarPost(
`${post._id}`,
);
}} }}
> >
{post.fixed ? "Liberar" : "Fijar"} {post.fixed
? "Liberar"
: "Fijar"}
</MaterialButton> </MaterialButton>
{post.fixed && ( {post.fixed && (
<> <>
<MaterialButton <MaterialButton
color="inherit" color="inherit"
startIcon={<UpIcon />} startIcon={
<UpIcon />
}
onClick={() => { onClick={() => {
moverPost( moverPost(
`${post._id}`, `${post._id}`,
@@ -808,7 +927,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton <MaterialButton
color="inherit" color="inherit"
startIcon={<DownIcon />} startIcon={
<DownIcon />
}
onClick={() => { onClick={() => {
moverPost( moverPost(
`${post._id}`, `${post._id}`,
@@ -824,7 +945,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton <MaterialButton
color="inherit" color="inherit"
onClick={() => { onClick={() => {
editarPost(`${post._id}`); editarPost(
`${post._id}`,
);
}} }}
> >
<EditIcon /> <EditIcon />
@@ -833,7 +956,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton <MaterialButton
color="inherit" color="inherit"
onClick={() => { onClick={() => {
eliminarPost(`${post._id}`); eliminarPost(
`${post._id}`,
);
}} }}
> >
<DeleteIcon /> <DeleteIcon />
@@ -858,7 +983,8 @@ export default function OrganizationPublicProfile() {
style={{ style={{
padding: "0px 0px 40px 0px", padding: "0px 0px 40px 0px",
display: "flex", display: "flex",
flexDirection: viewMode === "card" ? "row" : "column", flexDirection:
viewMode === "card" ? "row" : "column",
justifyContent: "start", justifyContent: "start",
gap: "20px", gap: "20px",
flexWrap: "wrap", flexWrap: "wrap",
@@ -65,3 +65,7 @@ export const toggleFixedPost = async (data: FixCompanyPostParams): Promise<void>
export const moveFixedPost = async (data: MoveCompanyFixedPostParams): Promise<void> => { export const moveFixedPost = async (data: MoveCompanyFixedPostParams): Promise<void> => {
return ApiRequest.post<void>("companies/move-fixed-post", data); return ApiRequest.post<void>("companies/move-fixed-post", data);
}; };
export const checkOrgAdmin = async (companyId: string, sessionUser: string): Promise<boolean> => {
return ApiRequest.post<boolean>("companies/check-admin", { companyId, sessionUser });
};
@@ -0,0 +1,10 @@
import ApiRequest from "@services/Api.Service";
import { ApiVoidResult } from "@models/Api.VoidResult.type";
export const uploadServiceImage = async (data: FormData): Promise<ApiVoidResult> => {
return ApiRequest.postFile<ApiVoidResult>("services/upload-image", data);
};
export const checkOrgAdmin = async (companyId: string, sessionUser: string): Promise<boolean> => {
return ApiRequest.post<boolean>("companies/check-admin", { companyId, sessionUser });
};
@@ -0,0 +1,59 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import ProductItem from "@core/app/components/ProductItem/ProductItem";
import { PublicServiceView } from "@models/Service.model";
import { PublicOrganizationView } from "@models/Company.model";
import ServiceImageEditPopup from "./ServiceImageEditPopup";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { checkOrgAdmin } from "@services/Header.Edit.Service";
interface ServiceDetailCardProps {
service: PublicServiceView;
organization: PublicOrganizationView;
}
export default function ServiceDetailCard({ service, organization }: ServiceDetailCardProps) {
const router = useRouter();
const SessionInfo = useSessionStore();
const [isAdmin, setIsAdmin] = useState(false);
const [showEditPopup, setShowEditPopup] = useState(false);
useEffect(() => {
if (!SessionInfo.userId || !organization.id || !service.id) return;
checkOrgAdmin(organization.id, SessionInfo.userId)
.then((result) => {
setIsAdmin(result);
})
.catch(() => {
setIsAdmin(false);
});
}, [SessionInfo.userId, organization.id, service.id]);
const handleImageSaved = () => {
setShowEditPopup(false);
router.refresh();
};
return (
<>
<ProductItem
product={service}
width="100%"
isAdmin={isAdmin}
onImageEdit={() => setShowEditPopup(true)}
/>
{isAdmin && (
<ServiceImageEditPopup
open={showEditPopup}
onClose={() => setShowEditPopup(false)}
serviceId={service.id}
companyId={organization.id}
currentImage={service.image}
onSaved={handleImageSaved}
/>
)}
</>
);
}
@@ -0,0 +1,105 @@
"use client";
import { useState } from "react";
import { IconButton, Dialog, DialogActions, DialogContent, DialogTitle, Button } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import { ThemeProvider } from "@emotion/react";
import ImagePicker from "@components/ImagePicker/ImagePicker";
import { useAlert } from "@core/Store/Alert.Store";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { uploadServiceImage } from "@services/Header.Edit.Service";
interface ServiceImageEditPopupProps {
open: boolean;
onClose: () => void;
serviceId: string;
companyId: string;
currentImage: string;
onSaved: () => void;
}
export default function ServiceImageEditPopup(props: ServiceImageEditPopupProps) {
const { open, onClose, serviceId, companyId, currentImage, onSaved } = props;
const alert = useAlert();
const SessionInfo = useSessionStore();
const [loading, setLoading] = useState(false);
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setLoading(true);
try {
const formData = new FormData();
formData.append("companyId", companyId);
formData.append("serviceId", serviceId);
formData.append("sessionUser", SessionInfo.userId);
formData.append("file", file);
uploadServiceImage(formData)
.then(() => {
alert.showSuccess("Imagen actualizada");
onSaved();
})
.catch((error) => {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
})
.finally(() => {
setLoading(false);
});
} catch (error) {
const formatted = error instanceof Error ? error.message : "Error al guardar la imagen";
alert.showError(formatted || "Error al guardar la imagen");
setLoading(false);
}
};
return (
<ThemeProvider theme={turnosXpressTheme}>
<Dialog
open={open}
onClose={onClose}
maxWidth="sm"
fullWidth
PaperProps={{
sx: {
borderRadius: 2,
width: 'auto',
height: 'auto',
},
}}
>
<DialogTitle sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", py: 2 }}>
Editar imagen del servicio
<IconButton onClick={onClose} size="small">
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent dividers sx={{ p: 3, display: "flex", justifyContent: "center" }}>
<ImagePicker
src={currentImage}
alt="Imagen del servicio"
style={{ width: 400, height: 400, borderRadius: 8 }}
readOnly={false}
onChange={handleImageChange}
imageSizeSrc="/service-image-size.webp"
mbLimit={5}
/>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2, pt: 1 }}>
<Button onClick={onClose}>Cancelar</Button>
<Button
onClick={() => {}}
disabled={loading}
>
Guardar
</Button>
</DialogActions>
</Dialog>
</ThemeProvider>
);
}
@@ -2,7 +2,6 @@ import AnimatedContainer from "@components/AnimatedConainer/AnimatedContainer";
import style from "./profile.module.css"; import style from "./profile.module.css";
import ApiServerService from "@services/Api.Server.Service"; import ApiServerService from "@services/Api.Server.Service";
import { PublicOrganizationServiceView } from "@core/Models/Service.model"; import { PublicOrganizationServiceView } from "@core/Models/Service.model";
import ProductItem from "@core/app/components/ProductItem/ProductItem";
import Appointment from "./components/Appointment/Appointment"; import Appointment from "./components/Appointment/Appointment";
import OrganizationHeader from "@components/Home/OrganizationHeader/OrganizationHeader"; import OrganizationHeader from "@components/Home/OrganizationHeader/OrganizationHeader";
import ProductGallery from "@core/app/components/Home/ProductsGallery/ProductGallery"; import ProductGallery from "@core/app/components/Home/ProductsGallery/ProductGallery";
@@ -12,6 +11,8 @@ import ServicePrivate from "@core/app/components/ServicePrivate/ServicePrivate";
import EvangelizeBanner from "@components/EvangelizeBanner/EvangelizeBanner"; import EvangelizeBanner from "@components/EvangelizeBanner/EvangelizeBanner";
import ReviewsCarousel from "@components/ReviewsCarousel/ReviewsCarousel"; import ReviewsCarousel from "@components/ReviewsCarousel/ReviewsCarousel";
import { RatingTargetType } from "@core/Models/Ratings.model"; import { RatingTargetType } from "@core/Models/Ratings.model";
import ServiceDetailCard from "./ServiceDetailCard";
import OrganizationHeaderEdit from "@components/OrganizationHeaderEdit/OrganizationHeaderEdit";
const GetServiceData = async (serviceId: string): Promise<PublicOrganizationServiceView> => { const GetServiceData = async (serviceId: string): Promise<PublicOrganizationServiceView> => {
try { try {
@@ -56,11 +57,20 @@ export default async function OrganizationPublicProfile({ params }: Props) {
<ScrollToTop /> <ScrollToTop />
<HeaderConfProvider /> <HeaderConfProvider />
<div className="homeCentered"> <div className="homeCentered">
<OrganizationHeader organization={organizationService.organization} /> <div id="header-wrapper" style={{ position: "relative" }}>
<OrganizationHeader organization={organizationService.organization} />
</div>
<OrganizationHeaderEdit
companyId={organizationService.organization.id}
headerColor={organizationService.organization.headerColor}
headerFontColor={organizationService.organization.headerFontColor}
headerFontShadowColor={organizationService.organization.headerFontShadowColor}
headerImage={organizationService.organization.headerFile}
/>
<div className={style.organizationContent}> <div className={style.organizationContent}>
<div className={style.serviceSide}> <div className={style.serviceSide}>
<div className={style.stickyWrapper}> <div className={style.stickyWrapper}>
<ProductItem product={organizationService.service} width="100%" /> <ServiceDetailCard service={organizationService.service} organization={organizationService.organization} />
</div> </div>
</div> </div>
<div className={style.bookingSide}> <div className={style.bookingSide}>