File size: 12,158 Bytes
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a2241a
70556b7
 
 
8a2241a
 
70556b7
 
 
8a2241a
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88d8af
70556b7
e88d8af
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a2241a
 
 
 
 
 
 
 
 
 
 
 
81ce36c
8a2241a
 
 
 
 
 
 
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
81ce36c
70556b7
8a2241a
 
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a2241a
 
 
 
 
 
 
70556b7
 
 
 
 
 
8a2241a
 
 
 
 
 
 
 
 
 
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
using Application.Abstractions.Interfaces;
using Application.DTOs.PaymentDTOs;
using Application.DTOs.OrderDTOs;
using Entities.Interfaces;
using Entities.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace RobDeliveryAPI.Controllers;

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class PaymentsController : ControllerBase
{
    private readonly IPaymentProcessorService _paymentProcessorService;
    private readonly IOrderRepository _orderRepository;
    private readonly IUserRepository _userRepository;

    public PaymentsController(
        IPaymentProcessorService paymentProcessorService,
        IOrderRepository orderRepository,
        IUserRepository userRepository)
    {
        _paymentProcessorService = paymentProcessorService;
        _orderRepository = orderRepository;
        _userRepository = userRepository;
    }

    /// <summary>
    /// Get authenticated user ID from JWT token
    /// </summary>
    private int GetAuthenticatedUserId()
    {
        var userIdClaim = User.FindFirst("Id") ?? User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId))
        {
            throw new UnauthorizedAccessException("User ID not found in token");
        }
        return userId;
    }

    /// <summary>
    /// Process a payment using the specified payment method (PayPal, GooglePay, or Stripe)
    /// </summary>
    [HttpPost("process")]
    public async Task<ActionResult<PaymentResultDTO>> ProcessPayment([FromBody] PaymentRequestDTO request)
    {
        try
        {
            if (request.Amount <= 0)
            {
                return BadRequest(new PaymentResultDTO
                {
                    Success = false,
                    TransactionId = string.Empty,
                    PaymentMethod = request.PaymentMethod,
                    Amount = request.Amount,
                    Currency = request.Currency,
                    ProcessedAt = DateTime.UtcNow,
                    ErrorMessage = "Payment amount must be greater than zero"
                });
            }

            var result = await _paymentProcessorService.ProcessPaymentAsync(request);

            if (result.Success)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new PaymentResultDTO
            {
                Success = false,
                TransactionId = string.Empty,
                PaymentMethod = request.PaymentMethod,
                Amount = request.Amount,
                Currency = request.Currency,
                ProcessedAt = DateTime.UtcNow,
                ErrorMessage = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new PaymentResultDTO
            {
                Success = false,
                TransactionId = string.Empty,
                PaymentMethod = request.PaymentMethod,
                Amount = request.Amount,
                Currency = request.Currency,
                ProcessedAt = DateTime.UtcNow,
                ErrorMessage = $"Internal server error: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// Pay for order product and/or delivery
    /// </summary>
    [HttpPost("pay-order")]
    public async Task<ActionResult<PaymentResultDTO>> PayOrder([FromBody] PayOrderDTO paymentDto)
    {
        try
        {
            int userId = GetAuthenticatedUserId();

            // Validate that at least one payment option is selected
            if (!paymentDto.PayProduct && !paymentDto.PayDelivery)
            {
                return BadRequest(new PaymentResultDTO
                {
                    Success = false,
                    ErrorMessage = "At least one payment option (PayProduct or PayDelivery) must be selected",
                    ProcessedAt = DateTime.UtcNow
                });
            }

            // Get order
            var order = await _orderRepository.GetByIdAsync(paymentDto.OrderId);
            if (order == null)
            {
                return NotFound(new PaymentResultDTO
                {
                    Success = false,
                    ErrorMessage = $"Order with ID {paymentDto.OrderId} not found",
                    ProcessedAt = DateTime.UtcNow
                });
            }

            // Validate user authorization
            bool isAuthorized = false;
            if (paymentDto.PayProduct && order.RecipientId == userId)
            {
                isAuthorized = true; // Recipient pays for product
            }
            if (paymentDto.PayDelivery)
            {
                // Check who should pay for delivery
                if ((order.DeliveryPayer == DeliveryPayer.Sender && order.SenderId == userId) ||
                    (order.DeliveryPayer == DeliveryPayer.Recipient && order.RecipientId == userId))
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                return StatusCode(403, new PaymentResultDTO
                {
                    Success = false,
                    ErrorMessage = "You are not authorized to make this payment",
                    ProcessedAt = DateTime.UtcNow
                });
            }

            // Calculate total amount to pay
            decimal totalAmount = 0;
            bool willPayProduct = false;
            bool willPayDelivery = false;

            if (paymentDto.PayProduct && !order.IsProductPaid)
            {
                totalAmount += order.ProductPrice;
                willPayProduct = true;
            }
            if (paymentDto.PayDelivery && !order.IsDeliveryPaid)
            {
                totalAmount += order.DeliveryPrice;
                willPayDelivery = true;
            }

            // Check if there's anything to pay
            if (totalAmount == 0)
            {
                if (order.Status == OrderStatus.AwaitingConfirmation && order.IsProductPaid && order.IsDeliveryPaid)
                {
                    // Allow simple confirmation if everything is already paid
                    order.Status = OrderStatus.Pending;
                    await _orderRepository.UpdateAsync(order);
                    
                    return Ok(new PaymentResultDTO
                    {
                        Success = true,
                        TransactionId = "CONFIRM_ONLY",
                        PaymentMethod = paymentDto.PaymentMethod,
                        Amount = 0,
                        Currency = "USD",
                        OrderId = order.Id,
                        ProductPaid = true,
                        DeliveryPaid = true,
                        ProcessedAt = DateTime.UtcNow
                    });
                }

                return BadRequest(new PaymentResultDTO
                {
                    Success = false,
                    ErrorMessage = "The selected items are already paid",
                    OrderId = order.Id,
                    ProductPaid = order.IsProductPaid,
                    DeliveryPaid = order.IsDeliveryPaid,
                    ProcessedAt = DateTime.UtcNow
                });
            }

            var paymentRequest = new PaymentRequestDTO
            {
                Amount = totalAmount,
                Currency = "USD",
                OrderId = order.Id,
                PaymentMethod = paymentDto.PaymentMethod,
                StripeCardToken = paymentDto.StripeCardToken
            };

            var paymentResult = await _paymentProcessorService.ProcessPaymentAsync(paymentRequest);

            if (!paymentResult.Success)
            {
                return BadRequest(new PaymentResultDTO
                {
                    Success = false,
                    ErrorMessage = $"Payment failed: {paymentResult.ErrorMessage}",
                    OrderId = order.Id,
                    ProcessedAt = DateTime.UtcNow
                });
            }

            // Update order payment status
            if (willPayProduct)
            {
                order.IsProductPaid = true;
                // Add ProductPrice to Sender's balance
                var sender = await _userRepository.GetByIdAsync(order.SenderId);
                if (sender != null)
                {
                    sender.Balance += order.ProductPrice;
                    await _userRepository.UpdateAsync(sender);
                }
            }
            if (willPayDelivery)
            {
                order.IsDeliveryPaid = true;
            }

            // Update order status
            if (order.Status == OrderStatus.AwaitingPayment && order.IsDeliveryPaid)
            {
                order.Status = OrderStatus.AwaitingConfirmation;
            }
            if (order.Status == OrderStatus.AwaitingConfirmation && order.IsProductPaid && order.IsDeliveryPaid)
            {
                order.Status = OrderStatus.Pending;
            }

            await _orderRepository.UpdateAsync(order);

            // Return success result
            return Ok(new PaymentResultDTO
            {
                Success = true,
                TransactionId = paymentResult.TransactionId,
                PaymentMethod = paymentResult.PaymentMethod,
                Amount = totalAmount,
                Currency = "UAH",
                ProcessedAt = paymentResult.ProcessedAt,
                OrderId = order.Id,
                ProductPaid = order.IsProductPaid,
                DeliveryPaid = order.IsDeliveryPaid
            });
        }
        catch (UnauthorizedAccessException ex)
        {
            return StatusCode(403, new PaymentResultDTO
            {
                Success = false,
                ErrorMessage = ex.Message,
                ProcessedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new PaymentResultDTO
            {
                Success = false,
                ErrorMessage = $"An error occurred while processing payment: {ex.Message}",
                ProcessedAt = DateTime.UtcNow
            });
        }
    }

    /// <summary>
    /// Refund a previously processed payment
    /// </summary>
    [HttpPost("refund")]
    public async Task<ActionResult<object>> RefundPayment([FromBody] RefundRequestDTO request)
    {
        try
        {
            if (request.Amount <= 0)
            {
                return BadRequest(new { success = false, message = "Refund amount must be greater than zero" });
            }

            var result = await _paymentProcessorService.RefundPaymentAsync(
                request.PaymentMethod,
                request.TransactionId,
                request.Amount
            );

            if (result)
            {
                return Ok(new
                {
                    success = true,
                    message = "Refund processed successfully",
                    transactionId = request.TransactionId,
                    amount = request.Amount,
                    processedAt = DateTime.UtcNow
                });
            }
            else
            {
                return BadRequest(new
                {
                    success = false,
                    message = "Refund processing failed"
                });
            }
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"Internal server error: {ex.Message}" });
        }
    }
}

public class RefundRequestDTO
{
    public string TransactionId { get; set; } = string.Empty;
    public string PaymentMethod { get; set; } = string.Empty;
    public decimal Amount { get; set; }
}