Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.xtraction.api.admin.dto.AdminData;
import com.xtraction.api.admin.dto.response.UserListData;
import com.xtraction.api.admin.service.AdminService;
import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.identity.auth.dto.LoginData;
import com.xtraction.api.core.exceptions.custom.ForbiddenException;
import com.xtraction.api.billing.subscription.model.SubscriptionPlan;
Expand Down Expand Up @@ -248,7 +249,7 @@ public ResponseEntity<ApiResponse<PromoCodeStatsDto>> getPromoCodeStats() {
}

// ==========================================
// CREDIT STATISTICS (Phase 6B)
// CREDIT STATISTICS
// ==========================================

@Operation(
Expand All @@ -262,7 +263,7 @@ public ResponseEntity<ApiResponse<CreditStatsDto>> getCreditStats() {
}

// ==========================================
// DOCUMENT STATISTICS (Phase 6C)
// DOCUMENT STATISTICS
// ==========================================

@Operation(
Expand All @@ -276,7 +277,7 @@ public ResponseEntity<ApiResponse<DocumentStatsDto>> getDocumentStats() {
}

// ==========================================
// NOTIFICATION STATISTICS (Phase 6D)
// NOTIFICATION STATISTICS
// ==========================================

@Operation(
Expand All @@ -290,7 +291,7 @@ public ResponseEntity<ApiResponse<NotificationStatsDto>> getNotificationStats()
}

// ==========================================
// SECURITY STATISTICS (Phase 6E)
// SECURITY STATISTICS
// ==========================================

@Operation(
Expand All @@ -304,7 +305,7 @@ public ResponseEntity<ApiResponse<SecurityStatsDto>> getSecurityStats() {
}

// ==========================================
// PAYMENT & REVENUE STATISTICS (Phase 4A)
// PAYMENT & REVENUE STATISTICS
// ==========================================

@Operation(
Expand All @@ -317,15 +318,15 @@ public ResponseEntity<ApiResponse<PaymentStatsDto>> getPaymentStats() {
}

// ==========================================
// RECEIPT MANAGEMENT (Phase 4B)
// RECEIPT MANAGEMENT
// ==========================================

@Operation(
summary = "Get All Receipts",
description = "Retrieves a paginated list of receipts with optional filtering.")
@GetMapping("/receipts")
@PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
public ResponseEntity<ApiResponse<org.springframework.data.domain.Page<AdminReceiptDto>>> getReceipts(
public ResponseEntity<ApiResponse<PagedResponse<AdminReceiptDto>>> getReceipts(
@Valid @ModelAttribute ReceiptFilterDto filter,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.xtraction.api.core.web.response.ApiResponse;

import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.admin.dto.request.ReceiptFilterDto;
import com.xtraction.api.admin.dto.response.AdminReceiptDto;
import org.springframework.data.domain.Page;
Expand All @@ -16,7 +17,9 @@ public interface AdminReceiptListService {
* @param size Page size
* @return Paginated response containing receipts
*/
ApiResponse<Page<AdminReceiptDto>> getReceipts(ReceiptFilterDto filter, int page, int size);
ApiResponse<PagedResponse<AdminReceiptDto>> getReceipts(
ReceiptFilterDto filter, int page, int size
);

/**
* Get details of a specific receipt.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.xtraction.api.admin.service;

import com.xtraction.api.core.web.response.ApiResponse;
import com.xtraction.api.core.web.response.PagedResponse;

import com.xtraction.api.admin.dto.AdminData;
import com.xtraction.api.admin.dto.request.*;
Expand Down Expand Up @@ -128,7 +129,8 @@ public ApiResponse<String> resetUserQuotas(String userId) {
return adminSubscriptionActionService.resetUserQuotas(userId);
}

public ApiResponse<org.springframework.data.domain.Page<AdminReceiptDto>> getReceipts(ReceiptFilterDto filter, int page, int size) {
public ApiResponse<PagedResponse<AdminReceiptDto>> getReceipts(
ReceiptFilterDto filter, int page, int size) {
return adminReceiptListService.getReceipts(filter, page, size);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.xtraction.api.admin.interfaces.AdminReceiptListService;
import com.xtraction.api.billing.payment.receipt.model.Receipt;
import com.xtraction.api.billing.payment.receipt.repository.ReceiptRepository;
import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.core.web.response.ResponseBuilderService;
import jakarta.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -34,8 +35,8 @@ public class AdminReceiptListServiceImpl implements AdminReceiptListService {

@Override
@Transactional(readOnly = true)
public ApiResponse<Page<AdminReceiptDto>> getReceipts(ReceiptFilterDto filter, int page, int size) {
log.info("Fetching receipts list for admin dashboard. Page: {}, Size: {}", page, size);
public ApiResponse<PagedResponse<AdminReceiptDto>> getReceipts(
ReceiptFilterDto filter, int page, int size) {

Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());

Expand Down Expand Up @@ -64,7 +65,7 @@ public ApiResponse<Page<AdminReceiptDto>> getReceipts(ReceiptFilterDto filter, i
Page<Receipt> receiptsPage = receiptRepository.findAll(spec, pageable);
Page<AdminReceiptDto> dtoPage = receiptsPage.map(this::mapToDto);

return responseBuilder.buildUserResponse(dtoPage, HttpStatus.OK, "Receipts retrieved successfully");
return responseBuilder.buildPagedResponse(dtoPage, HttpStatus.OK, "Receipts retrieved successfully");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.xtraction.api.billing.credit.service.CreditPackManagementService;
import com.xtraction.api.billing.credit.service.CreditPurchaseService;
import com.xtraction.api.billing.credit.service.PageCountService;
import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.core.web.response.ResponseBuilderService;
import com.xtraction.api.identity.user.model.User;
import io.swagger.v3.oas.annotations.Operation;
Expand Down Expand Up @@ -109,7 +110,7 @@ public ResponseEntity<ApiResponse<CreditTransferData>> transferCredits(
description = "Returns paginated credit transaction history"
)
@GetMapping("/transactions")
public ResponseEntity<ApiResponse<Page<CreditTransactionData>>> getTransactions(
public ResponseEntity<ApiResponse<PagedResponse<CreditTransactionData>>> getTransactions(
@AuthenticationPrincipal User user,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
Expand All @@ -118,8 +119,13 @@ public ResponseEntity<ApiResponse<Page<CreditTransactionData>>> getTransactions(
.findByUserIdOrderByCreatedAtDesc(user.getId(), PageRequest.of(page, size))
.map(this::toTransactionData);
return ResponseEntity.ok(
responseBuilderService.buildUserResponse(transactions, HttpStatus.OK,
"Transactions retrieved"));
responseBuilderService
.buildPagedResponse(
transactions,
HttpStatus.OK,
"Transactions retrieved"
)
);
}

@Operation(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.xtraction.api.billing.payment.paypal.controller;

import com.xtraction.api.billing.payment.paypal.config.PayPalConfig;
import com.xtraction.api.core.web.response.ApiResponse;
import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.core.web.response.ResponseBuilderService;
import com.xtraction.api.billing.payment.paypal.dto.request.CreateOrderRequest;
import com.xtraction.api.billing.payment.paypal.dto.request.CreateSubscriptionRequest;
import com.xtraction.api.billing.payment.paypal.dto.request.RefundOrderRequest;
Expand Down Expand Up @@ -49,6 +52,7 @@ public class PayPalPaymentController {
private final UserSubscriptionService userSubscriptionService;
private final PayPalConfig payPalConfig;
private final SanitizeLogging sanitizer;
private final ResponseBuilderService responseBuilderService;

@GetMapping("/plans")
@Operation(summary = "List available subscription plans", description = "Get all available PayPal subscription plans. This endpoint is public.")
Expand Down Expand Up @@ -135,13 +139,19 @@ public ResponseEntity<Map<String, Object>> refundPayment(@Valid @RequestBody Ref

@GetMapping("/payments/history")
@Operation(summary = "Get payment history", description = "Get paginated payment history for the authenticated user")
public ResponseEntity<Page<PayPalPaymentHistoryResponse>> getPaymentHistory(
public ResponseEntity<ApiResponse<PagedResponse<PayPalPaymentHistoryResponse>>> getPaymentHistory(
@AuthenticationPrincipal User user,
Pageable pageable) {

Page<PayPalPayment> payments = paymentService.getUserPayments(user.getId(), pageable);
Page<PayPalPaymentHistoryResponse> response = payments.map(PayPalPaymentHistoryResponse::fromEntity);
return ResponseEntity.ok(response);
Pageable pageable
) {
Page<PayPalPayment> payments = paymentService
.getUserPayments(user.getId(), pageable);
Page<PayPalPaymentHistoryResponse> response = payments
.map(PayPalPaymentHistoryResponse::fromEntity);
return ResponseEntity.ok(responseBuilderService.buildPagedResponse(
response,
HttpStatus.OK,
"Payment history retrieved successfully")
);
}

@GetMapping("/payments/{orderId}")
Expand Down Expand Up @@ -199,15 +209,15 @@ public ResponseEntity<PayPalSubscriptionHistoryResponse> getActiveSubscription(

@GetMapping("/subscriptions")
@Operation(summary = "Get subscription history", description = "Get paginated subscription history")
public ResponseEntity<Page<PayPalSubscriptionHistoryResponse>> getSubscriptionHistory(
public ResponseEntity<ApiResponse<PagedResponse<PayPalSubscriptionHistoryResponse>>> getSubscriptionHistory(
@AuthenticationPrincipal User user,
Pageable pageable) {

Page<PayPalSubscription> subscriptions = subscriptionService.getSubscriptionsByUserId(user.getId(),
pageable);
Page<PayPalSubscriptionHistoryResponse> response = subscriptions
.map(PayPalSubscriptionHistoryResponse::fromEntity);
return ResponseEntity.ok(response);
return ResponseEntity.ok(responseBuilderService.buildPagedResponse(response, HttpStatus.OK, "Subscription history retrieved successfully"));
}

@PostMapping("/subscriptions/{subscriptionId}/cancel")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.URI;
import java.time.Instant;

/**
Expand Down Expand Up @@ -49,43 +52,79 @@ private String getCurrentTraceId() {
return traceId != null ? traceId : java.util.UUID.randomUUID().toString();
}

private ResponseEntity<ApiResponse<Void>> buildErrorResponseEntity(HttpStatus status, String message, String errorCode) {
ApiResponse<Void> body = ApiResponse.<Void>builder()
.success(false)
.statusCode(status.value())
.message(message)
.errorCode(errorCode)
.timestamp(Instant.now())
.path(getCurrentRequestPath())
.traceId(getCurrentTraceId())
.build();
return ResponseEntity.status(status).body(body);
private boolean shouldReturnProblemDetail() {
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
String accept = attributes.getRequest().getHeader("Accept");
return accept != null && accept.contains("application/problem+json");
}
} catch (Exception e) {
// Ignore
}
return false;
}

private ResponseEntity<Object> buildErrorResponse(HttpStatus status, String message, String errorCode) {
if (shouldReturnProblemDetail()) {
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(status, message);
problemDetail.setType(URI.create("about:blank"));
problemDetail.setTitle(status.getReasonPhrase());
String path = getCurrentRequestPath();
if (path != null) {
problemDetail.setInstance(URI.create(path));
}
if (errorCode != null) {
problemDetail.setProperty("errorCode", errorCode);
}
problemDetail.setProperty("traceId", getCurrentTraceId());
problemDetail.setProperty("timestamp", Instant.now());

return ResponseEntity.status(status)
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.body(problemDetail);
} else {
ApiResponse<Void> body = ApiResponse.<Void>builder()
.success(false)
.statusCode(status.value())
.message(message)
.detail(message)
.errorCode(errorCode)
.timestamp(Instant.now())
.path(getCurrentRequestPath())
.instance(getCurrentRequestPath())
.type("about:blank")
.title(status.getReasonPhrase())
.traceId(getCurrentTraceId())
.build();
return ResponseEntity.status(status).body(body);
}
}

@ExceptionHandler(PayPalPaymentException.class)
public ResponseEntity<ApiResponse<Void>> handlePayPalPaymentException(PayPalPaymentException ex) {
public ResponseEntity<Object> handlePayPalPaymentException(PayPalPaymentException ex) {
log.error("PayPal payment error: {}", ex.getMessage(), ex);
return buildErrorResponseEntity(
return buildErrorResponse(
HttpStatus.BAD_REQUEST,
ex.getMessage(),
ex.getErrorCode() != null ? ex.getErrorCode() : "PAYMENT_ERROR"
);
}

@ExceptionHandler(PayPalSubscriptionNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleSubscriptionNotFound(PayPalSubscriptionNotFoundException ex) {
public ResponseEntity<Object> handleSubscriptionNotFound(PayPalSubscriptionNotFoundException ex) {
log.warn("PayPal subscription not found: {}", ex.getMessage());
return buildErrorResponseEntity(
return buildErrorResponse(
HttpStatus.NOT_FOUND,
ex.getMessage(),
"SUBSCRIPTION_NOT_FOUND"
);
}

@ExceptionHandler(PayPalWebhookException.class)
public ResponseEntity<ApiResponse<Void>> handleWebhookException(PayPalWebhookException ex) {
public ResponseEntity<Object> handleWebhookException(PayPalWebhookException ex) {
log.error("PayPal webhook error: {}", ex.getMessage(), ex);
return buildErrorResponseEntity(
return buildErrorResponse(
HttpStatus.BAD_REQUEST,
ex.getMessage(),
"WEBHOOK_PROCESSING_ERROR"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.xtraction.api.billing.payment.paystack.controller;

import com.xtraction.api.core.web.response.ApiResponse;
import com.xtraction.api.core.web.response.PagedResponse;
import com.xtraction.api.core.web.response.ResponseBuilderService;

import com.xtraction.api.billing.payment.paystack.dto.request.CreateSubscriptionRequest;
import com.xtraction.api.billing.payment.paystack.dto.request.InitializeTransactionRequest;
Expand Down Expand Up @@ -39,6 +41,7 @@ public class PaystackPaymentController {
private final PaystackPaymentService paymentService;
private final PaystackSubscriptionService subscriptionService;
private final UserSubscriptionService userSubscriptionService;
private final ResponseBuilderService responseBuilderService;

// ==================== TRANSACTION ENDPOINTS ====================

Expand Down Expand Up @@ -95,13 +98,13 @@ public ResponseEntity<ApiResponse<TransactionData>> chargeAuthorization(

@GetMapping("/transaction/history")
@Operation(summary = "Get payment history", description = "Get paginated payment history for the authenticated user")
public ResponseEntity<Page<PaymentHistoryResponse>> getPaymentHistory(
public ResponseEntity<ApiResponse<PagedResponse<PaymentHistoryResponse>>> getPaymentHistory(
@AuthenticationPrincipal User user,
Pageable pageable) {

Page<PaystackPayment> payments = paymentService.getPaymentsByUserId(user.getId(), pageable);
Page<PaymentHistoryResponse> response = payments.map(PaymentHistoryResponse::fromEntity);
return ResponseEntity.ok(response);
return ResponseEntity.ok(responseBuilderService.buildPagedResponse(response, HttpStatus.OK, "Payment history retrieved successfully"));
}

@GetMapping("/transaction/{reference}")
Expand Down Expand Up @@ -151,13 +154,13 @@ public ResponseEntity<PaystackSubscription> getActiveSubscription(@Authenticatio

@GetMapping("/subscriptions")
@Operation(summary = "Get subscription history", description = "Get paginated subscription history for the authenticated user")
public ResponseEntity<Page<PaystackSubscription>> getSubscriptionHistory(
public ResponseEntity<ApiResponse<PagedResponse<PaystackSubscription>>> getSubscriptionHistory(
@AuthenticationPrincipal User user,
Pageable pageable) {

Page<PaystackSubscription> subscriptions = subscriptionService.getSubscriptionsByUserId(user.getId(),
pageable);
return ResponseEntity.ok(subscriptions);
return ResponseEntity.ok(responseBuilderService.buildPagedResponse(subscriptions, HttpStatus.OK, "Subscription history retrieved successfully"));
}

@PostMapping("/subscription/{subscriptionCode}/enable")
Expand Down
Loading
Loading