16 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
31 changed files with 1976 additions and 626 deletions
@@ -2,6 +2,9 @@ import crypto from "crypto";
import axios from "axios";
import forge from "node-forge";
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 {
ARCA_WSAA_ENVIRONMENT,
@@ -123,6 +126,23 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
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(
companyId: string,
sessionUser: string
@@ -730,6 +750,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const keys = forge.pki.rsa.generateKeyPair(2048);
@@ -778,6 +799,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
if (!data.certificatePem || !data.certificatePem.trim()) {
throw new Error("Se requiere el certificado ARCA");
@@ -836,6 +858,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const service = ARCA_WSAA_SERVICE.WSFE;
const environment = this.getArcaEnvironment();
@@ -853,6 +876,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const loginTicket = await this.getWsaaLoginTicket(data.companyId);
const environment = this.getArcaEnvironment();
@@ -886,6 +910,7 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
public async issueFacturaC(data: ArcaWsfeIssueFacturaCParams): Promise<ArcaWsfeIssueFacturaCResult> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
if (data.amount <= 0) {
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> {
await this.validateCompanyAdmin(data.companyId, data.sessionUser);
await this.requirePaymentsFeature(data.companyId);
const fiscalProfile = await this.requireActiveFiscalProfile(data.companyId, data.sessionUser);
const loginTicket = await this.getWsaaLoginTicket(data.companyId);
const environment = this.getArcaEnvironment();
@@ -1054,8 +1080,11 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
await validateSessionUser({ sessionUser: data.sessionUser });
let companyId: string | undefined;
if (data.companyId) {
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
companyId = data.companyId;
} else if (data.id) {
const credential = await this.arcaCredentials.findOne(data);
@@ -1067,12 +1096,13 @@ class ArcaCredentialsManager implements IArcaCredentialsManager {
companyId: String(credential.companyId),
sessionUser: data.sessionUser,
});
return [this.sanitizeCredential(credential)];
companyId = String(credential.companyId);
} else {
throw new Error("Se requiere una organización para buscar credenciales ARCA");
}
await this.requirePaymentsFeature(companyId);
const credentials = await this.arcaCredentials.find(data);
return credentials.map((credential) => this.sanitizeCredential(credential));
}
@@ -380,4 +380,5 @@ export interface ICompaniesManager {
sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>;
sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>;
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();
@@ -1,4 +1,7 @@
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 { OrganizationFiscalProfilesAdapterMongoose } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
import {
@@ -70,6 +73,21 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
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);
const existingProfile = await this.organizationFiscalProfiles.findOne({
@@ -140,6 +158,18 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
companyId: data.companyId,
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) {
const profile = await this.organizationFiscalProfiles.findOne(data);
@@ -152,6 +182,18 @@ class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesMa
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];
} else {
throw new Error("Se requiere una organización para buscar perfiles fiscales");
+10 -1
View File
@@ -63,6 +63,7 @@ import ClientsList from "../Clients/Clients";
import RepeatsList from "../Repeats/Repeats";
import { OAuth2Client } from "google-auth-library";
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
import dayjs from "dayjs";
const cleanEmail = (email: string): string => {
return email.toLowerCase().trim();
@@ -1087,10 +1088,18 @@ class UsersManager implements IUsersManager {
await this.users.update(data);
const fecha = dayjs().format("DD/MM/YYYY");
const hora = dayjs().format("HH:mm");
await NotificationsManager.sendEmail({
email: cleanEmail(sessionUser.email),
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")
@Post()
public async toggleFixedCompanyPost(
@Body() requestBody: FixCompanyPostParams
@Body() requestBody: FixCompanyPostParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().toggleFixedPost(requestBody);
@@ -62,7 +62,7 @@ export class MoveCompanyFixedPostController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async moveFixedCompanyPost(
@Body() requestBody: MoveCompanyFixedPostParams
@Body() requestBody: MoveCompanyFixedPostParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().moveFixedPost(requestBody);
@@ -86,7 +86,7 @@ export class SetNotificationsStatusCompanyController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async setNotificationAuto(
@Body() requestBody: SetNotificationAutoParams
@Body() requestBody: SetNotificationAutoParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().setNotificationAuto(requestBody);
@@ -110,7 +110,7 @@ export class SetPublishedStatusCompanyController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async setPublishedStatus(
@Body() requestBody: SetOrganizationPublishedStatusParams
@Body() requestBody: SetOrganizationPublishedStatusParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().setPublishedStatus(requestBody);
@@ -134,7 +134,7 @@ export class CreateCompanyController extends Controller {
@SuccessResponse(200, "La compañia fue creada con exito")
@Post()
public async createCompany(
@Body() requestBody: CreateCompanyParams
@Body() requestBody: CreateCompanyParams,
): Promise<ICompany | ApiValidationError> {
try {
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")
@Post()
public async deleteCompany(
@Body() requestBody: DeleteCompanyParams
@Body() requestBody: DeleteCompanyParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().deleteCompany(requestBody);
@@ -179,7 +179,7 @@ export class UpdateCompanyController extends Controller {
@SuccessResponse(200, "La compañia fue modificada con exito")
@Post()
public async updateCompany(
@Body() requestBody: UpdateCompanyParams
@Body() requestBody: UpdateCompanyParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().updateCompany(requestBody);
@@ -202,7 +202,7 @@ export class GetCompanyByIdController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async getById(
@Body() requestBody: OranizationsViewByIdParams
@Body() requestBody: OranizationsViewByIdParams,
): Promise<MyOranizationsView | ApiValidationError> {
try {
const companies = await new CompaniesService().getById(requestBody);
@@ -222,7 +222,7 @@ export class GetCompanyByUserController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async getByUserId(
@Body() requestBody: MyOranizationsViewParams
@Body() requestBody: MyOranizationsViewParams,
): Promise<MyOranizationsView[] | ApiValidationError> {
try {
const companies = await new CompaniesService().getByUserId(requestBody);
@@ -242,7 +242,7 @@ export class PaginateCompanyController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async paginateUsers(
@Body() requestBody: PaginateCompaniesParams
@Body() requestBody: PaginateCompaniesParams,
): Promise<PaginateCompaniesResults | ApiValidationError> {
try {
const users = await new CompaniesService().paginateCompanies(requestBody);
@@ -265,7 +265,7 @@ export class UploadCompanyHeaderController extends Controller {
public async uploadHeader(
@FormField() companyId: string,
@FormField() sessionUser: string,
@UploadedFile() file: Express.Multer.File
@UploadedFile() file: Express.Multer.File,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().setCompanyHeader({
@@ -295,7 +295,7 @@ export class UploadCompanyIconController extends Controller {
public async uploadIcon(
@FormField() companyId: string,
@FormField() sessionUser: string,
@UploadedFile() file: Express.Multer.File
@UploadedFile() file: Express.Multer.File,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().setCompanyIcon({
@@ -325,7 +325,7 @@ export class DeleteCompanyHeaderController extends Controller {
@SuccessResponse(200, "El archivo fue cargado con exito")
@Post()
public async deleteHeader(
@Body() data: DeleteCompanyFileParams
@Body() data: DeleteCompanyFileParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().deleteCompanyHeader(data);
@@ -349,7 +349,7 @@ export class DeleteCompanyIconController extends Controller {
@SuccessResponse(200, "El archivo fue cargado con exito")
@Post()
public async deleteIcon(
@Body() data: DeleteCompanyFileParams
@Body() data: DeleteCompanyFileParams,
): Promise<ApiVoidResult | ApiValidationError> {
try {
await new CompaniesService().deleteCompanyIcon(data);
@@ -372,7 +372,7 @@ export class filterAllOrganizationsController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async filterAllOrganizations(
@Body() requestBody: PaginateCompaniesParams
@Body() requestBody: PaginateCompaniesParams,
): Promise<TextObjectFilterResult[] | ApiValidationError> {
try {
const clients = await new CompaniesService().filterAll(requestBody);
@@ -392,7 +392,7 @@ export class CheckCompanyNameController extends Controller {
@SuccessResponse(200, "Done")
@Post()
public async checkName(
@Body() requestBody: { name: string }
@Body() requestBody: { name: string },
): Promise<{ valid: boolean } | ApiValidationError> {
try {
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 });
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 });
};
@@ -17,6 +17,7 @@ import ReceiptLongOutlinedIcon from "@mui/icons-material/ReceiptLongOutlined";
import { Grid2 } from "@mui/material";
import { ApiError } from "@models/Server.Error.model";
import style from "./page.module.css";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import {
findArcaActivities,
findOrganizationFiscalProfiles,
@@ -188,123 +189,125 @@ export default function OrganizationFiscalProfileEdit() {
return (
<>
<Location />
<div className={style.pageContainer}>
<section className={style.heroCard}>
<div className={style.heroIcon}>
<ReceiptLongOutlinedIcon />
</div>
<div>
<h2>Configuración fiscal</h2>
<p>
Estos datos se usan para emitir Factura C desde los movimientos de caja y para precargar el asistente ARCA.
</p>
</div>
</section>
<SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
<div className={style.pageContainer}>
<section className={style.heroCard}>
<div className={style.heroIcon}>
<ReceiptLongOutlinedIcon />
</div>
<div>
<h2>Configuración fiscal</h2>
<p>
Estos datos se usan para emitir Factura C desde los movimientos de caja y para precargar el asistente ARCA.
</p>
</div>
</section>
<section className={style.formSection}>
<h3>Datos del emisor</h3>
<Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="cuit"
placeholder="CUIT"
type="text"
value={cuit}
width="100%"
onChange={(event) => {
setCuit(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="legalName"
placeholder="Razón social"
type="text"
value={legalName}
width="100%"
onChange={(event) => {
setLegalName(event.target.value);
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
</section>
<section className={style.formSection}>
<h3>Datos del emisor</h3>
<Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="cuit"
placeholder="CUIT"
type="text"
value={cuit}
width="100%"
onChange={(event) => {
setCuit(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="legalName"
placeholder="Razón social"
type="text"
value={legalName}
width="100%"
onChange={(event) => {
setLegalName(event.target.value);
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
</section>
<section className={style.formSection}>
<div className={style.sectionHeader}>
<h3>Condición fiscal</h3>
<p>Seleccioná la condición declarada para esta organización.</p>
</div>
<div className={style.optionGroup} role="radiogroup" aria-label="Condición fiscal">
{fiscalConditionOptions.map((option) => {
const selected = taxCondition === option.id;
<section className={style.formSection}>
<div className={style.sectionHeader}>
<h3>Condición fiscal</h3>
<p>Seleccioná la condición declarada para esta organización.</p>
</div>
<div className={style.optionGroup} role="radiogroup" aria-label="Condición fiscal">
{fiscalConditionOptions.map((option) => {
const selected = taxCondition === option.id;
return (
<button
key={option.id}
type="button"
className={`${style.optionCard} ${selected ? style.optionCardSelected : ""}`}
onClick={() => {
setTaxCondition(option.id);
markNeedsSave();
}}
aria-pressed={selected}
>
<span className={style.optionTitle}>{option.title}</span>
<span className={style.optionDescription}>{option.description}</span>
</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
return (
<button
key={option.id}
type="button"
className={`${style.optionCard} ${selected ? style.optionCardSelected : ""}`}
onClick={() => {
setTaxCondition(option.id);
markNeedsSave();
}}
aria-pressed={selected}
>
<span className={style.optionTitle}>{option.title}</span>
<span className={style.optionDescription}>{option.description}</span>
</button>
);
})}
</div>
</section>
setActivityCode(selectedActivity?.id || "");
setActivityDescription(selectedActivity?.name || "");
markNeedsSave();
}}
/>
)}
<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>
<p className={style.helpText}>
{activityCode && activityDescription
? `${activityCode} - ${activityDescription}`
: "Seleccioná la actividad principal declarada en ARCA."}
</p>
</section>
</div>
{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
);
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 ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
@@ -118,18 +119,30 @@ export default function Org() {
</div>
<div className={style.serviceActions}>
<span className={style.servicePrice}>{formatPrice(data.price)}</span>
<IconButton
className={style.shareButton}
sx={{ position: "absolute", top: "15px", right: "15px" }}
onClick={(e) => {
e.stopPropagation();
setShareService(data);
}}
size="small"
title="Compartir servicio"
>
<ShareOutlinedIcon fontSize="small" />
</IconButton>
<div className={style.iconsRow}>
<IconButton
onClick={(e) => {
e.stopPropagation();
goTo(`/landing/service/${data.id}`);
}}
size="small"
title="Ver perfil público del servicio"
className={style.iconButton}
>
<OpenInNewIcon fontSize="small" />
</IconButton>
<IconButton
onClick={(e) => {
e.stopPropagation();
setShareService(data);
}}
size="small"
title="Compartir servicio"
className={style.iconButton}
>
<ShareOutlinedIcon fontSize="small" />
</IconButton>
</div>
</div>
</div>
);
@@ -71,26 +71,29 @@
display: flex;
flex-direction: column;
align-items: flex-end;
justify-content: flex-end; /* changed from space-between */
min-width: 100px;
justify-content: center;
gap: 12px;
min-width: 60px;
}
.servicePrice {
font-size: 18px;
font-weight: 800;
color: #1e293b;
margin-bottom: 0; /* removed bottom margin */
}
.shareButton {
.iconsRow {
display: flex;
align-items: center;
gap: 4px;
}
.iconButton {
color: #94a3b8;
transition: color 0.2s ease;
position: absolute;
top: 15px;
right: 15px;
}
.shareButton:hover {
.iconButton:hover {
color: var(--wine-dark);
}
@@ -206,6 +206,7 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
const [wapError, setWapError] = useState<string | null>(null);
// State for ARCA onboarding flow
const [arcaIsBlocked, setArcaIsBlocked] = useState(false);
const [arcaCuit, setArcaCuit] = useState("");
const [arcaLegalName, setArcaLegalName] = useState("");
const [arcaTaxCondition, setArcaTaxCondition] = useState<"MONOTRIBUTO" | "EXENTO">("MONOTRIBUTO");
@@ -277,6 +278,7 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
};
const loadOrganizationContext = (org: any) => {
setArcaIsBlocked(false);
setCreatedCompanyId(org.id || org._id);
setSelectedOrganization(org);
setOrgName(org.name || "");
@@ -499,6 +501,18 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
setWapQr(null);
setWapError(null);
} 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);
setArcaError(null);
setArcaLoading(false);
@@ -527,6 +541,19 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
setArcaStatusLabel(getArcaStatusLabel(credential.status));
}).catch(console.error);
} 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);
setArcaError(null);
setArcaLoading(false);
@@ -2415,8 +2442,42 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
if (flowId === "public-link") return renderPublicLinkFlow();
if (flowId === "notifications") return renderNotificationsFlow();
if (flowId === "whatsapp-bot") return renderWhatsAppBotFlow();
if (flowId === "arca-onboarding") return renderArcaOnboardingFlow();
if (flowId === "arca-test-connection") return renderArcaTestConnectionFlow();
if (flowId === "arca-onboarding") {
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 === "open-reservation-periods") return renderReservationPeriodFlow();
if (flowId === "override-schedule") return renderOverrideScheduleFlow();
@@ -39,13 +39,47 @@ type 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 [customDurationValue, setCustomDurationValue] = React.useState("");
const fraction = heatMapFraction || 60;
const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4];
const customDurationMinutes = Number(customDurationValue);
const isValidCustomDuration = Number.isInteger(customDurationMinutes) && customDurationMinutes > 0;
const isValidCustomDuration =
Number.isInteger(customDurationMinutes) && customDurationMinutes > 0;
const selectDurationOption = (duration: number) => {
setIsCustomDuration(false);
@@ -65,390 +99,518 @@ export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps)
};
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Configura tus Servicios"
description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
onNext={handleNext}
nextLabel="Comenzar"
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Configura tus Servicios"
description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
onNext={handleNext}
nextLabel="Comenzar"
>
<div
style={{
color: "rgba(255, 255, 255, 0.7)",
textAlign: "center",
padding: "10px",
}}
>
<div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil!
</div>
</QuestionCard>
Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil!
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Nombre y Descripción"
description="Elige un nombre atractivo y describe de qué trata el servicio."
onNext={handleNext}
disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Nombre y Descripción"
description="Elige un nombre atractivo y describe de qué trata el servicio."
onNext={handleNext}
disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
>
<div
style={{ display: "flex", flexDirection: "column", gap: "15px", width: "100%" }}
>
<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
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)}
type="number"
min="1"
step="1"
placeholder="Duración en minutos"
value={customDurationValue}
onChange={(e) => updateCustomDuration(e.target.value)}
onKeyDown={(e) => {
if (serviceName.trim().length >= 3 && serviceDescription.trim().length >= 5) {
if (isValidCustomDuration) {
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
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'
color: "rgba(255,255,255,0.6)",
fontSize: "13px",
marginTop: "8px",
textAlign: "center",
}}
>
Otro
Ingresá la duración total del servicio expresada en minutos.
</div>
</div>
{isCustomDuration && (
<div style={{ width: '100%', marginTop: '16px' }}>
<QuestionInput
type="number"
min="1"
step="1"
placeholder="Duración en minutos"
value={customDurationValue}
onChange={(e) => updateCustomDuration(e.target.value)}
onKeyDown={(e) => {
if (isValidCustomDuration) {
handleKeyDown(e, handleNext);
}
)}
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="3. Precio y Cupos"
description="¿Cuánto cuesta y a cuántas personas puede atender cada profesional a la vez en este servicio?"
onNext={handleCreateService}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
>
<div
style={{ display: "flex", flexDirection: "column", gap: "20px", width: "100%" }}
>
<div>
<div style={{ color: "white", marginBottom: "10px", fontSize: "14px" }}>
Precio Original
</div>
<div style={{ position: "relative" }}>
<span
style={{
position: "absolute",
left: "15px",
top: "50%",
transform: "translateY(-50%)",
color: "white",
fontSize: "18px",
}}
>
$
</span>
<input
type="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' }}>
Ingresá la duración total del servicio expresada en minutos.
</div>
</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>
)}
</QuestionCard>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="3. Precio y Cupos"
description="¿Cuánto cuesta y a cuántas personas puedes atender a la vez en este servicio?"
onNext={handleCreateService}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
<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={{ 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'
}}
/>
</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={{
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)",
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '14px', width: '100%' }}>
<button
type="button"
onClick={handleAssignCreatedServiceToMe}
disabled={isCreating}
{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%",
}}
>
<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={{
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
display: "flex",
flexDirection: "column",
gap: "10px",
width: "100%",
}}
>
{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={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
{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 && (
<>
>
{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={handleFinishWithoutAssignment}
disabled={isCreating}
onClick={handleAssignCreatedServiceToCollaborators}
disabled={
isCreating ||
selectedServiceCollaboratorIds.length === 0
}
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
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,
}}
>
Lo configuro después
{isCreating ? "Asignando..." : "Asignar servicio"}
</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',
)}
</div>
)}
{!serviceAssignmentWarning && (
<>
<button
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,
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>
</>
)}
{serviceAssignmentError && (
<div style={{
padding: '12px 14px',
borderRadius: '12px',
background: 'rgba(255, 99, 132, 0.12)',
border: '1px solid rgba(255, 99, 132, 0.35)',
color: '#fecdd3',
fontSize: '14px',
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>
</>
)}
{serviceAssignmentError && (
<div
style={{
padding: "12px 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,
textAlign: 'center'
}}>
{serviceAssignmentError}
</div>
)}
</div>
</QuestionCard>
)}
</>
);
textAlign: "center",
}}
>
{serviceAssignmentError}
</div>
)}
</div>
</QuestionCard>
)}
</>
);
}
@@ -1,13 +1,17 @@
"use client";
import React, { useEffect, useState } from "react";
import { LineChart } from "@mui/x-charts/LineChart";
import { MyOranizationsView } from "@core/Models/Company.model";
import { DashboardFinancialsResult, getDashboardFinancials } from "../../landing/dashboard/Dashboard.Service";
import {
DashboardFinancialsResult,
getDashboardFinancials,
} from "../../landing/dashboard/Dashboard.Service";
import { loadCollaboratorsByCompanyId } from "../../admin/(organization-profile)/org/profile/[id]/collaborators/Collaborators.Service";
import { CompanyEmployeesView } from "@models/Collaborators.model";
import UnpaidIncomeCard from "../UnpaidIncomeCard/UnpaidIncomeCard";
import styles from "./FinancialWidget.module.css";
import dayjs from "dayjs";
import OpenInNewOutlinedIcon from "@mui/icons-material/OpenInNewOutlined";
import { useNavigation } from "@core/app/hooks/goto";
export interface FinancialWidgetProps {
sessionUser: string;
@@ -15,7 +19,12 @@ export interface FinancialWidgetProps {
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 [selectedEmployeeId, setSelectedEmployeeId] = useState<string>("");
const [collaborators, setCollaborators] = useState<CompanyEmployeesView[]>([]);
@@ -27,10 +36,12 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
useEffect(() => {
if (selectedOrgId) {
loadCollaboratorsByCompanyId({ companyId: selectedOrgId }).then((res) => {
setCollaborators(res);
setSelectedEmployeeId(""); // reset employee filter when org changes
}).catch(console.error);
loadCollaboratorsByCompanyId({ companyId: selectedOrgId })
.then((res) => {
setCollaborators(res);
setSelectedEmployeeId(""); // reset employee filter when org changes
})
.catch(console.error);
}
}, [selectedOrgId, sessionUser]);
@@ -43,14 +54,17 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
sessionUser,
companyId: selectedOrgId,
timeframe: selectedTimeframe,
employeeId: selectedEmployeeId || undefined
}).then((res) => {
setFinancials(res);
}).catch((err) => {
const errMsg = err.format ? err.format() : err.message;
console.warn("Acceso denegado a métricas financieras: ", errMsg);
setError("No tienes permisos de administrador para esta organización.");
}).finally(() => setLoading(false));
employeeId: selectedEmployeeId || undefined,
})
.then((res) => {
setFinancials(res);
})
.catch((err) => {
const errMsg = err.format ? err.format() : err.message;
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]);
@@ -64,15 +78,22 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
const previous = financials.previousPeriodTotal;
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>;
}
const diff = current - previous;
const percent = (diff / previous) * 100;
if (percent > 0) 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>;
if (percent > 0)
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>;
};
@@ -81,15 +102,46 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
if (error) {
return (
<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}>
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ''}
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ""}
</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>
{isOpen && (
<div style={{ padding: '40px 20px', textAlign: 'center', color: '#6b7280' }}>
<p style={{ fontWeight: '600', marginBottom: '8px', color: '#374151' }}>Acceso Restringido</p>
<div style={{ padding: "40px 20px", textAlign: "center", color: "#6b7280" }}>
<p style={{ fontWeight: "600", marginBottom: "8px", color: "#374151" }}>
Acceso Restringido
</p>
<p>{error}</p>
</div>
)}
@@ -98,67 +150,108 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
}
const chartData = financials?.currentPeriodData || [];
const xAxisData = chartData.map(d => {
const xAxisData = chartData.map((d) => {
// format label nicer depending on timeframe
if (selectedTimeframe === "year") return dayjs(d.date).format("MMM YYYY");
return dayjs(d.date).format("DD/MM");
});
const seriesData = chartData.map(d => d.amount);
const hasChartData = chartData.some(d => d.amount > 0);
const seriesData = chartData.map((d) => d.amount);
const hasChartData = chartData.some((d) => d.amount > 0);
return (
<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}>
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ''}
Rendimiento Financiero {organizationName ? `- ${organizationName}` : ""}
</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>
{isOpen && (
<>
<div className={styles.filters}>
<select
className={styles.select}
value={selectedTimeframe}
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>
</select>
<select
className={styles.select}
value={selectedTimeframe}
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>
</select>
<select
className={styles.select}
value={selectedEmployeeId}
onChange={e => setSelectedEmployeeId(e.target.value)}
>
<option value="">Todos los Profesionales</option>
{collaborators.map(c => (
<option key={c.id} value={c.id}>{c.fullName}</option>
))}
</select>
<select
className={styles.select}
value={selectedEmployeeId}
onChange={(e) => setSelectedEmployeeId(e.target.value)}
>
<option value="">Todos los Profesionales</option>
{collaborators.map((c) => (
<option key={c.id} value={c.id}>
{c.fullName}
</option>
))}
</select>
</div>
<div className={styles.metricsRow}>
<div className={styles.metricBox}>
<span className={styles.metricLabel}>Ingresos del Periodo</span>
<span className={styles.metricValue}>
{loading ? "..." : formatCurrency(financials?.currentPeriodTotal || 0)}
</span>
<div className={styles.metricComparison}>
{!loading && renderComparison()}
</div>
</div>
<div className={styles.metricBox}>
<span className={styles.metricLabel}>Ingresos del Periodo</span>
<span className={styles.metricValue}>
{loading
? "..."
: formatCurrency(financials?.currentPeriodTotal || 0)}
</span>
<div className={styles.metricComparison}>
{!loading && renderComparison()}
</div>
</div>
{financials && (
<UnpaidIncomeCard value={financials.unpaidToday} />
)}
{financials && <UnpaidIncomeCard value={financials.unpaidToday} />}
</div>
{loading && (
<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...
</div>
</div>
@@ -168,57 +261,68 @@ export default function FinancialWidget({ sessionUser, selectedOrgId, organizati
<div className={styles.chartContainer}>
<LineChart
height={350}
xAxis={[{
scaleType: 'point',
data: xAxisData,
}]}
xAxis={[
{
scaleType: "point",
data: xAxisData,
},
]}
series={[
{
data: seriesData,
color: 'rgb(36, 169, 53)',
color: "rgb(36, 169, 53)",
area: true,
showMark: true,
curve: 'monotoneX',
valueFormatter: (val: number | null) => val ? formatCurrency(val) : "0",
curve: "monotoneX",
valueFormatter: (val: number | null) =>
val ? formatCurrency(val) : "0",
},
]}
grid={{ horizontal: true }}
margin={{ top: 20, bottom: 40, left: 70, right: 20 }}
sx={{
'.MuiLineElement-root': {
".MuiLineElement-root": {
strokeWidth: 3,
},
'.MuiAreaElement-root': {
fill: 'url(#gradient)',
".MuiAreaElement-root": {
fill: "url(#gradient)",
},
'.MuiChartsGrid-line': {
strokeDasharray: '5 5',
stroke: '#e5e7eb',
".MuiChartsGrid-line": {
strokeDasharray: "5 5",
stroke: "#e5e7eb",
},
'.MuiChartsAxis-line': {
stroke: 'transparent',
".MuiChartsAxis-line": {
stroke: "transparent",
},
'.MuiChartsAxis-tick': {
stroke: 'transparent',
".MuiChartsAxis-tick": {
stroke: "transparent",
},
'.MuiChartsAxis-tickLabel': {
fill: '#9ca3af',
fontFamily: 'inherit',
fontSize: '12px',
".MuiChartsAxis-tickLabel": {
fill: "#9ca3af",
fontFamily: "inherit",
fontSize: "12px",
fontWeight: 500,
},
'.MuiMarkElement-root': {
stroke: 'rgb(36, 169, 53)',
".MuiMarkElement-root": {
stroke: "rgb(36, 169, 53)",
strokeWidth: 2,
fill: '#ffffff',
scale: '1.2',
}
fill: "#ffffff",
scale: "1.2",
},
}}
>
<defs>
<linearGradient id="gradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="rgb(36, 169, 53)" stopOpacity={0.3}/>
<stop offset="95%" stopColor="rgb(36, 169, 53)" stopOpacity={0.0}/>
<stop
offset="5%"
stopColor="rgb(36, 169, 53)"
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor="rgb(36, 169, 53)"
stopOpacity={0.0}
/>
</linearGradient>
</defs>
</LineChart>
@@ -17,6 +17,7 @@ import classNames from "classnames";
import { useNavigation } from "@core/app/hooks/goto";
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
@@ -69,6 +70,14 @@ export default function OrganizationHeader(props: OrganizationHeaderParams): Rea
icon: <ShareOutlinedIcon />,
});
menu.add({
text: "Ver perfil",
onClick: () => {
goTo(`/landing/org/${props.data.id}`);
},
icon: <OpenInNewIcon />,
});
menu.add({
text: "Notificaciones",
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 { getServiceImage } from "@core/helpers/getServiceImage";
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
import EditIcon from "@mui/icons-material/Edit";
export type FindResultsViewMode = "grid" | "card";
@@ -14,6 +15,8 @@ export interface ProductItemProps {
width?: number | string;
viewMode?: FindResultsViewMode;
dragging?: boolean;
isAdmin?: boolean;
onImageEdit?: () => void;
}
export default function ProductItem(props: ProductItemProps) {
@@ -21,6 +24,8 @@ export default function ProductItem(props: ProductItemProps) {
const { product } = props;
const { viewMode = "card" } = props;
const { dragging = false } = props;
const { isAdmin = false } = props;
const { onImageEdit } = props;
const { goTo } = useNavigation();
return (
@@ -38,7 +43,7 @@ export default function ProductItem(props: ProductItemProps) {
textAlign: "center",
padding: "10px",
border: "solid 1px rgba(0, 0, 0, 0.1)",
cursor: "pointer",
cursor: isAdmin ? "default" : "pointer",
position: "relative",
}}
onClick={() => {
@@ -58,6 +63,11 @@ export default function ProductItem(props: ProductItemProps) {
display: "block",
}}
/>
{isAdmin && (
<span className={style.adminEditButton} onClick={(e) => { e.stopPropagation(); onImageEdit?.(); }}>
<EditIcon fontSize="small" />
</span>
)}
<ServiceRatingSummary
serviceId={product.id}
variant="card"
@@ -8,6 +8,32 @@
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 {
margin: 10px 0;
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">
{orgData.id && (
<>
<OrganizationHeader organization={orgData} />
<div style={{ position: "relative" }} id="header-wrapper">
<OrganizationHeader organization={orgData} />
</div>
<OrganizationDataConnector orgData={orgData} />
<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 { useAlert } from "@core/Store/Alert.Store";
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 { ThemeProvider } from "@emotion/react";
@@ -55,12 +58,14 @@ import DownIcon from "@mui/icons-material/ArrowDownwardRounded";
import PinIcon from "@mui/icons-material/PushPin";
import EditIcon from "@mui/icons-material/AutoFixHigh";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import { useParams } from "next/navigation";
import { useParams, useRouter } from "next/navigation";
import dayjs from "dayjs";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import ReviewsCarousel from "@core/app/components/ReviewsCarousel/ReviewsCarousel";
import OrganizationProfessionals from "@core/app/components/OrganizationProfessionals/OrganizationProfessionals";
import { RatingTargetType } from "@core/Models/Ratings.model";
import HeaderEditPopup from "./HeaderEditPopup";
import { checkOrgAdmin } from "./post.service";
enum VIEW {
POSTS = "posts",
@@ -76,6 +81,7 @@ type UrlData = {
export default function OrganizationPublicProfile() {
const data = useParams<UrlData>();
const oid = data.oid;
const router = useRouter();
const OrganizationData = useOrgDataStore();
const [position, setPosition] = useState<[number, number]>([0, 0]);
const [orgData, setOrgData] = useState<PublicOrganizationView>();
@@ -96,8 +102,85 @@ export default function OrganizationPublicProfile() {
const [posts, setPosts] = useState<IPost[]>([]);
const [authorizedUsers, setAuthorizedUsers] = useState<string[]>([]);
const [currentPage, setCurrentPage] = useState<number>(1);
const [isOrgAdmin, setIsOrgAdmin] = useState<boolean>(false);
const [showEditPopup, setShowEditPopup] = useState<boolean>(false);
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 alert = useAlert();
const confirm = useConfirmStore();
@@ -338,7 +421,8 @@ export default function OrganizationPublicProfile() {
return response.data;
}
const newPosts = response.data.filter(
(newPost) => !prevPosts.some((prevPost) => prevPost._id === newPost._id),
(newPost) =>
!prevPosts.some((prevPost) => prevPost._id === newPost._id),
);
return [...prevPosts, ...newPosts];
@@ -508,7 +592,11 @@ export default function OrganizationPublicProfile() {
gap: "10px",
}}
>
<WhatsappShareButton title={shareTitle} separator=":: " url={window.location.href}>
<WhatsappShareButton
title={shareTitle}
separator=":: "
url={window.location.href}
>
<WhatsAppShareIcon size={32} round />
</WhatsappShareButton>
<FacebookShareButton title={shareTitle} url={window.location.href}>
@@ -531,6 +619,21 @@ export default function OrganizationPublicProfile() {
return (
<>
<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 && (
<div className={style.organizationContent}>
{showEditor && (
@@ -656,7 +759,9 @@ export default function OrganizationPublicProfile() {
)}
</div>
{view === VIEW.SERVICES && (
<div style={{ display: "flex", justifyContent: "flex-end" }}>
<div
style={{ display: "flex", justifyContent: "flex-end" }}
>
<ButtonGroup
variant="outlined"
aria-label="Basic button group"
@@ -711,7 +816,8 @@ export default function OrganizationPublicProfile() {
<div
style={{
textAlign: "center",
backgroundImage: "url(/no-conversation.webp)",
backgroundImage:
"url(/no-conversation.webp)",
backgroundRepeat: "no-repeat",
backgroundPosition: "center center",
backgroundSize: "50% auto",
@@ -726,7 +832,8 @@ export default function OrganizationPublicProfile() {
<div
key={post._id}
style={{
borderBottom: "1px solid var(--gray-light)",
borderBottom:
"1px solid var(--gray-light)",
paddingTop: "5px",
paddingBottom: "10px",
paddingLeft: "30px",
@@ -740,7 +847,11 @@ export default function OrganizationPublicProfile() {
justifyContent: "space-between",
}}
>
<div style={{ color: "var(--gray-darkest)" }}>
<div
style={{
color: "var(--gray-darkest)",
}}
>
{dayjs(post.createdAt).format(
"DD MMMM YYYY HH:mm",
)}
@@ -780,22 +891,30 @@ export default function OrganizationPublicProfile() {
color: "var(--gray-darkest)",
}}
>
<ThemeProvider theme={turnosXpressTheme}>
<ThemeProvider
theme={turnosXpressTheme}
>
<MaterialButton
color="inherit"
startIcon={<ClipIcon />}
onClick={() => {
fijarPost(`${post._id}`);
fijarPost(
`${post._id}`,
);
}}
>
{post.fixed ? "Liberar" : "Fijar"}
{post.fixed
? "Liberar"
: "Fijar"}
</MaterialButton>
{post.fixed && (
<>
<MaterialButton
color="inherit"
startIcon={<UpIcon />}
startIcon={
<UpIcon />
}
onClick={() => {
moverPost(
`${post._id}`,
@@ -808,7 +927,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton
color="inherit"
startIcon={<DownIcon />}
startIcon={
<DownIcon />
}
onClick={() => {
moverPost(
`${post._id}`,
@@ -824,7 +945,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton
color="inherit"
onClick={() => {
editarPost(`${post._id}`);
editarPost(
`${post._id}`,
);
}}
>
<EditIcon />
@@ -833,7 +956,9 @@ export default function OrganizationPublicProfile() {
<MaterialButton
color="inherit"
onClick={() => {
eliminarPost(`${post._id}`);
eliminarPost(
`${post._id}`,
);
}}
>
<DeleteIcon />
@@ -858,7 +983,8 @@ export default function OrganizationPublicProfile() {
style={{
padding: "0px 0px 40px 0px",
display: "flex",
flexDirection: viewMode === "card" ? "row" : "column",
flexDirection:
viewMode === "card" ? "row" : "column",
justifyContent: "start",
gap: "20px",
flexWrap: "wrap",
@@ -65,3 +65,7 @@ export const toggleFixedPost = async (data: FixCompanyPostParams): Promise<void>
export const moveFixedPost = async (data: MoveCompanyFixedPostParams): Promise<void> => {
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 ApiServerService from "@services/Api.Server.Service";
import { PublicOrganizationServiceView } from "@core/Models/Service.model";
import ProductItem from "@core/app/components/ProductItem/ProductItem";
import Appointment from "./components/Appointment/Appointment";
import OrganizationHeader from "@components/Home/OrganizationHeader/OrganizationHeader";
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 ReviewsCarousel from "@components/ReviewsCarousel/ReviewsCarousel";
import { RatingTargetType } from "@core/Models/Ratings.model";
import ServiceDetailCard from "./ServiceDetailCard";
import OrganizationHeaderEdit from "@components/OrganizationHeaderEdit/OrganizationHeaderEdit";
const GetServiceData = async (serviceId: string): Promise<PublicOrganizationServiceView> => {
try {
@@ -56,11 +57,20 @@ export default async function OrganizationPublicProfile({ params }: Props) {
<ScrollToTop />
<HeaderConfProvider />
<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.serviceSide}>
<div className={style.stickyWrapper}>
<ProductItem product={organizationService.service} width="100%" />
<ServiceDetailCard service={organizationService.service} organization={organizationService.organization} />
</div>
</div>
<div className={style.bookingSide}>