Compare commits

..
Author SHA1 Message Date
James Brunton f1f8c52b00 Redesign tsconfig.json files 2025-10-30 16:59:44 +00:00
James BruntonandGitHub 8060934ee9 Add linting to ensure correct imports style is used (#4759)
# Description of Changes
Add linting to ensure correct imports style is used.

I've disabled the linting for two imports which use relative paths
because the files they're importing are siblings to core and
proprietary. They could probs be imported by `@app/../assets/xxx` but it
seems silly. The other thing we could do is add an explicit `@assets`
path alias or something, but it seemed more complex than just disabling
the lint for those two imports at this stage. We could always do it in
the future if we want to import stuff up there a lot in the future.
2025-10-29 11:58:04 +00:00
James BruntonandGitHub ef177be918 Fix issues with fullscreen tools on Safari (#4757)
# Description of Changes
Fix issues with fullscreen tools not rendering and throwing SVG errors
in the console on Safari.
2025-10-29 09:56:16 +00:00
68 changed files with 338 additions and 5885 deletions
@@ -366,10 +366,6 @@ public class ApplicationProperties {
private String fileUploadLimit;
private TempFileManagement tempFileManagement = new TempFileManagement();
private List<String> corsAllowedOrigins = new ArrayList<>();
private String
frontendUrl; // Base URL for frontend (used for invite links, etc.). If not set,
// falls back to backend URL.
public boolean isAnalyticsEnabled() {
return this.getEnableAnalytics() != null && this.getEnableAnalytics();
@@ -553,7 +549,6 @@ public class ApplicationProperties {
public static class Mail {
private boolean enabled;
private boolean enableInvites = false;
private int inviteLinkExpiryHours = 72; // Default: 72 hours (3 days)
private String host;
private int port;
private String username;
@@ -62,10 +62,8 @@ public class ConfigController {
// Security settings
configData.put("enableLogin", applicationProperties.getSecurity().getEnableLogin());
// Mail settings - check both SMTP enabled AND invites enabled
boolean smtpEnabled = applicationProperties.getMail().isEnabled();
boolean invitesEnabled = applicationProperties.getMail().isEnableInvites();
configData.put("enableEmailInvites", smtpEnabled && invitesEnabled);
// Mail settings
configData.put("enableEmailInvites", applicationProperties.getMail().isEnableInvites());
// Check if user is admin using UserServiceInterface
boolean isAdmin = false;
@@ -1,15 +1,17 @@
package stirling.software.proprietary.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/** Configuration to enable scheduling for the audit system. */
/** Configuration to explicitly enable JPA repositories and scheduling for the audit system. */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "stirling.software.proprietary.repository")
@EnableScheduling
public class AuditJpaConfig {
// This configuration enables scheduling for audit cleanup tasks
// JPA repositories are now managed by DatabaseConfig to avoid conflicts
// This configuration enables JPA repositories in the specified package
// and enables scheduling for audit cleanup tasks
// No additional beans or methods needed
}
@@ -1,434 +0,0 @@
package stirling.software.proprietary.controller.api;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.ProprietaryUiDataApi;
import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.model.security.PersistentAuditEvent;
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
/** REST API controller for audit data used by React frontend. */
@Slf4j
@ProprietaryUiDataApi
@PreAuthorize("hasRole('ADMIN')")
@RequiredArgsConstructor
@EnterpriseEndpoint
public class AuditRestController {
private final PersistentAuditEventRepository auditRepository;
private final ObjectMapper objectMapper;
/**
* Get audit events with pagination and filters. Maps to frontend's getEvents() call.
*
* @param page Page number (0-indexed)
* @param pageSize Number of items per page
* @param eventType Filter by event type
* @param username Filter by username (principal)
* @param startDate Filter start date
* @param endDate Filter end date
* @return Paginated audit events response
*/
@GetMapping("/audit-events")
public ResponseEntity<AuditEventsResponse> getAuditEvents(
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "pageSize", defaultValue = "30") int pageSize,
@RequestParam(value = "eventType", required = false) String eventType,
@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate) {
Pageable pageable = PageRequest.of(page, pageSize, Sort.by("timestamp").descending());
Page<PersistentAuditEvent> events;
// Apply filters based on provided parameters
if (eventType != null && username != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events =
auditRepository.findByPrincipalAndTypeAndTimestampBetween(
username, eventType, start, end, pageable);
} else if (eventType != null && username != null) {
events = auditRepository.findByPrincipalAndType(username, eventType, pageable);
} else if (eventType != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events = auditRepository.findByTypeAndTimestampBetween(eventType, start, end, pageable);
} else if (username != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events =
auditRepository.findByPrincipalAndTimestampBetween(
username, start, end, pageable);
} else if (startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events = auditRepository.findByTimestampBetween(start, end, pageable);
} else if (eventType != null) {
events = auditRepository.findByType(eventType, pageable);
} else if (username != null) {
events = auditRepository.findByPrincipal(username, pageable);
} else {
events = auditRepository.findAll(pageable);
}
// Convert to response format expected by frontend
List<AuditEventDto> eventDtos =
events.getContent().stream().map(this::convertToDto).collect(Collectors.toList());
AuditEventsResponse response =
AuditEventsResponse.builder()
.events(eventDtos)
.totalEvents((int) events.getTotalElements())
.page(events.getNumber())
.pageSize(events.getSize())
.totalPages(events.getTotalPages())
.build();
return ResponseEntity.ok(response);
}
/**
* Get chart data for dashboard. Maps to frontend's getChartsData() call.
*
* @param period Time period for charts (day/week/month)
* @return Chart data for events by type, user, and over time
*/
@GetMapping("/audit-charts")
public ResponseEntity<AuditChartsData> getAuditCharts(
@RequestParam(value = "period", defaultValue = "week") String period) {
// Calculate days based on period
int days;
switch (period.toLowerCase()) {
case "day":
days = 1;
break;
case "month":
days = 30;
break;
case "week":
default:
days = 7;
break;
}
// Get events from the specified period
Instant startDate = Instant.now().minus(java.time.Duration.ofDays(days));
List<PersistentAuditEvent> events = auditRepository.findByTimestampAfter(startDate);
// Count events by type
Map<String, Long> eventsByType =
events.stream()
.collect(
Collectors.groupingBy(
PersistentAuditEvent::getType, Collectors.counting()));
// Count events by principal (user)
Map<String, Long> eventsByUser =
events.stream()
.collect(
Collectors.groupingBy(
PersistentAuditEvent::getPrincipal, Collectors.counting()));
// Count events by day
Map<String, Long> eventsByDay =
events.stream()
.collect(
Collectors.groupingBy(
e ->
LocalDateTime.ofInstant(
e.getTimestamp(),
ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_LOCAL_DATE),
Collectors.counting()));
// Convert to ChartData format
ChartData eventsByTypeChart =
ChartData.builder()
.labels(new ArrayList<>(eventsByType.keySet()))
.values(
eventsByType.values().stream()
.map(Long::intValue)
.collect(Collectors.toList()))
.build();
ChartData eventsByUserChart =
ChartData.builder()
.labels(new ArrayList<>(eventsByUser.keySet()))
.values(
eventsByUser.values().stream()
.map(Long::intValue)
.collect(Collectors.toList()))
.build();
// Sort events by day for time series
TreeMap<String, Long> sortedEventsByDay = new TreeMap<>(eventsByDay);
ChartData eventsOverTimeChart =
ChartData.builder()
.labels(new ArrayList<>(sortedEventsByDay.keySet()))
.values(
sortedEventsByDay.values().stream()
.map(Long::intValue)
.collect(Collectors.toList()))
.build();
AuditChartsData chartsData =
AuditChartsData.builder()
.eventsByType(eventsByTypeChart)
.eventsByUser(eventsByUserChart)
.eventsOverTime(eventsOverTimeChart)
.build();
return ResponseEntity.ok(chartsData);
}
/**
* Get available event types for filtering. Maps to frontend's getEventTypes() call.
*
* @return List of unique event types
*/
@GetMapping("/audit-event-types")
public ResponseEntity<List<String>> getEventTypes() {
// Get distinct event types from the database
List<String> dbTypes = auditRepository.findDistinctEventTypes();
// Include standard enum types in case they're not in the database yet
List<String> enumTypes =
Arrays.stream(AuditEventType.values())
.map(AuditEventType::name)
.collect(Collectors.toList());
// Combine both sources, remove duplicates, and sort
Set<String> combinedTypes = new HashSet<>();
combinedTypes.addAll(dbTypes);
combinedTypes.addAll(enumTypes);
List<String> result = combinedTypes.stream().sorted().collect(Collectors.toList());
return ResponseEntity.ok(result);
}
/**
* Get list of users for filtering. Maps to frontend's getUsers() call.
*
* @return List of unique usernames
*/
@GetMapping("/audit-users")
public ResponseEntity<List<String>> getUsers() {
// Use the countByPrincipal query to get unique principals
List<Object[]> principalCounts = auditRepository.countByPrincipal();
List<String> users =
principalCounts.stream()
.map(arr -> (String) arr[0])
.sorted()
.collect(Collectors.toList());
return ResponseEntity.ok(users);
}
/**
* Export audit data in CSV or JSON format. Maps to frontend's exportData() call.
*
* @param format Export format (csv or json)
* @param eventType Filter by event type
* @param username Filter by username
* @param startDate Filter start date
* @param endDate Filter end date
* @return File download response
*/
@GetMapping("/audit-export")
public ResponseEntity<byte[]> exportAuditData(
@RequestParam(value = "format", defaultValue = "csv") String format,
@RequestParam(value = "eventType", required = false) String eventType,
@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate) {
// Get data with same filtering as getAuditEvents
List<PersistentAuditEvent> events;
if (eventType != null && username != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events =
auditRepository.findAllByPrincipalAndTypeAndTimestampBetweenForExport(
username, eventType, start, end);
} else if (eventType != null && username != null) {
events = auditRepository.findAllByPrincipalAndTypeForExport(username, eventType);
} else if (eventType != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events =
auditRepository.findAllByTypeAndTimestampBetweenForExport(
eventType, start, end);
} else if (username != null && startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events =
auditRepository.findAllByPrincipalAndTimestampBetweenForExport(
username, start, end);
} else if (startDate != null && endDate != null) {
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
events = auditRepository.findAllByTimestampBetweenForExport(start, end);
} else if (eventType != null) {
events = auditRepository.findByTypeForExport(eventType);
} else if (username != null) {
events = auditRepository.findAllByPrincipalForExport(username);
} else {
events = auditRepository.findAll();
}
// Export based on format
if ("json".equalsIgnoreCase(format)) {
return exportAsJson(events);
} else {
return exportAsCsv(events);
}
}
// Helper methods
private AuditEventDto convertToDto(PersistentAuditEvent event) {
// Parse the JSON data field if present
Map<String, Object> details = new HashMap<>();
if (event.getData() != null && !event.getData().isEmpty()) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> parsed = objectMapper.readValue(event.getData(), Map.class);
details = parsed;
} catch (JsonProcessingException e) {
log.warn("Failed to parse audit event data as JSON: {}", event.getData());
details.put("rawData", event.getData());
}
}
return AuditEventDto.builder()
.id(String.valueOf(event.getId()))
.timestamp(event.getTimestamp().toString())
.eventType(event.getType())
.username(event.getPrincipal())
.ipAddress((String) details.getOrDefault("ipAddress", "")) // Extract if available
.details(details)
.build();
}
private ResponseEntity<byte[]> exportAsCsv(List<PersistentAuditEvent> events) {
StringBuilder csv = new StringBuilder();
csv.append("ID,Principal,Type,Timestamp,Data\n");
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
for (PersistentAuditEvent event : events) {
csv.append(event.getId()).append(",");
csv.append(escapeCSV(event.getPrincipal())).append(",");
csv.append(escapeCSV(event.getType())).append(",");
csv.append(formatter.format(event.getTimestamp())).append(",");
csv.append(escapeCSV(event.getData())).append("\n");
}
byte[] csvBytes = csv.toString().getBytes();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "audit_export.csv");
return ResponseEntity.ok().headers(headers).body(csvBytes);
}
private ResponseEntity<byte[]> exportAsJson(List<PersistentAuditEvent> events) {
try {
byte[] jsonBytes = objectMapper.writeValueAsBytes(events);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setContentDispositionFormData("attachment", "audit_export.json");
return ResponseEntity.ok().headers(headers).body(jsonBytes);
} catch (JsonProcessingException e) {
log.error("Error serializing audit events to JSON", e);
return ResponseEntity.internalServerError().build();
}
}
private String escapeCSV(String field) {
if (field == null) {
return "";
}
// Replace double quotes with two double quotes and wrap in quotes
return "\"" + field.replace("\"", "\"\"") + "\"";
}
// DTOs for response formatting
@lombok.Data
@lombok.Builder
public static class AuditEventsResponse {
private List<AuditEventDto> events;
private int totalEvents;
private int page;
private int pageSize;
private int totalPages;
}
@lombok.Data
@lombok.Builder
public static class AuditEventDto {
private String id;
private String timestamp;
private String eventType;
private String username;
private String ipAddress;
private Map<String, Object> details;
}
@lombok.Data
@lombok.Builder
public static class AuditChartsData {
private ChartData eventsByType;
private ChartData eventsByUser;
private ChartData eventsOverTime;
}
@lombok.Data
@lombok.Builder
public static class ChartData {
private List<String> labels;
private List<Integer> values;
}
}
@@ -39,7 +39,6 @@ import stirling.software.proprietary.audit.AuditLevel;
import stirling.software.proprietary.config.AuditConfigurationProperties;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.model.dto.TeamWithUserCountDTO;
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
import stirling.software.proprietary.security.database.repository.SessionRepository;
import stirling.software.proprietary.security.database.repository.UserRepository;
@@ -51,7 +50,6 @@ import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrin
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@Slf4j
@ProprietaryUiDataApi
@@ -66,8 +64,6 @@ public class ProprietaryUIDataController {
private final DatabaseService databaseService;
private final boolean runningEE;
private final ObjectMapper objectMapper;
private final UserLicenseSettingsService licenseSettingsService;
private final PersistentAuditEventRepository auditRepository;
public ProprietaryUIDataController(
ApplicationProperties applicationProperties,
@@ -78,9 +74,7 @@ public class ProprietaryUIDataController {
SessionRepository sessionRepository,
DatabaseService databaseService,
ObjectMapper objectMapper,
@Qualifier("runningEE") boolean runningEE,
UserLicenseSettingsService licenseSettingsService,
PersistentAuditEventRepository auditRepository) {
@Qualifier("runningEE") boolean runningEE) {
this.applicationProperties = applicationProperties;
this.auditConfig = auditConfig;
this.sessionPersistentRegistry = sessionPersistentRegistry;
@@ -90,8 +84,6 @@ public class ProprietaryUIDataController {
this.databaseService = databaseService;
this.objectMapper = objectMapper;
this.runningEE = runningEE;
this.licenseSettingsService = licenseSettingsService;
this.auditRepository = auditRepository;
}
@GetMapping("/audit-dashboard")
@@ -270,13 +262,6 @@ public class ProprietaryUIDataController {
.filter(team -> !team.getName().equals(TeamService.INTERNAL_TEAM_NAME))
.toList();
// Calculate license limits
int maxAllowedUsers = licenseSettingsService.calculateMaxAllowedUsers();
long availableSlots = licenseSettingsService.getAvailableUserSlots();
int grandfatheredCount = licenseSettingsService.getDisplayGrandfatheredCount();
int licenseMaxUsers = licenseSettingsService.getSettings().getLicenseMaxUsers();
boolean premiumEnabled = applicationProperties.getPremium().isEnabled();
AdminSettingsData data = new AdminSettingsData();
data.setUsers(sortedUsers);
data.setCurrentUsername(authentication.getName());
@@ -288,11 +273,6 @@ public class ProprietaryUIDataController {
data.setDisabledUsers(disabledUsers);
data.setTeams(allTeams);
data.setMaxPaidUsers(applicationProperties.getPremium().getMaxUsers());
data.setMaxAllowedUsers(maxAllowedUsers);
data.setAvailableSlots(availableSlots);
data.setGrandfatheredUserCount(grandfatheredCount);
data.setLicenseMaxUsers(licenseMaxUsers);
data.setPremiumEnabled(premiumEnabled);
return ResponseEntity.ok(data);
}
@@ -465,11 +445,6 @@ public class ProprietaryUIDataController {
private int disabledUsers;
private List<Team> teams;
private int maxPaidUsers;
private int maxAllowedUsers;
private long availableSlots;
private int grandfatheredUserCount;
private int licenseMaxUsers;
private boolean premiumEnabled;
}
@Data
@@ -1,236 +0,0 @@
package stirling.software.proprietary.controller.api;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.ProprietaryUiDataApi;
import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.model.security.PersistentAuditEvent;
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
/** REST API controller for usage analytics data used by React frontend. */
@Slf4j
@ProprietaryUiDataApi
@PreAuthorize("hasRole('ADMIN')")
@RequiredArgsConstructor
@EnterpriseEndpoint
public class UsageRestController {
private final PersistentAuditEventRepository auditRepository;
private final ObjectMapper objectMapper;
/**
* Get endpoint statistics derived from audit events. This endpoint analyzes HTTP_REQUEST audit
* events to generate usage statistics.
*
* @param limit Optional limit on number of endpoints to return
* @param dataType Type of data to include: "all" (default), "api" (API endpoints excluding
* auth), or "ui" (non-API endpoints)
* @return Endpoint statistics response
*/
@GetMapping("/usage-endpoint-statistics")
public ResponseEntity<EndpointStatisticsResponse> getEndpointStatistics(
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "dataType", defaultValue = "all") String dataType) {
// Get all HTTP_REQUEST audit events
List<PersistentAuditEvent> httpEvents =
auditRepository.findByTypeForExport(AuditEventType.HTTP_REQUEST.name());
// Count visits per endpoint
Map<String, Long> endpointCounts = new HashMap<>();
for (PersistentAuditEvent event : httpEvents) {
String endpoint = extractEndpointFromAuditData(event.getData());
if (endpoint != null) {
// Apply data type filter
if (!shouldIncludeEndpoint(endpoint, dataType)) {
continue;
}
endpointCounts.merge(endpoint, 1L, Long::sum);
}
}
// Calculate totals
long totalVisits = endpointCounts.values().stream().mapToLong(Long::longValue).sum();
int totalEndpoints = endpointCounts.size();
// Convert to list and sort by visit count (descending)
List<EndpointStatistic> statistics =
endpointCounts.entrySet().stream()
.map(
entry -> {
String endpoint = entry.getKey();
long visits = entry.getValue();
double percentage =
totalVisits > 0 ? (visits * 100.0 / totalVisits) : 0.0;
return EndpointStatistic.builder()
.endpoint(endpoint)
.visits((int) visits)
.percentage(Math.round(percentage * 10.0) / 10.0)
.build();
})
.sorted(Comparator.comparingInt(EndpointStatistic::getVisits).reversed())
.collect(Collectors.toList());
// Apply limit if specified
if (limit != null && limit > 0 && statistics.size() > limit) {
statistics = statistics.subList(0, limit);
}
EndpointStatisticsResponse response =
EndpointStatisticsResponse.builder()
.endpoints(statistics)
.totalEndpoints(totalEndpoints)
.totalVisits((int) totalVisits)
.build();
return ResponseEntity.ok(response);
}
/**
* Extract the endpoint path from the audit event's data field. The data field contains JSON
* with an "endpoint" or "path" key.
*
* @param dataJson JSON string from audit event
* @return Endpoint path or null if not found
*/
private String extractEndpointFromAuditData(String dataJson) {
if (dataJson == null || dataJson.isEmpty()) {
return null;
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> data = objectMapper.readValue(dataJson, Map.class);
// Try common keys for endpoint path
Object endpoint = data.get("endpoint");
if (endpoint != null) {
return normalizeEndpoint(endpoint.toString());
}
Object path = data.get("path");
if (path != null) {
return normalizeEndpoint(path.toString());
}
// Fallback: check if there's a request-related key
Object requestUri = data.get("requestUri");
if (requestUri != null) {
return normalizeEndpoint(requestUri.toString());
}
} catch (JsonProcessingException e) {
log.debug("Failed to parse audit data JSON: {}", dataJson, e);
}
return null;
}
/**
* Normalize endpoint paths by removing query strings and standardizing format.
*
* @param endpoint Raw endpoint path
* @return Normalized endpoint path
*/
private String normalizeEndpoint(String endpoint) {
if (endpoint == null) {
return null;
}
// Remove query string
int queryIndex = endpoint.indexOf('?');
if (queryIndex != -1) {
endpoint = endpoint.substring(0, queryIndex);
}
// Ensure it starts with /
if (!endpoint.startsWith("/")) {
endpoint = "/" + endpoint;
}
return endpoint;
}
/**
* Determine if an endpoint should be included based on the data type filter.
*
* @param endpoint The endpoint path to check
* @param dataType The filter type: "all", "api", or "ui"
* @return true if the endpoint should be included, false otherwise
*/
private boolean shouldIncludeEndpoint(String endpoint, String dataType) {
if ("all".equalsIgnoreCase(dataType)) {
return true;
}
boolean isApiEndpoint = isApiEndpoint(endpoint);
if ("api".equalsIgnoreCase(dataType)) {
return isApiEndpoint;
} else if ("ui".equalsIgnoreCase(dataType)) {
return !isApiEndpoint;
}
// Default to including all if unrecognized type
return true;
}
/**
* Check if an endpoint is an API endpoint. API endpoints match /api/v1/* pattern but exclude
* /api/v1/auth/* paths.
*
* @param endpoint The endpoint path to check
* @return true if this is an API endpoint (excluding auth endpoints), false otherwise
*/
private boolean isApiEndpoint(String endpoint) {
if (endpoint == null) {
return false;
}
// Check if it starts with /api/v1/
if (!endpoint.startsWith("/api/v1/")) {
return false;
}
// Exclude auth endpoints
if (endpoint.startsWith("/api/v1/auth/")) {
return false;
}
return true;
}
// DTOs for response formatting
@lombok.Data
@lombok.Builder
public static class EndpointStatisticsResponse {
private List<EndpointStatistic> endpoints;
private int totalEndpoints;
private int totalVisits;
}
@lombok.Data
@lombok.Builder
public static class EndpointStatistic {
private String endpoint;
private int visits;
private double percentage;
}
}
@@ -1,65 +0,0 @@
package stirling.software.proprietary.model;
import java.io.Serializable;
import jakarta.persistence.*;
import lombok.*;
/**
* Entity to store user license settings in the database. This is a singleton entity (only one row
* should exist). Tracks grandfathered user counts and license limits.
*/
@Entity
@Table(name = "user_license_settings")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class UserLicenseSettings implements Serializable {
private static final long serialVersionUID = 1L;
public static final Long SINGLETON_ID = 1L;
@Id
@Column(name = "id")
private Long id = SINGLETON_ID;
/**
* The number of users that existed in the database when grandfathering was initialized. This
* value is set once during initial setup and should NEVER be modified afterwards.
*/
@Column(name = "grandfathered_user_count", nullable = false)
private int grandfatheredUserCount = 0;
/**
* Flag to indicate that grandfathering has been initialized and locked. Once true, the
* grandfatheredUserCount should never change. This prevents manipulation by deleting/recreating
* the table.
*/
@Column(name = "grandfathering_locked", nullable = false)
private boolean grandfatheringLocked = false;
/**
* Maximum number of users allowed by the current license. This is updated when the license key
* is validated.
*/
@Column(name = "license_max_users", nullable = false)
private int licenseMaxUsers = 0;
/**
* Random salt used when generating signatures. Makes it harder to recompute the signature when
* manually editing the table.
*/
@Column(name = "integrity_salt", nullable = false, length = 64)
private String integritySalt = "";
/**
* Signed representation of {@code grandfatheredUserCount}. Stores the original value alongside
* a secret-backed HMAC so we can detect tampering and restore the correct count.
*/
@Column(name = "grandfathered_user_signature", nullable = false, length = 256)
private String grandfatheredUserSignature = "";
}
@@ -20,7 +20,6 @@ import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@Slf4j
@Component
@@ -31,7 +30,6 @@ public class InitialSecuritySetup {
private final TeamService teamService;
private final ApplicationProperties applicationProperties;
private final DatabaseServiceInterface databaseService;
private final UserLicenseSettingsService licenseSettingsService;
@PostConstruct
public void init() {
@@ -47,18 +45,12 @@ public class InitialSecuritySetup {
assignUsersToDefaultTeamIfMissing();
initializeInternalApiUser();
initializeUserLicenseSettings();
} catch (IllegalArgumentException | SQLException | UnsupportedProviderException e) {
log.error("Failed to initialize security setup.", e);
System.exit(1);
}
}
private void initializeUserLicenseSettings() {
licenseSettingsService.initializeGrandfatheredCount();
licenseSettingsService.updateLicenseMaxUsers();
}
private void assignUsersToDefaultTeamIfMissing() {
Team defaultTeam = teamService.getOrCreateDefaultTeam();
Team internalTeam = teamService.getOrCreateInternalTeam();
@@ -25,8 +25,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
@EnableJpaRepositories(
basePackages = {
"stirling.software.proprietary.security.database.repository",
"stirling.software.proprietary.security.repository",
"stirling.software.proprietary.repository"
"stirling.software.proprietary.security.repository"
})
@EntityScan({"stirling.software.proprietary.security.model", "stirling.software.proprietary.model"})
public class DatabaseConfig {
@@ -241,7 +241,6 @@ public class SecurityConfiguration {
|| trimmedUri.endsWith(".svg")
|| trimmedUri.startsWith("/register")
|| trimmedUri.startsWith("/signup")
|| trimmedUri.startsWith("/invite")
|| trimmedUri.startsWith("/auth/callback")
|| trimmedUri.startsWith("/error")
|| trimmedUri.startsWith("/images/")
@@ -264,10 +263,6 @@ public class SecurityConfiguration {
|| trimmedUri.startsWith(
"/api/v1/auth/refresh")
|| trimmedUri.startsWith("/api/v1/auth/me")
|| trimmedUri.startsWith(
"/api/v1/invite/validate")
|| trimmedUri.startsWith(
"/api/v1/invite/accept")
|| trimmedUri.startsWith("/v1/api-docs")
|| uri.contains("/v1/api-docs");
})
@@ -5,20 +5,14 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.GeneralUtils;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@Slf4j
@Component
@@ -30,36 +24,21 @@ public class LicenseKeyChecker {
private final ApplicationProperties applicationProperties;
private final UserLicenseSettingsService licenseSettingsService;
private License premiumEnabledResult = License.NORMAL;
public LicenseKeyChecker(
KeygenLicenseVerifier licenseService,
ApplicationProperties applicationProperties,
@Lazy UserLicenseSettingsService licenseSettingsService) {
KeygenLicenseVerifier licenseService, ApplicationProperties applicationProperties) {
this.licenseService = licenseService;
this.applicationProperties = applicationProperties;
this.licenseSettingsService = licenseSettingsService;
}
@PostConstruct
public void init() {
evaluateLicense();
}
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
synchronizeLicenseSettings();
this.checkLicense();
}
@Scheduled(initialDelay = 604800000, fixedRate = 604800000) // 7 days in milliseconds
public void checkLicensePeriodically() {
evaluateLicense();
synchronizeLicenseSettings();
checkLicense();
}
private void evaluateLicense() {
private void checkLicense() {
if (!applicationProperties.getPremium().isEnabled()) {
premiumEnabledResult = License.NORMAL;
} else {
@@ -80,10 +59,6 @@ public class LicenseKeyChecker {
}
}
private void synchronizeLicenseSettings() {
licenseSettingsService.updateLicenseMaxUsers();
}
private String getLicenseKeyContent(String keyOrFilePath) {
if (keyOrFilePath == null || keyOrFilePath.trim().isEmpty()) {
log.error("License key is not specified");
@@ -114,8 +89,7 @@ public class LicenseKeyChecker {
public void updateLicenseKey(String newKey) throws IOException {
applicationProperties.getPremium().setKey(newKey);
GeneralUtils.saveKeyToSettings("EnterpriseEdition.key", newKey);
evaluateLicense();
synchronizeLicenseSettings();
checkLicense();
}
public License getPremiumLicenseEnabledResult() {
@@ -1,484 +0,0 @@
package stirling.software.proprietary.security.controller.api;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.UserApi;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.InviteToken;
import stirling.software.proprietary.security.repository.InviteTokenRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
@UserApi
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/invite")
public class InviteLinkController {
private final InviteTokenRepository inviteTokenRepository;
private final TeamRepository teamRepository;
private final UserService userService;
private final ApplicationProperties applicationProperties;
private final Optional<EmailService> emailService;
/**
* Generate a new invite link (admin only)
*
* @param email The email address to invite
* @param role The role to assign (default: ROLE_USER)
* @param teamId The team to assign (optional, uses default team if not provided)
* @param expiryHours Custom expiry hours (optional, uses default from config)
* @param sendEmail Whether to send the invite link via email (default: false)
* @param principal The authenticated admin user
* @param request The HTTP request
* @return ResponseEntity with the invite link or error
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/generate")
public ResponseEntity<?> generateInviteLink(
@RequestParam(name = "email", required = false) String email,
@RequestParam(name = "role", defaultValue = "ROLE_USER") String role,
@RequestParam(name = "teamId", required = false) Long teamId,
@RequestParam(name = "expiryHours", required = false) Integer expiryHours,
@RequestParam(name = "sendEmail", defaultValue = "false") boolean sendEmail,
Principal principal,
HttpServletRequest request) {
try {
// Check if email invites are enabled
if (!applicationProperties.getMail().isEnableInvites()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Email invites are not enabled"));
}
// If email is provided, validate and check for conflicts
if (email != null && !email.trim().isEmpty()) {
// Validate email format
if (!email.contains("@")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Invalid email address"));
}
email = email.trim().toLowerCase();
// Check if user already exists
if (userService.usernameExistsIgnoreCase(email)) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", "User already exists"));
}
// Check if there's already an active invite for this email
Optional<InviteToken> existingInvite = inviteTokenRepository.findByEmail(email);
if (existingInvite.isPresent() && existingInvite.get().isValid()) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(
Map.of(
"error",
"An active invite already exists for this email address"));
}
// If sendEmail is requested but no email provided, reject
if (sendEmail) {
// Email will be sent
}
} else {
// No email provided - this is a general invite link
email = null; // Ensure it's null, not empty string
// Cannot send email if no email address provided
if (sendEmail) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Cannot send email without an email address"));
}
}
// Check license limits
if (applicationProperties.getPremium().isEnabled()) {
long currentUserCount = userService.getTotalUsersCount();
long activeInvites = inviteTokenRepository.countActiveInvites(LocalDateTime.now());
int maxUsers = applicationProperties.getPremium().getMaxUsers();
if (currentUserCount + activeInvites >= maxUsers) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"Maximum number of users reached for your license"));
}
}
// Validate role
try {
Role roleEnum = Role.fromString(role);
if (roleEnum == Role.INTERNAL_API_USER) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Cannot assign INTERNAL_API_USER role"));
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Invalid role specified"));
}
// Determine team
Long effectiveTeamId = teamId;
if (effectiveTeamId == null) {
Team defaultTeam =
teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
if (defaultTeam != null) {
effectiveTeamId = defaultTeam.getId();
}
} else {
Team selectedTeam = teamRepository.findById(effectiveTeamId).orElse(null);
if (selectedTeam != null
&& TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Cannot assign users to Internal team"));
}
}
// Generate token
String token = UUID.randomUUID().toString();
// Determine expiry time
int effectiveExpiryHours =
(expiryHours != null && expiryHours > 0)
? expiryHours
: applicationProperties.getMail().getInviteLinkExpiryHours();
LocalDateTime expiresAt = LocalDateTime.now().plusHours(effectiveExpiryHours);
// Create invite token
InviteToken inviteToken = new InviteToken();
inviteToken.setToken(token);
inviteToken.setEmail(email);
inviteToken.setRole(role);
inviteToken.setTeamId(effectiveTeamId);
inviteToken.setExpiresAt(expiresAt);
inviteToken.setCreatedBy(principal.getName());
inviteTokenRepository.save(inviteToken);
// Build invite URL
// Use configured frontend URL if available, otherwise fall back to backend URL
String baseUrl;
String configuredFrontendUrl = applicationProperties.getSystem().getFrontendUrl();
if (configuredFrontendUrl != null && !configuredFrontendUrl.trim().isEmpty()) {
// Use configured frontend URL (remove trailing slash if present)
baseUrl =
configuredFrontendUrl.endsWith("/")
? configuredFrontendUrl.substring(
0, configuredFrontendUrl.length() - 1)
: configuredFrontendUrl;
} else {
// Fall back to backend URL from request
baseUrl =
request.getScheme()
+ "://"
+ request.getServerName()
+ (request.getServerPort() != 80 && request.getServerPort() != 443
? ":" + request.getServerPort()
: "");
}
String inviteUrl = baseUrl + "/invite?token=" + token;
log.info("Generated invite link for {} by {}", email, principal.getName());
// Optionally send email
boolean emailSent = false;
String emailError = null;
if (sendEmail) {
if (!emailService.isPresent()) {
emailError = "Email service is not configured";
log.warn("Cannot send invite email: Email service not configured");
} else {
try {
emailService
.get()
.sendInviteLinkEmail(email, inviteUrl, expiresAt.toString());
emailSent = true;
log.info("Sent invite link email to: {}", email);
} catch (Exception emailEx) {
emailError = emailEx.getMessage();
log.error(
"Failed to send invite email to {}: {}",
email,
emailEx.getMessage());
}
}
}
Map<String, Object> response = new HashMap<>();
response.put("token", token);
response.put("inviteUrl", inviteUrl);
response.put("email", email);
response.put("expiresAt", expiresAt.toString());
response.put("expiryHours", effectiveExpiryHours);
if (sendEmail) {
response.put("emailSent", emailSent);
if (emailError != null) {
response.put("emailError", emailError);
}
}
return ResponseEntity.ok(response);
} catch (Exception e) {
log.error("Failed to generate invite link: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to generate invite link: " + e.getMessage()));
}
}
/**
* List all active invite links (admin only)
*
* @return List of active invite tokens
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/list")
public ResponseEntity<?> listInviteLinks() {
try {
List<InviteToken> activeInvites =
inviteTokenRepository.findByUsedFalseAndExpiresAtAfter(LocalDateTime.now());
List<Map<String, Object>> inviteList =
activeInvites.stream()
.map(
invite -> {
Map<String, Object> inviteMap = new HashMap<>();
inviteMap.put("id", invite.getId());
inviteMap.put("email", invite.getEmail());
inviteMap.put("role", invite.getRole());
inviteMap.put("teamId", invite.getTeamId());
inviteMap.put("createdBy", invite.getCreatedBy());
inviteMap.put(
"createdAt", invite.getCreatedAt().toString());
inviteMap.put(
"expiresAt", invite.getExpiresAt().toString());
return inviteMap;
})
.collect(Collectors.toList());
return ResponseEntity.ok(Map.of("invites", inviteList));
} catch (Exception e) {
log.error("Failed to list invite links: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to list invite links"));
}
}
/**
* Revoke an invite link (admin only)
*
* @param inviteId The invite token ID to revoke
* @return Success or error response
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@DeleteMapping("/revoke/{inviteId}")
public ResponseEntity<?> revokeInviteLink(@PathVariable Long inviteId) {
try {
Optional<InviteToken> inviteOpt = inviteTokenRepository.findById(inviteId);
if (inviteOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "Invite not found"));
}
inviteTokenRepository.deleteById(inviteId);
log.info("Revoked invite link ID: {}", inviteId);
return ResponseEntity.ok(Map.of("message", "Invite link revoked successfully"));
} catch (Exception e) {
log.error("Failed to revoke invite link: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to revoke invite link"));
}
}
/**
* Clean up expired invite tokens (admin only)
*
* @return Number of deleted tokens
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/cleanup")
public ResponseEntity<?> cleanupExpiredInvites() {
try {
List<InviteToken> expiredInvites =
inviteTokenRepository.findAll().stream()
.filter(invite -> !invite.isValid())
.collect(Collectors.toList());
int count = expiredInvites.size();
inviteTokenRepository.deleteAll(expiredInvites);
log.info("Cleaned up {} expired invite tokens", count);
return ResponseEntity.ok(Map.of("deletedCount", count));
} catch (Exception e) {
log.error("Failed to cleanup expired invites: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to cleanup expired invites"));
}
}
/**
* Validate an invite token (public endpoint)
*
* @param token The invite token to validate
* @return Invite details if valid, error otherwise
*/
@GetMapping("/validate/{token}")
public ResponseEntity<?> validateInviteToken(@PathVariable String token) {
try {
Optional<InviteToken> inviteOpt = inviteTokenRepository.findByToken(token);
if (inviteOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "Invalid invite link"));
}
InviteToken invite = inviteOpt.get();
if (invite.isUsed()) {
return ResponseEntity.status(HttpStatus.GONE)
.body(Map.of("error", "This invite link has already been used"));
}
if (invite.isExpired()) {
return ResponseEntity.status(HttpStatus.GONE)
.body(Map.of("error", "This invite link has expired"));
}
// Check if user already exists (only if email is pre-set)
if (invite.getEmail() != null
&& userService.usernameExistsIgnoreCase(invite.getEmail())) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", "User already exists"));
}
Map<String, Object> response = new HashMap<>();
response.put("email", invite.getEmail());
response.put("role", invite.getRole());
response.put("expiresAt", invite.getExpiresAt().toString());
response.put("emailRequired", invite.getEmail() == null);
return ResponseEntity.ok(response);
} catch (Exception e) {
log.error("Failed to validate invite token: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to validate invite link"));
}
}
/**
* Accept an invite and create user account (public endpoint)
*
* @param token The invite token
* @param email The email address (required if not pre-set in invite)
* @param password The password to set for the new account
* @return Success or error response
*/
@PostMapping("/accept/{token}")
public ResponseEntity<?> acceptInvite(
@PathVariable String token,
@RequestParam(name = "email", required = false) String email,
@RequestParam(name = "password") String password) {
try {
// Validate password
if (password == null || password.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Password is required"));
}
Optional<InviteToken> inviteOpt = inviteTokenRepository.findByToken(token);
if (inviteOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "Invalid invite link"));
}
InviteToken invite = inviteOpt.get();
if (invite.isUsed()) {
return ResponseEntity.status(HttpStatus.GONE)
.body(Map.of("error", "This invite link has already been used"));
}
if (invite.isExpired()) {
return ResponseEntity.status(HttpStatus.GONE)
.body(Map.of("error", "This invite link has expired"));
}
// Determine the email to use
String effectiveEmail = invite.getEmail();
if (effectiveEmail == null) {
// Email not pre-set, must be provided by user
if (email == null || email.trim().isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Email address is required"));
}
// Validate email format
if (!email.contains("@")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Invalid email address"));
}
effectiveEmail = email.trim().toLowerCase();
}
// Check if user already exists
if (userService.usernameExistsIgnoreCase(effectiveEmail)) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", "User already exists"));
}
// Create the user account
userService.saveUser(
effectiveEmail,
password,
invite.getTeamId(),
invite.getRole(),
false); // Don't force password change
// Mark invite as used
invite.setUsed(true);
invite.setUsedAt(LocalDateTime.now());
inviteTokenRepository.save(invite);
log.info(
"User account created via invite link: {} with role: {}",
effectiveEmail,
invite.getRole());
return ResponseEntity.ok(
Map.of("message", "Account created successfully", "username", effectiveEmail));
} catch (Exception e) {
log.error("Failed to accept invite: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to create account: " + e.getMessage()));
}
}
}
@@ -40,7 +40,6 @@ import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@UserApi
@Slf4j
@@ -54,7 +53,6 @@ public class UserController {
private final TeamRepository teamRepository;
private final UserRepository userRepository;
private final Optional<EmailService> emailService;
private final UserLicenseSettingsService licenseSettingsService;
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/register")
@@ -79,9 +77,10 @@ public class UserController {
.body(Map.of("error", "Invalid username format"));
}
if (usernameAndPass.getPassword() == null || usernameAndPass.getPassword().isEmpty()) {
if (usernameAndPass.getPassword() == null
|| usernameAndPass.getPassword().length() < 6) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Password is required"));
.body(Map.of("error", "Password must be at least 6 characters"));
}
Team team = teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
@@ -311,17 +310,11 @@ public class UserController {
"error",
"Invalid username format. Username must be 3-50 characters."));
}
if (licenseSettingsService.wouldExceedLimit(1)) {
long availableSlots = licenseSettingsService.getAvailableUserSlots();
int maxAllowed = licenseSettingsService.calculateMaxAllowedUsers();
if (applicationProperties.getPremium().isEnabled()
&& applicationProperties.getPremium().getMaxUsers()
<= userService.getTotalUsersCount()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"Maximum number of users reached. Allowed: "
+ maxAllowed
+ ", Available slots: "
+ availableSlots));
.body(Map.of("error", "Maximum number of users reached for your license."));
}
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
if (userOpt.isPresent()) {
@@ -414,19 +407,20 @@ public class UserController {
}
// Check license limits
if (licenseSettingsService.wouldExceedLimit(emailArray.length)) {
long availableSlots = licenseSettingsService.getAvailableUserSlots();
int maxAllowed = licenseSettingsService.calculateMaxAllowedUsers();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"Not enough user slots available. Allowed: "
+ maxAllowed
+ ", Available: "
+ availableSlots
+ ", Requested: "
+ emailArray.length));
if (applicationProperties.getPremium().isEnabled()) {
long currentUserCount = userService.getTotalUsersCount();
int maxUsers = applicationProperties.getPremium().getMaxUsers();
long availableSlots = maxUsers - currentUserCount;
if (availableSlots < emailArray.length) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"Not enough user slots available. Available: "
+ availableSlots
+ ", Requested: "
+ emailArray.length));
}
}
// Validate role
@@ -84,14 +84,11 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
boolean isPublicAuthEndpoint =
requestURI.startsWith(contextPath + "/login")
|| requestURI.startsWith(contextPath + "/signup")
|| requestURI.startsWith(contextPath + "/invite")
|| requestURI.startsWith(contextPath + "/auth/")
|| requestURI.startsWith(contextPath + "/oauth2")
|| requestURI.startsWith(contextPath + "/api/v1/auth/login")
|| requestURI.startsWith(contextPath + "/api/v1/auth/register")
|| requestURI.startsWith(contextPath + "/api/v1/auth/refresh")
|| requestURI.startsWith(contextPath + "/api/v1/invite/validate")
|| requestURI.startsWith(contextPath + "/api/v1/invite/accept");
|| requestURI.startsWith(contextPath + "/api/v1/auth/refresh");
if (!isPublicAuthEndpoint) {
// For API requests, return 401 JSON
@@ -227,7 +227,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
contextPath + "/login",
contextPath + "/signup",
contextPath + "/register",
contextPath + "/invite",
contextPath + "/error",
contextPath + "/images/",
contextPath + "/public/",
@@ -241,8 +240,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
contextPath + "/api/v1/auth/register",
contextPath + "/api/v1/auth/refresh",
contextPath + "/api/v1/auth/me",
contextPath + "/api/v1/invite/validate",
contextPath + "/api/v1/invite/accept",
contextPath + "/site.webmanifest"
};
@@ -1,62 +0,0 @@
package stirling.software.proprietary.security.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import org.hibernate.annotations.CreationTimestamp;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "invite_tokens")
@NoArgsConstructor
@Getter
@Setter
public class InviteToken implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "token", unique = true, nullable = false, length = 100)
private String token;
@Column(name = "email", nullable = true, length = 255)
private String email; // Optional - if not set, user can provide their own email
@Column(name = "role", nullable = false, length = 50)
private String role;
@Column(name = "team_id")
private Long teamId;
@Column(name = "expires_at", nullable = false)
private LocalDateTime expiresAt;
@Column(name = "used", nullable = false)
private boolean used = false;
@Column(name = "created_by", nullable = false, length = 255)
private String createdBy;
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
@Column(name = "used_at")
private LocalDateTime usedAt;
public boolean isExpired() {
return LocalDateTime.now().isAfter(expiresAt);
}
public boolean isValid() {
return !used && !isExpired();
}
}
@@ -1,32 +0,0 @@
package stirling.software.proprietary.security.repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.security.model.InviteToken;
@Repository
public interface InviteTokenRepository extends JpaRepository<InviteToken, Long> {
Optional<InviteToken> findByToken(String token);
Optional<InviteToken> findByEmail(String email);
List<InviteToken> findByUsedFalseAndExpiresAtAfter(LocalDateTime now);
List<InviteToken> findByCreatedBy(String createdBy);
@Modifying
@Query("DELETE FROM InviteToken it WHERE it.expiresAt < :now")
void deleteExpiredTokens(@Param("now") LocalDateTime now);
@Query("SELECT COUNT(it) FROM InviteToken it WHERE it.used = false AND it.expiresAt > :now")
long countActiveInvites(@Param("now") LocalDateTime now);
}
@@ -1,21 +0,0 @@
package stirling.software.proprietary.security.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.model.UserLicenseSettings;
@Repository
public interface UserLicenseSettingsRepository extends JpaRepository<UserLicenseSettings, Long> {
/**
* Finds the singleton UserLicenseSettings record.
*
* @return Optional containing the settings if they exist
*/
default Optional<UserLicenseSettings> findSettings() {
return findById(UserLicenseSettings.SINGLETON_ID);
}
}
@@ -159,58 +159,4 @@ public class EmailService {
sendPlainEmail(to, subject, body, true);
}
/**
* Sends an invitation link email to a new user.
*
* @param to The recipient email address
* @param inviteUrl The full URL for accepting the invite
* @param expiresAt The expiration timestamp
* @throws MessagingException If there is an issue with creating or sending the email.
*/
@Async
public void sendInviteLinkEmail(String to, String inviteUrl, String expiresAt)
throws MessagingException {
String subject = "You've been invited to Stirling PDF";
String body =
"""
<html><body style="margin: 0; padding: 0;">
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
<!-- Logo -->
<div style="text-align: center; padding: 20px; background-color: #222;">
<img src="https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/main/docs/stirling-transparent.svg" alt="Stirling PDF" style="max-height: 60px;">
</div>
<!-- Content -->
<div style="padding: 30px; color: #333;">
<h2 style="color: #222; margin-top: 0;">Welcome to Stirling PDF!</h2>
<p>Hi there,</p>
<p>You have been invited to join the Stirling PDF workspace. Click the button below to set up your account:</p>
<!-- CTA Button -->
<div style="text-align: center; margin: 30px 0;">
<a href="%s" style="display: inline-block; background-color: #007bff; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 5px; font-weight: bold;">Accept Invitation</a>
</div>
<p style="font-size: 14px; color: #666;">Or copy and paste this link in your browser:</p>
<div style="background-color: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 4px; word-break: break-all; font-size: 13px; color: #555;">
%s
</div>
<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; color: #856404; font-size: 14px;"><strong>⚠️ Important:</strong> This invitation link will expire on %s. Please complete your registration before then.</p>
</div>
<p>If you didn't expect this invitation, you can safely ignore this email.</p>
<p style="margin-bottom: 0;">— The Stirling PDF Team</p>
</div>
<!-- Footer -->
<div style="text-align: center; padding: 15px; font-size: 12px; color: #777; background-color: #f0f0f0;">
&copy; 2025 Stirling PDF. All rights reserved.
</div>
</div>
</div>
</body></html>
"""
.formatted(inviteUrl, inviteUrl, expiresAt);
sendPlainEmail(to, subject, body, true);
}
}
@@ -1,411 +0,0 @@
package stirling.software.proprietary.service;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.model.UserLicenseSettings;
import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository;
import stirling.software.proprietary.security.service.UserService;
/**
* Service for managing user license settings and grandfathering logic.
*
* <p>User limit calculation:
*
* <ul>
* <li>Default limit: 5 users
* <li>Grandfathered limit: max(5, existing user count at initialization)
* <li>With pro license: grandfathered limit + license maxUsers
* <li>Without pro license: grandfathered limit
* </ul>
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class UserLicenseSettingsService {
private static final int DEFAULT_USER_LIMIT = 5;
private static final String SIGNATURE_SEPARATOR = ":";
private static final String DEFAULT_INTEGRITY_SECRET = "stirling-pdf-user-license-guard";
private final UserLicenseSettingsRepository settingsRepository;
private final UserService userService;
private final ApplicationProperties applicationProperties;
/**
* Gets the current user license settings, creating them if they don't exist.
*
* @return The current settings
*/
@Transactional
public UserLicenseSettings getOrCreateSettings() {
return settingsRepository
.findSettings()
.orElseGet(
() -> {
log.info("Initializing user license settings");
UserLicenseSettings settings = new UserLicenseSettings();
settings.setId(UserLicenseSettings.SINGLETON_ID);
settings.setGrandfatheredUserCount(0);
settings.setLicenseMaxUsers(0);
settings.setGrandfatheringLocked(false);
settings.setIntegritySalt(UUID.randomUUID().toString());
settings.setGrandfatheredUserSignature("");
return settingsRepository.save(settings);
});
}
/**
* Initializes the grandfathered user count if not already set. This should be called on
* application startup.
*
* <p>IMPORTANT: Once grandfathering is locked, this value can NEVER be changed. This prevents
* manipulation by deleting the settings table.
*
* <p>Logic:
*
* <ul>
* <li>If grandfatheringLocked is true: Skip initialization (already set permanently)
* <li>If users exist in database: Set to max(5, current user count) - this is an existing
* installation
* <li>If no users exist: Set to 5 (default) - this is a fresh installation
* <li>Lock grandfathering immediately after setting
* </ul>
*/
@Transactional
public void initializeGrandfatheredCount() {
UserLicenseSettings settings = getOrCreateSettings();
boolean changed = ensureIntegritySalt(settings);
// CRITICAL: Never change grandfathering once it's locked
if (settings.isGrandfatheringLocked()) {
if (settings.getGrandfatheredUserSignature() == null
|| settings.getGrandfatheredUserSignature().isBlank()) {
settings.setGrandfatheredUserSignature(
generateSignature(settings.getGrandfatheredUserCount(), settings));
changed = true;
}
if (changed) {
settingsRepository.save(settings);
}
log.debug(
"Grandfathering is locked. Current grandfathered count: {}",
settings.getGrandfatheredUserCount());
return;
}
// Determine if this is an existing installation or fresh install
long currentUserCount = userService.getTotalUsersCount();
boolean isExistingInstallation = currentUserCount > 0;
int grandfatheredCount;
if (isExistingInstallation) {
// Existing installation (v2.0+ or has users) - grandfather current user count
grandfatheredCount = Math.max(DEFAULT_USER_LIMIT, (int) currentUserCount);
log.info(
"Existing installation detected. Grandfathering {} users (current: {}, minimum:"
+ " {})",
grandfatheredCount,
currentUserCount,
DEFAULT_USER_LIMIT);
} else {
// Fresh installation - set to default
grandfatheredCount = DEFAULT_USER_LIMIT;
log.info(
"Fresh installation detected. Setting default grandfathered limit: {}",
grandfatheredCount);
}
// Set and LOCK the grandfathering permanently
settings.setGrandfatheredUserCount(grandfatheredCount);
settings.setGrandfatheringLocked(true);
settings.setGrandfatheredUserSignature(generateSignature(grandfatheredCount, settings));
settingsRepository.save(settings);
log.warn(
"GRANDFATHERING LOCKED: {} users. This value can never be changed.",
grandfatheredCount);
}
/**
* Updates the license max users from the application properties. This should be called when the
* license is validated.
*/
@Transactional
public void updateLicenseMaxUsers() {
UserLicenseSettings settings = getOrCreateSettings();
int licenseMaxUsers = 0;
if (applicationProperties.getPremium().isEnabled()) {
licenseMaxUsers = applicationProperties.getPremium().getMaxUsers();
}
if (settings.getLicenseMaxUsers() != licenseMaxUsers) {
settings.setLicenseMaxUsers(licenseMaxUsers);
settingsRepository.save(settings);
log.info("Updated license max users to: {}", licenseMaxUsers);
}
}
/**
* Validates and enforces the integrity of license settings. This ensures that even if someone
* manually modifies the database, the grandfathering rules are still enforced.
*/
@Transactional
public void validateSettingsIntegrity() {
UserLicenseSettings settings = getOrCreateSettings();
boolean changed = ensureIntegritySalt(settings);
Optional<Integer> signedCountOpt = extractSignedCount(settings);
boolean signatureValid =
signedCountOpt.isPresent()
&& signatureMatches(
signedCountOpt.get(),
settings.getGrandfatheredUserSignature(),
settings);
int targetCount = settings.getGrandfatheredUserCount();
String targetSignature = settings.getGrandfatheredUserSignature();
if (!signatureValid) {
int restoredCount =
signedCountOpt.orElseGet(
() ->
Math.max(
DEFAULT_USER_LIMIT,
(int) userService.getTotalUsersCount()));
log.error(
"Grandfathered user signature invalid or missing. Restoring locked count to {}.",
restoredCount);
targetCount = restoredCount;
targetSignature = generateSignature(targetCount, settings);
changed = true;
} else {
int signedCount = signedCountOpt.get();
if (targetCount != signedCount) {
log.error(
"Grandfathered user count ({}) was modified without signature update. Restoring to {}.",
targetCount,
signedCount);
targetCount = signedCount;
targetSignature = generateSignature(targetCount, settings);
changed = true;
}
}
if (targetCount < DEFAULT_USER_LIMIT) {
if (targetCount != DEFAULT_USER_LIMIT) {
log.warn(
"Grandfathered count ({}) is below minimum ({}). Enforcing minimum.",
targetCount,
DEFAULT_USER_LIMIT);
}
targetCount = DEFAULT_USER_LIMIT;
targetSignature = generateSignature(targetCount, settings);
changed = true;
}
if (targetSignature == null || targetSignature.isBlank()) {
targetSignature = generateSignature(targetCount, settings);
changed = true;
}
if (changed
|| settings.getGrandfatheredUserCount() != targetCount
|| (targetSignature != null
&& !targetSignature.equals(settings.getGrandfatheredUserSignature()))) {
settings.setGrandfatheredUserCount(targetCount);
settings.setGrandfatheredUserSignature(targetSignature);
settingsRepository.save(settings);
}
}
/**
* Calculates the maximum allowed users based on grandfathering rules.
*
* <p>Logic:
*
* <ul>
* <li>Grandfathered limit = max(5, existing user count at initialization)
* <li>If premium enabled: total limit = grandfathered limit + license maxUsers
* <li>If premium disabled: total limit = grandfathered limit
* </ul>
*
* @return Maximum number of users allowed
*/
public int calculateMaxAllowedUsers() {
validateSettingsIntegrity();
UserLicenseSettings settings = getOrCreateSettings();
int grandfatheredLimit = settings.getGrandfatheredUserCount();
if (grandfatheredLimit == 0) {
// Fallback if not initialized yet - should not happen with validation
log.warn("Grandfathered limit is 0, using default: {}", DEFAULT_USER_LIMIT);
grandfatheredLimit = DEFAULT_USER_LIMIT;
}
int totalLimit = grandfatheredLimit;
if (applicationProperties.getPremium().isEnabled()) {
totalLimit = grandfatheredLimit + settings.getLicenseMaxUsers();
}
log.debug(
"Calculated max allowed users: {} (grandfathered: {}, license: {}, premium enabled: {})",
totalLimit,
grandfatheredLimit,
settings.getLicenseMaxUsers(),
applicationProperties.getPremium().isEnabled());
return totalLimit;
}
/**
* Checks if adding new users would exceed the limit.
*
* @param newUsersCount Number of new users to add
* @return true if the addition would exceed the limit
*/
public boolean wouldExceedLimit(int newUsersCount) {
long currentUserCount = userService.getTotalUsersCount();
int maxAllowed = calculateMaxAllowedUsers();
return (currentUserCount + newUsersCount) > maxAllowed;
}
/**
* Gets the number of available user slots.
*
* @return Number of users that can still be added
*/
public long getAvailableUserSlots() {
long currentUserCount = userService.getTotalUsersCount();
int maxAllowed = calculateMaxAllowedUsers();
return Math.max(0, maxAllowed - currentUserCount);
}
/**
* Gets the grandfathered user count for display purposes. Returns only the excess users beyond
* the base limit (5).
*
* <p>Examples:
*
* <ul>
* <li>If grandfathered = 5: returns 0 (base amount, nothing special)
* <li>If grandfathered = 10: returns 5 (5 extra users)
* <li>If grandfathered = 15: returns 10 (10 extra users)
* </ul>
*
* @return Number of grandfathered users beyond the base limit
*/
public int getDisplayGrandfatheredCount() {
UserLicenseSettings settings = getOrCreateSettings();
int totalGrandfathered = settings.getGrandfatheredUserCount();
return Math.max(0, totalGrandfathered - DEFAULT_USER_LIMIT);
}
/** Gets the current settings. */
public UserLicenseSettings getSettings() {
return getOrCreateSettings();
}
private boolean ensureIntegritySalt(UserLicenseSettings settings) {
if (settings.getIntegritySalt() == null || settings.getIntegritySalt().isBlank()) {
settings.setIntegritySalt(UUID.randomUUID().toString());
return true;
}
return false;
}
private Optional<Integer> extractSignedCount(UserLicenseSettings settings) {
String signature = settings.getGrandfatheredUserSignature();
if (signature == null || signature.isBlank()) {
return Optional.empty();
}
String[] parts = signature.split(SIGNATURE_SEPARATOR, 2);
if (parts.length != 2) {
log.warn("Invalid grandfathered user signature format detected");
return Optional.empty();
}
try {
return Optional.of(Integer.parseInt(parts[0]));
} catch (NumberFormatException ex) {
log.warn("Unable to parse grandfathered user signature count", ex);
return Optional.empty();
}
}
private boolean signatureMatches(int count, String signature, UserLicenseSettings settings) {
if (signature == null || signature.isBlank()) {
return false;
}
return generateSignature(count, settings).equals(signature);
}
private String generateSignature(int count, UserLicenseSettings settings) {
if (settings.getIntegritySalt() == null || settings.getIntegritySalt().isBlank()) {
throw new IllegalStateException("Integrity salt must be initialized before signing.");
}
String payload = buildSignaturePayload(count, settings.getIntegritySalt());
String secret = deriveIntegritySecret();
String digest = computeHmac(payload, secret);
return count + SIGNATURE_SEPARATOR + digest;
}
private String buildSignaturePayload(int count, String salt) {
return count + SIGNATURE_SEPARATOR + salt;
}
private String deriveIntegritySecret() {
StringBuilder builder = new StringBuilder();
appendIfPresent(builder, applicationProperties.getAutomaticallyGenerated().getKey());
appendIfPresent(builder, applicationProperties.getAutomaticallyGenerated().getUUID());
appendIfPresent(builder, applicationProperties.getPremium().getKey());
if (builder.length() == 0) {
builder.append(DEFAULT_INTEGRITY_SECRET);
}
return builder.toString();
}
private void appendIfPresent(StringBuilder builder, String value) {
if (value != null && !value.isBlank()) {
if (builder.length() > 0) {
builder.append(SIGNATURE_SEPARATOR);
}
builder.append(value);
}
}
private String computeHmac(String payload, String secret) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec keySpec =
new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(keySpec);
byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Failed to compute grandfathered user signature", e);
} catch (InvalidKeyException e) {
throw new IllegalStateException("Invalid key for grandfathered user signature", e);
}
}
}
+9
View File
@@ -27,6 +27,15 @@ export default defineConfig(
tseslint.configs.recommended,
{
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
".*", // Disallow any relative imports (they should be '@app/x/y/z' or similar)
"src/*", // Disallow any absolute imports (they should be '@app/x/y/z' or similar)
],
},
],
'@typescript-eslint/no-empty-object-type': [
'error',
{
-25
View File
@@ -38,8 +38,6 @@
"@mui/icons-material": "^7.3.2",
"@mui/material": "^7.3.2",
"@reactour/tour": "^3.8.0",
"@stripe/react-stripe-js": "^4.0.2",
"@stripe/stripe-js": "^7.9.0",
"@tailwindcss/postcss": "^4.1.13",
"@tanstack/react-virtual": "^3.13.12",
"autoprefixer": "^10.4.21",
@@ -3047,29 +3045,6 @@
"url": "https://github.com/sindresorhus/is?sponsor=1"
}
},
"node_modules/@stripe/react-stripe-js": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@stripe/react-stripe-js/-/react-stripe-js-4.0.2.tgz",
"integrity": "sha512-l2wau+8/LOlHl+Sz8wQ1oDuLJvyw51nQCsu6/ljT6smqzTszcMHifjAJoXlnMfcou3+jK/kQyVe04u/ufyTXgg==",
"license": "MIT",
"dependencies": {
"prop-types": "^15.7.2"
},
"peerDependencies": {
"@stripe/stripe-js": ">=1.44.1 <8.0.0",
"react": ">=16.8.0 <20.0.0",
"react-dom": ">=16.8.0 <20.0.0"
}
},
"node_modules/@stripe/stripe-js": {
"version": "7.9.0",
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-7.9.0.tgz",
"integrity": "sha512-ggs5k+/0FUJcIgNY08aZTqpBTtbExkJMYMLSMwyucrhtWexVOEY1KJmhBsxf+E/Q15f5rbwBpj+t0t2AW2oCsQ==",
"license": "MIT",
"engines": {
"node": ">=12.16"
}
},
"node_modules/@swc/core": {
"version": "1.13.5",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.13.5.tgz",
+3 -5
View File
@@ -31,8 +31,6 @@
"@mantine/dates": "^8.3.1",
"@mantine/dropzone": "^8.3.1",
"@mantine/hooks": "^8.3.1",
"@stripe/react-stripe-js": "^4.0.2",
"@stripe/stripe-js": "^7.9.0",
"@mui/icons-material": "^7.3.2",
"@mui/material": "^7.3.2",
"@reactour/tour": "^3.8.0",
@@ -64,9 +62,9 @@
"lint": "eslint --max-warnings=0",
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"typecheck:core": "tsc --noEmit --project tsconfig.core.json",
"typecheck:proprietary": "tsc --noEmit --project tsconfig.proprietary.json",
"typecheck": "npm run typecheck:proprietary",
"typecheck:core": "tsc --noEmit --project src/core/tsconfig.json",
"typecheck:proprietary": "tsc --noEmit --project src/proprietary/tsconfig.json",
"typecheck:all": "npm run typecheck:core && npm run typecheck:proprietary",
"check": "npm run typecheck && npm run lint && npm run test:run",
"generate-licenses": "node scripts/generate-licenses.js",
+5 -269
View File
@@ -298,20 +298,6 @@
"general": {
"title": "General",
"description": "Configure general application preferences.",
"account": "Account",
"accountDescription": "Manage your account settings",
"user": "User",
"signedInAs": "Signed in as",
"logout": "Log out",
"enableFeatures": {
"title": "For System Administrators",
"intro": "Enable user authentication, team management, and workspace features for your organization.",
"action": "Configure",
"and": "and",
"benefit": "Enables user roles, team collaboration, admin controls, and enterprise features.",
"learnMore": "Learn more in documentation",
"dismiss": "Dismiss"
},
"autoUnzip": "Auto-unzip API responses",
"autoUnzipDescription": "Automatically extract files from ZIP responses",
"autoUnzipTooltip": "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",
@@ -413,10 +399,8 @@
"top20": "Top 20",
"all": "All",
"refresh": "Refresh",
"dataTypeLabel": "Data Type:",
"dataTypeAll": "All",
"dataTypeApi": "API",
"dataTypeUi": "UI",
"includeHomepage": "Include Homepage ('/')",
"includeLoginPage": "Include Login Page ('/login')",
"totalEndpoints": "Total Endpoints",
"totalVisits": "Total Visits",
"showing": "Showing",
@@ -3077,10 +3061,7 @@
"magicLinkSent": "Magic link sent to {{email}}! Check your email and click the link to sign in.",
"passwordResetSent": "Password reset link sent to {{email}}! Check your email and follow the instructions.",
"failedToSignIn": "Failed to sign in with {{provider}}: {{message}}",
"unexpectedError": "Unexpected error: {{message}}",
"accountCreatedSuccess": "Account created successfully! You can now sign in.",
"passwordChangedSuccess": "Password changed successfully! Please sign in with your new password.",
"credentialsUpdated": "Your credentials have been updated. Please sign in again."
"unexpectedError": "Unexpected error: {{message}}"
},
"signup": {
"title": "Create an account",
@@ -3540,8 +3521,8 @@
"restartingMessage": "The server is restarting. Please wait a moment...",
"restartError": "Failed to restart server. Please restart manually.",
"general": {
"title": "System Settings",
"description": "Configure system-wide application settings including branding and default behaviour.",
"title": "General",
"description": "Configure general application settings including branding and default behaviour.",
"ui": "User Interface",
"system": "System",
"appName": "Application Name",
@@ -4505,41 +4486,10 @@
"directInvite": {
"tab": "Direct Create"
},
"inviteLinkTab": {
"tab": "Invite Link"
},
"inviteLink": {
"description": "Generate a secure link that allows the user to set their own password",
"email": "Email Address",
"emailRequired": "Email address is required",
"emailOptional": "Optional - leave blank for a general invite link",
"emailRequiredForSend": "Email address is required to send email notification",
"expiryHours": "Expiry Hours",
"expiryDescription": "How many hours until the link expires",
"sendEmail": "Send invite link via email",
"smtpRequired": "SMTP not configured",
"generate": "Generate Link",
"generated": "Invite Link Generated",
"copied": "Link copied to clipboard",
"success": "Invite link generated successfully",
"successWithEmail": "Invite link generated and sent via email",
"emailFailed": "Email failed to send",
"error": "Failed to generate invite link"
},
"inviteMode": {
"username": "Username",
"email": "Email",
"emailDisabled": "Email invites require SMTP configuration and mail.enableInvites=true in settings"
},
"license": {
"users": "users",
"availableSlots": "Available Slots",
"grandfathered": "Grandfathered",
"grandfatheredShort": "{{count}} grandfathered",
"fromLicense": "from license",
"slotsAvailable": "{{count}} user slot(s) available",
"noSlotsAvailable": "No slots available",
"currentUsage": "Currently using {{current}} of {{max}} user licences"
}
},
"teams": {
@@ -4623,89 +4573,6 @@
}
}
},
"plan": {
"currency": "Currency",
"popular": "Popular",
"current": "Current Plan",
"upgrade": "Upgrade",
"contact": "Contact Us",
"customPricing": "Custom",
"showComparison": "Compare All Features",
"hideComparison": "Hide Feature Comparison",
"featureComparison": "Feature Comparison",
"activePlan": {
"title": "Active Plan",
"subtitle": "Your current subscription details"
},
"availablePlans": {
"title": "Available Plans",
"subtitle": "Choose the plan that fits your needs"
},
"static": {
"title": "Billing Information",
"message": "Online billing is not currently configured. To upgrade your plan or manage subscriptions, please contact us directly.",
"contactSales": "Contact Sales",
"contactToUpgrade": "Contact us to upgrade or customize your plan",
"maxUsers": "Max Users",
"upTo": "Up to"
},
"period": {
"month": "month"
},
"free": {
"name": "Free",
"highlight1": "Limited Tool Usage Per week",
"highlight2": "Access to all tools",
"highlight3": "Community support"
},
"pro": {
"name": "Pro",
"highlight1": "Unlimited Tool Usage",
"highlight2": "Advanced PDF tools",
"highlight3": "No watermarks"
},
"enterprise": {
"name": "Enterprise",
"highlight1": "Custom pricing",
"highlight2": "Dedicated support",
"highlight3": "Latest features"
},
"feature": {
"title": "Feature",
"pdfTools": "Basic PDF Tools",
"fileSize": "File Size Limit",
"automation": "Automate tool workflows",
"api": "API Access",
"priority": "Priority Support",
"customPricing": "Custom Pricing"
}
},
"subscription": {
"status": {
"active": "Active",
"pastDue": "Past Due",
"canceled": "Canceled",
"incomplete": "Incomplete",
"trialing": "Trial",
"none": "No Subscription"
},
"renewsOn": "Renews on {{date}}",
"cancelsOn": "Cancels on {{date}}"
},
"billing": {
"manageBilling": "Manage Billing",
"portal": {
"error": "Failed to open billing portal"
}
},
"payment": {
"preparing": "Preparing your checkout...",
"upgradeTitle": "Upgrade to {{planName}}",
"success": "Payment Successful!",
"successMessage": "Your subscription has been activated successfully. You will receive a confirmation email shortly.",
"autoClose": "This window will close automatically...",
"error": "Payment Error"
},
"firstLogin": {
"title": "First Time Login",
"welcomeTitle": "Welcome!",
@@ -4725,136 +4592,5 @@
"passwordMustBeDifferent": "New password must be different from current password",
"passwordChangedSuccess": "Password changed successfully! Please log in again.",
"passwordChangeFailed": "Failed to change password. Please check your current password."
},
"invite": {
"welcome": "Welcome to Stirling PDF",
"invalidToken": "Invalid invitation link",
"validationError": "Failed to validate invitation link",
"passwordRequired": "Password is required",
"passwordTooShort": "Password must be at least 6 characters",
"passwordMismatch": "Passwords do not match",
"acceptError": "Failed to create account",
"validating": "Validating invitation...",
"invalidInvitation": "Invalid Invitation",
"goToLogin": "Go to Login",
"welcomeTitle": "You've been invited!",
"welcomeSubtitle": "Complete your account setup to get started",
"accountFor": "Creating account for",
"linkExpires": "Link expires",
"email": "Email address",
"emailPlaceholder": "Enter your email address",
"emailRequired": "Email address is required",
"invalidEmail": "Invalid email address",
"choosePassword": "Choose a password",
"passwordPlaceholder": "Enter your password",
"confirmPassword": "Confirm password",
"confirmPasswordPlaceholder": "Re-enter your password",
"createAccount": "Create Account",
"creating": "Creating Account...",
"alreadyHaveAccount": "Already have an account?",
"signIn": "Sign in"
},
"audit": {
"error": {
"title": "Error loading audit system"
},
"notAvailable": "Audit system not available",
"notAvailableMessage": "The audit system is not configured or not available.",
"disabled": "Audit logging is disabled",
"disabledMessage": "Enable audit logging in your application configuration to track system events.",
"systemStatus": {
"title": "System Status",
"status": "Audit Logging",
"enabled": "Enabled",
"disabled": "Disabled",
"level": "Audit Level",
"retention": "Retention Period",
"days": "days",
"totalEvents": "Total Events"
},
"tabs": {
"dashboard": "Dashboard",
"events": "Audit Events",
"export": "Export"
},
"charts": {
"title": "Audit Dashboard",
"error": "Error loading charts",
"day": "Day",
"week": "Week",
"month": "Month",
"byType": "Events by Type",
"byUser": "Events by User",
"overTime": "Events Over Time"
},
"events": {
"title": "Audit Events",
"filterByType": "Filter by type",
"filterByUser": "Filter by user",
"startDate": "Start date",
"endDate": "End date",
"clearFilters": "Clear",
"error": "Error loading events",
"noEvents": "No events found",
"timestamp": "Timestamp",
"type": "Type",
"user": "User",
"ipAddress": "IP Address",
"actions": "Actions",
"viewDetails": "View Details",
"eventDetails": "Event Details",
"details": "Details"
},
"export": {
"title": "Export Audit Data",
"description": "Export audit events to CSV or JSON format. Use filters to limit the exported data.",
"format": "Export Format",
"filters": "Filters (Optional)",
"filterByType": "Filter by type",
"filterByUser": "Filter by user",
"startDate": "Start date",
"endDate": "End date",
"clearFilters": "Clear",
"exportButton": "Export Data",
"error": "Failed to export data"
}
},
"usage": {
"noData": "No data available",
"error": "Error loading usage statistics",
"noDataMessage": "No usage statistics are currently available.",
"controls": {
"top10": "Top 10",
"top20": "Top 20",
"all": "All",
"refresh": "Refresh",
"dataTypeLabel": "Data Type:",
"dataType": {
"all": "All",
"api": "API",
"ui": "UI"
}
},
"showing": {
"top10": "Top 10",
"top20": "Top 20",
"all": "All"
},
"stats": {
"totalEndpoints": "Total Endpoints",
"totalVisits": "Total Visits",
"showing": "Showing",
"selectedVisits": "Selected Visits"
},
"chart": {
"title": "Endpoint Usage Chart"
},
"table": {
"title": "Detailed Statistics",
"endpoint": "Endpoint",
"visits": "Visits",
"percentage": "Percentage",
"noData": "No data available"
}
}
}
@@ -1,6 +1,5 @@
import React from 'react';
import { Box } from '@mantine/core';
import { useRainbowThemeContext } from '../shared/RainbowThemeProvider';
import { useRainbowThemeContext } from '@app/components/shared/RainbowThemeProvider';
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
import { useFileHandler } from '@app/hooks/useFileHandler';
import { useFileState } from '@app/contexts/FileContext';
@@ -8,16 +7,16 @@ import { useNavigationState, useNavigationActions } from '@app/contexts/Navigati
import { isBaseWorkbench } from '@app/types/workbench';
import { useViewer } from '@app/contexts/ViewerContext';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import './Workbench.css';
import '@app/components/layout/Workbench.css';
import TopControls from '../shared/TopControls';
import FileEditor from '../fileEditor/FileEditor';
import PageEditor from '../pageEditor/PageEditor';
import PageEditorControls from '../pageEditor/PageEditorControls';
import Viewer from '../viewer/Viewer';
import LandingPage from '../shared/LandingPage';
import Footer from '../shared/Footer';
import DismissAllErrorsButton from '../shared/DismissAllErrorsButton';
import TopControls from '@app/components/shared/TopControls';
import FileEditor from '@app/components/fileEditor/FileEditor';
import PageEditor from '@app/components/pageEditor/PageEditor';
import PageEditorControls from '@app/components/pageEditor/PageEditorControls';
import Viewer from '@app/components/viewer/Viewer';
import LandingPage from '@app/components/shared/LandingPage';
import Footer from '@app/components/shared/Footer';
import DismissAllErrorsButton from '@app/components/shared/DismissAllErrorsButton';
// No props needed - component uses contexts directly
export default function Workbench() {
@@ -192,7 +191,7 @@ export default function Workbench() {
</Box>
<Footer
analyticsEnabled={config?.enableAnalytics}
analyticsEnabled={config?.enableAnalytics === true}
termsAndConditions={config?.termsAndConditions}
privacyPolicy={config?.privacyPolicy}
cookiePolicy={config?.cookiePolicy}
@@ -1,14 +1,13 @@
import React, { useMemo, useState, useEffect } from 'react';
import { Modal, Text, ActionIcon, Tooltip } from '@mantine/core';
import { Modal, Text, ActionIcon } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';
import { useNavigate, useLocation } from 'react-router-dom';
import LocalIcon from '@app/components/shared/LocalIcon';
import Overview from '@app/components/shared/config/configSections/Overview';
import { createConfigNavSections } from '@app/components/shared/config/configNavSections';
import { NavKey } from '@app/components/shared/config/types';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import '@app/components/shared/AppConfigModal.css';
import { Z_INDEX_OVER_FULLSCREEN_SURFACE, Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
interface AppConfigModalProps {
opened: boolean;
@@ -16,50 +15,20 @@ interface AppConfigModalProps {
}
const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
const navigate = useNavigate();
const location = useLocation();
const [active, setActive] = useState<NavKey>('general');
const [active, setActive] = useState<NavKey>('overview');
const isMobile = useMediaQuery("(max-width: 1024px)");
const { config } = useAppConfig();
// Extract section from URL path (e.g., /settings/people -> people)
const getSectionFromPath = (pathname: string): NavKey | null => {
const match = pathname.match(/\/settings\/([^/]+)/);
if (match && match[1]) {
const validSections: NavKey[] = [
'people', 'teams', 'general', 'hotkeys',
'adminGeneral', 'adminSecurity', 'adminConnections', 'adminLegal',
'adminPrivacy', 'adminDatabase', 'adminPremium', 'adminFeatures',
'adminPlan', 'adminAudit', 'adminUsage', 'adminEndpoints', 'adminAdvanced'
];
const section = match[1] as NavKey;
return validSections.includes(section) ? section : null;
}
return null;
};
// Sync active state with URL path
useEffect(() => {
const section = getSectionFromPath(location.pathname);
if (opened && section) {
setActive(section);
} else if (opened && location.pathname.startsWith('/settings') && !section) {
// If at /settings without a section, redirect to general
navigate('/settings/general', { replace: true });
}
}, [location.pathname, opened, navigate]);
// Handle custom events for backwards compatibility
useEffect(() => {
const handler = (ev: Event) => {
const detail = (ev as CustomEvent).detail as { key?: NavKey } | undefined;
if (detail?.key) {
navigate(`/settings/${detail.key}`);
setActive(detail.key);
}
};
window.addEventListener('appConfig:navigate', handler as EventListener);
return () => window.removeEventListener('appConfig:navigate', handler as EventListener);
}, [navigate]);
}, []);
const colors = useMemo(() => ({
navBg: 'var(--modal-nav-bg)',
@@ -77,21 +46,17 @@ const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
console.log('Logout placeholder for SaaS compatibility');
};
// Get isAdmin and runningEE from app config
// Get isAdmin from app config (based on JWT role)
const isAdmin = config?.isAdmin ?? false;
const runningEE = config?.runningEE ?? false;
console.log('[AppConfigModal] Config:', { isAdmin, runningEE, fullConfig: config });
// Left navigation structure and icons
const configNavSections = useMemo(() =>
createConfigNavSections(
Overview,
handleLogout,
isAdmin,
runningEE
isAdmin
),
[isAdmin, runningEE]
[isAdmin]
);
const activeLabel = useMemo(() => {
@@ -110,16 +75,10 @@ const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
return null;
}, [configNavSections, active]);
const handleClose = () => {
// Navigate back to home when closing modal
navigate('/', { replace: true });
onClose();
};
return (
<Modal
opened={opened}
onClose={handleClose}
onClose={onClose}
title={null}
size={isMobile ? "100%" : 980}
centered
@@ -150,24 +109,15 @@ const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
<div className="modal-nav-section-items">
{section.items.map(item => {
const isActive = active === item.key;
const isDisabled = item.disabled ?? false;
const color = isActive ? colors.navItemActive : colors.navItem;
const iconSize = isMobile ? 28 : 18;
const navItemContent = (
return (
<div
key={item.key}
onClick={() => {
if (!isDisabled) {
setActive(item.key);
navigate(`/settings/${item.key}`);
}
}}
onClick={() => setActive(item.key)}
className={`modal-nav-item ${isMobile ? 'mobile' : ''}`}
style={{
background: isActive ? colors.navItemActiveBg : 'transparent',
opacity: isDisabled ? 0.5 : 1,
cursor: isDisabled ? 'not-allowed' : 'pointer',
}}
>
<LocalIcon icon={item.icon} width={iconSize} height={iconSize} style={{ color }} />
@@ -178,20 +128,6 @@ const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
)}
</div>
);
return isDisabled && item.disabledTooltip ? (
<Tooltip
key={item.key}
label={item.disabledTooltip}
position="right"
withArrow
zIndex={Z_INDEX_OVER_CONFIG_MODAL}
>
{navItemContent}
</Tooltip>
) : (
<React.Fragment key={item.key}>{navItemContent}</React.Fragment>
);
})}
</div>
</div>
@@ -211,7 +147,7 @@ const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
}}
>
<Text fw={700} size="lg">{activeLabel}</Text>
<ActionIcon variant="subtle" onClick={handleClose} aria-label="Close">
<ActionIcon variant="subtle" onClick={onClose} aria-label="Close">
<LocalIcon icon="close-rounded" width={18} height={18} />
</ActionIcon>
</div>
@@ -1,6 +1,6 @@
import React from 'react';
import { addCollection, Icon } from '@iconify/react';
import iconSet from '../../../assets/material-symbols-icons.json';
import iconSet from '../../../assets/material-symbols-icons.json'; // eslint-disable-line no-restricted-imports -- Outside app paths
// Load icons synchronously at import time - guaranteed to be ready on first render
let iconsLoaded = false;
@@ -29,7 +29,7 @@ interface LocalIconProps {
* LocalIcon component that uses our locally bundled Material Symbols icons
* instead of loading from CDN
*/
export const LocalIcon: React.FC<LocalIconProps> = ({ icon, ...props }) => {
export const LocalIcon: React.FC<LocalIconProps> = ({ icon, width, height, style, ...props }) => {
// Convert our icon naming convention to the local collection format
const iconName = icon.startsWith('material-symbols:')
? icon
@@ -45,8 +45,20 @@ export const LocalIcon: React.FC<LocalIconProps> = ({ icon, ...props }) => {
}
}
const iconStyle: React.CSSProperties = { ...style };
// Use width if provided, otherwise fall back to height
const size = width || height;
if (size && typeof size === 'string') {
// If it's a CSS unit string (like '1.5rem'), use it as fontSize
iconStyle.fontSize = size;
} else if (typeof size === 'number') {
// If it's a number, treat it as pixels
iconStyle.fontSize = `${size}px`;
}
// Always render the icon - Iconify will use local if available, CDN if not
return <Icon icon={iconName} {...props} />;
return <Icon icon={iconName} style={iconStyle} {...props} />;
};
export default LocalIcon;
@@ -1,37 +0,0 @@
import React, { useState } from 'react';
import { Button } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import licenseService from '@app/services/licenseService';
import { alert } from '@app/components/toast';
interface ManageBillingButtonProps {
returnUrl?: string;
}
export const ManageBillingButton: React.FC<ManageBillingButtonProps> = ({
returnUrl = window.location.href,
}) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const handleClick = async () => {
try {
setLoading(true);
const response = await licenseService.createBillingPortalSession(returnUrl);
window.location.href = response.url;
} catch (error) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
});
setLoading(false);
}
};
return (
<Button variant="outline" onClick={handleClick} loading={loading}>
{t('billing.manageBilling', 'Manage Billing')}
</Button>
);
};
@@ -1,7 +1,6 @@
import React, { useState, useRef, forwardRef, useEffect } from "react";
import { ActionIcon, Stack, Divider } from "@mantine/core";
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import LocalIcon from '@app/components/shared/LocalIcon';
import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
import { useIsOverflowing } from '@app/hooks/useIsOverflowing';
@@ -24,8 +23,6 @@ import {
const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const { isRainbowMode } = useRainbowThemeContext();
const { openFilesModal, isFilesModalOpen } = useFilesModalContext();
const { handleReaderToggle, handleToolSelect, selectedToolKey, leftPanelView, toolRegistry, readerMode, resetTool } = useToolWorkflow();
@@ -37,12 +34,6 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
const scrollableRef = useRef<HTMLDivElement>(null);
const isOverflow = useIsOverflowing(scrollableRef);
// Open modal if URL is at /settings/*
useEffect(() => {
const isSettings = location.pathname.startsWith('/settings');
setConfigModalOpen(isSettings);
}, [location.pathname]);
useEffect(() => {
const next = getActiveNavButton(selectedToolKey, readerMode);
setActiveButton(next);
@@ -189,7 +180,6 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
size: 'lg',
type: 'modal',
onClick: () => {
navigate('/settings/overview');
setConfigModalOpen(true);
}
}
@@ -1,178 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Modal, Button, Text, Alert, Loader, Stack } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { loadStripe } from '@stripe/stripe-js';
import { EmbeddedCheckoutProvider, EmbeddedCheckout } from '@stripe/react-stripe-js';
import licenseService from '@app/services/licenseService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
// Initialize Stripe - this should come from environment variables
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || '');
interface StripeCheckoutProps {
opened: boolean;
onClose: () => void;
planId: string;
planName: string;
planPrice: number;
currency: string;
onSuccess?: (sessionId: string) => void;
onError?: (error: string) => void;
}
type CheckoutState = {
status: 'idle' | 'loading' | 'ready' | 'success' | 'error';
clientSecret?: string;
error?: string;
sessionId?: string;
};
const StripeCheckout: React.FC<StripeCheckoutProps> = ({
opened,
onClose,
planId,
planName,
planPrice,
currency,
onSuccess,
onError,
}) => {
const { t } = useTranslation();
const [state, setState] = useState<CheckoutState>({ status: 'idle' });
const createCheckoutSession = async () => {
try {
setState({ status: 'loading' });
const response = await licenseService.createCheckoutSession({
planId,
currency,
successUrl: `${window.location.origin}/settings/adminPlan?session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: `${window.location.origin}/settings/adminPlan`,
});
setState({
status: 'ready',
clientSecret: response.clientSecret,
sessionId: response.sessionId,
});
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to create checkout session';
setState({
status: 'error',
error: errorMessage,
});
onError?.(errorMessage);
}
};
const handlePaymentComplete = () => {
setState({ status: 'success' });
onSuccess?.(state.sessionId || '');
};
const handleClose = () => {
setState({ status: 'idle' });
onClose();
};
// Initialize checkout when modal opens
useEffect(() => {
if (opened && state.status === 'idle') {
createCheckoutSession();
} else if (!opened) {
setState({ status: 'idle' });
}
}, [opened]);
const renderContent = () => {
switch (state.status) {
case 'loading':
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '2rem 0' }}>
<Loader size="lg" />
<Text size="sm" c="dimmed" mt="md">
{t('payment.preparing', 'Preparing your checkout...')}
</Text>
</div>
);
case 'ready':
if (!state.clientSecret) return null;
return (
<EmbeddedCheckoutProvider
key={state.clientSecret}
stripe={stripePromise}
options={{
clientSecret: state.clientSecret,
onComplete: handlePaymentComplete,
}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
case 'success':
return (
<Alert color="green" title={t('payment.success', 'Payment Successful!')}>
<Stack gap="md">
<Text size="sm">
{t(
'payment.successMessage',
'Your subscription has been activated successfully. You will receive a confirmation email shortly.'
)}
</Text>
<Text size="xs" c="dimmed">
{t('payment.autoClose', 'This window will close automatically...')}
</Text>
</Stack>
</Alert>
);
case 'error':
return (
<Alert color="red" title={t('payment.error', 'Payment Error')}>
<Stack gap="md">
<Text size="sm">{state.error}</Text>
<Button variant="outline" onClick={handleClose}>
{t('common.close', 'Close')}
</Button>
</Stack>
</Alert>
);
default:
return null;
}
};
return (
<Modal
opened={opened}
onClose={handleClose}
title={
<div>
<Text fw={600} size="lg">
{t('payment.upgradeTitle', 'Upgrade to {{planName}}', { planName })}
</Text>
<Text size="sm" c="dimmed">
{currency}
{planPrice}/{t('plan.period.month', 'month')}
</Text>
</div>
}
size="xl"
centered
withCloseButton={state.status !== 'ready'}
closeOnEscape={state.status !== 'ready'}
closeOnClickOutside={state.status !== 'ready'}
zIndex={Z_INDEX_OVER_CONFIG_MODAL}
>
{renderContent()}
</Modal>
);
};
export default StripeCheckout;
@@ -2,6 +2,8 @@ import React from 'react';
import { NavKey } from '@app/components/shared/config/types';
import HotkeysSection from '@app/components/shared/config/configSections/HotkeysSection';
import GeneralSection from '@app/components/shared/config/configSections/GeneralSection';
import PeopleSection from '@app/components/shared/config/configSections/PeopleSection';
import TeamsSection from '@app/components/shared/config/configSections/TeamsSection';
import AdminGeneralSection from '@app/components/shared/config/configSections/AdminGeneralSection';
import AdminSecuritySection from '@app/components/shared/config/configSections/AdminSecuritySection';
import AdminConnectionsSection from '@app/components/shared/config/configSections/AdminConnectionsSection';
@@ -12,17 +14,12 @@ import AdminLegalSection from '@app/components/shared/config/configSections/Admi
import AdminPremiumSection from '@app/components/shared/config/configSections/AdminPremiumSection';
import AdminFeaturesSection from '@app/components/shared/config/configSections/AdminFeaturesSection';
import AdminEndpointsSection from '@app/components/shared/config/configSections/AdminEndpointsSection';
import AdminPlanSection from '@app/components/shared/config/configSections/AdminPlanSection';
import AdminAuditSection from '@app/components/shared/config/configSections/AdminAuditSection';
import AdminUsageSection from '@app/components/shared/config/configSections/AdminUsageSection';
export interface ConfigNavItem {
key: NavKey;
label: string;
icon: string;
component: React.ReactNode;
disabled?: boolean;
disabledTooltip?: string;
}
export interface ConfigNavSection {
@@ -43,10 +40,37 @@ export interface ConfigColors {
export const createConfigNavSections = (
Overview: React.ComponentType<{ onLogoutClick: () => void }>,
onLogoutClick: () => void,
isAdmin: boolean = false,
runningEE: boolean = false
isAdmin: boolean = false
): ConfigNavSection[] => {
const sections: ConfigNavSection[] = [
{
title: 'Account',
items: [
{
key: 'overview',
label: 'Overview',
icon: 'person-rounded',
component: <Overview onLogoutClick={onLogoutClick} />
},
],
},
{
title: 'Workspace',
items: [
{
key: 'people',
label: 'People',
icon: 'group-rounded',
component: <PeopleSection />
},
{
key: 'teams',
label: 'Teams',
icon: 'groups-rounded',
component: <TeamsSection />
},
],
},
{
title: 'Preferences',
items: [
@@ -66,18 +90,53 @@ export const createConfigNavSections = (
},
];
// Add Admin sections if user is admin
// Add Admin Settings section if user is admin
if (isAdmin) {
// Configuration
sections.push({
title: 'Configuration',
title: 'Admin Settings',
items: [
{
key: 'adminGeneral',
label: 'System Settings',
label: 'General',
icon: 'settings-rounded',
component: <AdminGeneralSection />
},
{
key: 'adminSecurity',
label: 'Security',
icon: 'shield-rounded',
component: <AdminSecuritySection />
},
{
key: 'adminConnections',
label: 'Connections',
icon: 'link-rounded',
component: <AdminConnectionsSection />
},
{
key: 'adminLegal',
label: 'Legal',
icon: 'gavel-rounded',
component: <AdminLegalSection />
},
{
key: 'adminPrivacy',
label: 'Privacy',
icon: 'visibility-rounded',
component: <AdminPrivacySection />
},
{
key: 'adminDatabase',
label: 'Database',
icon: 'storage-rounded',
component: <AdminDatabaseSection />
},
{
key: 'adminPremium',
label: 'Premium',
icon: 'star-rounded',
component: <AdminPremiumSection />
},
{
key: 'adminFeatures',
label: 'Features',
@@ -90,12 +149,6 @@ export const createConfigNavSections = (
icon: 'api-rounded',
component: <AdminEndpointsSection />
},
{
key: 'adminDatabase',
label: 'Database',
icon: 'storage-rounded',
component: <AdminDatabaseSection />
},
{
key: 'adminAdvanced',
label: 'Advanced',
@@ -104,79 +157,6 @@ export const createConfigNavSections = (
},
],
});
// Security & Authentication
sections.push({
title: 'Security & Authentication',
items: [
{
key: 'adminSecurity',
label: 'Security',
icon: 'shield-rounded',
component: <AdminSecuritySection />
},
{
key: 'adminConnections',
label: 'Connections',
icon: 'link-rounded',
component: <AdminConnectionsSection />
},
],
});
// Licensing & Analytics
sections.push({
title: 'Licensing & Analytics',
items: [
{
key: 'adminPremium',
label: 'Premium',
icon: 'star-rounded',
component: <AdminPremiumSection />
},
{
key: 'adminPlan',
label: 'Plan',
icon: 'receipt-long-rounded',
component: <AdminPlanSection />
},
{
key: 'adminAudit',
label: 'Audit',
icon: 'fact-check-rounded',
component: <AdminAuditSection />,
disabled: !runningEE,
disabledTooltip: 'Requires Enterprise license'
},
{
key: 'adminUsage',
label: 'Usage Analytics',
icon: 'analytics-rounded',
component: <AdminUsageSection />,
disabled: !runningEE,
disabledTooltip: 'Requires Enterprise license'
},
],
});
// Policies & Privacy
sections.push({
title: 'Policies & Privacy',
items: [
{
key: 'adminLegal',
label: 'Legal',
icon: 'gavel-rounded',
component: <AdminLegalSection />
},
{
key: 'adminPrivacy',
label: 'Privacy',
icon: 'visibility-rounded',
component: <AdminPrivacySection />
},
],
});
}
return sections;
@@ -1,99 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Tabs, Loader, Alert, Stack } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import auditService, { AuditSystemStatus as AuditStatus } from '@app/services/auditService';
import AuditSystemStatus from './audit/AuditSystemStatus';
import AuditChartsSection from './audit/AuditChartsSection';
import AuditEventsTable from './audit/AuditEventsTable';
import AuditExportSection from './audit/AuditExportSection';
const AdminAuditSection: React.FC = () => {
const { t } = useTranslation();
const [systemStatus, setSystemStatus] = useState<AuditStatus | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchSystemStatus = async () => {
try {
setLoading(true);
setError(null);
const status = await auditService.getSystemStatus();
setSystemStatus(status);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load audit system status');
} finally {
setLoading(false);
}
};
fetchSystemStatus();
}, []);
if (loading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '2rem 0' }}>
<Loader size="lg" />
</div>
);
}
if (error) {
return (
<Alert color="red" title={t('audit.error.title', 'Error loading audit system')}>
{error}
</Alert>
);
}
if (!systemStatus) {
return (
<Alert color="yellow" title={t('audit.notAvailable', 'Audit system not available')}>
{t('audit.notAvailableMessage', 'The audit system is not configured or not available.')}
</Alert>
);
}
return (
<Stack gap="lg">
<AuditSystemStatus status={systemStatus} />
{systemStatus.enabled ? (
<Tabs defaultValue="dashboard">
<Tabs.List>
<Tabs.Tab value="dashboard">
{t('audit.tabs.dashboard', 'Dashboard')}
</Tabs.Tab>
<Tabs.Tab value="events">
{t('audit.tabs.events', 'Audit Events')}
</Tabs.Tab>
<Tabs.Tab value="export">
{t('audit.tabs.export', 'Export')}
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="dashboard" pt="md">
<AuditChartsSection />
</Tabs.Panel>
<Tabs.Panel value="events" pt="md">
<AuditEventsTable />
</Tabs.Panel>
<Tabs.Panel value="export" pt="md">
<AuditExportSection />
</Tabs.Panel>
</Tabs>
) : (
<Alert color="blue" title={t('audit.disabled', 'Audit logging is disabled')}>
{t(
'audit.disabledMessage',
'Enable audit logging in your application configuration to track system events.'
)}
</Alert>
)}
</Stack>
);
};
export default AdminAuditSection;
@@ -165,9 +165,9 @@ export default function AdminGeneralSection() {
return (
<Stack gap="lg">
<div>
<Text fw={600} size="lg">{t('admin.settings.general.title', 'System Settings')}</Text>
<Text fw={600} size="lg">{t('admin.settings.general.title', 'General')}</Text>
<Text size="sm" c="dimmed">
{t('admin.settings.general.description', 'Configure system-wide application settings including branding and default behaviour.')}
{t('admin.settings.general.description', 'Configure general application settings including branding and default behaviour.')}
</Text>
</div>
@@ -1,180 +0,0 @@
import React, { useState, useCallback, useEffect } from 'react';
import { Divider, Loader, Alert, Select, Group, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { usePlans } from '@app/hooks/usePlans';
import { PlanTier } from '@app/services/licenseService';
import StripeCheckout from '@app/components/shared/StripeCheckout';
import AvailablePlansSection from './plan/AvailablePlansSection';
import ActivePlanSection from './plan/ActivePlanSection';
import StaticPlanSection from './plan/StaticPlanSection';
import { userManagementService } from '@app/services/userManagementService';
import { useAppConfig } from '@app/contexts/AppConfigContext';
const AdminPlanSection: React.FC = () => {
const { t } = useTranslation();
const { config } = useAppConfig();
const [checkoutOpen, setCheckoutOpen] = useState(false);
const [selectedPlan, setSelectedPlan] = useState<PlanTier | null>(null);
const [currency, setCurrency] = useState<string>('gbp');
const [useStaticVersion, setUseStaticVersion] = useState(false);
const [currentLicenseInfo, setCurrentLicenseInfo] = useState<any>(null);
const { plans, currentSubscription, loading, error, refetch } = usePlans(currency);
// Check if we should use static version and fetch license info
useEffect(() => {
const fetchLicenseInfo = async () => {
try {
const adminData = await userManagementService.getUsers();
// Determine plan name based on config flags
let planName = 'Free';
if (config?.runningEE) {
planName = 'Enterprise';
} else if (config?.runningProOrHigher || adminData.premiumEnabled) {
planName = 'Pro';
}
setCurrentLicenseInfo({
planName,
maxUsers: adminData.maxAllowedUsers,
grandfathered: adminData.grandfatheredUserCount > 0,
});
} catch (err) {
console.error('Failed to fetch license info:', err);
}
};
// Check if Stripe is configured
const stripeKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;
if (!stripeKey || error) {
setUseStaticVersion(true);
fetchLicenseInfo();
}
}, [error, config]);
const currencyOptions = [
{ value: 'gbp', label: 'British pound (GBP, £)' },
{ value: 'usd', label: 'US dollar (USD, $)' },
{ value: 'eur', label: 'Euro (EUR, €)' },
{ value: 'cny', label: 'Chinese yuan (CNY, ¥)' },
{ value: 'inr', label: 'Indian rupee (INR, ₹)' },
{ value: 'brl', label: 'Brazilian real (BRL, R$)' },
{ value: 'idr', label: 'Indonesian rupiah (IDR, Rp)' },
];
const handleUpgradeClick = useCallback(
(plan: PlanTier) => {
if (plan.isContactOnly) {
// Open contact form or redirect to contact page
window.open('mailto:sales@stirlingpdf.com?subject=Enterprise Plan Inquiry', '_blank');
return;
}
if (!currentSubscription || plan.id !== currentSubscription.plan.id) {
setSelectedPlan(plan);
setCheckoutOpen(true);
}
},
[currentSubscription]
);
const handlePaymentSuccess = useCallback(
(sessionId: string) => {
console.log('Payment successful, session:', sessionId);
// Refetch plans to update current subscription
refetch();
// Close modal after brief delay to show success message
setTimeout(() => {
setCheckoutOpen(false);
setSelectedPlan(null);
}, 2000);
},
[refetch]
);
const handlePaymentError = useCallback((error: string) => {
console.error('Payment error:', error);
// Error is already displayed in the StripeCheckout component
}, []);
const handleCheckoutClose = useCallback(() => {
setCheckoutOpen(false);
setSelectedPlan(null);
}, []);
// Show static version if Stripe is not configured or there's an error
if (useStaticVersion) {
return <StaticPlanSection currentLicenseInfo={currentLicenseInfo} />;
}
// Early returns after all hooks are called
if (loading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '2rem 0' }}>
<Loader size="lg" />
</div>
);
}
if (error) {
// Fallback to static version on error
return <StaticPlanSection currentLicenseInfo={currentLicenseInfo} />;
}
if (!plans || !currentSubscription) {
return (
<Alert color="yellow" title="No data available">
Plans data is not available at the moment.
</Alert>
);
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
{/* Currency Selector */}
<div>
<Group justify="space-between" align="center" mb="md">
<Text size="lg" fw={600}>
{t('plan.currency', 'Currency')}
</Text>
<Select
value={currency}
onChange={(value) => setCurrency(value || 'gbp')}
data={currencyOptions}
searchable
clearable={false}
w={300}
/>
</Group>
</div>
<ActivePlanSection subscription={currentSubscription} />
<Divider />
<AvailablePlansSection
plans={plans}
currentPlanId={currentSubscription.plan.id}
onUpgradeClick={handleUpgradeClick}
/>
{/* Stripe Checkout Modal */}
{selectedPlan && (
<StripeCheckout
opened={checkoutOpen}
onClose={handleCheckoutClose}
planId={selectedPlan.id}
planName={selectedPlan.name}
planPrice={selectedPlan.price}
currency={selectedPlan.currency}
onSuccess={handlePaymentSuccess}
onError={handlePaymentError}
/>
)}
</div>
);
};
export default AdminPlanSection;
@@ -1,201 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
Stack,
Group,
Text,
Button,
SegmentedControl,
Loader,
Alert,
Card,
} from '@mantine/core';
import { useTranslation } from 'react-i18next';
import usageAnalyticsService, { EndpointStatisticsResponse } from '@app/services/usageAnalyticsService';
import UsageAnalyticsChart from './usage/UsageAnalyticsChart';
import UsageAnalyticsTable from './usage/UsageAnalyticsTable';
import LocalIcon from '@app/components/shared/LocalIcon';
const AdminUsageSection: React.FC = () => {
const { t } = useTranslation();
const [data, setData] = useState<EndpointStatisticsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [displayMode, setDisplayMode] = useState<'top10' | 'top20' | 'all'>('top10');
const [dataType, setDataType] = useState<'all' | 'api' | 'ui'>('all');
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const limit = displayMode === 'all' ? undefined : displayMode === 'top10' ? 10 : 20;
const response = await usageAnalyticsService.getEndpointStatistics(limit, dataType);
setData(response);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load usage statistics');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, [displayMode, dataType]);
const handleRefresh = () => {
fetchData();
};
const getDisplayModeLabel = () => {
switch (displayMode) {
case 'top10':
return t('usage.showing.top10', 'Top 10');
case 'top20':
return t('usage.showing.top20', 'Top 20');
case 'all':
return t('usage.showing.all', 'All');
default:
return '';
}
};
// Early returns for loading/error states
if (loading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', padding: '2rem' }}>
<Loader size="lg" />
</div>
);
}
if (error) {
return (
<Alert color="red" title={t('usage.error', 'Error loading usage statistics')}>
{error}
</Alert>
);
}
if (!data) {
return (
<Alert color="yellow" title={t('usage.noData', 'No data available')}>
{t('usage.noDataMessage', 'No usage statistics are currently available.')}
</Alert>
);
}
const chartData = data.endpoints.map((e) => ({ label: e.endpoint, value: e.visits }));
const displayedVisits = data.endpoints.reduce((sum, e) => sum + e.visits, 0);
const displayedPercentage = data.totalVisits > 0
? ((displayedVisits / data.totalVisits) * 100).toFixed(1)
: '0';
return (
<Stack gap="lg">
{/* Controls */}
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Group justify="space-between" wrap="wrap">
<Group>
<SegmentedControl
value={displayMode}
onChange={(value) => setDisplayMode(value as 'top10' | 'top20' | 'all')}
data={[
{
value: 'top10',
label: t('usage.controls.top10', 'Top 10'),
},
{
value: 'top20',
label: t('usage.controls.top20', 'Top 20'),
},
{
value: 'all',
label: t('usage.controls.all', 'All'),
},
]}
/>
<Button
variant="outline"
leftSection={<LocalIcon icon="refresh" width="1rem" height="1rem" />}
onClick={handleRefresh}
loading={loading}
>
{t('usage.controls.refresh', 'Refresh')}
</Button>
</Group>
</Group>
<Group>
<Text size="sm" fw={500}>
{t('usage.controls.dataTypeLabel', 'Data Type:')}
</Text>
<SegmentedControl
value={dataType}
onChange={(value) => setDataType(value as 'all' | 'api' | 'ui')}
data={[
{
value: 'all',
label: t('usage.controls.dataType.all', 'All'),
},
{
value: 'api',
label: t('usage.controls.dataType.api', 'API'),
},
{
value: 'ui',
label: t('usage.controls.dataType.ui', 'UI'),
},
]}
/>
</Group>
{/* Statistics Summary */}
<Group gap="xl" style={{ flexWrap: 'wrap' }}>
<div>
<Text size="sm" c="dimmed">
{t('usage.stats.totalEndpoints', 'Total Endpoints')}
</Text>
<Text size="lg" fw={600}>
{data.totalEndpoints}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
{t('usage.stats.totalVisits', 'Total Visits')}
</Text>
<Text size="lg" fw={600}>
{data.totalVisits.toLocaleString()}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
{t('usage.stats.showing', 'Showing')}
</Text>
<Text size="lg" fw={600}>
{getDisplayModeLabel()}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
{t('usage.stats.selectedVisits', 'Selected Visits')}
</Text>
<Text size="lg" fw={600}>
{displayedVisits.toLocaleString()} ({displayedPercentage}%)
</Text>
</div>
</Group>
</Stack>
</Card>
{/* Chart and Table */}
<UsageAnalyticsChart data={chartData} totalVisits={data.totalVisits} />
<UsageAnalyticsTable data={data.endpoints} totalVisits={data.totalVisits} />
</Stack>
);
};
export default AdminUsageSection;
@@ -1,98 +1,29 @@
import React, { useState, useEffect } from 'react';
import { Paper, Stack, Switch, Text, Tooltip, NumberInput, SegmentedControl, Alert, Code, Group, Anchor, ActionIcon } from '@mantine/core';
import { Paper, Stack, Switch, Text, Tooltip, NumberInput, SegmentedControl } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { usePreferences } from '@app/contexts/PreferencesContext';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import type { ToolPanelMode } from '@app/constants/toolPanel';
import LocalIcon from '@app/components/shared/LocalIcon';
const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;
const BANNER_DISMISSED_KEY = 'stirlingpdf_features_banner_dismissed';
interface GeneralSectionProps {
hideTitle?: boolean;
}
const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false }) => {
const GeneralSection: React.FC = () => {
const { t } = useTranslation();
const { preferences, updatePreference } = usePreferences();
const { config } = useAppConfig();
const [fileLimitInput, setFileLimitInput] = useState<number | string>(preferences.autoUnzipFileLimit);
const [bannerDismissed, setBannerDismissed] = useState(() => {
// Check localStorage on mount
return localStorage.getItem(BANNER_DISMISSED_KEY) === 'true';
});
// Sync local state with preference changes
useEffect(() => {
setFileLimitInput(preferences.autoUnzipFileLimit);
}, [preferences.autoUnzipFileLimit]);
// Check if login is disabled
const loginDisabled = !config?.enableLogin;
const handleDismissBanner = () => {
setBannerDismissed(true);
localStorage.setItem(BANNER_DISMISSED_KEY, 'true');
};
return (
<Stack gap="lg">
{!hideTitle && (
<div>
<Text fw={600} size="lg">{t('settings.general.title', 'General')}</Text>
<Text size="sm" c="dimmed">
{t('settings.general.description', 'Configure general application preferences.')}
</Text>
</div>
)}
{loginDisabled && !bannerDismissed && (
<Paper withBorder p="md" radius="md" style={{ background: 'var(--mantine-color-blue-0)', position: 'relative' }}>
<ActionIcon
variant="subtle"
color="gray"
size="sm"
style={{ position: 'absolute', top: '0.5rem', right: '0.5rem' }}
onClick={handleDismissBanner}
aria-label={t('settings.general.enableFeatures.dismiss', 'Dismiss')}
>
<LocalIcon icon="close-rounded" width="1rem" height="1rem" />
</ActionIcon>
<Stack gap="sm">
<Group gap="xs">
<LocalIcon icon="admin-panel-settings-rounded" width="1.2rem" height="1.2rem" style={{ color: 'var(--mantine-color-blue-6)' }} />
<Text fw={600} size="sm" style={{ color: 'var(--mantine-color-blue-9)' }}>
{t('settings.general.enableFeatures.title', 'For System Administrators')}
</Text>
</Group>
<Text size="sm" c="dimmed">
{t('settings.general.enableFeatures.intro', 'Enable user authentication, team management, and workspace features for your organization.')}
</Text>
<Group gap="xs" wrap="wrap">
<Text size="sm" c="dimmed">
{t('settings.general.enableFeatures.action', 'Configure')}
</Text>
<Code>SECURITY_ENABLELOGIN=true</Code>
<Text size="sm" c="dimmed">
{t('settings.general.enableFeatures.and', 'and')}
</Text>
<Code>DISABLE_ADDITIONAL_FEATURES=false</Code>
</Group>
<Text size="xs" c="dimmed" fs="italic">
{t('settings.general.enableFeatures.benefit', 'Enables user roles, team collaboration, admin controls, and enterprise features.')}
</Text>
<Anchor
href="https://docs.stirlingpdf.com/Advanced%20Configuration/System%20and%20Security"
target="_blank"
size="sm"
style={{ color: 'var(--mantine-color-blue-6)' }}
>
{t('settings.general.enableFeatures.learnMore', 'Learn more in documentation')} →
</Anchor>
</Stack>
</Paper>
)}
<div>
<Text fw={600} size="lg">{t('settings.general.title', 'General')}</Text>
<Text size="sm" c="dimmed">
{t('settings.general.description', 'Configure general application preferences.')}
</Text>
</div>
<Paper withBorder p="md" radius="md">
<Stack gap="md">
@@ -23,7 +23,7 @@ import {
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
import { userManagementService, User } from '@app/services/userManagementService';
import { teamService, Team } from '@proprietary/services/teamService';
import { teamService, Team } from '@app/services/teamService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
import { useAppConfig } from '@app/contexts/AppConfigContext';
@@ -40,16 +40,6 @@ export default function PeopleSection() {
const [processing, setProcessing] = useState(false);
const [inviteMode, setInviteMode] = useState<'email' | 'direct'>('direct');
// License information
const [licenseInfo, setLicenseInfo] = useState<{
maxAllowedUsers: number;
availableSlots: number;
grandfatheredUserCount: number;
licenseMaxUsers: number;
premiumEnabled: boolean;
totalUsers: number;
} | null>(null);
// Form state for direct invite
const [inviteForm, setInviteForm] = useState({
username: '',
@@ -99,16 +89,6 @@ export default function PeopleSection() {
setUsers(enrichedUsers);
setTeams(teamsData);
// Store license information
setLicenseInfo({
maxAllowedUsers: adminData.maxAllowedUsers,
availableSlots: adminData.availableSlots,
grandfatheredUserCount: adminData.grandfatheredUserCount,
licenseMaxUsers: adminData.licenseMaxUsers,
premiumEnabled: adminData.premiumEnabled,
totalUsers: adminData.totalUsers,
});
} catch (error) {
console.error('Failed to fetch people data:', error);
alert({ alertType: 'error', title: 'Failed to load people data' });
@@ -345,39 +325,6 @@ export default function PeopleSection() {
</Text>
</div>
{/* License Information - Compact */}
{licenseInfo && (
<Group gap="md" c="dimmed" style={{ fontSize: '0.875rem' }}>
<Text size="sm" span>
<Text component="span" fw={600} c="inherit">{licenseInfo.totalUsers}</Text>
<Text component="span" c="dimmed"> / </Text>
<Text component="span" fw={600} c="inherit">{licenseInfo.maxAllowedUsers}</Text>
<Text component="span" c="dimmed" ml={4}>{t('workspace.people.license.users', 'users')}</Text>
</Text>
{licenseInfo.availableSlots === 0 && (
<Badge color="red" variant="light" size="sm">
{t('workspace.people.license.noSlotsAvailable', 'No slots available')}
</Badge>
)}
{licenseInfo.grandfatheredUserCount > 0 && (
<Text size="sm" c="dimmed" span>
•
<Text component="span" ml={4}>
{t('workspace.people.license.grandfatheredShort', '{{count}} grandfathered', { count: licenseInfo.grandfatheredUserCount })}
</Text>
</Text>
)}
{licenseInfo.premiumEnabled && licenseInfo.licenseMaxUsers > 0 && (
<Badge color="blue" variant="light" size="sm">
+{licenseInfo.licenseMaxUsers} {t('workspace.people.license.fromLicense', 'from license')}
</Badge>
)}
</Group>
)}
{/* Header Actions */}
<Group justify="space-between">
<TextInput
@@ -387,149 +334,77 @@ export default function PeopleSection() {
onChange={(e) => setSearchQuery(e.currentTarget.value)}
style={{ maxWidth: 300 }}
/>
<Tooltip
label={t('workspace.people.license.noSlotsAvailable', 'No user slots available')}
disabled={!licenseInfo || licenseInfo.availableSlots > 0}
position="bottom"
withArrow
>
<Button
leftSection={<LocalIcon icon="person-add" width="1rem" height="1rem" />}
onClick={() => setInviteModalOpened(true)}
disabled={licenseInfo && licenseInfo.availableSlots === 0}
>
{t('workspace.people.addMembers')}
</Button>
</Tooltip>
<Button leftSection={<LocalIcon icon="person-add" width="1rem" height="1rem" />} onClick={() => setInviteModalOpened(true)}>
{t('workspace.people.addMembers')}
</Button>
</Group>
{/* Members Table */}
<Table
horizontalSpacing="md"
verticalSpacing="sm"
style={{
'--table-border-color': 'var(--mantine-color-gray-3)',
} as React.CSSProperties}
>
<Table.Thead>
<Table.Tr style={{ backgroundColor: 'var(--mantine-color-gray-0)' }}>
<Table.Th style={{ fontWeight: 600, color: 'var(--mantine-color-gray-7)' }} fz="sm">
{t('workspace.people.user')}
</Table.Th>
<Table.Th style={{ fontWeight: 600, color: 'var(--mantine-color-gray-7)' }} fz="sm" w={100}>
{t('workspace.people.role')}
</Table.Th>
<Table.Th style={{ fontWeight: 600, color: 'var(--mantine-color-gray-7)' }} fz="sm">
{t('workspace.people.team')}
</Table.Th>
<Table.Th w={50}></Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{filteredUsers.length === 0 ? (
<Paper withBorder p="md">
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Td colSpan={4}>
<Text ta="center" c="dimmed" py="xl">
{t('workspace.people.noMembersFound')}
</Text>
</Table.Td>
<Table.Th>{t('workspace.people.user')}</Table.Th>
<Table.Th>{t('workspace.people.role')}</Table.Th>
<Table.Th>{t('workspace.people.team')}</Table.Th>
<Table.Th>{t('workspace.people.status')}</Table.Th>
<Table.Th style={{ width: 50 }}></Table.Th>
</Table.Tr>
) : (
filteredUsers.map((user) => (
<Table.Tr
key={user.id}
style={{
borderBottom: '1px solid var(--mantine-color-gray-3)',
}}
>
<Table.Td>
<Group gap="xs" wrap="nowrap">
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
backgroundColor: user.enabled
? 'var(--mantine-color-blue-1)'
: 'var(--mantine-color-gray-2)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontWeight: 600,
fontSize: '0.875rem',
color: user.enabled
? 'var(--mantine-color-blue-7)'
: 'var(--mantine-color-gray-6)',
flexShrink: 0,
border: user.isActive ? '2px solid var(--mantine-color-green-6)' : 'none',
opacity: user.enabled ? 1 : 0.5,
}}
title={
!user.enabled
? t('workspace.people.disabled', 'Disabled')
: user.isActive
? t('workspace.people.activeSession', 'Active session')
: t('workspace.people.active', 'Active')
}
>
{user.username.charAt(0).toUpperCase()}
</div>
<div style={{ minWidth: 0, flex: 1 }}>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
</Table.Thead>
<Table.Tbody>
{filteredUsers.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={5}>
<Text ta="center" c="dimmed" py="xl">
{t('workspace.people.noMembersFound')}
</Text>
</Table.Td>
</Table.Tr>
) : (
filteredUsers.map((user) => (
<Table.Tr key={user.id}>
<Table.Td>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
{user.isActive && (
<div
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
width: '6px',
height: '6px',
borderRadius: '50%',
backgroundColor: 'var(--mantine-color-green-6)',
flexShrink: 0,
}}
>
title={t('workspace.people.activeSession', 'Active session')}
/>
)}
<div>
<Text size="sm" fw={500}>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
</Text>
)}
{user.email && (
<Text size="xs" c="dimmed">
{user.email}
</Text>
)}
</div>
</div>
</Group>
</Table.Td>
<Table.Td w={100}>
<Badge
size="sm"
variant="light"
color={(user.rolesAsString || '').includes('ROLE_ADMIN') ? 'blue' : 'gray'}
>
{(user.rolesAsString || '').includes('ROLE_ADMIN')
? t('workspace.people.admin', 'Admin')
: t('workspace.people.member', 'Member')}
</Badge>
</Table.Td>
<Table.Td>
{user.team?.name ? (
<Tooltip label={user.team.name} disabled={user.team.name.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
c="dimmed"
maw={150}
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.team.name}
</Text>
</Tooltip>
) : (
<Text size="sm" c="dimmed">—</Text>
)}
</Table.Td>
</Table.Td>
<Table.Td>
<Badge
color={(user.rolesAsString || '').includes('ROLE_ADMIN') ? 'blue' : 'gray'}
variant="light"
>
{(user.rolesAsString || '').includes('ROLE_ADMIN') ? t('workspace.people.admin') : t('workspace.people.member')}
</Badge>
</Table.Td>
<Table.Td>
<Text size="sm">{user.team?.name || '—'}</Text>
</Table.Td>
<Table.Td>
<Badge color={user.enabled ? 'green' : 'red'} variant="light">
{user.enabled ? t('workspace.people.active') : t('workspace.people.disabled')}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs" wrap="nowrap">
{/* Info icon with tooltip */}
@@ -581,8 +456,9 @@ export default function PeopleSection() {
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
</Table.Tbody>
</Table>
</Paper>
{/* Add Member Modal */}
<Modal
@@ -600,8 +476,8 @@ export default function PeopleSection() {
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1
}}
/>
@@ -619,32 +495,6 @@ export default function PeopleSection() {
)}
</Stack>
{/* License Warning/Info */}
{licenseInfo && (
<Paper withBorder p="sm" bg={licenseInfo.availableSlots === 0 ? 'var(--mantine-color-red-light)' : 'var(--mantine-color-blue-light)'}>
<Stack gap="xs">
<Group gap="xs">
<LocalIcon icon={licenseInfo.availableSlots > 0 ? 'info' : 'warning'} width="1rem" height="1rem" />
<Text size="sm" fw={500}>
{licenseInfo.availableSlots > 0
? t('workspace.people.license.slotsAvailable', {
count: licenseInfo.availableSlots,
defaultValue: `${licenseInfo.availableSlots} user slot(s) available`
})
: t('workspace.people.license.noSlotsAvailable', 'No user slots available')}
</Text>
</Group>
<Text size="xs" c="dimmed">
{t('workspace.people.license.currentUsage', {
current: licenseInfo.totalUsers,
max: licenseInfo.maxAllowedUsers,
defaultValue: `Currently using ${licenseInfo.totalUsers} of ${licenseInfo.maxAllowedUsers} user licenses`
})}
</Text>
</Stack>
</Paper>
)}
{/* Mode Toggle */}
<Tooltip
label={t('workspace.people.inviteMode.emailDisabled', 'Email invites require SMTP configuration and mail.enableInvites=true in settings')}
@@ -779,8 +629,8 @@ export default function PeopleSection() {
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1
}}
/>
@@ -18,7 +18,7 @@ import {
} from '@mantine/core';
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
import { teamService, Team } from '@proprietary/services/teamService';
import { teamService, Team } from '@app/services/teamService';
import { User, userManagementService } from '@app/services/userManagementService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
@@ -42,11 +42,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
const [selectedTeamId, setSelectedTeamId] = useState<string>('');
const [processing, setProcessing] = useState(false);
// License information
const [licenseInfo, setLicenseInfo] = useState<{
availableSlots: number;
} | null>(null);
useEffect(() => {
fetchTeamDetails();
fetchAllTeams();
@@ -55,20 +50,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
const fetchTeamDetails = async () => {
try {
setLoading(true);
const [data, adminData] = await Promise.all([
teamService.getTeamDetails(teamId),
userManagementService.getUsers(),
]);
const data = await teamService.getTeamDetails(teamId);
console.log('[TeamDetailsSection] Raw data:', data);
setTeam(data.team);
setTeamUsers(Array.isArray(data.teamUsers) ? data.teamUsers : []);
setAvailableUsers(Array.isArray(data.availableUsers) ? data.availableUsers : []);
setUserLastRequest(data.userLastRequest || {});
// Store license information
setLicenseInfo({
availableSlots: adminData.availableSlots,
});
} catch (error) {
console.error('Failed to fetch team details:', error);
alert({ alertType: 'error', title: 'Failed to load team details' });
@@ -240,131 +227,65 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
{/* Add Member Button */}
<Group justify="flex-end">
<Tooltip
label={t('workspace.people.license.noSlotsAvailable', 'No user slots available')}
disabled={!licenseInfo || licenseInfo.availableSlots > 0}
position="bottom"
withArrow
zIndex={Z_INDEX_OVER_CONFIG_MODAL}
<Button
leftSection={<LocalIcon icon="person-add" width="1rem" height="1rem" />}
onClick={() => setAddMemberModalOpened(true)}
disabled={team.name === 'Internal'}
>
<Button
leftSection={<LocalIcon icon="person-add" width="1rem" height="1rem" />}
onClick={() => setAddMemberModalOpened(true)}
disabled={team.name === 'Internal' || (licenseInfo && licenseInfo.availableSlots === 0)}
>
{t('workspace.teams.addMember')}
</Button>
</Tooltip>
{t('workspace.teams.addMember')}
</Button>
</Group>
{/* Members Table */}
<Table
horizontalSpacing="md"
verticalSpacing="sm"
style={{
'--table-border-color': 'var(--mantine-color-gray-3)',
} as React.CSSProperties}
>
<Table.Thead>
<Table.Tr style={{ backgroundColor: 'var(--mantine-color-gray-0)' }}>
<Table.Th style={{ fontWeight: 600, color: 'var(--mantine-color-gray-7)' }} fz="sm">
{t('workspace.people.user')}
</Table.Th>
<Table.Th style={{ fontWeight: 600, color: 'var(--mantine-color-gray-7)' }} fz="sm" w={100}>
{t('workspace.people.role')}
</Table.Th>
<Table.Th w={50}></Table.Th>
</Table.Tr>
</Table.Thead>
<Paper withBorder p="md">
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>{t('workspace.people.user')}</Table.Th>
<Table.Th>{t('workspace.people.role')}</Table.Th>
<Table.Th>{t('workspace.people.status')}</Table.Th>
<Table.Th style={{ width: 50 }}></Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{teamUsers.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={3}>
<Table.Td colSpan={4}>
<Text ta="center" c="dimmed" py="xl">
{t('workspace.teams.noMembers', 'No members in this team')}
</Text>
</Table.Td>
</Table.Tr>
) : (
teamUsers.map((user) => {
const isActive = userLastRequest[user.username] &&
(Date.now() - userLastRequest[user.username]) < 5 * 60 * 1000; // Active within last 5 minutes
return (
<Table.Tr
key={user.id}
style={{
borderBottom: '1px solid var(--mantine-color-gray-3)',
}}
>
<Table.Td>
<Group gap="xs" wrap="nowrap">
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
backgroundColor: user.enabled
? 'var(--mantine-color-blue-1)'
: 'var(--mantine-color-gray-2)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontWeight: 600,
fontSize: '0.875rem',
color: user.enabled
? 'var(--mantine-color-blue-7)'
: 'var(--mantine-color-gray-6)',
flexShrink: 0,
border: isActive ? '2px solid var(--mantine-color-green-6)' : 'none',
opacity: user.enabled ? 1 : 0.5,
}}
title={
!user.enabled
? t('workspace.people.disabled', 'Disabled')
: isActive
? t('workspace.people.activeSession', 'Active session')
: t('workspace.people.active', 'Active')
}
>
{user.username.charAt(0).toUpperCase()}
</div>
<div style={{ minWidth: 0, flex: 1 }}>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
</Text>
)}
</div>
</Group>
</Table.Td>
<Table.Td w={100}>
<Badge
size="sm"
color={(user.rolesAsString || '').includes('ROLE_ADMIN') ? 'blue' : 'gray'}
variant="light"
>
{(user.rolesAsString || '').includes('ROLE_ADMIN')
? t('workspace.people.admin')
: t('workspace.people.member')}
</Badge>
</Table.Td>
teamUsers.map((user) => (
<Table.Tr key={user.id}>
<Table.Td>
<div>
<Text size="sm" fw={500}>
{user.username}
</Text>
{user.email && (
<Text size="xs" c="dimmed">
{user.email}
</Text>
)}
</div>
</Table.Td>
<Table.Td>
<Badge
color={(user.rolesAsString || '').includes('ROLE_ADMIN') ? 'blue' : 'gray'}
variant="light"
>
{(user.rolesAsString || '').includes('ROLE_ADMIN')
? t('workspace.people.admin')
: t('workspace.people.member')}
</Badge>
</Table.Td>
<Table.Td>
<Badge color={user.enabled ? 'green' : 'red'} variant="light">
{user.enabled ? t('workspace.people.active') : t('workspace.people.disabled')}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs" wrap="nowrap">
{/* Info icon with tooltip */}
@@ -431,11 +352,11 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
</Group>
</Table.Td>
</Table.Tr>
);
})
))
)}
</Table.Tbody>
</Table>
</Table>
</Paper>
{/* Add Member Modal */}
<Modal
@@ -453,8 +374,8 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1,
}}
/>
@@ -512,8 +433,8 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1,
}}
/>
@@ -15,14 +15,13 @@ import {
Paper,
Select,
CloseButton,
Tooltip,
} from '@mantine/core';
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
import { teamService, Team } from '@proprietary/services/teamService';
import { teamService, Team } from '@app/services/teamService';
import { userManagementService, User } from '@app/services/userManagementService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
import TeamDetailsSection from '@proprietary/components/shared/config/configSections/TeamDetailsSection';
import TeamDetailsSection from '@app/components/shared/config/configSections/TeamDetailsSection';
export default function TeamsSection() {
const { t } = useTranslation();
@@ -225,24 +224,15 @@ export default function TeamsSection() {
</Group>
{/* Teams Table */}
<Table
horizontalSpacing="md"
verticalSpacing="sm"
style={{
'--table-border-color': 'var(--mantine-color-gray-3)',
} as React.CSSProperties}
>
<Table.Thead>
<Table.Tr style={{ backgroundColor: 'var(--mantine-color-gray-0)' }}>
<Table.Th style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--mantine-color-gray-7)' }}>
{t('workspace.teams.teamName')}
</Table.Th>
<Table.Th style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--mantine-color-gray-7)' }}>
{t('workspace.teams.totalMembers')}
</Table.Th>
<Table.Th style={{ width: 50 }}></Table.Th>
</Table.Tr>
</Table.Thead>
<Paper withBorder p="md">
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>{t('workspace.teams.teamName')}</Table.Th>
<Table.Th>{t('workspace.teams.totalMembers')}</Table.Th>
<Table.Th style={{ width: 50 }}></Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{teams.length === 0 ? (
<Table.Tr>
@@ -256,44 +246,23 @@ export default function TeamsSection() {
teams.map((team) => (
<Table.Tr
key={team.id}
style={{
cursor: 'pointer',
borderBottom: '1px solid var(--mantine-color-gray-3)',
}}
style={{ cursor: 'pointer' }}
onClick={() => setViewingTeamId(team.id)}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = 'var(--mantine-color-gray-0)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
<Table.Td>
<Group gap="xs">
<Tooltip label={team.name} disabled={team.name.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
c="dark"
maw={200}
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{team.name}
</Text>
</Tooltip>
<Text size="sm" fw={500}>
{team.name}
</Text>
{team.name === 'Internal' && (
<Badge size="xs" color="gray" variant="light">
<Badge size="xs" color="gray">
{t('workspace.teams.system')}
</Badge>
)}
</Group>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">{team.userCount || 0}</Text>
<Text size="sm">{team.userCount || 0}</Text>
</Table.Td>
<Table.Td onClick={(e) => e.stopPropagation()}>
<Menu position="bottom-end" withinPortal>
@@ -328,7 +297,8 @@ export default function TeamsSection() {
))
)}
</Table.Tbody>
</Table>
</Table>
</Paper>
{/* Create Team Modal */}
<Modal
@@ -346,8 +316,8 @@ export default function TeamsSection() {
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1
}}
/>
@@ -391,8 +361,8 @@ export default function TeamsSection() {
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1
}}
/>
@@ -439,8 +409,8 @@ export default function TeamsSection() {
size="lg"
style={{
position: 'absolute',
top: -8,
right: -8,
top: '-8px',
right: '-8px',
zIndex: 1
}}
/>
@@ -1,165 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Card, Text, Group, Stack, SegmentedControl, Loader, Alert } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import auditService, { AuditChartsData } from '@app/services/auditService';
interface SimpleBarChartProps {
data: { label: string; value: number }[];
title: string;
color?: string;
}
const SimpleBarChart: React.FC<SimpleBarChartProps> = ({ data, title, color = 'blue' }) => {
const maxValue = Math.max(...data.map((d) => d.value), 1);
return (
<Stack gap="sm">
<Text size="sm" fw={600}>
{title}
</Text>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
{data.map((item, index) => (
<div key={index}>
<Group justify="space-between" mb={4}>
<Text size="xs" c="dimmed" maw={200} style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
{item.label}
</Text>
<Text size="xs" fw={600}>
{item.value}
</Text>
</Group>
<div
style={{
width: '100%',
height: 8,
backgroundColor: 'var(--mantine-color-gray-2)',
borderRadius: 4,
overflow: 'hidden',
}}
>
<div
style={{
width: `${(item.value / maxValue) * 100}%`,
height: '100%',
backgroundColor: `var(--mantine-color-${color}-6)`,
transition: 'width 0.3s ease',
}}
/>
</div>
</div>
))}
</div>
</Stack>
);
};
interface AuditChartsSectionProps {}
const AuditChartsSection: React.FC<AuditChartsSectionProps> = () => {
const { t } = useTranslation();
const [timePeriod, setTimePeriod] = useState<'day' | 'week' | 'month'>('week');
const [chartsData, setChartsData] = useState<AuditChartsData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchChartsData = async () => {
try {
setLoading(true);
setError(null);
const data = await auditService.getChartsData(timePeriod);
setChartsData(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load charts');
} finally {
setLoading(false);
}
};
fetchChartsData();
}, [timePeriod]);
if (loading) {
return (
<Card padding="lg" radius="md" withBorder>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Loader size="lg" my="xl" />
</div>
</Card>
);
}
if (error) {
return (
<Alert color="red" title={t('audit.charts.error', 'Error loading charts')}>
{error}
</Alert>
);
}
if (!chartsData) {
return null;
}
const eventsByTypeData = chartsData.eventsByType.labels.map((label, index) => ({
label,
value: chartsData.eventsByType.values[index],
}));
const eventsByUserData = chartsData.eventsByUser.labels.map((label, index) => ({
label,
value: chartsData.eventsByUser.values[index],
}));
const eventsOverTimeData = chartsData.eventsOverTime.labels.map((label, index) => ({
label,
value: chartsData.eventsOverTime.values[index],
}));
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="lg">
<Group justify="space-between" align="center">
<Text size="lg" fw={600}>
{t('audit.charts.title', 'Audit Dashboard')}
</Text>
<SegmentedControl
value={timePeriod}
onChange={(value) => setTimePeriod(value as 'day' | 'week' | 'month')}
data={[
{ label: t('audit.charts.day', 'Day'), value: 'day' },
{ label: t('audit.charts.week', 'Week'), value: 'week' },
{ label: t('audit.charts.month', 'Month'), value: 'month' },
]}
/>
</Group>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gap: '1.5rem',
}}
>
<SimpleBarChart
data={eventsByTypeData}
title={t('audit.charts.byType', 'Events by Type')}
color="blue"
/>
<SimpleBarChart
data={eventsByUserData}
title={t('audit.charts.byUser', 'Events by User')}
color="green"
/>
<SimpleBarChart
data={eventsOverTimeData}
title={t('audit.charts.overTime', 'Events Over Time')}
color="purple"
/>
</div>
</Stack>
</Card>
);
};
export default AuditChartsSection;
@@ -1,300 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
Card,
Text,
Group,
Stack,
Select,
TextInput,
Button,
Pagination,
Modal,
Code,
Loader,
Alert,
} from '@mantine/core';
import { DateInput } from '@mantine/dates';
import { useTranslation } from 'react-i18next';
import auditService, { AuditEvent, AuditFilters } from '@app/services/auditService';
interface AuditEventsTableProps {}
const AuditEventsTable: React.FC<AuditEventsTableProps> = () => {
const { t } = useTranslation();
const [events, setEvents] = useState<AuditEvent[]>([]);
const [totalPages, setTotalPages] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedEvent, setSelectedEvent] = useState<AuditEvent | null>(null);
const [eventTypes, setEventTypes] = useState<string[]>([]);
const [users, setUsers] = useState<string[]>([]);
// Filters
const [filters, setFilters] = useState<AuditFilters>({
eventType: undefined,
username: undefined,
startDate: undefined,
endDate: undefined,
page: 0,
pageSize: 20,
});
useEffect(() => {
const fetchMetadata = async () => {
try {
const [types, usersList] = await Promise.all([
auditService.getEventTypes(),
auditService.getUsers(),
]);
setEventTypes(types);
setUsers(usersList);
} catch (err) {
console.error('Failed to fetch metadata:', err);
}
};
fetchMetadata();
}, []);
useEffect(() => {
const fetchEvents = async () => {
try {
setLoading(true);
setError(null);
const response = await auditService.getEvents({
...filters,
page: currentPage - 1,
});
setEvents(response.events);
setTotalPages(response.totalPages);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load events');
} finally {
setLoading(false);
}
};
fetchEvents();
}, [filters, currentPage]);
const handleFilterChange = (key: keyof AuditFilters, value: any) => {
setFilters((prev) => ({ ...prev, [key]: value }));
setCurrentPage(1);
};
const handleClearFilters = () => {
setFilters({
eventType: undefined,
username: undefined,
startDate: undefined,
endDate: undefined,
page: 0,
pageSize: 20,
});
setCurrentPage(1);
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString();
};
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Text size="lg" fw={600}>
{t('audit.events.title', 'Audit Events')}
</Text>
{/* Filters */}
<Group>
<Select
placeholder={t('audit.events.filterByType', 'Filter by type')}
data={eventTypes.map((type) => ({ value: type, label: type }))}
value={filters.eventType}
onChange={(value) => handleFilterChange('eventType', value || undefined)}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
<Select
placeholder={t('audit.events.filterByUser', 'Filter by user')}
data={users.map((user) => ({ value: user, label: user }))}
value={filters.username}
onChange={(value) => handleFilterChange('username', value || undefined)}
clearable
searchable
style={{ flex: 1, minWidth: 200 }}
/>
<DateInput
placeholder={t('audit.events.startDate', 'Start date')}
value={filters.startDate ? new Date(filters.startDate) : null}
onChange={(value) =>
handleFilterChange('startDate', value ? value.toISOString() : undefined)
}
clearable
style={{ flex: 1, minWidth: 150 }}
/>
<DateInput
placeholder={t('audit.events.endDate', 'End date')}
value={filters.endDate ? new Date(filters.endDate) : null}
onChange={(value) =>
handleFilterChange('endDate', value ? value.toISOString() : undefined)
}
clearable
style={{ flex: 1, minWidth: 150 }}
/>
<Button variant="outline" onClick={handleClearFilters}>
{t('audit.events.clearFilters', 'Clear')}
</Button>
</Group>
{/* Table */}
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Loader size="lg" my="xl" />
</div>
) : error ? (
<Alert color="red" title={t('audit.events.error', 'Error loading events')}>
{error}
</Alert>
) : (
<>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr
style={{
borderBottom: '2px solid var(--mantine-color-gray-3)',
}}
>
<th style={{ textAlign: 'left' }}>
{t('audit.events.timestamp', 'Timestamp')}
</th>
<th style={{ textAlign: 'left' }}>
{t('audit.events.type', 'Type')}
</th>
<th style={{ textAlign: 'left' }}>
{t('audit.events.user', 'User')}
</th>
<th style={{ textAlign: 'left' }}>
{t('audit.events.ipAddress', 'IP Address')}
</th>
<th style={{ textAlign: 'center' }}>
{t('audit.events.actions', 'Actions')}
</th>
</tr>
</thead>
<tbody>
{events.length === 0 ? (
<tr>
<td colSpan={5} style={{ textAlign: 'center', padding: '2rem' }}>
<Text c="dimmed">{t('audit.events.noEvents', 'No events found')}</Text>
</td>
</tr>
) : (
events.map((event) => (
<tr
key={event.id}
style={{
borderBottom: '1px solid var(--mantine-color-gray-2)',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor =
'var(--mantine-color-gray-0)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
<td>
<Text size="sm">{formatDate(event.timestamp)}</Text>
</td>
<td>
<Text size="sm">{event.eventType}</Text>
</td>
<td>
<Text size="sm">{event.username}</Text>
</td>
<td>
<Text size="sm">{event.ipAddress}</Text>
</td>
<td style={{ textAlign: 'center' }}>
<Button
variant="subtle"
size="xs"
onClick={() => setSelectedEvent(event)}
>
{t('audit.events.viewDetails', 'View Details')}
</Button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<Group justify="center" mt="md">
<Pagination
value={currentPage}
onChange={setCurrentPage}
total={totalPages}
/>
</Group>
)}
</>
)}
</Stack>
{/* Event Details Modal */}
<Modal
opened={selectedEvent !== null}
onClose={() => setSelectedEvent(null)}
title={t('audit.events.eventDetails', 'Event Details')}
size="lg"
>
{selectedEvent && (
<Stack gap="md">
<div>
<Text size="sm" fw={600} c="dimmed">
{t('audit.events.timestamp', 'Timestamp')}
</Text>
<Text size="sm">{formatDate(selectedEvent.timestamp)}</Text>
</div>
<div>
<Text size="sm" fw={600} c="dimmed">
{t('audit.events.type', 'Type')}
</Text>
<Text size="sm">{selectedEvent.eventType}</Text>
</div>
<div>
<Text size="sm" fw={600} c="dimmed">
{t('audit.events.user', 'User')}
</Text>
<Text size="sm">{selectedEvent.username}</Text>
</div>
<div>
<Text size="sm" fw={600} c="dimmed">
{t('audit.events.ipAddress', 'IP Address')}
</Text>
<Text size="sm">{selectedEvent.ipAddress}</Text>
</div>
<div>
<Text size="sm" fw={600} c="dimmed">
{t('audit.events.details', 'Details')}
</Text>
<Code block mah={300} style={{ overflow: 'auto' }}>
{JSON.stringify(selectedEvent.details, null, 2)}
</Code>
</div>
</Stack>
)}
</Modal>
</Card>
);
};
export default AuditEventsTable;
@@ -1,182 +0,0 @@
import React, { useState } from 'react';
import {
Card,
Text,
Group,
Stack,
Select,
Button,
SegmentedControl,
} from '@mantine/core';
import { DateInput } from '@mantine/dates';
import { useTranslation } from 'react-i18next';
import auditService, { AuditFilters } from '@app/services/auditService';
import LocalIcon from '@app/components/shared/LocalIcon';
interface AuditExportSectionProps {}
const AuditExportSection: React.FC<AuditExportSectionProps> = () => {
const { t } = useTranslation();
const [exportFormat, setExportFormat] = useState<'csv' | 'json'>('csv');
const [exporting, setExporting] = useState(false);
const [eventTypes, setEventTypes] = useState<string[]>([]);
const [users, setUsers] = useState<string[]>([]);
// Filters for export
const [filters, setFilters] = useState<AuditFilters>({
eventType: undefined,
username: undefined,
startDate: undefined,
endDate: undefined,
});
React.useEffect(() => {
const fetchMetadata = async () => {
try {
const [types, usersList] = await Promise.all([
auditService.getEventTypes(),
auditService.getUsers(),
]);
setEventTypes(types);
setUsers(usersList);
} catch (err) {
console.error('Failed to fetch metadata:', err);
}
};
fetchMetadata();
}, []);
const handleExport = async () => {
try {
setExporting(true);
const blob = await auditService.exportData(exportFormat, filters);
// Create download link
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `audit-export-${new Date().toISOString()}.${exportFormat}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (err) {
console.error('Export failed:', err);
alert(t('audit.export.error', 'Failed to export data'));
} finally {
setExporting(false);
}
};
const handleFilterChange = (key: keyof AuditFilters, value: any) => {
setFilters((prev) => ({ ...prev, [key]: value }));
};
const handleClearFilters = () => {
setFilters({
eventType: undefined,
username: undefined,
startDate: undefined,
endDate: undefined,
});
};
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Text size="lg" fw={600}>
{t('audit.export.title', 'Export Audit Data')}
</Text>
<Text size="sm" c="dimmed">
{t(
'audit.export.description',
'Export audit events to CSV or JSON format. Use filters to limit the exported data.'
)}
</Text>
{/* Format Selection */}
<div>
<Text size="sm" fw={600} mb="xs">
{t('audit.export.format', 'Export Format')}
</Text>
<SegmentedControl
value={exportFormat}
onChange={(value) => setExportFormat(value as 'csv' | 'json')}
data={[
{ label: 'CSV', value: 'csv' },
{ label: 'JSON', value: 'json' },
]}
/>
</div>
{/* Filters */}
<div>
<Text size="sm" fw={600} mb="xs">
{t('audit.export.filters', 'Filters (Optional)')}
</Text>
<Stack gap="sm">
<Group>
<Select
placeholder={t('audit.export.filterByType', 'Filter by type')}
data={eventTypes.map((type) => ({ value: type, label: type }))}
value={filters.eventType}
onChange={(value) => handleFilterChange('eventType', value || undefined)}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
<Select
placeholder={t('audit.export.filterByUser', 'Filter by user')}
data={users.map((user) => ({ value: user, label: user }))}
value={filters.username}
onChange={(value) => handleFilterChange('username', value || undefined)}
clearable
searchable
style={{ flex: 1, minWidth: 200 }}
/>
</Group>
<Group>
<DateInput
placeholder={t('audit.export.startDate', 'Start date')}
value={filters.startDate ? new Date(filters.startDate) : null}
onChange={(value) =>
handleFilterChange('startDate', value ? value.toISOString() : undefined)
}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
<DateInput
placeholder={t('audit.export.endDate', 'End date')}
value={filters.endDate ? new Date(filters.endDate) : null}
onChange={(value) =>
handleFilterChange('endDate', value ? value.toISOString() : undefined)
}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
<Button variant="outline" onClick={handleClearFilters}>
{t('audit.export.clearFilters', 'Clear')}
</Button>
</Group>
</Stack>
</div>
{/* Export Button */}
<Group justify="flex-end">
<Button
leftSection={<LocalIcon icon="download" width="1rem" height="1rem" />}
onClick={handleExport}
loading={exporting}
disabled={exporting}
>
{t('audit.export.exportButton', 'Export Data')}
</Button>
</Group>
</Stack>
</Card>
);
};
export default AuditExportSection;
@@ -1,64 +0,0 @@
import React from 'react';
import { Card, Group, Stack, Badge, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { AuditSystemStatus as AuditStatus } from '@app/services/auditService';
interface AuditSystemStatusProps {
status: AuditStatus;
}
const AuditSystemStatus: React.FC<AuditSystemStatusProps> = ({ status }) => {
const { t } = useTranslation();
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Text size="lg" fw={600}>
{t('audit.systemStatus.title', 'System Status')}
</Text>
<Group justify="space-between">
<div>
<Text size="sm" c="dimmed">
{t('audit.systemStatus.status', 'Audit Logging')}
</Text>
<Badge color={status.enabled ? 'green' : 'red'} variant="light" size="lg" mt="xs">
{status.enabled
? t('audit.systemStatus.enabled', 'Enabled')
: t('audit.systemStatus.disabled', 'Disabled')}
</Badge>
</div>
<div>
<Text size="sm" c="dimmed">
{t('audit.systemStatus.level', 'Audit Level')}
</Text>
<Text size="lg" fw={600} mt="xs">
{status.level}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
{t('audit.systemStatus.retention', 'Retention Period')}
</Text>
<Text size="lg" fw={600} mt="xs">
{status.retentionDays} {t('audit.systemStatus.days', 'days')}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
{t('audit.systemStatus.totalEvents', 'Total Events')}
</Text>
<Text size="lg" fw={600} mt="xs">
{status.totalEvents.toLocaleString()}
</Text>
</div>
</Group>
</Stack>
</Card>
);
};
export default AuditSystemStatus;
@@ -1,89 +0,0 @@
import React from 'react';
import { Card, Text, Group, Stack, Badge } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { SubscriptionInfo } from '@app/services/licenseService';
import { ManageBillingButton } from '@app/components/shared/ManageBillingButton';
interface ActivePlanSectionProps {
subscription: SubscriptionInfo;
}
const ActivePlanSection: React.FC<ActivePlanSectionProps> = ({ subscription }) => {
const { t } = useTranslation();
const getStatusBadge = (status: string) => {
const statusConfig: Record<
string,
{ color: string; label: string }
> = {
active: { color: 'green', label: t('subscription.status.active', 'Active') },
past_due: { color: 'yellow', label: t('subscription.status.pastDue', 'Past Due') },
canceled: { color: 'red', label: t('subscription.status.canceled', 'Canceled') },
incomplete: { color: 'orange', label: t('subscription.status.incomplete', 'Incomplete') },
trialing: { color: 'blue', label: t('subscription.status.trialing', 'Trial') },
none: { color: 'gray', label: t('subscription.status.none', 'No Subscription') },
};
const config = statusConfig[status] || statusConfig.none;
return (
<Badge color={config.color} variant="light">
{config.label}
</Badge>
);
};
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<h3 style={{ margin: 0, color: 'var(--mantine-color-text)', fontSize: '1rem' }}>
{t('plan.activePlan.title', 'Active Plan')}
</h3>
{subscription.status !== 'none' && subscription.stripeCustomerId && (
<ManageBillingButton returnUrl={`${window.location.origin}/settings/adminPlan`} />
)}
</div>
<p
style={{
margin: '0.25rem 0 1rem 0',
color: 'var(--mantine-color-dimmed)',
fontSize: '0.875rem',
}}
>
{t('plan.activePlan.subtitle', 'Your current subscription details')}
</p>
<Card padding="lg" radius="md" withBorder>
<Group justify="space-between" align="center">
<Stack gap="xs">
<Group gap="sm">
<Text size="lg" fw={600}>
{subscription.plan.name}
</Text>
{getStatusBadge(subscription.status)}
</Group>
{subscription.currentPeriodEnd && subscription.status === 'active' && (
<Text size="sm" c="dimmed">
{subscription.cancelAtPeriodEnd
? t('subscription.cancelsOn', 'Cancels on {{date}}', {
date: new Date(subscription.currentPeriodEnd).toLocaleDateString(),
})
: t('subscription.renewsOn', 'Renews on {{date}}', {
date: new Date(subscription.currentPeriodEnd).toLocaleDateString(),
})}
</Text>
)}
</Stack>
<div style={{ textAlign: 'right' }}>
<Text size="xl" fw={700}>
{subscription.plan.currency}
{subscription.plan.price}
/month
</Text>
</div>
</Group>
</Card>
</div>
);
};
export default ActivePlanSection;
@@ -1,131 +0,0 @@
import React, { useState } from 'react';
import { Button, Card, Badge, Text, Collapse } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { PlanTier } from '@app/services/licenseService';
import PlanCard from './PlanCard';
interface AvailablePlansSectionProps {
plans: PlanTier[];
currentPlanId: string;
onUpgradeClick: (plan: PlanTier) => void;
}
const AvailablePlansSection: React.FC<AvailablePlansSectionProps> = ({
plans,
currentPlanId,
onUpgradeClick,
}) => {
const { t } = useTranslation();
const [showComparison, setShowComparison] = useState(false);
return (
<div>
<h3 style={{ margin: 0, color: 'var(--mantine-color-text)', fontSize: '1rem' }}>
{t('plan.availablePlans.title', 'Available Plans')}
</h3>
<p
style={{
margin: '0.25rem 0 1rem 0',
color: 'var(--mantine-color-dimmed)',
fontSize: '0.875rem',
}}
>
{t('plan.availablePlans.subtitle', 'Choose the plan that fits your needs')}
</p>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gap: '1rem',
marginBottom: '1rem',
}}
>
{plans.map((plan) => (
<PlanCard
key={plan.id}
plan={plan}
isCurrentPlan={plan.id === currentPlanId}
onUpgradeClick={onUpgradeClick}
/>
))}
</div>
<div style={{ textAlign: 'center' }}>
<Button variant="subtle" onClick={() => setShowComparison(!showComparison)}>
{showComparison
? t('plan.hideComparison', 'Hide Feature Comparison')
: t('plan.showComparison', 'Compare All Features')}
</Button>
</div>
<Collapse in={showComparison}>
<Card padding="lg" radius="md" withBorder style={{ marginTop: '1rem' }}>
<Text size="lg" fw={600} mb="md">
{t('plan.featureComparison', 'Feature Comparison')}
</Text>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%' }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--mantine-color-gray-3)' }}>
<th style={{ textAlign: 'left', padding: '0.5rem' }}>
{t('plan.feature.title', 'Feature')}
</th>
{plans.map((plan) => (
<th
key={plan.id}
style={{ textAlign: 'center', padding: '0.5rem', minWidth: '6rem', position: 'relative' }}
>
{plan.name}
{plan.popular && (
<Badge
color="blue"
variant="filled"
style={{
position: 'absolute',
top: '0rem',
right: '-2rem',
fontSize: '0.5rem',
fontWeight: '500',
height: '1rem',
padding: '0 0.25rem',
}}
>
{t('plan.popular', 'Popular')}
</Badge>
)}
</th>
))}
</tr>
</thead>
<tbody>
{plans[0].features.map((_, featureIndex) => (
<tr
key={featureIndex}
style={{ borderBottom: '1px solid var(--mantine-color-gray-3)' }}
>
<td style={{ padding: '0.5rem' }}>{plans[0].features[featureIndex].name}</td>
{plans.map((plan) => (
<td key={plan.id} style={{ textAlign: 'center', padding: '0.5rem' }}>
{plan.features[featureIndex].included ? (
<Text c="green" fw={600}>
✓
</Text>
) : (
<Text c="gray">-</Text>
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</Card>
</Collapse>
</div>
);
};
export default AvailablePlansSection;
@@ -1,83 +0,0 @@
import React from 'react';
import { Button, Card, Badge, Text, Group, Stack } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { PlanTier } from '@app/services/licenseService';
interface PlanCardProps {
plan: PlanTier;
isCurrentPlan: boolean;
onUpgradeClick: (plan: PlanTier) => void;
}
const PlanCard: React.FC<PlanCardProps> = ({ plan, isCurrentPlan, onUpgradeClick }) => {
const { t } = useTranslation();
return (
<Card
key={plan.id}
padding="lg"
radius="md"
withBorder
style={{
position: 'relative',
display: 'flex',
flexDirection: 'column',
}}
>
{plan.popular && (
<Badge
variant="filled"
size="xs"
style={{ position: 'absolute', top: '0.5rem', right: '0.5rem' }}
>
{t('plan.popular', 'Popular')}
</Badge>
)}
<Stack gap="md" style={{ height: '100%' }}>
<div>
<Text size="lg" fw={600}>
{plan.name}
</Text>
<Group gap="xs" style={{ alignItems: 'baseline' }}>
<Text size="xl" fw={700} style={{ fontSize: '2rem' }}>
{plan.isContactOnly
? t('plan.customPricing', 'Custom')
: `${plan.currency}${plan.price}`}
</Text>
{!plan.isContactOnly && (
<Text size="sm" c="dimmed">
{plan.period}
</Text>
)}
</Group>
</div>
<Stack gap="xs">
{plan.highlights.map((highlight, index) => (
<Text key={index} size="sm" c="dimmed">
• {highlight}
</Text>
))}
</Stack>
<div style={{ flexGrow: 1 }} />
<Button
variant={isCurrentPlan ? 'filled' : plan.isContactOnly ? 'outline' : 'filled'}
disabled={isCurrentPlan}
fullWidth
onClick={() => onUpgradeClick(plan)}
>
{isCurrentPlan
? t('plan.current', 'Current Plan')
: plan.isContactOnly
? t('plan.contact', 'Contact Us')
: t('plan.upgrade', 'Upgrade')}
</Button>
</Stack>
</Card>
);
};
export default PlanCard;
@@ -1,262 +0,0 @@
import React from 'react';
import { Card, Text, Group, Stack, Badge, Button, Alert } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import LocalIcon from '@app/components/shared/LocalIcon';
interface StaticPlanSectionProps {
currentLicenseInfo?: {
planName: string;
maxUsers: number;
grandfathered: boolean;
};
}
const StaticPlanSection: React.FC<StaticPlanSectionProps> = ({ currentLicenseInfo }) => {
const { t } = useTranslation();
const staticPlans = [
{
id: 'free',
name: t('plan.free.name', 'Free'),
price: 0,
currency: '£',
period: t('plan.period.month', '/month'),
highlights: [
t('plan.free.highlight1', 'Limited Tool Usage Per week'),
t('plan.free.highlight2', 'Access to all tools'),
t('plan.free.highlight3', 'Community support'),
],
features: [
{ name: t('plan.feature.pdfTools', 'Basic PDF Tools'), included: true },
{ name: t('plan.feature.fileSize', 'File Size Limit'), included: false },
{ name: t('plan.feature.automation', 'Automate tool workflows'), included: false },
{ name: t('plan.feature.api', 'API Access'), included: false },
{ name: t('plan.feature.priority', 'Priority Support'), included: false },
],
maxUsers: 5,
},
{
id: 'pro',
name: t('plan.pro.name', 'Pro'),
price: 8,
currency: '£',
period: t('plan.period.month', '/month'),
popular: true,
highlights: [
t('plan.pro.highlight1', 'Unlimited Tool Usage'),
t('plan.pro.highlight2', 'Advanced PDF tools'),
t('plan.pro.highlight3', 'No watermarks'),
],
features: [
{ name: t('plan.feature.pdfTools', 'Basic PDF Tools'), included: true },
{ name: t('plan.feature.fileSize', 'File Size Limit'), included: true },
{ name: t('plan.feature.automation', 'Automate tool workflows'), included: true },
{ name: t('plan.feature.api', 'Weekly API Credits'), included: true },
{ name: t('plan.feature.priority', 'Priority Support'), included: false },
],
maxUsers: 'Unlimited',
},
{
id: 'enterprise',
name: t('plan.enterprise.name', 'Enterprise'),
price: 0,
currency: '',
period: '',
highlights: [
t('plan.enterprise.highlight1', 'Custom pricing'),
t('plan.enterprise.highlight2', 'Dedicated support'),
t('plan.enterprise.highlight3', 'Latest features'),
],
features: [
{ name: t('plan.feature.pdfTools', 'Basic PDF Tools'), included: true },
{ name: t('plan.feature.fileSize', 'File Size Limit'), included: true },
{ name: t('plan.feature.automation', 'Automate tool workflows'), included: true },
{ name: t('plan.feature.api', 'Weekly API Credits'), included: true },
{ name: t('plan.feature.priority', 'Priority Support'), included: true },
],
maxUsers: 'Custom',
},
];
const getCurrentPlan = () => {
if (!currentLicenseInfo) return staticPlans[0];
if (currentLicenseInfo.planName === 'Enterprise') return staticPlans[2];
if (currentLicenseInfo.maxUsers > 5) return staticPlans[1];
return staticPlans[0];
};
const currentPlan = getCurrentPlan();
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
{/* Stripe Not Configured Alert */}
<Alert color="blue" title={t('plan.static.title', 'Billing Information')}>
<Stack gap="sm">
<Text size="sm">
{t(
'plan.static.message',
'Online billing is not currently configured. To upgrade your plan or manage subscriptions, please contact us directly.'
)}
</Text>
<Button
variant="light"
leftSection={<LocalIcon icon="email" width="1rem" height="1rem" />}
onClick={() =>
window.open('mailto:sales@stirlingpdf.com?subject=License Upgrade Inquiry', '_blank')
}
style={{ width: 'fit-content' }}
>
{t('plan.static.contactSales', 'Contact Sales')}
</Button>
</Stack>
</Alert>
{/* Current Plan Section */}
<div>
<h3 style={{ margin: 0, color: 'var(--mantine-color-text)', fontSize: '1rem' }}>
{t('plan.activePlan.title', 'Active Plan')}
</h3>
<p
style={{
margin: '0.25rem 0 1rem 0',
color: 'var(--mantine-color-dimmed)',
fontSize: '0.875rem',
}}
>
{t('plan.activePlan.subtitle', 'Your current subscription details')}
</p>
<Card padding="lg" radius="md" withBorder>
<Group justify="space-between" align="center">
<Stack gap="xs">
<Group gap="sm">
<Text size="lg" fw={600}>
{currentPlan.name}
</Text>
<Badge color="green" variant="light">
{t('subscription.status.active', 'Active')}
</Badge>
</Group>
{currentLicenseInfo && (
<Text size="sm" c="dimmed">
{t('plan.static.maxUsers', 'Max Users')}: {currentLicenseInfo.maxUsers}
{currentLicenseInfo.grandfathered &&
` (${t('workspace.people.license.grandfathered', 'Grandfathered')})`}
</Text>
)}
</Stack>
<div style={{ textAlign: 'right' }}>
<Text size="xl" fw={700}>
{currentPlan.price === 0 ? t('plan.free.name', 'Free') : `${currentPlan.currency}${currentPlan.price}${currentPlan.period}`}
</Text>
</div>
</Group>
</Card>
</div>
{/* Available Plans */}
<div>
<h3 style={{ margin: 0, color: 'var(--mantine-color-text)', fontSize: '1rem' }}>
{t('plan.availablePlans.title', 'Available Plans')}
</h3>
<p
style={{
margin: '0.25rem 0 1rem 0',
color: 'var(--mantine-color-dimmed)',
fontSize: '0.875rem',
}}
>
{t('plan.static.contactToUpgrade', 'Contact us to upgrade or customize your plan')}
</p>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gap: '1rem',
paddingBottom: '1rem',
}}
>
{staticPlans.map((plan) => (
<Card
key={plan.id}
padding="lg"
radius="md"
withBorder
style={{
position: 'relative',
display: 'flex',
flexDirection: 'column',
}}
>
{plan.popular && (
<Badge
variant="filled"
size="xs"
style={{ position: 'absolute', top: '0.5rem', right: '0.5rem' }}
>
{t('plan.popular', 'Popular')}
</Badge>
)}
<Stack gap="md" style={{ height: '100%' }}>
<div>
<Text size="lg" fw={600}>
{plan.name}
</Text>
<Group gap="xs" style={{ alignItems: 'baseline' }}>
<Text size="xl" fw={700} style={{ fontSize: '2rem' }}>
{plan.price === 0 && plan.id !== 'free'
? t('plan.customPricing', 'Custom')
: plan.price === 0
? t('plan.free.name', 'Free')
: `${plan.currency}${plan.price}`}
</Text>
{plan.period && (
<Text size="sm" c="dimmed">
{plan.period}
</Text>
)}
</Group>
<Text size="xs" c="dimmed" mt="xs">
{typeof plan.maxUsers === 'string'
? plan.maxUsers
: `${t('plan.static.upTo', 'Up to')} ${plan.maxUsers} ${t('workspace.people.license.users', 'users')}`}
</Text>
</div>
<Stack gap="xs">
{plan.highlights.map((highlight, index) => (
<Text key={index} size="sm" c="dimmed">
• {highlight}
</Text>
))}
</Stack>
<div style={{ flexGrow: 1 }} />
<Button
variant={plan.id === currentPlan.id ? 'filled' : 'outline'}
disabled={plan.id === currentPlan.id}
fullWidth
onClick={() =>
window.open(
`mailto:sales@stirlingpdf.com?subject=Upgrade to ${plan.name} Plan`,
'_blank'
)
}
>
{plan.id === currentPlan.id
? t('plan.current', 'Current Plan')
: t('plan.contact', 'Contact Us')}
</Button>
</Stack>
</Card>
))}
</div>
</div>
</div>
);
};
export default StaticPlanSection;
@@ -1,89 +0,0 @@
import React from 'react';
import { Card, Text, Stack } from '@mantine/core';
import { useTranslation } from 'react-i18next';
interface SimpleBarChartProps {
data: { label: string; value: number }[];
maxValue: number;
}
const SimpleBarChart: React.FC<SimpleBarChartProps> = ({ data, maxValue }) => {
const { t } = useTranslation();
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
{data.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
{t('usage.noData', 'No data available')}
</Text>
) : (
data.map((item, index) => (
<div key={index}>
<div style={{ display: 'flex', justifyContent: 'space-between' }} mb={4}>
<Text
size="xs"
c="dimmed"
style={{
maxWidth: '60%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{item.label}
</Text>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<Text size="xs" fw={600}>
{item.value}
</Text>
<Text size="xs" c="dimmed">
({((item.value / maxValue) * 100).toFixed(1)}%)
</Text>
</div>
</div>
<div
style={{
width: '100%',
height: 8,
backgroundColor: 'var(--mantine-color-gray-2)',
borderRadius: 4,
overflow: 'hidden',
}}
>
<div
style={{
width: `${(item.value / maxValue) * 100}%`,
height: '100%',
backgroundColor: 'var(--mantine-color-blue-6)',
transition: 'width 0.3s ease',
}}
/>
</div>
</div>
))
)}
</div>
);
};
interface UsageAnalyticsChartProps {
data: { label: string; value: number }[];
totalVisits: number;
}
const UsageAnalyticsChart: React.FC<UsageAnalyticsChartProps> = ({ data, totalVisits }) => {
const { t } = useTranslation();
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Text size="lg" fw={600}>
{t('usage.chart.title', 'Endpoint Usage Chart')}
</Text>
<SimpleBarChart data={data} maxValue={Math.max(...data.map((d) => d.value), 1)} />
</Stack>
</Card>
);
};
export default UsageAnalyticsChart;
@@ -1,126 +0,0 @@
import React from 'react';
import { Card, Text, Stack } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { EndpointStatistic } from '@app/services/usageAnalyticsService';
interface UsageAnalyticsTableProps {
data: EndpointStatistic[];
totalVisits: number;
}
const UsageAnalyticsTable: React.FC<UsageAnalyticsTableProps> = ({ data, totalVisits }) => {
const { t } = useTranslation();
return (
<Card padding="lg" radius="md" withBorder>
<Stack gap="md">
<Text size="lg" fw={600}>
{t('usage.table.title', 'Detailed Statistics')}
</Text>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr
style={{
borderBottom: '2px solid var(--mantine-color-gray-3)',
}}
>
<th
style={{
textAlign: 'left',
fontSize: '0.875rem',
width: '5%',
}}
>
#
</th>
<th
style={{
textAlign: 'left',
fontSize: '0.875rem',
width: '55%',
}}
>
{t('usage.table.endpoint', 'Endpoint')}
</th>
<th
style={{
textAlign: 'right',
fontSize: '0.875rem',
width: '20%',
}}
>
{t('usage.table.visits', 'Visits')}
</th>
<th
style={{
textAlign: 'right',
fontSize: '0.875rem',
width: '20%',
}}
>
{t('usage.table.percentage', 'Percentage')}
</th>
</tr>
</thead>
<tbody>
{data.length === 0 ? (
<tr>
<td colSpan={4} style={{ textAlign: 'center', padding: '2rem' }}>
<Text c="dimmed">{t('usage.table.noData', 'No data available')}</Text>
</td>
</tr>
) : (
data.map((stat, index) => (
<tr
key={index}
style={{
borderBottom: '1px solid var(--mantine-color-gray-2)',
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = 'var(--mantine-color-gray-0)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
<td>
<Text size="sm" c="dimmed">
{index + 1}
</Text>
</td>
<td>
<Text
size="sm"
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{stat.endpoint}
</Text>
</td>
<td style={{ textAlign: 'right' }}>
<Text size="sm" fw={600}>
{stat.visits.toLocaleString()}
</Text>
</td>
<td style={{ textAlign: 'right' }}>
<Text size="sm" c="dimmed">
{stat.percentage.toFixed(2)}%
</Text>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</Stack>
</Card>
);
};
export default UsageAnalyticsTable;
@@ -1,4 +1,5 @@
export type NavKey =
| 'overview'
| 'preferences'
| 'notifications'
| 'connections'
@@ -22,9 +23,6 @@ export type NavKey =
| 'adminLegal'
| 'adminPremium'
| 'adminFeatures'
| 'adminPlan'
| 'adminAudit'
| 'adminUsage'
| 'adminEndpoints';
@@ -187,7 +187,6 @@
border: 1px solid var(--fullscreen-border-subtle-65);
box-shadow: 0 14px 32px var(--fullscreen-shadow-group);
break-inside: avoid;
backdrop-filter: blur(10px);
}
.tool-panel__fullscreen-section-header {
@@ -230,7 +229,6 @@
border: 1px solid var(--fullscreen-border-subtle-70);
border-radius: 0.95rem;
background: var(--fullscreen-bg-item);
backdrop-filter: blur(6px);
cursor: pointer;
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
width: 100%;
-49
View File
@@ -1,49 +0,0 @@
import { useState, useEffect } from 'react';
import licenseService, {
PlanTier,
SubscriptionInfo,
PlansResponse,
} from '@app/services/licenseService';
export interface UsePlansReturn {
plans: PlanTier[];
currentSubscription: SubscriptionInfo | null;
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
export const usePlans = (currency: string = 'gbp'): UsePlansReturn => {
const [plans, setPlans] = useState<PlanTier[]>([]);
const [currentSubscription, setCurrentSubscription] = useState<SubscriptionInfo | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchPlans = async () => {
try {
setLoading(true);
setError(null);
const data: PlansResponse = await licenseService.getPlans(currency);
setPlans(data.plans);
setCurrentSubscription(data.currentSubscription);
} catch (err) {
console.error('Error fetching plans:', err);
setError(err instanceof Error ? err.message : 'Failed to fetch plans');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchPlans();
}, [currency]);
return {
plans,
currentSubscription,
loading,
error,
refetch: fetchPlans,
};
};
-115
View File
@@ -1,115 +0,0 @@
import apiClient from '@app/services/apiClient';
export interface AuditSystemStatus {
enabled: boolean;
level: string;
retentionDays: number;
totalEvents: number;
}
export interface AuditEvent {
id: string;
timestamp: string;
eventType: string;
username: string;
ipAddress: string;
details: Record<string, any>;
}
export interface AuditEventsResponse {
events: AuditEvent[];
totalEvents: number;
page: number;
pageSize: number;
totalPages: number;
}
export interface ChartData {
labels: string[];
values: number[];
}
export interface AuditChartsData {
eventsByType: ChartData;
eventsByUser: ChartData;
eventsOverTime: ChartData;
}
export interface AuditFilters {
eventType?: string;
username?: string;
startDate?: string;
endDate?: string;
page?: number;
pageSize?: number;
}
const auditService = {
/**
* Get audit system status
*/
async getSystemStatus(): Promise<AuditSystemStatus> {
const response = await apiClient.get<any>('/api/v1/proprietary/ui-data/audit-dashboard');
const data = response.data;
// Map V1 response to expected format
return {
enabled: data.auditEnabled,
level: data.auditLevel,
retentionDays: data.retentionDays,
totalEvents: 0, // Will be fetched separately
};
},
/**
* Get audit events with pagination and filters
*/
async getEvents(filters: AuditFilters = {}): Promise<AuditEventsResponse> {
const response = await apiClient.get<AuditEventsResponse>('/api/v1/proprietary/ui-data/audit-events', {
params: filters,
});
return response.data;
},
/**
* Get chart data for dashboard
*/
async getChartsData(timePeriod: 'day' | 'week' | 'month' = 'week'): Promise<AuditChartsData> {
const response = await apiClient.get<AuditChartsData>('/api/v1/proprietary/ui-data/audit-charts', {
params: { period: timePeriod },
});
return response.data;
},
/**
* Export audit data
*/
async exportData(
format: 'csv' | 'json',
filters: AuditFilters = {}
): Promise<Blob> {
const response = await apiClient.get('/api/v1/proprietary/ui-data/audit-export', {
params: { format, ...filters },
responseType: 'blob',
});
return response.data;
},
/**
* Get available event types for filtering
*/
async getEventTypes(): Promise<string[]> {
const response = await apiClient.get<string[]>('/api/v1/proprietary/ui-data/audit-event-types');
return response.data;
},
/**
* Get list of users for filtering
*/
async getUsers(): Promise<string[]> {
const response = await apiClient.get<string[]>('/api/v1/proprietary/ui-data/audit-users');
return response.data;
},
};
export default auditService;
@@ -1,91 +0,0 @@
import apiClient from '@app/services/apiClient';
export interface PlanFeature {
name: string;
included: boolean;
}
export interface PlanTier {
id: string;
name: string;
price: number;
currency: string;
period: string;
popular?: boolean;
features: PlanFeature[];
highlights: string[];
isContactOnly?: boolean;
}
export interface SubscriptionInfo {
plan: PlanTier;
status: 'active' | 'past_due' | 'canceled' | 'incomplete' | 'trialing' | 'none';
currentPeriodEnd?: string;
cancelAtPeriodEnd?: boolean;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
}
export interface PlansResponse {
plans: PlanTier[];
currentSubscription: SubscriptionInfo;
}
export interface CheckoutSessionRequest {
planId: string;
currency: string;
successUrl: string;
cancelUrl: string;
}
export interface CheckoutSessionResponse {
clientSecret: string;
sessionId: string;
}
export interface BillingPortalResponse {
url: string;
}
const licenseService = {
/**
* Get available plans with pricing for the specified currency
*/
async getPlans(currency: string = 'gbp'): Promise<PlansResponse> {
const response = await apiClient.get<PlansResponse>(`/api/v1/license/plans`, {
params: { currency },
});
return response.data;
},
/**
* Get current subscription details
*/
async getCurrentSubscription(): Promise<SubscriptionInfo> {
const response = await apiClient.get<SubscriptionInfo>('/api/v1/license/subscription');
return response.data;
},
/**
* Create a Stripe checkout session for upgrading
*/
async createCheckoutSession(request: CheckoutSessionRequest): Promise<CheckoutSessionResponse> {
const response = await apiClient.post<CheckoutSessionResponse>(
'/api/v1/license/checkout',
request
);
return response.data;
},
/**
* Create a Stripe billing portal session for managing subscription
*/
async createBillingPortalSession(returnUrl: string): Promise<BillingPortalResponse> {
const response = await apiClient.post<BillingPortalResponse>('/api/v1/license/billing-portal', {
returnUrl,
});
return response.data;
},
};
export default licenseService;
@@ -1,61 +0,0 @@
import apiClient from '@app/services/apiClient';
export interface EndpointStatistic {
endpoint: string;
visits: number;
percentage: number;
}
export interface EndpointStatisticsResponse {
endpoints: EndpointStatistic[];
totalEndpoints: number;
totalVisits: number;
}
export interface UsageChartData {
labels: string[];
values: number[];
}
const usageAnalyticsService = {
/**
* Get endpoint statistics
*/
async getEndpointStatistics(
limit?: number,
dataType: 'all' | 'api' | 'ui' = 'all'
): Promise<EndpointStatisticsResponse> {
const params: Record<string, any> = {};
if (limit !== undefined) {
params.limit = limit;
}
if (dataType !== 'all') {
params.dataType = dataType;
}
const response = await apiClient.get<EndpointStatisticsResponse>(
'/api/v1/proprietary/ui-data/usage-endpoint-statistics',
{ params }
);
return response.data;
},
/**
* Get chart data for endpoint usage
*/
async getChartData(
limit?: number,
dataType: 'all' | 'api' | 'ui' = 'all'
): Promise<UsageChartData> {
const stats = await this.getEndpointStatistics(limit, dataType);
return {
labels: stats.endpoints.map((e) => e.endpoint),
values: stats.endpoints.map((e) => e.visits),
};
},
};
export default usageAnalyticsService;
@@ -31,12 +31,6 @@ export interface AdminSettingsData {
roleDetails?: Record<string, string>;
teams?: any[];
maxPaidUsers?: number;
// License information
maxAllowedUsers: number;
availableSlots: number;
grandfatheredUserCount: number;
licenseMaxUsers: number;
premiumEnabled: boolean;
}
export interface CreateUserRequest {
@@ -1,5 +1,5 @@
{
"extends": "./tsconfig.json",
"extends": "../../tsconfig.json",
"compilerOptions": {
"paths": {
"@app/*": [
@@ -9,7 +9,7 @@
}
},
"exclude": [
"src/proprietary",
"../proprietary",
"node_modules"
]
}
@@ -1,53 +0,0 @@
import { NavKey } from '@app/components/shared/config/types';
/**
* Navigate to a specific settings section
*
* @param section - The settings section key to navigate to
*
* @example
* // Navigate to People section
* navigateToSettings('people');
*
* // Navigate to Admin Premium section
* navigateToSettings('adminPremium');
*/
export function navigateToSettings(section: NavKey) {
const basePath = window.location.pathname.split('/settings')[0] || '';
const newPath = `${basePath}/settings/${section}`;
window.history.pushState({}, '', newPath);
// Trigger a popstate event to notify components
window.dispatchEvent(new PopStateEvent('popstate'));
}
/**
* Get the URL path for a settings section
* Useful for creating links
*
* @param section - The settings section key
* @returns The URL path for the settings section
*
* @example
* <a href={getSettingsUrl('people')}>Go to People Settings</a>
* // Returns: "/settings/people"
*/
export function getSettingsUrl(section: NavKey): string {
return `/settings/${section}`;
}
/**
* Check if currently viewing a settings section
*
* @param section - Optional section key to check for specific section
* @returns True if in settings (and matching specific section if provided)
*/
export function isInSettings(section?: NavKey): boolean {
const pathname = window.location.pathname;
if (!section) {
return pathname.startsWith('/settings');
}
return pathname === `/settings/${section}`;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import '@mantine/core/styles.css';
import '@mantine/dates/styles.css';
import '../vite-env.d.ts';
import '../vite-env.d.ts'; // eslint-disable-line no-restricted-imports -- Outside app paths
import '@app/styles/index.css'; // Import global styles
import React from 'react';
import ReactDOM from 'react-dom/client';
@@ -1,44 +0,0 @@
import React from 'react';
import { createConfigNavSections as createCoreConfigNavSections, ConfigNavSection } from '@core/components/shared/config/configNavSections';
import PeopleSection from '@proprietary/components/shared/config/configSections/PeopleSection';
import TeamsSection from '@proprietary/components/shared/config/configSections/TeamsSection';
/**
* Proprietary extension of createConfigNavSections that adds workspace sections
*/
export const createConfigNavSections = (
Overview: React.ComponentType<{ onLogoutClick: () => void }>,
onLogoutClick: () => void,
isAdmin: boolean = false,
runningEE: boolean = false
): ConfigNavSection[] => {
// Get the core sections
const sections = createCoreConfigNavSections(Overview, onLogoutClick, isAdmin, runningEE);
// Add Workspace section after Preferences (index 1)
const workspaceSection: ConfigNavSection = {
title: 'Workspace',
items: [
{
key: 'people',
label: 'People',
icon: 'group-rounded',
component: <PeopleSection />
},
{
key: 'teams',
label: 'Teams',
icon: 'groups-rounded',
component: <TeamsSection />
},
],
};
// Insert workspace section after Preferences (at index 1)
sections.splice(1, 0, workspaceSection);
return sections;
};
// Re-export types for convenience
export type { ConfigNavSection, ConfigNavItem, ConfigColors } from '@core/components/shared/config/configNavSections';
@@ -1,53 +0,0 @@
import React from 'react';
import { Paper, Stack, Text, Button, Divider } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@app/auth/UseSession';
import { useNavigate } from 'react-router-dom';
import CoreGeneralSection from '@core/components/shared/config/configSections/GeneralSection';
/**
* Proprietary extension of GeneralSection that adds account management
*/
const GeneralSection: React.FC = () => {
const { t } = useTranslation();
const { signOut, user } = useAuth();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await signOut();
navigate('/login');
} catch (error) {
console.error('Logout error:', error);
}
};
return (
<Stack gap="lg">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div>
<Text fw={600} size="lg">{t('settings.general.title', 'General')}</Text>
<Text size="sm" c="dimmed">
{t('settings.general.description', 'Configure general application preferences.')}
</Text>
</div>
{user && (
<Stack gap="xs" align="flex-end">
<Text size="sm" c="dimmed">
{t('settings.general.user', 'User')}: <strong>{user.email || user.username}</strong>
</Text>
<Button color="red" variant="outline" size="xs" onClick={handleLogout}>
{t('settings.general.logout', 'Log out')}
</Button>
</Stack>
)}
</div>
{/* Render core general section preferences (without title since we show it above) */}
<CoreGeneralSection hideTitle />
</Stack>
);
};
export default GeneralSection;
@@ -1,281 +0,0 @@
import { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useDocumentMeta } from '@app/hooks/useDocumentMeta';
import AuthLayout from '@app/routes/authShared/AuthLayout';
import LoginHeader from '@app/routes/login/LoginHeader';
import ErrorMessage from '@app/routes/login/ErrorMessage';
import { BASE_PATH } from '@app/constants/app';
import apiClient from '@app/services/apiClient';
interface InviteData {
email: string | null;
role: string;
expiresAt: string;
emailRequired: boolean;
}
export default function InviteAccept() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { t } = useTranslation();
const token = searchParams.get('token');
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [inviteData, setInviteData] = useState<InviteData | null>(null);
const [error, setError] = useState<string | null>(null);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const baseUrl = window.location.origin + BASE_PATH;
// Set document meta
useDocumentMeta({
title: `${t('invite.welcome', 'Welcome to Stirling PDF')} - Stirling PDF`,
description: t('app.description', 'The Free Adobe Acrobat alternative (10M+ Downloads)'),
ogTitle: `${t('invite.welcome', 'Welcome to Stirling PDF')} - Stirling PDF`,
ogDescription: t('app.description', 'The Free Adobe Acrobat alternative (10M+ Downloads)'),
ogImage: `${baseUrl}/og_images/home.png`,
ogUrl: `${window.location.origin}${window.location.pathname}`
});
useEffect(() => {
if (!token) {
setError(t('invite.invalidToken', 'Invalid invitation link'));
setLoading(false);
return;
}
validateToken();
}, [token]);
const validateToken = async () => {
try {
setLoading(true);
const response = await apiClient.get<InviteData>(`/api/v1/invite/validate/${token}`, {
suppressErrorToast: true,
} as any);
setInviteData(response.data);
setError(null);
} catch (err: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.validationError', 'Failed to validate invitation link');
setError(errorMessage);
} finally {
setLoading(false);
}
};
const handleAccept = async (e: React.FormEvent) => {
e.preventDefault();
// Validate email if required
if (inviteData?.emailRequired) {
if (!email || email.trim().length === 0) {
setError(t('invite.emailRequired', 'Email address is required'));
return;
}
if (!email.includes('@')) {
setError(t('invite.invalidEmail', 'Invalid email address'));
return;
}
}
// Validate passwords
if (!password) {
setError(t('invite.passwordRequired', 'Password is required'));
return;
}
if (password !== confirmPassword) {
setError(t('invite.passwordMismatch', 'Passwords do not match'));
return;
}
try {
setSubmitting(true);
setError(null);
const formData = new FormData();
if (inviteData?.emailRequired) {
formData.append('email', email.trim().toLowerCase());
}
formData.append('password', password);
await apiClient.post(`/api/v1/invite/accept/${token}`, formData, {
suppressErrorToast: true,
} as any);
// Success - redirect to login
navigate('/login?messageType=accountCreated');
} catch (err: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.acceptError', 'Failed to create account');
setError(errorMessage);
} finally {
setSubmitting(false);
}
};
if (loading) {
return (
<AuthLayout>
<LoginHeader title={t('invite.validating', 'Validating invitation...')} />
<div style={{ textAlign: 'center', padding: '3rem 0' }}>
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
</div>
</AuthLayout>
);
}
if (error && !inviteData) {
return (
<AuthLayout>
<LoginHeader title={t('invite.invalidInvitation', 'Invalid Invitation')} />
<ErrorMessage error={error} />
<div className="auth-section">
<button
type="button"
onClick={() => navigate('/login')}
className="w-full px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold cursor-pointer border-0 auth-cta-button"
>
{t('invite.goToLogin', 'Go to Login')}
</button>
</div>
</AuthLayout>
);
}
return (
<AuthLayout>
<LoginHeader
title={t('invite.welcomeTitle', "You've been invited!")}
subtitle={t('invite.welcomeSubtitle', 'Complete your account setup to get started')}
/>
{inviteData && !inviteData.emailRequired && (
<div style={{ marginBottom: '1.5rem' }}>
<div style={{
textAlign: 'center',
padding: '1.25rem',
backgroundColor: 'rgba(59, 130, 246, 0.08)',
borderRadius: '0.75rem',
border: '1px solid rgba(59, 130, 246, 0.2)'
}}>
<p style={{
fontSize: '0.8125rem',
textTransform: 'uppercase',
letterSpacing: '0.05em',
color: '#6b7280',
margin: '0 0 0.5rem 0',
fontWeight: 500
}}>
{t('invite.accountFor', 'Creating account for')}
</p>
<p style={{
fontSize: '1.125rem',
fontWeight: 600,
margin: '0 0 0.75rem 0',
color: '#1f2937'
}}>
{inviteData.email}
</p>
<p style={{
fontSize: '0.8125rem',
color: '#6b7280',
margin: 0
}}>
{t('invite.linkExpires', 'Link expires')}: {new Date(inviteData.expiresAt).toLocaleDateString()} at {new Date(inviteData.expiresAt).toLocaleTimeString()}
</p>
</div>
</div>
)}
<ErrorMessage error={error} />
<form onSubmit={handleAccept}>
{inviteData?.emailRequired && (
<div style={{ marginBottom: '1rem' }}>
<label htmlFor="email" className="auth-label">
{t('invite.email', 'Email address')}
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t('invite.emailPlaceholder', 'Enter your email address')}
disabled={submitting}
required
className="auth-input"
autoComplete="email"
/>
</div>
)}
<div style={{ marginBottom: '1rem' }}>
<label htmlFor="password" className="auth-label">
{t('invite.choosePassword', 'Choose a password')}
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={t('invite.passwordPlaceholder', 'Enter your password')}
disabled={submitting}
required
className="auth-input"
autoComplete="new-password"
/>
</div>
<div style={{ marginBottom: '1.5rem' }}>
<label htmlFor="confirmPassword" className="auth-label">
{t('invite.confirmPassword', 'Confirm password')}
</label>
<input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder={t('invite.confirmPasswordPlaceholder', 'Re-enter your password')}
disabled={submitting}
required
className="auth-input"
autoComplete="new-password"
/>
</div>
<div className="auth-section">
<button
type="submit"
disabled={submitting}
className="w-full px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold cursor-pointer border-0 disabled:opacity-50 disabled:cursor-not-allowed auth-cta-button"
>
{submitting ? t('invite.creating', 'Creating Account...') : t('invite.createAccount', 'Create Account')}
</button>
</div>
</form>
<div style={{ textAlign: 'center', margin: '1rem 0 0' }}>
<p style={{ color: '#6b7280', fontSize: '0.875rem', margin: 0 }}>
{t('invite.alreadyHaveAccount', 'Already have an account?')}{' '}
<button
type="button"
onClick={() => navigate('/login')}
className="auth-link-black"
>
{t('invite.signIn', 'Sign in')}
</button>
</p>
</div>
</AuthLayout>
);
}
+5 -37
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { springAuth } from '@app/auth/springAuthClient';
import { useAuth } from '@app/auth/UseSession';
import { useTranslation } from 'react-i18next';
@@ -17,42 +17,26 @@ import { BASE_PATH } from '@app/constants/app';
export default function Login() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { session, loading } = useAuth();
const { t } = useTranslation();
const [isSigningIn, setIsSigningIn] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [showEmailForm, setShowEmailForm] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// Handle query params (email prefill and success messages)
// Prefill email from query param (e.g. after password reset)
useEffect(() => {
try {
const emailFromQuery = searchParams.get('email');
const url = new URL(window.location.href);
const emailFromQuery = url.searchParams.get('email');
if (emailFromQuery) {
setEmail(emailFromQuery);
}
const messageType = searchParams.get('messageType')
if (messageType) {
switch (messageType) {
case 'accountCreated':
setSuccessMessage(t('login.accountCreatedSuccess', 'Account created successfully! You can now sign in.'))
break
case 'passwordChanged':
setSuccessMessage(t('login.passwordChangedSuccess', 'Password changed successfully! Please sign in with your new password.'))
break
case 'credsUpdated':
setSuccessMessage(t('login.credentialsUpdated', 'Your credentials have been updated. Please sign in again.'))
break
}
}
} catch (_) {
// ignore
}
}, [searchParams, t]);
}, []);
const baseUrl = window.location.origin + BASE_PATH;
@@ -137,22 +121,6 @@ export default function Login() {
<AuthLayout>
<LoginHeader title={t('login.login') || 'Sign in'} />
{/* Success message */}
{successMessage && (
<div style={{
padding: '1rem',
marginBottom: '1rem',
backgroundColor: 'rgba(34, 197, 94, 0.1)',
border: '1px solid rgba(34, 197, 94, 0.3)',
borderRadius: '0.5rem',
color: '#16a34a'
}}>
<p style={{ margin: 0, fontSize: '0.875rem', textAlign: 'center' }}>
{successMessage}
</p>
</div>
)}
<ErrorMessage error={error} />
{/* OAuth first */}
@@ -1,5 +1,5 @@
{
"extends": "./tsconfig.json",
"extends": "../../tsconfig.json",
"compilerOptions": {
"paths": {
"@app/*": [
@@ -9,5 +9,8 @@
"@proprietary/*": ["src/proprietary/*"],
"@core/*": ["src/core/*"]
}
}
},
"exclude": [
"node_modules"
]
}
+2 -2
View File
@@ -35,8 +35,8 @@
"src/proprietary/*",
"src/core/*"
],
"@core/*": ["src/core/*"],
"@proprietary/*": ["src/proprietary/*"]
"@proprietary/*": ["src/proprietary/*"],
"@core/*": ["src/core/*"]
},
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
+1 -2
View File
@@ -10,12 +10,11 @@ export default defineConfig({
react(),
tsconfigPaths({
projects: [
isProprietary ? './tsconfig.proprietary.json' : './tsconfig.core.json',
isProprietary ? './src/proprietary/tsconfig.json' : './src/core/tsconfig.json',
],
}),
],
server: {
host: true, // Listen on all addresses (0.0.0.0) - allows access from any domain/IP
proxy: {
'/api': {
target: 'http://localhost:8080',
+1 -1
View File
@@ -10,7 +10,7 @@ export default defineConfig({
react(),
tsconfigPaths({
projects: [
isProprietary ? './tsconfig.proprietary.json' : './tsconfig.core.json',
isProprietary ? './src/proprietary/tsconfig.json' : './src/core/tsconfig.json',
],
}),
],