chore: codify React component style

This commit is contained in:
2026-08-25 15:33:20 +03:00
parent 268acdf2e1
commit d10e1dd182
65 changed files with 711 additions and 365 deletions
+16 -9
View File
@@ -1,4 +1,5 @@
import { Loader } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { lazy, Suspense } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
@@ -40,11 +41,14 @@ const ProtectedLayout = lazy(async () => {
return { default: ProtectedLayout };
});
function LazyPage({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<Loader />}>{children}</Suspense>;
}
const LazyPage: FC<PropsWithChildren> = (props) => {
const { children } = props;
function Protected({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<Loader />}>{children}</Suspense>;
};
const Protected: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
const location = useLocation();
if (!ready) return null;
@@ -57,15 +61,16 @@ function Protected({ children }: { children: React.ReactNode }) {
replace
/>
);
}
};
function Public({ children }: { children: React.ReactNode }) {
const Public: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
if (!ready) return null;
return user ? <Navigate to="/accounts" replace /> : children;
}
};
export function AppRoutes() {
const AppRoutes: FC = () => {
return (
<Routes>
<Route path="/" element={<Navigate to="/accounts" replace />} />
@@ -149,4 +154,6 @@ export function AppRoutes() {
/>
</Routes>
);
}
};
export { AppRoutes };
+5 -2
View File
@@ -1,6 +1,9 @@
import type { FC } from "react";
import { AppBreadcrumbs } from "@/app/ui";
import { AppShell } from "@/shared/ui";
export function ProtectedLayout() {
const ProtectedLayout: FC = () => {
return <AppShell contentAboveOutlet={<AppBreadcrumbs />} />;
}
};
export { ProtectedLayout };
+11 -6
View File
@@ -1,5 +1,6 @@
import { MantineProvider } from "@mantine/core";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import type { FC } from "react";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RouteErrorBoundary } from "./RouteErrorBoundary";
@@ -9,10 +10,11 @@ vi.mock("@/features/auth", () => ({
useAuth: () => ({ user: authenticated ? {} : null }),
}));
function ThrowingRoute(): never {
const ThrowingRoute: FC = () => {
throw new Error("test route failure");
}
function HealthyRoute() {
};
const HealthyRoute: FC = () => {
return (
<div>
{useLocation().pathname === "/healthy" ? (
@@ -22,9 +24,11 @@ function HealthyRoute() {
)}
</div>
);
}
function RouteHarness() {
};
const RouteHarness: FC = () => {
const navigate = useNavigate();
return (
<>
<button type="button" onClick={() => navigate("/healthy")}>
@@ -35,7 +39,8 @@ function RouteHarness() {
</RouteErrorBoundary>
</>
);
}
};
function renderBoundary(path: string) {
return render(
<MantineProvider>
+19 -12
View File
@@ -1,24 +1,29 @@
import { Button, Stack, Text, Title } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { Component } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
type Props = {
children: React.ReactNode;
type BoundaryProps = PropsWithChildren<{
routeKey: string;
authenticated: boolean;
}>;
type RouteErrorFallbackProps = {
authenticated: boolean;
};
type State = { hasError: boolean };
class Boundary extends Component<Props, State> {
class Boundary extends Component<BoundaryProps, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
componentDidUpdate(previousProps: Props) {
componentDidUpdate(previousProps: BoundaryProps) {
if (previousProps.routeKey !== this.props.routeKey && this.state.hasError) {
this.setState({ hasError: false });
}
@@ -32,9 +37,11 @@ class Boundary extends Component<Props, State> {
}
}
function RouteErrorFallback({ authenticated }: { authenticated: boolean }) {
const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
const { authenticated } = props;
const { t } = useTranslation();
const to = authenticated ? "/accounts" : "/login";
return (
<Stack>
<Title order={1}>{t("routeError.title")}</Title>
@@ -44,18 +51,18 @@ function RouteErrorFallback({ authenticated }: { authenticated: boolean }) {
</Button>
</Stack>
);
}
};
export function RouteErrorBoundary({
children,
}: {
children: React.ReactNode;
}) {
const RouteErrorBoundary: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { pathname, search } = useLocation();
const { user } = useAuth();
return (
<Boundary authenticated={Boolean(user)} routeKey={`${pathname}${search}`}>
{children}
</Boundary>
);
}
};
export { RouteErrorBoundary };
+3 -1
View File
@@ -1,6 +1,6 @@
import { createTheme } from "@mantine/core";
export const theme = createTheme({
const theme = createTheme({
primaryColor: "blue",
defaultRadius: "md",
fontFamily:
@@ -20,3 +20,5 @@ export const theme = createTheme({
],
},
});
export { theme };
+5 -2
View File
@@ -1,5 +1,6 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { FC } from "react";
import { BrowserRouter } from "react-router";
import { AppRoutes, RouteErrorBoundary } from "@/app/routes";
import { theme } from "@/app/theme";
@@ -9,7 +10,7 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { refetchOnWindowFocus: false } },
});
export function App() {
const App: FC = () => {
return (
<MantineProvider theme={theme} forceColorScheme="light">
<QueryClientProvider client={queryClient}>
@@ -23,4 +24,6 @@ export function App() {
</QueryClientProvider>
</MantineProvider>
);
}
};
export { App };
+23 -14
View File
@@ -1,11 +1,24 @@
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link, useMatch } from "react-router";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
type Crumb = { label: string; to?: string };
function BreadcrumbTrail({ items }: { items: Crumb[] }) {
type BreadcrumbTrailProps = {
items: Crumb[];
};
type AccountBreadcrumbsProps = {
accountId: string;
events: boolean;
operations: boolean;
};
const BreadcrumbTrail: FC<BreadcrumbTrailProps> = (props) => {
const { items } = props;
const { t } = useTranslation();
return (
<nav
aria-label={t("breadcrumbs.label")}
@@ -33,23 +46,17 @@ function BreadcrumbTrail({ items }: { items: Crumb[] }) {
))}
</nav>
);
}
};
function AccountBreadcrumbs({
accountId,
events,
operations,
}: {
accountId: string;
events: boolean;
operations: boolean;
}) {
const AccountBreadcrumbs: FC<AccountBreadcrumbsProps> = (props) => {
const { accountId, events, operations } = props;
const { data: accounts } = useBrokerageAccounts();
const { t } = useTranslation();
const accountName =
accounts?.find((account) => account.id === accountId)?.name ??
t("breadcrumbs.accountFallback");
const accountPath = `/accounts/${accountId}`;
return (
<BreadcrumbTrail
items={
@@ -72,9 +79,9 @@ function AccountBreadcrumbs({
}
/>
);
}
};
export function AppBreadcrumbs() {
const AppBreadcrumbs: FC = () => {
const { t } = useTranslation();
const accountOperations = useMatch({
path: "/accounts/:accountId/operations",
@@ -117,4 +124,6 @@ export function AppBreadcrumbs() {
if (settings)
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} />;
return null;
}
};
export { AppBreadcrumbs };
@@ -1,7 +1,7 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import {
@@ -25,11 +25,15 @@ describe("useBrokerageOperations", () => {
}),
).toEqual({ categories: ["income", "tax"], cursor: "next" });
const client = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
};
const { result } = renderHook(
() => useBrokerageOperations("account-1", { limit: 5 }),
@@ -4,14 +4,14 @@ import type { paths } from "@/shared/api/generated/schema";
type OperationsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/operations"]["get"];
export type BrokerageOperation =
type BrokerageOperation =
OperationsEndpoint["responses"][200]["content"]["application/json"]["items"][number];
type BrokerageOperationsQuery = NonNullable<
OperationsEndpoint["parameters"]["query"]
>;
export type OperationCategory = BrokerageOperation["category"];
type OperationCategory = BrokerageOperation["category"];
export const operationCategories = [
const operationCategories = [
"trade",
"income",
"tax",
@@ -20,9 +20,7 @@ export const operationCategories = [
"other",
] as const satisfies readonly OperationCategory[];
export function brokerageOperationsQueryParams(
query: BrokerageOperationsQuery,
) {
function brokerageOperationsQueryParams(query: BrokerageOperationsQuery) {
return {
...(query.from ? { from: query.from } : {}),
...(query.to ? { to: query.to } : {}),
@@ -34,7 +32,7 @@ export function brokerageOperationsQueryParams(
};
}
export function useBrokerageOperations(
function useBrokerageOperations(
accountId: string | undefined,
query: BrokerageOperationsQuery = {},
) {
@@ -50,3 +48,11 @@ export function useBrokerageOperations(
retry: false,
});
}
export {
type BrokerageOperation,
brokerageOperationsQueryParams,
type OperationCategory,
operationCategories,
useBrokerageOperations,
};
+2 -4
View File
@@ -1,8 +1,6 @@
export type {
BrokerageOperation,
OperationCategory,
} from "./api/useBrokerageOperations";
export {
type BrokerageOperation,
type OperationCategory,
operationCategories,
useBrokerageOperations,
} from "./api/useBrokerageOperations";
@@ -2,7 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
@@ -10,11 +10,17 @@ import { useBrokerageAccounts } from "./useBrokerageAccounts";
function createWrapper() {
const client = new QueryClient();
return ({ children }: { children: ReactNode }) => (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
const TestWrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
};
return TestWrapper;
}
describe("useBrokerageAccounts", () => {
@@ -4,16 +4,21 @@ import type { paths } from "@/shared/api/generated/schema";
const brokerageAccountsQueryOptions = () =>
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
export const brokerageAccountsQueryKey =
brokerageAccountsQueryOptions().queryKey;
const brokerageAccountsQueryKey = brokerageAccountsQueryOptions().queryKey;
export type BrokerageAccount =
type BrokerageAccount =
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
export function useBrokerageAccounts() {
function useBrokerageAccounts() {
return useAuthenticatedQuery({
...brokerageAccountsQueryOptions(),
staleTime: 60_000,
retry: false,
});
}
export {
type BrokerageAccount,
brokerageAccountsQueryKey,
useBrokerageAccounts,
};
+1 -1
View File
@@ -1,5 +1,5 @@
export type { BrokerageAccount } from "./api/useBrokerageAccounts";
export {
type BrokerageAccount,
brokerageAccountsQueryKey,
useBrokerageAccounts,
} from "./api/useBrokerageAccounts";
@@ -1,11 +1,13 @@
import type { BrokerageAccount } from "../api/useBrokerageAccounts";
export function accountTypeKey(type: BrokerageAccount["type"]) {
function accountTypeKey(type: BrokerageAccount["type"]) {
return `accounts.types.${type}` as const;
}
export function errorCode(error: unknown): string | undefined {
function errorCode(error: unknown): string | undefined {
return typeof error === "object" && error !== null && "code" in error
? String(error.code)
: undefined;
}
export { accountTypeKey, errorCode };
@@ -1,4 +1,5 @@
import { Card, SimpleGrid, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { BrokerageAccount } from "../api/useBrokerageAccounts";
@@ -7,8 +8,10 @@ import classes from "./BrokerageAccountList.module.css";
type BrokerageAccountListProps = { accounts: BrokerageAccount[] };
export function BrokerageAccountList({ accounts }: BrokerageAccountListProps) {
const BrokerageAccountList: FC<BrokerageAccountListProps> = (props) => {
const { accounts } = props;
const { t } = useTranslation();
return (
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
{accounts.map((account) => (
@@ -43,4 +46,6 @@ export function BrokerageAccountList({ accounts }: BrokerageAccountListProps) {
))}
</SimpleGrid>
);
}
};
export { BrokerageAccountList };
@@ -2,7 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
import { server } from "@/test/server";
@@ -10,11 +10,17 @@ import { useBrokerageEvents } from "./useBrokerageEvents";
function createWrapper() {
const client = new QueryClient();
return ({ children }: { children: ReactNode }) => (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
const TestWrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
};
return TestWrapper;
}
describe("useBrokerageEvents", () => {
@@ -3,10 +3,10 @@ import type { paths } from "@/shared/api/generated/schema";
type EventsEndpoint =
paths["/api/v1/brokerage-accounts/{accountId}/events"]["get"];
export type BrokerageEvent =
type BrokerageEvent =
EventsEndpoint["responses"][200]["content"]["application/json"]["events"][number];
export function useBrokerageEvents(accountId: string | undefined) {
function useBrokerageEvents(accountId: string | undefined) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions(
"get",
@@ -18,3 +18,5 @@ export function useBrokerageEvents(accountId: string | undefined) {
retry: false,
});
}
export { type BrokerageEvent, useBrokerageEvents };
@@ -1,7 +1,7 @@
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { configureAuthClient } from "@/shared/api";
@@ -17,11 +17,15 @@ describe("usePortfolio", () => {
clear: vi.fn(),
});
const client = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
};
const { result } = renderHook(() => usePortfolio("account-1"), {
wrapper,
+4 -2
View File
@@ -6,10 +6,10 @@ const portfolioQueryPolicy = {
retry: false,
} as const;
export type Portfolio =
type Portfolio =
paths["/api/v1/brokerage-accounts/{accountId}/portfolio"]["get"]["responses"][200]["content"]["application/json"];
export function usePortfolio(accountId: string | undefined) {
function usePortfolio(accountId: string | undefined) {
return useAuthenticatedQuery({
...apiQueryClient.queryOptions(
"get",
@@ -20,3 +20,5 @@ export function usePortfolio(accountId: string | undefined) {
...portfolioQueryPolicy,
});
}
export { type Portfolio, usePortfolio };
+1 -2
View File
@@ -1,5 +1,4 @@
export type { Portfolio } from "./api/usePortfolio";
export { usePortfolio } from "./api/usePortfolio";
export { type Portfolio, usePortfolio } from "./api/usePortfolio";
export {
formatMoney,
formatShare,
+13 -7
View File
@@ -12,12 +12,12 @@ function formatDecimal(value: string): string {
return `${sign}${grouped}${fraction ? `,${fraction}` : ""}`;
}
export function formatMoney(money: Money | null): string {
function formatMoney(money: Money | null): string {
if (!money) return "—";
return `${formatDecimal(money.value)} ${money.currency === "RUB" ? "₽" : money.currency}`;
}
export function formatShare(
function formatShare(
numerator: Money | null,
denominator: Money | null,
): string | null {
@@ -32,7 +32,7 @@ export function formatShare(
return `${rounded} %`;
}
export function formatSnapshotTime(value: string): string {
function formatSnapshotTime(value: string): string {
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
@@ -40,7 +40,7 @@ export function formatSnapshotTime(value: string): string {
}).format(new Date(value));
}
export function portfolioErrorCode(error: unknown): string | undefined {
function portfolioErrorCode(error: unknown): string | undefined {
return typeof error === "object" && error !== null && "code" in error
? String(error.code)
: undefined;
@@ -48,11 +48,17 @@ export function portfolioErrorCode(error: unknown): string | undefined {
const logoSize = 160;
export function instrumentLogoUrl(
logoName: string | null | undefined,
): string | null {
function instrumentLogoUrl(logoName: string | null | undefined): string | null {
const stem = logoName?.trim().replace(/\.png$/i, "");
return stem
? `https://invest-brands.cdn-tinkoff.ru/${stem}x${logoSize}.png`
: null;
}
export {
formatMoney,
formatShare,
formatSnapshotTime,
instrumentLogoUrl,
portfolioErrorCode,
};
+28 -16
View File
@@ -1,7 +1,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { describe, expect, it } from "vitest";
import { apiClient } from "@/shared/api";
import { server } from "@/test/server";
@@ -22,11 +22,15 @@ describe("AuthProvider", () => {
return HttpResponse.json([]);
}),
);
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={new QueryClient()}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={new QueryClient()}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
@@ -39,11 +43,15 @@ describe("AuthProvider", () => {
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
const queryClient = new QueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.ready).toBe(true));
@@ -71,11 +79,15 @@ describe("AuthProvider", () => {
);
const queryClient = new QueryClient();
queryClient.setQueryData(["cached-query"], { value: "stale" });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
};
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() =>
+7 -4
View File
@@ -1,4 +1,5 @@
import { useQueryClient } from "@tanstack/react-query";
import type { FC, PropsWithChildren } from "react";
import {
createContext,
useCallback,
@@ -25,7 +26,6 @@ type AuthContextValue = {
logout: () => Promise<void>;
refresh: () => Promise<boolean>;
};
const AuthContext = createContext<AuthContextValue | null>(null);
async function request(
@@ -40,7 +40,8 @@ async function request(
return data as Authentication;
}
export function AuthProvider({ children }: { children: React.ReactNode }) {
const AuthProvider: FC<PropsWithChildren> = (props) => {
const { children } = props;
const queryClient = useQueryClient();
const [user, setUser] = useState<User | null>(null);
const [accessToken, setAccessToken] = useState<string | null>(null);
@@ -138,10 +139,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
{children}
</AuthContext>
);
}
};
export function useAuth() {
function useAuth() {
const context = useContext(AuthContext);
if (!context) throw new Error("AuthProvider is required");
return context;
}
export { AuthProvider, useAuth };
+9 -7
View File
@@ -1,5 +1,6 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { Alert, Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { FormProvider, type Resolver, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
@@ -50,14 +51,13 @@ const registerSchema = loginSchema.refine(
}),
);
type AuthFormValues = z.input<typeof loginSchema>;
export function AuthForm({
register,
onSubmit,
}: {
type AuthFormProps = {
register?: true;
onSubmit: (email: string, password: string) => Promise<void>;
}) {
};
const AuthForm: FC<AuthFormProps> = (props) => {
const { register, onSubmit } = props;
const { t } = useTranslation();
const schema = register ? registerSchema : loginSchema;
const methods = useForm<AuthFormValues>({
@@ -114,4 +114,6 @@ export function AuthForm({
</form>
</FormProvider>
);
}
};
export { AuthForm };
+6 -2
View File
@@ -1,13 +1,15 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth";
import { AuthForm } from "./AuthForm";
export function LoginForm() {
const LoginForm: FC = () => {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
return (
<AuthForm
onSubmit={async (email, password) => {
@@ -16,4 +18,6 @@ export function LoginForm() {
}}
/>
);
}
};
export { LoginForm };
+6 -2
View File
@@ -1,13 +1,15 @@
import type { FC } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../model/auth";
import { AuthForm } from "./AuthForm";
export function RegisterForm() {
const RegisterForm: FC = () => {
const { register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const returnTo =
(location.state as { returnTo?: string } | null)?.returnTo ?? "/accounts";
return (
<AuthForm
register
@@ -17,4 +19,6 @@ export function RegisterForm() {
}}
/>
);
}
};
export { RegisterForm };
@@ -7,6 +7,7 @@ import {
Text,
} from "@mantine/core";
import { useQueryClient } from "@tanstack/react-query";
import type { FC } from "react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
@@ -24,6 +25,9 @@ import {
type Status =
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
type TbankConnectionSectionLoadedProps = {
status: Status;
};
function errorCode(error: unknown): string | undefined {
return typeof error === "object" && error !== null && "code" in error
@@ -31,15 +35,18 @@ function errorCode(error: unknown): string | undefined {
: undefined;
}
export function TbankConnectionSection() {
const TbankConnectionSection: FC = () => {
const viewModel = useTbankConnectionViewModel();
if (viewModel.state === "loading") return <TbankConnectionLoading />;
if (viewModel.state === "error")
return <TbankConnectionError retry={viewModel.retry} />;
return <TbankConnectionSectionLoaded status={viewModel.status} />;
}
};
function TbankConnectionSectionLoaded({ status }: { status: Status }) {
const TbankConnectionSectionLoaded: FC<TbankConnectionSectionLoadedProps> = (
props,
) => {
const { status } = props;
const { t } = useTranslation();
const queryClient = useQueryClient();
const [deleteOpened, setDeleteOpened] = useState(false);
@@ -151,4 +158,6 @@ function TbankConnectionSectionLoaded({ status }: { status: Status }) {
</Modal>
</Stack>
);
}
};
export { TbankConnectionSection };
@@ -1,12 +1,20 @@
import { Alert, Button, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
export function TbankConnectionLoading() {
type TbankConnectionErrorProps = {
retry: () => void;
};
const TbankConnectionLoading: FC = () => {
const { t } = useTranslation();
return <Text>{t("states.loadingText")}</Text>;
}
export function TbankConnectionError({ retry }: { retry: () => void }) {
};
const TbankConnectionError: FC<TbankConnectionErrorProps> = (props) => {
const { retry } = props;
const { t } = useTranslation();
return (
<Alert color="red" title={t("tbank.statusError")}>
<Button variant="subtle" onClick={retry}>
@@ -14,4 +22,6 @@ export function TbankConnectionError({ retry }: { retry: () => void }) {
</Button>
</Alert>
);
}
};
export { TbankConnectionError, TbankConnectionLoading };
@@ -5,9 +5,9 @@ import { apiQueryClient } from "@/shared/api";
const tbankConnectionQueryOptions = () =>
apiQueryClient.queryOptions("get", "/api/v1/tbank-connection");
export const tbankConnectionQueryKey = tbankConnectionQueryOptions().queryKey;
const tbankConnectionQueryKey = tbankConnectionQueryOptions().queryKey;
export function useTbankConnectionViewModel() {
function useTbankConnectionViewModel() {
const { accessToken } = useAuth();
const status = useQuery({
...tbankConnectionQueryOptions(),
@@ -18,3 +18,5 @@ export function useTbankConnectionViewModel() {
return { state: "error" as const, retry: () => status.refetch() };
return { state: "loaded" as const, status: status.data };
}
export { tbankConnectionQueryKey, useTbankConnectionViewModel };
@@ -1,4 +1,5 @@
import { Button, Card, Group, Stack, Text, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router";
import {
@@ -8,7 +9,19 @@ import {
import { formatMoney } from "@/entities/portfolio";
import { StateView } from "@/shared/ui";
export function AccountEventsPage() {
type AccountEventsPageErrorProps = {
retry: () => void;
};
type AccountEventsPageLoadedProps = {
events: BrokerageEvent[];
};
type AccountEventRowProps = {
event: BrokerageEvent;
};
const AccountEventsPage: FC = () => {
const { accountId } = useParams();
const events = useBrokerageEvents(accountId);
if (events.isLoading) return <AccountEventsPageLoading />;
@@ -17,10 +30,11 @@ export function AccountEventsPage() {
if (!events.data) return <AccountEventsPageLoading />;
if (!events.data.events.length) return <AccountEventsPageEmpty />;
return <AccountEventsPageLoaded events={events.data.events} />;
}
};
function AccountEventsPageLoading() {
const AccountEventsPageLoading: FC = () => {
const { t } = useTranslation();
return (
<StateView
loading
@@ -28,10 +42,12 @@ function AccountEventsPageLoading() {
text={t("states.loadingText")}
/>
);
}
};
function AccountEventsPageError({ retry }: { retry: () => void }) {
const AccountEventsPageError: FC<AccountEventsPageErrorProps> = (props) => {
const { retry } = props;
const { t } = useTranslation();
return (
<StateView
error
@@ -40,10 +56,11 @@ function AccountEventsPageError({ retry }: { retry: () => void }) {
action={<Button onClick={retry}>{t("events.retry")}</Button>}
/>
);
}
};
function AccountEventsPageEmpty() {
const AccountEventsPageEmpty: FC = () => {
const { t } = useTranslation();
return (
<Stack maw={960} gap="lg">
<Title order={1}>{t("events.title")}</Title>
@@ -51,10 +68,12 @@ function AccountEventsPageEmpty() {
<StateView title={t("events.emptyTitle")} text={t("events.emptyText")} />
</Stack>
);
}
};
function AccountEventsPageLoaded({ events }: { events: BrokerageEvent[] }) {
const AccountEventsPageLoaded: FC<AccountEventsPageLoadedProps> = (props) => {
const { events } = props;
const { t } = useTranslation();
return (
<Stack maw={960} gap="lg">
<Title order={1}>{t("events.title")}</Title>
@@ -67,10 +86,12 @@ function AccountEventsPageLoaded({ events }: { events: BrokerageEvent[] }) {
))}
</Stack>
);
}
};
function AccountEventRow({ event }: { event: BrokerageEvent }) {
const AccountEventRow: FC<AccountEventRowProps> = (props) => {
const { event } = props;
const { t } = useTranslation();
return (
<Card withBorder>
<Group justify="space-between" align="flex-start" wrap="wrap">
@@ -94,7 +115,7 @@ function AccountEventRow({ event }: { event: BrokerageEvent }) {
</Group>
</Card>
);
}
};
function formatCalendarDate(date: string) {
return new Intl.DateTimeFormat("ru-RU", {
@@ -102,3 +123,5 @@ function formatCalendarDate(date: string) {
timeZone: "UTC",
}).format(new Date(`${date}T00:00:00Z`));
}
export { AccountEventsPage };
@@ -8,6 +8,7 @@ import {
TextInput,
Title,
} from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router";
@@ -28,7 +29,11 @@ function dateEnd(value: string) {
return value ? `${value}T23:59:59.999Z` : undefined;
}
export function AccountOperationsPage() {
type OperationRowProps = {
operation: BrokerageOperation;
};
const AccountOperationsPage: FC = () => {
const { accountId } = useParams();
const { t } = useTranslation();
const [from, setFrom] = useState("");
@@ -147,10 +152,12 @@ export function AccountOperationsPage() {
) : null}
</Stack>
);
}
};
export function OperationRow({ operation }: { operation: BrokerageOperation }) {
const OperationRow: FC<OperationRowProps> = (props) => {
const { operation } = props;
const { t } = useTranslation();
return (
<Card withBorder>
<Group justify="space-between" align="flex-start">
@@ -176,4 +183,6 @@ export function OperationRow({ operation }: { operation: BrokerageOperation }) {
</Group>
</Card>
);
}
};
export { AccountOperationsPage, OperationRow };
+5 -3
View File
@@ -1,3 +1,4 @@
import type { FC } from "react";
import {
AccountPageEmpty,
AccountPageError,
@@ -6,7 +7,7 @@ import {
} from "./AccountPage.view";
import { useAccountPageViewModel } from "./AccountPage.vm";
export function AccountPage() {
const AccountPage: FC = () => {
const viewModel = useAccountPageViewModel();
if (viewModel.state === "loading") return <AccountPageLoading />;
if (viewModel.state === "error") return <AccountPageError {...viewModel} />;
@@ -33,11 +34,12 @@ export function AccountPage() {
recentEvents={viewModel.recentEvents}
/>
);
}
};
export {
AccountPage,
AccountPageEmpty,
AccountPageError,
AccountPageLoaded,
AccountPageLoading,
} from "./AccountPage.view";
};
+63 -46
View File
@@ -1,4 +1,5 @@
import { Alert, Button, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { BrokerageAccount } from "@/entities/brokerage-account";
@@ -22,8 +23,34 @@ import {
Section,
} from "./components";
export function AccountPageLoading() {
type AccountPageErrorProps = {
code?: string;
retry: () => void;
};
type AccountPageEmptyProps = {
account?: BrokerageAccount;
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
};
type AccountPageLoadedProps = {
account?: BrokerageAccount;
portfolio: Portfolio;
positionSections: AccountPagePositionSection[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
};
const AccountPageLoading: FC = () => {
const { t } = useTranslation();
return (
<StateView
loading
@@ -31,15 +58,10 @@ export function AccountPageLoading() {
text={t("states.loadingText")}
/>
);
}
};
export function AccountPageError({
code,
retry,
}: {
code?: string;
retry: () => void;
}) {
const AccountPageError: FC<AccountPageErrorProps> = (props) => {
const { code, retry } = props;
const { t } = useTranslation();
if (code === "NOT_FOUND")
return (
@@ -84,24 +106,19 @@ export function AccountPageError({
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
}
};
export function AccountPageEmpty({
account,
refreshing = false,
refreshError = false,
retry,
recentOperations,
recentEvents,
}: {
account?: BrokerageAccount;
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
}) {
const AccountPageEmpty: FC<AccountPageEmptyProps> = (props) => {
const {
account,
refreshing = false,
refreshError = false,
retry,
recentOperations,
recentEvents,
} = props;
const { t } = useTranslation();
return (
<Stack>
<AccountHeading account={account} />
@@ -118,28 +135,21 @@ export function AccountPageEmpty({
<RecentEvents events={recentEvents} />
</Stack>
);
}
};
export function AccountPageLoaded({
account,
portfolio,
positionSections,
refreshing = false,
refreshError = false,
retry,
recentOperations,
recentEvents,
}: {
account?: BrokerageAccount;
portfolio: Portfolio;
positionSections: AccountPagePositionSection[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
recentOperations: AccountPageRecentOperations;
recentEvents: AccountPageRecentEvents;
}) {
const AccountPageLoaded: FC<AccountPageLoadedProps> = (props) => {
const {
account,
portfolio,
positionSections,
refreshing = false,
refreshError = false,
retry,
recentOperations,
recentEvents,
} = props;
const { t } = useTranslation();
return (
<Stack className={classes.page} gap="lg">
<AccountHeading account={account} />
@@ -171,10 +181,17 @@ export function AccountPageLoaded({
<RecentEvents events={recentEvents} />
</Stack>
);
}
};
function positionSectionTitleKey(kind: AccountPagePositionSection["kind"]) {
if (kind === "stocks") return "portfolio.stocks";
if (kind === "bonds") return "portfolio.bonds";
return "portfolio.otherPositions";
}
export {
AccountPageEmpty,
AccountPageError,
AccountPageLoaded,
AccountPageLoading,
};
+5 -3
View File
@@ -2,7 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Portfolio } from "@/entities/portfolio";
@@ -60,7 +60,9 @@ function configureTestAuth() {
});
}
function wrapper({ children }: { children: ReactNode }) {
const wrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<QueryClientProvider client={new QueryClient()}>
<MantineProvider>
@@ -72,7 +74,7 @@ function wrapper({ children }: { children: ReactNode }) {
</MantineProvider>
</QueryClientProvider>
);
}
};
function mockLoadedAccountPage() {
server.use(
+16 -7
View File
@@ -22,20 +22,20 @@ import {
type PositionSectionKind = "stocks" | "bonds" | "other";
type AccountPageReturnTone = "positive" | "negative";
export type AccountPagePosition = Portfolio["positions"][number] & {
type AccountPagePosition = Portfolio["positions"][number] & {
shareText: string | null;
returnText: string | null;
returnTone?: AccountPageReturnTone;
logoSrc: string | null;
};
export type AccountPagePositionSection = {
type AccountPagePositionSection = {
kind: PositionSectionKind;
wide: boolean;
positions: AccountPagePosition[];
};
export type AccountPageRecentOperations =
type AccountPageRecentOperations =
| {
state: "loading" | "error" | "empty";
to: string;
@@ -46,7 +46,7 @@ export type AccountPageRecentOperations =
items: BrokerageOperation[];
};
export type AccountPageRecentEvents =
type AccountPageRecentEvents =
| {
state: "loading" | "error" | "empty";
to: string;
@@ -77,13 +77,13 @@ type AccountPageEmptyViewModel = AccountPageContent & {
state: "empty";
};
export type AccountPageViewModel =
type AccountPageViewModel =
| { state: "loading" }
| { state: "error"; code?: string; retry: () => void }
| AccountPageEmptyViewModel
| AccountPageLoadedViewModel;
export function useAccountPageViewModel(): AccountPageViewModel {
function useAccountPageViewModel(): AccountPageViewModel {
const { accountId } = useParams();
const portfolio = usePortfolio(accountId);
const operations = useBrokerageOperations(accountId, {
@@ -153,7 +153,7 @@ function toRecentEvents(
return { state: "loaded", to, items };
}
export function toAccountPagePositionSections(
function toAccountPagePositionSections(
portfolio: Portfolio,
): AccountPagePositionSection[] {
const denominators = new Map<string, number>();
@@ -221,3 +221,12 @@ function toPosition(
logoSrc: wide ? instrumentLogoUrl(position.logoName) : null,
};
}
export {
type AccountPagePosition,
type AccountPagePositionSection,
type AccountPageRecentEvents,
type AccountPageRecentOperations,
toAccountPagePositionSections,
useAccountPageViewModel,
};
@@ -1,10 +1,17 @@
import { Stack, Text, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { accountTypeKey } from "@/entities/brokerage-account";
export function AccountHeading({ account }: { account?: BrokerageAccount }) {
type AccountHeadingProps = {
account?: BrokerageAccount;
};
const AccountHeading: FC<AccountHeadingProps> = (props) => {
const { account } = props;
const { t } = useTranslation();
return (
<Stack gap={2}>
<Title order={1}>{account?.name ?? t("portfolio.title")}</Title>
@@ -15,4 +22,6 @@ export function AccountHeading({ account }: { account?: BrokerageAccount }) {
) : null}
</Stack>
);
}
};
export { AccountHeading };
@@ -1,13 +1,16 @@
import { Paper, Text } from "@mantine/core";
import type { FC } from "react";
import type { Portfolio } from "@/entities/portfolio";
import { formatMoney } from "@/entities/portfolio";
import classes from "../AccountPage.module.css";
export function CashBalances({
balances,
}: {
type CashBalancesProps = {
balances: Portfolio["cashBalances"];
}) {
};
const CashBalances: FC<CashBalancesProps> = (props) => {
const { balances } = props;
return (
<>
{balances.map((balance) => (
@@ -18,4 +21,6 @@ export function CashBalances({
))}
</>
);
}
};
export { CashBalances };
@@ -1,17 +1,18 @@
import { Alert, Button, Group, Loader, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
export function PortfolioRefreshState({
refreshing,
refreshError,
retry,
}: {
type PortfolioRefreshStateProps = {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
}) {
};
const PortfolioRefreshState: FC<PortfolioRefreshStateProps> = (props) => {
const { refreshing, refreshError, retry } = props;
const { t } = useTranslation();
if (!refreshing && !refreshError) return null;
return (
<>
{refreshing ? (
@@ -34,4 +35,6 @@ export function PortfolioRefreshState({
) : null}
</>
);
}
};
export { PortfolioRefreshState };
@@ -1,13 +1,16 @@
import { Paper, SimpleGrid, Text } from "@mantine/core";
import type { FC } from "react";
import type { Portfolio } from "@/entities/portfolio";
import { formatMoney } from "@/entities/portfolio";
import classes from "../AccountPage.module.css";
export function PortfolioTotals({
totals,
}: {
type PortfolioTotalsProps = {
totals: Portfolio["totalsByCurrency"];
}) {
};
const PortfolioTotals: FC<PortfolioTotalsProps> = (props) => {
const { totals } = props;
return (
<SimpleGrid cols={{ base: 1, sm: 2, md: 3 }}>
{totals.map((total) => (
@@ -22,4 +25,6 @@ export function PortfolioTotals({
))}
</SimpleGrid>
);
}
};
export { PortfolioTotals };
@@ -1,17 +1,18 @@
import { Card, Group, Stack, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { formatMoney } from "@/entities/portfolio";
import classes from "../AccountPage.module.css";
import type { AccountPagePosition } from "../AccountPage.vm";
import { PositionLogo } from "./PositionLogo.view";
export function PositionCard({
position,
wide = false,
}: {
type PositionCardProps = {
position: AccountPagePosition;
wide?: boolean;
}) {
};
const PositionCard: FC<PositionCardProps> = (props) => {
const { position, wide = false } = props;
const { t } = useTranslation();
const returnClass = position.returnTone
? classes[position.returnTone]
@@ -78,4 +79,6 @@ export function PositionCard({
) : null}
</Card>
);
}
};
export { PositionCard };
@@ -1,14 +1,16 @@
import { Avatar } from "@mantine/core";
import type { FC } from "react";
import { useState } from "react";
export function PositionLogo({
src,
label,
}: {
type PositionLogoProps = {
src: string | null;
label: string;
}) {
};
const PositionLogo: FC<PositionLogoProps> = (props) => {
const { src, label } = props;
const [failed, setFailed] = useState(false);
if (src && !failed)
return (
<Avatar
@@ -24,4 +26,6 @@ export function PositionLogo({
{(label.trim()[0] ?? "?").toUpperCase()}
</Avatar>
);
}
};
export { PositionLogo };
@@ -1,15 +1,17 @@
import { SimpleGrid } from "@mantine/core";
import type { FC } from "react";
import type { AccountPagePositionSection } from "../AccountPage.vm";
import { PositionCard } from "./PositionCard.view";
import { Section } from "./Section.view";
export function PositionSection({
title,
section,
}: {
type PositionSectionProps = {
title: string;
section: AccountPagePositionSection;
}) {
};
const PositionSection: FC<PositionSectionProps> = (props) => {
const { title, section } = props;
return (
<Section title={title}>
<SimpleGrid cols={section.wide ? 1 : { base: 1, sm: 2, md: 3 }}>
@@ -23,4 +25,6 @@ export function PositionSection({
</SimpleGrid>
</Section>
);
}
};
export { PositionSection };
@@ -1,4 +1,5 @@
import { Alert, Button, Paper, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { BrokerageEvent } from "@/entities/brokerage-event";
@@ -7,8 +8,18 @@ import classes from "../AccountPage.module.css";
import type { AccountPageRecentEvents } from "../AccountPage.vm";
import { Section } from "./Section.view";
export function RecentEvents({ events }: { events: AccountPageRecentEvents }) {
type RecentEventsProps = {
events: AccountPageRecentEvents;
};
type RecentEventProps = {
event: BrokerageEvent;
};
const RecentEvents: FC<RecentEventsProps> = (props) => {
const { events } = props;
const { t } = useTranslation();
return (
<Section title={t("events.recentTitle")}>
{events.state === "loading" ? (
@@ -33,10 +44,12 @@ export function RecentEvents({ events }: { events: AccountPageRecentEvents }) {
</Button>
</Section>
);
}
};
function RecentEvent({ event }: { event: BrokerageEvent }) {
const RecentEvent: FC<RecentEventProps> = (props) => {
const { event } = props;
const { t } = useTranslation();
return (
<Paper className={classes.cash} withBorder>
<Text>{`${t(`events.type.${event.type}`)} · ${event.displayName}`}</Text>
@@ -47,4 +60,6 @@ function RecentEvent({ event }: { event: BrokerageEvent }) {
</Text>
</Paper>
);
}
};
export { RecentEvents };
@@ -1,4 +1,5 @@
import { Alert, Button, Paper, Text } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { formatMoney } from "@/entities/portfolio";
@@ -6,12 +7,14 @@ import classes from "../AccountPage.module.css";
import type { AccountPageRecentOperations } from "../AccountPage.vm";
import { Section } from "./Section.view";
export function RecentOperations({
operations,
}: {
type RecentOperationsProps = {
operations: AccountPageRecentOperations;
}) {
};
const RecentOperations: FC<RecentOperationsProps> = (props) => {
const { operations } = props;
const { t } = useTranslation();
return (
<Section title={t("ledger.recentTitle")}>
{operations.state === "loading" ? (
@@ -40,4 +43,6 @@ export function RecentOperations({
</Button>
</Section>
);
}
};
export { RecentOperations };
@@ -1,16 +1,19 @@
import { Stack, Title } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
export function Section({
title,
children,
}: {
type SectionProps = PropsWithChildren<{
title: string;
children: React.ReactNode;
}) {
}>;
const Section: FC<SectionProps> = (props) => {
const { title, children } = props;
return (
<Stack gap="sm">
<Title order={2}>{title}</Title>
{children}
</Stack>
);
}
};
export { Section };
+5 -3
View File
@@ -1,3 +1,4 @@
import type { FC } from "react";
import {
AccountsPageEmpty,
AccountsPageError,
@@ -6,7 +7,7 @@ import {
} from "./AccountsPage.view";
import { useAccountsPageViewModel } from "./AccountsPage.vm";
export function AccountsPage() {
const AccountsPage: FC = () => {
const viewModel = useAccountsPageViewModel();
if (viewModel.state === "loading") return <AccountsPageLoading />;
if (viewModel.state === "error") return <AccountsPageError {...viewModel} />;
@@ -26,10 +27,11 @@ export function AccountsPage() {
retry={viewModel.retry}
/>
);
}
};
export {
AccountsPage,
AccountsPageEmpty,
AccountsPageError,
AccountsPageLoading,
} from "./AccountsPage.view";
};
+50 -42
View File
@@ -7,14 +7,40 @@ import {
Text,
Title,
} from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import type { BrokerageAccount } from "@/entities/brokerage-account";
import { BrokerageAccountList } from "@/entities/brokerage-account";
import { StateView } from "@/shared/ui";
export function AccountsPageLoading() {
type AccountsPageErrorProps = {
code?: string;
retry?: () => void;
};
type AccountsPageEmptyProps = {
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
};
type AccountsPageLoadedProps = {
accounts: BrokerageAccount[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
};
type AccountsRefreshStateProps = {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
};
const AccountsPageLoading: FC = () => {
const { t } = useTranslation();
return (
<StateView
loading
@@ -22,15 +48,10 @@ export function AccountsPageLoading() {
text={t("states.loadingText")}
/>
);
}
};
export function AccountsPageError({
code,
retry,
}: {
code?: string;
retry?: () => void;
}) {
const AccountsPageError: FC<AccountsPageErrorProps> = (props) => {
const { code, retry } = props;
const { t } = useTranslation();
const settingsAction = (
<Button component={Link} to="/settings" variant="light">
@@ -77,18 +98,12 @@ export function AccountsPageError({
action={<Button onClick={retry}>{t("accounts.retry")}</Button>}
/>
);
}
};
export function AccountsPageEmpty({
refreshing = false,
refreshError = false,
retry,
}: {
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
}) {
const AccountsPageEmpty: FC<AccountsPageEmptyProps> = (props) => {
const { refreshing = false, refreshError = false, retry } = props;
const { t } = useTranslation();
return (
<Stack>
<AccountsRefreshState
@@ -102,20 +117,12 @@ export function AccountsPageEmpty({
/>
</Stack>
);
}
};
export function AccountsPageLoaded({
accounts,
refreshing = false,
refreshError = false,
retry,
}: {
accounts: BrokerageAccount[];
refreshing?: boolean;
refreshError?: boolean;
retry?: () => void;
}) {
const AccountsPageLoaded: FC<AccountsPageLoadedProps> = (props) => {
const { accounts, refreshing = false, refreshError = false, retry } = props;
const { t } = useTranslation();
return (
<Stack>
<Title order={1}>{t("accounts.title")}</Title>
@@ -127,19 +134,13 @@ export function AccountsPageLoaded({
<BrokerageAccountList accounts={accounts} />
</Stack>
);
}
};
function AccountsRefreshState({
refreshing,
refreshError,
retry,
}: {
refreshing: boolean;
refreshError: boolean;
retry?: () => void;
}) {
const AccountsRefreshState: FC<AccountsRefreshStateProps> = (props) => {
const { refreshing, refreshError, retry } = props;
const { t } = useTranslation();
if (!refreshing && !refreshError) return null;
return (
<>
{refreshing ? (
@@ -162,4 +163,11 @@ function AccountsRefreshState({
) : null}
</>
);
}
};
export {
AccountsPageEmpty,
AccountsPageError,
AccountsPageLoaded,
AccountsPageLoading,
};
+3 -1
View File
@@ -1,6 +1,6 @@
import { errorCode, useBrokerageAccounts } from "@/entities/brokerage-account";
export function useAccountsPageViewModel() {
function useAccountsPageViewModel() {
const accounts = useBrokerageAccounts();
if (!accounts.data) {
if (accounts.isFetching) return { state: "loading" as const };
@@ -26,3 +26,5 @@ export function useAccountsPageViewModel() {
retry: () => accounts.refetch(),
};
}
export { useAccountsPageViewModel };
+6 -2
View File
@@ -1,9 +1,11 @@
import { Paper, Stack, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { LoginForm } from "@/features/auth";
export function LoginPage() {
const LoginPage: FC = () => {
const { t } = useTranslation();
return (
<main className="auth-page">
<Paper className="auth-card" p="xl" radius="lg" withBorder>
@@ -14,4 +16,6 @@ export function LoginPage() {
</Paper>
</main>
);
}
};
export { LoginPage };
+6 -2
View File
@@ -1,10 +1,12 @@
import { Stack, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { Button, StateView } from "@/shared/ui";
export function NotFoundPage() {
const NotFoundPage: FC = () => {
const { t } = useTranslation();
return (
<Stack>
<Title order={1}>{t("notFound.title")}</Title>
@@ -19,4 +21,6 @@ export function NotFoundPage() {
/>
</Stack>
);
}
};
export { NotFoundPage };
+6 -2
View File
@@ -1,9 +1,11 @@
import { Paper, Stack, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { RegisterForm } from "@/features/auth";
export function RegisterPage() {
const RegisterPage: FC = () => {
const { t } = useTranslation();
return (
<main className="auth-page">
<Paper className="auth-card" p="xl" radius="lg" withBorder>
@@ -14,4 +16,6 @@ export function RegisterPage() {
</Paper>
</main>
);
}
};
export { RegisterPage };
+6 -2
View File
@@ -1,13 +1,15 @@
import { Button, Stack, Title } from "@mantine/core";
import type { FC } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router";
import { useAuth } from "@/features/auth";
import { TbankConnectionSection } from "@/features/tbank-connection";
export function SettingsPage() {
const SettingsPage: FC = () => {
const { t } = useTranslation();
const { logout } = useAuth();
const navigate = useNavigate();
return (
<Stack>
<Title order={1}>{t("settings.title")}</Title>
@@ -22,4 +24,6 @@ export function SettingsPage() {
</Button>
</Stack>
);
}
};
export { SettingsPage };
+12 -6
View File
@@ -2,7 +2,7 @@ import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import type { FC, PropsWithChildren } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { server } from "@/test/server";
import { useAuthenticatedQuery } from "./authenticated-query";
@@ -10,11 +10,17 @@ import { apiQueryClient, configureAuthClient } from "./client";
function createWrapper() {
const client = new QueryClient();
return ({ children }: { children: ReactNode }) => (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
const TestWrapper: FC<PropsWithChildren> = (props) => {
const { children } = props;
return (
<MantineProvider>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</MantineProvider>
);
};
return TestWrapper;
}
describe("useAuthenticatedQuery", () => {
+3 -1
View File
@@ -10,7 +10,7 @@ import {
subscribeAuthenticatedSession,
} from "./client";
export function useAuthenticatedQuery<
function useAuthenticatedQuery<
TQueryFnData = unknown,
TError = Error,
TData = TQueryFnData,
@@ -32,3 +32,5 @@ export function useAuthenticatedQuery<
(typeof enabled === "function" ? enabled(query) : (enabled ?? true)),
});
}
export { useAuthenticatedQuery };
+13 -5
View File
@@ -21,16 +21,16 @@ function setAuthenticatedSession(next: boolean) {
for (const listener of authSessionListeners) listener();
}
export function configureAuthClient(handlers: AuthHandlers | null) {
function configureAuthClient(handlers: AuthHandlers | null) {
auth = handlers;
setAuthenticatedSession(Boolean(auth?.accessToken()));
}
export function getAuthenticatedSessionSnapshot() {
function getAuthenticatedSessionSnapshot() {
return hasAuthenticatedSession;
}
export function subscribeAuthenticatedSession(listener: () => void) {
function subscribeAuthenticatedSession(listener: () => void) {
authSessionListeners.add(listener);
return () => authSessionListeners.delete(listener);
}
@@ -71,10 +71,18 @@ async function authenticatedFetch(request: Request): Promise<Response> {
: response;
}
export const apiClient = createClient<paths>({
const apiClient = createClient<paths>({
baseUrl: apiBaseUrl,
credentials: "include",
fetch: authenticatedFetch,
});
export const apiQueryClient = createQueryClient(apiClient);
const apiQueryClient = createQueryClient(apiClient);
export {
apiClient,
apiQueryClient,
configureAuthClient,
getAuthenticatedSessionSnapshot,
subscribeAuthenticatedSession,
};
+3 -1
View File
@@ -1,4 +1,4 @@
export const ru = {
const ru = {
translation: {
appName: "WealthLedger",
navigation: { accounts: "Счета", settings: "Настройки" },
@@ -167,3 +167,5 @@ export const ru = {
},
},
} as const;
export { ru };
+3 -1
View File
@@ -2,8 +2,10 @@ import type { ParseKeys } from "i18next";
import { i18n } from "./i18n";
export function validationMessage(
function validationMessage(
key: ParseKeys,
): (_value: unknown) => { message: string } {
return () => ({ message: i18n.t(key) });
}
export { validationMessage };
+9 -6
View File
@@ -1,13 +1,14 @@
import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import type { ReactNode } from "react";
import type { FC, ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
export function AppShell({
contentAboveOutlet,
}: {
type AppShellProps = {
contentAboveOutlet?: ReactNode;
}) {
};
const AppShell: FC<AppShellProps> = (props) => {
const { contentAboveOutlet } = props;
const { t } = useTranslation();
const { pathname } = useLocation();
const items = [
@@ -52,4 +53,6 @@ export function AppShell({
</nav>
</MantineAppShell>
);
}
};
export { AppShell };
+5 -10
View File
@@ -1,5 +1,5 @@
import { Button, Loader, Paper, Stack, Text, Title } from "@mantine/core";
import type { ReactNode } from "react";
import type { FC, ReactNode } from "react";
type StateViewProps = {
title: string;
@@ -9,13 +9,8 @@ type StateViewProps = {
error?: boolean;
};
export function StateView({
title,
text,
action,
loading = false,
error = false,
}: StateViewProps) {
const StateView: FC<StateViewProps> = (props) => {
const { title, text, action, loading = false, error = false } = props;
const role = loading ? "status" : error ? "alert" : undefined;
return (
@@ -28,6 +23,6 @@ export function StateView({
</Stack>
</Paper>
);
}
};
export { Button };
export { Button, StateView };
+3 -1
View File
@@ -5,7 +5,7 @@ const authentication = {
user: { id: "user-1", email: "user@example.com" },
};
export const handlers = [
const handlers = [
http.post("*/api/v1/auth/register", () => HttpResponse.json(authentication)),
http.post("*/api/v1/auth/login", () => HttpResponse.json(authentication)),
http.post("*/api/v1/auth/refresh", () =>
@@ -53,3 +53,5 @@ export const handlers = [
}),
),
];
export { handlers };
+3 -1
View File
@@ -1,4 +1,6 @@
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);
const server = setupServer(...handlers);
export { server };