|
1 | 1 | using IMS.API.Models.TransactionsDtos; |
| 2 | +using IMS.Core.Contracts; |
2 | 3 | using IMS.Core.Entities; |
3 | 4 | using IMS.Infrastructure.Data; |
| 5 | +using IMS.Infrastructure.Services; |
4 | 6 | using Microsoft.AspNetCore.Authorization; |
5 | 7 | using Microsoft.AspNetCore.Mvc; |
6 | 8 | using Microsoft.EntityFrameworkCore; |
| 9 | +using Microsoft.Extensions.Options; |
7 | 10 | using System.Security.Claims; |
8 | 11 |
|
9 | 12 |
|
10 | 13 | namespace IMS.API.Controllers |
11 | 14 | { |
12 | 15 | [Route("api/[controller]")] |
13 | 16 | [ApiController] |
14 | | - public class TransactionsController(ApplicationDbContext _context) : ControllerBase |
| 17 | + public class TransactionsController(ApplicationDbContext _context |
| 18 | + , IEmailService emailService, |
| 19 | + IOptions<NotificationSettings> notificationSettings) : ControllerBase |
15 | 20 | { |
16 | 21 |
|
| 22 | + private readonly IEmailService _emailService = emailService; |
| 23 | + private readonly NotificationSettings _notificationSettings = notificationSettings.Value; |
| 24 | + |
17 | 25 | [HttpGet] |
18 | 26 | [Authorize(Roles = "Admin,Manager")] |
19 | 27 | public async Task<IActionResult> GetTransactions() |
@@ -63,6 +71,23 @@ public async Task<IActionResult> RecordTransaction([FromBody] CreateTransactionD |
63 | 71 | return BadRequest("Insufficient stock for this sale!!"); |
64 | 72 |
|
65 | 73 | product.QuantityInStock -= model.Quantity; |
| 74 | + if (product.QuantityInStock <= _notificationSettings.LowStockThreshold) |
| 75 | + { |
| 76 | + var subject = $"Low Stock Alert: {product.Name}"; |
| 77 | + var body = $"Product '{product.Name}'(ID: {product.Id}) has low stock. \n" + |
| 78 | + $"Current quantity: {product.QuantityInStock}\n" + |
| 79 | + $"Threshold: {_notificationSettings.LowStockThreshold}\n" + |
| 80 | + $"Please restock this item soon"; |
| 81 | + |
| 82 | + try |
| 83 | + { |
| 84 | + await _emailService.SendEmailAsync(_notificationSettings.AdminEmail, subject, body); |
| 85 | + } |
| 86 | + catch (Exception ex) |
| 87 | + { |
| 88 | + Console.WriteLine($"Failed to send low stock email: {ex.Message}"); |
| 89 | + } |
| 90 | + } |
66 | 91 | } |
67 | 92 | else |
68 | 93 | { |
|
0 commit comments