feat(project-currency): implement project-specific currency support

- Added a currency column to the projects table to allow different projects to use different currencies.
- Updated existing projects to default to 'USD' if no currency is set.
- Enhanced project finance controller to handle currency retrieval and updates.
- Introduced API endpoints for updating project currency with validation.
- Updated frontend components to display and manage project currency effectively.
This commit is contained in:
chamikaJ
2025-06-04 11:30:51 +05:30
parent 1ec9759434
commit d6686d64be
18 changed files with 269 additions and 23 deletions

View File

@@ -50,6 +50,17 @@ export const projectFinanceApiService = {
return response.data;
},
updateProjectCurrency: async (
projectId: string,
currency: string
): Promise<IServerResponse<any>> => {
const response = await apiClient.put<IServerResponse<any>>(
`${rootUrl}/project/${projectId}/currency`,
{ currency }
);
return response.data;
},
exportFinanceData: async (
projectId: string,
groupBy: 'status' | 'priority' | 'phases' = 'status'

View File

@@ -7,6 +7,7 @@ import { IProjectViewModel } from '@/types/project/projectViewModel.types';
import { ITeamMemberOverviewGetResponse } from '@/types/project/project-insights.types';
import { IProjectMembersViewModel } from '@/types/projectMember.types';
import { IProjectManager } from '@/types/project/projectManager.types';
import { ITaskPhase } from '@/types/tasks/taskPhase.types';
const rootUrl = `${API_BASE_URL}/projects`;
@@ -120,5 +121,14 @@ export const projectsApiService = {
const response = await apiClient.get<IServerResponse<IProjectManager[]>>(`${url}`);
return response.data;
},
updateProjectPhaseLabel: async (projectId: string, phaseLabel: string) => {
const q = toQueryString({ id: projectId, current_project_id: projectId });
const response = await apiClient.put<IServerResponse<ITaskPhase>>(
`${rootUrl}/label/${projectId}${q}`,
{ name: phaseLabel }
);
return response.data;
},
};

View File

@@ -116,6 +116,11 @@ const projectSlice = createSlice({
state.project.phase_label = action.payload;
}
},
updateProjectCurrency: (state, action: PayloadAction<string>) => {
if (state.project) {
state.project.currency = action.payload;
}
},
addTask: (
state,
action: PayloadAction<{ task: IProjectTask; groupId: string; insert?: boolean }>
@@ -214,7 +219,8 @@ export const {
setCreateTaskTemplateDrawerOpen,
setProjectView,
updatePhaseLabel,
setRefreshTimestamp
setRefreshTimestamp,
updateProjectCurrency
} = projectSlice.actions;
export default projectSlice.reducer;

View File

@@ -1,6 +1,6 @@
import { projectFinanceApiService } from '@/api/project-finance-ratecard/project-finance.api.service';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { IProjectFinanceGroup, IProjectFinanceTask, IProjectRateCard } from '@/types/project/project-finance.types';
import { IProjectFinanceGroup, IProjectFinanceTask, IProjectRateCard, IProjectFinanceProject } from '@/types/project/project-finance.types';
import { parseTimeToSeconds } from '@/utils/timeUtils';
type FinanceTabType = 'finance' | 'ratecard';
@@ -12,6 +12,7 @@ interface ProjectFinanceState {
loading: boolean;
taskGroups: IProjectFinanceGroup[];
projectRateCards: IProjectRateCard[];
project: IProjectFinanceProject | null;
}
// Utility functions for frontend calculations
@@ -67,6 +68,7 @@ const initialState: ProjectFinanceState = {
loading: false,
taskGroups: [],
projectRateCards: [],
project: null,
};
export const fetchProjectFinances = createAsyncThunk(
@@ -173,6 +175,7 @@ export const projectFinancesSlice = createSlice({
state.loading = false;
state.taskGroups = action.payload.groups;
state.projectRateCards = action.payload.project_rate_cards;
state.project = action.payload.project;
})
.addCase(fetchProjectFinances.rejected, (state) => {
state.loading = false;
@@ -181,6 +184,7 @@ export const projectFinancesSlice = createSlice({
// Update data without changing loading state for silent refresh
state.taskGroups = action.payload.groups;
state.projectRateCards = action.payload.project_rate_cards;
state.project = action.payload.project;
})
.addCase(updateTaskFixedCostAsync.fulfilled, (state, action) => {
const { taskId, groupId, fixedCost } = action.payload;

View File

@@ -27,7 +27,7 @@ import TeamMembersSettings from '@/pages/settings/team-members/team-members-sett
import TeamsSettings from '../../pages/settings/teams/teams-settings';
import ChangePassword from '@/pages/settings/change-password/change-password';
import LanguageAndRegionSettings from '@/pages/settings/language-and-region/language-and-region-settings';
import RatecardSettings from '@/pages/settings/ratecard/ratecard-settings';
import RatecardSettings from '@/pages/settings/rate-card/rate-card-settings';
import AppearanceSettings from '@/pages/settings/appearance/appearance-settings';
// type of menu item in settings sidebar

View File

@@ -76,7 +76,7 @@ const FinanceTableWrapper: React.FC<FinanceTableWrapperProps> = ({ activeTablesL
}, [editingFixedCost]);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const { currency } = useAppSelector(state => state.financeReducer);
const currency = useAppSelector(state => state.projectFinances.project?.currency || "").toUpperCase();
const taskGroups = useAppSelector(state => state.projectFinances.taskGroups);
// Use Redux store data for totals calculation to ensure reactivity

View File

@@ -7,6 +7,7 @@ import { useAppDispatch } from '@/hooks/useAppDispatch';
import { useAppSelector } from '@/hooks/useAppSelector';
import { fetchProjectFinances, setActiveTab, setActiveGroup } from '@/features/projects/finance/project-finance.slice';
import { changeCurrency, toggleImportRatecardsDrawer } from '@/features/finance/finance-slice';
import { updateProjectCurrency } from '@/features/project/project.slice';
import { projectFinanceApiService } from '@/api/project-finance-ratecard/project-finance.api.service';
import { RootState } from '@/app/store';
import FinanceTableWrapper from './finance-tab/finance-table/finance-table-wrapper';
@@ -14,14 +15,16 @@ import RatecardTable from './ratecard-tab/reatecard-table/ratecard-table';
import ImportRatecardsDrawer from '@/features/finance/ratecard-drawer/import-ratecards-drawer';
import { useAuthService } from '@/hooks/useAuth';
import { hasFinanceEditPermission } from '@/utils/finance-permissions';
import { CURRENCY_OPTIONS, DEFAULT_CURRENCY } from '@/shared/constants/currencies';
const ProjectViewFinance = () => {
const { projectId } = useParams<{ projectId: string }>();
const dispatch = useAppDispatch();
const { t } = useTranslation('project-view-finance');
const [exporting, setExporting] = useState(false);
const [updatingCurrency, setUpdatingCurrency] = useState(false);
const { activeTab, activeGroup, loading, taskGroups } = useAppSelector((state: RootState) => state.projectFinances);
const { activeTab, activeGroup, loading, taskGroups, project: financeProject } = useAppSelector((state: RootState) => state.projectFinances);
const { refreshTimestamp, project } = useAppSelector((state: RootState) => state.projectReducer);
const phaseList = useAppSelector((state) => state.phaseReducer.phaseList);
@@ -30,6 +33,12 @@ const ProjectViewFinance = () => {
const currentSession = auth.getCurrentSession();
const hasEditPermission = hasFinanceEditPermission(currentSession, project);
// Get project-specific currency from finance API response, fallback to project reducer, then default
const projectCurrency = (financeProject?.currency || project?.currency || DEFAULT_CURRENCY).toLowerCase();
// Show loading state for currency selector until finance data is loaded
const currencyLoading = loading || updatingCurrency || !financeProject;
useEffect(() => {
if (projectId) {
dispatch(fetchProjectFinances({ projectId, groupBy: activeGroup }));
@@ -71,6 +80,30 @@ const ProjectViewFinance = () => {
}
};
const handleCurrencyChange = async (currency: string) => {
if (!projectId || !hasEditPermission) {
message.error('You do not have permission to change the project currency');
return;
}
try {
setUpdatingCurrency(true);
const upperCaseCurrency = currency.toUpperCase();
await projectFinanceApiService.updateProjectCurrency(projectId, upperCaseCurrency);
// Update both global currency state and project-specific currency
dispatch(changeCurrency(currency));
dispatch(updateProjectCurrency(upperCaseCurrency));
message.success('Project currency updated successfully');
} catch (error) {
console.error('Currency update failed:', error);
message.error('Failed to update project currency');
} finally {
setUpdatingCurrency(false);
}
};
const groupDropdownMenuItems = [
{ key: 'status', value: 'status', label: t('statusText') },
{ key: 'priority', value: 'priority', label: t('priorityText') },
@@ -130,13 +163,11 @@ const ProjectViewFinance = () => {
<Flex gap={8} align="center">
<Typography.Text>{t('currencyText')}</Typography.Text>
<Select
defaultValue={'lkr'}
options={[
{ value: 'lkr', label: 'LKR' },
{ value: 'usd', label: 'USD' },
{ value: 'inr', label: 'INR' },
]}
onChange={(value) => dispatch(changeCurrency(value))}
value={projectCurrency}
loading={currencyLoading}
disabled={!hasEditPermission}
options={CURRENCY_OPTIONS}
onChange={handleCurrencyChange}
/>
</Flex>
<Button

View File

@@ -1,4 +1,4 @@
import { Avatar, Button, Input, Popconfirm, Table, TableProps, Select, Flex } from 'antd';
import { Avatar, Button, Input, Popconfirm, Table, TableProps, Select, Flex, InputRef } from 'antd';
import React, { useEffect, useState } from 'react';
import CustomAvatar from '../../../../../../components/CustomAvatar';
import { DeleteOutlined, PlusOutlined, SaveOutlined } from '@ant-design/icons';
@@ -31,7 +31,7 @@ const RatecardTable: React.FC = () => {
// Redux state
const rolesRedux = useAppSelector((state) => state.projectFinanceRateCard.rateCardRoles) || [];
const isLoading = useAppSelector((state) => state.projectFinanceRateCard.isLoading);
const currency = useAppSelector((state) => state.financeReducer.currency).toUpperCase();
const currency = useAppSelector((state) => state.projectFinances.project?.currency || "USD").toUpperCase();
const rateInputRefs = React.useRef<Array<HTMLInputElement | null>>([]);
// Auth and permissions
@@ -244,7 +244,9 @@ const RatecardTable: React.FC = () => {
align: 'right',
render: (value: number, record: JobRoleType, index: number) => (
<Input
ref={el => rateInputRefs.current[index] = el}
ref={(el: InputRef | null) => {
if (el) rateInputRefs.current[index] = el as unknown as HTMLInputElement;
}}
type="number"
value={roles[index]?.rate ?? 0}
min={0}

View File

@@ -0,0 +1,54 @@
export interface CurrencyOption {
value: string;
label: string;
symbol?: string;
}
export const CURRENCY_OPTIONS: CurrencyOption[] = [
{ value: 'usd', label: 'USD - US Dollar', symbol: '$' },
{ value: 'eur', label: 'EUR - Euro', symbol: '€' },
{ value: 'gbp', label: 'GBP - British Pound', symbol: '£' },
{ value: 'jpy', label: 'JPY - Japanese Yen', symbol: '¥' },
{ value: 'cad', label: 'CAD - Canadian Dollar', symbol: 'C$' },
{ value: 'aud', label: 'AUD - Australian Dollar', symbol: 'A$' },
{ value: 'chf', label: 'CHF - Swiss Franc', symbol: 'CHF' },
{ value: 'cny', label: 'CNY - Chinese Yuan', symbol: '¥' },
{ value: 'inr', label: 'INR - Indian Rupee', symbol: '₹' },
{ value: 'lkr', label: 'LKR - Sri Lankan Rupee', symbol: 'Rs' },
{ value: 'sgd', label: 'SGD - Singapore Dollar', symbol: 'S$' },
{ value: 'hkd', label: 'HKD - Hong Kong Dollar', symbol: 'HK$' },
{ value: 'nzd', label: 'NZD - New Zealand Dollar', symbol: 'NZ$' },
{ value: 'sek', label: 'SEK - Swedish Krona', symbol: 'kr' },
{ value: 'nok', label: 'NOK - Norwegian Krone', symbol: 'kr' },
{ value: 'dkk', label: 'DKK - Danish Krone', symbol: 'kr' },
{ value: 'pln', label: 'PLN - Polish Zloty', symbol: 'zł' },
{ value: 'czk', label: 'CZK - Czech Koruna', symbol: 'Kč' },
{ value: 'huf', label: 'HUF - Hungarian Forint', symbol: 'Ft' },
{ value: 'rub', label: 'RUB - Russian Ruble', symbol: '₽' },
{ value: 'brl', label: 'BRL - Brazilian Real', symbol: 'R$' },
{ value: 'mxn', label: 'MXN - Mexican Peso', symbol: '$' },
{ value: 'zar', label: 'ZAR - South African Rand', symbol: 'R' },
{ value: 'krw', label: 'KRW - South Korean Won', symbol: '₩' },
{ value: 'thb', label: 'THB - Thai Baht', symbol: '฿' },
{ value: 'myr', label: 'MYR - Malaysian Ringgit', symbol: 'RM' },
{ value: 'idr', label: 'IDR - Indonesian Rupiah', symbol: 'Rp' },
{ value: 'php', label: 'PHP - Philippine Peso', symbol: '₱' },
{ value: 'vnd', label: 'VND - Vietnamese Dong', symbol: '₫' },
{ value: 'aed', label: 'AED - UAE Dirham', symbol: 'د.إ' },
{ value: 'sar', label: 'SAR - Saudi Riyal', symbol: '﷼' },
{ value: 'egp', label: 'EGP - Egyptian Pound', symbol: '£' },
{ value: 'try', label: 'TRY - Turkish Lira', symbol: '₺' },
{ value: 'ils', label: 'ILS - Israeli Shekel', symbol: '₪' },
];
export const DEFAULT_CURRENCY = 'usd';
export const getCurrencySymbol = (currencyCode: string): string => {
const currency = CURRENCY_OPTIONS.find(c => c.value === currencyCode.toLowerCase());
return currency?.symbol || currencyCode.toUpperCase();
};
export const getCurrencyLabel = (currencyCode: string): string => {
const currency = CURRENCY_OPTIONS.find(c => c.value === currencyCode.toLowerCase());
return currency?.label || currencyCode.toUpperCase();
};

View File

@@ -63,9 +63,16 @@ export interface IProjectRateCard {
job_title_name: string;
}
export interface IProjectFinanceProject {
id: string;
name: string;
currency: string;
}
export interface IProjectFinanceResponse {
groups: IProjectFinanceGroup[];
project_rate_cards: IProjectRateCard[];
project: IProjectFinanceProject;
}
export interface ITaskBreakdownMember {

View File

@@ -65,4 +65,5 @@ export interface IProjectViewModel extends IProject {
use_manual_progress?: boolean;
use_weighted_progress?: boolean;
use_time_progress?: boolean;
currency?: string;
}