first push

This commit is contained in:
2025-05-23 14:44:12 +08:00
commit abefd1b19b
817 changed files with 580289 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
SECRET_KEY =
EMAIL_HOST =
EMAIL_HOST_USER =
EMAIL_HOST_PASSWORD =
EMAIL_PORT =
DB_ENGINE =
for mysql: "django.db.backends.mysql"
for postgresql: "django.db.backends.postgresql"
DB_DATABASE =
DB_USERNAME =
DB_PASSWORD =
DB_HOST =
DB_PORT =
+6
View File
@@ -0,0 +1,6 @@
# *.py[cod]
**/__pycache__
**/.env
**/env
# .pytest_cache
media
+2
View File
@@ -0,0 +1,2 @@
import pymysql
pymysql.install_as_MySQLdb()
+16
View File
@@ -0,0 +1,16 @@
"""
ASGI config for AssetManagement project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AssetManagement.settings')
application = get_asgi_application()
+2
View File
@@ -0,0 +1,2 @@
[settings]
DEBUG=True
+184
View File
@@ -0,0 +1,184 @@
"""
Django settings for AssetManagement project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from ctypes import cast
from pathlib import Path
from dotenv import load_dotenv
import os
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv()
LOGIN_REDIRECT_URL = '/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = os.environ.get('SECRET_KEY')
SECRET_KEY = "django-insecure-^o6u10km7xey-)n6ng+hh2rxm+ydcvor*)$fnl7)3_i)nu)a&x"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG')
ALLOWED_HOSTS = ['*']
LOCALHOST_URL = 'http:127.0.0.1:8000'
DEV_URL = os.environ.get('DEV_URL') if os.getcwd() == "/app" else None
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authentication',
'vendors',
'products',
'assets',
'dashboard',
'recycle_bin',
'upload',
'error_handlers',
'smart_selects',
'roles',
'users',
'support',
'notifications',
'simple_history'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'simple_history.middleware.HistoryRequestMiddleware'
]
ROOT_URLCONF = 'AssetManagement.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages'
],
},
},
]
WSGI_APPLICATION = 'AssetManagement.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'eamtest', # 数据库名字
'USER': 'root',
'PASSWORD': 'guoan123',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR/'static'
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'authentication.User'
LOGIN_URL = 'authentication:login'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.environ.get('EMAIL_HOST')
EMAIL_PORT = os.environ.get('EMAIL_PORT')
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
#Image Processing
DJANGORESIZED_DEFAULT_SIZE = [1024, 768]
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
+69
View File
@@ -0,0 +1,69 @@
"""AssetManagement URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from authentication.forms import UserPasswordChangeForm, UserPasswordResetForm, UserPasswordResetRequestForm
from authentication.decorators import unauthenticated_user
urlpatterns = [
path('secret/', admin.site.urls),
path('', include('authentication.urls', namespace='authentication')),
path('vendors/', include('vendors.urls', namespace='vendors')),
path('products/', include('products.urls', namespace='products')),
path('admin/', include('dashboard.urls', namespace='dashboard')),
path('upload/', include('upload.urls', namespace='upload')),
path('recycle-bin/', include('recycle_bin.urls', namespace='recycle_bin')),
path('assets/', include('assets.urls', namespace='assets')),
path('roles/', include('roles.urls', namespace='roles')),
path('support/', include('support.urls', namespace='support')),
path('users/', include('users.urls', namespace='users')),
path('notifications/', include('notifications.urls', namespace='notifications')),
# django smart select urls
path('chaining/', include('smart_selects.urls')),
# Password Change Views
path('change-password/', auth_views.PasswordChangeView.as_view(form_class=UserPasswordChangeForm,
template_name='auth/password/password-change.html'), name='password_change'),
path('change-password/done/', auth_views.PasswordChangeDoneView.as_view(
template_name='auth/password/password-change-done.html'), name='password_change_done'),
# Password Reset Views
path('reset-password/', unauthenticated_user(auth_views.PasswordResetView.as_view(form_class=UserPasswordResetRequestForm,
template_name='auth/password/password-reset.html', html_email_template_name='auth/verification/password_reset_html_email.html')), name="password_reset"),
path('reset-password/done/', unauthenticated_user(auth_views.PasswordResetDoneView.as_view(
template_name='auth/password/password-reset-done.html')), name="password_reset_done"),
path('reset/<uidb64>/<token>', unauthenticated_user(auth_views.PasswordResetConfirmView.as_view(form_class=UserPasswordResetForm,
template_name='auth/password/password-reset-confirm.html')), name="password_reset_confirm"),
path('reset/done/', unauthenticated_user(auth_views.PasswordResetCompleteView.as_view(
template_name='auth/password/password-reset-complete.html')), name="password_reset_complete"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Error Handlers
handler403 = 'error_handlers.views.handle_403'
handler404 = 'error_handlers.views.handle_404'
handler500 = 'error_handlers.views.handle_500'
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for AssetManagement project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AssetManagement.settings')
application = get_wsgi_application()
+82
View File
@@ -0,0 +1,82 @@
# Contributing to Asset Management Project
Thank you for considering contributing to the Asset Management Project! Your contributions help make this project better for everyone. Below are guidelines to help you get started.
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [How Can I Contribute?](#how-can-i-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Submitting Pull Requests](#submitting-pull-requests)
- [Coding Standards](#coding-standards)
- [Style Guides](#style-guides)
- [Python Style Guide](#python-style-guide)
- [Git Commit Messages](#git-commit-messages)
- [License](#license)
## Code of Conduct
Please read and follow our [Code of Conduct](CODE_OF_CONDUCT.md).
## How Can I Contribute?
### Reporting Bugs
If you find a bug, please report it by opening an issue in the [issue tracker](https://github.com/VyrazuLabs/asseto-asset-management/issues). Please include:
- A clear and descriptive title.
- A detailed description of the steps to reproduce the bug.
- Any relevant screenshots or log output.
### Suggesting Enhancements
If you have a feature request or enhancement suggestion, please open an issue in the [issue tracker](https://github.com/VyrazuLabs/asseto-asset-management/issues). Please include:
- A clear and descriptive title.
- A detailed description of the proposed enhancement.
- Any relevant use cases or benefits.
### Submitting Pull Requests
1. Fork the repository.
2. Create a new branch (`git checkout -b feature-branch`).
3. Make your changes and ensure they follow the [coding standards](#coding-standards).
4. Test your changes thoroughly.
5. Commit your changes with a descriptive commit message.
6. Push to the branch (`git push origin feature-branch`).
7. Open a pull request.
Please include in your pull request:
- A clear title and description of the changes.
- A reference to the issue it fixes (if applicable).
## Coding Standards
To maintain code quality and consistency, please follow these guidelines:
- Write clear, concise, and well-documented code.
- Follow the project's existing code style and structure.
- Include tests for any new features or bug fixes.
- Ensure all tests passed before submitting a pull request.
## Style Guides
### Python Style Guide
- Follow the [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide for Python code.
- Use meaningful variable and function names.
- Write docstrings for all public modules, functions, classes, and methods.
### Git Commit Messages
- Use the present tense ("Add feature" not "Added feature").
- Use the imperative mood ("Move cursor to..." not "Moves cursor to...").
- Limit the subject line to 50 characters or less.
- Include a body if the commit message is more than 50 characters.
## License
By contributing to this project, you agree that your contributions will be licensed under the MIT License.
+20
View File
@@ -0,0 +1,20 @@
Vyrazu License (Based on GPL v3)
Copyright (c) [2024] [Vyrazu Labs Pvt. Ltd.]
Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for commercial purposes, subject to the following conditions:
1. Usage Rights:
- Users may use this project for commercial purposes.
- Users may suggest modifications to the original project holder.
- Users may submit modifications to the original project holder.
2. Attribution:
- If the Software or any modifications are shared with others, proper credit must be given to the original project by including the original author's name and a link to the original repository.
3. Restrictions:
- Users may not sell copies of the original or modified Software.
- Users may not upload modified versions of the Software to other platforms.
- Users may not distribute the original or modified versions 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.
+209
View File
@@ -0,0 +1,209 @@
# Asset Management Project
## Overview
The Asset Management Project is a comprehensive solution designed to help organizations efficiently manage their assets. This project provides functionalities for asset information, maintenance, asset allocation to users under admin, and dashboard viewing. The system is built with a user-friendly interface.
## Table of Contents
- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Unit Testing](#unit-testing)
- [Configuration](#configuration)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)
## Features
- **Admin**: Maintain detailed records of all Assigned Users, Locations, Departments, Product Types, Product Categories, and Roles.
- **Dashboard**: Displays information like Assets, Assigned/Unassigned Assets, Vendors, Locations, Products, Users, and Total Asset Cost in a tabular format along with Upcoming Warranty Expiries and Recent Activities Performed in the dashboard.
- **Assets**: Assign people to assets by adding them and a list to display all the assigned people with their respective assets.
- **Upload**: To generate a sample file or upload them for all the displayed data of Vendors, Locations, Departments, Product Types, Product Categories.
- **Reporting and Analytics**: Generate reports on asset performance, utilization, and maintenance history.
- **User Management**: Role-based access control to secure sensitive asset information.
- **Integration**: API support for integrating with other enterprise systems.
- **Recycle Bin**: Contains all the previously deleted files by the admin and also has functionality to restore them.
## Installation
### Prerequisites
- [Python 3.9+](https://www.python.org/)
- [Mysql](https://www.mysql.com/) (Can be replaced by your preferred database)
- [Docker](https://www.docker.com/) (optional, for containerized deployment)
### Steps
1. Clone the repository:
```sh
git clone https://github.com/yourusername/assetmanagement.git
cd asseto-asset-management
```
2. Create and activate a virtual environment:
```sh
python -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
```
3. Install dependencies:
```sh
pip install -r requirements.txt
```
4. Set up environment variables:
```sh
cp .env.example .env
```
Edit the `.env` file with your preferred settings.
5. Apply migrations:
```sh
python manage.py migrate
```
6. Start the development server:
```sh
python manage.py runserver
```
7. Open your browser and navigate to `http://localhost:8000`.
8. Create a superuser if necessary:
```sh
python manage.py createsuperuser
```
## Usage
#### Try This Project with a Demo Account
You can use this project before downloading.
The project is hosted [here](https://asset-management-hg2x.onrender.com/login?next=/).\
\
Credentials:\
&nbsp;&nbsp;&nbsp;&nbsp; email: asset-management@demo.com \
&nbsp;&nbsp;&nbsp;&nbsp; password: DM4g476ZmQ$U
Log in with this credential and use the below features
### Admin
<img src="static/assets/images/006-Locations.png" alt="Admin Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Admin" section.
2. Admin consists of five sections: Locations, Departments, Product Types, Product Categories, and Roles.
3. Each section has its own functionalities where you can perform operations such as Add/Edit/Delete/View.
### Vendors
<img src="static/assets/images/002-Vendors.png" alt="Vendors Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Vendors" section.
2. Click the buttons as per your needs (Add/Edit/Delete/View vendors).
3. Fill in the vendor details and click Save.
4. Searching and downloading vendor details are also available.
### Products
<img src="static/assets/images/003-Products.png" alt="Products Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Products" section.
2. Click the buttons as per your needs (Add/Edit/Delete/View products).
3. Fill in the product details and click Save.
4. Searching and downloading product details are also available.
### Users
<img src="static/assets/images/004-Users.png" alt="Users Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Users" section.
2. Click the buttons as per your needs (Add/Edit/Delete/View users).
3. Fill in the user details and click Save.
4. Searching and downloading user details are also available.
### Assets
<img src="static/assets/images/005-Assigned_assets.png" alt="Assets Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Assets" section.
2. Click the buttons as per your needs (Add/Edit/Delete/View assets).
3. Fill in the asset details and click Save.
4. Assigned Assets also contain a list of all the assets assigned to different individuals with search functionalities and Reassign/Unassign features.
### Upload
<img src="static/assets/images/012-uploads.png" alt="Upload Section" style="border-radius: 15px;" width="900" height="450"/>
1. Navigate to the "Upload" section.
2. Upload consists of five sections: Locations, Departments, Product Types, Product Categories, and Vendors.
3. Each section has its own functionalities where you may either upload the data or download a sample.
### Recycle Bin
<img src="static/assets/images/013-recycle_bin.png" alt="Recycle Bin Section" style="border-radius: 15px;" width="900" height="450"/>
1. The Recycle Bin contains all the previously deleted files by the admin and also has functionality to restore them, divided by category.
## Unit Testing
To ensure the quality and reliability of the system, unit tests are written to test various functionalities of the project. You can run the tests to verify that the project works as expected.
### Running Unit Tests
1. **Activate your virtual environment** (if not already activated):
```sh
source env/bin/activate # On Windows use `env\Scripts\activate`
```
2. **Run tests**:
```sh
python manage.py test
```
This will run all the tests across the project.
3. **Run tests for a specific app**:
If you want to run tests from a specific app, use the app name:
```sh
python manage.py test assets
```
4. **Verbose Output**:
For more detailed output while running the tests, use the `-v` flag:
```sh
python manage.py test -v 2
```
### Other Useful Commands
- **Show test results without resetting the database**:
```sh
python manage.py test --keepdb
```
## Configuration
Configuration options are managed via the `.env` file. Key settings include:
- Database credentials
- SMTP server credentias
- Other service configurations
Copy the settings from `.env.example` to `.env` and modify as needed.
## Contributing
We welcome contributions! To contribute:
1. Fork the repository.
2. Create a new branch (`git checkout -b feature-branch`).
3. Make your changes and commit them (`git commit -m 'Add new feature'`).
4. Push to the branch (`git push origin feature-branch`).
5. Open a pull request.
Please ensure your code follows our [coding standards](CONTRIBUTING.md).
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
## Contact
For any inquiries or support, please contact:
- Email: info@vyrazu.com
- Project Maintainer: [Vyrazu Labs Ltd](https://vyrazu.com/)
+251
View File
@@ -0,0 +1,251 @@
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class Assets(models.Model):
name = models.CharField(max_length=255)
serial_no = models.CharField(max_length=45)
price = models.FloatField()
purchase_date = models.DateField()
warranty_expiry_date = models.DateField()
purchase_type = models.CharField(max_length=45)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.DateTimeField()
products_product = models.ForeignKey('Products', models.DO_NOTHING)
vendors_vendor = models.ForeignKey('Vendors', models.DO_NOTHING)
organization = models.ForeignKey('Organization', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'assets'
unique_together = (('id', 'products_product', 'vendors_vendor', 'organization'),)
class AssetsSpecification(models.Model):
assets_asset = models.OneToOneField(Assets, models.DO_NOTHING, primary_key=True)
specification_specification = models.ForeignKey('Specification', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'assets_specification'
unique_together = (('assets_asset', 'specification_specification'),)
class Departments(models.Model):
name = models.CharField(max_length=255)
contact_person_name = models.CharField(max_length=255)
contact_person_email = models.CharField(max_length=255)
contact_person_phone = models.CharField(max_length=255)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
organization = models.ForeignKey('Organization', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'departments'
unique_together = (('id', 'organization'),)
class Employees(models.Model):
name = models.CharField(max_length=255)
employee_id = models.CharField(max_length=45)
departments = models.ForeignKey(Departments, models.DO_NOTHING)
reporting_manager = models.ForeignKey('self', models.DO_NOTHING, db_column='reporting_manager')
email = models.CharField(max_length=255)
phone = models.CharField(max_length=45)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
organization = models.ForeignKey('Organization', models.DO_NOTHING)
locations = models.ForeignKey('Locations', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'employees'
unique_together = (('id', 'departments', 'reporting_manager', 'organization', 'locations'),)
class Locations(models.Model):
organization = models.ForeignKey('Organization', models.DO_NOTHING)
office_name = models.CharField(max_length=255)
address_line_one = models.CharField(max_length=255)
address_line_two = models.CharField(max_length=255)
country = models.IntegerField()
state = models.IntegerField()
city = models.CharField(max_length=255)
pin_code = models.CharField(max_length=255)
contact_person_name = models.CharField(max_length=255)
contact_person_phone = models.CharField(max_length=255)
status = models.IntegerField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
class Meta:
managed = False
db_table = 'locations'
unique_together = (('id', 'organization'),)
class Organization(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
website = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255)
phone = models.CharField(max_length=255)
currency = models.IntegerField()
date_format = models.IntegerField(blank=True, null=True)
logo = models.CharField(max_length=255, blank=True, null=True)
status = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'organization'
class ProductCategory(models.Model):
category_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.DateTimeField()
organization = models.ForeignKey(Organization, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'product_category'
unique_together = (('category_id', 'organization'),)
class ProductType(models.Model):
type_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
organization = models.ForeignKey(Organization, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'product_type'
unique_together = (('type_id', 'organization'),)
class Products(models.Model):
name = models.CharField(max_length=255)
manufacturer = models.CharField(max_length=255)
description = models.CharField(max_length=255)
status = models.IntegerField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
product_category_category = models.ForeignKey(ProductCategory, models.DO_NOTHING)
product_type_type = models.ForeignKey(ProductType, models.DO_NOTHING)
organization = models.ForeignKey(Organization, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'products'
unique_together = (('id', 'product_category_category', 'product_type_type', 'organization'),)
class Specification(models.Model):
specification_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
value = models.CharField(max_length=255)
created_by = models.IntegerField(blank=True, null=True)
updated_by = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'specification'
class Uploads(models.Model):
id = models.IntegerField(primary_key=True)
organization = models.ForeignKey(Organization, models.DO_NOTHING)
entity_type = models.CharField(max_length=255, blank=True, null=True)
entity_id = models.IntegerField(blank=True, null=True)
filename = models.CharField(max_length=255, blank=True, null=True)
orignal_filename = models.CharField(max_length=255, blank=True, null=True)
notes = models.TextField(blank=True, null=True)
size = models.CharField(max_length=255, blank=True, null=True)
created_by = models.IntegerField(blank=True, null=True)
updated_at = models.CharField(max_length=255, blank=True, null=True)
updated_by = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'uploads'
unique_together = (('id', 'organization'),)
class Users(models.Model):
organization = models.ForeignKey(Locations, models.DO_NOTHING)
user_id = models.CharField(max_length=255)
locations = models.ForeignKey(Locations, models.DO_NOTHING)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255)
phone = models.CharField(max_length=255)
user_role = models.CharField(max_length=255)
status = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
class Meta:
managed = False
db_table = 'users'
unique_together = (('id', 'organization', 'locations'),)
class Vendors(models.Model):
vendor_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
phone = models.CharField(max_length=45)
contact_person = models.CharField(max_length=255)
designation = models.CharField(max_length=255)
country = models.CharField(max_length=255)
state = models.CharField(max_length=255)
city = models.CharField(max_length=255)
pin_code = models.CharField(max_length=45)
gstin_number = models.CharField(max_length=45)
address = models.CharField(max_length=255)
description = models.CharField(max_length=255)
status = models.IntegerField()
created_by = models.IntegerField()
updated_by = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.IntegerField()
organization = models.ForeignKey(Organization, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'vendors'
unique_together = (('id', 'organization'),)
View File
+10
View File
@@ -0,0 +1,10 @@
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import *
# Register your models here.
@admin.register(Asset)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['name', 'serial_no',
'organization', 'is_deleted', 'created_at']
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class AssetsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'assets'
+137
View File
@@ -0,0 +1,137 @@
from django import forms
from assets.models import Asset, AssignAsset
from products.models import Product
from vendors.models import Vendor
from dashboard.models import Location
from authentication.models import User
class AssetForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Enter Asset Name'}
))
serial_no = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Enter Serial No.'}
))
price = forms.FloatField(required=True, widget=forms.NumberInput(
attrs={'class': 'form-control',
'placeholder': 'Enter Price'}
))
purchase_date = forms.DateField(required=True, widget=forms.DateInput(
attrs={'type': 'date', 'class': 'form-control'}
))
warranty_expiry_date = forms.DateField(required=True, widget=forms.DateInput(
attrs={'type': 'date', 'class': 'form-control'}
))
description = forms.CharField(required=False, widget=forms.Textarea(
attrs={'class': 'form-control form-control-sm',
'rows': '3', 'placeholder': 'Enter Description'}
))
purchase_type = forms.ChoiceField(
required=True,
choices=(
("1", "Owned"),
("2", "Rented"),
),
initial=0,
widget=forms.Select(
attrs={'class': 'form-select'}
))
product = forms.ModelChoiceField(
required=True,
queryset=None,
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
vendor = forms.ModelChoiceField(
required=True,
queryset=None,
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
location = forms.ModelChoiceField(
required=True,
queryset=None,
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
def __init__(self, *args, **kwargs):
self._organization = kwargs.pop('organization', None)
super().__init__(*args, **kwargs)
self.fields['product'].queryset = Product.undeleted_objects.filter(organization=self._organization, status=True)
self.fields['vendor'].queryset = Vendor.undeleted_objects.filter(organization=self._organization, status=True)
self.fields['location'].queryset = Location.undeleted_objects.filter(organization=self._organization, status=True)
class Meta:
model = Asset
fields = ['name', 'serial_no', 'price', 'purchase_date', 'warranty_expiry_date', 'description',
'purchase_type', 'product', 'vendor', 'organization', 'location']
class AssignedAssetForm(forms.ModelForm):
asset = forms.ModelChoiceField(
required=True,
queryset=None,
label='he;ll',
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
user = forms.ModelChoiceField(
required=True,
queryset=None,
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
def __init__(self, *args, **kwargs):
self._organization = kwargs.pop('organization', None)
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = Asset.undeleted_objects.filter(is_assigned=False, status=True, organization=self._organization)
self.fields['user'].queryset = User.undeleted_objects.filter(is_active=True, organization=self._organization).exclude(is_superuser=True)
class Meta:
model = AssignAsset
fields = ['asset', 'user']
class ReassignedAssetForm(forms.ModelForm):
user = forms.ModelChoiceField(
required=True,
queryset=None,
empty_label="--SELECT--",
widget=forms.Select(
attrs={'class': 'form-select'}
))
def __init__(self, *args, **kwargs):
self._organization = kwargs.pop('organization', None)
super().__init__(*args, **kwargs)
self.fields['user'].queryset = User.undeleted_objects.filter(is_active=True, organization=self._organization).exclude(is_superuser=True)
class Meta:
model = AssignAsset
fields = ['user']
+83
View File
@@ -0,0 +1,83 @@
# Generated by Django 3.2 on 2022-05-27 06:01
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
('vendors', '0001_initial'),
('dashboard', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Asset',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('serial_no', models.CharField(blank=True, max_length=45, null=True)),
('price', models.FloatField(blank=True, null=True)),
('purchase_date', models.DateField(blank=True, null=True)),
('warranty_expiry_date', models.DateField(blank=True, null=True)),
('purchase_type', models.CharField(blank=True, max_length=45, null=True)),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='products.product')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Specification',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('value', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='AssetSpecification',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('asset', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='assets.asset')),
('specification', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='assets.specification')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='asset',
name='specifications',
field=models.ManyToManyField(blank=True, null=True, related_name='asset_specification', through='assets.AssetSpecification', to='assets.Specification'),
),
migrations.AddField(
model_name='asset',
name='vendor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='vendors.vendor'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-05-27 06:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='specifications',
field=models.ManyToManyField(related_name='asset_specification', through='assets.AssetSpecification', to='assets.Specification'),
),
]
@@ -0,0 +1,43 @@
# Generated by Django 3.2 on 2022-06-21 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0002_alter_asset_specifications'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='asset',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='assetspecification',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='assetspecification',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='specification',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='specification',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
+18
View File
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-07-03 18:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0003_auto_20220621_1350'),
]
operations = [
migrations.AddField(
model_name='asset',
name='deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,30 @@
# Generated by Django 3.2 on 2022-09-26 11:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0007_remove_productcategory_product_type'),
('assets', '0004_asset_deleted'),
]
operations = [
migrations.AddField(
model_name='asset',
name='description',
field=models.CharField(blank=True, max_length=999, null=True),
),
migrations.AddField(
model_name='asset',
name='location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location'),
),
migrations.AlterField(
model_name='asset',
name='specifications',
field=models.ManyToManyField(blank=True, related_name='asset_specification', through='assets.AssetSpecification', to='assets.Specification'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-09-28 08:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('vendors', '0003_auto_20220703_1843'),
('assets', '0005_auto_20220926_1137'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='vendor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='vendors.vendor'),
),
]
@@ -0,0 +1,25 @@
# Generated by Django 3.2 on 2022-09-29 07:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0009_producttype_deleted'),
('assets', '0006_alter_asset_vendor'),
]
operations = [
migrations.AddField(
model_name='asset',
name='is_deleted',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='asset',
name='location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='dashboard.location'),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 3.2 on 2022-09-29 07:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assets', '0007_auto_20220929_0734'),
]
operations = [
migrations.RemoveField(
model_name='asset',
name='deleted',
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-09-29 11:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0011_location_is_deleted'),
('assets', '0008_remove_asset_deleted'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-09-30 07:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('products', '0010_remove_product_deleted'),
('assets', '0009_alter_asset_location'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='product',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='products.product'),
),
]
@@ -0,0 +1,31 @@
# Generated by Django 3.2 on 2022-10-13 07:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0010_alter_asset_product'),
]
operations = [
migrations.RemoveField(
model_name='asset',
name='specifications',
),
migrations.RemoveField(
model_name='assetspecification',
name='specification',
),
migrations.AddField(
model_name='assetspecification',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='assetspecification',
name='value',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,16 @@
# Generated by Django 3.2 on 2022-10-13 07:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assets', '0011_auto_20221013_0710'),
]
operations = [
migrations.DeleteModel(
name='Specification',
),
]
@@ -0,0 +1,19 @@
# Generated by Django 3.2 on 2022-10-13 07:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('assets', '0012_delete_specification'),
]
operations = [
migrations.AlterField(
model_name='assetspecification',
name='asset',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='assets.asset'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-10-27 05:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0013_alter_assetspecification_asset'),
]
operations = [
migrations.AddField(
model_name='asset',
name='is_assigned',
field=models.BooleanField(default=False),
),
]
+34
View File
@@ -0,0 +1,34 @@
# Generated by Django 3.2 on 2022-10-28 09:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('assets', '0014_asset_is_assigned'),
]
operations = [
migrations.CreateModel(
name='AssignAsset',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('asset', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='assets.asset')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
@@ -0,0 +1,37 @@
# Generated by Django 3.2 on 2022-11-02 09:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assets', '0015_assignasset'),
]
operations = [
migrations.RemoveField(
model_name='assignasset',
name='created_at',
),
migrations.RemoveField(
model_name='assignasset',
name='created_by',
),
migrations.RemoveField(
model_name='assignasset',
name='is_deleted',
),
migrations.RemoveField(
model_name='assignasset',
name='status',
),
migrations.RemoveField(
model_name='assignasset',
name='updated_at',
),
migrations.RemoveField(
model_name='assignasset',
name='updated_by',
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-11-29 05:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0016_auto_20221102_1438'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='description',
field=models.TextField(blank=True, null=True),
),
]
@@ -0,0 +1,23 @@
# Generated by Django 3.2 on 2023-01-04 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0017_alter_asset_description'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='assetspecification',
name='status',
field=models.BooleanField(default=True),
),
]
+57
View File
@@ -0,0 +1,57 @@
# Generated by Django 3.2 on 2023-01-06 07:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('vendors', '0008_auto_20230104_1455'),
('products', '0014_historicalproduct'),
('dashboard', '0018_auto_20230104_1455'),
('assets', '0018_auto_20230104_1455'),
]
operations = [
migrations.CreateModel(
name='HistoricalAsset',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('serial_no', models.CharField(blank=True, max_length=45, null=True)),
('price', models.FloatField(blank=True, null=True)),
('purchase_date', models.DateField(blank=True, null=True)),
('warranty_expiry_date', models.DateField(blank=True, null=True)),
('purchase_type', models.CharField(blank=True, max_length=45, null=True)),
('description', models.TextField(blank=True, null=True)),
('is_assigned', models.BooleanField(default=False)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('location', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.location')),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
('product', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='products.product')),
('vendor', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='vendors.vendor')),
],
options={
'verbose_name': 'historical asset',
'verbose_name_plural': 'historical assets',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
View File
+46
View File
@@ -0,0 +1,46 @@
import uuid
from django.db import models
from dashboard.models import Location, TimeStampModel, Organization, SoftDeleteModel
from products.models import Product
from vendors.models import Vendor
from django.db.models import Sum
from authentication.models import User
from simple_history.models import HistoricalRecords
# Create your models here.
class AssetSpecification(TimeStampModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
asset = models.ForeignKey('Asset', models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
value = models.CharField(max_length=255, blank=True, null=True)
class Asset(TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
serial_no = models.CharField(max_length=45, blank=True, null=True)
price = models.FloatField(blank=True, null=True)
purchase_date = models.DateField(blank=True, null=True)
warranty_expiry_date = models.DateField(blank=True, null=True)
purchase_type = models.CharField(max_length=45, blank=True, null=True)
description = models.TextField(blank=True, null=True)
is_assigned = models.BooleanField(default=False)
product = models.ForeignKey(Product, models.PROTECT, blank=True, null=True)
vendor = models.ForeignKey(Vendor, models.PROTECT, blank=True, null=True)
location = models.ForeignKey(Location, models.DO_NOTHING, blank=True, null=True)
organization = models.ForeignKey(Organization, models.DO_NOTHING, blank=True, null=True)
history = HistoricalRecords()
@classmethod
def total_asset_cost(self):
return self.objects.all().aggregate(total_cost=Sum('price')).get('total_cost',0)
def __str__(self):
return f'{self.name} ({self.serial_no})'
class AssignAsset(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
asset = models.ForeignKey(Asset, models.DO_NOTHING, blank=True, null=True)
user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True)
+195
View File
@@ -0,0 +1,195 @@
from django.test import TestCase
from dashboard.models import Organization,Address,Location,ProductType,ProductCategory,Department
from vendors.models import Vendor
from products.models import Product
from .models import Asset
# Create your tests here.
class Asseto_test(TestCase):
def setUp(self):
user_address=Address.objects.create(
address_line_one = "Address line 1",
address_line_two = "Address line 2",
country = "India",
state="West Bengal",
city = "Kolkata",
pin_code = "700018",
)
user_organization = Organization.objects.create(
name="Organization 1",
website="asseto.com",
phone="1234567890",
email="asseto@asseto.com",
currency="INR",
date_format="dd-mm-yyyy",
logo = "logo.png"
)
user_vendor=Vendor.objects.create(
name = "Vendor 1",
email = "vendor1@asseto.com",
phone = "7896321454",
contact_person = "Person 1",
designation = "Designation 1",
gstin_number = "1234567890",
description = "Description 1",
address= user_address,
organization = user_organization
)
product_category=ProductCategory.objects.create(
name="Category 1",
organization=user_organization,
)
product_type=ProductType.objects.create(
name="Type 1",
organization=user_organization,
)
user_product=Product.objects.create(
name = "Product 1",
product_picture = "test.jpg",
manufacturer = "Manufacturer 1",
description = "Description 1",
product_category = product_category,
product_type = product_type,
organization = user_organization
)
user_location=Location.objects.create(
office_name = "Office 1",
address = user_address,
contact_person_name = "Person 1",
contact_person_email = "person1@asseto.com",
contact_person_phone = "1234567890",
organization = user_organization,
)
self.asset=Asset.objects.create(
name = "Asset 1",
serial_no = "1234567890",
description = "Description 1",
location = user_location,
organization = user_organization,
product=user_product,
vendor=user_vendor,
price = 1000.00,
purchase_date = "2020-01-01",
warranty_expiry_date = "2021-01-01",
purchase_type = "Warranty",
is_assigned = False,
)
def test_asset(self):
print("Asset Testing Start")
asset = Asset.objects.get(name="Asset 1")
self.assertEqual(asset.name, "Asset 1")
self.assertEqual(asset.serial_no, "1234567890")
self.assertEqual(asset.description, "Description 1")
self.assertEqual(asset.price, 1000.00)
# self.assertEqual(asset.purchase_date, "2020-01-01")
# self.assertEqual(asset.warranty_expiry_date, "2021-01-01")
self.assertEqual(asset.purchase_type, "Warranty")
self.assertEqual(asset.is_assigned, False)
self.assertEqual(asset.location.office_name, "Office 1")
self.assertEqual(asset.location.address.address_line_one, "Address line 1")
self.assertEqual(asset.location.address.address_line_two, "Address line 2")
self.assertEqual(asset.location.address.country, "India")
self.assertEqual(asset.location.address.state, "West Bengal")
self.assertEqual(asset.location.address.city, "Kolkata")
self.assertEqual(asset.organization.name, "Organization 1")
self.assertEqual(asset.location.contact_person_name, "Person 1")
self.assertEqual(asset.location.contact_person_email, "person1@asseto.com")
self.assertEqual(asset.location.contact_person_phone, "1234567890")
self.assertEqual(asset.product.name, "Product 1")
self.assertEqual(asset.product.product_picture, "test.jpg")
self.assertEqual(asset.product.manufacturer, "Manufacturer 1")
self.assertEqual(asset.product.description, "Description 1")
self.assertEqual(asset.product.product_category.name, "Category 1")
self.assertEqual(asset.product.product_type.name, "Type 1")
self.assertEqual(asset.vendor.email, "vendor1@asseto.com")
self.assertEqual(asset.vendor.name, "Vendor 1")
self.assertEqual(asset.vendor.phone, "7896321454")
self.assertEqual(asset.vendor.contact_person, "Person 1")
self.assertEqual(asset.vendor.designation, "Designation 1")
self.assertEqual(asset.vendor.gstin_number, "1234567890")
self.assertEqual(asset.vendor.description, "Description 1")
print("Asset Testing Successful\n")
def edit_asset(self):
print("Asset Edit Testing Start")
self.asset.name = "Asset 2"
self.asset.serial_no = "1234567892"
self.asset.description = "Description 2"
self.asset.location.office_name = "Office 2"
self.asset.organization.name = "Organization 2"
self.asset.organization.website = "asseto2.com"
self.asset.organization.phone = "1234567892"
self.asset.organization.email = "asseto@asseto2.com"
self.asset.organization.currency = "INR"
self.asset.organization.date_format = "dd-mm-yyyy"
self.asset.organization.logo = "logo2.png"
self.asset.product.name = "Product 2"
self.asset.product.product_picture = "test2.jpg"
self.asset.product.manufacturer = "Manufacturer 2"
self.asset.product.description = "Description 2"
self.asset.product.product_category.name = "Category 2"
self.asset.product.product_type.name = "Type 2"
self.asset.vendor.name = "Vendor 2"
self.asset.vendor.email = "vendor2@asseto.com"
self.asset.vendor.phone = "7896321452"
self.asset.vendor.contact_person = "Person 2"
self.asset.vendor.designation = "Designation 2"
self.asset.vendor.gstin_number = "1234567892"
self.asset.vendor.description = "Description 2"
self.asset.price = 1002.00
self.asset.purchase_date = "2020-01-02"
self.asset.warranty_expiry_date = "2021-01-02"
self.asset.purchase_type = "Warranty"
self.asset.is_assigned = False
self.asset.save()
self.assertEqual(self.asset.name, "Asset 2")
self.assertEqual(self.asset.serial_no, "1234567892")
self.assertEqual(self.asset.description, "Description 2")
self.assertEqual(self.asset.location.office_name, "Office 2")
self.assertEqual(self.asset.organization.name, "Organization 2")
self.assertEqual(self.asset.organization.website, "asseto2.com")
self.assertEqual(self.asset.organization.phone, "1234567892")
self.assertEqual(self.asset.organization.email, "asseto@asseto2.com")
self.assertEqual(self.asset.organization.currency, "INR")
self.assertEqual(self.asset.organization.date_format, "dd-mm-yyyy")
self.assertEqual(self.asset.organization.logo, "logo2.png")
self.assertEqual(self.asset.location.contact_person_name, "Person 2")
self.assertEqual(self.asset.location.contact_person_email, "person2@asseto.com")
self.assertEqual(self.asset.location.contact_person_phone, "1234567892")
self.assertEqual(self.asset.product.name, "Product 2")
self.assertEqual(self.asset.product.product_picture, "test2.jpg")
self.assertEqual(self.asset.product.manufacturer, "Manufacturer 2")
self.assertEqual(self.asset.product.description, "Description 2")
self.assertEqual(self.asset.product.product_category.name, "Category 2")
self.assertEqual(self.asset.product.product_type.name, "Type 2")
self.assertEqual(self.asset.vendor.name, "Vendor 2")
self.assertEqual(self.asset.vendor.email, "vendor2@asseto.com")
self.assertEqual(self.asset.vendor.phone, "7896321452")
self.assertEqual(self.asset.vendor.contact_person, "Person 2")
self.assertEqual(self.asset.vendor.designation, "Designation 2")
self.assertEqual(self.asset.vendor.gstin_number, "1234567892")
self.assertEqual(self.asset.vendor.description, "Description 2")
self.assertEqual(self.asset.price, 1002.00)
self.assertEqual(self.asset.purchase_date, "2020-01-02")
self.assertEqual(self.asset.warranty_expiry_date, "2021-01-02")
self.assertEqual(self.asset.purchase_type, "Warranty")
self.assertEqual(self.asset.is_assigned, False)
print("Asset Edit Testing Successful\n")
def delete_asset(self):
print("Asset Delete Testing Start")
self.asset.delete()
with self.assertRaises(Asset.DoesNotExist):
Asset.objects.get(id=self.asset.id)
location=Location.objects.get(id=self.asset.location.id)
organization=Organization.objects.get(id=self.asset.organization.id)
vendor=Vendor.objects.get(id=self.asset.vendor.id)
product=Product.objects.get(id=self.asset.product.id)
self.assertIsNotNone(location)
self.assertIsNotNone(organization)
self.assertIsNotNone(vendor)
self.assertIsNotNone(product)
print("Asset Delete Testing Successful\n")
+19
View File
@@ -0,0 +1,19 @@
from django.urls import path
from . import views
app_name = 'assets'
urlpatterns = [
path('list', views.list, name='list'),
path('details/<uuid:id>', views.details, name='details'),
path('update/<uuid:id>', views.update, name='update'),
path('delete/<uuid:id>', views.delete, name='delete'),
path('status/<uuid:id>', views.status, name='status'),
path('add', views.add, name='add'),
path('search/<str:page>', views.search, name='search'),
path('assigned-list', views.assigned_list, name='assigned_list'),
path('assign-asset', views.assign_asset, name='assign_asset'),
path('reassign-asset/<uuid:id>', views.reassign_asset, name='reassign_asset'),
path('delete-assign/<uuid:id>', views.delete_assign, name='delete_assign'),
path('assign_asset_search/<str:page>', views.assign_asset_search, name='assign_asset_search'),
]
+308
View File
@@ -0,0 +1,308 @@
from django.shortcuts import render, redirect
from .forms import AssetForm, AssignedAssetForm, ReassignedAssetForm
from django.contrib import messages
from .models import Asset, AssetSpecification, AssignAsset
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.db.models import Q
PAGE_SIZE = 10
ORPHANS = 1
def check_admin(user):
return user.is_superuser
def manage_access_for_assets(user):
permissions_list = [
'authentication.edit_asset',
'authentication.view_asset',
'authentication.delete_asset',
'authentication.add_asset',
]
for permission in permissions_list:
if user.has_perm(permission):
return True
return False
def manage_access_for_assign_assets(user):
permissions_list = [
'authentication.reassign_assign_asset',
'authentication.add_assign_asset',
'authentication.delete_assign_asset',
]
for permission in permissions_list:
if user.has_perm(permission):
return True
return False
@login_required
@user_passes_test(manage_access_for_assets)
def list(request):
asset_list = Asset.undeleted_objects.filter(
organization=request.user.organization).order_by('-created_at')
paginator = Paginator(asset_list, PAGE_SIZE, orphans=ORPHANS)
page_number = request.GET.get('page')
page_object = paginator.get_page(page_number)
asset_form = AssetForm(organization=request.user.organization)
assign_asset_form = AssignedAssetForm(
organization=request.user.organization)
reassign_asset_form = ReassignedAssetForm(
organization=request.user.organization)
context = {
'sidebar': 'assets',
'submenu': 'list',
'page_object': page_object,
'asset_form': asset_form,
'assign_asset_form': assign_asset_form,
'reassign_asset_form': reassign_asset_form,
'title': 'Assets'
}
return render(request, 'assets/list.html', context=context)
@login_required
@permission_required('authentication.view_asset')
def details(request, id):
asset = get_object_or_404(
Asset.undeleted_objects, pk=id, organization=request.user.organization)
assetSpecifications = AssetSpecification.objects.filter(asset=asset)
history_list = asset.history.all()
paginator = Paginator(history_list, 5, orphans=1)
page_number = request.GET.get('page')
page_object = paginator.get_page(page_number)
context = {'sidebar': 'assets', 'asset': asset, 'submenu': 'list', 'page_object': page_object,
'assetSpecifications': assetSpecifications, 'title': 'Asset - Details'}
return render(request, 'assets/detail.html', context=context)
@login_required
@permission_required('authentication.edit_asset')
def update(request, id):
asset = get_object_or_404(
Asset.undeleted_objects, pk=id, organization=request.user.organization)
assetSpecifications = AssetSpecification.objects.filter(asset=asset)
form = AssetForm(request.POST or None, instance=asset,
organization=request.user.organization)
if request.method == "POST":
if form.is_valid():
assetSpecifications.delete()
specifications_names = request.POST.getlist(
'specifications_name')
specifications_values = request.POST.getlist(
'specifications_value')
for name, value in zip(specifications_names, specifications_values):
if name != '' or value != '':
AssetSpecification.objects.create(
asset=asset, name=name, value=value)
asset = form.save(commit=False)
asset.organization = request.user.organization
asset.save()
messages.success(request, 'Asset updated successfully')
return redirect('assets:list')
context = {
'sidebar': 'assets',
'submenu': 'list',
'form': form,
'asset': asset,
'assetSpecifications': assetSpecifications,
'title': 'Asset - Update'
}
return render(request, 'assets/update-assets.html', context=context)
@login_required
@permission_required('authentication.add_asset')
def add(request):
form = AssetForm(request.POST or None,
organization=request.user.organization)
if request.method == "POST":
if form.is_valid():
asset = form.save(commit=False)
asset.organization = request.user.organization
asset.save()
specifications_names = request.POST.getlist(
'specifications_name')
specifications_values = request.POST.getlist(
'specifications_value')
for name, value in zip(specifications_names, specifications_values):
if name != '' or value != '':
AssetSpecification.objects.create(
asset=asset, name=name, value=value)
messages.success(request, 'Asset added successfully')
return redirect('assets:list')
context = {
'sidebar': 'assets',
'submenu': 'add',
'form': form,
'title': 'Assets - Add'
}
return render(request, 'assets/add.html', context=context)
@login_required
@permission_required('authentication.delete_asset')
def delete(request, id):
if request.method == "POST":
asset = get_object_or_404(
Asset.undeleted_objects, pk=id, organization=request.user.organization)
if asset.is_assigned:
messages.error(
request, 'Error! Asset is assigned to a user')
else:
asset.soft_delete()
history_id = asset.history.first().history_id
asset.history.filter(pk=history_id).update(history_type='-')
messages.success(request, 'Asset deleted successfully.')
return redirect('assets:list')
@user_passes_test(check_admin)
def status(request, id):
if request.method == "POST":
asset = get_object_or_404(
Asset.undeleted_objects, pk=id, organization=request.user.organization)
asset.status = False if asset.status else True
asset.save()
return HttpResponse(status=204)
@login_required
def search(request, page):
search_text = request.GET.get('search_text').strip()
if search_text:
return render(request, 'assets/assets-data.html', {
'page_object': Asset.undeleted_objects.filter(Q(organization=request.user.organization) & (Q(
name__icontains=search_text) | Q(serial_no__icontains=search_text) | Q(purchase_type__icontains=search_text) | Q(product__name__icontains=search_text)
| Q(vendor__name__icontains=search_text) | Q(vendor__gstin_number__icontains=search_text) | Q(location__office_name__icontains=search_text) | Q(product__product_type__name__icontains=search_text)
)).order_by('-created_at')[:10]
})
asset_list = Asset.undeleted_objects.filter(
organization=request.user.organization).order_by('-created_at')
paginator = Paginator(asset_list, PAGE_SIZE, orphans=ORPHANS)
page_number = page
page_object = paginator.get_page(page_number)
return render(request, 'assets/assets-data.html', {'page_object': page_object})
@login_required
@user_passes_test(manage_access_for_assign_assets)
def assigned_list(request):
assign_asset_list = AssignAsset.objects.filter(
asset__organization=request.user.organization).order_by('-asset__created_at')
paginator = Paginator(assign_asset_list, PAGE_SIZE, orphans=ORPHANS)
page_number = request.GET.get('page')
page_object = paginator.get_page(page_number)
context = {
'sidebar': 'assets',
'submenu': 'assigned-assets',
'page_object': page_object,
'title': 'Assigned Assets'
}
return render(request, 'assets/assigned-list.html', context=context)
@login_required
@permission_required('authentication.add_assign_asset')
def assign_asset(request):
form = AssignedAssetForm(request.POST or None,
organization=request.user.organization)
if request.method == 'POST':
if form.is_valid():
form.instance.asset.is_assigned = True
form.instance.asset.save()
form.save()
messages.success(request, 'Asset assigned to user successfully')
return HttpResponse(status=204)
context = {'form': form}
return render(request, 'assets/assign-asset-modal.html', context=context)
@login_required
@permission_required('authentication.reassign_assign_asset')
def reassign_asset(request, id):
assignAsset = get_object_or_404(
AssignAsset, pk=id, asset__organization=request.user.organization)
form = ReassignedAssetForm(
request.POST or None, instance=assignAsset, organization=request.user.organization)
if request.method == 'POST':
if form.is_valid():
form.save()
messages.success(
request, 'Asset re-assigned successfully')
return HttpResponse(status=204)
context = {'form': form}
return render(request, 'assets/reassign-asset-modal.html', context=context)
@login_required
@permission_required('authentication.delete_assign_asset')
def delete_assign(request, id):
if request.method == 'POST':
assignAsset = get_object_or_404(
AssignAsset, pk=id, asset__organization=request.user.organization)
assignAsset.delete()
assignAsset.asset.is_assigned = False
assignAsset.asset.save()
messages.success(request, 'Asset unassigned successfully')
return redirect('assets:assigned_list')
@login_required
def assign_asset_search(request, page):
search_text = request.GET.get('search_text').strip()
if search_text:
return render(request, 'assets/assigned-assets-data.html', {
'page_object': AssignAsset.objects.filter(Q(asset__organization=request.user.organization) & (Q(
asset__name__icontains=search_text) | Q(asset__serial_no__icontains=search_text) | Q(user__full_name__icontains=search_text) | Q(user__department__name__icontains=search_text)
)).order_by('-asset__created_at')[:10]
})
asset_list = AssignAsset.objects.filter(
asset__organization=request.user.organization).order_by('-asset__created_at')
paginator = Paginator(asset_list, PAGE_SIZE, orphans=ORPHANS)
page_number = page
page_object = paginator.get_page(page_number)
return render(request, 'assets/assigned-assets-data.html', {'page_object': page_object})
+1
View File
@@ -0,0 +1 @@
default_app_config = 'authentication.apps.AuthenticationConfig'
+10
View File
@@ -0,0 +1,10 @@
from django.contrib import admin
from .models import User
# Register your models here.
@admin.register(User)
class SupportAdmin(admin.ModelAdmin):
list_display = ['full_name', 'email', 'role',
'organization', 'is_active', 'is_deleted', 'created_at']
+9
View File
@@ -0,0 +1,9 @@
from django.apps import AppConfig
class AuthenticationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'authentication'
def ready(self):
import authentication.signals
+11
View File
@@ -0,0 +1,11 @@
from django.contrib.auth import authenticate
from django.contrib import messages
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper(request,*args,**kwargs):
if request.user.is_authenticated:
return redirect('/')
else:
return view_func(request,*args,**kwargs)
return wrapper
+200
View File
@@ -0,0 +1,200 @@
from django import forms
from .models import User
from dashboard.models import Organization, Location
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm
from smart_selects.form_fields import ChainedModelChoiceField
from django.forms import URLField
from django.core.exceptions import ValidationError
class UserRegisterForm(UserCreationForm):
full_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Full name', 'autofocus': True}))
email = forms.EmailField(max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
username = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Username'}))
phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Phone'}))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Password'})
self.fields['password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Confirm password'})
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already registered with us')
return email.lower()
def clean_username(self):
username = self.cleaned_data.get('username')
return username.lower()
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
raise forms.ValidationError('Username already taken')
return username
def clean_full_name(self):
full_name = self.cleaned_data.get('full_name')
return full_name.title()
class Meta:
model = User
fields = ['full_name', 'email', 'username',
'phone', 'password1', 'password2']
class OrganizationForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Company Name'}))
website = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Company Website'}))
def clean_name(self):
name = self.cleaned_data.get('name')
return name.title()
def clean_website(self):
url = self.cleaned_data.get('website')
url_form_field = URLField()
try:
url = url_form_field.clean(url)
except ValidationError:
raise forms.ValidationError(
'This is not a valid website name.')
return url.lower()
class Meta:
model = Organization
fields = ['name', 'website']
class UserLoginForm(forms.Form):
email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
password = forms.CharField(required=True, widget=forms.PasswordInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Password'}))
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
class UserPasswordChangeForm(PasswordChangeForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['old_password'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Old password'})
self.fields['new_password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'New password'})
self.fields['new_password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Confirm password'})
class UserPasswordResetRequestForm(PasswordResetForm):
def __init__(self, *args, **kwargs):
super(UserPasswordResetRequestForm, self).__init__(*args, **kwargs)
email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
def clean_email(self):
email = self.cleaned_data.get('email')
if not User.objects.filter(email=email.lower(), is_active=True).exists():
raise forms.ValidationError(
'There is no user registered with the specified email address!')
return email.lower()
class UserPasswordResetForm(SetPasswordForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['new_password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'New password'})
self.fields['new_password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Confirm password'})
class UserUpdateForm(forms.ModelForm):
full_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Full name', 'autofocus': True}))
email = forms.EmailField(max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Email'}))
phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Phone'}))
profile_pic = forms.ImageField(
required=False,
widget=forms.FileInput(
attrs={'class': 'form-control', 'id': 'inputFile'}
))
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
def clean_full_name(self):
full_name = self.cleaned_data.get('full_name')
return full_name.title()
class Meta:
model = User
fields = ['full_name', 'email', 'phone', 'profile_pic']
class OrganizationUpdateForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Name'}))
website = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Website'}))
email = forms.EmailField(required=False, max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Email'}))
phone = forms.IntegerField(required=False, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Phone'}))
currency = forms.CharField(required=False, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Currency'}))
date_format = forms.CharField(required=False, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Date Format'}))
logo = forms.ImageField(required=False, widget=forms.FileInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'id': 'inputFile'}))
def clean_name(self):
name = self.cleaned_data.get('name')
return name.title()
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
def clean_currency(self):
currency = self.cleaned_data.get('currency')
return currency.upper()
def clean_website(self):
url = self.cleaned_data.get('website')
url_form_field = URLField()
try:
url = url_form_field.clean(url)
except ValidationError:
raise forms.ValidationError(
'This is not a valid website.')
return url.lower()
class Meta:
model = Organization
fields = ['name', 'website', 'email', 'phone',
'currency', 'date_format', 'logo']
+73
View File
@@ -0,0 +1,73 @@
# Generated by Django 3.2 on 2022-05-27 06:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('dashboard', '0001_initial'),
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=255, unique=True)),
('full_name', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('profile_pic', models.ImageField(blank=True, null=True, upload_to='profile_pics')),
('employee_id', models.CharField(blank=True, max_length=45, null=True)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location')),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Role',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='UserRole',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('role', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='authentication.role')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
@@ -0,0 +1,24 @@
# Generated by Django 3.2 on 2022-06-17 06:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Register',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('email', models.EmailField(max_length=50)),
('username', models.CharField(max_length=30)),
('pass1', models.CharField(max_length=30)),
('pass2', models.CharField(max_length=30)),
],
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-06-21 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0002_register'),
]
operations = [
migrations.DeleteModel(
name='Register',
),
migrations.AddField(
model_name='user',
name='username',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,33 @@
# Generated by Django 3.2 on 2022-06-21 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0003_auto_20220621_1344'),
]
operations = [
migrations.AlterField(
model_name='role',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='role',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='userrole',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='userrole',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-07-02 18:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0004_auto_20220621_1350'),
]
operations = [
migrations.AlterField(
model_name='user',
name='is_active',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-07-05 18:59
from django.db import migrations
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0005_alter_user_is_active'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=smart_selects.db_fields.ChainedForeignKey(auto_choose=True, blank=True, chained_field='organization', chained_model_field='organization', null=True, on_delete=django.db.models.deletion.CASCADE, to='dashboard.location'),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-07-05 19:10
from django.db import migrations
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0006_alter_user_location'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=smart_selects.db_fields.ChainedForeignKey(auto_choose=True, blank=True, chained_field='organization', chained_model_field='name', null=True, on_delete=django.db.models.deletion.CASCADE, to='dashboard.location'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-07-05 19:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0007_alter_user_location'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-26 06:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0008_alter_user_location'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='profile_pic',
new_name='profile_picture',
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-26 06:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0009_rename_profile_pic_user_profile_picture'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='profile_picture',
new_name='profile_pic',
),
]
@@ -0,0 +1,51 @@
# Generated by Django 3.2 on 2022-10-17 11:11
import authentication.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0015_delete_employee'),
('roles', '0001_initial'),
('authentication', '0010_rename_profile_picture_user_profile_pic'),
]
operations = [
migrations.RemoveField(
model_name='userrole',
name='role',
),
migrations.RemoveField(
model_name='userrole',
name='user',
),
migrations.AddField(
model_name='user',
name='access_level',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='user',
name='department',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.department'),
),
migrations.AddField(
model_name='user',
name='role',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='role', to='roles.role'),
),
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, null=True, upload_to=authentication.models.path_and_rename),
),
migrations.DeleteModel(
name='Role',
),
migrations.DeleteModel(
name='UserRole',
),
]
@@ -0,0 +1,24 @@
# Generated by Django 3.2 on 2022-10-18 10:15
import authentication.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0011_auto_20221017_1111'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, default='profile_pics/default.jpg', null=True, upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,19 @@
# Generated by Django 3.2 on 2022-10-18 10:22
import authentication.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0012_auto_20221018_1015'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, null=True, upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,40 @@
# Generated by Django 3.2 on 2022-10-18 10:30
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('authentication', '0013_alter_user_profile_pic'),
]
operations = [
migrations.AddField(
model_name='user',
name='created_at',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='user',
name='status',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='updated_at',
field=models.DateTimeField(auto_now=True),
),
migrations.AddField(
model_name='user',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-10-19 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0014_auto_20221018_1030'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')]),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-10-20 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0015_alter_user_access_level'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-11-02 06:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0016_user_is_deleted'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')], default=False),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-12-09 07:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0015_delete_employee'),
('authentication', '0017_alter_user_access_level'),
]
operations = [
migrations.AddField(
model_name='user',
name='address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.address'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-12-13 07:50
import authentication.models
from django.db import migrations
import django_resized.forms
class Migration(migrations.Migration):
dependencies = [
('authentication', '0018_user_address'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_pic',
field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', keep_meta=True, null=True, quality=75, scale=None, size=[1024, 768], upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2023-01-04 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0019_alter_user_profile_pic'),
]
operations = [
migrations.AlterField(
model_name='user',
name='status',
field=models.BooleanField(default=True),
),
]
@@ -0,0 +1,60 @@
# Generated by Django 3.2 on 2023-01-05 06:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid
class Migration(migrations.Migration):
dependencies = [
('roles', '0003_alter_role_status'),
('dashboard', '0018_auto_20230104_1455'),
('authentication', '0020_alter_user_status'),
]
operations = [
migrations.CreateModel(
name='HistoricalUser',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('email', models.EmailField(db_index=True, max_length=255)),
('username', models.CharField(blank=True, max_length=255, null=True)),
('full_name', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('profile_pic', models.TextField(blank=True, max_length=100, null=True)),
('employee_id', models.CharField(blank=True, max_length=45, null=True)),
('is_active', models.BooleanField(default=False)),
('is_staff', models.BooleanField(default=False)),
('access_level', models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')], default=False)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('address', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.address')),
('department', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.department')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('location', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.location')),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
('role', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='roles.role')),
],
options={
'verbose_name': 'historical user',
'verbose_name_plural': 'historical users',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
+91
View File
@@ -0,0 +1,91 @@
import uuid
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, Permission
from django.contrib.contenttypes.models import ContentType
from dashboard.models import Organization, Location, Address, Department, TimeStampModel, SoftDeleteModel
from django.conf import settings
from roles.models import Role
import os
from uuid import uuid4
from django_resized import ResizedImageField
from simple_history.models import HistoricalRecords
def path_and_rename(instance, filename):
upload_to = 'profile/'
ext = filename.split('.')[-1]
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(upload_to, filename)
class UserManager(BaseUserManager):
def create_user(self, email, full_name, username, phone, password, **extra_fields):
if not email:
raise ValueError('Users must have an email address.')
user = self.model(email=self.normalize_email(email), full_name=full_name,username=username, phone=phone, **extra_fields)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def create_superuser(self, email, full_name, username, phone, password, **extra_fields):
user = self.create_user(email, full_name, username, phone, password, is_active = True, access_level=True, **extra_fields)
# Create or get the Superuser default
organization = Organization.objects.filter(name='DjangoSuperUserOrganization').first()
if not organization:
organization = Organization.objects.create(name='DjangoSuperUserOrganization')
role = Role.objects.filter(related_name='Superuser', organization=organization).first()
if not role:
role = Role.objects.create(
name = "all_permissions",
related_name='Superuser',
organization=organization
)
if role.permissions.count() == 0:
all_permisisons = Permission.objects.all()
for permission in all_permisisons:
role.permissions.add(permission)
role.save()
user.role = role
user.save(using=self._db)
return user
BOOL_CHOICES = ((False, 'Only Assigned'), (True, 'All'))
class User(AbstractBaseUser, PermissionsMixin, TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=255 , blank=True, null=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
phone = models.CharField(max_length=255, blank=True, null=True)
profile_pic = ResizedImageField(upload_to=path_and_rename, blank=True, null=True)
employee_id = models.CharField(max_length=45, blank=True, null=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
organization = models.ForeignKey(Organization, models.DO_NOTHING, blank=True, null=True)
address = models.ForeignKey(Address, models.DO_NOTHING, blank=True, null=True)
location = models.ForeignKey(Location, models.DO_NOTHING, blank=True, null=True)
department = models.ForeignKey(Department, models.DO_NOTHING, blank=True, null=True)
access_level = models.BooleanField(choices=BOOL_CHOICES,default=False)
role = models.ForeignKey(Role, models.DO_NOTHING, related_name='role', blank=True, null=True)
objects = UserManager()
history = HistoricalRecords()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name', 'phone', 'username']
def __str__(self):
return f'{self.full_name} ({self.role})'
+66
View File
@@ -0,0 +1,66 @@
from django.db.models.signals import post_save, post_init
from django.dispatch import receiver
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.core.mail import send_mail
from authentication.token import account_activation_token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def send_verification_mail(sender, instance, created, **kwargs):
if created and not instance.is_active:
url = settings.LOCALHOST_URL if settings.DEBUG else settings.DEV_URL
subject = 'Account activation mail for Asset Management'
message_html = render_to_string('auth/verification/account_activation_email.html', {
'user': instance,
'url': url,
'uid': urlsafe_base64_encode(force_bytes(instance.pk)),
'token': account_activation_token.make_token(instance)
})
send_mail(
subject,
'User activation email',
'Asset Management <noreply@assetmanagement.com>',
[instance.email],
html_message=message_html,
fail_silently=False,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def post_save(sender, instance, created, **kwargs):
if instance.previous_email != instance.email and not created:
sender.objects.filter(pk=instance.pk).update(is_active=False)
user = sender.objects.get(pk=instance.pk)
url = settings.LOCALHOST_URL if settings.DEBUG else settings.DEV_URL
subject = 'Account re-activation mail for Asset Management'
message_html = render_to_string('auth/verification/account_re_activation_email.html', {
'user': instance,
'url': url,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user)
})
send_mail(
subject,
'User activation email',
'Asset Management <noreply@assetmanagement.com>',
[user.email],
html_message=message_html,
fail_silently=False,
)
@receiver(post_init, sender=settings.AUTH_USER_MODEL)
def remember_state(sender, instance, **kwargs):
instance.previous_email = instance.email
+237
View File
@@ -0,0 +1,237 @@
from django.test import TestCase
from django.contrib.auth import get_user_model
from dashboard.models import Organization,Address,Location,Department
from roles.models import Role
from authentication.models import User
from vendors.models import Vendor
import uuid
# Create your tests here.
class User_Test(TestCase):
def setUp(self):
self.user_organization = Organization.objects.create(
name="Organization 1",
website="asseto.com",
phone="1234567890",
email="asseto@asseto.com",
currency="INR",
date_format="dd-mm-yyyy",
logo = "logo.png"
)
self.user_address=Address.objects.create(
country = "India",
state = "Rajasthan",
address_line_one = "testline 1",
address_line_two = "testline 2",
city = "Jaipur",
pin_code = "302001"
)
self.user_role=Role.objects.create(
related_name= "Role 1",
organization=self.user_organization,
)
self.user_location=Location.objects.create(
office_name = "Office 1",
address = self.user_address,
contact_person_name = "Person 1",
contact_person_email = "person1@asseto.com",
contact_person_phone = "1234567890",
organization = self.user_organization
)
self.user_department=Department.objects.create(
name="Department 1",
organization=self.user_organization,
contact_person_name = "Person 1",
contact_person_email = "person1@asseto.com",
contact_person_phone = "1234567890",
)
self.user=User.objects.create(
email = "mail@gmail.com",
username = 'usertest',
full_name = 'test',
phone = '1234567890',
role = self.user_role,
organization = self.user_organization,
address= self.user_address,
location=self.user_location,
department=self.user_department,
profile_pic="test.jpg",
employee_id="1234",
is_active=True,
is_staff=True,
access_level=1
)
self.edit_user_organization = Organization.objects.create(
name="Organization 2",
website="asseto2.com",
phone="123456789",
email="asseto@asseto2.com",
currency="INR2",
date_format="dd-mm-yyyy",
logo = "logo2.png"
)
self.edit_user_address=Address.objects.create(
country = "India",
state = "West Bengal",
address_line_one = "testline 11",
address_line_two = "testline 21",
city = "Kolkata",
pin_code = "700018"
)
# self.edit_user_role=Role.objects.create(
# related_name= "Role 2",
# organization=self.edit_user_organization,
# )
self.edit_user_location=Location.objects.create(
office_name = "Office 2",
address = self.edit_user_address,
contact_person_name = "Person 2",
contact_person_email = "person2@asseto.com",
contact_person_phone = "1234567899",
organization = self.edit_user_organization
)
self.edit_user_department=Department.objects.create(
name="Department 2",
organization=self.edit_user_organization,
contact_person_name = "Person 2",
contact_person_email = "person2@asseto.com",
contact_person_phone = "1234567899",
)
self.edit_user=User.objects.create(
email = "mail2@gmail.com",
username = 'usertest2',
full_name = 'test2',
phone = '1234567899',
role = self.user_role,
organization = self.edit_user_organization,
address= self.edit_user_address,
location= self.edit_user_location,
department= self.edit_user_department,
profile_pic="test2.jpg",
employee_id="12342",
is_active=True,
is_staff=True,
access_level=0
)
def test_user(self):
print("User Testing Start")
# self.user = User.objects.get(email = "mail@gmail.com")
self.assertEqual(self.user.full_name, "test")
self.assertEqual(self.user.username, "usertest")
self.assertEqual(self.user.profile_pic, "test.jpg")
self.assertEqual(self.user.phone, "1234567890")
self.assertEqual(self.user.employee_id, "1234")
self.assertEqual(self.user.is_active, True)
self.assertEqual(self.user.is_staff, True)
self.assertEqual(self.user.access_level, 1)
self.assertEqual(self.user.address.address_line_one, "testline 1")
self.assertEqual(self.user.address.address_line_two, "testline 2")
self.assertEqual(self.user.address.city, "Jaipur")
self.assertEqual(self.user.address.pin_code, "302001")
self.assertEqual(self.user.address.state, "Rajasthan")
self.assertEqual(self.user.address.country, "India")
self.assertEqual(self.user.location.office_name, "Office 1")
# self.assertEqual(user.location.contact_person_name, "Person 1")
# self.assertEqual(user.location.contact_person_email, "person1@asseto.com")
# self.assertEqual(user.location.contact_person_phone, "1234567890")
self.assertEqual(self.user.role.related_name, "Role 1")
self.assertEqual(self.user.department.name, "Department 1")
self.assertEqual(self.user.department.contact_person_name, "Person 1")
self.assertEqual(self.user.department.contact_person_email, "person1@asseto.com")
self.assertEqual(self.user.department.contact_person_phone, "1234567890")
self.assertEqual(self.user.organization.name, "Organization 1")
self.assertEqual(self.user.organization.website, "asseto.com")
self.assertEqual(self.user.organization.phone, "1234567890")
self.assertEqual(self.user.organization.email, "asseto@asseto.com")
self.assertEqual(self.user.organization.currency, "INR")
self.assertEqual(self.user.organization.date_format, "dd-mm-yyyy")
self.assertEqual(self.user.organization.logo, "logo.png")
print("User Testing Successful\n")
def test_edit_user(self):
# user = User.objects.get(email="mail2@gmail.com")
print("User Edit Testing Start")
self.user.username = "usertest2"
self.user.full_name = "test2"
self.user.phone = "1234567890"
self.user.profile_pic = "test2.jpg"
self.user.employee_id = "12342"
self.user.is_active = True
self.user.is_staff = True
self.user.access_level = 0
self.user.organization.name = "Organization 2"
self.user.organization.website = "asseto2.com"
self.user.organization.phone = "123456789"
self.user.organization.email = "asseto@asseto2.com"
self.user.organization.currency = "INR2"
self.user.organization.date_format = "dd-mm-yyyy"
self.user.organization.logo = "logo2.png"
self.user.address.country = "India"
self.user.address.state = "West Bengal"
self.user.address.address_line_one = "testline 11"
self.user.address.address_line_two = "testline 21"
self.user.address.city = "Kolkata"
self.user.address.pin_code = "700018"
self.user.location.office_name = "Office 2"
self.user.location.contact_person_name = "Person 2"
self.user.location.contact_person_email = "person2@asseto.com"
self.user.location.contact_person_phone = "1234567890"
self.user.department.name = "Department 2"
self.user.department.contact_person_name = "Person 2"
self.user.department.contact_person_email = "person2@asseto.com"
self.user.department.contact_person_phone = "1234567890"
self.user.save()
self.assertEqual(self.user.username, "usertest2")
self.assertEqual(self.user.full_name, "test2")
self.assertEqual(self.user.phone, "1234567890")
self.assertEqual(self.user.profile_pic, "test2.jpg")
self.assertEqual(self.user.employee_id, "12342")
self.assertEqual(self.user.is_active, True)
self.assertEqual(self.user.is_staff, True)
self.assertEqual(self.user.access_level, 0)
self.assertEqual(self.user.organization.name, "Organization 2")
self.assertEqual(self.user.organization.website, "asseto2.com")
self.assertEqual(self.user.organization.phone, "123456789")
self.assertEqual(self.user.organization.email, "asseto@asseto2.com")
self.assertEqual(self.user.organization.currency, "INR2")
self.assertEqual(self.user.organization.date_format, "dd-mm-yyyy")
self.assertEqual(self.user.organization.logo, "logo2.png")
self.assertEqual(self.user.address.country, "India")
self.assertEqual(self.user.address.state, "West Bengal")
self.assertEqual(self.user.address.address_line_one, "testline 11")
self.assertEqual(self.user.address.address_line_two, "testline 21")
self.assertEqual(self.user.address.city, "Kolkata")
self.assertEqual(self.user.address.pin_code, "700018")
self.assertEqual(self.user.location.office_name, "Office 2")
self.assertEqual(self.user.location.contact_person_name, "Person 2")
self.assertEqual(self.user.location.contact_person_email, "person2@asseto.com")
self.assertEqual(self.user.location.contact_person_phone, "1234567890")
self.assertEqual(self.user.department.name, "Department 2")
self.assertEqual(self.user.department.contact_person_name, "Person 2")
self.assertEqual(self.user.department.contact_person_email, "person2@asseto.com")
self.assertEqual(self.user.department.contact_person_phone, "1234567890")
print('User Edit Testing Successfuol\n')
def delete_user(self):
print("User Delete Testing Start")
self.user.delete()
# Check if the vendor object is deleted from the database
with self.assertRaises(User.DoesNotExist):
User.objects.get(id=self.product.id)
# Check if the address and organization objects are not affected
address=Address.objects.get(id=self.user.address.id)
location=Location.objects.get(id=self.user.location.id)
organization = Organization.objects.get(name=self.user.organization.id)
department=Department.objects.get(id=self.user.department.id)
role=Role.objects.get(related_name=self.user.role.related_name)
self.assertIsNotNone(location)
self.assertIsNotNone(address)
self.assertIsNotNone(department)
self.assertIsNotNone(organization)
self.assertIsNotNone(role)
print("User Delete Testing Successful\n")
+12
View File
@@ -0,0 +1,12 @@
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return(
text_type(user.pk) + text_type(timestamp) + text_type(user.is_active)
)
account_activation_token = AccountActivationTokenGenerator()
+16
View File
@@ -0,0 +1,16 @@
from django.urls import path
from authentication import views
from django.contrib.auth import views as auth_views
app_name = 'authentication'
urlpatterns = [
path('', views.index, name = 'index'),
path('login', views.user_login, name = 'login'),
path('register', views.user_register, name = 'register'),
path('activate/<uidb64>/<token>', views.activate, name='activate'),
path('profile', views.profile, name='profile'),
path('logout', auth_views.LogoutView.as_view(next_page='authentication:login'), name='logout'),
path('profile-basic-information/update', views.profile_basic_info_update, name='profile_basic_info_update'),
path('organization-information/update', views.organization_info_update, name='organization_info_update'),
]
+226
View File
@@ -0,0 +1,226 @@
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import logout
from django.shortcuts import get_object_or_404
from datetime import datetime, timedelta
from asyncio.log import logger
from django.shortcuts import redirect
from django.shortcuts import render, HttpResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from authentication.forms import (
UserRegisterForm, OrganizationForm, UserPasswordChangeForm, UserLoginForm, UserUpdateForm, OrganizationUpdateForm)
from authentication.decorators import unauthenticated_user
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from authentication.token import account_activation_token
from django.contrib.auth.models import User
from dashboard.forms import LocationForm, AddressForm
from dashboard.models import Location, Address
from django.contrib.auth import get_user_model
from products.models import Product
from vendors.models import Vendor
from assets.models import *
User = get_user_model()
@login_required
def index(request):
all_asset_cost = 0
today = datetime.now()
time_threshold = datetime.now() + timedelta(days=30)
expiring_assets = Asset.undeleted_objects.filter(organization=request.user.organization, warranty_expiry_date__lt=time_threshold).exclude(
warranty_expiry_date__lt=today).order_by('warranty_expiry_date')
all_asset_list = Asset.undeleted_objects.filter(
organization=request.user.organization)
asset_count = all_asset_list.count()
for asset in all_asset_list:
all_asset_cost = all_asset_cost + asset.price
all_product_list = Product.undeleted_objects.filter(
organization=request.user.organization)
latest_product_list = Product.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
product_count = all_product_list.count()
all_vendor_list = Vendor.undeleted_objects.filter(
organization=request.user.organization)
latest_vendor_list = Vendor.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
vendor_count = all_vendor_list.count()
location_list = Location.undeleted_objects.filter(
organization=request.user.organization)
all_location_list = Location.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
location_count = location_list.count()
assign_assets = AssignAsset.objects.filter(
asset__organization=request.user.organization)
assign_assets_counts = assign_assets.count()
unassign_assets_count = asset_count - assign_assets_counts
users_list = User.undeleted_objects.filter(
organization=request.user.organization).exclude(is_superuser=True)
latest_users_list = User.undeleted_objects.filter(organization=request.user.organization).exclude(
is_superuser=True).order_by('created_at').reverse()[0:5]
users_count = users_list.count()
context = {
'sidebar': 'index',
'product_count': product_count,
'vendor_count': vendor_count,
'asset_count': asset_count,
'location_count': location_count,
'all_asset_cost': all_asset_cost,
'latest_vendor_list': latest_vendor_list,
'latest_product_list': latest_product_list,
'all_location_list': all_location_list,
'assign_assets_counts': assign_assets_counts,
'unassign_assets_count': unassign_assets_count,
'latest_users_list': latest_users_list,
'users_count': users_count,
'expiring_assets': expiring_assets,
'title': 'Dashboard'
}
return render(request, 'index.html', context=context)
@unauthenticated_user
def user_login(request):
form = UserLoginForm()
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
messages.success(request, f'Welcome, {user.full_name}')
# redirecting to the requested url
if request.GET.get('next'):
return redirect(request.GET.get('next'))
return redirect('/')
else:
messages.error(request, 'Invalid credentials!')
return render(request, 'auth/login.html', context={'form': form})
@unauthenticated_user
def user_register(request):
u_form = UserRegisterForm()
o_form = OrganizationForm()
if request.method == "POST":
o_form = OrganizationForm(request.POST)
u_form = UserRegisterForm(request.POST)
if o_form.is_valid() and u_form.is_valid():
organization = o_form.save()
user = u_form.save(commit=False)
user.organization = organization
user.is_superuser = True
user.access_level = True
user.save()
messages.success(
request, f'Account for {user.full_name} created successfully. Please verify your email to continue.')
return redirect('authentication:login')
else:
messages.error(request, 'Please correct the below errors.')
return render(request, 'auth/register.html', context={'u_form': u_form, 'o_form': o_form})
@unauthenticated_user
def activate(request, uidb64, token):
User = get_user_model()
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
messages.success(
request, 'Your account verified successfully. You can login now.')
return redirect('authentication:login')
else:
messages.error(request, 'Invalid token.')
return redirect('authentication:login')
@login_required
def profile(request):
context = {'profile': True, 'title': 'Profile'}
return render(request, 'auth/profile.html', context=context)
@login_required
def profile_basic_info_update(request):
user = request.user
old_email = user.email
form = UserUpdateForm(instance=user)
address_form = None
if not user.is_superuser:
address = get_object_or_404(Address, pk=user.address.id)
address_form = AddressForm(request.POST or None, instance=address)
if request.method == "POST":
form = UserUpdateForm(request.POST, request.FILES, instance=user)
if user.is_superuser:
if form.is_valid():
new_email = form.cleaned_data['email']
form.save()
if (old_email) != (new_email):
logout(request)
messages.success(
request, 'Profile updated successfully. and verification mail has been sent to the new email address.')
else:
messages.success(request, 'Profile updated successfully')
return HttpResponse(status=204)
else:
if form.is_valid() and address_form.is_valid():
new_email = form.cleaned_data['email']
form.save()
address_form.save()
if (old_email) != (new_email):
logout(request)
messages.success(
request, 'Profile updated successfully. and verification mail has been sent to the new email address.')
else:
messages.success(request, 'Profile updated successfully')
return HttpResponse(status=204)
context = {'form': form, 'address_form': address_form}
return render(request, 'auth/profile_basic_info_update.html', context=context)
@login_required
@user_passes_test(lambda u: u.is_superuser)
def organization_info_update(request):
organization = request.user.organization
organization_form = OrganizationUpdateForm(instance=organization)
if request.method == "POST":
organization_form = OrganizationUpdateForm(
request.POST, request.FILES, instance=organization)
if organization_form.is_valid():
organization_form.save()
messages.success(
request, 'Organization details updated successfully')
return HttpResponse(status=204)
context = {'organization_form': organization_form,
'organization': organization}
return render(request, 'auth/organization_info_update.html', context=context)
View File
+30
View File
@@ -0,0 +1,30 @@
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import *
# Register your models here.
@admin.register(Organization)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['name', 'website', 'created_at']
@admin.register(Location)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['office_name', 'address',
'organization', 'is_deleted', 'created_at']
@admin.register(Department)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['name', 'organization', 'is_deleted', 'created_at']
@admin.register(ProductType)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['name', 'organization', 'is_deleted', 'created_at']
@admin.register(ProductCategory)
class SupportAdmin(SimpleHistoryAdmin):
list_display = ['name', 'organization', 'is_deleted', 'created_at']
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class DashboardConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'dashboard'
+158
View File
@@ -0,0 +1,158 @@
from dataclasses import fields
from django import forms
from .models import Location, Address, ProductType, Department, ProductCategory
class LocationForm(forms.ModelForm):
office_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Office Name'}
))
contact_person_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Contact Person Name'}
))
contact_person_email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Contact Person Email'}
))
contact_person_phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Contact Person Phone'}
))
def clean_office_name(self):
office_name = self.cleaned_data.get('office_name')
return office_name.title()
def clean_contact_person_name(self):
contact_person_name = self.cleaned_data.get('contact_person_name')
return contact_person_name.title()
def clean_contact_person_email(self):
contact_person_email = self.cleaned_data.get('contact_person_email')
return contact_person_email.lower()
class Meta:
model = Location
fields = ['office_name', 'contact_person_name',
'contact_person_email', 'contact_person_phone']
class AddressForm(forms.ModelForm):
address_line_one = forms.CharField(required=True, widget=forms.Textarea(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Address Line 1', 'rows': '2'}
))
address_line_two = forms.CharField(required=True, widget=forms.Textarea(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Address Line 2', 'rows': '2'}
))
country = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off',
'class': 'form-control', 'placeholder': 'Country'}
))
state = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off',
'class': 'form-control', 'placeholder': 'State'}
))
city = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off',
'class': 'form-control', 'placeholder': 'City'}
))
pin_code = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Zip Code'}
))
def clean_country(self):
country = self.cleaned_data.get('country')
return country.title()
def clean_state(self):
state = self.cleaned_data.get('state')
return state.title()
def clean_city(self):
city = self.cleaned_data.get('city')
return city.title()
class Meta:
model = Address
fields = ['address_line_one', 'address_line_two',
'country', 'state', 'city', 'pin_code']
class ProductTypeForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Type Name'}
))
def __init__(self, *args, **kwargs):
self._organization = kwargs.pop('organization', None)
self._pk = kwargs.pop('pk', None)
super(ProductTypeForm, self).__init__(*args, **kwargs)
def clean_name(self):
name = self.cleaned_data.get('name')
if ProductType.undeleted_objects.filter(name__iexact=name, organization=self._organization).exclude(pk=self._pk).exists():
raise forms.ValidationError('Name must be unique!')
return name
class Meta:
model = ProductType
fields = ['name']
class DepartmentForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Department Name'}
))
contact_person_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Contact Person Name'}
))
contact_person_email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Contact Person Email'}
))
contact_person_phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Contact Person Phone'}
))
def clean_contact_person_name(self):
contact_person_name = self.cleaned_data.get('contact_person_name')
return contact_person_name.title()
def clean_contact_person_email(self):
contact_person_email = self.cleaned_data.get('contact_person_email')
return contact_person_email.lower()
class Meta:
model = Department
fields = ['name', 'contact_person_name',
'contact_person_email', 'contact_person_phone']
class ProductCategoryForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control',
'placeholder': 'Category Name'}
))
def __init__(self, *args, **kwargs):
self._organization = kwargs.pop('organization', None)
self._pk = kwargs.pop('pk', None)
super(ProductCategoryForm, self).__init__(*args, **kwargs)
def clean_name(self):
name = self.cleaned_data.get('name')
if ProductCategory.undeleted_objects.filter(name__iexact=name, organization=self._organization).exclude(pk=self._pk).exists():
raise forms.ValidationError('Name must be unique!')
return name
class Meta:
model = ProductCategory
fields = ['name']
+139
View File
@@ -0,0 +1,139 @@
# Generated by Django 3.2 on 2022-05-27 06:01
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Department',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_email', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_phone', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Organization',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('website', models.CharField(blank=True, max_length=255, null=True)),
('email', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('currency', models.CharField(blank=True, max_length=255, null=True)),
('date_format', models.CharField(blank=True, max_length=255, null=True)),
('logo', models.ImageField(blank=True, max_length=255, null=True, upload_to='')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ProductType',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ProductCategory',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
('product_category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.producttype')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Location',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('office_name', models.CharField(blank=True, max_length=255, null=True)),
('address_line_one', models.CharField(blank=True, max_length=255, null=True)),
('address_line_two', models.CharField(blank=True, max_length=255, null=True)),
('country', models.IntegerField()),
('state', models.IntegerField()),
('city', models.CharField(blank=True, max_length=255, null=True)),
('pin_code', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_phone', models.CharField(blank=True, max_length=255, null=True)),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Employee',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('employee_id', models.CharField(blank=True, max_length=45, null=True)),
('email', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=45, null=True)),
('departments', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.department')),
('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location')),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
('reporting_manager', models.ForeignKey(blank=True, db_column='reporting_manager', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.employee')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='department',
name='organization',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization'),
),
]
@@ -0,0 +1,73 @@
# Generated by Django 3.2 on 2022-06-21 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='department',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='department',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='employee',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='employee',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='location',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='location',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='organization',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='organization',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='productcategory',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='productcategory',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='producttype',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='producttype',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,64 @@
# Generated by Django 3.2 on 2022-07-03 18:43
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_auto_20220621_1350'),
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('address_line_one', models.TextField(blank=True, null=True)),
('address_line_two', models.TextField(blank=True, null=True)),
('country', models.CharField(blank=True, max_length=255, null=True)),
('state', models.CharField(blank=True, max_length=255, null=True)),
('city', models.CharField(blank=True, max_length=255, null=True)),
('pin_code', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='location',
name='address_line_one',
),
migrations.RemoveField(
model_name='location',
name='address_line_two',
),
migrations.RemoveField(
model_name='location',
name='city',
),
migrations.RemoveField(
model_name='location',
name='country',
),
migrations.RemoveField(
model_name='location',
name='pin_code',
),
migrations.RemoveField(
model_name='location',
name='state',
),
migrations.AddField(
model_name='location',
name='address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='dashboard.address'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-07-05 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0003_auto_20220703_1843'),
]
operations = [
migrations.AddField(
model_name='location',
name='contact_person_email',
field=models.EmailField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-07-05 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0004_location_contact_person_email'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='logo',
field=models.ImageField(blank=True, null=True, upload_to='logos'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-08-30 07:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
]
operations = [
migrations.RenameField(
model_name='productcategory',
old_name='product_category',
new_name='product_type',
),
]
@@ -0,0 +1,17 @@
# Generated by Django 3.2 on 2022-09-21 11:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0006_rename_product_category_productcategory_product_type'),
]
operations = [
migrations.RemoveField(
model_name='productcategory',
name='product_type',
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-28 09:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0007_remove_productcategory_product_type'),
]
operations = [
migrations.AddField(
model_name='producttype',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-29 07:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0008_producttype_is_deleted'),
]
operations = [
migrations.AddField(
model_name='producttype',
name='deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 3.2 on 2022-09-29 07:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0009_producttype_deleted'),
]
operations = [
migrations.RemoveField(
model_name='producttype',
name='deleted',
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-29 10:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0010_remove_producttype_deleted'),
]
operations = [
migrations.AddField(
model_name='location',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-29 10:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0010_remove_producttype_deleted'),
]
operations = [
migrations.AddField(
model_name='productcategory',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,14 @@
# Generated by Django 3.2 on 2022-09-29 13:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0011_location_is_deleted'),
('dashboard', '0011_productcategory_is_deleted'),
]
operations = [
]
@@ -0,0 +1,14 @@
# Generated by Django 3.2 on 2022-09-30 05:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0011_location_is_deleted'),
('dashboard', '0011_productcategory_is_deleted'),
]
operations = [
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-29 13:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0012_merge_20220929_1355'),
]
operations = [
migrations.AddField(
model_name='department',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,14 @@
# Generated by Django 3.2 on 2022-10-06 11:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0012_merge_20220930_0513'),
('dashboard', '0013_department_is_deleted'),
]
operations = [
]
@@ -0,0 +1,16 @@
# Generated by Django 3.2 on 2022-10-13 12:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0014_merge_20221006_1112'),
]
operations = [
migrations.DeleteModel(
name='Employee',
),
]
@@ -0,0 +1,19 @@
# Generated by Django 3.2 on 2022-12-12 13:17
import dashboard.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0015_delete_employee'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='logo',
field=models.ImageField(blank=True, null=True, upload_to=dashboard.models.path_and_rename),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-12-13 13:08
import dashboard.models
from django.db import migrations
import django_resized.forms
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0016_alter_organization_logo'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='logo',
field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', keep_meta=True, null=True, quality=75, scale=None, size=[1024, 768], upload_to=dashboard.models.path_and_rename),
),
]
@@ -0,0 +1,43 @@
# Generated by Django 3.2 on 2023-01-04 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0017_alter_organization_logo'),
]
operations = [
migrations.AlterField(
model_name='address',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='department',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='location',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='organization',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='productcategory',
name='status',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='producttype',
name='status',
field=models.BooleanField(default=True),
),
]
@@ -0,0 +1,159 @@
# Generated by Django 3.2 on 2023-01-05 08:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('dashboard', '0018_auto_20230104_1455'),
]
operations = [
migrations.CreateModel(
name='HistoricalProductType',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
],
options={
'verbose_name': 'historical product type',
'verbose_name_plural': 'historical product types',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalProductCategory',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
],
options={
'verbose_name': 'historical product category',
'verbose_name_plural': 'historical product categorys',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalOrganization',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('website', models.CharField(blank=True, max_length=255, null=True)),
('email', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('currency', models.CharField(blank=True, max_length=255, null=True)),
('date_format', models.CharField(blank=True, max_length=255, null=True)),
('logo', models.TextField(blank=True, max_length=100, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'historical organization',
'verbose_name_plural': 'historical organizations',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalLocation',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('office_name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_email', models.EmailField(blank=True, max_length=255, null=True)),
('contact_person_phone', models.CharField(blank=True, max_length=255, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('address', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.address')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
],
options={
'verbose_name': 'historical location',
'verbose_name_plural': 'historical locations',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalDepartment',
fields=[
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_name', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_email', models.CharField(blank=True, max_length=255, null=True)),
('contact_person_phone', models.CharField(blank=True, max_length=255, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
],
options={
'verbose_name': 'historical department',
'verbose_name_plural': 'historical departments',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
View File
+132
View File
@@ -0,0 +1,132 @@
import uuid
from django.db import models
import os
from uuid import uuid4
from django_resized import ResizedImageField
from simple_history.models import HistoricalRecords
def path_and_rename(instance, filename):
upload_to = 'logo/'
ext = filename.split('.')[-1]
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(upload_to, filename)
class TimeStampModel(models.Model):
status = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
created_by = models.CharField(max_length=255, blank=True, null=True)
updated_by = models.CharField(max_length=255, blank=True, null=True)
class Meta:
abstract = True
class RestoreManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_deleted=True)
class SoftDeleteManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_deleted=False)
class SoftDeleteModel(models.Model):
is_deleted = models.BooleanField(default=False)
objects = models.Manager()
undeleted_objects = SoftDeleteManager()
deleted_objects = RestoreManager()
def soft_delete(self):
self.is_deleted = True
self.save()
def restore(self):
self.is_deleted = False
self.save()
class Meta:
abstract = True
class Department(TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
contact_person_name = models.CharField(max_length=255, blank=True, null=True)
contact_person_email = models.CharField(max_length=255, blank=True, null=True)
contact_person_phone = models.CharField(max_length=255, blank=True, null=True)
organization = models.ForeignKey('Organization', models.DO_NOTHING, blank=True, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Location(TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
organization = models.ForeignKey('Organization', models.DO_NOTHING, blank=True, null=True)
office_name = models.CharField(max_length=255, blank=True, null=True)
contact_person_name = models.CharField(max_length=255, blank=True, null=True)
contact_person_email = models.EmailField(max_length=255, blank=True, null=True)
contact_person_phone = models.CharField(max_length=255, blank=True, null=True)
address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=True, null=True)
history = HistoricalRecords()
def __str__(self):
return f'{self.office_name} - {self.address}'
class Organization(TimeStampModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
website = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255, blank=True, null=True)
phone = models.CharField(max_length=255, blank=True, null=True)
currency = models.CharField(max_length=255, blank=True, null=True)
date_format = models.CharField(max_length=255, blank=True, null=True)
logo = ResizedImageField(upload_to=path_and_rename, blank=True, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class ProductType(TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
organization = models.ForeignKey(Organization, models.DO_NOTHING, blank=True, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class ProductCategory(TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
organization = models.ForeignKey(Organization, models.DO_NOTHING, blank=True, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Address(TimeStampModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
address_line_one = models.TextField(blank=True, null=True)
address_line_two = models.TextField(blank=True, null=True)
country = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
pin_code = models.CharField(max_length=255, blank=True, null=True)
# def __str__(self):
# return f'{self.address_line_one}, {self.address_line_two}, {self.country}, {self.state}, {self.city}, {self.pin_code}'

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