Initial Commit

basic web-app functionality works
This commit is contained in:
Adam Goldsmith 2020-12-03 12:31:39 -05:00
commit 9ec48f075f
20 changed files with 471 additions and 0 deletions

22
manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'recmaint.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
recmaint/__init__.py Normal file
View File

16
recmaint/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for recmaint project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'recmaint.settings')
application = get_asgi_application()

121
recmaint/settings.py Normal file
View File

@ -0,0 +1,121 @@
"""
Django settings for recmaint project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g&zqf68eks@z$ctb%3_5+retmt%_i0=)7-y$i^gvc6p#s1+*ng'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'tasks.apps.TasksConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'recmaint.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'recmaint.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = False
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'

24
recmaint/urls.py Normal file
View File

@ -0,0 +1,24 @@
"""recmaint URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.shortcuts import redirect
from django.urls import include, path
urlpatterns = [
path('', lambda request: redirect('/tasks/')),
path('tasks/', include('tasks.urls')),
path('admin/', admin.site.urls),
]

16
recmaint/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for recmaint project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'recmaint.settings')
application = get_wsgi_application()

0
tasks/__init__.py Normal file
View File

7
tasks/admin.py Normal file
View File

@ -0,0 +1,7 @@
from django.contrib import admin
from .models import Tool, Task, Event
admin.site.register(Tool)
admin.site.register(Task)
admin.site.register(Event)

5
tasks/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class TasksConfig(AppConfig):
name = 'tasks'

8
tasks/forms.py Normal file
View File

@ -0,0 +1,8 @@
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['date', 'user', 'notes']

View File

@ -0,0 +1,20 @@
import smtplib
from email.message import EmailMessage
from django.core.management.base import BaseCommand, CommandError
from tasks.models import Tool, Task, Event
class Command(BaseCommand):
help = 'Sends any notifications for upcoming and overdue tasks'
# TODO: actually send notifications
def handle(self, *args, **options):
for tool in Tool.objects.all():
print(tool.name)
for task in tool.task_set.all():
print('==>', task.name, 'next:', task.next_recurrence())
if task.is_overdue():
self.stdout.write(self.style.SUCCESS(
f'Sending Notification for task {task.name}'))

View File

@ -0,0 +1,44 @@
# Generated by Django 3.1.3 on 2020-12-02 20:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Tool',
fields=[
('name', models.CharField(max_length=200)),
('asset_tag', models.CharField(max_length=10, primary_key=True, serialize=False)),
],
),
migrations.CreateModel(
name='Task',
fields=[
('name', models.CharField(max_length=200)),
('slug', models.SlugField(primary_key=True, serialize=False)),
('recurrence_interval', models.CharField(max_length=200)),
('recurrence_base', models.DateField(blank=True, null=True)),
('tool', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tasks.tool')),
],
),
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField()),
('notes', models.TextField(blank=True)),
('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tasks.task')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View File

68
tasks/models.py Normal file
View File

@ -0,0 +1,68 @@
from datetime import datetime
from dateutil.rrule import rrulestr
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
class Tool(models.Model):
name = models.CharField(max_length=200)
asset_tag = models.CharField(max_length=10, primary_key=True)
def __str__(self):
return f"{self.name} - {self.asset_tag}"
def get_absolute_url(self):
return reverse('toolDetail', args=[self.asset_tag])
class Task(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(primary_key=True)
tool = models.ForeignKey(Tool, on_delete=models.CASCADE)
recurrence_interval = models.CharField(max_length=200)
recurrence_base = models.DateField(null=True, blank=True)
def __str__(self):
return f"{self.tool.name}: {self.name}"
def get_absolute_url(self):
return reverse('taskDetail', args=[self.tool.asset_tag, self.slug])
@property
def last_event(self):
return self.event_set.latest('date')
@property
def next_recurrence(self):
if self.recurrence_base is None: # relative date
try:
rrule = rrulestr(self.recurrence_interval, dtstart=self.last_event.date)
return rrule[1]
except Event.DoesNotExist:
return None
else: # absolute date
rrule = rrulestr(self.recurrence_interval, dtstart=self.recurrence_base)
try:
return rrule.after(self.last_event.date)
except Event.DoesNotExist:
return rrule[1]
@property
def is_overdue(self):
next_rec = self.next_recurrence
if next_rec is None:
return False
else:
return next_rec < datetime.now()
class Event(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
date = models.DateField()
notes = models.TextField(blank=True)
def __str__(self):
return f"{self.task}: {self.user} {self.date}"

View File

@ -0,0 +1,21 @@
<h1> Tools </h1>
{% if tools %}
<ul>
{% for tool in tools %}
<li><a href="{{ tool.get_absolute_url }}">{{ tool.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No tools are available.</p>
{% endif %}
<h1> Tasks </h1>
{% if tasks %}
<ul>
{% for task in tasks %}
<li><a href="{{ task.get_absolute_url }}">{{ task.name }}</a> - last at {{ task.last_event.date }}, next at {{ task.next_recurrence }} </li>
{% endfor %}
</ul>
{% else %}
<p>No tasks are available.</p>
{% endif %}

View File

@ -0,0 +1,25 @@
<h1><a href="{{ tool.get_absolute_url }}">{{ tool }}</a></h1>
<h2> {{ task.name }} </h2>
<p> Next scheduled time: {{ task.next_recurrence }} </p>
<p> Overdue: {{ task.is_overdue }} </p>
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<table>
<tr>
<th> Date </th>
<th> User </th>
<th> Notes </th>
</tr>
{% for event in events %}
<tr>
<td> {{ event.date }} </td>
<td> {{ event.user }} </td>
<td> {{ event.notes }} </td>
</tr>
{% endfor %}
</table>

View File

@ -0,0 +1,6 @@
<h1> {{ tool }} </h1>
{% for task in tasks %}
<li><a href="{{ task.get_absolute_url }}">{{ task.name }}</a></li>
{% endfor %}

3
tasks/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

14
tasks/urls.py Normal file
View File

@ -0,0 +1,14 @@
from django.shortcuts import redirect
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
# ex: /CMS00001/
path('<str:asset_tag>/', views.toolDetail, name='toolDetail'),
# ex: /CMS00001/tasks/
path('<str:asset_tag>/tasks/', lambda request, asset_tag: redirect('toolDetail', asset_tag)),
# ex: /CMS00001/tasks/task_name/
path('<str:asset_tag>/tasks/<str:task_slug>', views.taskDetail, name='taskDetail'),
]

51
tasks/views.py Normal file
View File

@ -0,0 +1,51 @@
from datetime import datetime
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from .models import Tool, Task, Event
from .forms import EventForm
def index(request):
context = {
'tools': Tool.objects.all(),
'tasks': Task.objects.all(),
}
return render(request, 'tasks/index.html', context)
def toolDetail(request, asset_tag):
tool = get_object_or_404(Tool, asset_tag=asset_tag)
tasks = tool.task_set.all()
context = {
'tool': tool,
'tasks': tasks,
}
return render(request, 'tasks/toolDetail.html', context)
def taskDetail(request, asset_tag, task_slug):
tool = get_object_or_404(Tool, asset_tag=asset_tag)
task = get_object_or_404(tool.task_set, slug=task_slug)
events = task.event_set.all()
if request.method == 'POST':
event = Event(task=task)
form = EventForm(request.POST, instance=event)
if form.is_valid():
form.save()
pass
else:
form = EventForm(initial={
'date': datetime.now(),
'user': request.user,
})
context = {
'tool': tool,
'task': task,
'events': events,
'form': form,
}
return render(request, 'tasks/taskDetail.html', context)