Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@kallyas
Copy link
Owner

@kallyas kallyas commented Apr 19, 2025

This pull request introduces extensive test coverage enhancements across multiple modules in the sacco_backend application. It adds new test cases for models, views, and services, focusing on user authentication, ledger entries, loans, and permissions. Additionally, it improves the structure and data validation in existing tests. Below are the key changes grouped by theme:

Authentication Tests

  • Added comprehensive tests for the User, Role, and Permission models, including methods like create_user, create_superuser, and __str__.
  • Enhanced view tests for user registration and login, including response structure validation and additional edge cases like invalid credentials and mismatched passwords.

Ledger Tests

  • Introduced tests for the LedgerEntry model, covering creation, string representation, and account balance validation using LedgerService.
  • Added tests for deposit entry creation, including handling of fees and multiple ledger entries.

Loan Tests

  • Improved test setup for LoanModelTest and LoanServiceTest by adding detailed member attributes (e.g., marital status, employment status). [1] [2]
  • Refactored loan eligibility tests to support synchronous testing and added helper methods for eligibility checks.
  • Enhanced LoanViewsTest with additional test cases for loan creation and updated test data to use Decimal for monetary fields.

General Improvements

  • Standardized test setups across modules by creating reusable roles and members with detailed attributes. [1] [2]
  • Improved test readability and maintainability by replacing hardcoded values with dynamic setups and mock objects.

These changes significantly improve the robustness of the test suite, ensuring better coverage and reliability across the application's core functionalities.

Summary by CodeRabbit

  • New Features

    • Introduced new API modules for authentication, loans, members, and savings, enabling comprehensive backend interaction for user, loan, member, and savings account management.
    • Added a new main application component and entry point, including a loading spinner and route rendering.
    • Added a new HTML entry file and base CSS styles for the frontend.
  • Bug Fixes

    • Enhanced and expanded backend test coverage for authentication, ledger, loans, members, risk management, and transactions, improving reliability and correctness.
  • Chores

    • Updated project dependencies, scripts, and configuration files to switch to Vite, Material UI, and ESLint, streamlining development and build processes.
    • Removed unused Dockerfiles, configuration files, and legacy setup artifacts from the frontend.
  • Refactor

    • Replaced previous UI libraries and frontend code with a new stack based on MUI and Vite, removing old components, routes, and utilities.
  • Documentation

    • Rewrote the frontend README to provide updated setup instructions and ESLint configuration guidance.
  • Style

    • Introduced new CSS for consistent styling across the application.
  • Tests

    • Significantly expanded backend test suites for authentication, loans, members, ledger, risk management, and transactions, increasing test coverage and validation of business logic.

kallyas added 30 commits April 19, 2025 11:37
This commit introduces comprehensive unit tests for the User, Role, and Permission models within the authentication app.

- Added UserModelTest class with tests for user creation (create_user, create_superuser) and the __str__ method.  The `create_user` test now uses `create_user` instead of `create` to properly hash the password.
- Added RoleModelTest class with tests for role creation and the __str__ method.
- Added PermissionModelTest class with tests for permission creation and the __str__ method, including testing the many-to-many relationship with roles.

These tests ensure the models function as expected, covering key functionalities and string representations.
This commit adds comprehensive tests for authentication views,
including user registration, login (successful and failed),
registration with mismatched passwords, and the "me" endpoint.

The tests verify status codes, response structure, and data
integrity to ensure the authentication functionality works as
expected. They cover edge cases and invalid scenarios, improving
the reliability of the authentication process. Relevant models
are User, Role and tests include checking tokens, invalid
credentials and password mismatch during registration.
This commit introduces comprehensive tests for the LedgerEntry model
and related accounting functionalities.  It tests the creation of
LedgerEntry objects, the string representation, and the
`get_account_balance` method in LedgerService.  Additionally, it
includes tests for creating deposit entries using
`LedgerService.create_deposit_entries`, verifying the correct
creation of debit and credit entries for cash, savings, and fees.

The tests cover:
- LedgerEntry creation with DEBIT and CREDIT types
- LedgerEntry string representation
- LedgerService.get_account_balance for different accounts
- LedgerService.create_deposit_entries for deposit transactions and fees.

These tests ensure the accuracy and reliability of the ledger system.
This commit modifies the `setUp` method in `LoanModelTest` to
include the creation of a `Role`, `User` and `Member` instance.
The `User` is created with a `phone_number` and `national_id`.
The `Member` is created with more realistic data, ensuring all
required fields are populated including `membership_number`,
`marital_status`, `employment_status`, `occupation`,
`monthly_income`, `physical_address`, `city`, `district`,
`national_id`, and `membership_type`. This provides a more robust
testing environment for loan model functionalities. The use of
`timezone` was removed as it's not necessary here, and `date` was
imported instead.
This commit refactors the loan service tests to improve reliability
and adds more comprehensive member creation in the setup.

Key changes:

- Added more fields to member creation (marital_status, employment_status,
  occupation, physical_address, city, district, national_id,
  membership_number, membership_type) to reflect real-world scenarios.
- Added `risk_level` to RiskProfile creation.
- Modified `test_check_eligibility` tests to use synchronous mocking
  due to limitations with TestCase and async methods. A helper function
  `_mock_check_eligibility` was introduced for this purpose.
- Mocked the `count` method directly on the filtered Loan queryset instead
  of using `acount` on a MagicMock to simplify the test setup.
- Improved assertions in eligibility tests for clarity.

These changes ensure more realistic test conditions and improve the
testability of the `check_eligibility` function. Includes mocks for
`RiskProfile` and `Loan` models.
This commit enhances the LoanViewsTest to include tests for approving and disbursing loans.

- Adds tests for approving a loan using the 'loans-approve' endpoint.
- Adds tests to ensure that only approved loans can be disbursed via 'loans-disburse' endpoint, and provides a bad request if the loan is pending
- Adds tests for disbursing approved loans using the 'loans-disburse' endpoint.
- Updates the setUp method to create a role and add user details like phone_number and national_id.
- Changes url names to include loans
- Adds more data to the member creation for full member details
- Changes the amounts to Decimal for consistency.

These tests ensure the correct workflow for loan approval and disbursement, enhancing the reliability of the loans feature.
This commit introduces comprehensive tests for the Member model,
including validation of data inputs, string representation, and
creation of related models (NextOfKin, MemberDocument).

The changes include:
- Creation of a Role and User instances with specific fields for
  testing purposes.
- Assertions for member creation, string representation, and field
  values.
- Tests for creating and validating NextOfKin and MemberDocument
  instances linked to a Member.
- Use of Decimal for monthly_income and percentage_share

These enhancements ensure the Member model functions as expected and
correctly handles related data. Keywords: Member, NextOfKin,
MemberDocument, tests, validation, Decimal.
This commit introduces comprehensive tests for the MemberViewSet,
covering member creation, retrieving the logged-in user's member
profile ('me' endpoint), and updating member details.

- Added tests for creating members via the API.
- Added tests for retrieving the logged-in user's member details
  using the 'me' endpoint (get_me_endpoint).
- Added tests for updating member details (occupation, monthly_income).
- Mocked `generate_member_number` to provide a consistent member
  number during testing.
- Added `tearDown` method to restore the original
  `generate_member_number` function.
- Updated setUp to create a user with a role, email, phone_number and national_id
- Fixed member creation test data and url mapping.

These tests ensure the correct functionality of the member management
API endpoints and improve the overall reliability of the application.
This commit introduces comprehensive unit tests for the risk management and fraud detection functionalities.

The changes include:
- Creation of test cases for risk profile creation, risk assessment, and fraud detection.
- Implementation of mock services (`_mock_assess_member_risk`, `_mock_analyze_transaction`) to simulate asynchronous operations synchronously for testing.
- Testing of normal and suspicious transactions to verify fraud alert generation.
- Implementation of risk level determination tests based on credit score using `RiskAssessmentService._determine_risk_level`.
- Added setup and teardown methods for creating test users, members, transactions, and roles.
- Patched async methods `assess_member_risk` and `analyze_transaction` to use synchronous versions.

These tests ensure the reliability and accuracy of the risk management and fraud detection features, covering key scenarios and edge cases.  Relevant models and services involved are RiskProfile, FraudAlert, RiskAssessmentService, FraudDetectionService, and Transaction.
The `fee_amount=fee` assignment has been commented out within the `create_transaction` function in `TransactionService`. This change removes the direct setting of the fee amount during transaction creation.  The removal likely stems from a decision to handle fee calculation or assignment differently, potentially in a separate process or at a later stage. This avoids directly including the fee when creating the transaction record.

This change impacts how transaction records are created and may affect downstream processes that rely on the `fee_amount` field. Further investigation might be required to understand the new fee handling mechanism.
This commit introduces comprehensive unit tests for the transaction
workflow, covering deposit and withdrawal scenarios, including:

- Successful deposit transactions: Verifies balance updates and
  notification sending.
- Successful withdrawal transactions: Verifies balance updates and
  notification sending.
- Withdrawal exceeding balance:  Ensures `ValueError` is raised and
  balance remains unchanged.
- Transactions with fees: Checks that fees are correctly calculated and
  deducted from the savings account balance.

Mocks are used for `NotificationService` and `LedgerService` to isolate
the transaction logic and prevent external dependencies during testing.
The `_generate_reference` and `_calculate_fee` methods are also mocked
for deterministic testing.  Includes setup and teardown for test
environment.

These tests ensure the correctness and reliability of the transaction
processing logic.
This commit applies database migrations, updating the db.sqlite3 file.
The binary diff indicates changes to the database schema, likely
including new tables, columns, or indexes. This update is necessary
to support new features and/or bug fixes implemented in the application.
This commit refactors the LoginPage component to utilize the auth-provider
for handling login functionality. It replaces the previous react-query
mutation with the `login` function from the auth-provider. Also
replaces `useNavigate` with `Link` component for routing to register
and forgot password pages.

Key changes include:
- Removal of react-query `useMutation` and related toast notifications.
- Integration of the `useAuth` hook to access the `login` function and `isLoading` state.
- Addition of `loginError` state and `Alert` component to display login errors.
- Replacing `useNavigate` with the `Link` component.
- Added links to Terms of Service and Privacy Policy.

This change enhances the login process by providing more robust error
handling and a better user experience.
This commit introduces a refresh token mechanism to handle expired access tokens.

- Updates axios config to use env variable VITE_API_URL.
- Implements token storage and retrieval from localStorage.
- Adds request interceptor to include access token in headers.
- Implements response interceptor that intercepts 401 errors, uses the
  refresh token to obtain a new access token, and retries the original
  request. If refresh fails, the user is redirected to the login page (simulated
  by clearing tokens).
- Uses a queue to manage multiple requests failing due to token expiry, ensuring
  each request is retried after the token is refreshed.
- Adds `tokenRefreshApi` to handle token refresh requests in a separate instance
  to avoid infinite loops.
- Introduces `isRefreshing` flag and `failedQueue` to manage concurrent token
  refresh attempts.

This improves user experience by seamlessly refreshing tokens without requiring
the user to manually log in again when their access token expires.
This commit refactors the auth provider to enhance token management and initial authentication check.
Key changes include:

- Implemented initial token check on component mount using useEffect to determine authentication status.
- Modified the getCurrentUser query to only run after the initial authentication check.
- Updated login and register mutations to handle token storage and user data caching upon successful authentication.
- Streamlined error handling in the getCurrentUser query by leveraging API interceptors for 401 errors and token refreshing.
- Ensured logout functionality clears tokens and resets the query cache.
- Renamed AUTH_ONLY_ROUTES to AUTH_RESTRICTED_ROUTES to better reflect its purpose.
- Adjusted the return types of the login, register, and updateProfile mutations to return void,
  since tokens and user data are now handled in the onSuccess callbacks.

These changes improve the overall reliability and efficiency of the authentication process.
This commit introduces the AuthProvider component to wrap the Outlet
component within the App component. This provides authentication context
to all routes rendered by the Outlet, enabling protected routes and
authentication-related features.  This ensures that the authentication
state is available throughout the application.

The AuthProvider is imported from `./providers/auth-provider`.
This commit refactors the `authService` from a simple object literal to a class.
This change improves code organization and maintainability by grouping related
authentication methods within a class structure.

Key changes include:
- Converting `authService` to a class `AuthService`.
- Updating method implementations to use `this` keyword where needed.
- Explicitly defining return types using `Promise<AxiosResponse<T>>`.
- Standardizing request bodies for consistency (e.g., using snake_case).
- Adjusting refreshToken to pass refresh_token in the body.
- Adjusting changePassword to pass old_password and new_password in the body.
- Adjusting resetPassword to pass confirm_password in the body.
- Updating the imports to include the correct types for login credentials, register data, auth response, and user.
This commit refactors the authentication types (User, LoginCredentials,
RegisterData, AuthResponse) to align with recent backend API changes.

Key changes include:
- Updated `User` interface to reflect the new user object structure,
  including `id` (number), `phone_number`, `gender`, `date_of_birth`,
  `national_id`, `is_verified`, and nested `role` object.
- Modified `RegisterData` to include `confirm_password`, `first_name`,
  `last_name`, `phone_number`, `gender`, `date_of_birth`, and `national_id`.
- Moved interfaces to the top and used `export` keyword
This commit modifies the Welcome component to conditionally render navigation links based on user authentication status.

- Added `useAuth` hook to check if a user is authenticated.
- If a user is authenticated, a "Dashboard" link is displayed, redirecting them to their dashboard.
- If no user is authenticated, the "Log In" and "Sign Up" links are displayed as before.

This change improves user experience by providing a more relevant navigation menu based on their authentication state. The `useAuth` hook ensures that the UI reflects the user's login status accurately.
The database file 'sacco_backend/db.sqlite3' has been updated to reflect the latest schema changes. These changes are a result of running database migrations, which likely include new tables, columns, or modified relationships to support new features or enhancements.

The exact schema modifications are not visible directly from the binary diff, but this commit ensures that the database is synchronized with the current application code and its defined data structures.
This commit integrates the `useAuth` hook from the `AuthProvider` to fetch the current user data within the `AppSidebar` component.  It also renames the `NavUser` component to `UserNav` and passes the authenticated user data to it.

Specifically:

- Imported `useAuth` hook from `~/providers/auth-provider`.
- Renamed `NavUser` import to `UserNav`.
- Used `useAuth` to retrieve the `user` object.
- Passed the `user` object from `useAuth` to the `UserNav` component.

These changes allow the sidebar to display dynamic user information based on the authenticated user, improving the user experience.
This commit refactors the `NavUser` component to `UserNav` and
implements navigation using `react-router-dom`.
The component now utilizes `useNavigate` for routing and includes links to
profile, settings, billing, notifications, and help pages within the dropdown.
The logout functionality is now handled via `useAuth` hook.
Helper functions `getInitials` and `formatRole` were also added to handle user's initials and role.
The component also uses a different UI from `lucide-react` and `~/components/ui/button` to make it more consistent.
This commit refactors the authentication provider to include robust token management using local storage and JWT decoding. It introduces token refresh functionality, route protection, and improved user experience.

Key changes:

- Implemented token storage, retrieval, and clearing using `localStorage`.
- Added JWT decoding for token expiry checks.
- Introduced token refresh mechanism using `authService.refreshToken`.
- Integrated route protection logic to redirect users based on authentication status using `PUBLIC_ROUTES` and `AUTH_ONLY_ROUTES`.
- Updated the `AuthContext` to include a `user` property.
- Modified login and registration flows to store tokens and update the query cache.
- Improved error handling and user feedback with toast notifications.
- Added a check in the `AuthProvider` component to ensure it only renders after the initial authentication check has been completed, preventing potential race conditions or UI flickering.
- Removed `AUTH_RESTRICTED_ROUTES` as they were redundant.
- Replaced `Navigate` component with `useNavigate` hook from `react-router-dom`.

The changes enhance security, improve user experience, and provide a more robust authentication solution.
This commit introduces a new interface `AuthTokens` to explicitly define the structure of authentication tokens (access_token and refresh_token). This new interface mirrors the token structure already present in the `AuthResponse` interface.

The purpose of this change is to improve code clarity and maintainability by providing a dedicated type for scenarios where only the token pair is needed, without requiring the full `AuthResponse` object. This enhances type safety and reduces potential confusion when working with authentication tokens throughout the application.
This commit adds the `jwt-decode` package as a dependency. This library will be used to decode JSON Web Tokens (JWTs) on the frontend, allowing us to access and utilize the claims embedded within the tokens.  This is necessary for features like user authentication and authorization, where we need to extract user roles and permissions from the JWT.
This commit adds the `jwt-decode` package as a dependency. This package will be used for decoding JSON Web Tokens (JWTs) on the frontend, allowing us to extract user information and other relevant data stored within the token. This is necessary for implementing authentication and authorization features. The specific version added is 4.0.0.
This commit introduces authentication route guards to protect and manage access to different parts of the application.  It adds three main guards:

- `RequireAuth`: Protects routes for authenticated users, redirecting to /login if not authenticated.  Saves the attempted path in state for redirect after login.
- `PublicOnlyRoute`: Prevents authenticated users from accessing public routes like /login or /register, redirecting to /dashboard.
- `RoleGuard`: Checks if the user has the required role(s) to access a route, redirecting to /unauthorized if not. Saves the attempted path in state.

Also includes:
- `AuthLoadingScreen`: A loading indicator displayed during authentication checks.
- `UnauthorizedPage`: A page displayed when a user attempts to access a route without the necessary permissions.

These guards leverage the `useAuth` hook from the `auth-provider` to determine authentication status and user roles.  The location state is used to save the intended route before redirection, providing a seamless user experience. This change enhances the security and usability of the application by controlling access based on authentication and authorization.
This commit introduces the ProtectedLayout component, which provides a consistent layout for authenticated sections of the application.

The layout includes:
- A sidebar using the `AppSidebar` component for navigation.
- Breadcrumbs for contextual navigation.
- A user navigation component (`UserNav`) displaying user information.
- An `Outlet` for rendering nested routes within the protected area.
- `RequireAuth` component to ensure only authenticated users can access the layout.
- Loading spinner for `Suspense` fallback.

The layout utilizes radix-ui components for visual structure (Breadcrumb, Separator, Sidebar). The `useAuth` hook is used to fetch the current user's information.
This commit introduces `tsconfig.node.json` to configure the TypeScript compiler specifically for the Vite build process. This configuration includes:

- Setting `target` to `ES2022` and `lib` to `ES2023` for modern JavaScript support.
- Using `module: ESNext` and `moduleResolution: bundler` to enable ES module support and optimize for bundling.
- Enabling strict linting rules (`strict`, `noUnusedLocals`, etc.) for improved code quality.
- Including `vite.config.ts` in the compilation context.

This configuration ensures that Vite's server-side code is correctly compiled and optimized.
kallyas added 28 commits April 19, 2025 15:38
This commit introduces the `AuthContext` to manage user authentication state.
It includes:

- `AuthProvider`: A component that provides the authentication context to the application.
- `isAuthenticated`: A state variable to track authentication status.
- `user`: A state variable to store user information.
- `loading`: A state variable to indicate loading state during authentication processes.
- `error`: A state variable to store error messages.
- `login`: A function to handle user login using the `AuthService`.
- `register`: A function to handle user registration using the `AuthService`.
- `logout`: A function to handle user logout using the `AuthService`.
- `useEffect`: Hook to initialize authentication state on component mount, checking for existing tokens and refreshing them if necessary.

The context also handles potential errors during login, registration, and logout, updating the error state accordingly.
This commit introduces the `useAuth` hook. This hook leverages the `useContext` hook from React to access the authentication context (`AuthContext`).

The `useAuth` hook provides a convenient and centralized way for components to access authentication-related data and functions, such as the current user and sign-in/sign-out methods, without needing to directly import and use `useContext` every time.

A check is included to ensure the hook is used within an `AuthProvider`, throwing an error if not, which prevents unexpected behavior and aids in debugging.
This commit introduces the `AuthLayout` component, providing a consistent layout for authentication-related pages (login, register, password reset, etc.).

The layout features:

- A responsive design using `useMediaQuery` to adapt to different screen sizes.
- A left-side panel (hidden on mobile) displaying the SACCO Management System name and a brief description.
- A right-side panel containing the authentication form wrapped in a `Paper` component for visual separation.
- A footer with a copyright notice.
- Utilizes `theme.palette` for consistent styling with the overall application theme.

This component aims to improve the user experience by providing a clear and visually appealing authentication interface.
Keywords: AuthLayout, authentication, layout, responsive, Material UI, useMediaQuery, theme.palette
This commit introduces the DashboardLayout component, which provides a consistent UI structure for the application.

Key changes include:

- Implemented a responsive drawer navigation using MUI components.
- Added menu items for Dashboard, Members, Loans, Savings, and Transactions.
- Implemented user profile menu with options for Profile, Settings, and Logout, utilizing the `useAuth` hook.
- The drawer's open state is managed based on screen size using `useMediaQuery`.
- Navigation is handled using `useNavigate` hook and `navigateTo` function.
- Applied responsive styling for AppBar and main content area.

This layout provides a foundation for the SACCO management system's user interface.
This commit integrates Material UI for styling and introduces React Router for client-side navigation.

- Replaced default React StrictMode setup with a new structure.
- Wrapped the App component with ThemeProvider from Material UI to apply a custom theme.
- Added CssBaseline from Material UI to provide basic styling resets.
- Wrapped the App component with BrowserRouter to enable routing within the application.
- Added AuthProvider to manage authentication context. This provides user authentication functionality.
- Updated imports to align with the new structure and added necessary Material UI and React Router imports.

This change sets the foundation for a more visually appealing and navigable application.
This commit introduces the Login page (`Login.tsx`) with the following:

- Implements a login form with email and password fields using Material UI components.
- Includes form validation for email format and required fields.
- Integrates the `useAuth` hook for handling user authentication.
- Displays error messages from the `useAuth` hook or form validation.
- Implements password visibility toggle.
- Redirects users to the dashboard after successful login.
- Includes links to the "Forgot Password" and "Sign Up" pages.
- Uses `react-router-dom` for navigation and passing state for redirection.
- Adds a loading state using `isSubmitting` to disable the form during login process.
This commit introduces the Register page (`Register.tsx`) which allows users to create new accounts.

Key changes include:

- Implemented a form with fields for first name, last name, email, phone number, gender, date of birth, national ID, password, and confirm password.
- Added client-side validation for all form fields, including email format, password strength (minimum length), phone number format (international format), and password confirmation matching.  The `validateForm` function performs these checks.
- Integrated with the `useAuth` hook to handle user registration via the `register` function.
- Implemented visual feedback for errors and successful registration using MUI's `Alert` component.
- Added password visibility toggle using `Visibility` and `VisibilityOff` icons.
- Implemented loading state during form submission using the `isSubmitting` state variable to prevent multiple submissions.
- Redirects to dashboard after successful registration.

The page uses MUI components for styling and form elements, enhancing the user experience. The `RegisterRequest` type is used to define the structure of the form data.  Error handling and form state management are handled using React's `useState` hook.
This commit introduces the initial implementation of the Dashboard page.
It includes the following features:

- Fetches and displays key metrics such as total members, active loans,
  total savings balance, and outstanding loan portfolio. The data is currently
  mocked but will be integrated with a real API in future commits.
- Implements "Recent Transactions" section displaying a list of recent
  transactions with details like member name, date, type, and amount.
- Implements "Pending Applications" section displaying a list of pending
  applications and a button to review each application.
- Adds "Quick Actions" section providing quick access to common tasks like
  adding a new member, creating a new savings account, applying for a loan,
  and initiating a new transaction using `Button` components.
- Uses `useNavigate` to navigate to different sections of the application
  when clicking "View All" or "Review" buttons.
- Implements loading state with `CircularProgress` while fetching data.
- Implements `formatCurrency` function for formatting currency values in UGX.
- Implements `formatDate` function for formatting dates.
- Implements `getTransactionTypeColor` function to assign a color to a transaction type.
- The dashboard UI is built using Material UI components like `Grid`,
  `Card`, `Paper`, `Typography`, and `Box`.
- Implements responsive layout for different screen sizes.

Keywords: Dashboard, metrics, transactions, applications, quick actions,
Material UI, useNavigate, formatCurrency, formatDate, loading state, API
This commit introduces the ApplyLoan page, enabling users to apply for loans.

Key changes:
- Implemented the ApplyLoan component with tabs for loan type selection and application form.
- Added LoanTypeSelector component to allow users to choose a loan type.
- Integrated LoanApplicationForm component for users to fill in their loan application details.
- Implemented navigation to loan details page after successful form submission (handleSubmitSuccess).
- Added breadcrumbs for easy navigation.
- The loan application form is displayed in the second tab, and it's activated upon selecting the loan type (handleLoanTypeChange function).
This commit introduces the Loan Details page, displaying comprehensive
information about a specific loan. It includes the following features:

- Fetches and displays loan details using `loansApi.getLoan(id)`.
- Implements Approve, Reject, and Disburse actions, updating the UI
  accordingly using `loansApi.approveLoan(id)`, `loansApi.rejectLoan(id, reason)`,
  and `loansApi.disburseLoan(id)`.
- Adds a tabbed interface (Repayment Schedule, Transaction History,
  Documents) for related loan information.  The Repayment Schedule tab
  fetches and displays repayment data using `loansApi.getLoanRepayments(id)`
  and leverages the `RepaymentSchedule` component.
- Implements a Loan Payment Form modal to process loan payments.
- Implements a View Statement button that navigates to the Loan Statement page.
- Implements dialogs for Approve and Reject actions, including a reason
  field for rejections.
- Includes loading indicators and error handling.

Keywords: LoanDetailsPage, loansApi, getLoan, approveLoan, rejectLoan,
disburseLoan, getLoanRepayments, RepaymentSchedule, Loan Payment, Tabs,
Approve Dialog, Reject Dialog.
This commit introduces the LoansList page, providing a comprehensive
interface for managing loan applications. Key features include:

- Implemented loan listing with pagination using DataGrid.
- Added filtering by status, type, and member ID.
- Implemented Approve, Reject, and Disburse actions for loan officers.
- Integrated with loansApi for fetching and updating loan data.
- Added summary cards for quick loan statistics.
- Implemented tab-based filtering for loan statuses (All, Pending, Approved, Active, Completed).
- Added dialogs for loan approval, rejection (with reason), and disbursement.
- Implemented search functionality for loans.
- Display error messages using Alert component.
- Implemented role-based authorization to show approve, reject and disburse actions for ADMIN and LOAN_OFFICER roles

The page enhances loan management efficiency and provides a clear
overview of loan statuses and related actions.
This commit introduces the MembersList page, displaying a list of members with features for searching, pagination, and viewing member details.

Key changes include:
- Implemented a table using Material UI's DataGrid to display member data.
- Added search functionality with debounce to filter members by name, member number, phone.
- Integrated pagination to handle large member datasets, using server-side pagination.
- Included summary cards displaying total, active and unverified members.
- Added actions (View, Edit, Delete) for each member.
- Fetches member data from the membersApi endpoint.
- Displays member verification status.

The page provides a user-friendly interface for managing members.

Keywords: MembersList, DataGrid, pagination, search, memberApi, member, verification, summary cards.
This commit introduces the `PrivateRoute` component to protect routes
requiring authentication.

The component utilizes the `useAuth` hook to check authentication status
and displays a loading indicator (`CircularProgress`) while the auth
state is being determined.  If the user is not authenticated, they are
redirected to the `/login` page, preserving the current location in
the `state` prop of the `Navigate` component, allowing redirection back
after login. This enhances user experience by preventing access to
protected resources without proper authentication.

The `PrivateRoute` component accepts `children` prop to render the
protected content.

Keywords: PrivateRoute, authentication, useAuth, Navigate, loading,
CircularProgress, redirect, login, route protection.
This commit introduces the `PublicRoute` component, which handles
authentication-based routing for public-facing pages.

The component utilizes `useAuth` hook to check authentication status and
`useLocation` to manage redirection after authentication.

- Added: `PublicRoute` component with `restricted` prop.
- Functionality: Redirects authenticated users from restricted public
  pages (e.g., login) to the dashboard or intended route.
- Loading state: Displays a `CircularProgress` indicator while checking
  authentication status (`loading` from `useAuth`).
- Redirection: Uses `<Navigate>` to redirect users.
This commit introduces the main application routes using React Router v6.
It defines both public (authentication) and private (dashboard) routes,
protected by `PublicRoute` and `PrivateRoute` components respectively.

The routes are structured using `DashboardLayout` and `AuthLayout`
components to provide consistent UI across different sections.

Specifically:
- Defined routes for login, register, dashboard, members, loans, and savings.
- Implemented navigation to the login page as the default route.
- Used `<Navigate>` component for redirection.
- Included routes for listing members and loans, applying for loans, and viewing loan details.
- Commented out routes related to forgot password, adding/viewing members, savings accounts and transactions.
- Configured a catch-all route to redirect to the dashboard.

This setup provides a basic routing structure for the application.
This commit introduces the AuthService to manage user authentication.

- Implemented `login` and `register` functions that store access and refresh tokens in cookies upon successful authentication.
- Added `logout` function to remove tokens from cookies, and optionally call authApi logout endpoint.
- Implemented `refreshToken` function to refresh access tokens using refresh tokens stored in cookies.
- Added `getCurrentUser` function to retrieve the currently authenticated user.
- Implemented `isAuthenticated` function to check if the user is authenticated based on the presence of an access token.
- Added `getAccessToken` function to retrieve the access token from cookies.
- Uses js-cookie for cookie management with secure and sameSite attributes.
- Configured token expiry times for access and refresh tokens.
This commit introduces TypeScript interfaces to define the data structures used for authentication in the frontend.

The following interfaces are defined:

- `User`: Represents the structure of a user object, including properties like `id`, `email`, `first_name`, `last_name`, `phone_number`, `national_id`, `is_verified`, and `role`.
- `AuthState`: Defines the structure of the authentication state, including properties like `isAuthenticated`, `user`, `accessToken`, `refreshToken`, `loading`, and `error`.
- `LoginRequest`: Represents the structure of a login request object, including `email` and `password`.
- `LoginResponse`: Represents the structure of a login response object, including `user` and `tokens` (`access_token` and `refresh_token`).
- `RegisterRequest`: Represents the structure of a registration request, including user details and password confirmation.
- `RefreshTokenRequest`:  Specifies the structure for refreshing tokens, containing the `refresh_token`.
- `RefreshTokenResponse`: Defines the structure for a refresh token response, with new `access_token` and `refresh_token`.

These types will improve code maintainability, readability, and reduce potential errors by providing explicit type checking for authentication-related data.
This commit introduces TypeScript interfaces for `Loan`,
`LoanApplication`, and `LoanRepayment` to provide type safety
and improve code maintainability. It also includes request and
response types for loan applications and repayments, enhancing
data structure definition.

Specifically:

- Defined the `Loan` interface with properties like `id`, `reference`,
  `member`, `loan_type`, `amount`, `status`, etc.  Included optional
  fields `member_name` and `member_number` for enhanced member display.
- Defined the `LoanApplication` interface with properties related to
  loan application details.
- Defined the `LoanRepayment` interface with properties related to
  loan repayment schedules.
- Added `LoanApplicationRequest`, `LoanRepaymentRequest`, and
  `LoanEligibilityResponse` interfaces to represent request and
  response structures for related operations.

These types will be used throughout the application to ensure data
consistency and reduce errors when working with loan-related data.
This commit introduces TypeScript interfaces for representing member data,
next of kin information, member documents, and member registration
requests. These interfaces (Member, NextOfKin, MemberDocument,
MemberRegistrationRequest) provide type safety and improve code
readability when working with member-related data throughout the
frontend application. These types are essential for data consistency and
validation when interacting with the backend API.
This commit introduces TypeScript interfaces for savings accounts,
transactions, interest rates, and API request/response structures.

The following interfaces are defined:

- `SavingsAccount`:  Represents a savings account with fields like
   `id`, `member`, `account_number`, `account_type`, `balance`,
   `interest_rate`, `status`, `minimum_balance`, `date_opened`, and
   `last_interest_date`.
- `SavingsTransaction`: Represents a savings transaction with fields
  like `id`, `account`, `transaction_type`, `amount`,
  `balance_after`, `date`, and `reference`.
- `InterestRate`: Defines the structure for interest rate information
  including `account_type`, `minimum_balance`, `rate`, and
  `effective_date`.
- `OpenAccountRequest`: Defines the structure for opening a new
   savings account, including `member_id`, `account_type`, and
   `initial_deposit`.
- `TransactionRequest`: Defines the structure for making a transaction
   on a savings account, including `account_id`, `transaction_type`,
   `amount`, and `payment_method`.
- `AccountBalanceResponse`: Defines the structure for returning account
  balance information including `account_number`, `balance`,
  `available_balance`, `currency`, and `as_of_date`.
- `AccountStatementRequest`: Defines the structure for requesting account
  statement information including `account_id`, `start_date`,
  `end_date`, and `format`.

These types will be used for type-safe interactions with the backend
savings-related API endpoints and within the frontend application.
This commit introduces TypeScript interfaces for handling transaction data within the application.  Specifically, it defines:

- `Transaction`: Represents the structure of a transaction object, including fields like `id`, `transaction_ref`, `member`, `transaction_type`, `amount`, `payment_method`, `status`, and various reference and descriptive fields. It also includes auditing fields. The `transaction_type` and `payment_method` are defined as string literals.

- `TransactionFee`: Defines the structure for transaction fee configuration, including `transaction_type`, `payment_method`, `fixed_amount`, `percentage`, `min_amount`, and `max_amount`.

- `TransactionLimit`: Defines the structure for transaction limits including `transaction_type`, `limit_type`, `amount`, and `member_type`.

- `CreateTransactionRequest`: Defines the structure for requesting the creation of new transactions, containing `member_id`, `transaction_type`, `amount`, `payment_method`, and optional reference fields.

- `TransactionHistoryRequest`: Defines the structure for filtering transaction history data including `member_id`, date ranges, `transaction_type`, `status`, and pagination parameters.

- `TransactionReceiptRequest`: Defines the structure for requesting a transaction receipt in a specific format, using transaction id, and defining the `format`.

These interfaces provide type safety and clarity when working with transaction-related data throughout the frontend application.
This commit configures path aliases in `tsconfig.app.json` to simplify and improve the readability of import statements throughout the project.  This change adds a `baseUrl` and `paths` section to the `compilerOptions` object.  Specific aliases have been added for:

- `@/*` (maps to `src/*`)
- `@api/*` (maps to `src/api/*`)
- `@assets/*` (maps to `src/assets/*`)
- `@components/*` (maps to `src/components/*`)
- `@context/*` (maps to `src/context/*`)
- `@hooks/*` (maps to `src/hooks/*`)
- `@layouts/*` (maps to `src/layouts/*`)
- `@pages/*` (maps to `src/pages/*`)
- `@routes/*` (maps to `src/routes/*`)
- `@services/*` (maps to `src/services/*`)
- `@types/*` (maps to `src/types/*`)
- `@utils/*` (maps to `src/utils/*`)

These aliases allow developers to use shorter, more descriptive import paths, such as `@components/MyComponent` instead of potentially long relative paths like `../../components/MyComponent`.  This improves code maintainability and reduces the risk of import errors when refactoring.  The `baseUrl` is set to the project root. This uses the TypeScript `paths` compiler option.
This commit adds the `@types/js-cookie` package as a dependency.
This package provides TypeScript definitions for the `js-cookie`
library, enabling type-safe interaction with browser cookies within
the application. The `js-cookie` library will likely be used to
store and retrieve user preferences or session data.
This commit introduces the LoanCalculator component, enabling users to
calculate loan repayments based on amount, term, and loan type.

Key changes include:
- Implemented UI elements for input (amount, term, loan type) using Material UI.
- Integrated with the `loansApi.calculateLoanRepayment` endpoint to
  fetch accurate repayment schedules.
- Added a fallback calculation logic in case the API call fails, ensuring
  the component remains functional. This includes generating a simple
  repayment schedule.
- Implemented currency formatting and date formatting for improved
  readability.
- Added loading state using `CircularProgress` to indicate API calls.
- Defined loan types with corresponding interest rates and updated the
  interest rate based on the selected loan type.
- Included validation for amount and term inputs using `isNaN`.

The component also displays a summary of the loan including monthly
payment, total repayment, and total interest and the interest as a
percentage of the principal.
This commit introduces the `LoanPaymentForm` component, enabling users to make loan repayments.

Key features include:
- Form for entering payment amount, method (cash, mobile money, bank transfer, cheque, internal transfer), and optional remarks.
- Conditional fields based on the selected payment method (e.g., phone number for Mobile Money, reference number for Bank Transfer, Cheque number for cheque).
- Form validation to ensure required fields are filled and amount is valid.
- Option to choose between a specific amount and full payment, with the full payment amount dynamically set to the remaining loan balance.
- Integration with the `loansApi.makeRepayment` API endpoint to process payments.
- Error handling and display of payment processing errors.
- Loading state to indicate ongoing payment processing.
- Utilizes Material UI components for a consistent user interface.

The component accepts `loanId`, `open`, `onClose`, `onSuccess`, `defaultAmount`, and `maxAmount` as props. `maxAmount` represents the outstanding loan amount.
This commit introduces the LoanTypeSelector component, enabling users
to select a loan type from a predefined list.

The LoanTypeSelector component:
- Displays loan types (Personal, Business, Education, Home, Emergency)
  as selectable cards using Material UI Grid and Card components.
- Highlights the selected loan type with a colored border and shadow.
- Includes loan type icons, names, descriptions, interest rates, and
  maximum terms.
- Uses the `onChange` prop to communicate the selected loan type ID to
  the parent component.
- Implements basic styling using `useTheme` hook from Material UI.

This component enhances the user experience for loan applications by
providing a clear and intuitive way to choose the desired loan type.
This commit introduces the LoanCalculatorPage, which provides a user
interface for calculating loan estimates.  It includes:

- Breadcrumbs for easy navigation.
- An information section with a disclaimer about the calculator's estimates.
- A LoanCalculator component (reusing existing component).
- Detailed information on various loan options offered by the SACCO
  (Personal, Business, Education, Home Improvement, Emergency Loans)
  including indicative interest rates and maximum terms.

The page utilizes MUI components for styling and layout (Box, Typography,
Breadcrumbs, Link, Paper, Alert, Divider). It aims to educate users on
available loan products and provide a tool for preliminary financial planning.
This commit introduces the `theme.tsx` file, which defines a custom theme for the Sacco frontend using Material UI's `createTheme` function.

The theme configuration includes:

- **Palette:** Defines the primary, secondary, error, warning, info, success, and background colors.
- **Typography:** Sets the default font family to "Roboto, Arial, sans-serif" and adjusts the font weight for heading elements (h1-h6) to 500.
- **Components:** Customizes the styles for several Material UI components:
    - `MuiButton`: Sets border radius, removes text transform, and adjusts box shadow for hover state.
    - `MuiCard`: Sets border radius and box shadow.
    - `MuiPaper`: Sets border radius.
    - `MuiAppBar`: Adjusts box shadow.
    - `MuiDrawer`: Adds a subtle border to the right side.

This theme aims to provide a consistent and visually appealing user interface for the Sacco application.
@coderabbitai
Copy link

coderabbitai bot commented Apr 19, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update represents a major restructuring of the frontend codebase, transitioning from a React Router and Radix UI/Tailwind CSS stack to a new setup based on Vite, Material UI, Emotion, and ESLint. The previous frontend implementation, including all UI components, routes, authentication logic, utilities, and configuration files, has been removed. In their place, new foundational files have been introduced: a Vite-based entry point (index.html), a new App component, and API client modules for authentication, members, loans, and savings, all using Axios with robust token management. The backend tests for authentication, ledger, loans, members, risk management, and transactions have been expanded or improved, but the backend logic remains unchanged.

Changes

File(s) / Path(s) Change Summary
sacco_backend/apps/authentication/tests/test_models.py, sacco_backend/apps/authentication/tests/test_views.py, sacco_backend/apps/ledger/tests.py, sacco_backend/apps/loans/tests/test_model.py, sacco_backend/apps/loans/tests/test_services.py, sacco_backend/apps/loans/tests/test_views.py, sacco_backend/apps/members/tests/test_models.py, sacco_backend/apps/members/tests/test_views.py, sacco_backend/apps/risk_management/tests.py, sacco_backend/apps/transactions/tests.py Expanded and improved backend test coverage for authentication, ledger, loans, members, risk management, and transactions. Added new test methods and classes, enhanced test setups, and increased validation of model and service behaviors.
sacco_backend/apps/transactions/services/transaction_service.py Commented out the assignment of the fee_amount field during transaction creation; no other logic changed.
sacco_frontend/.dockerignore, sacco_frontend/Dockerfile, sacco_frontend/Dockerfile.bun, sacco_frontend/Dockerfile.pnpm, sacco_frontend/app/app.css, sacco_frontend/app/auth/forgot-password/index.tsx, sacco_frontend/app/auth/login/index.tsx, sacco_frontend/app/auth/reset-password/index.tsx, sacco_frontend/app/components/app-sidebar.tsx, sacco_frontend/app/components/nav-main.tsx, sacco_frontend/app/components/nav-projects.tsx, sacco_frontend/app/components/nav-user.tsx, sacco_frontend/app/components/team-switcher.tsx, sacco_frontend/app/components/ui/*, sacco_frontend/app/dashboard/dashboard.tsx, sacco_frontend/app/hooks/use-auth.ts, sacco_frontend/app/hooks/use-mobile.tsx, sacco_frontend/app/hooks/use-toast.ts, sacco_frontend/app/layouts/dashboard-layout.tsx, sacco_frontend/app/lib/api.ts, sacco_frontend/app/lib/utils.ts, sacco_frontend/app/providers/auth-provider.tsx, sacco_frontend/app/root.tsx, sacco_frontend/app/routes.ts, sacco_frontend/app/routes/dashboard.tsx, sacco_frontend/app/routes/forgot-password.tsx, sacco_frontend/app/routes/home.tsx, sacco_frontend/app/routes/login.tsx, sacco_frontend/app/routes/reset-password.tsx, sacco_frontend/app/routes/setup.tsx, sacco_frontend/app/services/auth.service.ts, sacco_frontend/app/setup/setup.tsx, sacco_frontend/app/types/auth.ts, sacco_frontend/app/welcome/welcome.tsx, sacco_frontend/components.json, sacco_frontend/postcss.config.js, sacco_frontend/react-router.config.ts Entire files and directories deleted, removing previous React Router, Radix UI, Tailwind CSS, and custom utility/component infrastructure. All previous route, layout, and UI logic removed.
sacco_frontend/.gitignore Expanded to ignore more files and directories, including logs, build outputs, and IDE/editor files.
sacco_frontend/README.md Replaced detailed React Router/TailwindCSS guide with a minimal Vite + React + ESLint setup and usage instructions.
sacco_frontend/eslint.config.js Added new ESLint configuration for TypeScript and React, enabling recommended rules and plugins for hooks and refresh.
sacco_frontend/index.html Added new Vite-compatible HTML entry point with Google Fonts, root div, and script for main TypeScript entry.
sacco_frontend/package.json Overhauled: switched from React Router/Tailwind/Radix UI dependencies to Vite, MUI, Emotion, ESLint, and updated React/TypeScript. Scripts changed to Vite-based commands.
sacco_frontend/src/App.css Added new global CSS for root layout, logos, cards, and documentation links, including animation.
sacco_frontend/src/App.tsx Added new main React App component with authentication loading state and route rendering.
sacco_frontend/src/api/auth.api.ts, sacco_frontend/src/api/axios.ts, sacco_frontend/src/api/loans.api.ts, sacco_frontend/src/api/members.api.ts, sacco_frontend/src/api/savings.api.ts Added new API client modules for authentication, members, loans, and savings, using Axios with cookie/token management, and typed request/response interfaces.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App (React)
    participant API Client (Axios)
    participant Backend

    User->>App (React): Loads app
    App (React)->>API Client (Axios): Fetch current user (with token from cookies)
    API Client (Axios)->>Backend: GET /auth/user (with Authorization header)
    Backend-->>API Client (Axios): 401 Unauthorized? (if token expired)
    API Client (Axios)->>Backend: POST /auth/refresh (with refresh token)
    Backend-->>API Client (Axios): New access token
    API Client (Axios)->>API Client (Axios): Update cookies & Authorization header
    API Client (Axios)->>Backend: Retry original request
    Backend-->>API Client (Axios): User data
    API Client (Axios)-->>App (React): User data or redirect to login
    App (React)-->>User: Render routes or login screen
Loading

Poem

A rabbit hopped through fields of code,
Sweeping old UI, lightening the load.
Vite and MUI now set the scene,
With ESLint keeping all things clean.
API clients, fresh and neat,
Await the frontend’s nimble feet.
Goodbye to Tailwind’s swirling hue—
The meadow’s new, and so are you!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kallyas kallyas merged commit 05ee1aa into main Apr 19, 2025
1 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant