Commit d3b3629f authored by DwyxE's avatar DwyxE

csv now read yay

parent 07abeafd
# Generated by Django 4.2 on 2023-04-04 12:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('IPSapp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='summaryreport',
name='employee_name',
field=models.CharField(default='No Name', max_length=255),
),
migrations.AlterField(
model_name='productivity',
name='report_no',
field=models.AutoField(primary_key=True, serialize=False),
),
]
# Generated by Django 4.2 on 2023-04-04 13:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('IPSapp', '0002_summaryreport_employee_name_and_more'),
]
operations = [
migrations.AlterField(
model_name='summaryreport',
name='prod_score',
field=models.FloatField(),
),
]
...@@ -22,7 +22,7 @@ class Employee(models.Model): ...@@ -22,7 +22,7 @@ class Employee(models.Model):
# db_table = 'employee' # db_table = 'employee'
class Productivity(models.Model): class Productivity(models.Model):
report_no = models.AutoField(max_length=10, primary_key=True) report_no = models.AutoField(primary_key=True)
#employee = models.ForeignKey('Employee', on_delete=models.CASCADE) #employee = models.ForeignKey('Employee', on_delete=models.CASCADE)
prod_date = models.DateField(null=True) prod_date = models.DateField(null=True)
workinghours = models.DurationField() workinghours = models.DurationField()
...@@ -94,8 +94,8 @@ class History(models.Model): ...@@ -94,8 +94,8 @@ class History(models.Model):
class SummaryReport(models.Model): class SummaryReport(models.Model):
sr_no = models.AutoField(primary_key=True) sr_no = models.AutoField(primary_key=True)
employee_name = models.CharField(max_length=255) employee_name = models.CharField(max_length=255, default="No Name")
prod_score = models.IntegerField() prod_score = models.FloatField()
date = models.DateField() date = models.DateField()
totalworkhrs = models.DurationField() totalworkhrs = models.DurationField()
......
{% extends 'base.html' %} <html>
<head>
<title>Bar Chart Example using Chart.js</title>
<!-- Load Chart.js from jsdelivr -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<!-- <body>
<canvas id="myChart"></canvas>
<script>
// Get the data from the server using Django templates
const data = JSON.parse('{{ summary_data | safe }}');
// Get the labels and values from the data
const labels = data.map(entry => entry.employee_name);
const values = data.map(entry => entry.prod_score);
// Create a new Chart.js instance
const ctx = document.getElementById('myChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Productivity Score',
data: values,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</body> -->
</html>
{% block content %}
<div id="chart-container">
{{ chart|safe }}
</div>
{% endblock %}
\ No newline at end of file
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<td>{{ row.sr_no}}</td> <td>{{ row.sr_no}}</td>
<td>{{ row.employee_name}}</td> <td>{{ row.employee_name}}</td>
<td>{{ row.date}}</td> <td>{{ row.date}}</td>
<td>{{ row.productivity_score }}</td> <td>{{ row.prod_score }}</td>
<td>{{ row.totalworkhrs }}</td> <td>{{ row.totalworkhrs }}</td>
<!-- add more cells for additional fields --> <!-- add more cells for additional fields -->
</tr> </tr>
......
...@@ -9,7 +9,8 @@ urlpatterns = [ ...@@ -9,7 +9,8 @@ urlpatterns = [
path('upload_csv/', views.upload_csv, name = 'upload_csv'), path('upload_csv/', views.upload_csv, name = 'upload_csv'),
path('show_csv_data/', views.show_csv_data, name ='show_csv_data'), path('show_csv_data/', views.show_csv_data, name ='show_csv_data'),
path('signup/', views.signup, name='signup'), path('signup/', views.signup, name='signup'),
path('show_csv_data2/', views.show_csv_data2, name='show_csv_data2') path('show_csv_data2/', views.show_csv_data2, name='show_csv_data2'),
path('chart_template/', views.chart_template, name='chart_template')
# path('', views.login_page, name='loginpage'), # path('', views.login_page, name='loginpage'),
] ]
\ No newline at end of file
...@@ -10,6 +10,8 @@ from django.views.generic import View ...@@ -10,6 +10,8 @@ from django.views.generic import View
# from chartjs.views.lines import BaseLineChartView # from chartjs.views.lines import BaseLineChartView
# import Chart from 'chart.js/auto'; # import Chart from 'chart.js/auto';
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.db.models import Sum
from django.http import JsonResponse
def home(request): def home(request):
return render(request, 'EmployeeProdDB/home.html') return render(request, 'EmployeeProdDB/home.html')
...@@ -75,46 +77,84 @@ def loginpage(request): ...@@ -75,46 +77,84 @@ def loginpage(request):
else: else:
return render(request, 'EmployeeProdDB/loginpage.html') return render(request, 'EmployeeProdDB/loginpage.html')
# def upload_csv(request):
# if request.method == 'POST':
# csv_file = request.FILES['csv_file']
# if not csv_file.name.endswith('.csv'):
# messages.error(request, 'This is not a CSV file')
# else:
# # read the data from the uploaded file
# csv_data = csv.reader(
# (line.decode('utf-8') for line in csv_file),
# delimiter=',',
# quotechar='"'
# )
# #Loop through data rows
# for i, row in enumerate(csv_data):
# # Check if this row is the start of a new report
# if row[0] == 'PRODUCTIVITY REPORT':
# # Reset variables for the new report
# sr_no = row[1]
# employee_name= None
# prod_score = None
# date = None
# totalworkhrs = None
# # Check if this is the fifth row after the start of the report
# elif i == 4 and employee_name is None:
# employee_name = row[0]
# # Check if this row contains a date and "Total Duration:" and "Productivity %"
# if len(row) > 2 and "/" in row[0] and "Total Duration:" in row and "Productivity %" in row:
# date = datetime.strptime(row[0], '%m/%d/%Y').date()
# totalworkhrs = timedelta(hours=float(row[row.index("Total Duration:") + 2]))
# prod_score = int(row[row.index("Productivity %") + 2])
# summary_pr = SummaryReport.objects.create(sr_no=sr_no, employee_name=employee_name, prod_score=prod_score, date=date, totalworkhrs=totalworkhrs)
# summary_pr.save()
# return redirect('home')
# return render(request, 'EmployeeProdDB/upload_csv.html')
def upload_csv(request): def upload_csv(request):
if request.method == 'POST': if request.method == 'POST':
csv_file = request.FILES['csv_file'] csv_file = request.FILES['csv_file']
if not csv_file.name.endswith('.csv'): if not csv_file.name.endswith('.csv'):
messages.error(request, 'This is not a CSV file') messages.error(request, 'This is not a CSV file')
else: else:
# read the data from the uploaded file # Read the data from the uploaded file
csv_data = csv.reader( csv_data = csv.DictReader(csv_file.read().decode('utf-8').splitlines())
(line.decode('utf-8') for line in csv_file),
delimiter=',', # Loop through data rows
quotechar='"' for row in csv_data:
# Convert duration string to a Duration object
working_hours = row['Work Hours']
if working_hours:
hours, minutes, seconds= map(int, working_hours.split(':'))
working_hours = timedelta(hours=hours, minutes=minutes, seconds=seconds)
# Create a new SummaryReport object
summary_report = SummaryReport.objects.create(
employee_name=row['Employee Name'],
prod_score=row['Productivity Score'],
date=row['Date'],
totalworkhrs=working_hours
) )
#Loop through data rows
for i, row in enumerate(csv_data):
# Check if this row is the start of a new report
if row[0] == 'PRODUCTIVITY REPORT':
# Reset variables for the new report
sr_no = row[1]
employee_name= None
prod_score = None
date = None
totalworkhrs = None
# Check if this is the fifth row after the start of the report
elif i == 4 and employee_name is None:
employee_name = row[0]
# Check if this row contains a date and "Total Duration:" and "Productivity %"
if len(row) > 2 and "/" in row[0] and "Total Duration:" in row and "Productivity %" in row:
date = datetime.strptime(row[0], '%m/%d/%Y').date()
totalworkhrs = timedelta(hours=float(row[row.index("Total Duration:") + 2]))
prod_score = int(row[row.index("Productivity %") + 2])
summary_pr = SummaryReport.objects.create(sr_no=sr_no, employee_name=employee_name, prod_score=prod_score, date=date, totalworkhrs=totalworkhrs)
summary_pr.save()
return redirect('home')
return render(request, 'EmployeeProdDB/upload_csv.html')
return render(request, 'EmployeeProdDB/upload_csv.html', {'message': 'Data imported successfully!'})
return render(request, 'EmployeeProdDB/upload_csv.html')
def chart_template(request):
data = SummaryReport.objects.values('employee_name').annotate(total_prod_score=Sum('prod_score')).order_by('-total_prod_score')[:10]
labels = list(map(lambda x: x['employee_name'], data))
data = list(map(lambda x: x['total_prod_score'], data))
return render(request, 'EmployeeProdDB/chart_template.html', {
'labels': labels,
'data': data,
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment