Spaces:
Sleeping
Sleeping
File size: 64,871 Bytes
d97b8f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 | // Import existing types
import type {
Role,
RoleCreateRequest,
RoleUpdateRequest,
Employee,
EmployeeRegistrationRequest,
ProjectApi,
ProjectCreateRequest,
ProjectUpdateRequest as ProjectUpdateRequestType,
Deliverable,
DeliverableCreateRequest,
DeliverableUpdateRequest,
IssueApi,
IssueCreateRequest,
IssueUpdateRequest,
Team,
TeamCreateRequest,
TeamUpdateRequest,
TeamMember,
TeamMemberCreateRequest,
TeamMemberUpdateRequest,
// New types for meeting room booking
MeetingRoom,
MeetingRoomCreateRequest,
MeetingRoomUpdateRequest,
RoomBooking,
RoomBookingCreateRequest,
RoomBookingUpdateRequest,
MaintenanceAmcDate,
MaintenanceAmcDateCreateRequest,
MaintenanceAmcDateUpdateRequest,
ReleaseDate,
ReleaseDateCreateRequest,
ReleaseDateUpdateRequest
} from '@/types';
import { mapApiProject, mapApiIssue } from '@/types';
import { API_BASE_URL as CONFIG_API_URL } from '@/config';
import { Project, Employee as GenericEmployee, ResponseData, Deliverable as DeliverableType, IssueApi as IssueApiType, ProjectTeamApi } from '@/types';
import { Employee as EmployeeType } from '@/services/employeeApi';
import axios, { AxiosError } from 'axios';
import apiClient from '@/lib/api/axios-instance';
// Define the base API URL
const PRIMARY_API_URL = `${CONFIG_API_URL}/api`;
// Current active API URL - will be updated if needed
let API_BASE_URL = PRIMARY_API_URL;
// Utility function to check if API is available and update base URL if needed
export const checkApiConnection = async (): Promise<boolean> => {
// Only check the primary URL, no alternates
try {
console.log(`Checking API connection at ${PRIMARY_API_URL}...`);
const response = await apiClient.get(`${PRIMARY_API_URL}/health`, {
headers: {
'Content-Type': 'application/json',
},
});
if (response.status === 200) {
console.log('API connection successful!');
API_BASE_URL = PRIMARY_API_URL;
return true;
}
} catch (error) {
console.error('API connection failed:', error);
}
console.error('API connection attempt failed');
return false;
};
// Interface for login request payload
export interface LoginRequest {
email: string;
password: string;
}
// Interface for login response
export interface LoginResponse {
userId: number;
email: string;
firstName: string;
lastName: string;
roleId: number;
roleName: string | null;
token: string;
employeeId: number;
}
/**
* Store user session in localStorage
*/
export const userSessionService = {
setSession: (userData: LoginResponse) => {
localStorage.setItem('user_session', JSON.stringify(userData));
},
getSession: (): LoginResponse | null => {
const session = localStorage.getItem('user_session');
return session ? JSON.parse(session) : null;
},
clearSession: () => {
localStorage.removeItem('user_session');
},
isAuthenticated: (): boolean => {
return !!localStorage.getItem('user_session');
}
};
// Create headers with auth info if needed
export const createHeaders = (includeAuth: boolean = true): Record<string, string> => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Accept': '*/*',
};
// Add authorization header if needed
if (includeAuth) {
const userSession = localStorage.getItem('user_session');
console.log(`CreateHeaders - includeAuth: ${includeAuth}, session exists: ${!!userSession}`);
if (userSession) {
try {
const userData = JSON.parse(userSession);
console.log(`User from session: ${userData?.firstName || 'unknown'}, token exists: ${!!userData?.token}`);
if (userData && userData.token) {
headers.Authorization = `Bearer ${userData.token}`;
console.log(`Authorization header set: Bearer ${userData.token.substring(0, 15)}...`);
} else {
console.warn('No token found in user session data');
}
} catch (error) {
console.error('Error parsing user session:', error);
}
} else {
console.warn('createHeaders: No user_session found in localStorage');
}
}
return headers;
};
// Base API request function with error handling
async function apiRequest<T>(
endpoint: string,
method: string = 'GET',
data?: any,
requireAuth: boolean = true
): Promise<T> {
const url = `${API_BASE_URL}${endpoint}`;
const config: any = {
method,
url,
headers: createHeaders(requireAuth),
withCredentials: true
};
// For GET requests, convert data to query params if provided
if (method === 'GET' && data && Object.keys(data).length > 0) {
// If the URL already has query params, use them and add more
const hasParams = url.includes('?');
const separator = hasParams ? '&' : '?';
const queryParams = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
queryParams.append(key, String(value));
}
});
const queryString = queryParams.toString();
if (queryString) {
config.url = `${url}${separator}${queryString}`;
}
} else if (method !== 'GET' && data) {
// For non-GET requests, add data to the request body
config.data = data;
}
try {
console.log(`Making API request to: ${config.url}`);
const response = await apiClient(config);
console.log(`Response status: ${response.status}`);
console.log(`API data received: ${response.data ? 'yes' : 'no'}`);
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
// Try to parse error response as JSON
let errorMessage: string;
const errorData = error.response?.data;
errorMessage = errorData?.message || errorData?.error ||
`API Error: ${error.response?.status} ${error.message}`;
console.error(`API error: ${errorMessage}`);
throw new Error(errorMessage);
}
console.error('API request error:', error);
throw error;
}
}
/**
* API service for authentication
*/
export const authService = {
/**
* Login user with email and password
* @param credentials - User credentials
* @returns LoginResponse
*/
login: async (credentials: LoginRequest): Promise<LoginResponse> => {
try {
const response = await apiRequest<LoginResponse>(
'/auth/login',
'POST',
credentials,
false
);
if (response && response.userId) {
console.log('Login successful:', {
userId: response.userId,
name: `${response.firstName} ${response.lastName}`,
role: response.roleName
});
// Store user session instead of token
userSessionService.setSession(response);
return response;
}
throw new Error('Invalid login response');
} catch (error) {
console.error('Login failed:', error);
throw error;
}
},
logout: () => {
userSessionService.clearSession();
},
/**
* Reset user password
* @param userId - User ID
* @param password - New password
* @param token - Reset token for verification
* @param email - User email (alternative to userId)
* @returns Response message
*/
resetPassword: async (userId?: number, password?: string, token?: string, email?: string): Promise<{ message: string }> => {
try {
console.log('Resetting password:', userId ? `for user ID: ${userId}` : `for email: ${email}`);
console.log('Token provided:', !!token);
// Prepare the request payload based on what we have
const payload: any = {
password
};
// Add either userId or email to the payload
if (userId) {
payload.userId = userId;
} else if (email) {
payload.email = email;
}
// Add token if provided
if (token) {
payload.token = token;
}
// Try the standard endpoint first
const response = await apiRequest<any>(
'/auth/reset-password',
'PUT',
payload,
false
);
console.log('Password reset response:', response);
// Handle different response formats
if (typeof response === 'string') {
return { message: response };
} else if (typeof response === 'object') {
if (response.message) {
return { message: response.message };
} else if (response.success) {
return { message: 'Your password has been reset successfully.' };
}
}
return { message: 'Password reset successful.' };
} catch (error) {
console.error('Password reset failed:', error);
throw error;
}
},
/**
* Request a password reset link
* @param email - User email
* @returns Response message
*/
requestPasswordReset: async (email: string): Promise<{ message: string }> => {
try {
const response = await apiRequest<{ message: string }>(
'/auth/request-reset-password',
'POST',
{ email },
false
);
return response;
} catch (error) {
console.error('Password reset request failed:', error);
throw error;
}
},
/**
* Validate a password reset token
* @param token - Reset token to validate
* @returns Validation result with user ID if valid
*/
validateResetToken: async (token: string): Promise<{ valid: boolean; userId?: number; email?: string }> => {
try {
// Log the token being validated
console.log('Validating reset token:', token);
let response;
// Try several common API endpoint patterns
try {
// Try endpoint format with query parameter
response = await apiRequest<any>(
`/auth/validate-reset-token?token=${encodeURIComponent(token)}`,
'GET',
undefined,
false
);
} catch (firstError) {
console.log('First validation attempt failed, trying alternative endpoints...');
try {
// Try endpoint with token directly in the path
response = await apiRequest<any>(
`/auth/validate-reset-token/${encodeURIComponent(token)}`,
'GET',
undefined,
false
);
} catch (secondError) {
// Try POST request with token in body
try {
response = await apiRequest<any>(
'/auth/validate-reset-token',
'POST',
{ token },
false
);
} catch (thirdError) {
console.error('All token validation attempts failed');
// If all endpoints fail, simulate a response for testing
// Remove this in production
if (token && token.length > 10) {
console.log('Using simulated validation response for testing');
response = { valid: true, email: "test@example.com", userId: 1 };
} else {
throw thirdError;
}
}
}
}
console.log('Token validation response:', response);
// Handle different response formats from the API
if (response && typeof response === 'object') {
// Create the result object - pass through both userId and email if they exist
const result: { valid: boolean; userId?: number; email?: string } = {
valid: false
};
// Check if the response has the valid property set to true
if ('valid' in response && response.valid === true) {
result.valid = true;
// Pass through userId if it exists
if ('userId' in response && (response.userId !== null && response.userId !== undefined)) {
result.userId = response.userId;
}
// Pass through email if it exists
if ('email' in response && response.email) {
result.email = response.email;
}
// Return early if we have at least valid=true and either userId or email
if (result.userId !== undefined || result.email) {
return result;
} else {
// If valid is true but no email/userId provided, consider it invalid
console.error('Token validation failed: Token is valid but no email/userId provided');
return { valid: false };
}
}
// Legacy support for different API formats
if ('userId' in response && (response.userId !== null && response.userId !== undefined)) {
return {
valid: true,
userId: response.userId,
email: response.email
};
}
// If API returns a success property
if ('success' in response && response.success === true) {
const successResult: { valid: boolean; userId?: number; email?: string } = {
valid: true
};
if ('email' in response && response.email) {
successResult.email = response.email;
}
if ('userId' in response && (response.userId !== null && response.userId !== undefined)) {
successResult.userId = response.userId;
} else if ('id' in response && (response.id !== null && response.id !== undefined)) {
successResult.userId = response.id;
}
if (successResult.email || successResult.userId !== undefined) {
return successResult;
} else {
// If success is true but no email/userId/id, consider it invalid
console.error('Token validation failed: Success is true but no identifier provided');
return { valid: false };
}
}
}
// If response is empty or doesn't match expected format, consider it invalid
return { valid: false };
} catch (error) {
console.error('Token validation failed:', error);
// Return invalid on error
return { valid: false };
}
},
};
// Project services, user services, etc. can be added here
/**
* API service for employee management
*/
export const employeeService = {
/**
* Register a new employee
* @param employeeData - Employee registration data
* @returns Employee data with ID and success message
*/
register: async (employeeData: any): Promise<any> => {
try {
const response = await apiRequest<any>(
'/employee/create',
'POST',
employeeData,
true
);
// Transform the response if it's a string (which happens when API returns a simple message)
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...employeeData }
};
}
return response;
} catch (error) {
console.error('Employee registration failed:', error);
throw error;
}
},
/**
* Update an existing employee
* @param employeeData - Employee data to update
* @returns Updated employee data and success message
*/
update: async (employeeData: any): Promise<any> => {
try {
// Handle empty password field - if password is empty, remove it from the request
const dataToSend = { ...employeeData };
if (!dataToSend.passwordHash) {
delete dataToSend.passwordHash;
}
const response = await apiRequest<any>(
`/employee/${employeeData.id}`,
'PUT',
dataToSend,
true
);
// Transform the response if it's a string (which happens when API returns a simple message)
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...employeeData }
};
}
return response;
} catch (error) {
console.error('Employee update failed:', error);
throw error;
}
},
/**
* Get employee by ID
* @param id - Employee ID
* @returns Employee data
*/
getById: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/employee/${id}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get employee with ID ${id}:`, error);
throw error;
}
},
/**
* Get all employees
* @returns List of employees
*/
getAll: async (): Promise<any[]> => {
try {
const response = await apiRequest<any[]>(
'/employee',
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error('Failed to get employees:', error);
throw error;
}
},
/**
* Import multiple employees from CSV data
* @param employees - Array of employee data objects to import
* @returns Status of the import operation with counts
*/
importEmployees: async (employees: any[]): Promise<any> => {
try {
// In a real implementation, you would send this to a bulk import endpoint
const response = await apiRequest<any>(
'/employee/import',
'POST',
{ employees },
true
);
// If the endpoint doesn't exist in development, simulate success
if (response?.status === 404) {
console.log('Import endpoint not found, simulating successful import');
// Simulate a successful response with counts
return {
success: true,
message: `Successfully processed ${employees.length} employees`,
imported: employees.length,
failed: 0,
total: employees.length
};
}
return response;
} catch (error) {
console.error('Failed to import employees:', error);
throw error;
}
},
updateEmployee: async (id: number, data: EmployeeType): Promise<EmployeeType> => {
console.log(`Updating employee: ${id}`);
const response = await apiClient.put(`${CONFIG_API_URL}/v1/employees/${id}`, {
id: data.id,
empCode: data.empCode,
firstName: data.firstName,
middleName: data.middleName,
lastName: data.lastName,
email: data.email,
mobile: data.mobile,
type: data.type,
academics: data.academics,
financialData: data.financialData,
description: data.description,
userId: data.userId,
passwordHash: data.passwordHash,
roleId: data.roleId,
avatarUrl: data.avatarUrl
}, {
headers: {
'Content-Type': 'application/json',
}
});
if (response.status >= 400) {
throw new Error(`Failed to update employee: ${response.statusText}`);
}
return response.data;
},
};
/**
* API service for role management
*/
export const roleService = {
/**
* Get all roles
* @returns List of roles
*/
getAll: async (): Promise<any[]> => {
try {
const response = await apiRequest<any[]>(
'/Role',
'GET',
undefined,
true
);
// Log the raw API response
console.log('Raw roles API response:', response);
// Ensure consistent property structure
const normalizedRoles = Array.isArray(response) ? response.map(role => {
// Map to ensure consistent structure
const normalizedRole = { ...role };
// Ensure roleId exists
if (normalizedRole.roleId === undefined && normalizedRole.id !== undefined) {
normalizedRole.roleId = normalizedRole.id;
}
// Ensure id exists
if (normalizedRole.id === undefined && normalizedRole.roleId !== undefined) {
normalizedRole.id = normalizedRole.roleId;
}
return normalizedRole;
}) : [];
return normalizedRoles;
} catch (error) {
console.error('Failed to get roles:', error);
throw error;
}
},
/**
* Get role by ID
* @param id - Role ID
* @returns Role data
*/
getById: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Role/${id}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get role with ID ${id}:`, error);
throw error;
}
},
/**
* Create a new role
* @param roleData - Role data
* @returns Created role data
*/
create: async (roleData: any): Promise<any> => {
try {
const response = await apiRequest<any>(
'/Role',
'POST',
roleData,
true
);
// Transform the response if it's a string
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...roleData }
};
}
return response;
} catch (error) {
console.error('Role creation failed:', error);
throw error;
}
},
/**
* Update an existing role
* @param roleData - Role data to update
* @returns Updated role data
*/
update: async (roleData: any): Promise<any> => {
try {
console.log("Updating role with data:", roleData);
// Ensure we're using roleId for the URL
const roleId = roleData.roleId || roleData.id;
const response = await apiRequest<any>(
`/Role/${roleId}`,
'PUT',
roleData,
true
);
console.log("Role update response:", response);
// Transform the response if it's a string
if (typeof response === 'string') {
return {
success: true,
message: response || `Role '${roleData.roleName}' was updated successfully`,
data: { ...roleData }
};
}
return {
success: true,
message: `Role '${roleData.roleName}' was updated successfully`,
data: response || { ...roleData }
};
} catch (error) {
console.error('Role update failed:', error);
throw error;
}
},
/**
* Delete a role
* @param id - Role ID
* @returns Success message
*/
delete: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Role/${id}`,
'DELETE',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to delete role with ID ${id}:`, error);
throw error;
}
}
};
/**
* API service for project management
*/
export const projectService = {
/**
* Get all projects
* @returns List of projects
*/
getAll: async (): Promise<ProjectApi[]> => {
try {
console.log('Fetching all projects...');
// Get the current user session to check role
const currentUser = userSessionService.getSession();
console.log('Current user role:', currentUser?.roleName);
let directUrl = `${API_BASE_URL}/Project`;
// If user is CEO, COO, or Admin, they should see all projects
// Otherwise, get projects by employee ID
if (currentUser?.roleName && ['CEO', 'COO', 'Admin'].includes(currentUser.roleName)) {
console.log('User has admin-level role, fetching all projects');
directUrl = `${API_BASE_URL}/Project`;
} else if (currentUser?.employeeId) {
console.log(`User is not admin, fetching projects for employee ID: ${currentUser.employeeId}`);
directUrl = `${API_BASE_URL}/Project/GetProjectsByEmpId/${currentUser.employeeId}`;
}
console.log(`Making direct request to: ${directUrl}`);
const response = await apiClient.get(directUrl, {
headers: createHeaders(true)
});
console.log(`Project response status: ${response.status}`);
if (response.status >= 400) {
throw new Error(`Failed to fetch projects: ${response.statusText}`);
}
const rawData = response.data;
console.log(`Projects fetched: ${rawData?.length || 0}`);
// Inspect the structure of the first project if available
if (rawData && rawData.length > 0) {
console.log('First project structure:', JSON.stringify(rawData[0], null, 2));
console.log('Project properties:', Object.keys(rawData[0]));
} else {
console.log('No projects returned from API');
}
// Map the API response to the expected ProjectApi format
const mappedProjects = Array.isArray(rawData)
? rawData.map(project => mapApiProject(project))
: [];
console.log('Mapped projects:', mappedProjects);
return mappedProjects;
} catch (error) {
console.error('Failed to get projects:', error);
// Return empty array instead of throwing to prevent UI errors
return [];
}
},
/**
* Get projects by employee ID
* @param employeeId - Employee ID
* @returns List of projects associated with the employee
*/
getByEmployeeId: async (employeeId: number): Promise<ProjectApi[]> => {
try {
console.log(`Fetching projects for employee ID: ${employeeId}...`);
const directUrl = `${API_BASE_URL}/Project/GetProjectsByEmpId/${employeeId}`;
console.log(`Making direct request to: ${directUrl}`);
const response = await apiClient.get(directUrl, {
headers: createHeaders(true)
});
console.log(`Project response status: ${response.status}`);
if (response.status >= 400) {
throw new Error(`Failed to fetch projects for employee ${employeeId}: ${response.statusText}`);
}
const rawData = response.data;
console.log(`Projects fetched for employee: ${rawData?.length || 0}`);
// Map the API response to the expected ProjectApi format
const mappedProjects = Array.isArray(rawData)
? rawData.map(project => mapApiProject(project))
: [];
return mappedProjects;
} catch (error) {
console.error(`Failed to get projects for employee ${employeeId}:`, error);
// Return empty array instead of throwing to prevent UI errors
return [];
}
},
/**
* Get project by ID
* @param id - Project ID
* @returns Project data
*/
getById: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Project/${id}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get project with ID ${id}:`, error);
throw error;
}
},
/**
* Create a new project
* @param projectData - Project data
* @returns Created project data
*/
create: async (projectData: any): Promise<any> => {
try {
const response = await apiRequest<any>(
'/Project',
'POST',
projectData,
true
);
// Transform the response if it's a string
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...projectData }
};
}
return response;
} catch (error) {
console.error('Project creation failed:', error);
throw error;
}
},
/**
* Update an existing project
* @param projectData - Project data to update
* @returns Updated project data
*/
update: async (projectData: any): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Project/${projectData.id}`,
'PUT',
projectData,
true
);
// Transform the response if it's a string
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...projectData }
};
}
return response;
} catch (error) {
console.error('Project update failed:', error);
throw error;
}
},
/**
* Delete a project
* @param id - Project ID
* @returns Success message
*/
delete: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Project/${id}`,
'DELETE',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to delete project with ID ${id}:`, error);
throw error;
}
}
};
/**
* Deliverables API
*/
export const deliverablesApi = {
/**
* Get all deliverables
* @returns List of all deliverables
*/
getAll: async (): Promise<Deliverable[]> => {
try {
console.log('Fetching all deliverables...');
// Get the current user session to check role
const currentUser = userSessionService.getSession();
console.log('Current user role for deliverables access:', currentUser?.roleName);
// First get the projects the user has access to
let accessibleProjects: number[] = [];
// If user is CEO, COO, or Admin, they should see all deliverables
// Otherwise, only see deliverables from assigned projects
if (currentUser?.roleName && ['CEO', 'COO', 'Admin'].includes(currentUser.roleName)) {
console.log('User has admin-level role, fetching all deliverables');
// Admin-level users don't need to filter by projects
} else if (currentUser?.employeeId) {
console.log(`User is not admin, fetching projects for employee ID: ${currentUser.employeeId}`);
// Get assigned projects first
const projectsResponse = await projectService.getByEmployeeId(currentUser.employeeId);
accessibleProjects = projectsResponse.map(project => project.id);
console.log(`User has access to ${accessibleProjects.length} projects:`, accessibleProjects);
}
// Direct fetch with custom options to bypass certificate validation
const directUrl = `${API_BASE_URL}/Deliverables`;
console.log(`Making direct request to: ${directUrl}`);
const response = await apiClient.get(directUrl, {
headers: createHeaders(true)
});
console.log(`Deliverables response status: ${response.status}`);
if (response.status >= 400) {
throw new Error(`Failed to fetch deliverables: ${response.statusText}`);
}
const data = response.data;
console.log(`Deliverables fetched: ${data?.length || 0}`);
// Filter deliverables by project access if the user isn't an admin
let filteredData = data;
if (currentUser?.roleName && !['CEO', 'COO', 'Admin'].includes(currentUser.roleName) && accessibleProjects.length > 0) {
filteredData = data.filter((deliverable: Deliverable) =>
accessibleProjects.includes(deliverable.projectId)
);
console.log(`Filtered to ${filteredData.length} deliverables based on project access`);
}
return filteredData;
} catch (error) {
console.error('Failed to fetch deliverables:', error);
// Return empty array instead of throwing to prevent UI errors
return [];
}
},
/**
* Get a specific deliverable by ID
* @param id - Deliverable ID
* @returns Deliverable data
*/
getById: async (id: number): Promise<Deliverable> => {
try {
const response = await apiRequest<Deliverable>(`/Deliverables/${id}`, 'GET', undefined, true);
return response;
} catch (error) {
console.error(`Failed to fetch deliverable with ID ${id}:`, error);
throw error;
}
},
/**
* Get deliverables by project ID
* @param projectId - Project ID
* @returns List of deliverables for the project
*/
getByProjectId: async (projectId: number): Promise<Deliverable[]> => {
try {
console.log(`Fetching deliverables for project ID ${projectId}...`);
// Get the current user session to check role
const currentUser = userSessionService.getSession();
// Check if user has access to this project
let hasAccess = false;
// Admin roles have access to all projects
if (currentUser?.roleName && ['CEO', 'COO', 'Admin'].includes(currentUser.roleName)) {
hasAccess = true;
} else if (currentUser?.employeeId) {
// For non-admin users, check if this project is in their assigned projects
try {
const userProjects = await projectService.getByEmployeeId(currentUser.employeeId);
hasAccess = userProjects.some(p => p.id === projectId);
} catch (error) {
console.error(`Error checking project access for employee ${currentUser.employeeId}:`, error);
// Default to no access if there's an error
hasAccess = false;
}
}
if (!hasAccess) {
console.warn(`User doesn't have access to project ${projectId}`);
return []; // Return empty array if no access
}
const allDeliverables = await apiRequest<Deliverable[]>('/Deliverables', 'GET', undefined, true);
return allDeliverables.filter(deliverable => deliverable.projectId === projectId);
} catch (error) {
console.error(`Failed to fetch deliverables for project ID ${projectId}:`, error);
throw error;
}
},
/**
* Create a new deliverable
* @param deliverableData - Deliverable data to create
* @returns Created deliverable data
*/
create: async (deliverableData: DeliverableCreateRequest): Promise<any> => {
try {
const response = await apiRequest<any>(
'/Deliverables',
'POST',
deliverableData,
true
);
return response;
} catch (error) {
console.error('Deliverable creation failed:', error);
throw error;
}
},
/**
* Update an existing deliverable
* @param deliverableData - Deliverable data to update
* @returns Updated deliverable data
*/
update: async (deliverableData: DeliverableUpdateRequest): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Deliverables/${deliverableData.id}`,
'PUT',
deliverableData,
true
);
// Transform the response if it's a string
if (typeof response === 'string') {
return {
success: true,
message: response,
data: { ...deliverableData }
};
}
return response;
} catch (error) {
console.error('Deliverable update failed:', error);
throw error;
}
},
/**
* Delete a deliverable
* @param id - Deliverable ID
* @returns Success message
*/
delete: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(
`/Deliverables/${id}`,
'DELETE',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to delete deliverable with ID ${id}:`, error);
throw error;
}
}
};
/**
* Issues API
*/
export const issuesApi = {
/**
* Get all issues
* @returns List of all issues
*/
getAll: async (): Promise<IssueApi[]> => {
try {
console.log('Fetching all issues...');
const response = await apiRequest<any[]>('/Issues', 'GET', undefined, true);
// Map the API response to handle property name differences
const mappedIssues = Array.isArray(response)
? response.map(issue => mapApiIssue(issue))
: [];
console.log(`Fetched ${mappedIssues.length} issues`);
return mappedIssues;
} catch (error) {
console.error('Failed to fetch issues:', error);
throw error;
}
},
/**
* Get a specific issue by ID
* @param id - Issue ID
* @returns Issue data
*/
getById: async (id: number): Promise<IssueApi> => {
try {
const response = await apiRequest<any>(`/Issues/${id}`, 'GET', undefined, true);
return mapApiIssue(response);
} catch (error) {
console.error(`Failed to fetch issue with ID ${id}:`, error);
throw error;
}
},
/**
* Get issues by project ID
* @param projectId - Project ID
* @returns List of issues for the project
*/
getByProjectId: async (projectId: number): Promise<IssueApi[]> => {
try {
const response = await apiRequest<any[]>('/Issues', 'GET', undefined, true);
// Map the API response to handle property name differences
const allIssues = Array.isArray(response)
? response.map(issue => mapApiIssue(issue))
: [];
// Filter issues by project ID
return allIssues.filter(issue => issue.projectId === projectId);
} catch (error) {
console.error(`Failed to fetch issues for project ID ${projectId}:`, error);
throw error;
}
},
/**
* Get issues by deliverable ID
* @param deliverableId - Deliverable ID
* @returns List of issues for the deliverable
*/
getByDeliverableId: async (deliverableId: number): Promise<IssueApi[]> => {
try {
console.log(`Fetching issues for deliverable ID ${deliverableId}...`);
const directUrl = `${API_BASE_URL}/Issues/GetByDeliverableID/${deliverableId}`;
console.log(`Making direct request to: ${directUrl}`);
const response = await apiClient.get(directUrl, {
headers: {
'Accept': '*/*',
'Content-Type': 'application/json'
}
});
console.log(`Issues API response status: ${response.status}`);
if (response.status >= 400) {
console.error(`Issues API error: ${response.status} ${response.statusText}`);
console.log('Falling back to regular method...');
return await fallbackGetIssuesByDeliverableId(deliverableId);
}
// Get raw data to inspect
const rawData = response.data;
console.log(`Raw issues data from API: Total count = ${Array.isArray(rawData) ? rawData.length : 0}`);
if (Array.isArray(rawData) && rawData.length > 0) {
console.log('First issue structure from API:', rawData[0]);
// Map the API response to our expected format
const mappedIssues = rawData.map(issue => {
console.log(`Processing issue ID ${issue.id}, deliverable ID: ${issue.deliverablesId}`);
return mapApiIssue(issue);
});
console.log(`Mapped ${mappedIssues.length} issues for deliverable ID ${deliverableId}`);
return mappedIssues;
} else {
console.log(`No issues found for deliverable ID ${deliverableId} from direct API`);
return [];
}
} catch (error) {
console.error(`Failed to fetch issues for deliverable ID ${deliverableId}:`, error);
// Fall back to the original method if the direct endpoint fails
console.log('Trying fallback method due to error...');
return await fallbackGetIssuesByDeliverableId(deliverableId);
}
},
/**
* Create a new issue
* @param issueData - Issue data to create
* @returns Created issue data
*/
create: async (issueData: IssueCreateRequest): Promise<any> => {
try {
return await apiRequest<any>(
'/Issues',
'POST',
issueData,
true
);
} catch (error) {
console.error('Issue creation failed:', error);
throw error;
}
},
/**
* Update an existing issue
* @param issueData - Issue data to update
* @returns Updated issue data
*/
update: async (issueData: IssueUpdateRequest): Promise<any> => {
try {
return await apiRequest<any>(
`/Issues/${issueData.id}`,
'PUT',
issueData,
true
);
} catch (error) {
console.error('Issue update failed:', error);
throw error;
}
},
/**
* Delete an issue
* @param id - Issue ID
*/
delete: async (id: number): Promise<any> => {
try {
return await apiRequest<any>(
`/Issues/${id}`,
'DELETE',
undefined,
true
);
} catch (error) {
console.error(`Failed to delete issue with ID ${id}:`, error);
throw error;
}
},
/**
* Create an issue directly using fetch (alternative implementation)
* This can be helpful when troubleshooting API integration
* @param issueData - Issue data to create
* @returns Created issue data
*/
createDirect: async (issueData: IssueCreateRequest): Promise<any> => {
try {
const url = `${API_BASE_URL}/Issues`;
console.log(`Making direct POST request to: ${url}`);
console.log('Request data:', JSON.stringify(issueData, null, 2));
const response = await apiClient.post(url, issueData, {
headers: {
'Accept': 'text/plain',
'Content-Type': 'application/json'
}
});
console.log(`Issue create API response status: ${response.status}`);
if (response.status >= 400) {
throw new Error(`API Error: ${response.status}`);
}
console.log('Issue created successfully:', response.data);
return response.data;
} catch (error) {
console.error('Issue direct creation failed:', error);
throw error;
}
},
};
// Fallback method to get issues by deliverable ID if the direct endpoint fails
async function fallbackGetIssuesByDeliverableId(deliverableId: number): Promise<IssueApi[]> {
try {
console.log(`Using fallback method to get issues for deliverable ID ${deliverableId}`);
// Get all issues and filter client-side
const response = await apiRequest<any[]>('/Issues', 'GET', undefined, true);
// Map the API response to handle property name differences
const allIssues = Array.isArray(response)
? response.map(issue => mapApiIssue(issue))
: [];
console.log(`Got ${allIssues.length} issues in fallback, filtering for deliverable ID ${deliverableId}`);
// Filter issues based on deliverable ID
const filteredIssues = allIssues.filter(issue => Number(issue.deliverablesId) === Number(deliverableId));
console.log(`Found ${filteredIssues.length} issues for deliverable ID ${deliverableId} in fallback method`);
return filteredIssues;
} catch (error) {
console.error(`Fallback method for fetching issues also failed:`, error);
// Return empty array instead of throwing to prevent UI errors
return [];
}
}
/**
* API service for team management
*/
export const teamService = {
/**
* Get all teams
*/
getAll: async (): Promise<Team[]> => {
return apiRequest<Team[]>('/Team');
},
/**
* Get team by ID
*/
getById: async (id: number): Promise<Team> => {
return apiRequest<Team>(`/Team/${id}`);
},
/**
* Create a new team
*/
create: async (team: TeamCreateRequest): Promise<Team> => {
return apiRequest<Team>('/Team', 'POST', team);
},
/**
* Update an existing team
*/
update: async (team: TeamUpdateRequest): Promise<Team> => {
return apiRequest<Team>(`/Team/${team.id}`, 'PUT', team);
},
/**
* Delete a team
*/
delete: async (id: number): Promise<void> => {
return apiRequest<void>(`/Team/${id}`, 'DELETE');
}
};
/**
* API service for team member management
*/
export const teamMemberService = {
/**
* Get all team members
*/
getAll: async (): Promise<TeamMember[]> => {
return apiRequest<TeamMember[]>('/TeamMember');
},
/**
* Get team member by ID
*/
getById: async (id: number): Promise<TeamMember> => {
return apiRequest<TeamMember>(`/TeamMember/${id}`);
},
/**
* Create a new team member
*/
create: async (member: TeamMemberCreateRequest): Promise<TeamMember> => {
return apiRequest<TeamMember>('/TeamMember', 'POST', member);
},
/**
* Update an existing team member
*/
update: async (member: TeamMemberUpdateRequest): Promise<TeamMember> => {
return apiRequest<TeamMember>(`/TeamMember/${member.id}`, 'PUT', member);
},
/**
* Delete a team member
*/
delete: async (id: number): Promise<void> => {
return apiRequest<void>(`/TeamMember/${id}`, 'DELETE');
},
/**
* Update team member status (active/released)
*/
updateStatus: async (id: number, isActive: string): Promise<any> => {
return apiRequest<any>(
`/TeamMember/update-is-active/${id}`,
'PUT',
isActive, // Pass the string directly as body
true
);
}
};
// ProjectTeam API Service
export const projectTeamService = {
getAll: async (): Promise<any[]> => {
try {
const response = await apiRequest<any[]>('/ProjectTeam');
return response;
} catch (error) {
console.error('Error fetching project teams:', error);
throw error;
}
},
getById: async (id: number): Promise<any> => {
try {
const response = await apiRequest<any>(`/ProjectTeam/${id}`);
return response;
} catch (error) {
console.error(`Error fetching project team ${id}:`, error);
throw error;
}
},
create: async (projectTeam: any): Promise<any> => {
try {
const response = await apiRequest<any>('/ProjectTeam', 'POST', projectTeam);
return response;
} catch (error) {
console.error('Error creating project team:', error);
throw error;
}
},
update: async (id: number, projectTeam: any): Promise<any> => {
try {
const response = await apiRequest<any>(`/ProjectTeam/${id}`, 'PUT', projectTeam);
return response;
} catch (error) {
console.error(`Error updating project team ${id}:`, error);
throw error;
}
},
delete: async (id: number): Promise<void> => {
try {
await apiRequest<void>(`/ProjectTeam/${id}`, 'DELETE');
} catch (error) {
console.error(`Error deleting project team ${id}:`, error);
throw error;
}
},
getByProjectId: async (projectId: number): Promise<any[]> => {
try {
const allTeams = await projectTeamService.getAll();
return allTeams.filter(team => team.projectId === projectId);
} catch (error) {
console.error(`Error fetching teams for project ${projectId}:`, error);
throw error;
}
}
};
/**
* API service for meeting rooms
*/
export const meetingRoomService = {
/**
* Get all meeting rooms
* @returns List of meeting rooms
*/
getAllRooms: async (): Promise<MeetingRoom[]> => {
return apiRequest<MeetingRoom[]>('/MeetingRoom', 'GET');
},
/**
* Get meeting room by ID
* @param id - Meeting room ID
* @returns Meeting room details
*/
getRoomById: async (id: number): Promise<MeetingRoom> => {
return apiRequest<MeetingRoom>(`/MeetingRoom/${id}`, 'GET');
},
/**
* Create new meeting room
* @param room - Meeting room data
* @returns Created meeting room
*/
createRoom: async (room: MeetingRoomCreateRequest): Promise<MeetingRoom> => {
return apiRequest<MeetingRoom>('/MeetingRoom', 'POST', room);
},
/**
* Update meeting room
* @param room - Meeting room data with updates
* @returns Updated meeting room
*/
updateRoom: async (room: MeetingRoomUpdateRequest): Promise<MeetingRoom> => {
return apiRequest<MeetingRoom>(`/MeetingRoom/${room.id}`, 'PUT', room);
},
/**
* Delete meeting room
* @param id - Meeting room ID
* @returns Success message
*/
deleteRoom: async (id: number): Promise<void> => {
return apiRequest<void>(`/MeetingRoom/${id}`, 'DELETE');
},
/**
* Check room availability for a time period
* @param roomId - Room ID
* @param startTime - Start time (ISO string)
* @param endTime - End time (ISO string)
* @returns Availability status
*/
checkRoomAvailability: async (
roomId: number,
startTime: string,
endTime: string
): Promise<{ isAvailable: boolean }> => {
return apiRequest<{ isAvailable: boolean }>(
`/MeetingRoom/${roomId}/availability?startTime=${encodeURIComponent(startTime)}&endTime=${encodeURIComponent(endTime)}`,
'GET'
);
}
};
/**
* API service for room bookings
*/
export const roomBookingService = {
/**
* Get all room bookings
* @returns List of room bookings
*/
getAllBookings: async (): Promise<RoomBooking[]> => {
console.log('Fetching all room bookings');
try {
const response = await apiRequest<any[]>('/RoomBooking');
// Parse bookingAttendees from string to array of numbers
return response.map((booking: any) => ({
...booking,
attendees: parseAttendees(booking.bookingAttendees)
}));
} catch (error) {
console.error('Error fetching room bookings:', error);
throw error;
}
},
/**
* Get room bookings by room ID
* @param roomId - Room ID
* @returns List of bookings for the room
*/
getBookingsByRoomId: async (roomId: number): Promise<RoomBooking[]> => {
console.log(`Fetching bookings for room ID: ${roomId}`);
try {
const response = await apiRequest<any[]>('/RoomBooking/room/' + roomId);
return response.map((booking: any) => ({
...booking,
attendees: parseAttendees(booking.bookingAttendees)
}));
} catch (error) {
console.error(`Error fetching bookings for room ${roomId}:`, error);
throw error;
}
},
/**
* Get room bookings by employee ID
* @param employeeId - Employee ID
* @returns List of bookings made by the employee
*/
getBookingsByEmployeeId: async (employeeId: number): Promise<RoomBooking[]> => {
console.log(`Fetching bookings for employee ID: ${employeeId}`);
try {
const response = await apiRequest<any[]>('/RoomBooking/employee/' + employeeId);
return response.map((booking: any) => ({
...booking,
attendees: parseAttendees(booking.bookingAttendees)
}));
} catch (error) {
console.error(`Error fetching bookings for employee ${employeeId}:`, error);
throw error;
}
},
/**
* Get room booking by ID
* @param id - Booking ID
* @returns Booking details
*/
getBookingById: async (id: number): Promise<RoomBooking> => {
console.log(`Fetching booking details for ID: ${id}`);
try {
const response = await apiRequest<any>(`/RoomBooking/${id}`);
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error(`Error fetching booking ${id}:`, error);
throw error;
}
},
/**
* Create new room booking
* @param booking - Booking data
* @returns Created booking
*/
createBooking: async (booking: RoomBookingCreateRequest): Promise<RoomBooking> => {
try {
console.log('Creating new room booking with data:', booking);
// Ensure all required fields are present
const bookingData = {
...booking,
// Ensure roomName is set if missing
roomName: booking.roomName || 'Meeting Room',
// Ensure status is set to pending by default
status: booking.status || 'pending',
// Set timestamps if not provided
// Convert attendees array to string format for API
bookingAttendees: Array.isArray(booking.attendees) ?
`{${booking.attendees.join(',')}}` :
'{}'
};
const response = await apiRequest<RoomBooking>('/RoomBooking', 'POST', bookingData);
console.log('Room booking created successfully:', response);
// Ensure attendees is properly set in the response
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error('Failed to create room booking:', error);
throw error;
}
},
/**
* Update room booking
* @param booking - Booking data with updates
* @returns Updated booking
*/
updateBooking: async (booking: RoomBookingUpdateRequest): Promise<RoomBooking> => {
try {
console.log('Updating booking with data:', booking);
// Prepare data for API by converting attendees to string format if needed
const updateData = {
...booking,
// Convert attendees array to string format for API if present
bookingAttendees: booking.attendees ?
`{${booking.attendees.join(',')}}` :
undefined
};
const response = await apiRequest<RoomBooking>(`/RoomBooking/${booking.id}`, 'PUT', updateData);
// Ensure attendees is properly set in the response
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error(`Failed to update booking ${booking.id}:`, error);
throw error;
}
},
/**
* Delete room booking
* @param id - Booking ID
* @returns Success message
*/
deleteBooking: async (id: number): Promise<void> => {
try {
console.log(`Deleting booking ID: ${id}`);
await apiRequest<void>(`/RoomBooking/${id}`, 'DELETE');
} catch (error) {
console.error(`Error deleting booking ${id}:`, error);
throw error;
}
},
/**
* Approve booking
* @param id - Booking ID
* @returns Updated booking
*/
approveBooking: async (id: number): Promise<RoomBooking> => {
try {
console.log(`Approving booking ID: ${id}`);
const response = await apiRequest<RoomBooking>(`/RoomBooking/${id}/approve`, 'PUT');
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error(`Error approving booking ${id}:`, error);
throw error;
}
},
/**
* Reject booking
* @param id - Booking ID
* @param reason - Rejection reason
* @returns Updated booking
*/
rejectBooking: async (id: number, reason: string): Promise<RoomBooking> => {
try {
console.log(`Rejecting booking ID: ${id} with reason: ${reason}`);
const response = await apiRequest<RoomBooking>(`/RoomBooking/${id}/reject`, 'PUT', { reason });
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error(`Error rejecting booking ${id}:`, error);
throw error;
}
},
/**
* Cancel booking
* @param id - Booking ID
* @returns Updated booking
*/
cancelBooking: async (id: number): Promise<RoomBooking> => {
try {
console.log(`Cancelling booking ID: ${id}`);
const response = await apiRequest<RoomBooking>(`/RoomBooking/${id}/cancel`, 'PUT');
return {
...response,
attendees: parseAttendees(response.bookingAttendees)
};
} catch (error) {
console.error(`Error cancelling booking ${id}:`, error);
throw error;
}
},
/**
* Get available rooms for a time period
* @param startTime - Start time (ISO string)
* @param endTime - End time (ISO string)
* @param minCapacity - Minimum capacity required
* @returns List of available rooms
*/
getAvailableRooms: async (
startTime: string,
endTime: string,
minCapacity?: number
): Promise<MeetingRoom[]> => {
try {
console.log(`Finding available rooms from ${startTime} to ${endTime} with min capacity: ${minCapacity || 'any'}`);
const queryParams = new URLSearchParams();
queryParams.append('startTime', startTime);
queryParams.append('endTime', endTime);
if (minCapacity) {
queryParams.append('minCapacity', minCapacity.toString());
}
return apiRequest<MeetingRoom[]>(`/MeetingRoom/available?${queryParams.toString()}`, 'GET');
} catch (error) {
console.error('Error finding available rooms:', error);
throw error;
}
}
};
// Helper function to parse attendees string into array of numbers
function parseAttendees(attendeesString: string | null | undefined): number[] {
if (!attendeesString) return [];
try {
// Handle format like "{101, 102, 103}"
if (typeof attendeesString === 'string') {
// Remove braces and split by comma
const cleanString = attendeesString.replace(/[{}]/g, '');
return cleanString.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
}
// If it's already an array, return it
if (Array.isArray(attendeesString)) {
return attendeesString;
}
return [];
} catch (error) {
console.error('Error parsing attendees:', error);
return [];
}
}
/**
* API service for maintenance AMC dates
*/
export const maintenanceAmcDateService = {
/**
* Get all maintenance AMC dates
* @returns List of maintenance AMC dates
*/
getAll: async (): Promise<MaintenanceAmcDate[]> => {
try {
const response = await apiRequest<MaintenanceAmcDate[]>(
'/MaintenanceAmcDates',
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error('Failed to get maintenance AMC dates:', error);
return [];
}
},
/**
* Get maintenance AMC date by ID
* @param id - Maintenance AMC date ID
* @returns Maintenance AMC date data
*/
getById: async (id: number): Promise<MaintenanceAmcDate> => {
try {
const response = await apiRequest<MaintenanceAmcDate>(
`/MaintenanceAmcDates/${id}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get maintenance AMC date with ID ${id}:`, error);
throw error;
}
},
/**
* Get maintenance AMC dates by project ID
* @param projectId - Project ID
* @returns List of maintenance AMC dates for the project
*/
getByProjectId: async (projectId: number): Promise<MaintenanceAmcDate[]> => {
try {
const allData = await maintenanceAmcDateService.getAll();
return allData.filter(item => item.projectId === projectId);
} catch (error) {
console.error(`Failed to get maintenance AMC dates for project ${projectId}:`, error);
return [];
}
},
/**
* Create a new maintenance AMC date
* @param data - Maintenance AMC date data
* @returns Created maintenance AMC date data
*/
create: async (data: MaintenanceAmcDateCreateRequest): Promise<MaintenanceAmcDate> => {
try {
const response = await apiRequest<MaintenanceAmcDate>(
'/MaintenanceAmcDates',
'POST',
data,
true
);
return response;
} catch (error) {
console.error('Failed to create maintenance AMC date:', error);
throw error;
}
},
/**
* Update an existing maintenance AMC date
* @param data - Maintenance AMC date data to update
* @returns Updated maintenance AMC date data
*/
update: async (data: MaintenanceAmcDateUpdateRequest): Promise<MaintenanceAmcDate> => {
try {
const response = await apiRequest<MaintenanceAmcDate>(
`/MaintenanceAmcDates/${data.maintenanceId}`,
'PUT',
data,
true
);
return response;
} catch (error) {
console.error(`Failed to update maintenance AMC date with ID ${data.maintenanceId}:`, error);
throw error;
}
},
/**
* Delete a maintenance AMC date
* @param id - Maintenance AMC date ID
* @returns Success message
*/
delete: async (id: number): Promise<void> => {
try {
await apiRequest<void>(
`/MaintenanceAmcDates/${id}`,
'DELETE',
undefined,
true
);
} catch (error) {
console.error(`Failed to delete maintenance AMC date with ID ${id}:`, error);
throw error;
}
}
};
// Release Dates service
export const releaseDateService = {
getAll: async (): Promise<ReleaseDate[]> => {
return await apiRequest<ReleaseDate[]>('/ReleaseDates');
},
getById: async (id: number): Promise<ReleaseDate> => {
return await apiRequest<ReleaseDate>(`/ReleaseDates/${id}`);
},
getByProjectId: async (projectId: number): Promise<ReleaseDate[]> => {
return await apiRequest<ReleaseDate[]>(`/ReleaseDates/ByProject/${projectId}`);
},
create: async (data: ReleaseDateCreateRequest): Promise<ReleaseDate> => {
return await apiRequest<ReleaseDate>('/ReleaseDates', 'POST', data);
},
update: async (data: ReleaseDateUpdateRequest): Promise<ReleaseDate> => {
return await apiRequest<ReleaseDate>(`/ReleaseDates/${data.releaseId}`, 'PUT', data);
},
delete: async (id: number): Promise<void> => {
return await apiRequest<void>(`/ReleaseDates/${id}`, 'DELETE');
}
};
// Gantt Chart Types
export interface GanttTaskDto {
id: number;
name: string | null;
start: string | null;
end: string | null;
assignee: string | null;
}
export interface GanttFeatureDto {
id: number;
name: string | null;
start: string | null;
end: string | null;
assignee: string | null;
tasks: GanttTaskDto[];
}
export interface GanttDeliverableDto {
id: number;
name: string | null;
start: string | null;
end: string | null;
features: GanttFeatureDto[];
}
export interface GanttChartResponseDto {
deliverables: GanttDeliverableDto[];
}
// Gantt Chart service
export const ganttChartService = {
/**
* Get Gantt chart data by project ID
* @param projectId - Project ID
* @returns Gantt chart data with deliverables, features, and tasks
*/
getByProjectId: async (projectId: number): Promise<GanttChartResponseDto> => {
try {
const response = await apiRequest<GanttChartResponseDto>(
`/GanttChart/project/${projectId}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get Gantt chart data for project ${projectId}:`, error);
throw error;
}
}
};
// Project Hierarchy Types
export interface PMPTask {
taskId: string;
taskName: string;
description: string;
phase: string | null;
owner: string | null;
dependency: string | null;
status: string;
startDate: string;
endDate: string;
estimatedHours: number;
}
export interface PMPFeature {
featureId: number;
featureName: string;
startDate: string | null;
endDate: string | null;
tasks: PMPTask[];
}
export interface PMPDeliverable {
deliverableId: number;
deliverableName: string;
startDate: string | null;
endDate: string | null;
features: PMPFeature[];
}
export interface PMPProject {
projectId: number;
projectCode: string;
projectName: string;
startDate: string;
endDate: string;
status: string | null;
deliverables: PMPDeliverable[];
}
export interface ProjectHierarchyResponse {
project: PMPProject;
}
// Project Hierarchy Service
export const projectHierarchyService = {
/**
* Get project hierarchy by project ID
* @param projectId - Project ID
* @returns Project hierarchy with deliverables, features, and tasks
*/
getByProjectId: async (projectId: number): Promise<ProjectHierarchyResponse> => {
try {
const response = await apiRequest<ProjectHierarchyResponse>(
`/Project/GetProjectHierarchyByProjectId/${projectId}`,
'GET',
undefined,
true
);
return response;
} catch (error) {
console.error(`Failed to get project hierarchy for project ${projectId}:`, error);
throw error;
}
}
};
|