From 9ec48f075fb5104adc7935905e6d7ea7532ff3ee Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Thu, 3 Dec 2020 12:31:39 -0500 Subject: [PATCH] Initial Commit basic web-app functionality works --- manage.py | 22 ++++ recmaint/__init__.py | 0 recmaint/asgi.py | 16 +++ recmaint/settings.py | 121 ++++++++++++++++++ recmaint/urls.py | 24 ++++ recmaint/wsgi.py | 16 +++ tasks/__init__.py | 0 tasks/admin.py | 7 + tasks/apps.py | 5 + tasks/forms.py | 8 ++ .../management/commands/sendNotifications.py | 20 +++ tasks/migrations/0001_initial.py | 44 +++++++ tasks/migrations/__init__.py | 0 tasks/models.py | 68 ++++++++++ tasks/templates/tasks/index.html | 21 +++ tasks/templates/tasks/taskDetail.html | 25 ++++ tasks/templates/tasks/toolDetail.html | 6 + tasks/tests.py | 3 + tasks/urls.py | 14 ++ tasks/views.py | 51 ++++++++ 20 files changed, 471 insertions(+) create mode 100755 manage.py create mode 100644 recmaint/__init__.py create mode 100644 recmaint/asgi.py create mode 100644 recmaint/settings.py create mode 100644 recmaint/urls.py create mode 100644 recmaint/wsgi.py create mode 100644 tasks/__init__.py create mode 100644 tasks/admin.py create mode 100644 tasks/apps.py create mode 100644 tasks/forms.py create mode 100644 tasks/management/commands/sendNotifications.py create mode 100644 tasks/migrations/0001_initial.py create mode 100644 tasks/migrations/__init__.py create mode 100644 tasks/models.py create mode 100644 tasks/templates/tasks/index.html create mode 100644 tasks/templates/tasks/taskDetail.html create mode 100644 tasks/templates/tasks/toolDetail.html create mode 100644 tasks/tests.py create mode 100644 tasks/urls.py create mode 100644 tasks/views.py diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..d08bb83 --- /dev/null +++ b/manage.py @@ -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() diff --git a/recmaint/__init__.py b/recmaint/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/recmaint/asgi.py b/recmaint/asgi.py new file mode 100644 index 0000000..86a7bc7 --- /dev/null +++ b/recmaint/asgi.py @@ -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() diff --git a/recmaint/settings.py b/recmaint/settings.py new file mode 100644 index 0000000..7868b56 --- /dev/null +++ b/recmaint/settings.py @@ -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/' diff --git a/recmaint/urls.py b/recmaint/urls.py new file mode 100644 index 0000000..d849ca1 --- /dev/null +++ b/recmaint/urls.py @@ -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), +] diff --git a/recmaint/wsgi.py b/recmaint/wsgi.py new file mode 100644 index 0000000..c6caae7 --- /dev/null +++ b/recmaint/wsgi.py @@ -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() diff --git a/tasks/__init__.py b/tasks/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tasks/admin.py b/tasks/admin.py new file mode 100644 index 0000000..6c3bda0 --- /dev/null +++ b/tasks/admin.py @@ -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) diff --git a/tasks/apps.py b/tasks/apps.py new file mode 100644 index 0000000..2054722 --- /dev/null +++ b/tasks/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class TasksConfig(AppConfig): + name = 'tasks' diff --git a/tasks/forms.py b/tasks/forms.py new file mode 100644 index 0000000..0e03d29 --- /dev/null +++ b/tasks/forms.py @@ -0,0 +1,8 @@ +from django import forms + +from .models import Event + +class EventForm(forms.ModelForm): + class Meta: + model = Event + fields = ['date', 'user', 'notes'] diff --git a/tasks/management/commands/sendNotifications.py b/tasks/management/commands/sendNotifications.py new file mode 100644 index 0000000..12e7177 --- /dev/null +++ b/tasks/management/commands/sendNotifications.py @@ -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}')) diff --git a/tasks/migrations/0001_initial.py b/tasks/migrations/0001_initial.py new file mode 100644 index 0000000..4e40d5a --- /dev/null +++ b/tasks/migrations/0001_initial.py @@ -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)), + ], + ), + ] diff --git a/tasks/migrations/__init__.py b/tasks/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tasks/models.py b/tasks/models.py new file mode 100644 index 0000000..dd64343 --- /dev/null +++ b/tasks/models.py @@ -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}" diff --git a/tasks/templates/tasks/index.html b/tasks/templates/tasks/index.html new file mode 100644 index 0000000..475ff92 --- /dev/null +++ b/tasks/templates/tasks/index.html @@ -0,0 +1,21 @@ +

Tools

+{% if tools %} + +{% else %} +

No tools are available.

+{% endif %} + +

Tasks

+{% if tasks %} + +{% else %} +

No tasks are available.

+{% endif %} diff --git a/tasks/templates/tasks/taskDetail.html b/tasks/templates/tasks/taskDetail.html new file mode 100644 index 0000000..c67cacb --- /dev/null +++ b/tasks/templates/tasks/taskDetail.html @@ -0,0 +1,25 @@ +

{{ tool }}

+

{{ task.name }}

+

Next scheduled time: {{ task.next_recurrence }}

+

Overdue: {{ task.is_overdue }}

+ +
+ {% csrf_token %} + {{ form }} + +
+ + + + + + + + {% for event in events %} + + + + + + {% endfor %} +
Date User Notes
{{ event.date }} {{ event.user }} {{ event.notes }}
diff --git a/tasks/templates/tasks/toolDetail.html b/tasks/templates/tasks/toolDetail.html new file mode 100644 index 0000000..6c025fe --- /dev/null +++ b/tasks/templates/tasks/toolDetail.html @@ -0,0 +1,6 @@ +

{{ tool }}

+ + +{% for task in tasks %} +
  • {{ task.name }}
  • +{% endfor %} diff --git a/tasks/tests.py b/tasks/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/tasks/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/tasks/urls.py b/tasks/urls.py new file mode 100644 index 0000000..74c3d49 --- /dev/null +++ b/tasks/urls.py @@ -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('/', views.toolDetail, name='toolDetail'), + # ex: /CMS00001/tasks/ + path('/tasks/', lambda request, asset_tag: redirect('toolDetail', asset_tag)), + # ex: /CMS00001/tasks/task_name/ + path('/tasks/', views.taskDetail, name='taskDetail'), +] diff --git a/tasks/views.py b/tasks/views.py new file mode 100644 index 0000000..e12b2fc --- /dev/null +++ b/tasks/views.py @@ -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)