Skip to content

Commit

Permalink
sizzle: User can add org url while starting timelog
Browse files Browse the repository at this point in the history
  • Loading branch information
apoorvapendse committed Nov 23, 2024
1 parent d7f8096 commit 239e8f4
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 12 deletions.
13 changes: 13 additions & 0 deletions company/templatetags/custom_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,16 @@
def get_item(dictionary, key):
"""Return the value for `key` in `dictionary`."""
return dictionary.get(key)

@register.filter
def before_dot(value):
return str(value).split(".")[0]

@register.filter
def issue_url(value):
prefix = "https://github.com/"
if prefix in value:
value = value[len(prefix):]
if len(value) > 20:
value=value[0:20]+"....."
return value
25 changes: 23 additions & 2 deletions website/api/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import uuid
from datetime import datetime
from urllib.parse import urlparse

from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
Expand Down Expand Up @@ -846,13 +847,31 @@ class TimeLogViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]

def perform_create(self, serializer):
organization_url = self.request.data.get('organization_url')

try:
serializer.save(user=self.request.user)
if organization_url:
parsed_url = urlparse(organization_url)
normalized_url = parsed_url.netloc + parsed_url.path

# Normalize the URL in the Company model (remove the protocol if present)
try:
organization = Company.objects.get(
Q(url__iexact=normalized_url) |
Q(url__iexact=f"http://{normalized_url}") |
Q(url__iexact=f"https://{normalized_url}")
)
except Company.DoesNotExist:
raise ParseError(detail="Organization not found for the given URL.")

# Save the TimeLog with the user and organization (if found, or None)
serializer.save(user=self.request.user, organization=organization)

except ValidationError as e:
raise ParseError(detail=str(e))
except Exception as e:
raise ParseError(detail="An unexpected error occurred while creating the time log.")

@action(detail=False, methods=["post"])
def start(self, request):
"""Starts a new time log"""
Expand All @@ -867,6 +886,7 @@ def start(self, request):
except ValidationError as e:
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
return Response(
{"detail": "An unexpected error occurred while starting the time log."},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
Expand All @@ -890,6 +910,7 @@ def stop(self, request, pk=None):
except ValidationError as e:
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
return Response(
{"detail": "An unexpected error occurred while stopping the time log."},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
Expand Down
25 changes: 25 additions & 0 deletions website/migrations/0154_timelog_organization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 5.1.3 on 2024-11-21 13:44

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("website", "0153_delete_contributorstats"),
]

operations = [
migrations.AddField(
model_name="timelog",
name="organization",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="organization",
to="website.company",
),
),
]
18 changes: 18 additions & 0 deletions website/migrations/0155_alter_company_url.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.1.3 on 2024-11-22 11:54

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("website", "0154_timelog_organization"),
]

operations = [
migrations.AlterField(
model_name="company",
name="url",
field=models.URLField(unique=True),
),
]
5 changes: 4 additions & 1 deletion website/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class Company(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=500, null=True, blank=True)
logo = models.ImageField(upload_to="company_logos", null=True, blank=True)
url = models.URLField()
url = models.URLField(unique=True)
email = models.EmailField(null=True, blank=True)
twitter = models.CharField(max_length=30, null=True, blank=True)
facebook = models.URLField(null=True, blank=True)
Expand Down Expand Up @@ -862,12 +862,15 @@ class TimeLog(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="timelogs"
)
#associate organization with sizzle
organization = models.ForeignKey(Company, on_delete=models.CASCADE,related_name="organization",null=True,blank=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField(null=True, blank=True)
duration = models.DurationField(null=True, blank=True)
github_issue_url = models.URLField(null=True, blank=True) # URL field for GitHub issue
created = models.DateTimeField(default=timezone.now, editable=False)


def save(self, *args, **kwargs):
if self.end_time and self.start_time <= self.end_time:
self.duration = self.end_time - self.start_time
Expand Down
2 changes: 1 addition & 1 deletion website/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ class Meta:
class TimeLogSerializer(serializers.ModelSerializer):
class Meta:
model = TimeLog
fields = ["id", "user", "start_time", "end_time", "duration", "github_issue_url", "created"]
fields = ["id", "user", "organization", "start_time", "end_time", "duration", "github_issue_url", "created"]
read_only_fields = [
"id",
"user",
Expand Down
60 changes: 52 additions & 8 deletions website/templates/sizzle/time_logs.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!-- templates/time_logs.html -->
{% extends "base.html" %}
{% load custom_filters%}
{% load static %}
{% block content %}
<style>
Expand All @@ -22,7 +23,7 @@
<form id="start-time-log-form" novalidate>
{% csrf_token %}
<div class="form-group">
<label for="github_issue_url">GitHub Issue URL:</label>
<label for="github_issue_url">GitHub Issue URL*</label>
<input type="url"
class="form-control"
id="github_issue_url"
Expand All @@ -36,6 +37,21 @@
</small>
<div class="invalid-feedback">Please provide a valid GitHub Issue URL.</div>
</div>
<div class="form-group">
<label for="organization_url">Organization URL(optional)</label>
<input type="url"
class="form-control"
id="organization_url"
name="organization_url"
required
pattern="https?://.+"
aria-describedby="organizationURL"
placeholder="https://myorg.xyz">
<small id="organizationURL" class="form-text text-muted">
Enter a valid Organization URL (e.g., https://myorg.xyz).
</small>
<div class="invalid-feedback">Please provide a valid Organization URL(optional).</div>
</div>
<button type="submit" class="btn btn-primary" id="start-button">Start Time Log</button>
</form>
{% endif %}
Expand Down Expand Up @@ -67,6 +83,7 @@ <h2>Existing Time Logs</h2>
<th scope="col">End Time</th>
<th scope="col">Duration</th>
<th scope="col">GitHub Issue URL</th>
<th scope="col">Organization URL</th>
</tr>
</thead>
<tbody id="time-logs-table-body">
Expand All @@ -75,11 +92,24 @@ <h2>Existing Time Logs</h2>
<tr>
<td>{{ log.start_time|date:"DATETIME_FORMAT" }}</td>
<td>{{ log.end_time|date:"DATETIME_FORMAT" }}</td>
<td>{{ log.duration }}</td>
{% comment %} Only show hours, mins, seconds {% endcomment %}
<td>{{ log.duration|before_dot }}</td>

<td>
<a href="{{ log.github_issue_url }}"
target="_blank"
rel="noopener noreferrer">{{ log.github_issue_url }}</a>
title="{{ log.github_issue_url }}"
rel="noopener noreferrer">{{ log.github_issue_url | issue_url }}</a>
</td>
<td>
{% if log.organization %}
<a href="https://{{ log.organization }}"
target="_blank"
title="{{ log.organization }}"
rel="noopener noreferrer">{{ log.organization }}</a>
{%else %}
<span>-</span>
{%endif%}
</td>
</tr>
{% endif %}
Expand Down Expand Up @@ -164,16 +194,30 @@ <h2>Existing Time Logs</h2>
$('#start-time-log-form').on('submit', function(event){
event.preventDefault();
const githubIssueUrl = $('#github_issue_url').val().trim();

// Simple URL validation
const urlPattern = /^https?:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+$/;
if (!urlPattern.test(githubIssueUrl)) {
const organizationURL = $('#organization_url').val().trim();

// Simple URL validation for github and organization
const githubUrlPattern = /^https?:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/\d+$/;
if (!githubUrlPattern.test(githubIssueUrl)) {
// Display an alert message
$('#message-container').html(`<div class="alert_box" role="alert">
Please provide a valid GitHub Issue URL.
</div>`);
return;
}
//only check organizationURL if it is entered
const organizationUrlPattern = /^https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (organizationURL &&!organizationUrlPattern.test(organizationURL)) {
// Display an alert message
$('#message-container').html(`<div class="alert_box" role="alert">
Please provide a valid Organization URL.
</div>`);
return;
}
let ajaxdata={
'github_issue_url': githubIssueUrl,
'organization_url': organizationURL
}

$.ajax({
url: apiBaseUrl + 'start/',
Expand All @@ -182,7 +226,7 @@ <h2>Existing Time Logs</h2>
'Authorization': `Token ${token}`,
'Content-Type': 'application/json'
},
data: JSON.stringify({ 'github_issue_url': githubIssueUrl }),
data: JSON.stringify(ajaxdata),
success: function(data){
location.reload();
},
Expand Down

0 comments on commit 239e8f4

Please sign in to comment.