text changes
This commit is contained in:
@@ -1,46 +0,0 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
@@ -5,19 +5,25 @@
|
||||
* automatic token verification and manual code entry.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { vi, type MockedFunction } from 'vitest';
|
||||
import { MemoryRouter, Routes, Route } from 'react-router';
|
||||
import VerifyEmail from '../../pages/VerifyEmail';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { authAPI } from '../../services/api';
|
||||
import { mockUser, mockUnverifiedUser } from '../../mocks/handlers';
|
||||
import React from "react";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
fireEvent,
|
||||
act,
|
||||
} from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { vi, type MockedFunction } from "vitest";
|
||||
import { MemoryRouter, Routes, Route } from "react-router";
|
||||
import VerifyEmail from "../../pages/VerifyEmail";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
import { authAPI } from "../../services/api";
|
||||
import { mockUser, mockUnverifiedUser } from "../../mocks/handlers";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('../../contexts/AuthContext');
|
||||
vi.mock('../../services/api', () => ({
|
||||
vi.mock("../../contexts/AuthContext");
|
||||
vi.mock("../../services/api", () => ({
|
||||
authAPI: {
|
||||
verifyEmail: vi.fn(),
|
||||
resendVerification: vi.fn(),
|
||||
@@ -25,8 +31,8 @@ vi.mock('../../services/api', () => ({
|
||||
}));
|
||||
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react-router')>();
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
@@ -34,16 +40,23 @@ vi.mock('react-router', async (importOriginal) => {
|
||||
});
|
||||
|
||||
const mockedUseAuth = useAuth as MockedFunction<typeof useAuth>;
|
||||
const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<typeof authAPI.verifyEmail>;
|
||||
const mockedResendVerification = authAPI.resendVerification as MockedFunction<typeof authAPI.resendVerification>;
|
||||
const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<
|
||||
typeof authAPI.verifyEmail
|
||||
>;
|
||||
const mockedResendVerification = authAPI.resendVerification as MockedFunction<
|
||||
typeof authAPI.resendVerification
|
||||
>;
|
||||
|
||||
// Helper to render VerifyEmail with route params
|
||||
const renderVerifyEmail = (searchParams: string = '', authOverrides: Partial<ReturnType<typeof useAuth>> = {}) => {
|
||||
const renderVerifyEmail = (
|
||||
searchParams: string = "",
|
||||
authOverrides: Partial<ReturnType<typeof useAuth>> = {},
|
||||
) => {
|
||||
mockedUseAuth.mockReturnValue({
|
||||
user: mockUnverifiedUser,
|
||||
loading: false,
|
||||
showAuthModal: false,
|
||||
authModalMode: 'login',
|
||||
authModalMode: "login",
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
googleLogin: vi.fn(),
|
||||
@@ -60,11 +73,11 @@ const renderVerifyEmail = (searchParams: string = '', authOverrides: Partial<Ret
|
||||
<Routes>
|
||||
<Route path="/verify-email" element={<VerifyEmail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('VerifyEmail', () => {
|
||||
describe("VerifyEmail", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
@@ -76,77 +89,85 @@ describe('VerifyEmail', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('Initial Loading State', () => {
|
||||
it('shows loading state while auth is initializing', async () => {
|
||||
renderVerifyEmail('', { loading: true });
|
||||
describe("Initial Loading State", () => {
|
||||
it("shows loading state while auth is initializing", async () => {
|
||||
renderVerifyEmail("", { loading: true });
|
||||
|
||||
expect(screen.getByRole('status')).toBeInTheDocument();
|
||||
expect(screen.getByRole("status")).toBeInTheDocument();
|
||||
// There are multiple "Loading..." elements - the spinner's visually-hidden text and the heading
|
||||
expect(screen.getAllByText('Loading...').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getAllByText("Loading...").length).toBeGreaterThanOrEqual(
|
||||
1,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Authentication Check', () => {
|
||||
it('redirects unauthenticated users to login', async () => {
|
||||
renderVerifyEmail('', { user: null });
|
||||
describe("Authentication Check", () => {
|
||||
it("redirects unauthenticated users to login", async () => {
|
||||
renderVerifyEmail("", { user: null });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/?login=true&redirect='),
|
||||
{ replace: true }
|
||||
expect.stringContaining("/?login=true&redirect="),
|
||||
{ replace: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users with token to login with return URL', async () => {
|
||||
renderVerifyEmail('?token=test-token-123', { user: null });
|
||||
it("redirects unauthenticated users with token to login with return URL", async () => {
|
||||
renderVerifyEmail("?token=test-token-123", { user: null });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('login=true'),
|
||||
{ replace: true }
|
||||
expect.stringContaining("login=true"),
|
||||
{ replace: true },
|
||||
);
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('verify-email'),
|
||||
{ replace: true }
|
||||
expect.stringContaining("verify-email"),
|
||||
{ replace: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto-Verification with Token', () => {
|
||||
it('auto-verifies when token present in URL', async () => {
|
||||
renderVerifyEmail('?token=valid-token-123');
|
||||
describe("Auto-Verification with Token", () => {
|
||||
it("auto-verifies when token present in URL", async () => {
|
||||
renderVerifyEmail("?token=valid-token-123");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith('valid-token-123');
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith("valid-token-123");
|
||||
});
|
||||
});
|
||||
|
||||
it('shows success state after successful verification', async () => {
|
||||
it("shows success state after successful verification", async () => {
|
||||
const mockCheckAuth = vi.fn();
|
||||
renderVerifyEmail('?token=valid-token', { checkAuth: mockCheckAuth });
|
||||
renderVerifyEmail("?token=valid-token", { checkAuth: mockCheckAuth });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(mockCheckAuth).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows success state immediately for already verified user', async () => {
|
||||
renderVerifyEmail('', { user: mockUser });
|
||||
it("shows success state immediately for already verified user", async () => {
|
||||
renderVerifyEmail("", { user: mockUser });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('auto-redirects to home after successful verification', async () => {
|
||||
renderVerifyEmail('?token=valid-token');
|
||||
it("auto-redirects to home after successful verification", async () => {
|
||||
renderVerifyEmail("?token=valid-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Advance timers to trigger auto-redirect (3 seconds)
|
||||
@@ -155,215 +176,228 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Manual Code Entry', () => {
|
||||
it('shows manual code entry form when no token in URL', async () => {
|
||||
describe("Manual Code Entry", () => {
|
||||
it("shows manual code entry form when no token in URL", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('Enter the 6-digit code sent to your email')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Enter the 6-digit code sent to your email"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Check for 6 input fields
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
expect(inputs).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('handles 6-digit input with auto-focus', async () => {
|
||||
it("handles 6-digit input with auto-focus", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
|
||||
// Type first digit using fireEvent
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
expect(inputs[0]).toHaveValue('1');
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
expect(inputs[0]).toHaveValue("1");
|
||||
|
||||
// Focus should auto-move to next input
|
||||
// (Note: actual focus behavior may depend on DOM focus events)
|
||||
// (actual focus behavior may depend on DOM focus events)
|
||||
});
|
||||
|
||||
it('filters non-numeric input', async () => {
|
||||
it("filters non-numeric input", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
|
||||
// Try typing letters
|
||||
fireEvent.change(inputs[0], { target: { value: 'a' } });
|
||||
expect(inputs[0]).toHaveValue('');
|
||||
fireEvent.change(inputs[0], { target: { value: "a" } });
|
||||
expect(inputs[0]).toHaveValue("");
|
||||
|
||||
// Try typing numbers
|
||||
fireEvent.change(inputs[0], { target: { value: '5' } });
|
||||
expect(inputs[0]).toHaveValue('5');
|
||||
fireEvent.change(inputs[0], { target: { value: "5" } });
|
||||
expect(inputs[0]).toHaveValue("5");
|
||||
});
|
||||
|
||||
it('handles paste of 6-digit code', async () => {
|
||||
it("handles paste of 6-digit code", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const container = document.querySelector('.d-flex.justify-content-center.gap-2');
|
||||
const container = document.querySelector(
|
||||
".d-flex.justify-content-center.gap-2",
|
||||
);
|
||||
|
||||
// Simulate paste event
|
||||
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true }) as any;
|
||||
const pasteEvent = new Event("paste", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}) as any;
|
||||
pasteEvent.clipboardData = {
|
||||
getData: () => '123456',
|
||||
getData: () => "123456",
|
||||
};
|
||||
|
||||
fireEvent(container!, pasteEvent);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith('123456');
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith("123456");
|
||||
});
|
||||
});
|
||||
|
||||
it('submits manual code on button click', async () => {
|
||||
it("submits manual code on button click", async () => {
|
||||
// Make the verification hang to test the button state
|
||||
mockedVerifyEmail.mockImplementation(() => new Promise(() => {}));
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
|
||||
// Fill in 5 digits (not 6 to avoid auto-submit)
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[2], { target: { value: '3' } });
|
||||
fireEvent.change(inputs[3], { target: { value: '4' } });
|
||||
fireEvent.change(inputs[4], { target: { value: '5' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
fireEvent.change(inputs[2], { target: { value: "3" } });
|
||||
fireEvent.change(inputs[3], { target: { value: "4" } });
|
||||
fireEvent.change(inputs[4], { target: { value: "5" } });
|
||||
|
||||
// Button should be disabled with only 5 digits
|
||||
const verifyButton = screen.getByRole('button', { name: /verify email/i });
|
||||
const verifyButton = screen.getByRole("button", {
|
||||
name: /verify email/i,
|
||||
});
|
||||
expect(verifyButton).toBeDisabled();
|
||||
|
||||
// Now fill in the 6th digit - this will auto-submit
|
||||
fireEvent.change(inputs[5], { target: { value: '6' } });
|
||||
fireEvent.change(inputs[5], { target: { value: "6" } });
|
||||
|
||||
// The component auto-submits when 6 digits are entered
|
||||
await waitFor(() => {
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith('123456');
|
||||
expect(mockedVerifyEmail).toHaveBeenCalledWith("123456");
|
||||
});
|
||||
});
|
||||
|
||||
it('disables verify button when code incomplete', async () => {
|
||||
it("disables verify button when code incomplete", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const verifyButton = screen.getByRole('button', { name: /verify email/i });
|
||||
const verifyButton = screen.getByRole("button", {
|
||||
name: /verify email/i,
|
||||
});
|
||||
expect(verifyButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('backspace moves focus to previous input', async () => {
|
||||
it("backspace moves focus to previous input", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
|
||||
// Fill first input and move to second
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
|
||||
// Clear second input and press backspace
|
||||
fireEvent.change(inputs[1], { target: { value: '' } });
|
||||
fireEvent.keyDown(inputs[1], { key: 'Backspace' });
|
||||
fireEvent.change(inputs[1], { target: { value: "" } });
|
||||
fireEvent.keyDown(inputs[1], { key: "Backspace" });
|
||||
|
||||
// The component handles this by focusing previous input
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('displays EXPIRED error message', async () => {
|
||||
describe("Error Handling", () => {
|
||||
it("displays EXPIRED error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'VERIFICATION_EXPIRED' } },
|
||||
response: { data: { code: "VERIFICATION_EXPIRED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=expired-token');
|
||||
renderVerifyEmail("?token=expired-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/verification code has expired/i)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/verification code has expired/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays INVALID error message', async () => {
|
||||
it("displays INVALID error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'VERIFICATION_INVALID' } },
|
||||
response: { data: { code: "VERIFICATION_INVALID" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=invalid-token');
|
||||
renderVerifyEmail("?token=invalid-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/code didn't match/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays TOO_MANY_ATTEMPTS error message', async () => {
|
||||
it("displays TOO_MANY_ATTEMPTS error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'TOO_MANY_ATTEMPTS' } },
|
||||
response: { data: { code: "TOO_MANY_ATTEMPTS" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=blocked-token');
|
||||
renderVerifyEmail("?token=blocked-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/too many attempts/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays ALREADY_VERIFIED error message', async () => {
|
||||
it("displays ALREADY_VERIFIED error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'ALREADY_VERIFIED' } },
|
||||
response: { data: { code: "ALREADY_VERIFIED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=already-verified-token');
|
||||
renderVerifyEmail("?token=already-verified-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/already verified/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('clears input on error', async () => {
|
||||
it("clears input on error", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'VERIFICATION_INVALID' } },
|
||||
response: { data: { code: "VERIFICATION_INVALID" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
|
||||
// Fill all digits - this will auto-submit due to the component behavior
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[2], { target: { value: '3' } });
|
||||
fireEvent.change(inputs[3], { target: { value: '4' } });
|
||||
fireEvent.change(inputs[4], { target: { value: '5' } });
|
||||
fireEvent.change(inputs[5], { target: { value: '6' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
fireEvent.change(inputs[2], { target: { value: "3" } });
|
||||
fireEvent.change(inputs[3], { target: { value: "4" } });
|
||||
fireEvent.change(inputs[4], { target: { value: "5" } });
|
||||
fireEvent.change(inputs[5], { target: { value: "6" } });
|
||||
|
||||
// Wait for error message to appear
|
||||
await waitFor(() => {
|
||||
@@ -372,33 +406,35 @@ describe('VerifyEmail', () => {
|
||||
|
||||
// Inputs should be cleared after error
|
||||
await waitFor(() => {
|
||||
const updatedInputs = screen.getAllByRole('textbox');
|
||||
const updatedInputs = screen.getAllByRole("textbox");
|
||||
updatedInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
expect(input).toHaveValue("");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resend Verification', () => {
|
||||
it('shows resend button', async () => {
|
||||
describe("Resend Verification", () => {
|
||||
it("shows resend button", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByRole('button', { name: /send code/i })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /send code/i }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('starts 60-second cooldown after resend', async () => {
|
||||
it("starts 60-second cooldown after resend", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -408,32 +444,32 @@ describe('VerifyEmail', () => {
|
||||
expect(mockedResendVerification).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables resend during cooldown', async () => {
|
||||
it("disables resend during cooldown", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/resend in 60s/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const cooldownButton = screen.getByRole('button', { name: /resend in/i });
|
||||
const cooldownButton = screen.getByRole("button", { name: /resend in/i });
|
||||
expect(cooldownButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows success message after resend', async () => {
|
||||
it("shows success message after resend", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -441,14 +477,14 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('counts down timer', async () => {
|
||||
it("counts down timer", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -457,25 +493,30 @@ describe('VerifyEmail', () => {
|
||||
|
||||
// With shouldAdvanceTime: true, the timer will automatically count down
|
||||
// Wait for the countdown to show a lower value
|
||||
await waitFor(() => {
|
||||
// Timer should have counted down from 60s to something less
|
||||
const resendText = screen.getByRole('button', { name: /resend in \d+s/i }).textContent;
|
||||
expect(resendText).toMatch(/Resend in [0-5][0-9]s/);
|
||||
}, { timeout: 3000 });
|
||||
await waitFor(
|
||||
() => {
|
||||
// Timer should have counted down from 60s to something less
|
||||
const resendText = screen.getByRole("button", {
|
||||
name: /resend in \d+s/i,
|
||||
}).textContent;
|
||||
expect(resendText).toMatch(/Resend in [0-5][0-9]s/);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
});
|
||||
|
||||
it('handles resend error for already verified', async () => {
|
||||
it("handles resend error for already verified", async () => {
|
||||
mockedResendVerification.mockRejectedValue({
|
||||
response: { data: { code: 'ALREADY_VERIFIED' } },
|
||||
response: { data: { code: "ALREADY_VERIFIED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -483,7 +524,7 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('handles rate limit error (429)', async () => {
|
||||
it("handles rate limit error (429)", async () => {
|
||||
mockedResendVerification.mockRejectedValue({
|
||||
response: { status: 429 },
|
||||
});
|
||||
@@ -491,39 +532,43 @@ describe('VerifyEmail', () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const resendButton = screen.getByRole('button', { name: /send code/i });
|
||||
const resendButton = screen.getByRole("button", { name: /send code/i });
|
||||
fireEvent.click(resendButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/please wait before requesting/i)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/please wait before requesting/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navigation', () => {
|
||||
it('has return to home link', async () => {
|
||||
describe("Navigation", () => {
|
||||
it("has return to home link", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const homeLink = screen.getByRole('link', { name: /return to home/i });
|
||||
expect(homeLink).toHaveAttribute('href', '/');
|
||||
const homeLink = screen.getByRole("link", { name: /return to home/i });
|
||||
expect(homeLink).toHaveAttribute("href", "/");
|
||||
});
|
||||
|
||||
it('has go to home link on success', async () => {
|
||||
renderVerifyEmail('?token=valid-token');
|
||||
it("has go to home link on success", async () => {
|
||||
renderVerifyEmail("?token=valid-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const homeLink = screen.getByRole('link', { name: /go to home page/i });
|
||||
expect(homeLink).toHaveAttribute('href', '/');
|
||||
const homeLink = screen.getByRole("link", { name: /go to home page/i });
|
||||
expect(homeLink).toHaveAttribute("href", "/");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
* direct uploads, and signed URL generation for private content.
|
||||
*/
|
||||
|
||||
import { vi, type Mocked } from 'vitest';
|
||||
import api from '../../services/api';
|
||||
import { vi, type Mocked } from "vitest";
|
||||
import api from "../../services/api";
|
||||
import {
|
||||
getPublicImageUrl,
|
||||
getPresignedUrl,
|
||||
@@ -16,10 +16,10 @@ import {
|
||||
uploadFile,
|
||||
getSignedUrl,
|
||||
PresignedUrlResponse,
|
||||
} from '../../services/uploadService';
|
||||
} from "../../services/uploadService";
|
||||
|
||||
// Mock the api module
|
||||
vi.mock('../../services/api');
|
||||
vi.mock("../../services/api");
|
||||
|
||||
const mockedApi = api as Mocked<typeof api>;
|
||||
|
||||
@@ -29,16 +29,22 @@ class MockXMLHttpRequest {
|
||||
|
||||
status = 200;
|
||||
readyState = 4;
|
||||
responseText = '';
|
||||
responseText = "";
|
||||
upload = {
|
||||
onprogress: null as ((e: { lengthComputable: boolean; loaded: number; total: number }) => void) | null,
|
||||
onprogress: null as
|
||||
| ((e: {
|
||||
lengthComputable: boolean;
|
||||
loaded: number;
|
||||
total: number;
|
||||
}) => void)
|
||||
| null,
|
||||
};
|
||||
onload: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
|
||||
private headers: Record<string, string> = {};
|
||||
private method = '';
|
||||
private url = '';
|
||||
private method = "";
|
||||
private url = "";
|
||||
|
||||
constructor() {
|
||||
MockXMLHttpRequest.instances.push(this);
|
||||
@@ -58,8 +64,16 @@ class MockXMLHttpRequest {
|
||||
// This allows promises to resolve without real delays
|
||||
Promise.resolve().then(() => {
|
||||
if (this.upload.onprogress) {
|
||||
this.upload.onprogress({ lengthComputable: true, loaded: 50, total: 100 });
|
||||
this.upload.onprogress({ lengthComputable: true, loaded: 100, total: 100 });
|
||||
this.upload.onprogress({
|
||||
lengthComputable: true,
|
||||
loaded: 50,
|
||||
total: 100,
|
||||
});
|
||||
this.upload.onprogress({
|
||||
lengthComputable: true,
|
||||
loaded: 100,
|
||||
total: 100,
|
||||
});
|
||||
}
|
||||
if (this.onload) {
|
||||
this.onload();
|
||||
@@ -84,181 +98,222 @@ class MockXMLHttpRequest {
|
||||
}
|
||||
|
||||
static getLastInstance() {
|
||||
return MockXMLHttpRequest.instances[MockXMLHttpRequest.instances.length - 1];
|
||||
return MockXMLHttpRequest.instances[
|
||||
MockXMLHttpRequest.instances.length - 1
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Store original XMLHttpRequest
|
||||
const originalXMLHttpRequest = global.XMLHttpRequest;
|
||||
|
||||
describe('Upload Service', () => {
|
||||
describe("Upload Service", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
MockXMLHttpRequest.reset();
|
||||
// Reset environment variables using stubEnv for Vitest
|
||||
vi.stubEnv('VITE_S3_BUCKET', 'test-bucket');
|
||||
vi.stubEnv('VITE_AWS_REGION', 'us-east-1');
|
||||
vi.stubEnv("VITE_S3_BUCKET", "test-bucket");
|
||||
vi.stubEnv("VITE_AWS_REGION", "us-east-1");
|
||||
// Mock XMLHttpRequest globally
|
||||
(global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }).XMLHttpRequest = MockXMLHttpRequest;
|
||||
(
|
||||
global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }
|
||||
).XMLHttpRequest = MockXMLHttpRequest;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original XMLHttpRequest
|
||||
(global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }).XMLHttpRequest = originalXMLHttpRequest;
|
||||
(
|
||||
global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }
|
||||
).XMLHttpRequest = originalXMLHttpRequest;
|
||||
});
|
||||
|
||||
describe('getPublicImageUrl', () => {
|
||||
it('should return empty string for null input', () => {
|
||||
expect(getPublicImageUrl(null)).toBe('');
|
||||
describe("getPublicImageUrl", () => {
|
||||
it("should return empty string for null input", () => {
|
||||
expect(getPublicImageUrl(null)).toBe("");
|
||||
});
|
||||
|
||||
it('should return empty string for undefined input', () => {
|
||||
expect(getPublicImageUrl(undefined)).toBe('');
|
||||
it("should return empty string for undefined input", () => {
|
||||
expect(getPublicImageUrl(undefined)).toBe("");
|
||||
});
|
||||
|
||||
it('should return empty string for empty string input', () => {
|
||||
expect(getPublicImageUrl('')).toBe('');
|
||||
it("should return empty string for empty string input", () => {
|
||||
expect(getPublicImageUrl("")).toBe("");
|
||||
});
|
||||
|
||||
it('should return full S3 URL unchanged', () => {
|
||||
const fullUrl = 'https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg';
|
||||
it("should return full S3 URL unchanged", () => {
|
||||
const fullUrl =
|
||||
"https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg";
|
||||
expect(getPublicImageUrl(fullUrl)).toBe(fullUrl);
|
||||
});
|
||||
|
||||
it('should construct S3 URL from key', () => {
|
||||
const key = 'items/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
const expectedUrl = 'https://test-bucket.s3.us-east-1.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
it("should construct S3 URL from key", () => {
|
||||
const key = "items/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
const expectedUrl =
|
||||
"https://test-bucket.s3.us-east-1.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
expect(getPublicImageUrl(key)).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it('should handle profiles folder', () => {
|
||||
const key = 'profiles/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
expect(getPublicImageUrl(key)).toContain('profiles/');
|
||||
it("should handle profiles folder", () => {
|
||||
const key = "profiles/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
expect(getPublicImageUrl(key)).toContain("profiles/");
|
||||
});
|
||||
|
||||
it('should handle forum folder', () => {
|
||||
const key = 'forum/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
expect(getPublicImageUrl(key)).toContain('forum/');
|
||||
it("should handle forum folder", () => {
|
||||
const key = "forum/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
expect(getPublicImageUrl(key)).toContain("forum/");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPresignedUrl', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
describe("getPresignedUrl", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
const mockResponse: PresignedUrlResponse = {
|
||||
uploadUrl: 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc',
|
||||
key: 'items/550e8400-e29b-41d4-a716-446655440000.jpg',
|
||||
uploadUrl:
|
||||
"https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc",
|
||||
key: "items/550e8400-e29b-41d4-a716-446655440000.jpg",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg',
|
||||
publicUrl:
|
||||
"https://bucket.s3.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg",
|
||||
expiresAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
it('should request presigned URL with correct parameters', async () => {
|
||||
it("should request presigned URL with correct parameters", async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
const result = await getPresignedUrl('item', mockFile);
|
||||
const result = await getPresignedUrl("item", mockFile);
|
||||
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
|
||||
uploadType: 'item',
|
||||
contentType: 'image/jpeg',
|
||||
fileName: 'photo.jpg',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
|
||||
uploadType: "item",
|
||||
contentType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
fileSize: mockFile.size,
|
||||
});
|
||||
expect(result).toEqual(mockResponse);
|
||||
});
|
||||
|
||||
it('should handle different upload types', async () => {
|
||||
it("should handle different upload types", async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
await getPresignedUrl('profile', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'profile',
|
||||
}));
|
||||
await getPresignedUrl("profile", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "profile",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('message', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'message',
|
||||
}));
|
||||
await getPresignedUrl("message", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "message",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('forum', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'forum',
|
||||
}));
|
||||
await getPresignedUrl("forum", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "forum",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('condition-check', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'condition-check',
|
||||
}));
|
||||
await getPresignedUrl("condition-check", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "condition-check",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should propagate API errors', async () => {
|
||||
const error = new Error('API error');
|
||||
it("should propagate API errors", async () => {
|
||||
const error = new Error("API error");
|
||||
mockedApi.post.mockRejectedValue(error);
|
||||
|
||||
await expect(getPresignedUrl('item', mockFile)).rejects.toThrow('API error');
|
||||
await expect(getPresignedUrl("item", mockFile)).rejects.toThrow(
|
||||
"API error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPresignedUrls', () => {
|
||||
describe("getPresignedUrls", () => {
|
||||
const mockFiles = [
|
||||
new File(['test1'], 'photo1.jpg', { type: 'image/jpeg' }),
|
||||
new File(['test2'], 'photo2.png', { type: 'image/png' }),
|
||||
new File(["test1"], "photo1.jpg", { type: "image/jpeg" }),
|
||||
new File(["test2"], "photo2.png", { type: "image/png" }),
|
||||
];
|
||||
|
||||
const mockResponses: PresignedUrlResponse[] = [
|
||||
{
|
||||
uploadUrl: 'https://presigned-url1.s3.amazonaws.com',
|
||||
key: 'items/uuid1.jpg',
|
||||
uploadUrl: "https://presigned-url1.s3.amazonaws.com",
|
||||
key: "items/uuid1.jpg",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid1.jpg',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid1.jpg",
|
||||
expiresAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
uploadUrl: 'https://presigned-url2.s3.amazonaws.com',
|
||||
key: 'items/uuid2.png',
|
||||
uploadUrl: "https://presigned-url2.s3.amazonaws.com",
|
||||
key: "items/uuid2.png",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid2.png',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid2.png",
|
||||
expiresAt: new Date().toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
it('should request batch presigned URLs', async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: { uploads: mockResponses, baseKey: 'base-key' } });
|
||||
it("should request batch presigned URLs", async () => {
|
||||
mockedApi.post.mockResolvedValue({
|
||||
data: { uploads: mockResponses, baseKey: "base-key" },
|
||||
});
|
||||
|
||||
const result = await getPresignedUrls('item', mockFiles);
|
||||
const result = await getPresignedUrls("item", mockFiles);
|
||||
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign-batch', {
|
||||
uploadType: 'item',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign-batch", {
|
||||
uploadType: "item",
|
||||
files: [
|
||||
{ contentType: 'image/jpeg', fileName: 'photo1.jpg', fileSize: mockFiles[0].size },
|
||||
{ contentType: 'image/png', fileName: 'photo2.png', fileSize: mockFiles[1].size },
|
||||
{
|
||||
contentType: "image/jpeg",
|
||||
fileName: "photo1.jpg",
|
||||
fileSize: mockFiles[0].size,
|
||||
},
|
||||
{
|
||||
contentType: "image/png",
|
||||
fileName: "photo2.png",
|
||||
fileSize: mockFiles[1].size,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result).toEqual({ uploads: mockResponses, baseKey: 'base-key' });
|
||||
expect(result).toEqual({ uploads: mockResponses, baseKey: "base-key" });
|
||||
});
|
||||
|
||||
it('should handle empty file array', async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: { uploads: [], baseKey: undefined } });
|
||||
it("should handle empty file array", async () => {
|
||||
mockedApi.post.mockResolvedValue({
|
||||
data: { uploads: [], baseKey: undefined },
|
||||
});
|
||||
|
||||
const result = await getPresignedUrls('item', []);
|
||||
const result = await getPresignedUrls("item", []);
|
||||
|
||||
expect(result).toEqual({ uploads: [], baseKey: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadToS3', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
const mockUploadUrl = 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc';
|
||||
describe("uploadToS3", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
const mockUploadUrl =
|
||||
"https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc";
|
||||
|
||||
it('should upload file successfully', async () => {
|
||||
it("should upload file successfully", async () => {
|
||||
await uploadToS3(mockFile, mockUploadUrl);
|
||||
|
||||
const instance = MockXMLHttpRequest.getLastInstance();
|
||||
expect(instance.getMethod()).toBe('PUT');
|
||||
expect(instance.getMethod()).toBe("PUT");
|
||||
expect(instance.getUrl()).toBe(mockUploadUrl);
|
||||
expect(instance.getHeaders()['Content-Type']).toBe('image/jpeg');
|
||||
expect(instance.getHeaders()["Content-Type"]).toBe("image/jpeg");
|
||||
});
|
||||
|
||||
it('should call onProgress callback during upload', async () => {
|
||||
it("should call onProgress callback during upload", async () => {
|
||||
const onProgress = vi.fn();
|
||||
|
||||
await uploadToS3(mockFile, mockUploadUrl, { onProgress });
|
||||
@@ -269,37 +324,37 @@ describe('Upload Service', () => {
|
||||
expect(onProgress).toHaveBeenCalledWith(expect.any(Number));
|
||||
});
|
||||
|
||||
it('should export uploadToS3 function with correct signature', () => {
|
||||
expect(typeof uploadToS3).toBe('function');
|
||||
it("should export uploadToS3 function with correct signature", () => {
|
||||
expect(typeof uploadToS3).toBe("function");
|
||||
// Function accepts file, url, and optional options
|
||||
expect(uploadToS3.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('should set correct content-type header', async () => {
|
||||
const pngFile = new File(['test'], 'image.png', { type: 'image/png' });
|
||||
it("should set correct content-type header", async () => {
|
||||
const pngFile = new File(["test"], "image.png", { type: "image/png" });
|
||||
await uploadToS3(pngFile, mockUploadUrl);
|
||||
|
||||
const instance = MockXMLHttpRequest.getLastInstance();
|
||||
expect(instance.getHeaders()['Content-Type']).toBe('image/png');
|
||||
expect(instance.getHeaders()["Content-Type"]).toBe("image/png");
|
||||
});
|
||||
});
|
||||
|
||||
describe('confirmUploads', () => {
|
||||
it('should confirm uploaded keys', async () => {
|
||||
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
|
||||
describe("confirmUploads", () => {
|
||||
it("should confirm uploaded keys", async () => {
|
||||
const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
|
||||
const mockResponse = { confirmed: keys, total: 2 };
|
||||
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
const result = await confirmUploads(keys);
|
||||
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', { keys });
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", { keys });
|
||||
expect(result).toEqual(mockResponse);
|
||||
});
|
||||
|
||||
it('should handle partial confirmation', async () => {
|
||||
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
|
||||
const mockResponse = { confirmed: ['items/uuid1.jpg'], total: 2 };
|
||||
it("should handle partial confirmation", async () => {
|
||||
const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
|
||||
const mockResponse = { confirmed: ["items/uuid1.jpg"], total: 2 };
|
||||
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
@@ -310,17 +365,19 @@ describe('Upload Service', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadFile', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
describe("uploadFile", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
const presignResponse: PresignedUrlResponse = {
|
||||
uploadUrl: 'https://presigned.s3.amazonaws.com/items/uuid.jpg',
|
||||
key: 'items/uuid.jpg',
|
||||
uploadUrl: "https://presigned.s3.amazonaws.com/items/uuid.jpg",
|
||||
key: "items/uuid.jpg",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid.jpg',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid.jpg",
|
||||
expiresAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
it('should complete full upload flow successfully', async () => {
|
||||
it("should complete full upload flow successfully", async () => {
|
||||
// Mock presign response
|
||||
mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
|
||||
// Mock confirm response
|
||||
@@ -328,7 +385,7 @@ describe('Upload Service', () => {
|
||||
data: { confirmed: [presignResponse.key], total: 1 },
|
||||
});
|
||||
|
||||
const result = await uploadFile('item', mockFile);
|
||||
const result = await uploadFile("item", mockFile);
|
||||
|
||||
expect(result).toEqual({
|
||||
key: presignResponse.key,
|
||||
@@ -336,30 +393,32 @@ describe('Upload Service', () => {
|
||||
});
|
||||
|
||||
// Verify presign was called
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
|
||||
uploadType: 'item',
|
||||
contentType: 'image/jpeg',
|
||||
fileName: 'photo.jpg',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
|
||||
uploadType: "item",
|
||||
contentType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
fileSize: mockFile.size,
|
||||
});
|
||||
|
||||
// Verify confirm was called
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', {
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", {
|
||||
keys: [presignResponse.key],
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error when upload verification fails', async () => {
|
||||
it("should throw error when upload verification fails", async () => {
|
||||
mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
|
||||
// Mock confirm returning empty confirmed array
|
||||
mockedApi.post.mockResolvedValueOnce({
|
||||
data: { confirmed: [], total: 1 },
|
||||
});
|
||||
|
||||
await expect(uploadFile('item', mockFile)).rejects.toThrow('Upload verification failed');
|
||||
await expect(uploadFile("item", mockFile)).rejects.toThrow(
|
||||
"Upload verification failed",
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass onProgress to uploadToS3', async () => {
|
||||
it("should pass onProgress to uploadToS3", async () => {
|
||||
const onProgress = vi.fn();
|
||||
|
||||
mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
|
||||
@@ -367,16 +426,16 @@ describe('Upload Service', () => {
|
||||
data: { confirmed: [presignResponse.key], total: 1 },
|
||||
});
|
||||
|
||||
await uploadFile('item', mockFile, { onProgress });
|
||||
await uploadFile("item", mockFile, { onProgress });
|
||||
|
||||
// onProgress should have been called during XHR upload
|
||||
expect(onProgress).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should work with different upload types', async () => {
|
||||
it("should work with different upload types", async () => {
|
||||
const messagePresignResponse = {
|
||||
...presignResponse,
|
||||
key: 'messages/uuid.jpg',
|
||||
key: "messages/uuid.jpg",
|
||||
publicUrl: null, // Messages are private
|
||||
};
|
||||
|
||||
@@ -385,49 +444,54 @@ describe('Upload Service', () => {
|
||||
data: { confirmed: [messagePresignResponse.key], total: 1 },
|
||||
});
|
||||
|
||||
const result = await uploadFile('message', mockFile);
|
||||
const result = await uploadFile("message", mockFile);
|
||||
|
||||
expect(result.key).toBe('messages/uuid.jpg');
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'message',
|
||||
}));
|
||||
expect(result.key).toBe("messages/uuid.jpg");
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "message",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Note: uploadFiles function was removed from uploadService and replaced with uploadImagesWithVariants
|
||||
// Tests for batch uploads would need to be updated to test the new function
|
||||
|
||||
describe('getSignedUrl', () => {
|
||||
it('should request signed URL for private content', async () => {
|
||||
const key = 'messages/uuid.jpg';
|
||||
const signedUrl = 'https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc';
|
||||
describe("getSignedUrl", () => {
|
||||
it("should request signed URL for private content", async () => {
|
||||
const key = "messages/uuid.jpg";
|
||||
const signedUrl =
|
||||
"https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc";
|
||||
|
||||
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
|
||||
|
||||
const result = await getSignedUrl(key);
|
||||
|
||||
expect(mockedApi.get).toHaveBeenCalledWith(`/upload/signed-url/${encodeURIComponent(key)}`);
|
||||
expect(mockedApi.get).toHaveBeenCalledWith(
|
||||
`/upload/signed-url/${encodeURIComponent(key)}`,
|
||||
);
|
||||
expect(result).toBe(signedUrl);
|
||||
});
|
||||
|
||||
it('should encode key in URL', async () => {
|
||||
const key = 'condition-checks/uuid with spaces.jpg';
|
||||
const signedUrl = 'https://bucket.s3.amazonaws.com/signed';
|
||||
it("should encode key in URL", async () => {
|
||||
const key = "condition-checks/uuid with spaces.jpg";
|
||||
const signedUrl = "https://bucket.s3.amazonaws.com/signed";
|
||||
|
||||
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
|
||||
|
||||
await getSignedUrl(key);
|
||||
|
||||
expect(mockedApi.get).toHaveBeenCalledWith(
|
||||
`/upload/signed-url/${encodeURIComponent(key)}`
|
||||
`/upload/signed-url/${encodeURIComponent(key)}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('should propagate API errors', async () => {
|
||||
const error = new Error('Unauthorized');
|
||||
it("should propagate API errors", async () => {
|
||||
const error = new Error("Unauthorized");
|
||||
mockedApi.get.mockRejectedValue(error);
|
||||
|
||||
await expect(getSignedUrl('messages/uuid.jpg')).rejects.toThrow('Unauthorized');
|
||||
await expect(getSignedUrl("messages/uuid.jpg")).rejects.toThrow(
|
||||
"Unauthorized",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ const AlphaGate: React.FC = () => {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/alpha/validate-code`,
|
||||
{ code: fullCode },
|
||||
{ withCredentials: true }
|
||||
{ withCredentials: true },
|
||||
);
|
||||
|
||||
if (response.data.success) {
|
||||
@@ -115,7 +115,7 @@ const AlphaGate: React.FC = () => {
|
||||
<p className="text-center text-muted small mb-0">
|
||||
Have an alpha code? Get started below! <br></br> Want to join?{" "}
|
||||
<a
|
||||
href="mailto:support@villageshare.app?subject=Alpha Access Request"
|
||||
href="mailto:community-support@village-share.com?subject=Alpha Access Request"
|
||||
className="text-decoration-none"
|
||||
style={{ color: "#667eea" }}
|
||||
>
|
||||
|
||||
@@ -77,9 +77,13 @@ const Owning: React.FC = () => {
|
||||
const [itemToDelete, setItemToDelete] = useState<Item | null>(null);
|
||||
const [showPaymentFailedModal, setShowPaymentFailedModal] = useState(false);
|
||||
const [paymentFailedError, setPaymentFailedError] = useState<any>(null);
|
||||
const [paymentFailedRental, setPaymentFailedRental] = useState<Rental | null>(null);
|
||||
const [paymentFailedRental, setPaymentFailedRental] = useState<Rental | null>(
|
||||
null,
|
||||
);
|
||||
const [showAuthRequiredModal, setShowAuthRequiredModal] = useState(false);
|
||||
const [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(null);
|
||||
const [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchListings();
|
||||
@@ -89,7 +93,7 @@ const Owning: React.FC = () => {
|
||||
useEffect(() => {
|
||||
// Only fetch condition checks for rentals that will be displayed (pending/confirmed/active)
|
||||
const displayedRentals = ownerRentals.filter((r) =>
|
||||
["pending", "confirmed", "active"].includes(r.displayStatus || r.status)
|
||||
["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
|
||||
);
|
||||
if (displayedRentals.length > 0) {
|
||||
const rentalIds = displayedRentals.map((r) => r.id);
|
||||
@@ -111,7 +115,7 @@ const Owning: React.FC = () => {
|
||||
|
||||
// Filter items to only show ones owned by current user
|
||||
const myItems = response.data.items.filter(
|
||||
(item: Item) => item.ownerId === user.id
|
||||
(item: Item) => item.ownerId === user.id,
|
||||
);
|
||||
setListings(myItems);
|
||||
} catch (err: any) {
|
||||
@@ -152,8 +156,8 @@ const Owning: React.FC = () => {
|
||||
});
|
||||
setListings(
|
||||
listings.map((i) =>
|
||||
i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i
|
||||
)
|
||||
i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i,
|
||||
),
|
||||
);
|
||||
} catch (err: any) {
|
||||
alert("Failed to update availability");
|
||||
@@ -189,7 +193,8 @@ const Owning: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
const rentalIds = rentalsToFetch.map((r) => r.id);
|
||||
const response = await conditionCheckAPI.getBatchConditionChecks(rentalIds);
|
||||
const response =
|
||||
await conditionCheckAPI.getBatchConditionChecks(rentalIds);
|
||||
setConditionChecks(response.data.conditionChecks || []);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch condition checks:", err);
|
||||
@@ -203,7 +208,7 @@ const Owning: React.FC = () => {
|
||||
setIsProcessingPayment(rentalId);
|
||||
const response = await rentalAPI.updateRentalStatus(
|
||||
rentalId,
|
||||
"confirmed"
|
||||
"confirmed",
|
||||
);
|
||||
|
||||
// Check if payment processing was successful
|
||||
@@ -216,7 +221,6 @@ const Owning: React.FC = () => {
|
||||
}
|
||||
|
||||
fetchOwnerRentals();
|
||||
// Note: fetchAvailableChecks() removed - it will be triggered via ownerRentals useEffect
|
||||
|
||||
// Notify Navbar to update pending count
|
||||
window.dispatchEvent(new CustomEvent("rentalStatusChanged"));
|
||||
@@ -246,7 +250,7 @@ const Owning: React.FC = () => {
|
||||
alert(
|
||||
err.response?.data?.error ||
|
||||
err.response?.data?.details ||
|
||||
"Failed to accept rental request"
|
||||
"Failed to accept rental request",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
@@ -263,8 +267,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the owner rentals list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
setShowDeclineModal(false);
|
||||
setRentalToDecline(null);
|
||||
@@ -279,8 +283,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
|
||||
// Close the return status modal
|
||||
@@ -306,8 +310,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the owner rentals list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
setShowCancelModal(false);
|
||||
setRentalToCancel(null);
|
||||
@@ -321,7 +325,7 @@ const Owning: React.FC = () => {
|
||||
const handleConditionCheckSuccess = () => {
|
||||
// Refetch condition checks for displayed rentals
|
||||
const displayedRentals = ownerRentals.filter((r) =>
|
||||
["pending", "confirmed", "active"].includes(r.displayStatus || r.status)
|
||||
["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
|
||||
);
|
||||
const rentalIds = displayedRentals.map((r) => r.id);
|
||||
fetchAvailableChecks(rentalIds);
|
||||
@@ -337,7 +341,7 @@ const Owning: React.FC = () => {
|
||||
if (!Array.isArray(availableChecks)) return [];
|
||||
return availableChecks.filter(
|
||||
(check) =>
|
||||
check.rentalId === rentalId && check.checkType === "pre_rental_owner" // Only pre-rental; post-rental is in return modal
|
||||
check.rentalId === rentalId && check.checkType === "pre_rental_owner", // Only pre-rental; post-rental is in return modal
|
||||
);
|
||||
};
|
||||
|
||||
@@ -349,7 +353,9 @@ const Owning: React.FC = () => {
|
||||
// Filter owner rentals - exclude cancelled (shown in Rental History)
|
||||
// Use displayStatus for filtering/sorting as it includes computed "active" status
|
||||
const allOwnerRentals = ownerRentals
|
||||
.filter((r) => ["pending", "confirmed", "active"].includes(r.displayStatus || r.status))
|
||||
.filter((r) =>
|
||||
["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
|
||||
)
|
||||
.sort((a, b) => {
|
||||
const statusOrder = { pending: 0, confirmed: 1, active: 2 };
|
||||
const aStatus = a.displayStatus || a.status;
|
||||
@@ -396,14 +402,20 @@ const Owning: React.FC = () => {
|
||||
{rental.item?.imageFilenames &&
|
||||
rental.item.imageFilenames[0] && (
|
||||
<img
|
||||
src={getImageUrl(rental.item.imageFilenames[0], 'thumbnail')}
|
||||
src={getImageUrl(
|
||||
rental.item.imageFilenames[0],
|
||||
"thumbnail",
|
||||
)}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
onError={(e) => {
|
||||
const target = e.currentTarget;
|
||||
if (!target.dataset.fallback && rental.item) {
|
||||
target.dataset.fallback = 'true';
|
||||
target.src = getImageUrl(rental.item.imageFilenames[0], 'original');
|
||||
target.dataset.fallback = "true";
|
||||
target.src = getImageUrl(
|
||||
rental.item.imageFilenames[0],
|
||||
"original",
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
@@ -435,14 +447,18 @@ const Owning: React.FC = () => {
|
||||
className={`badge ${
|
||||
(rental.displayStatus || rental.status) === "active"
|
||||
? "bg-success"
|
||||
: (rental.displayStatus || rental.status) === "pending"
|
||||
? "bg-warning"
|
||||
: (rental.displayStatus || rental.status) === "confirmed"
|
||||
? "bg-info"
|
||||
: "bg-danger"
|
||||
: (rental.displayStatus || rental.status) ===
|
||||
"pending"
|
||||
? "bg-warning"
|
||||
: (rental.displayStatus || rental.status) ===
|
||||
"confirmed"
|
||||
? "bg-info"
|
||||
: "bg-danger"
|
||||
}`}
|
||||
>
|
||||
{(rental.displayStatus || rental.status).charAt(0).toUpperCase() +
|
||||
{(rental.displayStatus || rental.status)
|
||||
.charAt(0)
|
||||
.toUpperCase() +
|
||||
(rental.displayStatus || rental.status).slice(1)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -478,7 +494,7 @@ const Owning: React.FC = () => {
|
||||
<small className="d-block text-muted mt-1">
|
||||
Processed:{" "}
|
||||
{new Date(
|
||||
rental.refundProcessedAt
|
||||
rental.refundProcessedAt,
|
||||
).toLocaleDateString()}
|
||||
</small>
|
||||
)}
|
||||
@@ -556,7 +572,8 @@ const Owning: React.FC = () => {
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{(rental.displayStatus || rental.status) === "confirmed" && (
|
||||
{(rental.displayStatus || rental.status) ===
|
||||
"confirmed" && (
|
||||
<button
|
||||
className="btn btn-sm btn-outline-danger"
|
||||
onClick={() => handleCancelClick(rental)}
|
||||
@@ -564,7 +581,8 @@ const Owning: React.FC = () => {
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
{(rental.displayStatus || rental.status) === "active" && (
|
||||
{(rental.displayStatus || rental.status) ===
|
||||
"active" && (
|
||||
<button
|
||||
className="btn btn-sm btn-success"
|
||||
onClick={() => handleCompleteClick(rental)}
|
||||
@@ -587,17 +605,17 @@ const Owning: React.FC = () => {
|
||||
{check.checkType === "pre_rental_owner"
|
||||
? "Pre-Rental Condition"
|
||||
: check.checkType === "rental_start_renter"
|
||||
? "Rental Start Condition"
|
||||
: check.checkType === "rental_end_renter"
|
||||
? "Rental End Condition"
|
||||
: "Post-Rental Condition"}
|
||||
? "Rental Start Condition"
|
||||
: check.checkType === "rental_end_renter"
|
||||
? "Rental End Condition"
|
||||
: "Post-Rental Condition"}
|
||||
<small className="text-muted ms-2">
|
||||
{new Date(
|
||||
check.createdAt
|
||||
check.createdAt,
|
||||
).toLocaleDateString()}
|
||||
</small>
|
||||
</button>
|
||||
)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -660,14 +678,17 @@ const Owning: React.FC = () => {
|
||||
>
|
||||
{item.imageFilenames && item.imageFilenames[0] && (
|
||||
<img
|
||||
src={getImageUrl(item.imageFilenames[0], 'thumbnail')}
|
||||
src={getImageUrl(item.imageFilenames[0], "thumbnail")}
|
||||
className="card-img-top"
|
||||
alt={item.name}
|
||||
onError={(e) => {
|
||||
const target = e.currentTarget;
|
||||
if (!target.dataset.fallback) {
|
||||
target.dataset.fallback = 'true';
|
||||
target.src = getImageUrl(item.imageFilenames[0], 'original');
|
||||
target.dataset.fallback = "true";
|
||||
target.src = getImageUrl(
|
||||
item.imageFilenames[0],
|
||||
"original",
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
|
||||
@@ -15,7 +15,7 @@ let failedQueue: Array<{
|
||||
|
||||
const processQueue = (
|
||||
error: AxiosError | null,
|
||||
token: string | null = null
|
||||
token: string | null = null,
|
||||
) => {
|
||||
failedQueue.forEach((prom) => {
|
||||
if (error) {
|
||||
@@ -95,7 +95,7 @@ api.interceptors.response.use(
|
||||
methods: errorData.methods,
|
||||
originalRequest,
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
@@ -128,7 +128,6 @@ api.interceptors.response.use(
|
||||
const errorData = error.response?.data as any;
|
||||
|
||||
// Try to refresh for token errors
|
||||
// Note: We can't check refresh token from JS (httpOnly cookies)
|
||||
// The backend will determine if refresh is possible
|
||||
if (
|
||||
(errorData?.code === "TOKEN_EXPIRED" ||
|
||||
@@ -167,7 +166,7 @@ api.interceptors.response.use(
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const authAPI = {
|
||||
@@ -279,7 +278,7 @@ export const rentalAPI = {
|
||||
// Return status marking
|
||||
markReturn: (
|
||||
id: string,
|
||||
data: { status: string; actualReturnDateTime?: string }
|
||||
data: { status: string; actualReturnDateTime?: string },
|
||||
) => api.post(`/rentals/${id}/mark-return`, data),
|
||||
reportDamage: (id: string, data: any) =>
|
||||
api.post(`/rentals/${id}/report-damage`, data),
|
||||
@@ -338,7 +337,7 @@ export const forumAPI = {
|
||||
content: string;
|
||||
parentId?: string;
|
||||
imageFilenames?: string[];
|
||||
}
|
||||
},
|
||||
) => api.post(`/forum/posts/${postId}/comments`, data),
|
||||
updateComment: (commentId: string, data: any) =>
|
||||
api.put(`/forum/comments/${commentId}`, data),
|
||||
@@ -388,7 +387,7 @@ export const mapsAPI = {
|
||||
export const conditionCheckAPI = {
|
||||
submitConditionCheck: (
|
||||
rentalId: string,
|
||||
data: { checkType: string; imageFilenames: string[]; notes?: string }
|
||||
data: { checkType: string; imageFilenames: string[]; notes?: string },
|
||||
) => api.post(`/condition-checks/${rentalId}`, data),
|
||||
getBatchConditionChecks: (rentalIds: string[]) =>
|
||||
api.get(`/condition-checks/batch`, {
|
||||
|
||||
Reference in New Issue
Block a user