Skip to content

Commit

Permalink
feat: contribute emails feature, fix: loading fix for provider
Browse files Browse the repository at this point in the history
  • Loading branch information
muzammildafedar committed Oct 1, 2024
1 parent 5bfd141 commit b87eb31
Show file tree
Hide file tree
Showing 19 changed files with 383 additions and 62 deletions.
5 changes: 5 additions & 0 deletions functions/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ENCRYPTION_KEY =
DB_USERNAME = postgres
DB_PASSWORD =
DB_HOST = localhost
DB_DATABASE = postgres
24 changes: 20 additions & 4 deletions functions/controllers/hrEmailController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const HREmail = require('../models/HrEmail');
const { validationResult } = require('express-validator');
const { encrypt } = require('../encryption');
const { encrypt } = require('../encryption')
const fs = require('fs');
const path = require('path');
;

const addHREmail = async (req, res) => {

Expand All @@ -27,7 +30,7 @@ const addHREmail = async (req, res) => {
website,
added_by
});
res.status(201).json(newHREmail);
res.status(201).json({ success: "Thanks for your contribution", data: newHREmail});
} catch (error) {
console.error('Error adding HR email:', error);
res.status(500).json({ error: 'Failed to add HR email' });
Expand All @@ -45,7 +48,17 @@ const fetchCompanies = async (req, res) => {

const { company_id } = req.params;

console.log(company_id)
// Load email.json file
const emailJsonPath = path.join(__dirname,'..', 'data', 'email.json');
let emailJsonData = [];

try {
const emailFile = fs.readFileSync(emailJsonPath, 'utf8');
emailJsonData = JSON.parse(emailFile);
} catch (err) {
console.error('Error reading email.json file:', err);
}

if (company_id) {
//fetch the company with company_id
const email = await HREmail.findByPk(company_id)
Expand All @@ -61,8 +74,11 @@ const fetchCompanies = async (req, res) => {
const emails = await HREmail.findAll()
const plainEmails = emails.map(email => email.toJSON());

//merge two both the emails list
const combinedEmails = [...plainEmails, ...emailJsonData];

//encrypt the data
const encryptedEmails = encrypt(JSON.stringify(plainEmails))
const encryptedEmails = encrypt(JSON.stringify(combinedEmails))
res.status(200).json(encryptedEmails)
}
} catch (error) {
Expand Down
9 changes: 4 additions & 5 deletions functions/controllers/sendEmailController.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
const { validationResult } = require('express-validator');
const nodemailer = require('nodemailer');
const axios = require('axios');
const { Readable } = require('stream');


const sendEmail = async (req, res) => {
try {

const { smtpDetails, resumeUrl, from, to, subject, body } = req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}


// Create a Nodemailer transporter using the SMTP details
const transporter = nodemailer.createTransport({
logger: true, // Enables logging
debug: true, // Enable debugging output
// debug: true, // Enable debugging output

host: smtpDetails.host,
port: smtpDetails.port,
Expand Down Expand Up @@ -44,7 +43,7 @@ const sendEmail = async (req, res) => {
html: body,
attachments: [
{
filename: 'resume.pdf', // Adjust the filename as needed
filename: 'Resume.pdf', // Adjust the filename as needed
content: attachmentStream,
},
],
Expand Down
53 changes: 53 additions & 0 deletions functions/data/email.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
[
{
"email_id": "00001",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00002",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00003",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00004",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00005",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00006",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00007",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00008",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00009",
"email_address": "[email protected]",
"added_by": "admin"
},
{
"email_id": "00010",
"email_address": "[email protected]",
"added_by": "admin"
}
]

13 changes: 10 additions & 3 deletions functions/database/database.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
dialect: 'postgres',
});
port: 5432,
dialectOptions: {
ssl: {
require: true, // This will help you. But you will see nwe error
rejectUnauthorized: false // This line will fix new error
}
},
});

const connectDB = async () => {
try {
Expand Down
2 changes: 1 addition & 1 deletion lib/data/constants.dart
Original file line number Diff line number Diff line change
@@ -1 +1 @@
const String baseUrl = "https://painful-nicolette-muzammildafedaar-245f8a4f.koyeb.app/api";
const String baseUrl = "http://localhost:3000/api";
3 changes: 3 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:provider/provider.dart';
import 'package:udayah/firebase_options.dart';
import 'package:udayah/provider/auth.dart';
import 'package:udayah/provider/companies.dart';
import 'package:udayah/provider/hr_emails.dart';
import 'package:udayah/provider/mailer.dart';
import 'package:udayah/provider/navigation.dart';
import 'package:udayah/provider/smtp.dart';
Expand Down Expand Up @@ -33,6 +34,8 @@ class App extends StatelessWidget {
ChangeNotifierProvider(create: (_) => ActiveTabIndexProvider()),
ChangeNotifierProvider(create: (_) => CompaniesProvider()),
ChangeNotifierProvider(create: (_) => EmailProvider()),
ChangeNotifierProvider(create: (_) => HrEmailProvider()),

],
child: MaterialApp.router(
routerDelegate: router.routerDelegate,
Expand Down
23 changes: 23 additions & 0 deletions lib/models/hr_emails.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// hr_email.dart
class HrEmail {
final String emailAddress;
final String companyName;
final String website;
final String addedBy;

HrEmail({
required this.emailAddress,
required this.companyName,
required this.website,
required this.addedBy,
});

Map<String, dynamic> toJson() {
return {
'email_address': emailAddress,
'company_name': companyName,
'website': website,
'added_by': addedBy,
};
}
}
5 changes: 2 additions & 3 deletions lib/provider/auth.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:udayah/widgets/alerts.dart';

class AuthProvider with ChangeNotifier {
final FirebaseAuth _auth = FirebaseAuth.instance;
Expand All @@ -13,16 +14,14 @@ class AuthProvider with ChangeNotifier {
try {
UserCredential userCredential = await _auth.signInWithPopup(GoogleAuthProvider());
_user = userCredential.user;
// print(_user);
print("Hogaya bhai...");

// Redirect to dashboard after successful sign-in
if (_user != null) {
GoRouter.of(context).go('/dashboard');
}

notifyListeners();
} catch (e) {
ShowCustomDialog(context, "Error during Google sign-in: $e");
// print("Error during Google sign-in: $e");
}
}
Expand Down
41 changes: 41 additions & 0 deletions lib/provider/hr_emails.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:udayah/data/constants.dart';
import 'dart:convert';

import 'package:udayah/models/hr_emails.dart';

class HrEmailProvider with ChangeNotifier {
bool _isLoading = false;

bool get isLoading => _isLoading;

Future<String> addHrEmail(HrEmail hrEmail) async {
_isLoading = true;
notifyListeners();

try {
final response = await http.post(
Uri.parse('${baseUrl}/add-hr-email'),
headers: {'Content-Type': 'application/json'},
body: json.encode(hrEmail.toJson()),
);

if (response.statusCode == 201) {
// Handle success
final responseData = jsonDecode(response.body);
return responseData['success'];
} else {
// Handle failure
final responseData = jsonDecode(response.body);
String errorMessage = responseData['error'];
throw Exception('Failed: ${errorMessage}');
}
} catch (error) {
rethrow;
} finally {
_isLoading = false;
notifyListeners();
}
}
}
Loading

0 comments on commit b87eb31

Please sign in to comment.