Skip to content

Commit

Permalink
Merge pull request #5 from AdityaP700/feature/mongodb-integration
Browse files Browse the repository at this point in the history
Feature/mongodb integration
  • Loading branch information
AdityaP700 authored Dec 14, 2024
2 parents c8080fe + 957fa7e commit f43c6d0
Show file tree
Hide file tree
Showing 13 changed files with 422 additions and 77 deletions.
14 changes: 10 additions & 4 deletions backend/Controllers/EmailController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Threading.Tasks;
using SentimatrixAPI.Models;
using SentimatrixAPI.Services;
using Microsoft.Extensions.Options;
using SentimatrixAPI.Data;

namespace SentimatrixAPI.Controllers
{
Expand All @@ -21,12 +23,12 @@ public class EmailController : ControllerBase
public EmailController(
EmailService emailService,
ILogger<EmailController> logger,
IMongoDatabase database)
IMongoDatabase database,
IOptions<MongoDBSettings> settings)
{
_emailService = emailService ?? throw new ArgumentNullException(nameof(emailService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_emailCollection = database.GetCollection<EmailData>("email");
// Log a message indicating successful connection
_emailCollection = database.GetCollection<EmailData>(settings.Value.EmailsCollectionName);
_logger.LogInformation("Successfully connected to the Email database.");
}

Expand Down Expand Up @@ -71,7 +73,11 @@ public async Task<ActionResult<IEnumerable<EmailData>>> GetAllEmails()
{
try
{
var emails = await _emailCollection.Find(new BsonDocument()).ToListAsync();
_logger.LogInformation("Getting all emails");
var emails = await _emailCollection.Find(new BsonDocument())
.SortByDescending(e => e.ReceivedDate)
.ToListAsync();
_logger.LogInformation($"Found {emails.Count} emails");
return Ok(emails);
}
catch (Exception ex)
Expand Down
118 changes: 118 additions & 0 deletions backend/Controllers/EmailProcessController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ public async Task<IActionResult> GetSeriousTickets()
}
}

[HttpGet("test")]
public IActionResult Test()
{
return Ok(new { message = "API is working!" });
}

private string ConvertHtmlToPlainText(string html)
{
if (string.IsNullOrEmpty(html)) return string.Empty;
Expand Down Expand Up @@ -189,5 +195,117 @@ private async Task StoreEmail(ProcessedEmail email)
string updatedJson = JsonConvert.SerializeObject(emails, Formatting.Indented);
await System.IO.File.WriteAllTextAsync(filePath, updatedJson);
}

[HttpPost("trubot")]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> ProcessTrubotEmail([FromForm] TrubotEmailRequest emailData)
{
try
{
if (emailData == null)
{
return BadRequest(new { message = "Email data is required" });
}

_logger.LogInformation($"Processing TruBot email from: {emailData.senderEmail}");

// Create EmailData object from TruBot request
var email = new EmailData
{
Subject = emailData.subject ?? string.Empty,
Body = emailData.body ?? string.Empty,
SenderEmail = emailData.senderEmail ?? string.Empty,
ReceiverEmail = "[email protected]",
Score = 0, // Will be updated by sentiment analysis
Type = "pending",
ReceivedDate = DateTime.UtcNow
};

// Process the email using existing logic
var plainTextBody = ConvertHtmlToPlainText(email.Body);

// Analyze sentiment using Groq
int sentimentScore = await _groqService.AnalyzeSentiment(plainTextBody);

// Update email with sentiment score and type
email.Score = sentimentScore;
email.Type = sentimentScore > 60 ? "negative" : "positive";

// Log before storing
_logger.LogInformation($"Storing email: Subject={email.Subject}, Sender={email.SenderEmail}, Score={email.Score}");

// Store in MongoDB
await _emailService.CreateAsync(new Email
{
Body = plainTextBody,
Score = sentimentScore,
Sender = email.SenderEmail,
Receiver = email.ReceiverEmail,
Type = email.Type,
Time = DateTime.UtcNow
});

// If sentiment score is high (negative), notify connected clients
if (sentimentScore > 60)
{
await _hubContext.Clients.All.SendAsync("ReceiveSeriousTicket", email);
}

return Ok(new
{
status = "Success",
message = "Email processed successfully",
sentimentScore = sentimentScore,
type = email.Type
});
}
catch (Exception ex)
{
_logger.LogError($"Error processing TruBot email: {ex.Message}");
return StatusCode(500, new { message = "Failed to process email", error = ex.Message });
}
}

[HttpPost("test-trubot")]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult TestTrubotEmail([FromForm] TrubotEmailRequest emailData)
{
try
{
_logger.LogInformation("=== TEST ENDPOINT - Received TruBot Data ===");
_logger.LogInformation($"Subject: {emailData.subject}");
_logger.LogInformation($"Body: {emailData.body}");
_logger.LogInformation($"Sender Email: {emailData.senderEmail}");
_logger.LogInformation("=== RAW FORM DATA ===");

// Log all form data received
foreach (var key in Request.Form.Keys)
{
_logger.LogInformation($"{key}: {Request.Form[key]}");
}

return Ok(new
{
message = "Test endpoint - Data received",
receivedData = new
{
subject = emailData.subject,
body = emailData.body,
senderEmail = emailData.senderEmail
},
rawFormData = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString())
});
}
catch (Exception ex)
{
_logger.LogError($"Error in test endpoint: {ex.Message}");
return StatusCode(500, new
{
message = "Error in test endpoint",
error = ex.Message,
stackTrace = ex.StackTrace
});
}
}
}
}
9 changes: 9 additions & 0 deletions backend/Models/TrubotEmailRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace SentimatrixAPI.Models
{
public class TrubotEmailRequest
{
public string? subject { get; set; }
public string? body { get; set; }
public string? senderEmail { get; set; }
}
}
27 changes: 7 additions & 20 deletions backend/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,7 @@
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Sentimatrix API",
Version = "v1",
Description = "API for processing emails and analyzing sentiment"
});
});
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR();

// Register GroqService
Expand Down Expand Up @@ -61,24 +53,19 @@
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI(c =>
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sentimatrix API V1");
c.RoutePrefix = "swagger";
});
}
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sentimatrix API v1");
});

app.UseHttpsRedirection();
app.UseCors();
app.UseRouting();
app.UseCors();
app.UseAuthorization();

app.MapControllers();
app.MapHub<TicketHub>("/ticketHub");

// Ensure we're using HTTP
app.Urls.Clear();
app.Urls.Add("http://localhost:5000");

Expand Down
14 changes: 14 additions & 0 deletions backend/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"profiles": {
"SentimatrixAPI": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
6 changes: 3 additions & 3 deletions backend/SentimatrixAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
<LangVersion>11.0</LangVersion>
<LangVersion>10.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="3.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.54" />
<PackageReference Include="MongoDB.Driver" Version="2.22.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

</Project>
14 changes: 0 additions & 14 deletions backend/appsettings.sample.json

This file was deleted.

56 changes: 49 additions & 7 deletions frontend/AllEmailsWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,56 @@
<DataGrid x:Name="EmailsGrid"
AutoGenerateColumns="False"
IsReadOnly="True"
Style="{StaticResource TableStyle}">
Style="{StaticResource TableStyle}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
MaxHeight="700">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Time}" Width="150"/>
<DataGridTextColumn Header="Sender" Binding="{Binding Sender}" Width="200"/>
<DataGridTextColumn Header="Email" Binding="{Binding Email}" Width="250"/>
<DataGridTextColumn Header="Score" Binding="{Binding Score}" Width="100"/>
<DataGridTextColumn Header="Type" Binding="{Binding Type}" Width="100"/>
<DataGridTextColumn Header="Body" Binding="{Binding Body}" Width="*"/>
<DataGridTextColumn Header="Time"
Binding="{Binding Time, StringFormat={}{0:MM/dd/yyyy HH:mm}}"
Width="140"/>
<DataGridTextColumn Header="Sender"
Binding="{Binding SenderEmail}"
Width="200"/>
<DataGridTextColumn Header="Score"
Binding="{Binding Score}"
Width="70">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Score}" Value="100">
<Setter Property="Foreground" Value="#FF4444"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Type"
Binding="{Binding Type}"
Width="100">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Type}" Value="negative">
<Setter Property="Foreground" Value="#FF4444"/>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="positive">
<Setter Property="Foreground" Value="#4CAF50"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Body"
Binding="{Binding Body}"
Width="*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="MaxHeight" Value="100"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Border>
Expand Down
38 changes: 29 additions & 9 deletions frontend/AllEmailsWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,48 @@
using System.Collections.ObjectModel;
using System.Windows;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using WpfSidebarApp.Models;

namespace WpfSidebarApp
{
public partial class AllEmailsWindow : Window
{
private readonly HttpClient _httpClient;
private readonly string _apiBaseUrl = "http://localhost:5000/api";
public ObservableCollection<Email> Emails { get; set; }

public AllEmailsWindow()
{
InitializeComponent();
LoadEmails();
EmailsGrid.ItemsSource = Emails;
_httpClient = new HttpClient();
Emails = new ObservableCollection<Email>();
LoadEmailsAsync();
}

private void LoadEmails()
private async Task LoadEmailsAsync()
{
// Sample data for demonstration
Emails = new ObservableCollection<Email>
try
{
new Email { Sender = "[email protected]", Receiver = "[email protected]", Score = 5, Body = "This is a sample email body 1." },
new Email { Sender = "[email protected]", Receiver = "[email protected]", Score = 3, Body = "This is a sample email body 2." },
new Email { Sender = "[email protected]", Receiver = "[email protected]", Score = 4, Body = "This is a sample email body 3." }
};
var response = await _httpClient.GetStringAsync($"{_apiBaseUrl}/email");
var emailList = JsonConvert.DeserializeObject<List<Email>>(response);

Emails.Clear();
foreach (var email in emailList.OrderByDescending(e => e.Time))
{
Emails.Add(email);
}

EmailsGrid.ItemsSource = Emails;
}
catch (Exception ex)
{
MessageBox.Show($"Error loading emails: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}

private void DashboardButton_Click(object sender, RoutedEventArgs e)
Expand Down
Loading

0 comments on commit f43c6d0

Please sign in to comment.