17 Commits

Author SHA1 Message Date
231cefbcd4 claude version of first prompt 2026-11-01 19:00:54 -05:00
6546c86bcc updated task-brief with the first prompt and notes additions 2026-11-01 18:48:22 -05:00
cd9b7a095b may be the final 2026-11-01 16:58:57 -05:00
7bde8c3b85 updates to the questions
Answers:

 1. Checked against code:
     - Project dropdown: project_id / project_name ✓ (Project model)
     - "+ New Task" URL: /new_task/ ✓ (urls.py name=new_task)
     - View URL: /task_information/{task_id}/ ✓ (urls.py
       name=task_information)

 2. Updated sources/view-mockup-generation.md — now matches all decisions
    (6 statuses, higher-order badges, 3 priority color groups, real sort
    fields, numeric filter IDs, elided pagination).

 3. Unassigned filter value: 0 (numeric), not "unassigned". View treats
    assignee=0 as task_assigned_to__isnull=True.

 4. Mobile check: Can't render here — you'll need to open the generated
    wireframe in a browser and narrow to <1024px.

 5. Commit: Noted — I haven't committed anything.
2026-11-01 16:17:35 -05:00
ff653b9a97 after priority 2026-11-01 16:13:12 -05:00
93a1948e8b after pagination 2026-11-01 15:58:10 -05:00
0fd7e77ce7 up to sorting is now mocked 2026-11-01 15:33:07 -05:00
28899110bf create view mockup and updated specs 2026-11-01 15:08:48 -05:00
eb6677c9fa rewrote specs, added new ui generation spec
- task-brief is the essential 3 questions answers
- tdd - is the revised tdd plan
- wireframe-gen - is 1st cut at writing up the mockup instructions
- view-mockup - is the 2nd cut
2026-11-01 14:19:06 -05:00
63453fa3ed updated project-rules, expanding all sections 2026-11-01 13:39:36 -05:00
2460343d79 add new sources
- permissions - all about the permission system
- selected task - requirements for the task
- list-wireframe - html mock of the page
- tdd - tdd step through implemention
2026-11-01 13:12:28 -05:00
3d5135c8b8 add UI conventions doc and convo log up to 261030 2026-10-31 19:39:11 -04:00
c6ee18c1d3 added candidates tasks doc 2026-10-30 18:53:53 -04:00
1ad38e24ca new file 2026-10-30 13:19:41 -04:00
ef252a02e5 initial NearBeach 2026-10-28 21:00:21 -04:00
3d61b05194 fix up the project-rules.md 2026-10-27 18:41:09 -04:00
e76914c977 prep 2026-10-27 18:23:57 -04:00
2803 changed files with 804608 additions and 3495117 deletions

58
.gitignore vendored
View File

@@ -1,59 +1,5 @@
archive
**/__pycache__
.env
MODNet-with-training/
avds-cleaner/
avspeech/
browser-extensions/
elasticmq-container/
folders
gcp-application/
gcp-cloud-infrastructure/
gcp-infrastructure/
lambda-cloudwatch-logs-to-loggly/
lambda-datadog-forwarder/
lambda-potion-engagement/
lambda-potion-schedular/
lambda-potion-transcription-scheduler/
lambda-text-to-speech/
lambda-video-processing/
microservice-dynamic-screen-recording/
microservice-potion-voice/
potion-ai/
potion-ai-cpu/
potion-ai-gpu/
potion-ai-pretrained-models-infra/
potion-analytics/
potion-api/
potion-app/
potion-app-infra/
potion-bastion/
potion-custom-domain-app/
potion-devops/
potion-dynamic-screen-recording-lambda/
potion-job-consumer/
potion-job-producer/
potion-multi-dsr-watcher/
potion-qa/
potion-snapshot-testing/
potion-stitch/
potion-tryon/
potion-video-background-change/
potion-video-processing/
potion-video-processing-devops/
potion-voice/
potion-voice-dataset/
potion-voice-utils/
potion-watcher/
potion-web/
potion-website/
potion-website-recording-handler/
potion-wp-site/
sentence-split-service/
urlbox-experiments/
video-synth-api/
wav2lip-fa/
yeahsure-tryon/
*.gz
*.gz
*.zip

View File

@@ -0,0 +1,62 @@
version: 2.1
jobs:
build-and-test-backend:
docker:
- image: cimg/python:3.12.0
steps:
- checkout
- restore_cache:
key: deps1-{{ .Branch }}-{{ checksum "requirements.txt" }}
- run:
name: Building Virtual Environment
command: |
python3 -m venv venv
. venv/bin/activate
pip install -r requirements-dev.txt
pip install coverage
- save_cache:
key: deps1-{{ .Branch }}-{{ checksum "requirements.txt" }}
paths:
- "venv"
- run:
name: Running Tests
command: |
. venv/bin/activate
CI=true coverage run --branch \
--omit='venv/*,NearBeach/tests/*,NearBeach/migrations/*,*/__init__.py,manage.py,settings.py,NearBeach/admin.py,NearBeach/apps.py' \
manage.py test
coverage report
coverage html
- store_artifacts: # Upload test summary for display in Artifacts: https://circleci.com/docs/2.0/artifacts/
path: ~/project/htmlcov
destination: tr1
build-and-test-frontend:
docker:
- image: cimg/node:23.4.0
steps:
- checkout
- run:
name: Update NPM
command: "sudo npm install -g npm"
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Install npm Dependencies
command: "npm install"
- save_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
paths:
- ./node_modules
- run:
name: Run Vitest Unit Tests for VueJS
command: "npm run unit-test"
- store_artifacts:
path: ~/project/coverage
destination: tr2
workflows:
build:
jobs:
- build-and-test-backend
- build-and-test-frontend

View File

@@ -0,0 +1,27 @@
version = 1
test_patterns = [
"NearBeach/tests/**",
"test_*.py"
]
exclude_patterns = [
"browserstack/**",
"cypress/**",
"NearBeach/migrations/**",
"NearBeach/static/**",
"Nearbeach/migrations/**",
"tests/**",
]
[[analyzers]]
name = "javascript"
[analyzers.meta]
plugins = ["vue"]
[[analyzers]]
name = "python"
[analyzers.meta]
runtime_version = "3.x.x"

8
NearBeach/.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
# These are supported funding model platforms
github: NearBeach # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: NearBeach
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
custom: # Replace with a single custom sponsorship URL

View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Navigate the menu MENU -> SUB MENU
3. Click on '....'
4. Scroll down to '....'
5. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Actual Results**
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,17 @@
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -0,0 +1,32 @@
from string import Template
import requests
# Get the latest version from Github
results = requests.get("https://api.github.com/repos/NearBeach/NearBeach/releases?page=1&per_page=1")
results_json = results.json()
# Using the results, find the tag name (aka version)
version = results_json[0]['tag_name']
# Create the __init__.py file
with open('./.github/deployment_files/template__init__.txt', 'r') as input_file:
src = Template(input_file.read())
result = src.substitute({'version': version})
input_file.close()
with open('./NearBeach/__init__.py', 'w') as output_file:
output_file.write(result)
output_file.close()
# Create the pyproject.toml file
with open('./.github/deployment_files/template_pyproject.toml', 'r') as input_file:
src = Template(input_file.read())
result = src.substitute({'version': version})
input_file.close()
with open('./pyproject.toml', 'w') as output_file:
output_file.write(result)
output_file.close()

View File

@@ -0,0 +1,2 @@
name = "NearBeach"
__version__ = "$version"

View File

@@ -0,0 +1,60 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "NearBeach"
version = "$version"
dependencies = [
"Django>=4.2.17",
"simplejson",
"pillow>=10.0.1",
"urllib3",
"boto3==1.35.99",
"azure-storage-blob",
"azure-identity",
"pip>=19.2",
"djangorestframework",
"django-two-factor-auth",
"django-two-factor-auth[phonenumberslite]",
"django_otp",
"drf_spectacular",
"drf_spectacular[sidecar]"
]
requires-python = ">=3.10"
authors = [
{name = "Luke Christopher Clarke", email = "luke@nearbeach.org"},
]
maintainers = [
{name = "Luke Christopher Clarke", email = "luke@nearbeach.org"},
]
description = "NearBeach - an open source project management tool"
readme = "README.md"
license = {file = "LICENSE"}
keywords = [
"project",
"task",
"project management",
"request for change",
"open source"
]
classifiers = [
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.optional-dependencies]
dev = [
"black",
"bandit",
"python-dotenv",
"django-storages",
]
[project.urls]
Homepage = "https://nearbeach.org"
Documentation = "https://nearbeach.readthedocs.org"
Repository = "https://github.com/NearBeach/NearBeach.git"
"Bug Tracker" = "https://nearbeach.youtrack.cloud"

View File

@@ -0,0 +1,84 @@
name: Deploy NearBeach
on:
release:
types: [published]
workflow_dispatch:
jobs:
deploy-nearbeach:
runs-on: ubuntu-latest
environment: main
permissions:
# IMPORTANT: this permission is mandatory for trusted publishing
id-token: write
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.13.1
- name: Update Pip and Install Required Python Libraries
run: |
python3 -m pip install --upgrade pip
python3 -m pip install virtualenv
virtualenv venv
source ./venv/bin/activate
pip install requests setuptools wheel build
pip install --upgrade build
- name: Create __init__.py and PyProject.toml files
run: |
source ./venv/bin/activate
python3 ./.github/deployment_files/generate_templates.py
- name: Build Package
run: |
source ./venv/bin/activate
python3 -m build
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
deploy-static-files:
needs: deploy-nearbeach
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.12.1
- name: Create __init__.py and PyProject.toml files
run: |
python3 -m pip install --upgrade pip
python3 -m pip install virtualenv
virtualenv venv
source ./venv/bin/activate
pip install requests drf-spectacular drf-spectacular[sidecar] django-rest-knox
python3 ./.github/deployment_files/generate_templates.py
- name: Install Dependencies
run: |
source ./venv/bin/activate
pip install --editable .[dev]
- name: Collect Static files
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_STORAGE_BUCKET_NAME: ${{ secrets.AWS_STORAGE_BUCKET_NAME }}
run: |
source ./venv/bin/activate
python manage.py collectstatic --noinput
trigger-docker-build:
needs: [deploy-static-files, deploy-nearbeach]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Curl to trigger docker deployment
run: |
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.BEARER_TOKEN_FOR_GITHUB_ACTIONS }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/NearBeach/nearbeach-docker/dispatches \
-d '{"event_type":"deploy_nearbeach","client_payload":{"version":"${{ github.ref_name }}"}}'

View File

@@ -0,0 +1,38 @@
name: Build Swagger and Deploy to Azure Static Web App
on:
push:
branches:
- develop # or your deployment branch
workflow_dispatch:
jobs:
build-swagger:
runs-on: ubuntu-latest
steps:
- name: 🧾 Checkout Code
uses: actions/checkout@v3
- name: 🐍 Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11' # Match your dev env
- name: 📦 Install Dependencies
run: |
python -m pip install --upgrade pip
pip install django django-rest-framework simplejson pillow drf-spectacular drf-spectacular[sidecar] python-dotenv django_otp django-two-factor-auth django-two-factor-auth[phonenumberslite] azure-storage-blob azure-identity botocore boto3 django-rest-knox
- name: 🔧 Generate Swagger Schema
run: |
python manage.py spectacular --file swagger/swagger.json
- name: 🚀 Deploy to Azure Static Web Apps
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
action: "upload"
skip_app_build: true
app_location: "swagger"
output_location: "swagger.json"

130
NearBeach/.gitignore vendored Normal file
View File

@@ -0,0 +1,130 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Cypress
cypress/screenshots
cypress/downloads
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
node_models/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# .DS_Store
.DS_Store
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# node modules
node_modules/
# browser stack config
/tests/browserstatck/config.py
/tests/.auth/
.vscode/
.idea/
# Ignore any documents uploaded to the private folders
/local/private/
/playwright-report/
/test-results/
/playwright/.cache/
/coverage/

19
NearBeach/.prettierignore Normal file
View File

@@ -0,0 +1,19 @@
# Ignore artifacts:
build
coverage
NearBeach
NearBeach/**
.circleci
.github
.pytest_cache
.vscode
browserstack
docs
local
locust_tests
node_modules
webpack.common.js
webpack.dev.js
webpack.prod.js
webpack.watch.js
cypress.json

View File

@@ -0,0 +1,7 @@
{
"tabWidth": 4,
"useTabs": true,
"semi": true,
"vueIndentScriptAndStyle": true,
"singleAttributePerLine": true
}

View File

@@ -0,0 +1,22 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.11"
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# We recommend specifying your dependencies to enable reproducible builds:
# https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
python:
install:
- requirements: docs/requirements.in

208
NearBeach/Architecture.md Normal file
View File

@@ -0,0 +1,208 @@
# NearBeach Architecture
This document explains how NearBeach is structured so that new contributors can quickly understand how the parts of the system fit together and where to find things in the codebase.
If you are completely new to the project, start with the README for context, then come back here for a deeper architectural overview.
- Project homepage: https://nearbeach.org
- Documentation: https://nearbeach.readthedocs.io
- Community/Support: https://discord.gg/64uhRztS6n
## High-level overview
NearBeach is an open source project management system.
- Backend: Django (Python)
- Provides server‑rendered pages and a JSON API used by the frontend.
- Uses Django ORM for database access
- Uses Django for authentication handling
- Frontend: Vue.js (Single File Components, SFCs)
- Compiled via Webpack; served as static assets by Django.
- Talks to the backend using REST‑style JSON APIs.
- Database: Configured via Django ORM (SQLite for development by default, others in production).
- Tests and tooling: Python tests with pytest/Django test runner under tests/, end‑to‑end tooling available (Playwright), frontend tests with Vitest. Load testing with locust.
## Repository layout (top level)
- NearBeach/ — Django project and application code (models, serializers, views, URLs, templates, static, migrations, etc.).
- src/ — Frontend source (Vue components, JS entry points, styles). Bundled with Webpack.
- NearBeach/tests - Tests for backend
- tests/ Tests for frontend.
- docs/ — Documentation sources (Sphinx/readthedocs).
- swagger/ — API specification and assets related to API description.
- node_modules/, package.json, webpack.*.js, vitest.config.js — Frontend build and test tooling.
- pyproject.toml, requirements*.txt — Python packaging and dependencies.
- manage.py — Django management entry point.
- db.sqlite3 — Default local development database (do not commit changes from production use).
- browserstack/, playwright.config.ts, locust_tests/ — Testing and QA tooling.
## Django backend structure (NearBeach/)
Key paths inside NearBeach/ (only representative highlights listed):
- NearBeach/apps.py — Django app configuration.
- NearBeach/urls_two_factor.py — URL routes for optional two‑factor authentication flows.
- NearBeach/migrations/ — Database schema migrations (managed by Django).
- NearBeach/serializers/ — DRF‑style serializers used by API viewsets and endpoints.
- Example: NearBeach/serializers/destination_serializer.py
- NearBeach/views/ — View modules for pages and APIs. Notable sub-areas:
- NearBeach/views/api/ — JSON API endpoints grouped by domains (e.g., sprint_api_view.py, coffee_api_view.py, object_data/link_api_view.py, available_data/*_list_api_view.py, etc.).
- NearBeach/views/authentication/ — Login/2FA and related UI views.
- Other domain views: admin_views.py, sprint_views.py, card_views.py, change_task_views.py, customer_views.py, document_views.py, gdpr_wizard_views.py, etc.
- NearBeach/static/ — Static assets collected and served by Django (vendored libraries, icons, TinyMCE, etc.).
- NearBeach/templates/ — Django templates for server-rendered pages (if present).
Typical backend layering
- URL routing: Configured in project urls (and urls_two_factor.py for 2FA). Each domain area has URL patterns pointing to function-based views, class-based views, or DRF ViewSets.
- Views and APIs:
- Server-rendered views return HTML templates and embed frontend entrypoints for Vue where appropriate.
- API endpoints (in views/api) return JSON responses and accept JSON bodies. Patterns commonly use Django REST Framework style ViewSets or function-based views with @require_http_methods.
- Serializers:
- Define how model instances are converted to/from JSON payloads for the API.
- Live under NearBeach/serializers/ and are imported by API views.
- Models:
- Django ORM models define persistent data. Migrations in NearBeach/migrations/ track schema changes.
- Permissions and authentication:
- Authentication uses Django’s auth. 2FA support is routed via urls_two_factor.py and views under views/authentication/.
- Many views implement permission checks with helper utilities (e.g., get_user_group_permission) and per‑object gating.
## Vue frontend structure (src/)
- src/js/app.js — Main frontend entry that registers and bootstraps Vue components for pages.
- src/js/components.js — Central index of components for lazy/explicit imports.
- src/js/components/** — Vue Single File Components (SFCs) grouped by feature domain.
- Administration: src/js/components/administration/*.vue
- Change/Task: src/js/components/change_task/*.vue
- Cards/Kanban: src/js/components/card_information/*.vue, src/js/components/kanban/*.vue
- Users: src/js/components/users/*.vue
- Icons and shared UI: src/js/components/icons/*.vue
- State management: The project primarily composes state within components and passes props/events between them. If a global store is in use, it will be initialized from app.js; otherwise look for composables or shared modules by domain.
- Validation/UI libraries: Vuelidate is used for form validation; Bootstrap is used for CSS layout. TinyMCE is used for rich text editing.
Build output
- Webpack bundles the Vue SFCs into static assets that Django serves from its static files pipeline.
- The webpack.*.js files define common, dev, prod, and watch configurations.
## API and data flow
- Most user interactions in the UI trigger API calls to endpoints under NearBeach/views/api/.
- Serialization: Requests/Responses are validated and shaped by serializers (NearBeach/serializers/*).
- Permissions are checked server-side; the frontend should not rely solely on UI hiding.
- Common patterns:
- ViewSets for list/detail actions (e.g., CustomerListViewSet, SprintListViewSet).
- Domain-specific API modules (e.g., sprint_api_view.py) expose endpoints for the corresponding Vue components (e.g., Sprint boards, modules).
Example paths (non-exhaustive):
- NearBeach/views/api/sprint_api_view.py — Sprint-related JSON endpoints.
- NearBeach/views/api/object_data/link_api_view.py — Linking objects (relations) endpoints.
- NearBeach/views/api/coffee_api_view.py — Example/testing endpoints.
## Authentication, authorization, and security
- Authentication via Django’s session auth; the login/2FA views reside under NearBeach/views/authentication/ and urls_two_factor.py wires routes to the two_factor app.
- CSRF protection is enabled for session-authenticated POST/PUT/PATCH/DELETE by default in Django. Frontend must send CSRF tokens (usually embedded in templates or fetched via a CSRF endpoint).
- Authorization per feature/object is enforced in view functions using helper permission checks (see views/* importing get_user_group_permission and similar helpers). Always validate server-side.
## Testing
- Backend tests: Python tests under tests/ and NearBeach/tests/ where applicable.
- Example: NearBeach/tests/tests_specific_user_functionality/test_admin_user_settings.py
- Frontend unit tests: Vitest with configuration in vitest.config.js.
- E2E/Browser: Playwright config in playwright.config.ts. BrowserStack config available in browserstack/.
- Load testing: locust tests under locust_tests/.
To run backend tests locally:
- python manage.py test
- Or with pytest if configured via pyproject.toml
To run frontend unit tests:
- npm run test
## Development workflow
- Python environment
- Install dependencies from requirements.txt or requirements-dev.txt.
- Use manage.py for running the server, migrations, creating superusers, etc.
- Frontend environment
- Install Node dependencies via npm ci or npm install.
- Run Webpack in watch/dev mode with npm scripts (see package.json) and webpack.dev.js.
- Production bundles use webpack.prod.js.
Static files and assets
- Run Django collectstatic as part of deployment to gather bundled assets into the static root.
## Adding features (typical steps)
1. Backend
- Add/modify models in NearBeach/models.py or domain-specific modules and create migrations.
- Add/extend serializers in NearBeach/serializers/.
- Implement API views in NearBeach/views/api/ and add URL routes.
- Add permission checks as required.
2. Frontend
- Build or extend Vue components under src/js/components/<domain>/.
- Wire components in src/js/app.js or feature entry points.
- Call the new API endpoints and handle responses with appropriate validation and error states.
3. Tests
- Add/extend backend unit tests in tests/ or NearBeach/tests/.
- Add/extend frontend tests with Vitest.
- Update any E2E scenarios if user flows change.
## Conventions and guidelines
- Python: Follow PEP 8; keep views small and delegate serialization/validation to serializers.
- Vue: Prefer small, focused SFCs; lift shared logic into reusable components. Use Vuelidate for forms, Bootstrap for layout.
- API: Keep endpoints REST‑like; provide clear 4xx/5xx error responses with helpful detail; document in swagger/ when applicable.
- Security: Validate every server-side input; enforce object-level permissions in views; keep CSRF headers/tokens in place for state‑changing requests.
- Performance: Use pagination for list endpoints; minimize N+1 queries via select_related/prefetch_related; prefer incremental rendering on the frontend.
## Where to look for specific topics
- URL routing: NearBeach/urls_two_factor.py and the project’s main urls module.
- Authentication and 2FA: NearBeach/views/authentication/* and urls_two_factor.py (routes into two_factor.views and project-specific wrappers).
- Serializers: NearBeach/serializers/*
- API endpoints: NearBeach/views/api/*
- Feature views (HTML + Vue mount points): NearBeach/views/*_views.py
- Vue components: src/js/components/**
- Webpack configuration: webpack.common.js, webpack.dev.js, webpack.prod.js, webpack.watch.js
- Frontend entry: src/js/app.js and src/js/components.js
- Tests: tests/, NearBeach/tests/, locust_tests/
## Deployment notes (summary)
- Build frontend assets with npm run build (production) to generate minified bundles.
- Run Django migrations and collectstatic.
- Configure environment variables for database, secret key, allowed hosts, email, and any integrations.
- Serve with a production WSGI server (e.g., gunicorn/uwsgi) behind a reverse proxy; serve static files from a CDN or web server.
## Appendix: Example files referenced in recent work
- Backend views (examples):
- NearBeach/views/object_data_views.py
- NearBeach/views/api/object_data/link_api_view.py
- NearBeach/views/api/coffee_api_view.py
- NearBeach/views/sprint_views.py
- NearBeach/views/api/sprint_api_view.py
- NearBeach/views/gdpr_wizard_views.py
- Serializers:
- NearBeach/serializers/destination_serializer.py
- Frontend components:
- src/js/components/users/UserApiList.vue
- src/js/components/change_task/ChangeTaskModules.vue
- src/js/components/administration/UserList.vue
This document is intentionally high level. If you discover discrepancies or have suggestions, please open a PR to update Architecture.md or the docs in docs/.

View File

@@ -0,0 +1,50 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeach.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Separation of art from artist clause
Any code, wiki, or other form of submitted work will not be judged based on but not limited to age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. The content submitted will be judged by the validity of said content and not the person or persons whom created the content.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

143
NearBeach/CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,143 @@
# Contributing to NearBeach
Before you are able to contribute to NearBeach, you will need to the following two items;
* [Join our community on discord](https://discord.gg/64uhRztS6n)
* [Download and install NearBeach](https://nearbeach.readthedocs.io/en/latest/002-local-development-environment-setup/index.html)
From here we recommend using NearBeach, and feel free to ask questions on our discord. It will be extremely hard to contribute to NearBeach if you don't use it.
## Start of your contributing journey
We are always looking for new contributors. There are many different ways for you to contribute to NearBeach. As a beginner we are only expecting the following;
* Find and report bugs
* Send constructive feedback (especially on the UI/UX front)
* Helping others on the community use NearBeach
* Replicate issues other users are experiencing
* Discuss new feature requests
## Intermediate contributor
We do not expect everyone to submit pull requests within their first week. NearBeach is large, complicated, and made of many different moving parts. Just remember, the community is here to help you, and soon you will be;
* Submitting bug fixes
* Constructing both Unit Tests, and End-to-end tests
* Writing documentation
* Refactoring small sections of the code
## The NearBeach coder
Once you are familiar with the inner workings of NearBeach, you will be able to do the following tasks;
* Writing new components or functionality for NearBeach
* Refactoring large amounts of code
* Extending NearBeach's functionalities and implementing new functionality
and much much more. Join our [community on discord to see what you can do](https://discord.gg/64uhRztS6n)
## Misc contributions
If you like what we are archiving with NearBeach, please help us by;
* Donating via [github sponsorships](https://github.com/sponsors/NearBeach) or [our patreon](https://www.patreon.com/NearBeach)
* Marketing NearBeach
# Code of Conduct
Please read our [code of conduct here](https://github.com/NearBeach/NearBeach/blob/main/CODE_OF_CONDUCT.md).
# NearBeach Overview
NearBeach is an open source project management system, that has been built using both the frameworks; Django and VueJS.
## Objects in NearBeach
Each different module/componet in NearBeach are called Objects. The following objects currently exist;
- Organisations
- Customers
- Requirements
- Requirement Items
- Projects
- Tasks
- Request for Changes
- Kanban Boards
Each object shall have it's own folder structure within the respected location, i.e. `/views/projects`.
## Setting up local dev environment
Please follow the instructions in our documentation: [Setting up local dev environment](https://nearbeach.readthedocs.io/en/latest/002-local-development-environment-setup/index.html)
## Coding Style Guides
These style guides at the moment, are a recommendation. However are not followed strickly at the moment. We are looking at implementing automatic linting in the near future.
### Vue 3
Please refer to the [Vue 3 Style Guides located on their documentation](https://vuejs.org/style-guide/)
Please note the following outliers
- Local variables within a function are usually done in snake_case to differentiate them from the object and prop variables
EXAMPLE CODE
<template>
...
</template>
<script>
export default {
name: "ExampleComponent",
props: {
propVariable: {
type: String,
default: "value",
}
...
},
data() {
return {
dataVariable: "value",
...
}
},
methods: {
myMethod(input_variable) {
// Notice the "input_variable" is in snake case.
...
},
},
}
</script>
### Python
Please refer to the [PEP 8 – Style Guide for Python Code](https://peps.python.org/pep-0008/)
## Donating
Like most projects, there are some overhead costs. Every single dollar that we get will go towards;
- Software costs
- Administration costs
- Freelance costs (i.e. hiring help like designers)
We are being transparent with all our costs and will try and provide a yearly cost breakdown every 6 months.
## Bug Reporting
Bug reporting is a very important role for NearBeach. During Hacktoberfest, you are more than welcome to submit issues.
## Pull Requests
Please fork NearBeach, git your changes in and then submit a simple pull request.
When submitting a pull request, please fill out the template appropriately. We have flagged NearBeach's repository with Hacktoberfest, so any accepted pull requests WILL count towards Hacktoberfest.
Not all pull requests will be accepted.
## Documentation
Our documentation is hosted on [readthedocs](https://nearbeach.readthedocs.io). If you would like to contribute to the documentation, you will be able to find the files within `/docs`

21
NearBeach/LICENSE Executable file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

2
NearBeach/MANIFEST.in Normal file
View File

@@ -0,0 +1,2 @@
# Include all file
recursive-include NearBeach *

View File

@@ -0,0 +1,51 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeach.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Separation of art from artist clause
Any code, wiki, or other form of submitted work will not be judged based on but not limited to age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. The content submitted will be judged by the validity of said content and not the person or persons whom created the content.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -0,0 +1,8 @@
# Contributing to NearBeach
Welcome to NearBeach, we are an Open Source project management tool. We welcome all different types of contributes from but not limited to;
- Code patches
- Bug reports and patch reviews
- Documentation imparovements
- Feature requests/ideas/improvements
Please fork NearBeach, git your changes in and then submit a simple pull request. Not all pull requests will be accepted.

21
NearBeach/NearBeach/LICENSE Executable file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,32 @@
# Description
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
bug fixes # (bugs from https://bugzilla.nearbeach.org)
## Type of change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Database change that requires a migration
- [ ] This change requires a documentation update
# How Has This Been Tested?
Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
- [ ] Local testing via "./manage runserver"
- [ ] Tested on virtual box
- [ ] Tested on server
# Checklist:
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

162
NearBeach/NearBeach/README.md Executable file
View File

@@ -0,0 +1,162 @@
# NearBeach
NearBeach is in currently alpha development. If you find any issues, please do not hesitate to submit an issue. Alternatively you can submit through https://nearbeach.atlassian.net/servicedesk/customer/portal/1 (login not required)
## What is NearBeach?
NearBeach is a project and task management tool (PATMT) with a basic customer relationship management tool to help you manage your projects and task. The phillosophy of NearBeach is to be easy to install and use, be open sourced, be flexible, and aimed at small/personal organisation to large enterprises. Each new module brought to NearBeach expands it's capability tenfold and brings it closer to a competing product.
## Features
NearBeach's main focus is to create both projects and task. Each task can then be assigned to as many projects required (sometimes multiple projects will need to have the same task completed). Each project and task can also be assigned to multiple users to complete.
![NearBeach - Project Information](https://github.com/robotichead/Store_Github_Pictures/blob/master/NearBeach%20-%20project%20information.png?raw=true)
However projects and task are but a small feature to a PATMT system. You will need to store user requirement and be able to assign those requirement items to projects/task for completion. You will need to track these requirement to make sure they are completed. NearBeach has recently implemented a requirement module to help you store all your customer's requirement
![NearBeach - Requirements](https://github.com/robotichead/Store_Github_Pictures/blob/master/NearBeach%20-%20Requirements.png?raw=true)
What if you have an opportunity? You do not have the user's full requirement yet, but there could easily be a sale involved. NearBeach has also implemented the opportunity module, to help you store each potential opportunity that comes through the pipeline.
![NearBeach - Opportunity](https://github.com/robotichead/Store_Github_Pictures/blob/master/NearBeach%20-%20Opportunity?raw=true)
Finally, you might need to send a quote to your customer. As a new feature, the Quotes module has been implemented into NearBeach.
![NearBeach - Quotes](https://github.com/robotichead/Store_Github_Pictures/blob/master/NearBeach%20-%20Quote3.png?raw=true)
![NearBeach - Quotes](https://github.com/robotichead/Store_Github_Pictures/blob/master/NearBeach%20-%20Quote1.png?raw=true)
These are not the only features in NearBeach, but some which you may start using strait away. Feel free to download and install and start using NearBeach right away.
## Software References (thank you)
NearBeach will not be where it currently is without the help of other open sourced projects. Below are the references to all the different tools that are utilised within NearBeach. NearBeach would like to thank these projects as they have help construct a better and more stable product. Please consider visiting and donating.
### jQuery
Creator(s): John Resig
Github: https://github.com/jquery/jquery
Link: jquery.com
License: MIT
Note: jQuery help shorten a lot of the javascript code within NearBeach. There are also a few widgets that rely on this technology (i.e. Chosen-js).
### jQuery File Upload
Creator(s): Sebastian Tschan
Github: https://github.com/blueimp/jQuery-File-Upload
Link: https://blueimp.github.io/jQuery-File-Upload/
License : MIT
Note: jQuery File Upload is used when there is a file to be uploaded through the AJAX method.
### jQuery Plugin Date and Time Picker
Creator(s): Valeriy Chupurnov
Github: https://github.com/xdan/datetimepicker
License: MIT
Note: This plugin is a widget used to help improve picking dates and time.
### TinyMCE
Creator(s): Tiny Technologies Inc.
Github: https://github.com/tinymce/tinymce
License: GNU Lesser General Public License v2.1
Note: TinyMCE is used for rich text within NearBeach
### Geolocation - Python
Creator(s): Sławomir Kabik
Github: https://github.com/slawek87/geolocation-python
License: BSD 3-Clause
Note: Geolocation-Python is used to contact both Google Maps and Mapbox's API.
### Weasy Print
Creator(s): Kozea
Website: https://weasyprint.org/
Github: https://github.com/Kozea/WeasyPrint
License: BSD 3-Clause
Note: Weasy print is used to render PDF's in NearBeach
### Undraw.io <- images
### D3.js (Data-Driven Documents)
Creator(s): Mike Bostock, Jason Davies, Jeffrey Heer, Vadim Ogievetsky
Website: https://d3js.org/
Github: https://github.com/d3/d3
License: BSD 3-Clause
Note: D3 is used for producing graphical representatives of data for NearBeach
### Gantt-Chart
Creator(s): Dimitry Kudryavtsev
Github: https://github.com/dk8996/Gantt-Chart
License: Apache-2.0
Note: Gantt-Chart will be used for NearBeach's timeline feature.
### Bootstrap
Creator(s): Mark Otto, Jacob Thornton
Github: https://github.com/twbs/bootstrap
License: MIT
Note: NearBeach's CSS is currently being migrated to Bootstrap. For easy development.
### Feather Icons
Creator(s): Carmelo Pullara, Cole Bemis, Oliver Dumoulin
Github: https://github.com/feathericons/feather
License: MIT
Note: Feather icons are icons being utilised by NearBeach
### Django-select2
Creator(s): AppleGrew
Github: https://github.com/applegrew/django-select2
License: MIT
Note: NearBeach uses Djanogo-select2 to improve it's User Experience dealing with select statements.
### Select2
Creator(s): Select2
Github: https://github.com/select2/select2
License: MIT
Note: Django-select2 is built a top this product

View File

@@ -0,0 +1,2 @@
name = "NearBeach"
__version__ = "local_development"

92
NearBeach/NearBeach/admin.py Executable file
View File

@@ -0,0 +1,92 @@
from django.contrib import admin
# Register your models here.
from .models import (
Bug,
BugClient,
ChangeTask,
ChangeTaskBlock,
Customer,
Document,
DocumentPermission,
ExtendsAuthToken,
Folder,
Group,
KanbanBoard,
KanbanCard,
KanbanColumn,
KanbanLevel,
ListOfBugClient,
ListOfProjectStatus,
ListOfRequirementItemStatus,
ListOfRequirementItemType,
ListOfRequirementStatus,
ListOfRequirementType,
ListOfTaskStatus,
ListOfTitle,
Notification,
ObjectAssignment,
ObjectNote,
ObjectTemplate,
Organisation,
PermissionSet,
Project,
PublicLink,
RequestForChange,
RequestForChangeGroupApproval,
Requirement,
RequirementItem,
ScheduledObject,
Sprint,
SprintAuditTable,
SprintObjectAssignment,
Tag,
TagAssignment,
Task,
UserGroup,
UserJob,
)
admin.site.register(Bug)
admin.site.register(BugClient)
admin.site.register(ChangeTask)
admin.site.register(ChangeTaskBlock)
admin.site.register(Customer)
admin.site.register(Document)
admin.site.register(DocumentPermission)
admin.site.register(ExtendsAuthToken)
admin.site.register(Folder)
admin.site.register(Group)
admin.site.register(KanbanBoard)
admin.site.register(KanbanCard)
admin.site.register(KanbanColumn)
admin.site.register(KanbanLevel)
admin.site.register(ListOfBugClient)
admin.site.register(ListOfProjectStatus)
admin.site.register(ListOfRequirementItemStatus)
admin.site.register(ListOfRequirementItemType)
admin.site.register(ListOfRequirementStatus)
admin.site.register(ListOfRequirementType)
admin.site.register(ListOfTaskStatus)
admin.site.register(ListOfTitle)
admin.site.register(Notification)
admin.site.register(ObjectAssignment)
admin.site.register(ObjectNote)
admin.site.register(ObjectTemplate)
admin.site.register(Organisation)
admin.site.register(PermissionSet)
admin.site.register(Project)
admin.site.register(PublicLink)
admin.site.register(ScheduledObject)
admin.site.register(Sprint)
admin.site.register(SprintAuditTable)
admin.site.register(SprintObjectAssignment)
admin.site.register(RequestForChange)
admin.site.register(RequestForChangeGroupApproval)
admin.site.register(Requirement)
admin.site.register(RequirementItem)
admin.site.register(Tag)
admin.site.register(TagAssignment)
admin.site.register(Task)
admin.site.register(UserGroup)
admin.site.register(UserJob)

7
NearBeach/NearBeach/apps.py Executable file
View File

@@ -0,0 +1,7 @@
from __future__ import unicode_literals
from django.apps import AppConfig
class NearBeachConfig(AppConfig):
name = "NearBeach"

View File

@@ -0,0 +1,14 @@
import django
import NearBeach
def django_version(request):
"""Get's the django verion and returns it - used in template rendering."""
return {
"django_version": django.get_version(),
}
def nearbeach_version(request):
"""Get's the NearBeach version and returns it - used in template rendering."""
return {"nearbeach_version": NearBeach.__version__}

View File

@@ -0,0 +1,60 @@
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from functools import wraps
OBJECT_ARRAY = [
"change_task",
"customer",
"kanban",
"kanban_board",
"kanban_card",
"requirement",
"requirement_item",
"request_for_change",
"organisation",
"project",
"sprint",
"task",
]
def check_destination():
"""
Does a quick check to make sure the destination variable is inside the OBJECT_ARRAY
If not - it will return a Permission Denied. i.e. object does not exist, do nothing.
"""
def decorator(func):
@wraps(func)
def inner(request, destination, *args, **kwargs):
# See if the destination is correct (permission denied if not).
if destination not in OBJECT_ARRAY:
raise PermissionDenied
# It passed - return the function
return func(request, destination, *args, **kwargs)
return inner
return decorator
def check_public_destination():
"""
Does a quick check to make sure the destination variable is inside the OBJECT_ARRAY
If not - it will return the user to the login page. Use this for any PUBLIC facing
links
"""
def decorator(func):
@wraps(func)
def inner(request, destination, *args, **kwargs):
# See if the destination is correct (permission denied if not).
if destination not in OBJECT_ARRAY:
return HttpResponseRedirect('/login')
# It passed - return the function
return func(request, destination, *args, **kwargs)
return inner
return decorator

View File

@@ -0,0 +1,49 @@
from django.core.exceptions import PermissionDenied
from django.db.models import Max
from functools import wraps
from NearBeach.models import PermissionSet, UserGroup
def check_user_admin_permissions(min_permission_level, permission_lookup=""):
"""
Function is only used in the administration views. It is designed to make sure that
the user either;
1. Is an admin or
2. Has some administration permissions attributes associated with them.
Permission Lookup is the field we are looking up in the PermissionSet table
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# If user is admin - full permission
if request.user.is_superuser:
return func(request, *args, **kwargs, user_level=4)
# At this point - if permission lookup is an empty string - escape
if permission_lookup == "":
raise PermissionDenied
# Look at the user's permission set table
permission_set_results = PermissionSet.objects.filter(
is_deleted=False,
permission_set_id__in=UserGroup.objects.filter(
is_deleted=False, username=request.user
).values("permission_set_id"),
)
user_level = permission_set_results.aggregate(Max(permission_lookup))[
f"{permission_lookup}__max"
]
if user_level >= min_permission_level:
# Everything is fine - move on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,37 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from .partials.generic_permissions import generic_permissions
def api_object_data_permissions(min_permission_level):
"""
Checks the user's generic permissions. It will gather both the
- destination
- location id
from the API Url.
From here it will determine which partial permission it should
be checking against. The result from the partial will determine
if the user is granted permission or denied.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
passes, user_level, extra_level = generic_permissions(
request,
kwargs["destination"],
kwargs
)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level or extra_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,48 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from .partials.generic_permissions import generic_permissions
def check_user_api_permissions(min_permission_level):
"""
Checks the user's generic permissions. It will gather both the
- destination
- location id
from the API Url.
From here it will determine which partial permission it should
be checking against. The result from the partial will determine
if the user is granted permission or denied.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Extract the url string, and split into a list
url_string = request.request.path
url_list = url_string.replace("/api/v0/", "").removesuffix("/").split("/")
destination = ""
if len(url_list) == 1:
destination = url_list[0]
elif len(url_list) >= 2:
destination = url_list[0]
kwargs["location_id"] = url_list[1]
passes, user_level, extra_level = generic_permissions(request, destination, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level or extra_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def check_object_data_api_permissions():
return None

View File

@@ -0,0 +1,78 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from rest_framework import status
from rest_framework.response import Response
from NearBeach.decorators.check_user_permissions.object_permissions import FUNCTION_DICT
from NearBeach.decorators.check_user_permissions.partials.generic_permissions import generic_permissions
from NearBeach.serializers.sprint_serializer import SprintSerializer
def check_api_sprint_permissions(min_permission_level):
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
_request = request.request if hasattr(request, "request") else request
serializer = SprintSerializer(data=_request.data, context={'request': _request})
if not serializer.is_valid():
return Response(
data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST,
)
# If user is admin - grant them all permissions
if _request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Flat pack values
destination = serializer.data.get("destination")
location_id = serializer.data.get("location_id")
# Fold the location id into the {destination}_id.
kwargs[F"{destination}_id"] = location_id
# User the FUNCTION_DICT to determine which partial permissions we need
# to reference
passes, user_level, _ = FUNCTION_DICT[destination](_request, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def check_api_sprint_link_permissions(min_permission_level):
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# TODO - fix this terrible code
passes, user_level, extra_level = generic_permissions(
request,
"sprint",
{"location_id": kwargs["sprint_id"]}
)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level or extra_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,45 @@
from django.core.exceptions import PermissionDenied
from django.db.models import Max
from functools import wraps
from NearBeach.models import UserGroup
def check_user_customer_permissions(min_permission_level):
"""
Function is only used when checking user permissions against customers.
Min Permission Level determines the user permission and if they can
progress
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Need to update request if we are using API
_request = request.request if hasattr(request, "request") else request
# if user is admin -grant them all permissions
if _request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=_request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(Max("permission_set__customer"))[
"permission_set__customer__max"
]
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,70 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from NearBeach.models import Sprint
from NearBeach.decorators.check_user_permissions.object_permissions import FUNCTION_DICT
def check_gantt_chart_permissions_with_destination(min_permission_level):
"""
Checks the user's permission for the gantt chart, using the destination as
the object lookup. We will need to make sure the destination is either
a project or requirement, otherwise they will get permission denied.
We will then utilise the correct permission partials to determine if the
user should have access.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Obtain destination from args
# due to weird issue - we check the args length
if len(args) == 0:
destination = kwargs["destination"]
location_id = kwargs["location_id"]
else:
destination = args[0]
location_id = args[1]
# TEMP FUNCTIONALITY -> At the moment, we are only focusing on sprint functionality
# In the near future, we'll open this up to OTHER objects
# For the initial proof of concept, we are only dealing with sprints
if not destination == "sprint":
raise PermissionDenied
destination, location_id = get_sprint_parent_destination(location_id)
# If user is admin - grant them all permissions
if request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Fold the location id into the {destination}_id. This will be used in the partials
kwargs[F"{destination}_id"] = location_id
# User the FUNCTION_DICT to determine which partial permissions we need
# to reference
passes, user_level, _ = FUNCTION_DICT[destination](request, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def get_sprint_parent_destination(location_id):
# Get the sprint information
sprint_results = Sprint.objects.get(sprint_id=location_id)
# If there is a project assigned to the sprint. The destination should be project
if sprint_results.project is not None:
return "project", sprint_results.project_id
else:
return "requirement", sprint_results.requirement_id

View File

@@ -0,0 +1,142 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from .partials.change_task_permissions import change_task_permissions
from .partials.customer_permissions import customer_permissions
from .partials.generic_permissions import generic_permissions
from .partials.kanban_board_permissions import kanban_board_permissions
from .partials.kanban_card_permissions import kanban_card_permissions
from .partials.kanban_column_permissions import kanban_column_permissions
from .partials.kanban_level_permissions import kanban_level_permissions
from .partials.request_for_change_permissions import request_for_change_permissions
from .partials.requirement_permissions import requirement_permissions
from .partials.requirement_item_permissions import requirement_item_permissions
from .partials.object_note_permissions import object_note_permissions
from .partials.organisation_permissions import organisation_permissions
from .partials.project_permissions import project_permissions
from .partials.tag_permissions import tag_permissions
from .partials.task_permissions import task_permissions
FUNCTION_DICT = {
"change_task": change_task_permissions,
"customer": customer_permissions,
"kanban": kanban_board_permissions,
"kanban_board": kanban_board_permissions,
"kanban_card": kanban_card_permissions,
"kanban_column": kanban_column_permissions,
"kanban_level": kanban_level_permissions,
"request_for_change": request_for_change_permissions,
"requirement": requirement_permissions,
"requirement_item": requirement_item_permissions,
"organisation": organisation_permissions,
"object_note": object_note_permissions,
"project": project_permissions,
"tag": tag_permissions,
"task": task_permissions,
}
def check_user_generic_permissions(min_permission_level, extra_permissions=""):
"""
Checks the user's generic permissions. It will gather both the
- destination
- location id
from the *args and **kwargs.
From here it will determine which partial permission it should
be checking against. The result from the partial will determine
if the user is granted permission or denied.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Depending on the request type, depends which user we use
user = request.user if hasattr(request, "user") else request.request.user
# If user is admin - grant them all permissions
if user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Obtain destination from args
# Due to weird issue - we check the args length
if len(args) == 0:
destination = kwargs['destination']
else:
destination = args[0]
# Place Extra Permissions into the kwargs
kwargs["extra_permissions"] = extra_permissions
# If sub object, use partials
if destination == "kanban_card":
# Setup kwargs to have kanban_card_id
kwargs["kanban_card_id"] = kwargs["location_id"]
passes, user_level, extra_level = kanban_card_permissions(request, kwargs)
elif destination == "requirement_item":
# Setup kwargs to have requirement item id
kwargs["requirement_item_id"] = kwargs["location_id"]
passes, user_level, extra_level = requirement_item_permissions(request, kwargs)
elif destination == "change_task":
# Setup kwargs to have change task id
kwargs["change_task_id"] = kwargs["location_id"]
passes, user_level, extra_level = change_task_permissions(request, kwargs)
elif destination == "organisation":
passes, user_level, extra_level = organisation_permissions(request, kwargs)
elif destination == "customer":
passes, user_level, extra_level = customer_permissions(request, kwargs)
else:
passes, user_level, extra_level = generic_permissions(request, destination, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level or extra_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def check_specific_object_permissions(min_permission_level, object_lookup):
"""
Checks the user's permissions against the provided object_lookup.
From here it will determine which partial permission it should
be checking against. The result from the partial will determine
if the user is granted permission or denied.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# If user is admin - grant them all permissions
if request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
if object_lookup == "":
raise PermissionDenied
# Add extra permissions to kwargs
# kwargs["extra_permissions"] = extra_permissions
# Use the FUNCTION_DICT to determine which partial permissions we need to
# reference
passes, user_level, extra_level = FUNCTION_DICT[object_lookup](request, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level or extra_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,88 @@
from django.core.exceptions import PermissionDenied
from django.db.models import Max
from functools import wraps
from NearBeach.models import UserGroup
def check_user_organisation_permissions(min_permission_level):
"""
Function is only used when checking user permissions against
organisations. Min Permission Level determines if the user
will have enough permission to proceed.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Need to update request if we are using API
_request = request.request if hasattr(request, "request") else request
# if user is admin -grant them all permissions
if _request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=_request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__organisation")
)["permission_set__organisation__max"]
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def check_user_organisation_note_permissions():
"""
Function is only used when checking user permissions against
organisations. Min Permission Level determines if the user
will have enough permission to proceed.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# if user is admin -grant them all permissions
if request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__organisation")
)["permission_set__organisation__max"]
extra_level = user_group_results.aggregate(
Max("permission_set__organisation_note"),
)["permission_set__organisation_note__max"]
if user_level >= 2 or extra_level > 0:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,56 @@
from NearBeach.models import ChangeTask, Group, ObjectAssignment, UserGroup
from django.db.models import Max, Q
def change_task_permissions(request, kwargs):
# Extra Permissions
extra_permissions = ""
if "extra_permissions" in kwargs:
extra_permissions = kwargs.get("extra_permissions")
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# If we are passing in any args like change_task_id, we want to do the following
if len(kwargs) > 0:
# Get the rfc id
rfc_id = ChangeTask.objects.get(
change_task_id=kwargs["change_task_id"]
).request_for_change_id
# Determine if there are any cross over change tasks
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
# **{object_lookup: kwargs[object_lookup]},
request_for_change_id=rfc_id,
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__request_for_change")
)["permission_set__request_for_change__max"]
# Check all variations of the extra permissions
extra_level = False
if extra_permissions == "document":
extra_level = user_group_results.filter(
permission_set__document=1,
).count() > 0
# Return
return True, user_level, extra_level

View File

@@ -0,0 +1,17 @@
from django.db.models import Max
from NearBeach.models import UserGroup
def customer_permissions(request, *args, **kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__customer")
)["permission_set__customer__max"]
return True, user_level, False

View File

@@ -0,0 +1,100 @@
from django.db.models import Max, Q
from django.http import HttpResponseBadRequest
from NearBeach.models import (
ChangeTask,
Group,
KanbanBoard,
ObjectAssignment,
Requirement,
Sprint,
UserGroup,
)
from NearBeach.utils.api.is_child_object import is_child_object
def generic_permissions(request, object_lookup, kwargs):
user = request.user if hasattr(request, "user") else request.request.user
# Extra Permissions
extra_permissions = ""
if "extra_permissions" in kwargs:
extra_permissions = kwargs.get("extra_permissions")
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=user,
)
# If we are passing the object_lookup through, we will use a different function
if "location_id" in kwargs and not object_lookup == "organisation":
# If object is a child object, we want to look at the parent object's permission
location_id, object_lookup = _fetch_parent_details(kwargs, object_lookup)
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
**{object_lookup: location_id},
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max(f"permission_set__{object_lookup.replace('_id', '')}")
)[f"permission_set__{object_lookup.replace('_id', '')}__max"]
extra_level = False
if extra_permissions == "document":
extra_level = user_group_results.filter(
permission_set__document=1,
).count() > 0
if extra_permissions == "note":
extra_level = user_group_results.filter(
**{F"permission_set__{object_lookup}_note": 1}
).count() > 0
return True, user_level, extra_level
def _fetch_parent_details(kwargs, object_lookup):
# Set the default location id
location_id = kwargs["location_id"]
# If the object is NOT a child object - we'll pass back the results
if not is_child_object(object_lookup):
return location_id, object_lookup
match object_lookup:
case "change_task":
object_lookup = "request_for_change"
object_results = ChangeTask.objects.get(pk=location_id)
location_id = object_results.request_for_change_id
case "kanban_card":
object_lookup = "kanban_board"
object_results = KanbanBoard.objects.get(pk=location_id)
location_id = object_results.kanban_board_id
case "requirement_item":
object_lookup = "requirement"
object_results = Requirement.objects.get(pk=location_id)
location_id = object_results.requirement_id
case "sprint":
object_results = Sprint.objects.get(pk=location_id)
object_lookup = "requirement" if object_results.project is None else "project"
location_id = object_results.requirement_id if object_results.project is None else object_results.project_id
case _:
raise HttpResponseBadRequest("Invalid child object")
return location_id, object_lookup

View File

@@ -0,0 +1,38 @@
from NearBeach.models import Group, ObjectAssignment, UserGroup
from django.db.models import Max, Q
# Internal Function
def kanban_board_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if "kanban_board_id" in kwargs:
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
kanban_board_id=kwargs["kanban_board_id"]
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__kanban_board")
)["permission_set__kanban_board__max"]
return True, user_level, False

View File

@@ -0,0 +1,57 @@
from NearBeach.models import Group, KanbanCard, ObjectAssignment, UserGroup
from django.db.models import Max, Q
# Internal Function
def kanban_card_permissions(request, kwargs):
# Extra Permissions
extra_permissions = ""
if "extra_permissions" in kwargs:
extra_permissions = kwargs.get("extra_permissions")
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
kanban_board_id__in=KanbanCard.objects.filter(
kanban_card_id=kwargs["kanban_card_id"],
).values("kanban_board_id"),
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__kanban_board")
)["permission_set__kanban_board__max"]
# Check all variations of the extra permissions
extra_level = False
if extra_permissions == "document":
extra_level = user_group_results.filter(
permission_set__document=1,
).count() > 0
if extra_permissions == "note":
extra_level = user_group_results.filter(
permission_set__kanban_note=1,
).count() > 0
return True, user_level, extra_level

View File

@@ -0,0 +1,40 @@
from NearBeach.models import Group, KanbanColumn, ObjectAssignment, UserGroup
from django.db.models import Max, Q
# Internal Function
def kanban_column_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
kanban_board_id__in=KanbanColumn.objects.filter(
kanban_column_id=kwargs["kanban_column_id"],
).values("kanban_board_id"),
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__kanban_board")
)["permission_set__kanban_board__max"]
return True, user_level, False

View File

@@ -0,0 +1,40 @@
from NearBeach.models import Group, KanbanLevel, ObjectAssignment, UserGroup
from django.db.models import Max, Q
# Internal Function
def kanban_level_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
kanban_board_id__in=KanbanLevel.objects.filter(
kanban_level_id=kwargs["kanban_level_id"],
).values("kanban_board_id"),
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
# There are no matching groups - i.e. the user does not have any permission
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__kanban_board")
)["permission_set__kanban_board__max"]
return True, user_level, False

View File

@@ -0,0 +1,21 @@
from NearBeach.models import ObjectNote
def object_note_permissions(request, kwargs):
"""
Checks the user's permission to determine if they have permission to delete this note.
Currently only;
- Note owner
Can delete the note
"""
if len(kwargs) > 0:
# Get the requirement groups
object_results = ObjectNote.objects.filter(
object_note_id=kwargs["object_note_id"],
change_user=request.user,
).count()
return True, object_results, False
return False, 0, False

View File

@@ -0,0 +1,32 @@
from django.db.models import Max
from NearBeach.models import UserGroup
def organisation_permissions(request, kwargs):
# Extra Permissions
extra_permissions = kwargs.get("extra_permissions", "")
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__organisation")
)["permission_set__organisation__max"]
# Check all variations of the extra permissions
extra_level = False
if extra_permissions == "document":
extra_level = user_group_results.filter(
permission_set__document=1,
).count() > 0
if extra_permissions == "organisation_note":
extra_level = user_group_results.filter(
permission_set__organisation_note=1,
).count() > 0
return True, user_level, extra_level

View File

@@ -0,0 +1,38 @@
from NearBeach.models import ObjectAssignment, UserGroup
from django.db.models import Max, Q
def project_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Get the requirement groups
user_group_results = UserGroup.objects.filter(
Q(
is_deleted=False,
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
group_id__isnull=False,
project_id=kwargs["project_id"],
).values("group_id"),
)
& Q(
username=request.user,
)
)
# Check to see if there are any groups associated
if len(user_group_results) == 0:
# No groups - meaning no permissions
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__project")
)["permission_set__project__max"]
return True, user_level, False

View File

@@ -0,0 +1,38 @@
from NearBeach.models import Group, ObjectAssignment, UserGroup
from django.db.models import Max, Q
# Internal Function
def request_for_change_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# If we are passing the object_lookup through, we will use a different function
if len(kwargs) > 0:
# Determine if there are any cross over with user groups and object_lookup groups
group_results = Group.objects.filter(
Q(
is_deleted=False,
# The object_lookup groups
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
# **{object_lookup: kwargs[object_lookup]},
request_for_change_id=kwargs["rfc_id"],
).values("group_id"),
)
& Q(group_id__in=user_group_results.values("group_id"))
)
# Check to make sure the user groups intersect
if len(group_results) == 0:
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__request_for_change")
)["permission_set__request_for_change__max"]
return True, user_level, False

View File

@@ -0,0 +1,65 @@
from NearBeach.models import ObjectAssignment, Requirement, RequirementItem, UserGroup
from django.db.models import Max, Q
def requirement_item_permissions(request, kwargs):
# Extra Permissions
extra_permissions = ""
if "extra_permissions" in kwargs:
extra_permissions = kwargs.get("extra_permissions")
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Get the requirement_item instance
requirement_item_results = RequirementItem.objects.get(
**{"requirement_item_id": kwargs["requirement_item_id"]},
)
# Get the requirement instance
requirement_results = Requirement.objects.get(
requirement_id=requirement_item_results.requirement_id,
)
# Get the requirement groups
user_group_results = UserGroup.objects.filter(
Q(
is_deleted=False,
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
group_id__isnull=False,
requirement_id=requirement_results.requirement_id,
).values("group_id"),
)
& Q(
username=request.user,
)
)
# Check to see if there are any groups associated
if len(user_group_results) == 0:
# No groups - meaning no permissions
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__requirement")
)["permission_set__requirement__max"]
# Check all variation of the extra permissions
extra_level = False
if extra_permissions == "document":
extra_level = user_group_results.filter(
permission_set__document=1,
).count() > 0
if extra_permissions == "note":
extra_level = user_group_results.filter(
permission_set__requirement_item_note=1
).count() > 0
return True, user_level, extra_level

View File

@@ -0,0 +1,33 @@
from NearBeach.models import ObjectAssignment, UserGroup
from django.db.models import Max
def requirement_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
if len(kwargs) > 0:
# Get the requirement groups
user_group_results = user_group_results.filter(
is_deleted=False,
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
group_id__isnull=False,
requirement_id=kwargs["requirement_id"],
).values("group_id"),
)
# Check to see if there are any groups associated
if len(user_group_results) == 0:
# No groups - meaning no permissions
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__requirement")
)["permission_set__requirement__max"]
return True, user_level, False

View File

@@ -0,0 +1,17 @@
from django.db.models import Max
from NearBeach.models import UserGroup
def tag_permissions(request, *args, **kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__tag")
)["permission_set__tag__max"]
return True, user_level, False

View File

@@ -0,0 +1,39 @@
from NearBeach.models import ObjectAssignment, UserGroup
from django.db.models import Max, Q
def task_permissions(request, kwargs):
# Default user level is 0
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Check to see if we are passing the task id.
if len(kwargs) > 0:
# Get the requirement groups
user_group_results = user_group_results.filter(
Q(
is_deleted=False,
group_id__in=ObjectAssignment.objects.filter(
is_deleted=False,
group_id__isnull=False,
task_id=kwargs["task_id"],
).values("group_id"),
)
& Q(
username=request.user,
)
)
# Check to see if there are any groups associated
if len(user_group_results) == 0:
# No groups - meaning no permissions
return False, 0, False
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__task")
)["permission_set__task__max"]
return True, user_level, False

View File

@@ -0,0 +1,17 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
def check_permission_denied():
"""Just a test function - don't worry about it"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,50 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from django.db.models import Max
from NearBeach.models import UserGroup, ObjectTemplateGroup, ScheduledObject
def check_schedule_object_permissions(min_permission_level):
"""
Checks the user's permissions for the schedule object functionality in NearBeach.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# If user is admin - grant them all permissions
if request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Get permission sets
user_group_results = UserGroup.objects.filter(
is_deleted=False,
username=request.user,
)
# Get the scheduled object id if it exists
scheduled_object_id = kwargs.get('schedule_object_id')
if scheduled_object_id is not None:
user_group_results = user_group_results.filter(
group_id__in=ObjectTemplateGroup.objects.filter(
is_deleted=False,
object_template_id__in=ScheduledObject.objects.filter(
is_deleted=False,
schedule_object_id=scheduled_object_id,
).values("object_template_id")
).values("group_id")
)
if len(user_group_results) > 0:
# Get the max permission value from user_group_results
user_level = user_group_results.aggregate(
Max("permission_set__schedule_object")
)["permission_set__schedule_object__max"]
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,108 @@
from django.core.exceptions import PermissionDenied
from functools import wraps
from NearBeach.models import Sprint
from NearBeach.decorators.check_user_permissions.object_permissions import FUNCTION_DICT
def check_sprint_permissions_with_destination(min_permission_level):
"""
Checks the user's permission for the sprint, using the destination as
the object lookup. We will need to make sure the destination is either
a project or requirement, otherwise they will get permission denied.
We will then utilise the correct permission partials to determine if the
user should have access.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Obtain destination from args
# due to weird issue - we check the args length
if len(args) == 0:
destination = kwargs["destination"]
else:
destination = args[0]
# If destination is not project or requirement, send permission denied
if destination not in ["project", "requirement"]:
raise PermissionDenied
# If user is admin - grant them all permissions
if request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Fold the location id into the {destination}_id. This will be used in the partials
kwargs[F"{destination}_id"] = kwargs["location_id"]
# User the FUNCTION_DICT to determine which partial permissions we need
# to reference
passes, user_level, _ = FUNCTION_DICT[destination](request, kwargs)
if not passes:
raise PermissionDenied
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator
def check_sprint_permission_with_sprint(min_permission_level):
"""
Checks the user's permission for the sprint, using the sprint id as
the object lookup. We will need to make sure the destination is either
a project or requirement, otherwise they will get permission denied.
We will then utilise the correct permission partials to determine if the
user should have access.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
_request = request.request if hasattr(request, "request") else request
# If user is admin - grant them all permissions
if _request.user.is_superuser:
# Return the function with a user_level of 4
return func(request, *args, **kwargs, user_level=4)
# Get the sprint from the id
if "sprint_id" in kwargs:
sprint_id = kwargs["sprint_id"]
elif "location_id" in kwargs:
sprint_id = kwargs["location_id"]
elif "pk" in kwargs:
sprint_id = kwargs["pk"]
else:
sprint_id = args[0]
sprint_results = Sprint.objects.get(sprint_id=sprint_id)
if sprint_results.project is not None:
# We can assume this is a project
kwargs["project_id"] = sprint_results.project_id
passes, user_level, _ = FUNCTION_DICT["project"](_request, kwargs)
else:
kwargs["requirement_id"] = sprint_results.requirement_id
passes, user_level, _ = FUNCTION_DICT["requirement"](_request, kwargs)
# Check to see if it passes
if not passes:
raise PermissionDenied
if user_level >= min_permission_level:
# Everything is fine - continue on
return func(request, *args, **kwargs, user_level=user_level)
# Does not meet conditions
raise PermissionDenied
return inner
return decorator

View File

@@ -0,0 +1,85 @@
from collections import defaultdict, namedtuple
from itertools import zip_longest
ValueTypes = namedtuple("ValueTypes", ("expected", "got"))
class Registry(defaultdict):
"""A registy of event types and the hooks to call when they are emitted"""
def __init__(self, init=None, /, *args, **kwargs):
super().__init__(init, *args, **kwargs)
self._types = {}
def register_func(self, event_type):
"""register function against event type"""
def wrapper(func):
self[event_type].append(func)
return func
return wrapper
def register_event_type(self, event_type, *value_type):
# Use dict keys to register event types
if event_type in self:
if self._types[event_type] != value_type:
raise ValueError(f"event with same name '{event_type}' but different types {self._types[event_type]} != {value_type}")
else:
self._types[event_type] = value_type
def _check_value_types(self, event_type, values):
types = []
incorrect_found=False
for v, t in zip_longest(values, self._types[event_type]):
types.append(ValueTypes(expected=t, got=v))
if v is None and t is None:
continue
if (
(v is None and t is not None) or
(v is not None and t is None) or
not isinstance(v, t)
):
incorrect_found = True
if incorrect_found:
value_types = [
f"(expected={v.expected}, got={v.got}({type(v.got)}))"
for v in types
]
# TODO: log error
print(f"ERROR: Emit for event {event_type} submitted with an incorrect type submitted values [{', '.join(value_types)}]")
return False
return True
def emit(self, event_type, *values):
"""call registered functions for a given event type"""
if not self._check_value_types(event_type, values):
return
for func in self.get(event_type, []):
func(*values)
_registry = Registry(list)
# Hide registry via proxy functions
def register_event_type(event_type, value_type):
return _registry.register_event_type(event_type, value_type)
def emit(event_type, value):
return _registry.emit(event_type, value)
def register_func(event_type):
return _registry.register_func(event_type)
EventType = namedtuple("EventType", ("name", "types"))
def list_event_types():
return [
EventType(name=event_name, types=_registry._types[event_name])
for event_name in _registry.keys()
]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,539 @@
[
{
"model": "auth.user",
"fields": {
"password": "pbkdf2_sha256$720000$Cnbbpucg819VzTTCmgWSY5$gI2WfPS8PJDC0agAb2tdzV1JB1qRLCis/4j9nQtJSUw=",
"last_login": null,
"is_superuser": true,
"username": "admin",
"first_name": "",
"last_name": "",
"email": "support@nearbeach.org",
"is_staff": true,
"is_active": true,
"date_joined": "2023-12-28T03:13:59.086Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "NearBeach.listoftitle",
"pk": 1,
"fields": {
"title": "Mr",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftitle",
"pk": 2,
"fields": {
"title": "Ms",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftitle",
"pk": 3,
"fields": {
"title": "Mrs",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftitle",
"pk": 4,
"fields": {
"title": "Mx",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 1,
"fields": {
"task_status": "New",
"task_higher_order_status": "Backlog",
"task_status_sort_order": 1,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 2,
"fields": {
"task_status": "Backlog",
"task_higher_order_status": "Backlog",
"task_status_sort_order": 2,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 3,
"fields": {
"task_status": "Blocked",
"task_higher_order_status": "Blocked",
"task_status_sort_order": 3,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 4,
"fields": {
"task_status": "In Progress",
"task_higher_order_status": "Normal",
"task_status_sort_order": 4,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 5,
"fields": {
"task_status": "Test/Review",
"task_higher_order_status": "Normal",
"task_status_sort_order": 5,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listoftaskstatus",
"pk": 6,
"fields": {
"task_status": "Closed",
"task_higher_order_status": "Closed",
"task_status_sort_order": 6,
"date_created": "2023-12-28T03:12:34.024Z",
"date_modified": "2023-12-28T03:12:34.024Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementtype",
"pk": 1,
"fields": {
"requirement_type": "Non Specific",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementtype",
"pk": 2,
"fields": {
"requirement_type": "Customer Requirements",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementtype",
"pk": 3,
"fields": {
"requirement_type": "System Requirements",
"date_created": "2023-12-28T03:12:33.369Z",
"date_modified": "2023-12-28T03:12:33.369Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementstatus",
"pk": 1,
"fields": {
"requirement_status": "Backlog",
"requirement_higher_order_status": "Backlog",
"requirement_status_sort_order": 1,
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementstatus",
"pk": 2,
"fields": {
"requirement_status": "Blocked",
"requirement_higher_order_status": "Blocked",
"requirement_status_sort_order": 2,
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementstatus",
"pk": 3,
"fields": {
"requirement_status": "In Progress",
"requirement_higher_order_status": "Normal",
"requirement_status_sort_order": 3,
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementstatus",
"pk": 4,
"fields": {
"requirement_status": "Testing/Review",
"requirement_higher_order_status": "Normal",
"requirement_status_sort_order": 4,
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementstatus",
"pk": 5,
"fields": {
"requirement_status": "Closed",
"requirement_higher_order_status": "Closed",
"requirement_status_sort_order": 5,
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 1,
"fields": {
"requirement_item_type": "Informational",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 2,
"fields": {
"requirement_item_type": "Feature",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 3,
"fields": {
"requirement_item_type": "User Case",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 4,
"fields": {
"requirement_item_type": "User Interface",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 5,
"fields": {
"requirement_item_type": "Non Functional",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 6,
"fields": {
"requirement_item_type": "Constraint",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemtype",
"pk": 7,
"fields": {
"requirement_item_type": "System Function",
"date_created": "2023-12-28T03:12:33.368Z",
"date_modified": "2023-12-28T03:12:33.368Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 1,
"fields": {
"requirement_item_status": "Draft",
"requirement_item_higher_order_status": "Backlog",
"requirement_item_status_sort_order": 1,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 2,
"fields": {
"requirement_item_status": "Review",
"requirement_item_higher_order_status": "Backlog",
"requirement_item_status_sort_order": 2,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 3,
"fields": {
"requirement_item_status": "Developing/Working",
"requirement_item_higher_order_status": "Normal",
"requirement_item_status_sort_order": 3,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 4,
"fields": {
"requirement_item_status": "Testing",
"requirement_item_higher_order_status": "Normal",
"requirement_item_status_sort_order": 4,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 5,
"fields": {
"requirement_item_status": "User Acceptance Testing",
"requirement_item_higher_order_status": "Normal",
"requirement_item_status_sort_order": 5,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 6,
"fields": {
"requirement_item_status": "Rework",
"requirement_item_higher_order_status": "Normal",
"requirement_item_status_sort_order": 6,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 7,
"fields": {
"requirement_item_status": "Implemented",
"requirement_item_higher_order_status": "Closed",
"requirement_item_status_sort_order": 7,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 8,
"fields": {
"requirement_item_status": "Finish",
"requirement_item_higher_order_status": "Closed",
"requirement_item_status_sort_order": 8,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 9,
"fields": {
"requirement_item_status": "Not Tested",
"requirement_item_higher_order_status": "Normal",
"requirement_item_status_sort_order": 9,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofrequirementitemstatus",
"pk": 10,
"fields": {
"requirement_item_status": "Obsolete",
"requirement_item_higher_order_status": "Closed",
"requirement_item_status_sort_order": 10,
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 1,
"fields": {
"project_status": "New",
"project_higher_order_status": "Backlog",
"project_status_sort_order": 1,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 2,
"fields": {
"project_status": "Backlog",
"project_higher_order_status": "Backlog",
"project_status_sort_order": 2,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 3,
"fields": {
"project_status": "Blocked",
"project_higher_order_status": "Blocked",
"project_status_sort_order": 3,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 4,
"fields": {
"project_status": "In Progress",
"project_higher_order_status": "Normal",
"project_status_sort_order": 4,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 5,
"fields": {
"project_status": "Test/Review",
"project_higher_order_status": "Normal",
"project_status_sort_order": 5,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofprojectstatus",
"pk": 6,
"fields": {
"project_status": "Closed",
"project_higher_order_status": "Closed",
"project_status_sort_order": 6,
"date_created": "2023-12-28T03:12:34.023Z",
"date_modified": "2023-12-28T03:12:34.023Z",
"change_user": null,
"is_deleted": false
}
},
{
"model": "NearBeach.listofbugclient",
"pk": 1,
"fields": {
"bug_client_name": "Bugzilla",
"bug_client_api_url": "/rest/",
"api_open_bugs": "?open_status=True",
"api_search_bugs": "bug?quicksearch=",
"api_bug": "/show_bug.cgi?id=",
"date_created": "2023-12-28T03:12:33.367Z",
"date_modified": "2023-12-28T03:12:33.367Z",
"change_user": null,
"is_deleted": false
}
}
]

1618
NearBeach/NearBeach/forms.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,175 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from NearBeach.views.document_views import FILE_HANDLER
from django.conf import settings
from NearBeach.models import (
Document,
DocumentPermission,
)
import datetime
from django.utils import timezone
User = get_user_model()
class Command(BaseCommand):
help = "Run this command to remove any deleted documents/files that have been in the system for x amount of months."
def handle(self, *args, **kwargs):
"""
Removes all the deleted documents from the blob storage, with some exceptions.
Method
1. Find all deleted documents that have not already been purged
2. Loop through all the documents, and make sure the document is still not located within the object description
3. Remove document from blob, if it meets the above requirements
4. Bulk update - tell system we have PURGED the files
"""
documentation_clean_up = getattr(settings, "DOCUMENTATION_CLEAN_UP", False)
if not documentation_clean_up:
print("Documentation Clean Up in the Settings file is set to FALSE. Will not proceed")
return
# Clean up happens in two parts
self.clean_up_generic_object_documents(self, "kanban_card", "kanban_card_description")
self.clean_up_generic_object_documents(self, "project", "project_description")
self.clean_up_generic_object_documents(self, "requirement", "requirement_scope")
self.clean_up_generic_object_documents(self, "requirement_item", "requirement_item_scope")
self.clean_up_generic_object_documents(self, "task", "task_long_description")
self.clean_up_organisation_documents(self)
self.clean_up_rfc_documents(self)
@staticmethod
def get_today():
return timezone.now().today()
@staticmethod
def purge_document_from_blob(_, document_key_id):
FILE_HANDLER.delete(document_key_id=document_key_id)
@staticmethod
def clean_up_generic_object_documents(origin, field, description_field):
clean_after_days = getattr(settings, "DOCUMENTATION_CLEAN_AFTER_DAYS", 90)
todays_date = origin.get_today()
expired_date = todays_date - datetime.timedelta(days=clean_after_days)
documents_to_be_purged = DocumentPermission.objects.filter(
is_deleted=True,
is_purged=False,
date_modified__gte=expired_date,
**{F"{field}__isnull": False},
)
# Loop through all the records - and make sure the document is not in the description
purged_document_keys = []
for single_document in documents_to_be_purged:
document_key_id = str(single_document.document_key_id)
single_object = getattr(single_document, field)
description = getattr(single_object, description_field)
if document_key_id not in description:
# Process deleting the file
origin.purge_document_from_blob(document_key_id)
purged_document_keys.append(document_key_id)
# Bulk update to purged documents
Document.objects.filter(
document_key__in=purged_document_keys,
).update(
is_purged=True,
date_modified=todays_date,
)
DocumentPermission.objects.filter(
document_key__in=purged_document_keys,
).update(
is_purged=True,
date_modified=todays_date,
)
@staticmethod
def clean_up_organisation_documents(origin):
clean_after_days = getattr(settings, "DOCUMENTATION_CLEAN_AFTER_DAYS", 90)
todays_date = origin.get_today()
expired_date = todays_date - datetime.timedelta(days=clean_after_days)
documents_to_be_purged = DocumentPermission.objects.filter(
is_deleted=True,
is_purged=False,
date_modified__gte=expired_date,
organisation__isnull=False,
)
# Loop through all the records - and make sure the document is not in the description
for single_document in documents_to_be_purged:
document_key_id = str(single_document.document_key_id)
origin.purge_document_from_blob(document_key_id)
# Bulk update to purged documents
Document.objects.filter(
document_key__in=documents_to_be_purged.values("document_key"),
).update(
is_purged=True,
date_modified=todays_date,
)
DocumentPermission.objects.filter(
document_key__in=documents_to_be_purged.values("document_key"),
).update(
is_purged=True,
date_modified=todays_date,
)
@staticmethod
def clean_up_rfc_documents(self):
clean_after_days = getattr(settings, "DOCUMENTATION_CLEAN_AFTER_DAYS", 90)
todays_date = self.get_today()
expired_date = todays_date - datetime.timedelta(days=clean_after_days)
documents_to_be_purged = DocumentPermission.objects.filter(
is_deleted=True,
is_purged=False,
date_modified__gte=expired_date,
request_for_change__isnull=False,
)
# Loop through all the records - and make sure the document is not in the description
purged_document_keys = []
for single_document in documents_to_be_purged:
document_key_id = str(single_document.document_key_id)
single_object = single_document.request_for_change
rfc_summary = single_object.rfc_summary
rfc_risk_and_impact_analysis = single_object.rfc_risk_and_impact_analysis
rfc_implementation_plan = single_object.rfc_implementation_plan
rfc_backout_plan = single_object.rfc_backout_plan
rfc_test_plan = single_object.rfc_test_plan
if (document_key_id not in rfc_summary &
document_key_id not in rfc_risk_and_impact_analysis &
document_key_id not in rfc_implementation_plan &
document_key_id not in rfc_backout_plan &
document_key_id not in rfc_test_plan
):
# Process deleting the file
self.purge_document_from_blob(document_key_id)
purged_document_keys.append(document_key_id)
# Bulk update to purged documents
Document.objects.filter(
document_key__in=purged_document_keys,
).update(
is_purged=True,
date_modified=todays_date,
)
DocumentPermission.objects.filter(
document_key__in=purged_document_keys,
).update(
is_purged=True,
date_modified=todays_date,
)

View File

@@ -0,0 +1,14 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from NearBeach.utils.admin import initalize_base_values
User = get_user_model()
class Command(BaseCommand):
help = "Run this command will setup the base values"
def handle(self, *args, **kwargs):
admin_user = User.objects.get(is_admin=True).first()
initalize_base_values(admin_user)

View File

@@ -0,0 +1,45 @@
from django.core.management.base import BaseCommand
from NearBeach import event_hooks
# Import runschedular so that we get its events
from . import runscheduler as _
class Command(BaseCommand):
help = "Lists registered event which can be hooked onto"
def add_arguments(self, parser):
parser.add_argument("--prefix", action='append', type=str)
@staticmethod
def _has_prefix(event_name, prefixes):
return any(
event_name.startswith(p)
for p in prefixes
)
def handle(self, *args, **options):
print("options:", options)
prefixes = options.get("prefix")
prefix_msg_modifier=""
if prefixes is None:
prefixes = [""]
else:
prefix_msg_modifier = f"have the following prefixes [{', '.join(prefixes)}] " # Note needs trailing space
found = []
for e in sorted(event_hooks.list_event_types(), key=lambda e: e.name):
if self._has_prefix(e.name, prefixes):
found.append(f"- {e.name} ({", ".join(str(x) for x in e.types)})")
if len(found) == 0:
if prefix_msg_modifier == "":
print("No events found")
else:
print(f"No events that {prefix_msg_modifier}found")
else:
print(f"These are the events currently registered for event which {prefix_msg_modifier}can be hooked onto:")
print("key: event_name (arg types)")
for line in found:
print(line)

View File

@@ -0,0 +1,449 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db.models import Q, F, Max
from NearBeach import event_hooks
from django.utils import timezone
from NearBeach.models import (
ObjectAssignment,
ObjectTemplate,
Project,
SCH_SET_DAY_OF_THE_WEEK,
SCH_WEEKLY,
SCH_FORTNIGHTLY,
SCH_MONTHLY,
SCH_START_OF_THE_MONTH,
SCH_END_OF_THE_MONTH,
SCH_X_DAYS_BEFORE_END_OF_THE_MONTH,
ScheduledObject,
Task, Organisation, ListOfTaskStatus, ListOfProjectStatus, ObjectTemplateGroup, KanbanCard,
)
User = get_user_model()
import datetime
import calendar
OBJECT_DICT = {
"task": {
"object": Task,
"object_title": "task_short_description",
"object_description": "task_long_description",
"object_organisation": "organisation",
"object_start_date": "task_start_date",
"object_end_date": "task_end_date",
"object_status": "task_status",
"status": ListOfTaskStatus,
},
"project": {
"object": Project,
"object_title": "project_name",
"object_description": "project_description",
"object_organisation": "organisation",
"object_start_date": "project_start_date",
"object_end_date": "project_end_date",
"object_status": "project_status",
"status": ListOfProjectStatus,
}
}
event_hooks.register_event_type("task.create.scheduled_object", Task)
event_hooks.register_event_type("project.create.scheduled_object", Project)
class Command(BaseCommand):
help = "Run this command to run the scheduled jobs within NearBeach. Setup a daily cron job"
def handle(self, *args, **kwargs):
scheduled_objects = ScheduledObject.objects.none()
# Run each part
scheduled_objects = scheduled_objects.union(self.run_set_day_of_the_week())
scheduled_objects = scheduled_objects.union(self.run_weekly())
scheduled_objects = scheduled_objects.union(self.run_fortnightly())
scheduled_objects = scheduled_objects.union(self.run_monthly())
scheduled_objects = scheduled_objects.union(self.run_start_of_the_month())
scheduled_objects = scheduled_objects.union(self.run_end_of_the_month())
scheduled_objects = scheduled_objects.union(self.run_x_days_before_end_of_the_month())
# Loop through all objects and create them
for single_object in scheduled_objects:
self.create_object(single_object)
@staticmethod
def get_today():
return timezone.now().today()
def create_object(self, scheduled_object, *args, **kwargs):
#TODO: Print off a log when creating these tasks/projects
# Get the template
template = ObjectTemplate.objects.get(object_template_id=scheduled_object.object_template_id)
# Get the correct dictionary
object_string = template.object_template_json["object_type"]
# Use "create_kanban_card_object" for any kanban cards
if object_string == "kanban_card":
self.create_kanban_card_object(scheduled_object, template, *args, **kwargs)
else:
self.create_base_object(scheduled_object, object_string, template, *args, **kwargs)
# Update the database for the last run
scheduled_object.last_run = datetime.date.today()
# If scheduled object has number of repeats, we increase the run count
if scheduled_object.number_of_repeats >= 0:
scheduled_object.run_count = scheduled_object.run_count + 1
scheduled_object.save()
@staticmethod
def create_base_object(scheduled_object, object_string, template, *args, **kwargs):
# Set object dict
object_dict = OBJECT_DICT[object_string]
# Get the start and end date from the template
template_start_date = datetime.datetime.strptime(
template.object_template_json["object_start_date"],
"%Y-%m-%dT%H:%M:%SZ"
)
template_end_date = datetime.datetime.strptime(
template.object_template_json["object_end_date"],
"%Y-%m-%dT%H:%M:%SZ"
)
# Setup the start date for the object
object_start_date = timezone.now()
object_start_date = object_start_date.replace(
hour=template_start_date.hour,
minute=template_start_date.minute,
second=template_start_date.second,
microsecond=0,
)
object_end_date = object_start_date + abs(template_end_date - template_start_date)
# Organisation
organisation_instance = Organisation.objects.get(
organisation_id=template.object_template_json["object_organisation"],
)
# Status
status = object_dict["status"].objects.filter(
is_deleted=False,
).order_by(
F"{object_string}_status_sort_order",
).first()
# Setup the new template
submit_object = object_dict["object"](
change_user=User.objects.get(pk=1),
creation_user=User.objects.get(pk=1),
**{
object_dict["object_title"]: template.object_template_json["object_title"],
object_dict["object_description"]: template.object_template_json["object_description"],
object_dict["object_organisation"]: organisation_instance,
object_dict["object_start_date"]: object_start_date,
object_dict["object_end_date"]: object_end_date,
object_dict["object_status"]: status,
},
)
submit_object.save()
event_hooks.emit(f"{object_string}.create.scheduled_object", submit_object)
# Loop through the group list and add them
object_template_groups = ObjectTemplateGroup.objects.filter(
is_deleted=False,
object_template_id=template.object_template_id,
)
for group in object_template_groups:
submit_object_assignment = ObjectAssignment(
change_user=User.objects.get(pk=1),
group_id_id=group.group_id,
**{F"{object_string}_id": submit_object.pk }
)
submit_object_assignment.save()
@staticmethod
def create_kanban_card_object(scheduled_object, template, *args, **kwargs):
# Flatpack variables
kanban_card_text = template.object_template_json["object_title"]
kanban_board_id = template.object_template_json["kanban_card_setup"]["kanban_board"]
kanban_column_id = template.object_template_json["kanban_card_setup"]["kanban_column"]
kanban_level_id = template.object_template_json["kanban_card_setup"]["kanban_level"]
# Check to make sure the name is unique - otherwise place date at the end of the title
existing_title = len(KanbanCard.objects.filter(
is_deleted=False,
is_archived=False,
kanban_board_id=kanban_board_id,
kanban_card_text=kanban_card_text
)) > 0
if existing_title:
kanban_card_text = kanban_card_text[0:244] if len(kanban_card_text) > 244 else kanban_card_text
kanban_card_text = kanban_card_text + F" {datetime.date.today()}"
# Get the max sort number
sort_array = KanbanCard.objects.filter(
is_deleted=False,
kanban_board_id=kanban_board_id,
kanban_column_id=kanban_column_id,
kanban_level_id=kanban_level_id,
).annotate(
max=Max("kanban_card_sort_number"),
).values("max")
# If there is data, we want the max results + 1, else default to 0
kanban_card_sort_number = sort_array.first().get("max") + 1 if len(sort_array) > 0 else 0
submit_object = KanbanCard(
change_user=User.objects.get(pk=1),
kanban_card_text=kanban_card_text,
kanban_card_description=template.object_template_json["object_description"],
kanban_board_id=kanban_board_id,
kanban_column_id=kanban_column_id,
kanban_level_id=kanban_level_id,
kanban_card_sort_number=kanban_card_sort_number,
)
submit_object.save()
def run_set_day_of_the_week(self):
# Get today's date and day of the week
todays_date = self.get_today()
todays_day = calendar.day_name[todays_date.weekday()].lower()
last_run = todays_date - datetime.timedelta(days=1)
# Setup blank return query set
query_set_results = ScheduledObject.objects.none()
# Get data and process
potential_scheduled_objects = ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_SET_DAY_OF_THE_WEEK,
frequency_attribute__isnull=False,
frequency_attribute__days_of_the_week__isnull=False,
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True,
) | Q(
last_run__lte=last_run,
)
) & Q(
Q(
number_of_repeats=-1,
) | Q(
number_of_repeats__gte=0,
run_count__lte=F('number_of_repeats'),
)
)
)
# Loop through the potential and then deterine if they should be added to the return result
for scheduled_object in potential_scheduled_objects:
# Get JSON value
frequency_attribute = scheduled_object.frequency_attribute
days_of_the_week = frequency_attribute['days_of_the_week']
if todays_day in days_of_the_week:
# Using the union, we union on a query set of this results
# I don't like this :'(
# Refer to this -
# https://stackoverflow.com/questions/29587382/how-to-add-an-model-instance-to-a-django-queryset
query_set_results |= ScheduledObject.objects.filter(pk=scheduled_object.pk)
# Return
return query_set_results
def run_weekly(self):
todays_date = self.get_today()
day_of_the_week = calendar.day_name[todays_date.weekday()]
last_run = todays_date - datetime.timedelta(days=7)
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_WEEKLY,
frequency_attribute__day_of_the_week=day_of_the_week.lower(),
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True,
) | Q(
last_run__lte=last_run,
)
) & Q(
Q(
number_of_repeats=-1,
) | Q(
number_of_repeats__gte=0,
run_count__lte=F('number_of_repeats'),
)
)
)
def run_fortnightly(self):
todays_date = self.get_today()
day_of_the_week = calendar.day_name[todays_date.weekday()]
last_run = todays_date - datetime.timedelta(days=14)
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_FORTNIGHTLY,
frequency_attribute__day_of_the_week=day_of_the_week.lower(),
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True
) | Q(
last_run__lte=last_run
)
)
)
def run_monthly(self):
todays_date = self.get_today()
last_run = todays_date - datetime.timedelta(days=14)
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_MONTHLY,
start_date__lte=todays_date,
start_date__day=todays_date.day,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True
) | Q(
last_run__lte=last_run
)
)
)
def run_start_of_the_month(self):
# If today is not the 1st - we will just leave
todays_date = self.get_today()
last_run = todays_date - datetime.timedelta(days=14)
if todays_date.day != 1:
return ScheduledObject.objects.none()
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_START_OF_THE_MONTH,
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True,
) | Q(
last_run__lte=last_run,
)
)
)
def run_end_of_the_month(self):
# If today is not the end of the month - we will just leave
todays_date = self.get_today()
end_month_date = calendar.monthrange(todays_date.year, todays_date.month)[1]
last_run = todays_date - datetime.timedelta(days=14)
if todays_date.day != end_month_date:
return ScheduledObject.objects.none()
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_END_OF_THE_MONTH,
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__year__gte=todays_date.year,
end_date__month__gte=todays_date.month,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True,
) | Q(
last_run__lte=last_run,
)
)
)
def run_x_days_before_end_of_the_month(self):
# If today's date is earlier than the 14th, just leave
todays_date = self.get_today()
last_run = todays_date - datetime.timedelta(days=14)
if todays_date.day < 14:
return ScheduledObject.objects.none()
# Get the end date
end_month_date = calendar.monthrange(todays_date.year, todays_date.month)[1]
days_before = end_month_date - todays_date.day
# Get data and process
return ScheduledObject.objects.filter(
Q(
is_deleted=False,
frequency=SCH_X_DAYS_BEFORE_END_OF_THE_MONTH,
frequency_attribute__days_before=days_before,
start_date__lte=todays_date,
is_active=True,
) & Q(
Q(
end_date__gte=todays_date,
) | Q(
end_date__isnull=True,
)
) & Q(
Q(
last_run__isnull=True,
) | Q(
last_run__lte=last_run,
)
)
)

View File

@@ -0,0 +1,165 @@
from django.core.management.base import BaseCommand
from django.conf import settings
import string
import os
LINE_COMMAND = "python3 {manage_path} runscheduler 2>&1\n"
LINE_TEMPLATE = "{timestr} {cmd}"
DEFAULT_TIME_STRING = "0 0 * * *"
ALLOWED_CHARS = set(string.digits + "/*-, ")
DEFAULT_CRONTAB_PATH = "/etc/crontabs/nearbeach"
class ContabTime:
_fields = (
"minutes",
"hours",
"day_of_month",
"month",
"day_of_week",
)
_valid_ranges = (
(0, 59),
(0, 23),
(1, 31),
(1, 12),
(0, 6),
)
def __init__(self, mins=None, hrs=None, dom=None, month=None, dow=None, *args):
self._minutes = mins
self._hours = hrs
self._day_of_month = dom
self._month = month
self._day_of_week = dow
self._extras = args
@staticmethod
def _get_value(x, max_value):
if x == "*":
# replace x with a valid value
return max_value
return int(x)
def _get_values(self, x, min_value):
return list(map(lambda y, m=min_value: self._get_value(y, m), x))
def _check_list(self, v, min_value, max_value):
for x in v.split(","):
if x == "":
continue
if not self._check_value(x, min_value, max_value):
return False
return True
def _check_steps(self, v, min_value, max_value):
if "/" in v:
num, dom = v.split("/")
if not self._check_value_in_range(num, min_value, max_value):
return False
if not self._check_value_in_range(dom, min_value, max_value):
return False
return True
def _check_range(self, v, min_value, max_value):
start, end = v.split("-")
if not self._check_value_in_range(start, min_value, max_value):
return False
if "/" in end:
if not self._check_steps(end, min_value, max_value):
return False
elif not self._check_value_in_range(end, min_value, max_value):
return False
return True
def _check_value_in_range(self, v, min_value, max_value):
value = self._get_value(v, min_value)
if value < min_value or value > max_value:
return False
return True
def _check_value(self, v, min_value=0, max_value=59):
try:
if len(set(v).difference(ALLOWED_CHARS)) > 0:
return False
elif "," in v:
if not self._check_list(v, min_value, max_value):
return False
elif "-" in v:
if not self._check_range(v, min_value, max_value):
return False
elif "/" in v:
if not self._check_steps(v, min_value, max_value):
return False
elif not self._check_value_in_range(v, min_value, max_value):
return False
except:
return False
return True
def validate(self):
if len(self._extras) != 0 or any(
getattr(self, "_" + f) is None for f in self._fields
):
raise ValueError("Invalid crontab")
for f, r in zip(self._fields, self._valid_ranges):
v = getattr(self, "_" + f)
x = self._check_value(v, min_value=r[0], max_value=r[1])
if not x:
raise ValueError("Invalid crontab")
@staticmethod
def from_string(timestr):
return ContabTime(*timestr.split(" "))
def __str__(self):
return " ".join(
f
for f in map(lambda x: getattr(self, "_" + x), self._fields)
if f is not None
)
class Command(BaseCommand):
help = "Replaces the crontab entry for nearbeach"
def handle(self, *args, **kwargs):
base_dir = getattr(settings, "BASE_DIR")
if base_dir is None:
raise ValueError("BASE_DIR not set")
line_command = LINE_COMMAND.format(
manage_path=os.path.join(base_dir, "manage.py")
)
timestr = getattr(settings, "CRONTAB_TIMESTR", DEFAULT_TIME_STRING)
tab = ContabTime.from_string(timestr)
tab.validate()
with open(
getattr(settings, "CRONTAB_PATH", DEFAULT_CRONTAB_PATH), "r+"
) as crontab:
lines = crontab.readlines()
found_index = -1
for n, line in enumerate(lines):
if line.endswith(line_command):
found_index = n
break
write_line = LINE_TEMPLATE.format(
timestr=timestr,
cmd=line_command,
)
if found_index == -1:
lines.append(write_line)
else:
lines[found_index] = write_line
crontab.seek(0)
crontab.writelines(lines)

View File

@@ -0,0 +1,39 @@
from django.http import HttpResponse
from django.template.loader import get_template, TemplateDoesNotExist
from django.conf import settings
from NearBeach.views.theme_views import get_theme
class TemplateErrorMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Response
response = self.get_response(request)
# On debug send back response
if settings.DEBUG:
return response
try:
# Error Template
t = get_template(f"{response.status_code}.html")
# Context
c = {
"nearbeach_title": "error",
"need_tinymce": False,
"theme": get_theme(request),
}
# Return
response = HttpResponse(
t.render(c, request),
status=response.status_code,
)
except TemplateDoesNotExist:
pass
return response

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-26 08:32
from __future__ import unicode_literals
from django.db import migrations
def initialise_data(apps, schema_editor):
"""
The initial setup of the database should populate certain fields with
the correct data. Otherwise certain features of the database will
not function correctly.
"""
db_alias = schema_editor.connection.alias
# List of bug clients
list_of_bug_client = apps.get_model("NearBeach", "ListOfBugClient")
list_of_bug_client.objects.using(db_alias).bulk_create(
[
list_of_bug_client(
bug_client_name="Bugzilla",
bug_client_api_url="/rest/",
api_open_bugs="?open_status=True",
api_search_bugs="bug?quicksearch=",
api_bug="/show_bug.cgi?id=",
)
]
)
# List of requirement items status
list_of_requirement_item_status = apps.get_model(
"NearBeach", "ListOfRequirementItemStatus"
)
list_of_requirement_item_status.objects.using(db_alias).bulk_create(
[
list_of_requirement_item_status(requirement_item_status="Draft"),
list_of_requirement_item_status(requirement_item_status="Review"),
list_of_requirement_item_status(
requirement_item_status="Developing/Working"
),
list_of_requirement_item_status(requirement_item_status="Testing"),
list_of_requirement_item_status(
requirement_item_status="User Acceptance Testing"
),
list_of_requirement_item_status(requirement_item_status="Rework"),
list_of_requirement_item_status(requirement_item_status="Implemented"),
list_of_requirement_item_status(requirement_item_status="Finish"),
list_of_requirement_item_status(requirement_item_status="Not Tested"),
list_of_requirement_item_status(requirement_item_status="Obsolete"),
]
)
# List of requirement items type
list_of_requirement_item_type = apps.get_model(
"NearBeach", "ListOfRequirementItemType"
)
list_of_requirement_item_type.objects.using(db_alias).bulk_create(
[
list_of_requirement_item_type(requirement_item_type="Informational"),
list_of_requirement_item_type(requirement_item_type="Feature"),
list_of_requirement_item_type(requirement_item_type="User Case"),
list_of_requirement_item_type(requirement_item_type="User Interface"),
list_of_requirement_item_type(requirement_item_type="Non Functional"),
list_of_requirement_item_type(requirement_item_type="Constraint"),
list_of_requirement_item_type(requirement_item_type="System Function"),
]
)
# List of requirement status
list_of_requirement_status = apps.get_model("NearBeach", "ListOfRequirementStatus")
list_of_requirement_status.objects.using(db_alias).bulk_create(
[
list_of_requirement_status(requirement_status="Backlog"),
list_of_requirement_status(requirement_status="Blocked"),
list_of_requirement_status(requirement_status="In Progress"),
list_of_requirement_status(requirement_status="Testing/Review"),
list_of_requirement_status(
requirement_status="Closed", requirement_status_is_closed=True
),
]
)
# List of requirement type
list_of_requirement_type = apps.get_model("NearBeach", "ListOfRequirementType")
list_of_requirement_type.objects.using(db_alias).bulk_create(
[
list_of_requirement_type(requirement_type="Non Specific"),
list_of_requirement_type(requirement_type="Customer Requirements"),
list_of_requirement_type(requirement_type="System Requirements"),
]
)
# List of titles
list_of_titles = apps.get_model("NearBeach", "ListOfTitle")
list_of_titles.objects.using(db_alias).bulk_create(
[
list_of_titles(title="Mr"),
list_of_titles(title="Ms"),
list_of_titles(title="Mrs"),
list_of_titles(title="Mx"),
]
)
# List of RFC Status
list_of_rfc_status = apps.get_model("NearBeach", "ListOfRFCStatus")
list_of_rfc_status.objects.using(db_alias).bulk_create(
[
list_of_rfc_status(rfc_status_id=1, rfc_status="Draft"),
list_of_rfc_status(rfc_status_id=2, rfc_status="Waiting for approval"),
list_of_rfc_status(rfc_status_id=3, rfc_status="Approved"),
list_of_rfc_status(rfc_status_id=4, rfc_status="Started"),
list_of_rfc_status(rfc_status_id=5, rfc_status="Finished"),
list_of_rfc_status(rfc_status_id=6, rfc_status="Rejected"),
list_of_rfc_status(rfc_status_id=7, rfc_status="Paused"),
]
)
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0001_initial"),
]
operations = [
migrations.RunPython(initialise_data, reverse_code=migrations.RunPython.noop),
]

View File

@@ -0,0 +1,42 @@
# Generated by Django 4.1.4 on 2023-02-01 08:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0002_initialise_data"),
]
operations = [
migrations.AddField(
model_name="kanbancolumn",
name="kanban_property",
field=models.CharField(
choices=[
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Normal",
max_length=10,
),
),
migrations.AlterField(
model_name="changetask",
name="change_task_status",
field=models.IntegerField(
choices=[
(1, "Draft"),
(2, "Waiting for approval"),
(3, "Approved"),
(4, "Started"),
(5, "Finished"),
(6, "Rejected"),
(7, "Paused"),
(8, "Ready for QA"),
]
),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.1.4 on 2023-02-01 08:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0003_kanbancolumn_kanban_property_and_more"),
]
operations = [
migrations.RenameField(
model_name="kanbancolumn",
old_name="kanban_property",
new_name="kanban_column_property",
),
]

View File

@@ -0,0 +1,30 @@
# Generated by Django 4.1.4 on 2023-03-06 08:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(
"NearBeach",
"0004_rename_kanban_property_kanbancolumn_kanban_column_property",
),
]
operations = [
migrations.AddField(
model_name="kanbancard",
name="kanban_card_priority",
field=models.IntegerField(
choices=[
(0, "Highest"),
(1, "High"),
(2, "Normal"),
(3, "Low"),
(4, "Lowest"),
],
default=2,
),
),
]

View File

@@ -0,0 +1,31 @@
# Generated by Django 4.1.4 on 2023-03-08 09:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0005_kanbancard_kanban_card_priority"),
]
operations = [
migrations.AddField(
model_name="objectassignment",
name="link_relationship",
field=models.CharField(
choices=[
("Block", "Block"),
("Duplicate", "Duplicate"),
("Relate", "Relate"),
],
default="Relate",
max_length=10,
),
),
migrations.AddField(
model_name="objectassignment",
name="parent_link",
field=models.IntegerField(blank=True, null=True),
),
]

View File

@@ -0,0 +1,43 @@
# Generated by Django 4.1.4 on 2023-03-08 09:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0006_objectassignment_link_relationship_and_more"),
]
operations = [
migrations.AddField(
model_name="objectassignment",
name="change_task",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.changetask",
),
),
migrations.AlterField(
model_name="objectassignment",
name="link_relationship",
field=models.CharField(
blank=True,
choices=[
("Block", "Block"),
("Duplicate", "Duplicate"),
("Relate", "Relate"),
],
max_length=10,
null=True,
),
),
migrations.AlterField(
model_name="objectassignment",
name="parent_link",
field=models.CharField(blank=True, max_length=20, null=True),
),
]

View File

@@ -0,0 +1,28 @@
# Generated by Django 4.1.4 on 2023-03-13 08:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0007_objectassignment_change_task_and_more"),
]
operations = [
migrations.AlterField(
model_name="objectassignment",
name="link_relationship",
field=models.CharField(
blank=True,
choices=[
("Block", "Block"),
("Duplicate", "Duplicate"),
("Relate", "Relate"),
("Subobject", "Subobject"),
],
max_length=10,
null=True,
),
),
]

View File

@@ -0,0 +1,39 @@
# Generated by Django 4.1.1 on 2023-04-17 11:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0008_alter_objectassignment_link_relationship"),
]
operations = [
migrations.AddField(
model_name="documentpermission",
name="kanban_card",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.kanbancard",
),
),
migrations.AlterField(
model_name="objectassignment",
name="link_relationship",
field=models.CharField(
blank=True,
choices=[
("block", "Block"),
("duplicate", "Duplicate"),
("relate", "Relate"),
("subobject", "Subobject"),
],
max_length=10,
null=True,
),
),
]

View File

@@ -0,0 +1,24 @@
# Generated by Django 4.1.1 on 2023-04-17 11:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0009_documentpermission_kanban_card_and_more"),
]
operations = [
migrations.AddField(
model_name="folder",
name="kanban_card",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.kanbancard",
),
),
]

View File

@@ -0,0 +1,27 @@
# Generated by Django 4.1.1 on 2023-05-12 10:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0010_folder_kanban_card"),
]
operations = [
migrations.AddField(
model_name="permissionset",
name="tag",
field=models.IntegerField(
choices=[
(0, "No Permission"),
(1, "Read Only"),
(2, "Edit Only"),
(3, "Add and Edit"),
(4, "Full Permission"),
],
default=0,
),
),
]

View File

@@ -0,0 +1,46 @@
# Generated by Django 4.2.4 on 2023-09-03 08:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("NearBeach", "0011_permissionset_tag"),
]
operations = [
migrations.CreateModel(
name="UserSetting",
fields=[
(
"user_setting_id",
models.BigAutoField(primary_key=True, serialize=False),
),
(
"setting_type",
models.CharField(
choices=[
("DASHBOARD", "Dashboard"),
("EDIT_KANBAN_BOARD", "Edit Kanban Board"),
("KANBAN_BOARD", "Kanban Board"),
("SEARCH", "Search"),
("THEME", "NearBeach Theme"),
],
default="THEME",
max_length=30,
),
),
("setting_data", models.JSONField()),
(
"username",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.2.4 on 2023-10-03 20:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0012_usersetting"),
]
operations = [
migrations.AddField(
model_name="documentpermission",
name="new_object",
field=models.UUIDField(blank=True, null=True),
),
]

View File

@@ -0,0 +1,60 @@
# Generated by Django 4.2.4 on 2023-10-27 09:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0013_documentpermission_new_object"),
]
operations = [
migrations.AlterField(
model_name="notification",
name="notification_location",
field=models.CharField(
choices=[
("all", "All Options"),
("dashboard", "Dashboard Screen"),
("login", "Login Screen"),
],
default="All",
max_length=20,
),
),
migrations.AlterField(
model_name="objectassignment",
name="link_relationship",
field=models.CharField(
blank=True,
choices=[
("block", "Block"),
("duplicate", "Duplicate"),
("relate", "Relate"),
("subobject", "Subobject"),
],
default="",
max_length=10,
),
),
migrations.AlterField(
model_name="objectassignment",
name="meta_object_status",
field=models.CharField(blank=True, default="", max_length=255),
),
migrations.AlterField(
model_name="objectassignment",
name="meta_object_title",
field=models.CharField(blank=True, default="", max_length=255),
),
migrations.AlterField(
model_name="objectassignment",
name="parent_link",
field=models.CharField(blank=True, default="", max_length=20),
),
migrations.AlterField(
model_name="requestforchange",
name="rfc_version_number",
field=models.CharField(blank=True, default="", max_length=25),
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.2.4 on 2023-10-27 09:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0014_alter_notification_notification_location_and_more"),
]
operations = [
migrations.AddField(
model_name="notification",
name="is_deleted",
field=models.BooleanField(default=False),
),
]

View File

@@ -0,0 +1,27 @@
# Generated by Django 4.2.7 on 2023-11-22 09:07
from django.db import migrations, models
def set_successfully_status(apps, schema_editor):
Document = apps.get_model("NearBeach", "Document")
Document.objects.all().update(
document_upload_successfully=True,
)
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0015_notification_is_deleted"),
]
operations = [
migrations.AddField(
model_name="document",
name="document_upload_successfully",
field=models.BooleanField(default=False),
),
migrations.RunPython(set_successfully_status, migrations.RunPython.noop)
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.2.7 on 2023-11-29 08:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0016_document_document_upload_successfully"),
]
operations = [
migrations.AddField(
model_name="tag",
name="tag_text_colour",
field=models.CharField(default="#ffffff", max_length=7),
),
]

View File

@@ -0,0 +1,104 @@
# Generated by Django 5.0 on 2023-12-11 09:38
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0017_tag_tag_text_colour"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="PublicLink",
fields=[
("public_link_id", models.UUIDField(primary_key=True, serialize=False)),
("public_link_is_active", models.BooleanField(default=True)),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"creation_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_creation_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"kanban_board",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.kanbanboard",
),
),
(
"kanban_card",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.kanbancard",
),
),
(
"project",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.project",
),
),
(
"request_for_change",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requestforchange",
),
),
(
"requirement",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requirement",
),
),
(
"requirement_item",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requirementitem",
),
),
(
"task",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.task",
),
),
],
),
]

View File

@@ -0,0 +1,20 @@
# Generated by Django 5.0 on 2023-12-11 10:21
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0018_publiclink"),
]
operations = [
migrations.AlterField(
model_name="publiclink",
name="public_link_id",
field=models.UUIDField(
default=uuid.uuid4, primary_key=True, serialize=False
),
),
]

View File

@@ -0,0 +1,197 @@
# Generated by Django 5.0 on 2023-12-27 06:03
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
def initialise_data(apps, schema_editor):
"""
This will insert the default status for both projects and tasks.
"""
db_alias = schema_editor.connection.alias
# Projects
list_of_project_status = apps.get_model("NearBeach", "ListOfProjectStatus")
list_of_project_status.objects.using(db_alias).bulk_create(
[
list_of_project_status(
project_status_id=1,
project_status="New",
project_higher_order_status="Backlog",
project_status_order=1
),
list_of_project_status(
project_status_id=2,
project_status="Backlog",
project_higher_order_status="Backlog",
project_status_order=2
),
list_of_project_status(
project_status_id=3,
project_status="Blocked",
project_higher_order_status="Blocked",
project_status_order=3
),
list_of_project_status(
project_status_id=4,
project_status="In Progress",
project_higher_order_status="Normal",
project_status_order=4
),
list_of_project_status(
project_status_id=5,
project_status="Test/Review",
project_higher_order_status="Normal",
project_status_order=5
),
list_of_project_status(
project_status_id=6,
project_status="Closed",
project_higher_order_status="Closed",
project_status_order=6
),
]
)
# Tasks
list_of_task_status = apps.get_model("NearBeach", "ListOfTaskStatus")
list_of_task_status.objects.using(db_alias).bulk_create(
[
list_of_task_status(
task_status_id=1,
task_status="New",
task_higher_order_status="Backlog",
task_status_order=1,
),
list_of_task_status(
task_status_id=2,
task_status="Backlog",
task_higher_order_status="Backlog",
task_status_order=2,
),
list_of_task_status(
task_status_id=3,
task_status="Blocked",
task_higher_order_status="Blocked",
task_status_order=3,
),
list_of_task_status(
task_status_id=4,
task_status="In Progress",
task_higher_order_status="Normal",
task_status_order=4,
),
list_of_task_status(
task_status_id=5,
task_status="Test/Review",
task_higher_order_status="Normal",
task_status_order=5,
),
list_of_task_status(
task_status_id=6,
task_status="Closed",
task_higher_order_status="Closed",
task_status_order=6,
),
]
)
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0019_alter_publiclink_public_link_id"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AlterField(
model_name="kanbancolumn",
name="kanban_column_property",
field=models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Normal",
max_length=10,
),
),
migrations.CreateModel(
name="ListOfProjectStatus",
fields=[
(
"project_status_id",
models.BigAutoField(primary_key=True, serialize=False),
),
("project_status", models.CharField(max_length=100)),
(
"project_higher_order_status",
models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Backlog",
max_length=10,
),
),
("project_status_order", models.PositiveIntegerField(default=0)),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="ListOfTaskStatus",
fields=[
(
"task_status_id",
models.BigAutoField(primary_key=True, serialize=False),
),
("task_status", models.CharField(max_length=100)),
(
"task_higher_order_status",
models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Backlog",
max_length=10,
),
),
("task_status_order", models.PositiveIntegerField(default=0)),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.RunPython(initialise_data, reverse_code=migrations.RunPython.noop),
]

View File

@@ -0,0 +1,172 @@
# Generated by Django 5.0 on 2023-12-27 06:28
import django.db.models.deletion
from django.db import migrations, models
def update_foreign_key_status(app, schema_editor):
"""
All foreign key status' have defaulted to the value 1. We will NEED to update them to the
correct status. This will be applied for BOTH tasks and Projects
"""
db_alias = schema_editor.connection.alias
# Projects
project = app.get_model("NearBeach", "Project")
project.objects.filter(project_status="Backlog").update(status=2)
project.objects.filter(project_status="Blocked").update(status=3)
project.objects.filter(project_status="In Progress").update(status=4)
project.objects.filter(project_status="Test/Review").update(status=5)
project.objects.filter(project_status="Closed").update(status=6)
# Tasks
task = app.get_model("NearBeach", "Task")
task.objects.filter(task_status="Backlog").update(status=2)
task.objects.filter(task_status="Blocked").update(status=3)
task.objects.filter(task_status="In Progress").update(status=4)
task.objects.filter(task_status="Test/Review").update(status=5)
task.objects.filter(task_status="Closed").update(status=6)
# Requirement Item
requirement_item = app.get_model("NearBeach", "ListOfRequirementItemStatus")
requirement_item.objects.filter(pk=1).update(
requirement_item_higher_order_status="Backlog",
requirement_item_status_sort_order=1
)
requirement_item.objects.filter(pk=2).update(
requirement_item_higher_order_status="Backlog",
requirement_item_status_sort_order=2
)
requirement_item.objects.filter(pk=3).update(
requirement_item_higher_order_status="Normal",
requirement_item_status_sort_order=3
)
requirement_item.objects.filter(pk=4).update(
requirement_item_higher_order_status="Normal",
requirement_item_status_sort_order=4
)
requirement_item.objects.filter(pk=5).update(
requirement_item_higher_order_status="Normal",
requirement_item_status_sort_order=5
)
requirement_item.objects.filter(pk=6).update(
requirement_item_higher_order_status="Normal",
requirement_item_status_sort_order=6
)
requirement_item.objects.filter(pk=7).update(
requirement_item_higher_order_status="Closed",
requirement_item_status_sort_order=7
)
requirement_item.objects.filter(pk=8).update(
requirement_item_higher_order_status="Closed",
requirement_item_status_sort_order=8
)
requirement_item.objects.filter(pk=9).update(
requirement_item_higher_order_status="Normal",
requirement_item_status_sort_order=9
)
requirement_item.objects.filter(pk=10).update(
requirement_item_higher_order_status="Closed",
requirement_item_status_sort_order=10
)
# Requirement Item - User edited data
requirement_item.objects.filter(status_is_closed=True).update(
requirement_item_higher_order_status="Closed",
)
# Requirement
requirement = app.get_model("NearBeach", "ListOfRequirementStatus")
requirement.objects.filter(pk=1).update(
requirement_higher_order_status="Backlog",
requirement_status_sort_order=1,
)
requirement.objects.filter(pk=2).update(
requirement_higher_order_status="Blocked",
requirement_status_sort_order=2,
)
requirement.objects.filter(pk=3).update(
requirement_higher_order_status="Normal",
requirement_status_sort_order=3,
)
requirement.objects.filter(pk=4).update(
requirement_higher_order_status="Normal",
requirement_status_sort_order=4,
)
requirement.objects.filter(pk=5).update(
requirement_higher_order_status="Closed",
requirement_status_sort_order=5,
)
# Requirement - User edited data
requirement.objects.filter(requirement_status_is_closed=True).update(
requirement_higher_order_status="Closed",
)
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0020_alter_kanbancolumn_kanban_column_property_and_more"),
]
operations = [
migrations.AddField(
model_name="project",
name="status",
field=models.ForeignKey(
default=1,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.listofprojectstatus",
),
preserve_default=False,
),
migrations.AddField(
model_name="task",
name="status",
field=models.ForeignKey(
default=1,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.listoftaskstatus",
),
preserve_default=False,
),
migrations.AddField(
model_name="listofrequirementitemstatus",
name="requirement_item_higher_order_status",
field=models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Normal",
max_length=10,
),
),
migrations.AddField(
model_name="listofrequirementstatus",
name="requirement_higher_order_status",
field=models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Normal",
max_length=10,
),
),
migrations.AddField(
model_name="listofrequirementitemstatus",
name="requirement_item_status_sort_order",
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name="listofrequirementstatus",
name="requirement_status_sort_order",
field=models.PositiveIntegerField(default=0),
),
migrations.RunPython(update_foreign_key_status, reverse_code=migrations.RunPython.noop),
]

View File

@@ -0,0 +1,40 @@
# Generated by Django 4.1.1 on 2023-04-17 11:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0021_project_status_task_status"),
]
operations = [
migrations.RemoveField(
model_name="project",
name="project_status",
),
migrations.RenameField(
model_name="project",
old_name="status",
new_name="project_status",
),
migrations.RemoveField(
model_name="task",
name="task_status",
),
migrations.RenameField(
model_name="task",
old_name="status",
new_name="task_status",
),
migrations.RemoveField(
model_name="listofrequirementitemstatus",
name="status_is_closed",
),
migrations.RemoveField(
model_name="listofrequirementstatus",
name="requirement_status_is_closed",
),
]

View File

@@ -0,0 +1,29 @@
# Generated by Django 5.0 on 2023-12-29 06:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0022_project_status_task_status_switch"),
]
operations = [
migrations.AlterField(
model_name="changetask",
name="change_task_status",
field=models.IntegerField(
choices=[
(1, "Draft"),
(2, "Waiting for approval"),
(3, "Approved"),
(4, "Started"),
(5, "Finished"),
(6, "Rejected"),
(7, "Paused"),
(8, "Ready for QA"),
(9, "Failed"),
]
),
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 5.0.1 on 2024-01-10 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0023_alter_changetask_change_task_status"),
]
operations = [
migrations.AddField(
model_name="documentpermission",
name="is_profile_picture",
field=models.BooleanField(default=False),
),
]

View File

@@ -0,0 +1,22 @@
# Generated by Django 5.0.1 on 2024-02-16 10:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0024_documentpermission_is_profile_picture"),
]
operations = [
migrations.RenameField(
model_name="listofprojectstatus",
old_name="project_status_order",
new_name="project_status_sort_order",
),
migrations.RenameField(
model_name="listoftaskstatus",
old_name="task_status_order",
new_name="task_status_sort_order",
),
]

View File

@@ -0,0 +1,196 @@
# Generated by Django 5.0.1 on 2024-03-18 07:40
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(
"NearBeach",
"0025_rename_project_status_order_listofprojectstatus_project_status_sort_order_and_more",
),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Sprint",
fields=[
("sprint_id", models.BigAutoField(primary_key=True, serialize=False)),
(
"sprint_name",
models.CharField(default="empty sprint", max_length=100),
),
("total_story_points", models.IntegerField(default=0)),
("completed_story_points", models.IntegerField(default=0)),
(
"sprint_status",
models.CharField(
blank=True,
choices=[
("Draft", "Draft"),
("Current", "Current"),
("Finished", "Finished"),
],
default="Draft",
max_length=10,
),
),
("sprint_start_date", models.DateTimeField()),
("sprint_end_date", models.DateTimeField()),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"project",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.project",
),
),
(
"requirement",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requirement",
),
),
],
),
migrations.CreateModel(
name="SprintAuditTable",
fields=[
(
"sprint_audit_table_id",
models.BigAutoField(primary_key=True, serialize=False),
),
("story_point_cost", models.IntegerField(default=0)),
(
"higher_order_status",
models.CharField(
choices=[
("Backlog", "Backlog"),
("Normal", "Normal"),
("Blocked", "Blocked"),
("Closed", "Closed"),
],
default="Normal",
max_length=10,
),
),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"project",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.project",
),
),
(
"requirement_item",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requirementitem",
),
),
(
"sprint_id",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.sprint",
),
),
(
"task",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.task",
),
),
],
),
migrations.CreateModel(
name="SprintObjectAssignment",
fields=[
(
"sprint_object_assignment_id",
models.BigAutoField(primary_key=True, serialize=False),
),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"project",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.project",
),
),
(
"requirement_item",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.requirementitem",
),
),
(
"sprint_id",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.sprint",
),
),
(
"task",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.task",
),
),
],
),
]

View File

@@ -0,0 +1,67 @@
# Generated by Django 5.0.3 on 2024-05-03 09:45
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("NearBeach", "0026_sprint_sprintaudittable_sprintobjectassignment"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="UserJob",
fields=[
("user_job_id", models.BigAutoField(primary_key=True, serialize=False)),
("job_date", models.DateField(auto_now_add=True)),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
("is_deleted", models.BooleanField(default=False)),
(
"change_user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(class)s_change_user",
to=settings.AUTH_USER_MODEL,
),
),
(
"kanban_card",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.kanbancard",
),
),
(
"project",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.project",
),
),
(
"task",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="NearBeach.task",
),
),
(
"username",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]

Some files were not shown because too many files have changed in this diff Show More