Spaces:
Sleeping
Sleeping
File size: 45,723 Bytes
f10602a dddd6c6 f10602a f978499 f10602a dddd6c6 f10602a 367d57f f10602a 367d57f f10602a dddd6c6 f10602a 367d57f f10602a 367d57f f10602a dddd6c6 | 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 | # Reports API - Frontend Documentation
## Quick Start
```typescript
// 1. Generate a report
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'custom',
date_range: {
start_date: '2025-12-01',
end_date: '2025-12-31'
},
custom_config: {
entity: 'tickets',
columns: ['status', 'priority'],
aggregations: [{ field: 'id', type: 'count', alias: 'count' }],
group_by: ['status', 'priority']
},
project_id: 'your-project-id'
})
});
const data = await response.json();
// Use data.data for your charts/tables
```
---
## Overview
The Reports API provides business intelligence reports with pre-calculated metrics and aggregations. Use this for dashboard analytics, performance tracking, and compliance monitoring.
**Base URL:** `/api/v1/reports`
**Authorization:**
- `view_reports` permission required for viewing
- `export_reports` permission required for CSV downloads
- Available to: PLATFORM_ADMIN, PROJECT_MANAGER, DISPATCHER, SALES_MANAGER
**Key Features:**
- β
Pre-defined reports (SLA, Performance, Financial, Inventory)
- β
Custom reports with flexible configuration
- β
Calculated fields (SLA violations, days to complete)
- β
Aggregations (count, sum, avg, min, max)
- β
CSV export for Excel
- β
Real-time data (no caching)
---
## TypeScript Interfaces
Copy these into your frontend project:
```typescript
// ============================================
// REQUEST TYPES
// ============================================
type ReportType =
| 'sla_compliance'
| 'user_performance'
| 'financial_summary'
| 'inventory_usage'
| 'custom';
type AggregationType = 'count' | 'sum' | 'avg' | 'min' | 'max';
interface DateRange {
start_date: string; // ISO date: "2025-12-01"
end_date: string; // ISO date: "2025-12-31"
}
interface AggregationConfig {
field: string;
type: AggregationType;
alias?: string;
}
interface CustomReportConfig {
entity: 'tickets' | 'timesheets' | 'payroll' | 'expenses' | 'users';
columns: string[];
calculated_fields?: string[];
aggregations?: AggregationConfig[];
group_by?: string[];
additional_filters?: Record<string, any>;
}
interface ReportRequest {
report_type: ReportType;
date_range: DateRange;
project_id?: string;
region_id?: string;
user_id?: string;
status?: string;
limit?: number;
skip?: number;
custom_config?: CustomReportConfig; // Required when report_type = 'custom'
}
// ============================================
// RESPONSE TYPES
// ============================================
interface ReportMeta {
generated_at: string;
record_count: number;
filters_applied: Record<string, any>;
report_type: string;
}
interface ReportResponse<T = any> {
meta: ReportMeta;
data: T[];
}
// Specific row types
interface SLAReportRow {
ticket_id: string;
ticket_number: string;
project_name: string;
ticket_type: string;
priority: string;
status: string;
created_at: string;
due_date: string | null;
completed_at: string | null;
is_violated: boolean;
violation_margin_hours: number;
assigned_agent: string;
customer_name: string;
}
interface UserPerformanceRow {
user_id: string;
user_name: string;
role: string;
tickets_assigned: number;
tickets_completed: number;
completion_rate: number;
total_hours_logged: number;
avg_resolution_time_hours: number;
sla_violations_count: number;
on_time_percentage: number;
}
interface FinancialReportRow {
category: string;
description: string;
date: string;
project_name: string;
amount: number;
status: string;
transaction_type: 'Credit' | 'Debit';
}
interface InventoryUsageRow {
item_name: string;
serial_number: string | null;
category: string;
used_at: string;
ticket_id: string;
project_name: string;
used_by_user: string;
unit_cost: number;
}
// Custom report rows are dynamic
type CustomReportRow = Record<string, any>;
```
---
## Endpoints
### 1. Generate Report (JSON)
Returns report data as JSON for rendering in tables, charts, or dashboards.
```
POST /api/v1/reports/generate
```
**Headers:**
```
Authorization: Bearer {access_token}
Content-Type: application/json
```
**Request Body:**
```typescript
{
report_type: "sla_compliance" | "user_performance" | "financial_summary" | "inventory_usage";
date_range: {
start_date: string; // ISO date: "2025-12-01"
end_date: string; // ISO date: "2025-12-31"
};
project_id?: string; // UUID - optional filter
region_id?: string; // UUID - optional filter
user_id?: string; // UUID - optional filter
status?: string; // optional filter (e.g., "completed", "open")
limit?: number; // pagination limit (default: no limit)
skip?: number; // pagination offset (default: 0)
}
```
**Response (200 OK):**
```typescript
{
meta: {
generated_at: string; // ISO timestamp
record_count: number; // total records returned
filters_applied: object; // echo of filters used
report_type: string; // report type
};
data: Array<ReportRow>; // varies by report type (see below)
}
```
**Error Responses:**
- `401 Unauthorized` - Missing or invalid token
- `403 Forbidden` - User lacks `view_reports` permission
- `500 Internal Server Error` - Report generation failed
---
### 2. Export Report (CSV Download)
Downloads report data as CSV file for Excel or external processing.
```
POST /api/v1/reports/export
```
**Headers:**
```
Authorization: Bearer {access_token}
Content-Type: application/json
```
**Request Body:**
```typescript
{
report_type: "sla_compliance" | "user_performance" | "financial_summary" | "inventory_usage";
date_range: {
start_date: string; // ISO date: "2025-12-01"
end_date: string; // ISO date: "2025-12-31"
};
format?: "csv"; // only CSV supported currently
project_id?: string; // UUID - optional filter
region_id?: string; // UUID - optional filter
user_id?: string; // UUID - optional filter
status?: string; // optional filter
limit?: number; // pagination limit
skip?: number; // pagination offset
}
```
**Response (200 OK):**
- **Content-Type:** `text/csv`
- **Content-Disposition:** `attachment; filename="{report_type}_{timestamp}.csv"`
- **Body:** CSV file with UTF-8 BOM encoding (Excel-compatible)
**Error Responses:**
- `400 Bad Request` - Invalid format (only CSV supported)
- `401 Unauthorized` - Missing or invalid token
- `403 Forbidden` - User lacks `export_reports` permission
- `500 Internal Server Error` - Export failed
---
## Report Types & Data Shapes
### 1. Custom Report (NEW - Fully Configurable)
**Purpose:** Generate any report with flexible column selection, calculated fields, and aggregations
**Report Type:** `"custom"`
**Use Cases:**
- Ad-hoc data analysis
- Custom dashboard widgets
- Flexible reporting for any entity
- Aggregated statistics by any dimension
**Configuration:**
```typescript
{
report_type: "custom",
date_range: {
start_date: "2025-12-01",
end_date: "2025-12-31"
},
custom_config: {
entity: "tickets" | "timesheets" | "payroll" | "expenses" | "users",
columns: string[], // Fields to include
calculated_fields?: string[], // "sla_violated", "days_to_complete", "is_overdue"
aggregations?: Array<{
field: string,
type: "count" | "sum" | "avg" | "min" | "max",
alias?: string
}>,
group_by?: string[], // Group results by these fields
additional_filters?: Record<string, any> // Entity-specific filters
},
project_id?: string,
region_id?: string,
user_id?: string
}
```
**Example 1: Tickets by Status with Counts**
```json
{
"report_type": "custom",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-31"
},
"custom_config": {
"entity": "tickets",
"columns": ["status", "priority"],
"aggregations": [
{
"field": "id",
"type": "count",
"alias": "ticket_count"
}
],
"group_by": ["status", "priority"]
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a"
}
```
**Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T20:00:00Z",
"record_count": 6,
"filters_applied": {...},
"report_type": "custom"
},
"data": [
{
"status": "completed",
"priority": "high",
"ticket_count": 15
},
{
"status": "completed",
"priority": "medium",
"ticket_count": 23
},
{
"status": "open",
"priority": "high",
"ticket_count": 8
}
]
}
```
**Example 2: Detailed Ticket List with Calculated Fields**
```json
{
"report_type": "custom",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-31"
},
"custom_config": {
"entity": "tickets",
"columns": [
"id",
"ticket_name",
"status",
"priority",
"created_at",
"completed_at"
],
"calculated_fields": [
"sla_violated",
"days_to_complete",
"is_overdue"
],
"additional_filters": {
"ticket_type": "installation"
}
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a",
"limit": 50
}
```
**Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T20:00:00Z",
"record_count": 50,
"filters_applied": {...},
"report_type": "custom"
},
"data": [
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"ticket_name": "Install fiber at ABC Corp",
"status": "completed",
"priority": "high",
"created_at": "2025-12-01T10:00:00Z",
"completed_at": "2025-12-04T15:30:00Z",
"sla_violated": false,
"days_to_complete": 3,
"is_overdue": false
}
]
}
```
**Example 3: Payroll Summary by User**
```json
{
"report_type": "custom",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-31"
},
"custom_config": {
"entity": "payroll",
"columns": ["user_id"],
"aggregations": [
{
"field": "total_amount",
"type": "sum",
"alias": "total_paid"
},
{
"field": "days_worked",
"type": "sum",
"alias": "total_days"
},
{
"field": "tickets_closed",
"type": "sum",
"alias": "total_tickets"
}
],
"group_by": ["user_id"]
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a"
}
```
**Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T20:00:00Z",
"record_count": 12,
"filters_applied": {...},
"report_type": "custom"
},
"data": [
{
"user_id": "c3d4e5f6-a7b8-9012-cdef-123456789012",
"total_paid": 45000.0,
"total_days": 20,
"total_tickets": 35
}
]
}
```
**Supported Entities:**
- `tickets` - Work orders/tickets
- `timesheets` - Daily attendance and work logs
- `payroll` - Worker compensation records
- `expenses` - Ticket expenses
- `users` - User records
**Supported Calculated Fields:**
- `sla_violated` - Whether SLA was breached (tickets)
- `days_to_complete` - Days from creation to completion (tickets)
- `is_overdue` - Whether ticket is overdue (tickets)
**Supported Aggregations:**
- `count` - Count records
- `sum` - Sum numeric field
- `avg` - Average of numeric field
- `min` - Minimum value
- `max` - Maximum value
**UI Implementation Tips:**
- Use for custom dashboard widgets
- Allow users to build their own reports
- Combine with date range picker for flexible analysis
- Use aggregations for summary statistics
- Use detailed mode (no aggregations) for drill-down
---
### 2. SLA Compliance Report
**Purpose:** Track ticket completion vs due dates, identify SLA violations
**Report Type:** `"sla_compliance"`
**Use Cases:**
- Dashboard SLA metrics
- Overdue ticket alerts
- Performance monitoring
- Customer satisfaction tracking
**Data Shape:**
```typescript
interface SLAReportRow {
ticket_id: string; // UUID
ticket_number: string; // Display ID (e.g., "TKT-12345")
project_name: string; // Project title
ticket_type: string; // "installation" | "support" | "infrastructure"
priority: string; // "low" | "medium" | "high" | "urgent"
status: string; // "open" | "in_progress" | "completed" | etc.
created_at: string; // ISO timestamp
due_date: string | null; // ISO timestamp
completed_at: string | null; // ISO timestamp
is_violated: boolean; // true if SLA was breached
violation_margin_hours: number; // negative = early, positive = late
assigned_agent: string; // Agent name or "Unassigned"
customer_name: string; // Customer name or "Internal/Infrastructure"
}
```
**Example Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T18:30:00Z",
"record_count": 3,
"filters_applied": {
"report_type": "sla_compliance",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a"
},
"report_type": "sla_compliance"
},
"data": [
{
"ticket_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"ticket_number": "TKT-12345",
"project_name": "Atomio FTTX",
"ticket_type": "installation",
"priority": "high",
"status": "completed",
"created_at": "2025-12-01T10:00:00Z",
"due_date": "2025-12-05T17:00:00Z",
"completed_at": "2025-12-04T15:30:00Z",
"is_violated": false,
"violation_margin_hours": -25.5,
"assigned_agent": "John Doe",
"customer_name": "ABC Corporation"
},
{
"ticket_id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
"ticket_number": "TKT-12346",
"project_name": "Atomio FTTX",
"ticket_type": "support",
"priority": "urgent",
"status": "completed",
"created_at": "2025-12-02T09:00:00Z",
"due_date": "2025-12-03T17:00:00Z",
"completed_at": "2025-12-04T10:00:00Z",
"is_violated": true,
"violation_margin_hours": 17.0,
"assigned_agent": "Jane Smith",
"customer_name": "XYZ Ltd"
}
]
}
```
**UI Implementation Tips:**
- Show `is_violated: true` tickets in red/warning color
- Display `violation_margin_hours` as "X hours late" (positive) or "X hours early" (negative)
- Filter by `priority` for urgent SLA violations
- Sort by `violation_margin_hours` descending to show worst violations first
---
### 2. User Performance Report
**Purpose:** Aggregate worker performance metrics from timesheets
**Report Type:** `"user_performance"`
**Use Cases:**
- Team performance dashboards
- Individual worker reviews
- Productivity tracking
- Resource allocation planning
**Data Shape:**
```typescript
interface UserPerformanceRow {
user_id: string; // UUID
user_name: string; // Full name
role: string; // "field_agent" | "project_manager" | etc.
tickets_assigned: number; // Total tickets assigned
tickets_completed: number; // Total tickets completed
completion_rate: number; // Percentage (0-100)
total_hours_logged: number; // Total hours from timesheets
avg_resolution_time_hours: number; // Average hours per ticket
sla_violations_count: number; // Number of SLA breaches
on_time_percentage: number; // Percentage completed on time (0-100)
}
```
**Example Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T18:30:00Z",
"record_count": 2,
"filters_applied": {
"report_type": "user_performance",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
}
},
"report_type": "user_performance"
},
"data": [
{
"user_id": "c3d4e5f6-a7b8-9012-cdef-123456789012",
"user_name": "John Doe",
"role": "field_agent",
"tickets_assigned": 25,
"tickets_completed": 23,
"completion_rate": 92.0,
"total_hours_logged": 184.5,
"avg_resolution_time_hours": 8.02,
"sla_violations_count": 2,
"on_time_percentage": 91.3
},
{
"user_id": "d4e5f6a7-b8c9-0123-def1-234567890123",
"user_name": "Jane Smith",
"role": "field_agent",
"tickets_assigned": 30,
"tickets_completed": 28,
"completion_rate": 93.33,
"total_hours_logged": 210.0,
"avg_resolution_time_hours": 7.5,
"sla_violations_count": 1,
"on_time_percentage": 96.43
}
]
}
```
**UI Implementation Tips:**
- Show `completion_rate` as progress bar or percentage badge
- Highlight users with `on_time_percentage < 90%` in warning color
- Display `avg_resolution_time_hours` as "X.X hours per ticket"
- Sort by `completion_rate` or `on_time_percentage` for leaderboards
- Use `sla_violations_count` for quality metrics
---
### 3. Financial Summary Report
**Purpose:** Unified ledger of revenue (ProjectFinance) and expenses (TicketExpenses)
**Report Type:** `"financial_summary"`
**Use Cases:**
- Project financial tracking
- Budget monitoring
- Expense approval workflows
- Revenue vs cost analysis
**Data Shape:**
```typescript
interface FinancialReportRow {
category: string; // "General" | "Field Expense" | custom
description: string; // Transaction description
date: string; // ISO date (YYYY-MM-DD)
project_name: string; // Project title
amount: number; // Transaction amount (positive number)
status: string; // "Approved" | "Pending" | "Paid" | etc.
transaction_type: "Credit" | "Debit"; // Credit = revenue, Debit = expense
}
```
**Example Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T18:30:00Z",
"record_count": 4,
"filters_applied": {
"report_type": "financial_summary",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a"
},
"report_type": "financial_summary"
},
"data": [
{
"category": "General",
"description": "Client payment - Invoice #INV-001",
"date": "2025-12-01",
"project_name": "Atomio FTTX",
"amount": 150000.0,
"status": "Paid",
"transaction_type": "Credit"
},
{
"category": "Field Expense",
"description": "transport: Fuel for site visit",
"date": "2025-12-02",
"project_name": "Atomio FTTX",
"amount": 2500.0,
"status": "Approved",
"transaction_type": "Debit"
},
{
"category": "Field Expense",
"description": "materials: Fiber optic cable",
"date": "2025-12-03",
"project_name": "Atomio FTTX",
"amount": 15000.0,
"status": "Approved",
"transaction_type": "Debit"
}
]
}
```
**UI Implementation Tips:**
- Show `transaction_type: "Credit"` in green, `"Debit"` in red
- Calculate running balance: `balance += (Credit - Debit)`
- Group by `category` for expense breakdown charts
- Filter by `status` to show pending approvals
- Sort by `date` descending for recent transactions first
- Sum `amount` by `transaction_type` for totals
---
### 4. Inventory Usage Report
**Purpose:** Track inventory items installed/consumed across tickets
**Report Type:** `"inventory_usage"`
**Use Cases:**
- Inventory consumption tracking
- Cost analysis per project
- Equipment deployment monitoring
- Stock replenishment planning
**Data Shape:**
```typescript
interface InventoryUsageRow {
item_name: string; // Inventory item name
serial_number: string | null; // Serial number if tracked
category: string; // "General" | custom category
used_at: string; // ISO timestamp
ticket_id: string; // UUID of ticket where used
project_name: string; // Project title
used_by_user: string; // User name or "Unknown"
unit_cost: number; // Cost per unit
}
```
**Example Response:**
```json
{
"meta": {
"generated_at": "2025-12-14T18:30:00Z",
"record_count": 3,
"filters_applied": {
"report_type": "inventory_usage",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
},
"project_id": "0ade6bd1-e492-4e25-b681-59f42058d29a"
},
"report_type": "inventory_usage"
},
"data": [
{
"item_name": "ONT Device - Model X200",
"serial_number": "ONT-2025-001234",
"category": "Customer Equipment",
"used_at": "2025-12-02T14:30:00Z",
"ticket_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"project_name": "Atomio FTTX",
"used_by_user": "John Doe",
"unit_cost": 5500.0
},
{
"item_name": "Fiber Optic Cable (100m)",
"serial_number": null,
"category": "Installation Materials",
"used_at": "2025-12-03T10:15:00Z",
"ticket_id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
"project_name": "Atomio FTTX",
"used_by_user": "Jane Smith",
"unit_cost": 12000.0
}
]
}
```
**UI Implementation Tips:**
- Group by `category` for inventory breakdown
- Sum `unit_cost` for total inventory value used
- Link `ticket_id` to ticket detail pages
- Show `serial_number` for trackable equipment
- Filter by `used_by_user` for individual usage tracking
- Sort by `used_at` descending for recent usage
---
## Choosing Between Report Types
### Use Pre-defined Reports When:
- β
You need standard business metrics (SLA compliance, user performance)
- β
You want consistent reporting across the organization
- β
You need optimized queries for common use cases
- β
You want pre-calculated fields and complex joins
**Pre-defined Reports:**
- `sla_compliance` - Ticket SLA tracking
- `user_performance` - Worker productivity metrics
- `financial_summary` - Revenue and expenses ledger
- `inventory_usage` - Equipment deployment tracking
### Use Custom Reports When:
- β
You need flexible column selection
- β
You want to analyze data by custom dimensions
- β
You need aggregations (count, sum, avg) by any field
- β
You want to build ad-hoc reports or custom dashboards
- β
Pre-defined reports don't meet your specific needs
**Custom Report Advantages:**
- Fully configurable columns
- Any entity (tickets, timesheets, payroll, expenses, users)
- Flexible aggregations and grouping
- Calculated fields on demand
- Entity-specific filtering
---
## Common Filters
All report types support these optional filters:
```typescript
interface ReportFilters {
project_id?: string; // Filter by specific project (UUID)
region_id?: string; // Filter by project region (UUID)
user_id?: string; // Filter by specific user (UUID)
status?: string; // Filter by status (varies by report type)
limit?: number; // Pagination: max records to return
skip?: number; // Pagination: records to skip
}
```
**Filter Behavior:**
- All filters are optional (omit for all data)
- Multiple filters are combined with AND logic
- `limit` and `skip` enable pagination for large datasets
- Managers automatically see only their project data (authorization-filtered)
---
## Error Handling
**Common Error Response Format:**
```typescript
{
detail: string; // Human-readable error message
}
```
**Error Scenarios:**
**401 Unauthorized:**
```json
{
"detail": "Not authenticated"
}
```
**403 Forbidden:**
```json
{
"detail": "User does not have permission to view reports"
}
```
**500 Internal Server Error:**
```json
{
"detail": "Report generation failed: [error details]"
}
```
---
## Frontend Implementation Guide
### React Hook Example
```typescript
// hooks/useReports.ts
import { useState } from 'react';
import { ReportRequest, ReportResponse } from '@/types/reports';
export const useReports = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const generateReport = async <T = any>(
request: ReportRequest
): Promise<ReportResponse<T> | null> => {
setLoading(true);
setError(null);
try {
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to generate report');
}
const data = await response.json();
return data;
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
return null;
} finally {
setLoading(false);
}
};
const exportReport = async (request: ReportRequest) => {
setLoading(true);
setError(null);
try {
const response = await fetch('/api/v1/reports/export', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
if (!response.ok) {
throw new Error('Failed to export report');
}
// Trigger download
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `report_${Date.now()}.csv`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
};
return { generateReport, exportReport, loading, error };
};
```
### React Component Example
```typescript
// components/TicketStatusChart.tsx
import { useEffect, useState } from 'react';
import { useReports } from '@/hooks/useReports';
import { CustomReportRow } from '@/types/reports';
interface Props {
projectId: string;
startDate: string;
endDate: string;
}
export const TicketStatusChart: React.FC<Props> = ({
projectId,
startDate,
endDate
}) => {
const { generateReport, loading, error } = useReports();
const [data, setData] = useState<CustomReportRow[]>([]);
useEffect(() => {
const fetchData = async () => {
const result = await generateReport<CustomReportRow>({
report_type: 'custom',
date_range: { start_date: startDate, end_date: endDate },
project_id: projectId,
custom_config: {
entity: 'tickets',
columns: ['status', 'priority'],
aggregations: [
{ field: 'id', type: 'count', alias: 'count' }
],
group_by: ['status', 'priority']
}
});
if (result) {
setData(result.data);
}
};
fetchData();
}, [projectId, startDate, endDate]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h3>Tickets by Status</h3>
{data.map((row, idx) => (
<div key={idx}>
{row.status} ({row.priority}): {row.count} tickets
</div>
))}
</div>
);
};
```
### Vue Composable Example
```typescript
// composables/useReports.ts
import { ref } from 'vue';
import type { ReportRequest, ReportResponse } from '@/types/reports';
export const useReports = () => {
const loading = ref(false);
const error = ref<string | null>(null);
const generateReport = async <T = any>(
request: ReportRequest
): Promise<ReportResponse<T> | null> => {
loading.value = true;
error.value = null;
try {
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to generate report');
}
return await response.json();
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error';
return null;
} finally {
loading.value = false;
}
};
const exportReport = async (request: ReportRequest) => {
loading.value = true;
error.value = null;
try {
const response = await fetch('/api/v1/reports/export', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
if (!response.ok) {
throw new Error('Failed to export report');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `report_${Date.now()}.csv`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error';
} finally {
loading.value = false;
}
};
return { generateReport, exportReport, loading, error };
};
```
### API Service Class (Framework Agnostic)
```typescript
// services/reportsService.ts
import { ReportRequest, ReportResponse } from '@/types/reports';
class ReportsService {
private baseUrl = '/api/v1/reports';
private getHeaders() {
return {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
};
}
async generate<T = any>(request: ReportRequest): Promise<ReportResponse<T>> {
const response = await fetch(`${this.baseUrl}/generate`, {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(request)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to generate report');
}
return response.json();
}
async export(request: ReportRequest): Promise<void> {
const response = await fetch(`${this.baseUrl}/export`, {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(request)
});
if (!response.ok) {
throw new Error('Failed to export report');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `report_${Date.now()}.csv`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
// Helper: Generate SLA report
async getSLAReport(projectId: string, startDate: string, endDate: string) {
return this.generate({
report_type: 'sla_compliance',
date_range: { start_date: startDate, end_date: endDate },
project_id: projectId
});
}
// Helper: Generate custom aggregation report
async getAggregationReport(
entity: string,
columns: string[],
aggregations: any[],
groupBy: string[],
filters: any
) {
return this.generate({
report_type: 'custom',
date_range: filters.date_range,
project_id: filters.project_id,
custom_config: {
entity,
columns,
aggregations,
group_by: groupBy
}
});
}
}
export const reportsService = new ReportsService();
```
### 1. Report Dashboard Page
```typescript
// Example: Fetch SLA Compliance Report
const fetchSLAReport = async (projectId: string, startDate: string, endDate: string) => {
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'sla_compliance',
date_range: {
start_date: startDate,
end_date: endDate
},
project_id: projectId
})
});
if (!response.ok) {
throw new Error('Failed to fetch report');
}
return await response.json();
};
```
### 2. CSV Export Button
```typescript
// Example: Download CSV Export
const downloadReport = async (reportType: string, filters: any) => {
const response = await fetch('/api/v1/reports/export', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: reportType,
...filters
})
});
if (!response.ok) {
throw new Error('Failed to export report');
}
// Trigger download
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${reportType}_${new Date().toISOString()}.csv`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
};
```
### 3. Date Range Picker
```typescript
// Example: Default to current week
const getDefaultDateRange = () => {
const today = new Date();
const monday = new Date(today);
monday.setDate(today.getDate() - today.getDay() + 1);
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
return {
start_date: monday.toISOString().split('T')[0],
end_date: sunday.toISOString().split('T')[0]
};
};
```
### 4. Report Type Selector
```typescript
const reportTypes = [
{ value: 'sla_compliance', label: 'SLA Compliance', icon: 'β±οΈ' },
{ value: 'user_performance', label: 'User Performance', icon: 'π' },
{ value: 'financial_summary', label: 'Financial Summary', icon: 'π°' },
{ value: 'inventory_usage', label: 'Inventory Usage', icon: 'π¦' }
];
```
---
## Performance Notes
- Reports are designed for **sub-2 second** response times
- Use `limit` and `skip` for pagination on large datasets
- User Performance report uses aggregated timesheet data (fast)
- SLA Compliance may be slower for large date ranges (complex joins)
- Consider caching report results for frequently-accessed data
---
## Custom Report Examples
### Example 1: Ticket Status Dashboard
**Goal:** Show ticket counts by status and priority for current month
```typescript
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'custom',
date_range: {
start_date: '2025-12-01',
end_date: '2025-12-31'
},
custom_config: {
entity: 'tickets',
columns: ['status', 'priority'],
aggregations: [
{ field: 'id', type: 'count', alias: 'count' }
],
group_by: ['status', 'priority']
},
project_id: projectId
})
});
// Use for stacked bar chart or heatmap
```
### Example 2: Worker Performance Leaderboard
**Goal:** Rank workers by tickets completed this week
```typescript
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'custom',
date_range: {
start_date: '2025-12-08',
end_date: '2025-12-14'
},
custom_config: {
entity: 'timesheets',
columns: ['user_id'],
aggregations: [
{ field: 'tickets_completed', type: 'sum', alias: 'total_completed' },
{ field: 'hours_worked', type: 'sum', alias: 'total_hours' }
],
group_by: ['user_id']
},
project_id: projectId
})
});
// Sort by total_completed descending for leaderboard
```
### Example 3: Expense Analysis by Category
**Goal:** Breakdown expenses by type for budget tracking
```typescript
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'custom',
date_range: {
start_date: '2025-12-01',
end_date: '2025-12-31'
},
custom_config: {
entity: 'expenses',
columns: ['expense_type'],
aggregations: [
{ field: 'total_cost', type: 'sum', alias: 'total_amount' },
{ field: 'id', type: 'count', alias: 'expense_count' }
],
group_by: ['expense_type'],
additional_filters: {
is_approved: true
}
},
project_id: projectId
})
});
// Use for pie chart or expense breakdown table
```
### Example 4: Overdue Tickets Report
**Goal:** List all overdue tickets with details
```typescript
const response = await fetch('/api/v1/reports/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
report_type: 'custom',
date_range: {
start_date: '2025-01-01',
end_date: '2025-12-31'
},
custom_config: {
entity: 'tickets',
columns: [
'id',
'ticket_name',
'priority',
'status',
'due_date',
'created_at'
],
calculated_fields: ['is_overdue', 'days_to_complete'],
additional_filters: {
status: 'open'
}
},
project_id: projectId
})
});
// Filter client-side for is_overdue === true
// Sort by due_date ascending
```
---
## Testing
**Test with cURL:**
```bash
# Generate SLA Report
curl -X POST "http://localhost:7860/api/v1/reports/generate" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"report_type": "sla_compliance",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
}
}'
# Generate Custom Report
curl -X POST "http://localhost:7860/api/v1/reports/generate" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"report_type": "custom",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
},
"custom_config": {
"entity": "tickets",
"columns": ["status", "priority"],
"aggregations": [
{"field": "id", "type": "count", "alias": "count"}
],
"group_by": ["status", "priority"]
}
}'
# Export to CSV
curl -X POST "http://localhost:7860/api/v1/reports/export" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"report_type": "user_performance",
"date_range": {
"start_date": "2025-12-01",
"end_date": "2025-12-14"
}
}' \
--output report.csv
```
---
## Questions?
Contact the backend team or check:
- API Swagger docs: `/docs`
- Source code: `src/app/api/v1/reports.py`
- Service logic: `src/app/services/report_service.py`
---
## Common Integration Patterns
### Pattern 1: Dashboard Widget with Auto-Refresh
```typescript
// Auto-refresh every 5 minutes
useEffect(() => {
const fetchData = async () => {
const result = await reportsService.generate({
report_type: 'custom',
date_range: { start_date: startDate, end_date: endDate },
project_id: projectId,
custom_config: {
entity: 'tickets',
columns: ['status'],
aggregations: [{ field: 'id', type: 'count', alias: 'count' }],
group_by: ['status']
}
});
setData(result.data);
};
fetchData();
const interval = setInterval(fetchData, 5 * 60 * 1000);
return () => clearInterval(interval);
}, [projectId, startDate, endDate]);
```
### Pattern 2: Report Builder UI
```typescript
interface ReportBuilderState {
entity: string;
selectedColumns: string[];
aggregations: AggregationConfig[];
groupBy: string[];
filters: Record<string, any>;
}
const ReportBuilder = () => {
const [config, setConfig] = useState<ReportBuilderState>({
entity: 'tickets',
selectedColumns: [],
aggregations: [],
groupBy: [],
filters: {}
});
const handleGenerate = async () => {
const result = await reportsService.generate({
report_type: 'custom',
date_range: config.filters.date_range,
project_id: config.filters.project_id,
custom_config: {
entity: config.entity,
columns: config.selectedColumns,
aggregations: config.aggregations,
group_by: config.groupBy
}
});
// Display result
};
return (
<div>
<EntitySelector value={config.entity} onChange={...} />
<ColumnSelector columns={config.selectedColumns} onChange={...} />
<AggregationBuilder aggregations={config.aggregations} onChange={...} />
<button onClick={handleGenerate}>Generate Report</button>
</div>
);
};
```
### Pattern 3: Cached Reports with React Query
```typescript
import { useQuery } from '@tanstack/react-query';
const useTicketStatusReport = (projectId: string, dateRange: DateRange) => {
return useQuery({
queryKey: ['report', 'ticket-status', projectId, dateRange],
queryFn: () => reportsService.generate({
report_type: 'custom',
date_range: dateRange,
project_id: projectId,
custom_config: {
entity: 'tickets',
columns: ['status', 'priority'],
aggregations: [{ field: 'id', type: 'count', alias: 'count' }],
group_by: ['status', 'priority']
}
}),
staleTime: 5 * 60 * 1000, // 5 minutes
cacheTime: 10 * 60 * 1000 // 10 minutes
});
};
// Usage
const { data, isLoading, error } = useTicketStatusReport(projectId, dateRange);
```
### Pattern 4: Export with Loading State
```typescript
const ExportButton = ({ reportConfig }: { reportConfig: ReportRequest }) => {
const [exporting, setExporting] = useState(false);
const handleExport = async () => {
setExporting(true);
try {
await reportsService.export(reportConfig);
toast.success('Report exported successfully');
} catch (error) {
toast.error('Failed to export report');
} finally {
setExporting(false);
}
};
return (
<button onClick={handleExport} disabled={exporting}>
{exporting ? 'Exporting...' : 'Export to CSV'}
</button>
);
};
```
---
## Troubleshooting
### Issue: 403 Forbidden
**Cause:** User lacks `view_reports` or `export_reports` permission
**Solution:** Check user role - only PLATFORM_ADMIN, PROJECT_MANAGER, DISPATCHER, SALES_MANAGER have access
### Issue: 422 Validation Error
**Cause:** Invalid request body (missing required fields, wrong date format)
**Solution:**
- Ensure `date_range` has both `start_date` and `end_date`
- Use ISO date format: "YYYY-MM-DD"
- For custom reports, ensure `custom_config` is provided
### Issue: 500 Internal Server Error
**Cause:** Report generation failed (database error, invalid entity, etc.)
**Solution:**
- Check entity name is valid (tickets, timesheets, payroll, expenses, users)
- Verify column names exist for the entity
- Check aggregation field names are valid
- Review browser console for detailed error message
### Issue: Empty Data Array
**Cause:** No records match the filters
**Solution:**
- Expand date range
- Remove or adjust filters
- Check if project has data for the selected period
### Issue: Slow Report Generation
**Cause:** Large dataset or complex aggregations
**Solution:**
- Use pagination (`limit` and `skip`)
- Narrow date range
- Add more specific filters (project_id, region_id)
- Consider caching results
---
## Best Practices
### 1. Always Handle Errors
```typescript
try {
const result = await reportsService.generate(request);
setData(result.data);
} catch (error) {
console.error('Report generation failed:', error);
showErrorToast(error.message);
}
```
### 2. Use Pagination for Large Datasets
```typescript
const request: ReportRequest = {
report_type: 'custom',
date_range: { start_date, end_date },
limit: 100, // Fetch 100 records at a time
skip: page * 100, // Offset for pagination
custom_config: { ... }
};
```
### 3. Cache Report Results
```typescript
// Use React Query, SWR, or simple state management
const cacheKey = `report_${reportType}_${projectId}_${startDate}_${endDate}`;
const cached = localStorage.getItem(cacheKey);
if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
return JSON.parse(cached.data);
}
```
### 4. Show Loading States
```typescript
{loading && <Spinner />}
{error && <ErrorMessage message={error} />}
{data && <ReportTable data={data} />}
```
### 5. Validate Dates Before Sending
```typescript
const validateDateRange = (start: string, end: string) => {
const startDate = new Date(start);
const endDate = new Date(end);
if (startDate > endDate) {
throw new Error('Start date must be before end date');
}
if (endDate > new Date()) {
throw new Error('End date cannot be in the future');
}
};
```
---
## Questions?
Contact the backend team or check:
- API Swagger docs: `/docs`
- Source code: `src/app/api/v1/reports.py`
- Service logic: `src/app/services/report_service.py`
- Feature docs: `docs/api/reports/CUSTOM_REPORTS_FEATURE.md`
|