feat: enhance checkout process with purchase editing and status handling

- Implemented purchase editing functionality in CheckoutPageComponent, allowing users to modify items in their purchase.
- Added a new guard (checkoutPendingPurchaseGuard) to prevent navigation away from the checkout page while a purchase is in progress.
- Updated the login page to handle return URLs after authentication.
- Enhanced product detail page to support direct purchases with a new buyNow method.
- Introduced new UI elements and logic to handle purchase status, including expired and rejected states in PurchaseStatusPageComponent.
- Improved cart component to allow editing of item quantities with a toggle button.
- Added quantity selector enhancements to disable controls when necessary.
- Updated tests to cover new functionalities and ensure proper behavior of components.
This commit is contained in:
2026-07-27 12:49:00 -03:00
parent 9dcedc9382
commit 902f65d8d0
31 changed files with 1253 additions and 219 deletions

View File

@@ -235,7 +235,7 @@ describe('app routes', () => {
it('redirects unauthenticated users from /checkout to /login', async () => { it('redirects unauthenticated users from /checkout to /login', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false)); const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
expect(router.url).toBe('/login'); expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
}); });
it('allows authenticated users to access /checkout', async () => { it('allows authenticated users to access /checkout', async () => {

View File

@@ -14,7 +14,10 @@
/> />
@if (isCartOpen()) { @if (isCartOpen()) {
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div> <div
class="store-layout__cart-overlay"
(click)="isCartOpen.set(false)"
></div>
<div class="store-layout__cart-dropdown card border-0 shadow-lg"> <div class="store-layout__cart-dropdown card border-0 shadow-lg">
<app-cart <app-cart
[showClose]="true" [showClose]="true"
@@ -25,12 +28,20 @@
[backgroundColor]="'#ffffff'" [backgroundColor]="'#ffffff'"
(closed)="isCartOpen.set(false)" (closed)="isCartOpen.set(false)"
> >
<app-button variant="secondary" class="flex-grow-1" (click)="isCartOpen.set(false)" <app-button
variant="secondary"
class="flex-grow-1"
(click)="isCartOpen.set(false)"
>Seguir comprando</app-button >Seguir comprando</app-button
> >
<app-button variant="primary" class="flex-grow-1" (click)="onCheckoutClick()" <app-button
>Comprar</app-button variant="primary"
class="flex-grow-1"
[disabled]="isCreatingPurchase()"
(click)="onCheckoutClick()"
> >
Comprar
</app-button>
</app-cart> </app-cart>
</div> </div>
} }

View File

@@ -15,6 +15,7 @@ import { AuthService } from '../../services/auth/auth.service';
import { AuthUser } from '../../services/auth/auth.interfaces'; import { AuthUser } from '../../services/auth/auth.interfaces';
import { StoreLayoutComponent } from './store-layout.component'; import { StoreLayoutComponent } from './store-layout.component';
import { StoreHeaderComponent } from './store-header/store-header.component'; import { StoreHeaderComponent } from './store-header/store-header.component';
import { CheckoutService } from '../../services/checkout.service';
const tenant: Tenant = { const tenant: Tenant = {
id: 1, id: 1,
@@ -127,12 +128,17 @@ const tenant: Tenant = {
describe('StoreLayoutComponent', () => { describe('StoreLayoutComponent', () => {
let tenantState = signal<Tenant | null>(tenant); let tenantState = signal<Tenant | null>(tenant);
let cartState = signal<Cart | null>(null); let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
beforeEach(async () => { beforeEach(async () => {
tenantState = signal<Tenant | null>(tenant); tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null); cartState = signal<Cart | null>(null);
const authUserState = signal<AuthUser | null>(null); authUserState = signal<AuthUser | null>(null);
const isAuthenticatedState = signal(false); const isAuthenticatedState = signal(false);
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
};
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [StoreLayoutComponent], imports: [StoreLayoutComponent],
@@ -156,6 +162,7 @@ describe('StoreLayoutComponent', () => {
.fn() .fn()
.mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })), .mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
removeItem: vi.fn().mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })), removeItem: vi.fn().mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
clearCart: vi.fn(() => cartState.set(null)),
}, },
}, },
{ {
@@ -176,6 +183,10 @@ describe('StoreLayoutComponent', () => {
logout: vi.fn().mockReturnValue(of(void 0)), logout: vi.fn().mockReturnValue(of(void 0)),
}, },
}, },
{
provide: CheckoutService,
useValue: checkoutServiceStub,
},
], ],
}).compileComponents(); }).compileComponents();
}); });
@@ -394,8 +405,9 @@ describe('StoreLayoutComponent', () => {
expect(router.navigate).not.toHaveBeenCalled(); expect(router.navigate).not.toHaveBeenCalled();
}); });
it('logs out from the authenticated user dropdown', () => { it('logs out from the authenticated user dropdown, clears the cart and returns home', () => {
const authService = TestBed.inject(AuthService); const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate'); vi.spyOn(router, 'navigate');
@@ -424,11 +436,13 @@ describe('StoreLayoutComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(authService.logout).toHaveBeenCalled(); expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']); expect(cartService.clearCart).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']);
}); });
it('provides account actions from the footer', () => { it('provides account actions from the footer', () => {
const authService = TestBed.inject(AuthService); const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate'); vi.spyOn(router, 'navigate');
@@ -455,7 +469,28 @@ describe('StoreLayoutComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(authService.logout).toHaveBeenCalled(); expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']); expect(cartService.clearCart).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
it('leaves checkout before logging out so the pending purchase can be cancelled', async () => {
const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
await (fixture.componentInstance as any).onLogoutClick();
expect(navigateSpy).toHaveBeenCalledWith(['/']);
expect(authService.logout).toHaveBeenCalled();
expect(navigateSpy.mock.invocationCallOrder[0]).toBeLessThan(
(authService.logout as any).mock.invocationCallOrder[0],
);
expect(cartService.clearCart).toHaveBeenCalled();
}); });
it('renders only the help submenus assigned to the tenant in the footer', () => { it('renders only the help submenus assigned to the tenant in the footer', () => {
@@ -481,7 +516,7 @@ describe('StoreLayoutComponent', () => {
expect(compiled.textContent).not.toContain('Medios de pago'); expect(compiled.textContent).not.toContain('Medios de pago');
}); });
it('redirects to /checkout when cart buy button is clicked', () => { it('creates a purchase and redirects to checkout when cart buy is clicked', async () => {
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate'); vi.spyOn(router, 'navigate');
cartState.set({ cartState.set({
@@ -503,23 +538,73 @@ describe('StoreLayoutComponent', () => {
}, },
], ],
}); });
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
const buyButton = Array.from(compiled.querySelectorAll('app-button button')).find(
(button) => button.textContent?.trim() === 'Comprar',
) as HTMLButtonElement | undefined;
expect(buyButton).toBeDefined();
buyButton!.click();
await Promise.resolve();
fixture.detectChanges();
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1,
});
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 55 },
});
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
});
it('allows modifying quantities directly in the regular cart without a toggle', () => {
cartState.set({
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [
{
id: 1,
cantidad: 1,
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: null,
product: {
nombre: 'Producto',
imagen: null,
},
},
],
});
const fixture = TestBed.createComponent(StoreLayoutComponent); const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges(); fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true); (fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges(); fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement; const element = fixture.nativeElement as HTMLElement;
const buyButton = Array.from(compiled.querySelectorAll('app-button button')).find( const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
(button) => button.textContent?.trim() === 'Comprar', const buyButton = Array.from(
) as HTMLButtonElement | undefined; element.querySelectorAll<HTMLButtonElement>('app-button button'),
).find((button) => button.textContent?.trim() === 'Comprar');
expect(element.querySelector('.cart-edit-btn')).toBeNull();
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
expect(buyButton).toBeDefined(); expect(buyButton).toBeDefined();
buyButton!.click();
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['/checkout']);
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
}); });
}); });

View File

@@ -9,6 +9,8 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
import { CartItem } from '../../services/cart/cart.interface'; import { CartItem } from '../../services/cart/cart.interface';
import { AuthService } from '../../services/auth/auth.service'; import { AuthService } from '../../services/auth/auth.service';
import { findMenu } from '../../services/menu.utils'; import { findMenu } from '../../services/menu.utils';
import { CheckoutService } from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service';
@Component({ @Component({
selector: 'app-store-layout', selector: 'app-store-layout',
@@ -26,9 +28,12 @@ export class StoreLayoutComponent implements OnInit {
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly checkoutService = inject(CheckoutService);
private readonly toastService = inject(ToastService);
private readonly router = inject(Router); private readonly router = inject(Router);
protected readonly isCartOpen = signal(false); protected readonly isCartOpen = signal(false);
protected readonly isCreatingPurchase = signal(false);
protected readonly cartSubtotal = computed(() => { protected readonly cartSubtotal = computed(() => {
const cart = this.cartService.cart(); const cart = this.cartService.cart();
@@ -128,16 +133,69 @@ export class StoreLayoutComponent implements OnInit {
} }
} }
protected onLogoutClick(): void { protected async onLogoutClick(): Promise<void> {
const isLeavingCheckout = this.router.url.startsWith('/checkout');
// Checkout must be left while the authenticated session is still valid so
// its CanDeactivate guard can cancel the pending purchase.
if (isLeavingCheckout) {
const navigationSucceeded = await this.router.navigate(['/']);
if (!navigationSucceeded) {
return;
}
}
this.authService.logout().subscribe({ this.authService.logout().subscribe({
next: () => void this.router.navigate(['/login']), next: () => {
this.cartService.clearCart();
this.isCartOpen.set(false);
if (!isLeavingCheckout) {
void this.router.navigate(['/']);
}
},
error: (err) => console.error('Error logging out', err), error: (err) => console.error('Error logging out', err),
}); });
} }
protected onCheckoutClick(): void { protected async onCheckoutClick(): Promise<void> {
this.isCartOpen.set(false); if (this.isCreatingPurchase()) {
void this.router.navigate(['/checkout']); return;
}
const cart = this.cartService.cart();
const tenant = this.tenantService.tenant();
const user = this.authService.user();
if (!user) {
this.isCartOpen.set(false);
void this.router.navigate(['/login'], { queryParams: { returnUrl: '/' } });
return;
}
if (!cart?.id || !tenant) {
this.toastService.danger('No hay un carrito activo para iniciar la compra.');
return;
}
this.isCreatingPurchase.set(true);
try {
const purchase = await this.checkoutService.startCheckout(tenant.codigo, {
cart_id: cart.id,
});
this.cartService.clearCart();
this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
} catch (error) {
console.error('Failed to create cart purchase:', error);
this.toastService.danger('No se pudo iniciar la compra.');
} finally {
this.isCreatingPurchase.set(false);
}
} }
protected readonly footerSections = computed<StoreFooterSection[]>(() => { protected readonly footerSections = computed<StoreFooterSection[]>(() => {

View File

@@ -23,10 +23,14 @@ describe('auth guards', () => {
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }] providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
}); });
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never)); const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
);
expect(result instanceof UrlTree).toBe(true); expect(result instanceof UrlTree).toBe(true);
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login'); expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
);
}); });
it('allows authenticated users through authGuard', () => { it('allows authenticated users through authGuard', () => {
@@ -34,7 +38,9 @@ describe('auth guards', () => {
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }] providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
}); });
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never)); const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout' } as never),
);
expect(result).toBe(true); expect(result).toBe(true);
}); });

View File

@@ -3,11 +3,15 @@ import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () => { export const authGuard: CanActivateFn = (_route, state) => {
const authService = inject(AuthService); const authService = inject(AuthService);
const router = inject(Router); const router = inject(Router);
return authService.isAuthenticated() ? true : router.createUrlTree(['/login']); return authService.isAuthenticated()
? true
: router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
}; };
export const guestOnlyGuard: CanActivateFn = () => { export const guestOnlyGuard: CanActivateFn = () => {

View File

@@ -19,8 +19,12 @@ describe('AuthService', () => {
function createCookieServiceStub() { function createCookieServiceStub() {
return { return {
get: (name: string) => cookieStore[name] || null, get: (name: string) => cookieStore[name] || null,
set: (name: string, value: string) => { cookieStore[name] = value; }, set: (name: string, value: string) => {
delete: (name: string) => { delete cookieStore[name]; } cookieStore[name] = value;
},
delete: (name: string) => {
delete cookieStore[name];
}
}; };
} }
@@ -31,6 +35,10 @@ describe('AuthService', () => {
provideHttpClientTesting(), provideHttpClientTesting(),
AuthService, AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() }, { provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState TransferState
] ]
}); });
@@ -44,6 +52,12 @@ describe('AuthService', () => {
const request = httpController.expectOne(`${environment.url}login`); const request = httpController.expectOne(`${environment.url}login`);
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
email: 'ada@example.com',
password: 'secret123',
tenant_codigo: 'tenant-test'
});
expect(request.request.withCredentials).toBe(true);
request.flush({ request.flush({
message: 'Sesion iniciada correctamente.', message: 'Sesion iniciada correctamente.',
token: 'plain-text-token', token: 'plain-text-token',
@@ -96,6 +110,47 @@ describe('AuthService', () => {
httpController.verify(); httpController.verify();
}); });
it('sends tenant and credentials when completing Google login', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState
]
});
const service = TestBed.inject(AuthService);
const httpController = TestBed.inject(HttpTestingController);
service.completeGoogleLogin('oauth-code').subscribe();
const request = httpController.expectOne(`${environment.url}auth/google/exchange`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
oauth_code: 'oauth-code',
tenant_codigo: 'tenant-test'
});
expect(request.request.withCredentials).toBe(true);
request.flush({
message: 'Sesion iniciada correctamente.',
token: 'google-token',
token_type: 'Bearer',
user: {
id: 1,
nombre_apellido: 'Ada Lovelace',
email: 'ada@example.com'
}
});
httpController.verify();
});
it('clears an expired session when /me returns 401', async () => { it('clears an expired session when /me returns 401', async () => {
cookieStore['shopit.auth.token'] = 'expired-token'; cookieStore['shopit.auth.token'] = 'expired-token';
@@ -233,9 +288,7 @@ describe('AuthService', () => {
expect(response.body?.status).toBe('validated'); expect(response.body?.status).toBe('validated');
}); });
const request = httpController.expectOne( const request = httpController.expectOne(`${environment.url}password/reset-attempts/validate`);
`${environment.url}password/reset-attempts/validate`
);
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({ expect(request.request.body).toEqual({
email: 'ada@example.com', email: 'ada@example.com',
@@ -298,6 +351,10 @@ describe('AuthService', () => {
provideHttpClientTesting(), provideHttpClientTesting(),
AuthService, AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() }, { provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState TransferState
] ]
}); });

View File

@@ -42,10 +42,21 @@ export class AuthService {
readonly isAuthenticated = computed(() => this.tokenState() !== null); readonly isAuthenticated = computed(() => this.tokenState() !== null);
login(payload: LoginPayload): Observable<AuthUser> { login(payload: LoginPayload): Observable<AuthUser> {
return this.http.post<LoginResponse>(`${environment.url}login`, payload).pipe( const tenant = this.tenantService.getTenant();
tap((response) => this.applyAuthenticatedState(response.token, response.user)), if (!tenant) {
map((response) => response.user) throw new Error('No se pudo resolver el tenant activo.');
); }
return this.http
.post<LoginResponse>(
`${environment.url}login`,
{ ...payload, tenant_codigo: tenant.codigo },
{ withCredentials: true }
)
.pipe(
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
map((response) => response.user)
);
} }
register(payload: RegisterPayload): Observable<RegisterResponse> { register(payload: RegisterPayload): Observable<RegisterResponse> {
@@ -57,9 +68,7 @@ export class AuthService {
}); });
} }
requestPasswordReset( requestPasswordReset(email: string): Observable<HttpResponse<ResetPasswordAttemptResponse>> {
email: string
): Observable<HttpResponse<ResetPasswordAttemptResponse>> {
const tenantCode = this.tenantService.getTenant()?.codigo; const tenantCode = this.tenantService.getTenant()?.codigo;
return this.http.post<ResetPasswordAttemptResponse>( return this.http.post<ResetPasswordAttemptResponse>(
@@ -83,14 +92,10 @@ export class AuthService {
); );
} }
resetPassword( resetPassword(payload: ResetPasswordPayload): Observable<HttpResponse<ResetPasswordResponse>> {
payload: ResetPasswordPayload return this.http.post<ResetPasswordResponse>(`${environment.url}password/reset`, payload, {
): Observable<HttpResponse<ResetPasswordResponse>> { observe: 'response'
return this.http.post<ResetPasswordResponse>( });
`${environment.url}password/reset`,
payload,
{ observe: 'response' }
);
} }
loginWithGoogle(): void { loginWithGoogle(): void {
@@ -108,16 +113,25 @@ export class AuthService {
} }
completeGoogleLogin(oauthCode: string): Observable<AuthUser> { completeGoogleLogin(oauthCode: string): Observable<AuthUser> {
return this.http.post<LoginResponse>(`${environment.url}auth/google/exchange`, { oauth_code: oauthCode }).pipe( const tenant = this.tenantService.getTenant();
tap((response) => this.applyAuthenticatedState(response.token, response.user)), if (!tenant) {
map((response) => response.user) throw new Error('No se pudo resolver el tenant activo.');
); }
return this.http
.post<LoginResponse>(
`${environment.url}auth/google/exchange`,
{ oauth_code: oauthCode, tenant_codigo: tenant.codigo },
{ withCredentials: true }
)
.pipe(
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
map((response) => response.user)
);
} }
updateProfile(payload: UpdateProfilePayload): Observable<AuthUser> { updateProfile(payload: UpdateProfilePayload): Observable<AuthUser> {
return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe( return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe(tap((user) => this.userState.set(user)));
tap((user) => this.userState.set(user))
);
} }
logout(): Observable<void> { logout(): Observable<void> {
@@ -126,9 +140,7 @@ export class AuthService {
return of(void 0); return of(void 0);
} }
return this.http.post<void>(`${environment.url}logout`, {}).pipe( return this.http.post<void>(`${environment.url}logout`, {}).pipe(tap(() => this.clearSession()));
tap(() => this.clearSession())
);
} }
async bootstrap(): Promise<void> { async bootstrap(): Promise<void> {
@@ -167,9 +179,7 @@ export class AuthService {
} }
loadCurrentUser(): Observable<AuthUser> { loadCurrentUser(): Observable<AuthUser> {
return this.http.get<AuthUser>(`${environment.url}me`).pipe( return this.http.get<AuthUser>(`${environment.url}me`).pipe(tap((user) => this.userState.set(user)));
tap((user) => this.userState.set(user))
);
} }
hydrateSession(): void { hydrateSession(): void {

View File

@@ -4,14 +4,25 @@ import { firstValueFrom } from 'rxjs';
import { environment } from '../../../environments/environment'; import { environment } from '../../../environments/environment';
export interface CreatePurchasePayload { export interface UpdatePurchaseCustomerPayload {
cart_id: number;
dni: string; dni: string;
telefono: string; telefono: string;
nombre_apellido: string; nombre_apellido: string;
email: string; email: string;
} }
export type StartCheckoutPayload =
| {
cart_id: number;
}
| {
direct_item: {
catalog_item_id: number;
variant_id: number | null;
cantidad: number;
};
};
export interface PurchaseStatusResponse { export interface PurchaseStatusResponse {
status: string | null; status: string | null;
} }
@@ -62,17 +73,23 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
} }
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class CheckoutService { export class CheckoutService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
async createPurchase(tenantCode: string, payload: CreatePurchasePayload): Promise<{ id: number }> { async startCheckout(
tenantCode: string,
payload: StartCheckoutPayload,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom( const response = await firstValueFrom(
this.http.post<{ data?: { id: number }; id?: number }>(`${environment.url}tenants/${tenantCode}/compras`, payload) this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
payload,
),
); );
const purchase = this.extractResponseData<{ id: number }>(response); const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase?.id) { if (!purchase?.id) {
throw new Error('Error al crear la compra.'); throw new Error('Error al crear la compra.');
@@ -81,13 +98,21 @@ export class CheckoutService {
return purchase; return purchase;
} }
async generatePaymentIntent(tenantCode: string, purchaseId: number, method: 'qr' | 'transfer' | 'telepagos', payerDni?: string): Promise<any> { async generatePaymentIntent(
tenantCode: string,
purchaseId: number,
method: 'qr' | 'transfer' | 'telepagos',
payerDni?: string,
): Promise<any> {
const payload: any = { method }; const payload: any = { method };
if (payerDni) { if (payerDni) {
payload.transfer_payer_dni = payerDni; payload.transfer_payer_dni = payerDni;
} }
const response = await firstValueFrom( const response = await firstValueFrom(
this.http.post<any>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/payment-intent`, payload) this.http.post<any>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/payment-intent`,
payload,
),
); );
if (!response) { if (!response) {
throw new Error('Error al generar la intención de pago.'); throw new Error('Error al generar la intención de pago.');
@@ -95,9 +120,72 @@ export class CheckoutService {
return response; return response;
} }
async updateCustomerData(
tenantCode: string,
purchaseId: number,
payload: UpdatePurchaseCustomerPayload,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/customer-data`,
payload,
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al actualizar los datos de la compra.');
}
return purchase;
}
async updateItemQuantity(
tenantCode: string,
purchaseId: number,
itemId: number,
quantity: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
{ quantity },
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al actualizar la cantidad del producto.');
}
return purchase;
}
async prepareItemEditing(
tenantCode: string,
purchaseId: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/edit-items`,
{},
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al preparar la compra para editarla.');
}
return purchase;
}
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> { async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
const response = await firstValueFrom( const response = await firstValueFrom(
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`, {}) this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
{},
),
); );
const purchase = this.extractResponseData<PurchaseStatusResponse>(response); const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
@@ -107,27 +195,49 @@ export class CheckoutService {
} }
return { return {
status: purchase.status ?? null status: purchase.status ?? null,
}; };
} }
async getPurchases(tenantCode: string, status?: string): Promise<{ data: PurchaseSummaryResponse[] }> { async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/cancel`,
{},
),
);
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
if (!purchase) {
throw new Error('Error al cancelar la compra.');
}
return { status: purchase.status ?? null };
}
async getPurchases(
tenantCode: string,
status?: string,
): Promise<{ data: PurchaseSummaryResponse[] }> {
let url = `${environment.url}tenants/${tenantCode}/compras`; let url = `${environment.url}tenants/${tenantCode}/compras`;
if (status) { if (status) {
url += `?status=${status}`; url += `?status=${status}`;
} }
const response = await firstValueFrom( const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
this.http.get<{ data: PurchaseSummaryResponse[] }>(url)
);
if (!response) { if (!response) {
throw new Error('Error al obtener las compras.'); throw new Error('Error al obtener las compras.');
} }
return response; return response;
} }
async getPurchase(tenantCode: string, purchaseId: string | number): Promise<PurchaseDetailResponse> { async getPurchase(
tenantCode: string,
purchaseId: string | number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom( const response = await firstValueFrom(
this.http.get<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}`) this.http.get<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}`,
),
); );
const purchase = this.extractResponseData<PurchaseDetailResponse>(response); const purchase = this.extractResponseData<PurchaseDetailResponse>(response);

View File

@@ -1,7 +1,11 @@
<div class="checkout-page">
<div class="checkout-page"> <div
<div class="checkout-page__stepper-col "> class="checkout-page__stepper-col"
<app-stepper #stepper> [class.checkout-page__stepper-col--editing]="isEditingItems()"
[attr.aria-hidden]="isEditingItems()"
[attr.inert]="isEditingItems() ? '' : null"
>
<app-stepper #stepper>
<app-step label="Datos" [isValid]="isStep1Valid()"> <app-step label="Datos" [isValid]="isStep1Valid()">
<app-checkout-data-step <app-checkout-data-step
[form]="form" [form]="form"
@@ -30,16 +34,32 @@
(retryQrPolling)="retryQrPolling()" (retryQrPolling)="retryQrPolling()"
/> />
</app-step> </app-step>
</app-stepper> </app-stepper>
</div>
<div class="checkout-page__cart-col">
<app-cart
[items]="mappedCartItems()"
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
backgroundColor="transparent"
/>
</div>
</div> </div>
@if (isEditingItems()) {
<div class="checkout-page__editing-notice" role="status">
<p>Terminá de modificar las cantidades para continuar con el pago.</p>
</div>
}
<div class="checkout-page__cart-col">
<app-cart
title="COMPRA"
[items]="mappedCartItems()"
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
[allowEditing]="
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
"
[allowRemove]="false"
[persistQuantityChanges]="false"
[editing]="isEditingItems()"
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
backgroundColor="transparent"
(editingChange)="onEditingItemsChange($event)"
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
/>
</div>
</div>

View File

@@ -12,6 +12,27 @@
min-width: 0; min-width: 0;
border-radius: 4px; border-radius: 4px;
min-height: 420px; min-height: 420px;
&--editing {
display: none;
}
}
&__editing-notice {
display: grid;
min-height: 420px;
place-items: center;
padding: 2rem;
border-radius: 4px;
background: #f5f5f5;
color: #666666;
text-align: center;
p {
max-width: 360px;
margin: 0;
font-size: 14px;
}
} }
&__cart-col { &__cart-col {

View File

@@ -1,18 +1,24 @@
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { getTestBed, TestBed } from '@angular/core/testing'; import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { Router } from '@angular/router'; import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service'; import { CheckoutService } from '../../../../core/services/checkout.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { CheckoutPageComponent } from './checkout-page.component'; import { CheckoutPageComponent } from './checkout-page.component';
describe('CheckoutPageComponent payment validation', () => { describe('CheckoutPageComponent payment validation', () => {
let checkoutServiceStub: { let checkoutServiceStub: {
startCheckout: ReturnType<typeof vi.fn>;
updateCustomerData: ReturnType<typeof vi.fn>;
updateItemQuantity: ReturnType<typeof vi.fn>;
prepareItemEditing: ReturnType<typeof vi.fn>;
cancelPurchase: ReturnType<typeof vi.fn>;
generatePaymentIntent: ReturnType<typeof vi.fn>; generatePaymentIntent: ReturnType<typeof vi.fn>;
getPurchase: ReturnType<typeof vi.fn>; getPurchase: ReturnType<typeof vi.fn>;
}; };
@@ -23,6 +29,8 @@ describe('CheckoutPageComponent payment validation', () => {
clearCart: ReturnType<typeof vi.fn>; clearCart: ReturnType<typeof vi.fn>;
}; };
let routerStub: { navigate: ReturnType<typeof vi.fn> }; let routerStub: { navigate: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>;
beforeAll(() => { beforeAll(() => {
try { try {
@@ -36,6 +44,16 @@ describe('CheckoutPageComponent payment validation', () => {
vi.useFakeTimers(); vi.useFakeTimers();
checkoutServiceStub = { checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({
id: 25,
items: [],
subtotal: '0.00',
total: '0.00',
}),
updateCustomerData: vi.fn(),
updateItemQuantity: vi.fn(),
prepareItemEditing: vi.fn(),
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
generatePaymentIntent: vi.fn().mockResolvedValue({ generatePaymentIntent: vi.fn().mockResolvedValue({
qr_data: { qr_code: 'qr-value' }, qr_data: { qr_code: 'qr-value' },
}), }),
@@ -63,14 +81,27 @@ describe('CheckoutPageComponent payment validation', () => {
}); });
}); });
routerStub = { navigate: vi.fn() }; routerStub = { navigate: vi.fn() };
routeQueryParamMap = convertToParamMap({});
authUserState = signal(null);
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [CheckoutPageComponent], imports: [CheckoutPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutServiceStub }, { provide: CheckoutService, useValue: checkoutServiceStub },
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
{ provide: CartService, useValue: cartServiceStub }, { provide: CartService, useValue: cartServiceStub },
{ provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } }, { provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } },
{ provide: AuthService, useValue: { user: signal(null) } }, { provide: AuthService, useValue: { user: authUserState } },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
get queryParamMap() {
return routeQueryParamMap;
},
},
},
},
{ provide: Router, useValue: routerStub }, { provide: Router, useValue: routerStub },
], ],
}) })
@@ -87,6 +118,7 @@ describe('CheckoutPageComponent payment validation', () => {
const fixture = TestBed.createComponent(CheckoutPageComponent); const fixture = TestBed.createComponent(CheckoutPageComponent);
fixture.detectChanges(); fixture.detectChanges();
fixture.componentInstance['createdPurchaseId'].set(25); fixture.componentInstance['createdPurchaseId'].set(25);
routerStub.navigate.mockClear();
return { fixture, component: fixture.componentInstance as any }; return { fixture, component: fixture.componentInstance as any };
} }
@@ -105,7 +137,7 @@ describe('CheckoutPageComponent payment validation', () => {
await vi.advanceTimersByTimeAsync(5_000); await vi.advanceTimersByTimeAsync(5_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce(); expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
}); });
@@ -181,7 +213,7 @@ describe('CheckoutPageComponent payment validation', () => {
await component.onComplete(); await component.onComplete();
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce(); expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
@@ -197,4 +229,175 @@ describe('CheckoutPageComponent payment validation', () => {
expect(cartServiceStub.clearCart).not.toHaveBeenCalled(); expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
it('loads purchase items but prefills customer data from the user', async () => {
const purchase = {
id: 25,
cart_id: null,
nombre_apellido: 'Datos de la compra',
email: 'compra@example.com',
dni: '11111111',
telefono: '1111111111',
items: [
{
id: 91,
quantity: 2,
unit_price: '1250.50',
line_total: '2501.00',
source_catalog_item_id: 8,
source_variant_id: 21,
item_details: {
nombre: 'Remera',
descripcion: null,
slug: 'remera',
imagen: 'https://example.com/remera.jpg',
attributes: [{ name: 'Color', value: 'Negro' }],
},
},
],
subtotal: '2501.00',
total: '2501.00',
};
routeQueryParamMap = convertToParamMap({ purchase: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const { component } = createComponent();
await Promise.resolve();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(component.mappedCartItems()).toEqual([
{
cartItemId: 91,
imageUrl: 'https://example.com/remera.jpg',
product: 'Remera',
originalPrice: null,
discountedPrice: 1250.5,
discountPercentage: null,
attributes: [{ label: 'Color', value: 'Negro' }],
quantity: 2,
},
]);
expect(component.cartSubtotal()).toBe(2501);
expect(component.cartTotal()).toBe(2501);
expect(component.form.getRawValue()).toEqual({
nombre: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
});
it('updates a purchase item while editing and refreshes checkout totals', async () => {
const updatedPurchase = {
id: 25,
items: [],
subtotal: '300.00',
total: '300.00',
};
checkoutServiceStub.updateItemQuantity.mockResolvedValue(updatedPurchase);
const { component } = createComponent();
component.isEditingItems.set(true);
await component.onPurchaseItemQuantityChange({
item: {
cartItemId: 91,
imageUrl: null,
product: 'Remera',
originalPrice: null,
discountedPrice: 100,
discountPercentage: null,
attributes: [],
quantity: 2,
},
quantity: 3,
});
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
'tenant-test',
25,
91,
3,
);
expect(component.createdPurchase()).toBe(updatedPurchase);
expect(component.isUpdatingItem()).toBe(false);
});
it('keeps the payment step selected while editing and regenerates payment afterward', async () => {
const editablePurchase = {
id: 25,
status: 'created',
items: [],
subtotal: '100.00',
total: '100.00',
};
checkoutServiceStub.prepareItemEditing.mockResolvedValue(editablePurchase);
const { component } = createComponent();
component.stepper = { currentStepIndex: signal(1) };
const selectPaymentMethod = vi
.spyOn(component, 'selectPaymentMethod')
.mockResolvedValue(undefined);
await component.onEditingItemsChange(true);
expect(checkoutServiceStub.prepareItemEditing).toHaveBeenCalledWith('tenant-test', 25);
expect(component.isEditingItems()).toBe(true);
expect(component.createdPurchase()).toBe(editablePurchase);
await component.onEditingItemsChange(false);
expect(component.stepper.currentStepIndex()).toBe(1);
expect(selectPaymentMethod).toHaveBeenCalledWith('qr');
expect(component.isEditingItems()).toBe(false);
});
it('updates customer data on the existing purchase before payment', async () => {
const updatedPurchase = {
id: 25,
cart_id: 10,
items: [],
subtotal: '100.00',
total: '100.00',
};
checkoutServiceStub.updateCustomerData.mockResolvedValue(updatedPurchase);
const { component } = createComponent();
component.form.setValue({
nombre: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
component.stepper = { next: vi.fn() };
await component.onStep1Continue();
expect(checkoutServiceStub.startCheckout).not.toHaveBeenCalled();
expect(checkoutServiceStub.updateCustomerData).toHaveBeenCalledWith('tenant-test', 25, {
dni: '12345678',
telefono: '3415555555',
email: 'juan@example.com',
nombre_apellido: 'Juan Perez',
});
expect(component.createdPurchase()).toEqual({
...updatedPurchase,
status: 'pending_payment',
});
expect(component.stepper.next).toHaveBeenCalledOnce();
});
it('cancels the pending purchase before allowing navigation away', async () => {
const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true);
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.loadCart).toHaveBeenCalled();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(component.createdPurchaseId()).toBeNull();
});
}); });

View File

@@ -2,24 +2,25 @@ import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
computed, computed,
effect,
inject, inject,
OnDestroy, OnDestroy,
OnInit, OnInit,
signal, signal,
untracked,
ViewChild, ViewChild,
} from '@angular/core'; } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { startWith } from 'rxjs'; import { firstValueFrom, startWith } from 'rxjs';
import { CartService } from '../../../../core/services/cart/cart.service';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { CheckoutService, CreatePurchasePayload } from '../../../../core/services/checkout.service'; import {
CheckoutService,
PurchaseDetailItemResponse,
PurchaseDetailResponse,
} from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { BankAccount } from '../../../../core/services/tenant.interface'; import { BankAccount } from '../../../../core/services/tenant.interface';
import { CartItem } from '../../../../core/services/cart/cart.interface';
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component'; import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component'; import { StepComponent } from '../../../../shared/components/stepper/step.component';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component'; import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
@@ -51,11 +52,12 @@ import {
}) })
export class CheckoutPageComponent implements OnInit, OnDestroy { export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly formBuilder = inject(FormBuilder); private readonly formBuilder = inject(FormBuilder);
private readonly cartService = inject(CartService); private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly cartService = inject(CartService);
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 60; private readonly qrPollingMaxAttempts = 60;
@@ -74,19 +76,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
telefono: ['', [Validators.required]], telefono: ['', [Validators.required]],
}); });
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly cartSubtotal = computed(() => { protected readonly cartSubtotal = computed(() => {
const cart = this.cartService.cart(); const purchase = this.createdPurchase();
return cart ? parseFloat(cart.subtotal) : 0; return purchase ? parseFloat(purchase.subtotal) : 0;
}); });
protected readonly cartDiscount = computed(() => 0); protected readonly cartDiscount = computed(() => 0);
protected readonly cartTotal = computed(() => this.cartSubtotal() - this.cartDiscount()); protected readonly cartTotal = computed(() => {
const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.total) : this.cartSubtotal() - this.cartDiscount();
});
protected readonly mappedCartItems = computed<CartItemMock[]>(() => { protected readonly mappedCartItems = computed<CartItemMock[]>(() => {
const cart = this.cartService.cart(); const purchase = this.createdPurchase();
if (!cart || !cart.items) return []; return purchase ? purchase.items.map((item) => this.mapPurchaseItemToMock(item)) : [];
return cart.items.map((item) => this.mapCartItemToMock(item));
}); });
protected readonly isStep1Valid = signal(this.form.valid); protected readonly isStep1Valid = signal(this.form.valid);
@@ -100,32 +106,19 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly transferAccount = signal<TransferAccount | null>(null); protected readonly transferAccount = signal<TransferAccount | null>(null);
protected readonly transferDni = signal<string>(''); protected readonly transferDni = signal<string>('');
protected readonly isCreatingPurchase = signal(false); protected readonly isUpdatingPurchase = signal(false);
protected readonly isEditingItems = signal(false);
protected readonly isUpdatingItem = signal(false);
protected readonly isPreparingItemEdit = signal(false);
protected readonly createdPurchaseId = signal<number | null>(null); protected readonly createdPurchaseId = signal<number | null>(null);
protected readonly isGeneratingIntent = signal(false); protected readonly isGeneratingIntent = signal(false);
protected readonly isPaymentLoading = computed( protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
() => this.isGeneratingIntent() || this.cartService.isUpdating(),
);
protected readonly qrData = signal<string | null>(null); protected readonly qrData = signal<string | null>(null);
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle'); protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
protected readonly isCheckingQrPayment = signal(false); protected readonly isCheckingQrPayment = signal(false);
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle'); protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
constructor() { constructor() {
effect(() => {
// We only want to trigger the intent generation when the cart changes.
// So we track the cart, but untrack the other signals to prevent duplicate calls.
const cart = this.cartService.cart();
untracked(() => {
const purchaseId = this.createdPurchaseId();
if (cart && purchaseId && !this.navigationStarted) {
// Trigger payment intent generation when cart changes and we are on the payment step
void this.selectPaymentMethod(this.selectedPaymentMethod());
}
});
});
this.form.statusChanges this.form.statusChanges
.pipe(startWith(this.form.status)) .pipe(startWith(this.form.status))
.subscribe(() => this.isStep1Valid.set(this.form.valid)); .subscribe(() => this.isStep1Valid.set(this.form.valid));
@@ -144,68 +137,126 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
this.cartService.loadCart().subscribe(); const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']);
return;
}
void this.loadPurchase(purchaseId);
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.stopQrPolling(); this.stopQrPolling();
} }
private mapCartItemToMock(item: CartItem): CartItemMock { private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
const fullName = item.product?.nombre ?? '';
let product = fullName;
let attributes: { label: string; value: string }[] = [];
const match = fullName.match(/^(.*?)\s*\((.*?)\)$/);
if (match) {
product = match[1];
const attributesString = match[2];
attributes = attributesString.split(',').map((attr) => {
const parts = attr.split(':');
if (parts.length === 2) {
return { label: parts[0].trim(), value: parts[1].trim() };
}
return { label: '', value: attr.trim() };
});
}
return { return {
cartItemId: item.id, cartItemId: item.id,
imageUrl: item.product?.imagen ?? null, imageUrl: item.item_details.imagen,
product, product: item.item_details.nombre,
originalPrice: null, originalPrice: null,
discountedPrice: parseFloat(item.precio_unitario), discountedPrice: parseFloat(item.unit_price),
discountPercentage: null, discountPercentage: null,
attributes, attributes: item.item_details.attributes.map((attribute) => ({
quantity: item.cantidad, label: attribute.name,
value: attribute.value === null ? '' : String(attribute.value),
})),
quantity: item.quantity,
}; };
} }
protected async onStep1Continue(): Promise<void> { protected async onEditingItemsChange(editing: boolean): Promise<void> {
if (this.form.invalid) return; if (this.isUpdatingItem() || this.isPreparingItemEdit()) {
return;
}
const tenant = this.tenantService.tenant(); if (!editing) {
if (!tenant) return; this.isEditingItems.set(false);
this.isCreatingPurchase.set(true); if (this.stepper?.currentStepIndex() === 1) {
void this.selectPaymentMethod(this.selectedPaymentMethod());
try {
const cart = this.cartService.cart();
if (!cart?.id) {
throw new Error('No hay un carrito activo para finalizar la compra.');
} }
return;
}
this.isEditingItems.set(true);
this.stopQrPolling();
this.qrData.set(null);
this.qrPaymentStatus.set('idle');
this.transferAccount.set(null);
this.transferValidationStatus.set('idle');
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) {
this.isEditingItems.set(false);
return;
}
this.isPreparingItemEdit.set(true);
try {
const purchase = await this.checkoutService.prepareItemEditing(
tenant.codigo,
purchaseId,
);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to prepare purchase item editing:', error);
this.isEditingItems.set(false);
} finally {
this.isPreparingItemEdit.set(false);
}
}
protected async onPurchaseItemQuantityChange(event: {
item: CartItemMock;
quantity: number;
}): Promise<void> {
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
const itemId = event.item.cartItemId;
if (!tenant || !purchaseId || !itemId || this.isUpdatingItem() || !this.isEditingItems()) {
return;
}
this.isUpdatingItem.set(true);
try {
const purchase = await this.checkoutService.updateItemQuantity(
tenant.codigo,
purchaseId,
itemId,
event.quantity,
);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to update purchase item quantity:', error);
} finally {
this.isUpdatingItem.set(false);
}
}
protected async onStep1Continue(): Promise<void> {
if (this.form.invalid || this.isUpdatingPurchase() || this.isEditingItems()) return;
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) return;
this.isUpdatingPurchase.set(true);
try {
const formValue = this.form.getRawValue(); const formValue = this.form.getRawValue();
const payload: CreatePurchasePayload = { const purchase = await this.checkoutService.updateCustomerData(tenant.codigo, purchaseId, {
cart_id: cart.id,
dni: formValue.dni, dni: formValue.dni,
telefono: formValue.telefono, telefono: formValue.telefono,
email: formValue.email, email: formValue.email,
nombre_apellido: formValue.nombre, nombre_apellido: formValue.nombre,
}; });
this.createdPurchase.set(purchase);
const response = await this.checkoutService.createPurchase(tenant.codigo, payload);
this.createdPurchaseId.set(response.id);
this.stepper.next(); this.stepper.next();
@@ -215,17 +266,50 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
console.error('Failed to create purchase:', error); console.error('Failed to create purchase:', error);
// Here we could show an alert or toast // Here we could show an alert or toast
} finally { } finally {
this.isCreatingPurchase.set(false); this.isUpdatingPurchase.set(false);
} }
} }
protected onCancel(): void { protected async onCancel(): Promise<void> {
if (await this.canDeactivate()) {
void this.router.navigate(['/']);
}
}
public async canDeactivate(): Promise<boolean> {
this.stopQrPolling(); this.stopQrPolling();
void this.router.navigate(['/']);
if (this.navigationStarted) {
return true;
}
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
if (!purchaseId || !tenant) {
return true;
}
try {
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
this.createdPurchaseId.set(null);
this.createdPurchase.set(null);
try {
await firstValueFrom(this.cartService.loadCart());
} catch (error) {
console.error('Failed to restore cart after cancelling checkout:', error);
}
return true;
} catch (error) {
console.error('Failed to cancel purchase:', error);
return false;
}
} }
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> { protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
if (this.navigationStarted) { if (this.navigationStarted || this.isEditingItems()) {
return; return;
} }
@@ -266,6 +350,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
this.qrData.set(response.qr_data.qr_code); this.qrData.set(response.qr_data.qr_code);
this.markPurchasePendingPayment();
this.startQrPolling(); this.startQrPolling();
} }
} catch (error) { } catch (error) {
@@ -276,6 +361,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
protected async generateTransferIntent(dni: string): Promise<void> { protected async generateTransferIntent(dni: string): Promise<void> {
if (this.isEditingItems()) {
return;
}
const purchaseId = this.createdPurchaseId(); const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant(); const tenant = this.tenantService.tenant();
@@ -291,10 +380,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
tenant.codigo, tenant.codigo,
purchaseId, purchaseId,
'transfer', 'transfer',
dni dni,
); );
if (response.transfer_data) { if (response.transfer_data) {
this.markPurchasePendingPayment();
this.transferAccount.set({ this.transferAccount.set({
titular: response.transfer_data.titular, titular: response.transfer_data.titular,
entidad: response.transfer_data.entidad, entidad: response.transfer_data.entidad,
@@ -334,6 +424,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
!purchaseId || !purchaseId ||
!tenant || !tenant ||
this.navigationStarted || this.navigationStarted ||
this.isEditingItems() ||
this.transferValidationStatus() === 'checking' this.transferValidationStatus() === 'checking'
) { ) {
return; return;
@@ -448,11 +539,22 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} }
private handleConfirmedPayment(purchaseId: number): void { private markPurchasePendingPayment(): void {
this.navigateToPurchaseStatus(purchaseId, true); this.createdPurchase.update((purchase) =>
purchase
? {
...purchase,
status: 'pending_payment',
}
: purchase,
);
} }
private navigateToPurchaseStatus(purchaseId: number, clearCart = false): void { private handleConfirmedPayment(purchaseId: number): void {
this.navigateToPurchaseStatus(purchaseId);
}
private navigateToPurchaseStatus(purchaseId: number): void {
if (this.navigationStarted) { if (this.navigationStarted) {
return; return;
} }
@@ -460,10 +562,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true; this.navigationStarted = true;
this.stopQrPolling(); this.stopQrPolling();
if (clearCart) {
this.cartService.clearCart();
}
void this.router.navigate(['/checkout/status', purchaseId]); void this.router.navigate(['/checkout/status', purchaseId]);
} }
private async loadPurchase(purchaseId: number): Promise<void> {
const tenant = this.tenantService.tenant();
if (!tenant) {
void this.router.navigate(['/']);
return;
}
try {
const purchase = await this.checkoutService.getPurchase(tenant.codigo, purchaseId);
this.createdPurchaseId.set(purchase.id);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to load purchase:', error);
void this.router.navigate(['/']);
}
}
} }

View File

@@ -0,0 +1,8 @@
import { CanDeactivateFn } from '@angular/router';
interface PendingCheckoutComponent {
canDeactivate(): Promise<boolean>;
}
export const checkoutPendingPurchaseGuard: CanDeactivateFn<PendingCheckoutComponent> = (component) =>
component.canDeactivate();

View File

@@ -9,6 +9,7 @@ import { InputComponent } from '../../../../shared/components/input/input.compon
const PASSWORD_MIN_LENGTH = 8; const PASSWORD_MIN_LENGTH = 8;
const EMAIL_MAX_LENGTH = 255; const EMAIL_MAX_LENGTH = 255;
const POST_LOGIN_RETURN_URL_KEY = 'shopit.auth.return-url';
@Component({ @Component({
selector: 'app-login-page', selector: 'app-login-page',
@@ -84,6 +85,10 @@ export class LoginPageComponent {
this.serverErrorState.set(null); this.serverErrorState.set(null);
try { try {
const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
if (returnUrl?.startsWith('/') && !returnUrl.startsWith('//')) {
this.document.defaultView?.sessionStorage.setItem(POST_LOGIN_RETURN_URL_KEY, returnUrl);
}
this.authService.loginWithGoogle(); this.authService.loginWithGoogle();
} catch (error: unknown) { } catch (error: unknown) {
this.serverErrorState.set(this.resolveErrorMessage(error)); this.serverErrorState.set(this.resolveErrorMessage(error));
@@ -131,8 +136,16 @@ export class LoginPageComponent {
} }
protected redirectToHome(): void { protected redirectToHome(): void {
const homeUrl = this.router.serializeUrl(this.router.createUrlTree(['/'])); const requestedUrl =
this.document.location.assign(homeUrl); this.route.snapshot.queryParamMap.get('returnUrl') ??
this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY);
const destination =
requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//')
? requestedUrl
: this.router.serializeUrl(this.router.createUrlTree(['/']));
this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY);
this.document.location.assign(destination);
} }
private completeGoogleLogin(oauthCode: string): void { private completeGoogleLogin(oauthCode: string): void {

View File

@@ -73,9 +73,12 @@
<app-button <app-button
class="product-detail__cta" class="product-detail__cta"
type="button" type="button"
[disabled]="!selectedVariantAvailable() || variantLoading()" [disabled]="
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
"
(click)="buyNow()"
> >
@if (variantLoading()) { @if (variantLoading() || creatingDirectPurchase()) {
<div class="spinner-border spinner-border-sm" role="status"></div> <div class="spinner-border spinner-border-sm" role="status"></div>
} @else { } @else {
Comprar Comprar

View File

@@ -1,4 +1,5 @@
import { TestBed, getTestBed } from '@angular/core/testing'; import { TestBed, getTestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
@@ -10,6 +11,9 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component'; import { ProductDetailPageComponent } from './product-detail-page.component';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { import {
PRODUCT_DETAIL_ERROR_MESSAGE, PRODUCT_DETAIL_ERROR_MESSAGE,
ProductDetailResolvedData, ProductDetailResolvedData,
@@ -41,6 +45,7 @@ describe('ProductDetailPageComponent', () => {
let routerStub: any; let routerStub: any;
let cartServiceStub: any; let cartServiceStub: any;
let toastServiceStub: any; let toastServiceStub: any;
let checkoutServiceStub: any;
beforeAll(() => { beforeAll(() => {
try { try {
@@ -72,6 +77,9 @@ describe('ProductDetailPageComponent', () => {
danger: vi.fn(), danger: vi.fn(),
info: vi.fn(), info: vi.fn(),
}; };
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 44 }),
};
}); });
async function configureTestingModule() { async function configureTestingModule() {
@@ -100,6 +108,26 @@ describe('ProductDetailPageComponent', () => {
provide: ToastService, provide: ToastService,
useValue: toastServiceStub, useValue: toastServiceStub,
}, },
{
provide: CheckoutService,
useValue: checkoutServiceStub,
},
{
provide: TenantService,
useValue: { tenant: signal({ codigo: 'tenant-test' }) },
},
{
provide: AuthService,
useValue: {
user: signal({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
}),
},
},
], ],
}).compileComponents(); }).compileComponents();
} }
@@ -364,7 +392,7 @@ describe('ProductDetailPageComponent', () => {
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos'); expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
}); });
it('renders purchase actions without side effects', async () => { it('renders purchase actions and starts a direct checkout', async () => {
await configureTestingModule(); await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent); const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges(); fixture.detectChanges();
@@ -380,8 +408,18 @@ describe('ProductDetailPageComponent', () => {
buttons[0].click(); buttons[0].click();
buttons[1].click(); buttons[1].click();
await Promise.resolve();
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('tenant-test', {
direct_item: {
catalog_item_id: 1,
variant_id: null,
cantidad: 1,
},
});
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 44 },
});
}); });
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => { it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {

View File

@@ -28,6 +28,9 @@ import { ButtonComponent } from '../../../../shared/components/button/button.com
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component'; import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component'; import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
import { ProductDetailResolvedData } from './product-detail-page.resolver'; import { ProductDetailResolvedData } from './product-detail-page.resolver';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
@Component({ @Component({
selector: 'app-product-detail-page', selector: 'app-product-detail-page',
@@ -50,6 +53,9 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
private readonly catalogService = inject(CatalogService); private readonly catalogService = inject(CatalogService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly checkoutService = inject(CheckoutService);
private readonly tenantService = inject(TenantService);
private readonly authService = inject(AuthService);
private readonly attributeSelector = viewChild(ProductAttributeSelectorComponent); private readonly attributeSelector = viewChild(ProductAttributeSelectorComponent);
private readonly carouselHost = viewChild<ElementRef<HTMLElement>>('carouselHost'); private readonly carouselHost = viewChild<ElementRef<HTMLElement>>('carouselHost');
private readonly descriptionBody = viewChild<ElementRef<HTMLElement>>('descriptionBody'); private readonly descriptionBody = viewChild<ElementRef<HTMLElement>>('descriptionBody');
@@ -77,6 +83,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly loading = signal(false); protected readonly loading = signal(false);
protected readonly variantLoading = signal(false); protected readonly variantLoading = signal(false);
protected readonly addingToCart = signal(false); protected readonly addingToCart = signal(false);
protected readonly creatingDirectPurchase = signal(false);
protected readonly error = signal<string | null>(null); protected readonly error = signal<string | null>(null);
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null); protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
protected readonly quantity = signal(1); protected readonly quantity = signal(1);
@@ -253,6 +260,55 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}); });
} }
protected async buyNow(): Promise<void> {
const currentProduct = this.product();
const variant = this.selectedVariant();
if (this.creatingDirectPurchase()) {
return;
}
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
return;
}
const tenant = this.tenantService.tenant();
const user = this.authService.user();
if (!user) {
void this.router.navigate(['/login'], {
queryParams: { returnUrl: `/producto/${currentProduct.id}` },
});
return;
}
if (!tenant) {
this.toastService.danger('No se pudo identificar la tienda.');
return;
}
this.creatingDirectPurchase.set(true);
try {
const purchase = await this.checkoutService.startCheckout(tenant.codigo, {
direct_item: {
catalog_item_id: currentProduct.id,
variant_id: variant?.id ?? null,
cantidad: this.quantity(),
},
});
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
} catch (error) {
console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.');
} finally {
this.creatingDirectPurchase.set(false);
}
}
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean { private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0; return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
} }

View File

@@ -57,6 +57,20 @@
Actualizar estado Actualizar estado
</app-button> </app-button>
</div> </div>
} @else if (status() === 'expired') {
<div class="status-content__section status-content__section--primary">
<div class="status-content__icon status-content__icon--warning">
<i class="fa-solid fa-clock"></i>
</div>
<h2 class="status-content__title">LA COMPRA VENCI&Oacute;</h2>
<p class="status-content__subtitle">El plazo de pago termin&oacute; y liberamos el stock reservado.</p>
</div>
<hr class="status-content__divider" />
<div class="status-content__section status-content__section--secondary">
<p class="status-content__message">Pod&eacute;s volver a la tienda e iniciar una nueva compra.</p>
</div>
} @else if (status() === 'rejected') { } @else if (status() === 'rejected') {
<div class="status-content__section status-content__section--primary"> <div class="status-content__section status-content__section--primary">
<div class="status-content__icon status-content__icon--error"> <div class="status-content__icon status-content__icon--error">

View File

@@ -5,7 +5,7 @@ import { CheckoutService, PurchaseStatusResponse } from '../../../../core/servic
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component'; import { ButtonComponent } from '../../../../shared/components/button/button.component';
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'error'; type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
@Component({ @Component({
selector: 'app-purchase-status-page', selector: 'app-purchase-status-page',
@@ -93,6 +93,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'rejected'; return 'rejected';
} }
if (purchase.status === 'expired') {
return 'expired';
}
return 'pending'; return 'pending';
} }

View File

@@ -12,6 +12,7 @@ import { ResetPasswordPageComponent } from './pages/reset-password-page/reset-pa
import { RegisterPageComponent } from './pages/register-page/register-page.component'; import { RegisterPageComponent } from './pages/register-page/register-page.component';
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component'; import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
import { storeHomeCatalogResolver } from './pages/store-home-page/store-home-page.resolver'; import { storeHomeCatalogResolver } from './pages/store-home-page/store-home-page.resolver';
import { checkoutPendingPurchaseGuard } from './pages/checkout-page/checkout-page.guard';
export const routes: Routes = [ export const routes: Routes = [
{ {
@@ -86,6 +87,7 @@ export const routes: Routes = [
{ {
path: 'checkout', path: 'checkout',
canActivate: [authGuard, hasMenuGuard('checkout')], canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () => loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then( import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent, (m) => m.CheckoutPageComponent,

View File

@@ -34,20 +34,25 @@
} }
</div> </div>
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions"> @if (!readonly()) {
<app-quantity-selector <div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
size="small" <app-quantity-selector
[quantity]="quantity()" size="small"
(quantityChange)="onQuantityChange($event)" [quantity]="quantity()"
(increase)="onIncrease()" [disabled]="quantityDisabled()"
(decrease)="onDecrease()" (quantityChange)="onQuantityChange($event)"
/> (increase)="onIncrease()"
<app-icon-button (decrease)="onDecrease()"
variant="trash" />
class="cart-item-remove-btn" @if (!quantityDisabled() && showRemove()) {
(click)="onRemove()" <app-icon-button
/> variant="trash"
</div> class="cart-item-remove-btn"
(click)="onRemove()"
/>
}
</div>
}
</div> </div>
</article> </article>

View File

@@ -23,6 +23,9 @@ export class CartItemComponent {
readonly discountPercentage = input<number | null>(null); readonly discountPercentage = input<number | null>(null);
readonly attributes = input<CartItemAttribute[]>([]); readonly attributes = input<CartItemAttribute[]>([]);
readonly quantity = input<number>(1); readonly quantity = input<number>(1);
readonly readonly = input<boolean>(false);
readonly quantityDisabled = input<boolean>(false);
readonly showRemove = input<boolean>(true);
readonly quantityChange = output<number>(); readonly quantityChange = output<number>();
readonly remove = output<void>(); readonly remove = output<void>();
@@ -30,6 +33,7 @@ export class CartItemComponent {
readonly decrease = output<void>(); readonly decrease = output<void>();
protected onQuantityChange(newQuantity: number): void { protected onQuantityChange(newQuantity: number): void {
if (this.quantityDisabled()) return;
this.quantityChange.emit(newQuantity); this.quantityChange.emit(newQuantity);
} }

View File

@@ -5,16 +5,30 @@
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header"> <header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2> <h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
@if (showClose()) { <div class="d-flex align-items-center cart-header-actions">
<button @if (!readonly() && allowEditing() && items().length > 0) {
class="btn btn-link p-0 border-0 d-inline-flex align-items-center justify-content-center cart-close-btn" <button
type="button" class="btn btn-link p-0 border-0 cart-edit-btn"
aria-label="Cerrar carrito" type="button"
(click)="closed.emit()" [attr.aria-pressed]="editing()"
> [disabled]="editingDisabled()"
<i class="fa-solid fa-xmark"></i> (click)="toggleEditing()"
</button> >
} {{ editing() ? 'Listo' : 'Modificar' }}
</button>
}
@if (showClose()) {
<button
class="btn btn-link p-0 border-0 d-inline-flex align-items-center justify-content-center cart-close-btn"
type="button"
aria-label="Cerrar carrito"
(click)="closed.emit()"
>
<i class="fa-solid fa-xmark"></i>
</button>
}
</div>
</header> </header>
<div class="d-grid w-100 flex-grow-1 overflow-y-auto cart-items-container"> <div class="d-grid w-100 flex-grow-1 overflow-y-auto cart-items-container">
@@ -31,6 +45,9 @@
[discountPercentage]="item.discountPercentage" [discountPercentage]="item.discountPercentage"
[attributes]="item.attributes" [attributes]="item.attributes"
[quantity]="getItemQuantity(item)" [quantity]="getItemQuantity(item)"
[readonly]="readonly()"
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
[showRemove]="allowRemove()"
(quantityChange)="onItemQuantityChange(idx, $event)" (quantityChange)="onItemQuantityChange(idx, $event)"
(remove)="onItemRemove(idx)" (remove)="onItemRemove(idx)"
/> />

View File

@@ -21,6 +21,17 @@
color: #a0a0a0; color: #a0a0a0;
} }
.cart-header-actions {
gap: 14px;
}
.cart-edit-btn {
color: var(--bs-primary);
font-size: 11px;
font-weight: 500;
text-decoration: none;
}
.cart-items-container { .cart-items-container {
min-height: 0; min-height: 0;
gap: 0; gap: 0;

View File

@@ -306,4 +306,105 @@ describe('CartComponent', () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('enables quantity editing only while Modificar mode is active', async () => {
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
updateItemQuantity: vi.fn(),
removeItem: vi.fn(),
},
},
{ provide: ModalService, useValue: {} },
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto de prueba',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.componentRef.setInput('allowEditing', true);
const editingChange = vi.fn();
fixture.componentInstance.editing.subscribe(editingChange);
fixture.detectChanges();
const editButton = fixture.debugElement.query(By.css('.cart-edit-btn'));
expect(editButton.nativeElement.textContent.trim()).toBe('Modificar');
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(true);
editButton.nativeElement.click();
fixture.detectChanges();
expect(editButton.nativeElement.textContent.trim()).toBe('Listo');
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(false);
expect(editingChange).toHaveBeenCalledWith(true);
editButton.nativeElement.click();
fixture.detectChanges();
expect(editButton.nativeElement.textContent.trim()).toBe('Modificar');
expect(editingChange).toHaveBeenLastCalledWith(false);
});
it('allows editing directly when the optional Modificar toggle is disabled', async () => {
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
updateItemQuantity: vi.fn(),
removeItem: vi.fn(),
},
},
{ provide: ModalService, useValue: {} },
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto de prueba',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.cart-edit-btn'))).toBeNull();
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(false);
});
}); });

View File

@@ -4,6 +4,7 @@ import {
computed, computed,
inject, inject,
input, input,
model,
output, output,
signal, signal,
} from '@angular/core'; } from '@angular/core';
@@ -48,11 +49,21 @@ export class CartComponent {
readonly discount = input<number>(0); readonly discount = input<number>(0);
readonly total = input<number>(0); readonly total = input<number>(0);
readonly backgroundColor = input<string>('#ffffff'); readonly backgroundColor = input<string>('#ffffff');
readonly readonly = input<boolean>(false);
readonly allowEditing = input<boolean>(false);
readonly allowRemove = input<boolean>(true);
readonly persistQuantityChanges = input<boolean>(true);
readonly editingDisabled = input<boolean>(false);
readonly editing = model<boolean>(false);
readonly closed = output<void>(); readonly closed = output<void>();
readonly itemQuantityChange = output<{
item: CartItemMock;
index: number;
quantity: number;
}>();
protected readonly quantityOverrides = signal<Record<number, number>>({}); protected readonly quantityOverrides = signal<Record<number, number>>({});
constructor() { constructor() {
this.quantityUpdates$ this.quantityUpdates$
.pipe( .pipe(
@@ -103,6 +114,20 @@ export class CartComponent {
protected onItemQuantityChange(index: number, newQuantity: number): void { protected onItemQuantityChange(index: number, newQuantity: number): void {
const mockItem = this.items()[index]; const mockItem = this.items()[index];
if (!mockItem) {
return;
}
this.itemQuantityChange.emit({
item: mockItem,
index,
quantity: newQuantity,
});
if (!this.persistQuantityChanges()) {
return;
}
const cartItemId = mockItem?.cartItemId; const cartItemId = mockItem?.cartItemId;
if (cartItemId) { if (cartItemId) {
this.quantityOverrides.update((overrides) => ({ this.quantityOverrides.update((overrides) => ({
@@ -153,6 +178,15 @@ export class CartComponent {
protected readonly formattedDiscount = computed(() => this.formatCurrency(this.discount())); protected readonly formattedDiscount = computed(() => this.formatCurrency(this.discount()));
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total())); protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
protected toggleEditing(): void {
if (this.editingDisabled()) {
return;
}
const editing = !this.editing();
this.editing.set(editing);
}
private formatCurrency(value: number): string { private formatCurrency(value: number): string {
const rounded = Math.round(value); const rounded = Math.round(value);
const parts = rounded.toString().split('.'); const parts = rounded.toString().split('.');

View File

@@ -1,13 +1,15 @@
<div <div
class="quantity-selector d-inline-flex align-items-center overflow-hidden rounded" class="quantity-selector d-inline-flex align-items-center overflow-hidden rounded"
[class.quantity-selector--small]="size() === 'small'" [class.quantity-selector--small]="size() === 'small'"
[class.quantity-selector--disabled]="disabled()"
aria-label="Selector de cantidad" aria-label="Selector de cantidad"
[attr.aria-disabled]="disabled()"
> >
<button <button
type="button" type="button"
class="quantity-selector__button border-0 p-0 fw-bold lh-1" class="quantity-selector__button border-0 p-0 fw-bold lh-1"
aria-label="Disminuir cantidad" aria-label="Disminuir cantidad"
[disabled]="quantity() <= min()" [disabled]="disabled() || quantity() <= min()"
(click)="onDecrease()" (click)="onDecrease()"
> >
- -
@@ -22,7 +24,7 @@
type="button" type="button"
class="quantity-selector__button border-0 p-0 fw-bold lh-1" class="quantity-selector__button border-0 p-0 fw-bold lh-1"
aria-label="Aumentar cantidad" aria-label="Aumentar cantidad"
[disabled]="atMaximum()" [disabled]="disabled() || atMaximum()"
(click)="onIncrease()" (click)="onIncrease()"
> >
+ +

View File

@@ -60,3 +60,7 @@
} }
} }
} }
.quantity-selector--disabled {
opacity: 0.55;
}

View File

@@ -52,4 +52,21 @@ describe('QuantitySelectorComponent', () => {
expect(decreaseButton.disabled).toBe(true); expect(decreaseButton.disabled).toBe(true);
expect(fixture.componentInstance.quantity()).toBe(1); expect(fixture.componentInstance.quantity()).toBe(1);
}); });
it('disables both controls and ignores quantity changes when disabled', () => {
const fixture = TestBed.createComponent(QuantitySelectorComponent);
fixture.componentRef.setInput('quantity', 2);
fixture.componentRef.setInput('disabled', true);
fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>;
expect(Array.from(buttons).every((button) => button.disabled)).toBe(true);
expect(fixture.nativeElement.querySelector('[aria-disabled="true"]')).not.toBeNull();
(fixture.componentInstance as any).onIncrease();
(fixture.componentInstance as any).onDecrease();
expect(fixture.componentInstance.quantity()).toBe(2);
});
}); });

View File

@@ -13,6 +13,7 @@ export class QuantitySelectorComponent {
readonly min = input<number>(1); readonly min = input<number>(1);
readonly max = input<number | null>(100); readonly max = input<number | null>(100);
readonly size = input<'small' | 'medium'>('medium'); readonly size = input<'small' | 'medium'>('medium');
readonly disabled = input<boolean>(false);
protected readonly atMaximum = computed(() => { protected readonly atMaximum = computed(() => {
const max = this.max(); const max = this.max();
@@ -23,14 +24,14 @@ export class QuantitySelectorComponent {
readonly decrease = output<void>(); readonly decrease = output<void>();
protected onDecrease(): void { protected onDecrease(): void {
if (this.quantity() > this.min()) { if (!this.disabled() && this.quantity() > this.min()) {
this.quantity.set(this.quantity() - 1); this.quantity.set(this.quantity() - 1);
this.decrease.emit(); this.decrease.emit();
} }
} }
protected onIncrease(): void { protected onIncrease(): void {
if (!this.atMaximum()) { if (!this.disabled() && !this.atMaximum()) {
this.quantity.set(this.quantity() + 1); this.quantity.set(this.quantity() + 1);
this.increase.emit(); this.increase.emit();
} }