first push
This commit is contained in:
25
.env.local
Normal file
25
.env.local
Normal file
@@ -0,0 +1,25 @@
|
||||
SECRET_KEY=django-insecure-d3)=!q#x%7%r8xu*b813f4^o*(=52#(flf@gd8psr(+=qu5an=
|
||||
DEBUG=True
|
||||
ALLOWED_HOSTS=habackend.rasadyaar.ir,ha.rasadyaar.ir,127.0.0.1,rasadyaar.ir,rasadyar.net,habackend.rasadyar.com ,ha.rasadyar.com,rasadyar.com,
|
||||
DB_NAME=hamedan
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=nWYuG2dxiXxCrDz6yZKWHpyW7ExiXykb7qSAeQdPUDXBdZ17PXovrpg6KllnARSS
|
||||
DB_HOST=31.7.78.133
|
||||
DB_PORT=14332
|
||||
CELERY_BROKER_URL=redis://redis://localhost:6379
|
||||
CELERY_RESULT_BACKEND=redis://redis://localhost:6379
|
||||
CELERY_ACCEPT_CONTENT=application/json
|
||||
CELERY_TASK_SERIALIZER=json
|
||||
CELERY_RESULT_SERIALIZER=json
|
||||
CELERY_TIMEZONE=Asia/Tehran
|
||||
CORS_ORIGIN_ALLOW_ALL=True
|
||||
CORS_ORIGIN_WHITELIST=http://localhost:8080,http://127.0.0.1:8080,http://127.0.0.1:3000,http://localhost:3000,https://habackend.rasadyaar.ir,https://ha.rasadyaar.ir,https://rasadyaar.ir,https://rasadyar.net,https://habackend.rasadyar.com,https://rasadyar.com
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:8080,http://127.0.0.1:8080,http://127.0.0.1:3000,http://localhost:3000,https://habackend.rasadyaar.ir,https://ha.rasadyaar.ir,https://rasadyaar.ir,https://rasadyar.net,https://habackend.rasadyar.com,https://rasadyar.com
|
||||
SECURE_PROXY_SSL_HEADER=HTTP_X_FORWARDED_PROTO,https
|
||||
SECURE_SSL_REDIRECT=False
|
||||
SESSION_COOKIE_SECURE=True
|
||||
CSRF_COOKIE_SECURE=True
|
||||
REDIS_URL=redis://:ydnW4hwzuDRYcTX3FWCHgQ1f@apo.liara.cloud:33740/0
|
||||
|
||||
|
||||
ENV RUNNING_IN_DOCKER=0
|
||||
22
.env.prod
Normal file
22
.env.prod
Normal file
@@ -0,0 +1,22 @@
|
||||
SECRET_KEY=django-insecure-d3)=!q#x%7%r8xu*b813f4^o*(=52#(flf@gd8psr(+=qu5an=
|
||||
DEBUG=True
|
||||
ALLOWED_HOSTS=habackend.rasadyaar.ir,ha.rasadyaar.ir,127.0.0.1,rasadyaar.ir,rasadyar.net,habackend.rasadyar.com ,ha.rasadyar.com,rasadyar.com,
|
||||
DB_NAME=hamedan
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=nWYuG2dxiXxCrDz6yZKWHpyW7ExiXykb7qSAeQdPUDXBdZ17PXovrpg6KllnARSS
|
||||
DB_HOST=31.7.78.133
|
||||
DB_PORT=14332
|
||||
CELERY_BROKER_URL=redis://redis://localhost:6379
|
||||
CELERY_RESULT_BACKEND=redis://redis://localhost:6379
|
||||
CELERY_ACCEPT_CONTENT=application/json
|
||||
CELERY_TASK_SERIALIZER=json
|
||||
CELERY_RESULT_SERIALIZER=json
|
||||
CELERY_TIMEZONE=Asia/Tehran
|
||||
CORS_ORIGIN_ALLOW_ALL=True
|
||||
CORS_ORIGIN_WHITELIST=http://localhost:8080,http://127.0.0.1:8080,http://127.0.0.1:3000,http://localhost:3000,https://habackend.rasadyaar.ir,https://ha.rasadyaar.ir,https://rasadyaar.ir,https://rasadyar.net,https://habackend.rasadyar.com,https://rasadyar.com
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:8080,http://127.0.0.1:8080,http://127.0.0.1:3000,http://localhost:3000,https://habackend.rasadyaar.ir,https://ha.rasadyaar.ir,https://rasadyaar.ir,https://rasadyar.net,https://habackend.rasadyar.com,https://rasadyar.com
|
||||
SECURE_PROXY_SSL_HEADER=HTTP_X_FORWARDED_PROTO,https
|
||||
SECURE_SSL_REDIRECT=False
|
||||
SESSION_COOKIE_SECURE=True
|
||||
CSRF_COOKIE_SECURE=True
|
||||
REDIS_URL=redis://:ydnW4hwzuDRYcTX3FWCHgQ1f@apo.liara.cloud:33740/0
|
||||
135
.gitignore
vendored
Normal file
135
.gitignore
vendored
Normal file
@@ -0,0 +1,135 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
.idea
|
||||
.vscode
|
||||
.code
|
||||
.idea/*
|
||||
.vscode/*
|
||||
.code/*
|
||||
59
Dockerfile
Normal file
59
Dockerfile
Normal file
@@ -0,0 +1,59 @@
|
||||
# Dockerfile
|
||||
#FROM python:3.9-slim-bookworm
|
||||
#FROM ghcr.io/seniorkian/python39-rasadyar:1.0.2
|
||||
FROM registry-ea28d41763-mnpc.apps.ir-central1.arvancaas.ir/python39-rasadyar:1.0.2
|
||||
ENV TZ="Asia/Tehran"
|
||||
#RUN ls /usr/share/zoneinfo && \
|
||||
# cp /usr/share/zoneinfo/Asia/Tehran /etc/localtime && \
|
||||
# echo "Asia/Tehran" > /etc/timezone && \
|
||||
# dpkg-reconfigure -f noninteractive tzdata
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# ساخت sources.list جدید با mirror ArvanCloud (برای سرعت در ایران)
|
||||
#RUN echo "deb http://mirror.arvancloud.ir/debian bookworm main" > /etc/apt/sources.list \
|
||||
# && echo "deb-src http://mirror.arvancloud.ir/debian bookworm main" >> /etc/apt/sources.list \
|
||||
# && echo "deb https://mirror.arvancloud.ir/debian-security bookworm-security main" >> /etc/apt/sources.list \
|
||||
# && echo "deb-src https://mirror.arvancloud.ir/debian-security bookworm-security main" >> /etc/apt/sources.list \
|
||||
# && echo "deb http://mirror.arvancloud.ir/debian bookworm-updates main" >> /etc/apt/sources.list \
|
||||
# && echo "deb-src http://mirror.arvancloud.ir/debian bookworm-updates main" >> /etc/apt/sources.list
|
||||
|
||||
# Update + Install system deps (with apt cache)
|
||||
#RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
# build-essential \
|
||||
# libpq-dev \
|
||||
# python3-dev \
|
||||
# libcairo2 \
|
||||
# libcairo2-dev \
|
||||
# libpango-1.0-0 \
|
||||
# libpangoft2-1.0-0 \
|
||||
# libpangocairo-1.0-0 \
|
||||
# libpango1.0-dev \
|
||||
# libgdk-pixbuf-2.0-0 \
|
||||
# libffi-dev \
|
||||
# libjpeg-dev \
|
||||
# libpng-dev \
|
||||
# libfreetype6 \
|
||||
# libharfbuzz0b \
|
||||
# shared-mime-info \
|
||||
# fonts-dejavu \
|
||||
# curl \
|
||||
# && apt-get clean \
|
||||
# && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Upgrade pip
|
||||
#RUN pip install --upgrade pip
|
||||
|
||||
# فقط کپی requirements و نصب پکیجهای پایتون
|
||||
COPY ./requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy project files
|
||||
COPY . .
|
||||
|
||||
# Expose Django port
|
||||
EXPOSE 8000
|
||||
|
||||
# Run Django development server
|
||||
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
|
||||
#CMD ["gunicorn", "TestChicken.wsgi:application", "--bind", "0.0.0.0:8000"]
|
||||
74
GateWay.py
Normal file
74
GateWay.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import requests
|
||||
|
||||
|
||||
def PaymentGateway(deposit_id=None, amount=None, order_id=None):
|
||||
data = {
|
||||
"amount": amount,
|
||||
"orderId": order_id,
|
||||
"additionalData": deposit_id,
|
||||
|
||||
}
|
||||
req = requests.post(
|
||||
url='https://ravandno.ir/cumulative-dynamic-pay-request/',
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
if req.status_code == 200:
|
||||
return {req.status_code: req.json()['refId']}
|
||||
else:
|
||||
return {req.status_code: req.json()['error']}
|
||||
|
||||
# result = req.json()['refId'] if req.status_code == 200 else 'error'
|
||||
# return result
|
||||
# return {req.status_code: req.content}
|
||||
|
||||
|
||||
# def PaymentGatewayZarinPal(amount=None, description=None, province_code=None, wages=None, link=None):
|
||||
# data = {
|
||||
# "amount": amount,
|
||||
# "description": description,
|
||||
# "provincecode": province_code,
|
||||
# "wages": wages,
|
||||
# "isLink": link
|
||||
# }
|
||||
#
|
||||
# headers = {
|
||||
# 'Content-Type': 'application/json'
|
||||
# }
|
||||
#
|
||||
# req = requests.post(
|
||||
# url='https://pay.rasadyaar.ir/zarinpay',
|
||||
# json=data,
|
||||
# headers=headers,
|
||||
# verify=False
|
||||
# )
|
||||
# if req.status_code == 201:
|
||||
# return {req.status_code: req.json()['authority']}
|
||||
#
|
||||
# else:
|
||||
# return {req.status_code: req.json()['error']}
|
||||
|
||||
|
||||
def PaymentGatewayZarinPal(amount=None, phone=None, province_code=None, link=None,wages=None):
|
||||
data = {
|
||||
"amount": amount,
|
||||
"phone": phone,
|
||||
"provincecode": province_code,
|
||||
"isLink": link,
|
||||
"wages": wages
|
||||
}
|
||||
headers = {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
req = requests.post(
|
||||
url='https://pay.rasadyar.net/sep-pay-request/',
|
||||
json=data,
|
||||
headers=headers,
|
||||
verify=False
|
||||
)
|
||||
if req.status_code == 201:
|
||||
return {req.status_code: req.json()['token']}
|
||||
|
||||
else:
|
||||
return {req.status_code: req.json()['error']}
|
||||
0
HaChickenStore/__init__.py
Normal file
0
HaChickenStore/__init__.py
Normal file
14
HaChickenStore/asgi.py
Normal file
14
HaChickenStore/asgi.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
ASGI config for HaChickenStore 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', 'HaChickenStore.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
262
HaChickenStore/settings.py
Normal file
262
HaChickenStore/settings.py
Normal file
@@ -0,0 +1,262 @@
|
||||
"""
|
||||
Django settings for HaChickenStore project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 3.2.8.
|
||||
|
||||
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/
|
||||
"""
|
||||
import socket
|
||||
from pathlib import Path
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
loc_ip = socket.gethostbyname(socket.gethostname())
|
||||
|
||||
|
||||
if not os.getenv("RUNNING_IN_DOCKER"):
|
||||
dotenv_path = BASE_DIR / ".env.local"
|
||||
load_dotenv(dotenv_path)
|
||||
|
||||
SECRET_KEY = os.environ.get("SECRET_KEY")
|
||||
|
||||
|
||||
DEBUG = os.environ.get("DEBUG")
|
||||
|
||||
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS").split(',')
|
||||
|
||||
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'authentication.apps.AuthenticationConfig',
|
||||
'panel.apps.PanelConfig',
|
||||
'LiveStock.apps.LivestockConfig',
|
||||
'notification.apps.NotificationConfig',
|
||||
'oauth2_provider',
|
||||
'corsheaders',
|
||||
'rest_framework',
|
||||
'django_filters',
|
||||
'ticket.apps.TicketConfig',
|
||||
'RasadyaarBale',
|
||||
|
||||
# 'rest_framework.authtoken',
|
||||
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'corsheaders.middleware.CorsMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'oauth2_provider.middleware.OAuth2TokenMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'HaChickenStore.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 = 'HaChickenStore.wsgi.application'
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.postgresql_psycopg2',
|
||||
'NAME': os.environ.get("DB_NAME"),
|
||||
'USER': os.environ.get("DB_USER"),
|
||||
'PASSWORD': os.environ.get("DB_PASSWORD"),
|
||||
'HOST': os.environ.get("DB_HOST"),
|
||||
'PORT': os.environ.get("DB_PORT"),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
|
||||
# 'rest_framework.authentication.TokenAuthentication',
|
||||
),
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
),
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
}
|
||||
|
||||
OAUTH2_PROVIDER = {
|
||||
# other OAUTH2 settings
|
||||
'REFRESH_TOKEN_EXPIRE_SECONDS': 360000,
|
||||
'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
|
||||
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'},
|
||||
'ACCESS_TOKEN_EXPIRE_SECONDS': 360000
|
||||
}
|
||||
|
||||
AUTHENTICATION_BACKENDS = [
|
||||
'oauth2_provider.backends.OAuth2Backend',
|
||||
# Uncomment following if you want to access the admin
|
||||
'django.contrib.auth.backends.ModelBackend',
|
||||
]
|
||||
|
||||
CACHES = {
|
||||
"default": {
|
||||
"BACKEND": "django_redis.cache.RedisCache",
|
||||
"LOCATION": "redis://:ydnW4hwzuDRYcTX3FWCHgQ1f@apo.liara.cloud:33740/0",
|
||||
# "LOCATION": "redis://127.0.0.1:6379/1",
|
||||
"OPTIONS": {
|
||||
"CLIENT_CLASS": "django_redis.client.DefaultClient",
|
||||
# "PASSWORD": "foobar"
|
||||
},
|
||||
"KEY_PREFIX": "You have successfully set up a key-value pair!"
|
||||
}
|
||||
}
|
||||
|
||||
# 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 = 'en-us'
|
||||
|
||||
# TIME_ZONE = 'UTC'
|
||||
TIME_ZONE = 'Asia/Tehran'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = False
|
||||
|
||||
USE_TZ = False
|
||||
|
||||
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
|
||||
|
||||
# Cache time to live is 2 minutes.
|
||||
CACHE_TTL = 60 * 2
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/3.2/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
STATICFILES_DIRS = [
|
||||
os.path.join(BASE_DIR, 'static'),
|
||||
]
|
||||
|
||||
# در حالت production
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
DATA_UPLOAD_MAX_MEMORY_SIZE = 50242880
|
||||
|
||||
# CELERY STUFF
|
||||
BROKER_URL = 'redis://localhost:6379'
|
||||
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
|
||||
CELERY_ACCEPT_CONTENT = ['application/json']
|
||||
CELERY_TASK_SERIALIZER = 'json'
|
||||
CELERY_RESULT_SERIALIZER = 'json'
|
||||
CELERY_TIMEZONE = 'Asia/Tehran'
|
||||
|
||||
if DEBUG:
|
||||
MIDDLEWARE += [
|
||||
'debug_toolbar.middleware.DebugToolbarMiddleware',
|
||||
]
|
||||
INSTALLED_APPS += [
|
||||
'debug_toolbar',
|
||||
# 'oauth2_provider',
|
||||
# 'rest_framework',
|
||||
# 'corsheaders'
|
||||
]
|
||||
INTERNAL_IPS = [
|
||||
# ...
|
||||
"82.115.17.44",
|
||||
# "127.0.0.1",
|
||||
|
||||
# ...
|
||||
]
|
||||
|
||||
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
|
||||
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
|
||||
|
||||
DEBUG_TOOLBAR_PANELS = [
|
||||
'debug_toolbar.panels.history.HistoryPanel',
|
||||
'debug_toolbar.panels.versions.VersionsPanel',
|
||||
'debug_toolbar.panels.timer.TimerPanel',
|
||||
'debug_toolbar.panels.settings.SettingsPanel',
|
||||
'debug_toolbar.panels.headers.HeadersPanel',
|
||||
'debug_toolbar.panels.request.RequestPanel',
|
||||
'debug_toolbar.panels.sql.SQLPanel',
|
||||
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
|
||||
'debug_toolbar.panels.templates.TemplatesPanel',
|
||||
'debug_toolbar.panels.cache.CachePanel',
|
||||
'debug_toolbar.panels.signals.SignalsPanel',
|
||||
'debug_toolbar.panels.logging.LoggingPanel',
|
||||
'debug_toolbar.panels.redirects.RedirectsPanel',
|
||||
'debug_toolbar.panels.profiling.ProfilingPanel',
|
||||
]
|
||||
|
||||
# this is the main reason for not showing up the toolbar
|
||||
import mimetypes
|
||||
|
||||
mimetypes.add_type("application/javascript", ".js", True)
|
||||
|
||||
DEBUG_TOOLBAR_CONFIG = {
|
||||
'INTERCEPT_REDIRECTS': False,
|
||||
}
|
||||
|
||||
CORS_ORIGIN_ALLOW_ALL = os.environ.get("CORS_ORIGIN_ALLOW_ALL", "False").lower() == "true"
|
||||
CORS_ORIGIN_WHITELIST = os.environ.get("CORS_ORIGIN_WHITELIST").split(',')
|
||||
|
||||
CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ORIGIN_WHITELIST").split(',')
|
||||
|
||||
# SECURE_PROXY_SSL_HEADER = os.environ.get("SECURE_PROXY_SSL_HEADER").split(',')
|
||||
# SECURE_SSL_REDIRECT = os.environ.get("SECURE_SSL_REDIRECT")
|
||||
# SESSION_COOKIE_SECURE = os.environ.get("SESSION_COOKIE_SECURE")
|
||||
# CSRF_COOKIE_SECURE = os.environ.get("CSRF_COOKIE_SECURE")
|
||||
29
HaChickenStore/urls.py
Normal file
29
HaChickenStore/urls.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""HaChickenStore 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
|
||||
|
||||
# Mojtaba Zolfaghari Development
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('', include('authentication.urls')),
|
||||
path('LiveStock/', include('LiveStock.urls')),
|
||||
path('', include('panel.urls')),
|
||||
path('', include('notification.urls')),
|
||||
path('', include('ticket.urls')),
|
||||
path('bale/', include('RasadyaarBale.urls')),
|
||||
|
||||
]
|
||||
14
HaChickenStore/wsgi.py
Normal file
14
HaChickenStore/wsgi.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for HaChickenStore 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', 'HaChickenStore.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
BIN
Herds.xlsx
Normal file
BIN
Herds.xlsx
Normal file
Binary file not shown.
BIN
Herds2.xlsx
Normal file
BIN
Herds2.xlsx
Normal file
Binary file not shown.
0
LiveStock/Contractor/__init__.py
Normal file
0
LiveStock/Contractor/__init__.py
Normal file
0
LiveStock/Contractor/excel_processing.py
Normal file
0
LiveStock/Contractor/excel_processing.py
Normal file
20
LiveStock/Contractor/filterset.py
Normal file
20
LiveStock/Contractor/filterset.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import Contractor
|
||||
|
||||
|
||||
class ContractorFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = Contractor
|
||||
fields = [
|
||||
'address__city__name',
|
||||
'contractor_code',
|
||||
'fullname',
|
||||
'entity_code',
|
||||
'national_id',
|
||||
'company_name',
|
||||
'user__mobile',
|
||||
'user__first_name',
|
||||
'user__last_name',
|
||||
'user__fullname'
|
||||
]
|
||||
0
LiveStock/Contractor/helpers.py
Normal file
0
LiveStock/Contractor/helpers.py
Normal file
14
LiveStock/Contractor/serializers.py
Normal file
14
LiveStock/Contractor/serializers.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from LiveStock.models import Union, Contractor
|
||||
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
|
||||
from authentication.serializers import SystemAddressSerializer
|
||||
|
||||
|
||||
class ContractorSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
address = SystemAddressSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Contractor
|
||||
fields = '__all__'
|
||||
14
LiveStock/Contractor/urls.py
Normal file
14
LiveStock/Contractor/urls.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.Contractor import views as contractor_views
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'contractor-views',
|
||||
contractor_views.ContractorViewSet,
|
||||
basename="contractor-views"
|
||||
)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
60
LiveStock/Contractor/views.py
Normal file
60
LiveStock/Contractor/views.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.Contractor.filterset import ContractorFilterSet
|
||||
from LiveStock.Contractor.serializers import ContractorSerializer
|
||||
|
||||
from LiveStock.helpers import build_query, CustomPagination
|
||||
from LiveStock.models import Contractor
|
||||
from authentication.models import SystemUserProfile
|
||||
|
||||
|
||||
class ContractorViewSet(viewsets.ModelViewSet):
|
||||
queryset = Contractor.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = ContractorSerializer
|
||||
filterset_class = ContractorFilterSet
|
||||
pagination_class = CustomPagination
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
if 'profile' in request.GET:
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
|
||||
union = user.contractor_user.all()
|
||||
|
||||
serializer = self.serializer_class(union[0])
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
contractor = Contractor.objects.filter(trash=False).order_by('id')
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
contractor = contractor.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
page = self.paginate_queryset(contractor)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(contractor, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
contractor = Contractor.objects.get(key=request.data['key'], trash=False)
|
||||
request.data.pop('key')
|
||||
|
||||
serializer = self.serializer_class(contractor)
|
||||
|
||||
serializer.update(instance=contractor, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def destroy(self, request, pk=None, *args, **kwargs):
|
||||
contractor = Contractor.objects.get(key=request.GET["key"])
|
||||
contractor.trash = True
|
||||
contractor.save()
|
||||
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
|
||||
0
LiveStock/Cooperative/__init__.py
Normal file
0
LiveStock/Cooperative/__init__.py
Normal file
0
LiveStock/Cooperative/excel_processing.py
Normal file
0
LiveStock/Cooperative/excel_processing.py
Normal file
17
LiveStock/Cooperative/filterset.py
Normal file
17
LiveStock/Cooperative/filterset.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import Cooperative
|
||||
|
||||
|
||||
class CooperativeFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = Cooperative
|
||||
fields = [
|
||||
'address__city__name',
|
||||
'name',
|
||||
'mobile',
|
||||
'user__mobile',
|
||||
'user__first_name',
|
||||
'user__last_name',
|
||||
'user__fullname'
|
||||
]
|
||||
0
LiveStock/Cooperative/helpers.py
Normal file
0
LiveStock/Cooperative/helpers.py
Normal file
66
LiveStock/Cooperative/serializers.py
Normal file
66
LiveStock/Cooperative/serializers.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from LiveStock.models import Cooperative, LiveStockRolseProduct
|
||||
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
|
||||
from authentication.serializers import SystemAddressSerializer
|
||||
from ticket.serializers import SystemUserProfileForTicketPermissionSerializer
|
||||
|
||||
|
||||
class CooperativeSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
address = SystemAddressSerializer(read_only=True)
|
||||
user_bank_info = BankCardSerializer(required=False)
|
||||
|
||||
class Meta:
|
||||
model = Cooperative
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class CooperativeForSharesSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Cooperative
|
||||
fields = ['user', 'name']
|
||||
|
||||
|
||||
class CooperativeForAllocationsReportSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
info = serializers.SerializerMethodField('get_info')
|
||||
|
||||
class Meta:
|
||||
model = Cooperative
|
||||
fields = ['key','user', 'name','info']
|
||||
|
||||
def get_info(self, obj):
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
product =products[self.context.get('request').GET['name']]
|
||||
cooperative_roles = LiveStockRolseProduct.objects.get(cooperative=obj,parent_product__name=product)
|
||||
total_weight = cooperative_roles.total_weight
|
||||
total_receipt_weight = cooperative_roles.total_receipt_weight
|
||||
total_allocated_weight = cooperative_roles.total_allocated_weight
|
||||
total_remain_weight = cooperative_roles.total_remain_weight
|
||||
return {
|
||||
"total_weight": total_weight,
|
||||
"total_receipt_weight": total_receipt_weight,
|
||||
"total_allocated_weight": total_allocated_weight,
|
||||
"total_remain_weight": total_remain_weight,
|
||||
}
|
||||
|
||||
|
||||
class CooperativeForPosSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForTicketPermissionSerializer(read_only=True)
|
||||
address = SystemAddressSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Cooperative
|
||||
fields = ['user', 'name', 'address']
|
||||
21
LiveStock/Cooperative/urls.py
Normal file
21
LiveStock/Cooperative/urls.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.Cooperative import views as cooperative_views
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'cooperative-views',
|
||||
cooperative_views.CooperativeViewSet,
|
||||
basename="cooperative-views"
|
||||
)
|
||||
|
||||
router.register(
|
||||
r'cooperative-warehouse',
|
||||
cooperative_views.CooperativeWarehouseDashboardViewSet,
|
||||
basename="cooperative-warehouse"
|
||||
)
|
||||
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
196
LiveStock/Cooperative/views.py
Normal file
196
LiveStock/Cooperative/views.py
Normal file
@@ -0,0 +1,196 @@
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
import requests
|
||||
from django.contrib.auth.models import User, Group
|
||||
|
||||
from LiveStock.Cooperative.filterset import CooperativeFilterSet
|
||||
from LiveStock.Cooperative.serializers import CooperativeSerializer, CooperativeForAllocationsReportSerializer
|
||||
from LiveStock.helpers import build_query, CustomPagination
|
||||
from LiveStock.models import Cooperative, CooperativeProductsShare, LiveStockProduct, LiveStockRolseProduct
|
||||
from authentication.models import SystemUserProfile, City, Province, SystemAddress
|
||||
from authentication.views import ARTA_URL_CHANGE_MOBILE_NUMBER, ARTA_URL_REGISTER
|
||||
from panel.admin import PROJECT_API_KEY
|
||||
|
||||
|
||||
class CooperativeViewSet(viewsets.ModelViewSet):
|
||||
queryset = Cooperative.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = CooperativeSerializer
|
||||
filterset_class = CooperativeFilterSet
|
||||
pagination_class = CustomPagination
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
group = Group.objects.get(name__exact="Cooperative")
|
||||
city = City.objects.get(name=request.data['city'])
|
||||
request.data.pop('city')
|
||||
province = Province.objects.get(key=city.province.key)
|
||||
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
|
||||
if system_profile:
|
||||
if Cooperative.objects.filter(user=system_profile, trash=False).exists():
|
||||
return Response({"result": "این تعاونی قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
else:
|
||||
password = "123456"
|
||||
data = {
|
||||
"username": request.data['mobile'],
|
||||
"password": password,
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_URL_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'])
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=request.data['mobile'],
|
||||
first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'],
|
||||
fullname=request.data['first_name'] + " " + request.data['last_name'],
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password=password,
|
||||
national_id=request.data['national_id'],
|
||||
city=city,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
else:
|
||||
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
|
||||
address = SystemAddress(city=city, province=province, address=request.data['address'],
|
||||
postal_code=request.data['postal_code'])
|
||||
address.save()
|
||||
system_profile.role.add(group)
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
request.data.pop('address')
|
||||
request.data.pop('postal_code')
|
||||
products = LiveStockProduct.objects.filter(trash=False)
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
cooperative = serializer.create(validated_data=request.data)
|
||||
cooperative.user = system_profile
|
||||
cooperative.address = address
|
||||
cooperative.save()
|
||||
for product in products:
|
||||
share = CooperativeProductsShare(
|
||||
cooperative=cooperative,
|
||||
product=product
|
||||
)
|
||||
share.save()
|
||||
cooperative_roles_product = LiveStockRolseProduct(
|
||||
cooperative=cooperative,
|
||||
parent_product=product
|
||||
|
||||
)
|
||||
cooperative_roles_product.save()
|
||||
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
if 'profile' in request.GET:
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
|
||||
cooperative = user.cooperative_user.all()
|
||||
|
||||
serializer = self.serializer_class(cooperative[0])
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
cooperatives = cooperatives.filter(
|
||||
build_query(self.filterset_class.Meta.fields, search)
|
||||
)
|
||||
page = self.paginate_queryset(cooperatives)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(cooperatives, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
cooperative = Cooperative.objects.get(key=request.data['cooperative_key'], trash=False)
|
||||
address = SystemAddress.objects.get(key=cooperative.address.key, trash=False)
|
||||
request.data.pop('cooperative_key')
|
||||
if 'first_name' in request.data.keys():
|
||||
system_user_profile = SystemUserProfile.objects.get(key=cooperative.user.key, trash=False)
|
||||
system_user_profile.first_name = request.data['first_name']
|
||||
system_user_profile.last_name = request.data['last_name']
|
||||
system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
|
||||
system_user_profile.save()
|
||||
first_mobile_number = system_user_profile.mobile
|
||||
second_mobile_number = request.data['mobile']
|
||||
if first_mobile_number != second_mobile_number:
|
||||
if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
|
||||
return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
data = {
|
||||
"first_mobile_number": first_mobile_number,
|
||||
"second_mobile_number": second_mobile_number,
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_URL_CHANGE_MOBILE_NUMBER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
if req.status_code == 200:
|
||||
second_mobile_number = second_mobile_number
|
||||
user = User.objects.get(id=system_user_profile.user.id)
|
||||
user.username = second_mobile_number
|
||||
user.save()
|
||||
system_user_profile.mobile = second_mobile_number
|
||||
system_user_profile.save()
|
||||
city = City.objects.get(name=request.data['city'])
|
||||
province = Province.objects.get(key=city.province.key)
|
||||
address.city = city
|
||||
address.province = province
|
||||
address.address = request.data['address']
|
||||
address.postal_code = request.data['postal_code']
|
||||
address.save()
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
request.data.pop('address')
|
||||
request.data.pop('city')
|
||||
|
||||
serializer = self.serializer_class(cooperative)
|
||||
serializer.update(instance=cooperative, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class CooperativeWarehouseDashboardViewSet(viewsets.ModelViewSet):
|
||||
queryset = Cooperative.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = CooperativeForAllocationsReportSerializer
|
||||
filterset_class = CooperativeFilterSet
|
||||
pagination_class = CustomPagination
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
cooperatives = cooperatives.filter(
|
||||
build_query(self.filterset_class.Meta.fields, search)
|
||||
)
|
||||
page = self.paginate_queryset(cooperatives)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True,context={"request":request})
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(cooperatives, many=True,context={"request":request})
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
0
LiveStock/Jahad/__init__.py
Normal file
0
LiveStock/Jahad/__init__.py
Normal file
1906
LiveStock/Jahad/excel_processing.py
Normal file
1906
LiveStock/Jahad/excel_processing.py
Normal file
File diff suppressed because it is too large
Load Diff
35
LiveStock/Jahad/filterset.py
Normal file
35
LiveStock/Jahad/filterset.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import LiveStockAllocations, CooperativeProductsShare
|
||||
|
||||
|
||||
class LiveStockAllocationsFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = LiveStockAllocations
|
||||
fields = [
|
||||
'product__name',
|
||||
'jahad__user__mobile',
|
||||
'jahad__user__first_name',
|
||||
'jahad__user__last_name',
|
||||
'jahad__user__fullname',
|
||||
'union__user__mobile',
|
||||
'union__user__first_name',
|
||||
'union__user__last_name',
|
||||
'union__user__fullname',
|
||||
'cooperative__user__mobile',
|
||||
'cooperative__user__first_name',
|
||||
'cooperative__user__last_name',
|
||||
'cooperative__user__fullname'
|
||||
]
|
||||
|
||||
|
||||
class CooperativeProductsShareFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = CooperativeProductsShare
|
||||
fields = [
|
||||
'product__name',
|
||||
'cooperative__user__mobile',
|
||||
'cooperative__user__first_name',
|
||||
'cooperative__user__last_name',
|
||||
'cooperative__user__fullname'
|
||||
]
|
||||
45
LiveStock/Jahad/helpers.py
Normal file
45
LiveStock/Jahad/helpers.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from django.db.models import Sum, Q
|
||||
|
||||
from LiveStock.models import LiveStockAllocations
|
||||
|
||||
|
||||
def jahad_warehousing(product):
|
||||
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False,product=product, trash=False)
|
||||
# allocations = LiveStockAllocations.objects.filter(jahad=product.jahad, trash=False)
|
||||
input_allocations = allocations.filter(union__isnull=True, cooperative__isnull=True)
|
||||
output_allocations = allocations.filter(Q(union__isnull=False) | Q(cooperative__isnull=False))
|
||||
|
||||
input_weight = input_allocations.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
output_weight = output_allocations.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
product.total_weight = input_weight
|
||||
product.total_receipt_weight = input_weight
|
||||
product.total_allocated_weight = output_weight
|
||||
product.save()
|
||||
|
||||
|
||||
def union_warehousing(product):
|
||||
allocations = LiveStockAllocations.objects.filter(union=product.union,product__parent_product__name=product.parent_product.name, trash=False)
|
||||
input_allocations = allocations.filter(jahad__isnull=False)
|
||||
output_allocations = allocations.filter(cooperative__isnull=False)
|
||||
|
||||
input_weight = input_allocations.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
output_weight = output_allocations.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
product.total_weight = input_weight
|
||||
product.total_receipt_weight = input_weight
|
||||
product.total_allocated_weight = output_weight
|
||||
product.save()
|
||||
|
||||
|
||||
def cooperative_warehousing(product):
|
||||
input_allocations = LiveStockAllocations.objects.filter(cooperative=product.cooperative,product__parent_product__name=product.parent_product.name, trash=False).values_list('id',flat=True)
|
||||
total_receipt_weight = input_allocations.filter(charge=False).aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
real_input_weight = input_allocations.filter(charge=True).aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
product.total_receipt_weight = total_receipt_weight
|
||||
product.total_weight = real_input_weight
|
||||
product.save()
|
||||
54
LiveStock/Jahad/serializers.py
Normal file
54
LiveStock/Jahad/serializers.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from LiveStock.Cooperative.serializers import CooperativeSerializer, CooperativeForSharesSerializer
|
||||
from LiveStock.Union.serializers import UnionSerializer
|
||||
from LiveStock.models import LiveStockProvinceJahad, LiveStockRolseProduct, LiveStockAllocations, LiveStockProduct, \
|
||||
CooperativeProductsShare
|
||||
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
|
||||
from authentication.serializers import SystemAddressSerializer
|
||||
from ticket.serializers import SystemUserProfileForTicketPermissionSerializer
|
||||
|
||||
|
||||
class LiveStockProvinceJahadSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
address = SystemAddressSerializer(read_only=True)
|
||||
user_bank_info = BankCardSerializer(required=False)
|
||||
|
||||
class Meta:
|
||||
model = LiveStockProvinceJahad
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class LiveStockProductSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = LiveStockProduct
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class LiveStockRolseProductSerializer(serializers.ModelSerializer):
|
||||
parent_product = LiveStockProductSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = LiveStockRolseProduct
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class LiveStockAllocationsSerializer(serializers.ModelSerializer):
|
||||
product = LiveStockRolseProductSerializer(read_only=True)
|
||||
union = UnionSerializer(read_only=True)
|
||||
cooperative = CooperativeSerializer(read_only=True)
|
||||
jahad = LiveStockProvinceJahadSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = LiveStockAllocations
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class CooperativeProductsShareSerializer(serializers.ModelSerializer):
|
||||
cooperative = CooperativeForSharesSerializer(read_only=True)
|
||||
product = LiveStockRolseProductSerializer(read_only=True)
|
||||
|
||||
|
||||
class Meta:
|
||||
model = CooperativeProductsShare
|
||||
fields = '__all__'
|
||||
59
LiveStock/Jahad/urls.py
Normal file
59
LiveStock/Jahad/urls.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.Jahad import views as jahad_views
|
||||
from LiveStock.Jahad.excel_processing import allocation_live_stock_excel, warehouse_live_stock_excel, \
|
||||
live_stock_transaction_excel, cooperative_warehouse_excel, management_live_stock_excel, rancher_management, \
|
||||
live_stock_product_excel
|
||||
from LiveStock.Jahad.views import get_user_live_stock
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'profile',
|
||||
jahad_views.LiveStockProvinceJahadViewSet,
|
||||
basename="profile"
|
||||
)
|
||||
|
||||
router.register(
|
||||
r'live-stock-role-products',
|
||||
jahad_views.LiveStockRolseProductViewset,
|
||||
basename="live-stock-role-products"
|
||||
)
|
||||
router.register(
|
||||
r'live-stock-allocation',
|
||||
jahad_views.LiveStockAllocationsViewSet,
|
||||
basename="live-stock-allocation"
|
||||
)
|
||||
router.register(
|
||||
r'live-stock-product',
|
||||
jahad_views.LiveStockProductViewset,
|
||||
basename="live-stock-product"
|
||||
)
|
||||
router.register(
|
||||
r'dashboard-live-stock-allocation',
|
||||
jahad_views.DashboardLiveStockAllocationsViewSet,
|
||||
basename="dashboard-live-stock-allocation"
|
||||
)
|
||||
router.register(
|
||||
r'live-stock-warehouse-charge-allocation',
|
||||
jahad_views.LiveStockWarehouseChargeAllocationsViewSet,
|
||||
basename="live-stock-warehouse-charge-allocation"
|
||||
)
|
||||
|
||||
router.register(
|
||||
r'cooperative-shares',
|
||||
jahad_views.CooperativeProductsShareViewSet,
|
||||
basename="cooperative-shares"
|
||||
)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('get_user_live_stock/', get_user_live_stock),
|
||||
path('allocation_live_stock_excel/', allocation_live_stock_excel),
|
||||
path('warehouse_live_stock_excel/', warehouse_live_stock_excel),
|
||||
path('live_stock_transaction_excel/', live_stock_transaction_excel),
|
||||
path('cooperative_warehouse_excel/', cooperative_warehouse_excel),
|
||||
path('management_live_stock_excel/', management_live_stock_excel),
|
||||
path('rancher_management/', rancher_management),
|
||||
path('live_stock_product_excel/', live_stock_product_excel),
|
||||
]
|
||||
690
LiveStock/Jahad/views.py
Normal file
690
LiveStock/Jahad/views.py
Normal file
@@ -0,0 +1,690 @@
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
from django.db.models import Sum, Q
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.Jahad.filterset import LiveStockAllocationsFilterSet, CooperativeProductsShareFilterSet
|
||||
from LiveStock.Jahad.helpers import jahad_warehousing, union_warehousing, cooperative_warehousing
|
||||
from LiveStock.Jahad.serializers import LiveStockProvinceJahadSerializer, LiveStockRolseProductSerializer, \
|
||||
LiveStockAllocationsSerializer, LiveStockProductSerializer, CooperativeProductsShareSerializer
|
||||
from LiveStock.Rancher.helpers import update_quota_rancher_threading
|
||||
from LiveStock.Rancher.serializers import RancherSerializer
|
||||
from LiveStock.Union.serializers import UnionSerializer
|
||||
from LiveStock.helpers import CustomPagination, build_query
|
||||
from LiveStock.models import LiveStockProvinceJahad, LiveStockRolseProduct, LiveStockAllocations, Union, Cooperative, \
|
||||
Rancher, LiveStockProduct, CooperativeProductsShare
|
||||
from authentication.models import SystemUserProfile
|
||||
|
||||
|
||||
class LiveStockProvinceJahadViewSet(viewsets.ModelViewSet):
|
||||
queryset = LiveStockProvinceJahad.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockProvinceJahadSerializer
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
if 'profile' in request.GET:
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
|
||||
jahad = user.jahad_user.all()
|
||||
|
||||
serializer = self.serializer_class(jahad[0])
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class LiveStockRolseProductViewset(viewsets.ModelViewSet):
|
||||
queryset = LiveStockRolseProduct.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockRolseProductSerializer
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
name =products[request.GET.get('name')]
|
||||
|
||||
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
|
||||
if request.GET['role'] == 'LiveStockProvinceJahad':
|
||||
products = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
|
||||
, parent_product=product).first()
|
||||
elif request.GET['role'] == 'Union':
|
||||
products = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
|
||||
parent_product=product).first()
|
||||
|
||||
else:
|
||||
products = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
|
||||
parent_product=product).first()
|
||||
serializer = self.serializer_class(products)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class LiveStockAllocationsViewSet(viewsets.ModelViewSet):
|
||||
queryset = LiveStockAllocations.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockAllocationsSerializer
|
||||
pagination_class = CustomPagination
|
||||
filterset_class = LiveStockAllocationsFilterSet
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
product = LiveStockRolseProduct.objects.get(key=request.data['product_key'])
|
||||
|
||||
allocator = request.data['allocator']
|
||||
receiver = request.data['receiver']
|
||||
request.data.pop('allocator')
|
||||
request.data.pop('receiver')
|
||||
request.data.pop('product_key')
|
||||
|
||||
if allocator == 'LiveStockProvinceJahad':
|
||||
jahad = LiveStockProvinceJahad.objects.get(user=user, trash=False)
|
||||
jahad_roles_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False,parent_product__name=product.parent_product.name,trash=False).first()
|
||||
if receiver != 'LiveStockProvinceJahad':
|
||||
if request.data['weight'] > jahad_roles_product.total_remain_weight:
|
||||
return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
elif allocator == 'Cooperative':
|
||||
cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
cooperative_roles_product = LiveStockRolseProduct.objects.get(cooperative=cooperative,parent_product__name=product.parent_product.name, trash=False)
|
||||
if receiver != 'Cooperative':
|
||||
|
||||
if request.data[
|
||||
'weight'] + cooperative_roles_product.total_remain_weight > cooperative_roles_product.total_receipt_weight:
|
||||
return Response({"result": "مقدار وارد شده بیشتر از سهمیه دریافتی است !"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
|
||||
else:
|
||||
union = Union.objects.get(user=user, trash=False)
|
||||
union_roles_product = LiveStockRolseProduct.objects.filter(union__isnull=False,parent_product__name=product.parent_product.name, trash=False).first()
|
||||
if request.data['weight'] > union_roles_product.total_remain_weight:
|
||||
return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
if receiver == 'LiveStockProvinceJahad':
|
||||
pass
|
||||
elif receiver == 'Union':
|
||||
union = Union.objects.get(key=request.data['buyer_key'], trash=False)
|
||||
request.data.pop('buyer_key')
|
||||
|
||||
else:
|
||||
if allocator == 'Cooperative':
|
||||
pass
|
||||
else:
|
||||
cooperative = Cooperative.objects.get(key=request.data['buyer_key'], trash=False)
|
||||
request.data.pop('buyer_key')
|
||||
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
allocation = serializer.create(validated_data=request.data)
|
||||
allocation.product = product
|
||||
if allocator == 'LiveStockProvinceJahad':
|
||||
allocation.jahad = jahad
|
||||
allocation.allocate_from = "LiveStockProvinceJahad"
|
||||
|
||||
elif allocator == 'Cooperative':
|
||||
allocation.cooperative = cooperative
|
||||
allocation.allocate_from = "Cooperative"
|
||||
|
||||
else:
|
||||
allocation.union = union
|
||||
allocation.allocate_from = "Union"
|
||||
|
||||
if receiver == 'LiveStockProvinceJahad':
|
||||
allocation.allocate_to = "LiveStockProvinceJahad"
|
||||
allocation.charge = True
|
||||
allocation.state = 'accepted'
|
||||
|
||||
|
||||
elif receiver == 'Union':
|
||||
allocation.union = union
|
||||
allocation.allocate_to = "Union"
|
||||
|
||||
else:
|
||||
allocation.cooperative = cooperative
|
||||
allocation.allocate_to = "Cooperative"
|
||||
if allocator == 'Cooperative':
|
||||
allocation.charge = True
|
||||
|
||||
allocation.save()
|
||||
|
||||
if allocator == 'LiveStockProvinceJahad':
|
||||
jahad_warehousing(product)
|
||||
|
||||
elif allocator == 'Cooperative':
|
||||
pass
|
||||
else:
|
||||
union_warehousing(product)
|
||||
if receiver == 'Union':
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product, union=union)
|
||||
|
||||
union_warehousing(reciver_product)
|
||||
elif receiver == 'Cooperative':
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
|
||||
cooperative=cooperative)
|
||||
cooperative_warehousing(reciver_product)
|
||||
|
||||
else:
|
||||
pass
|
||||
return Response({"result": "با موفقیت ثبت شد!"}, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
allocation = LiveStockAllocations.objects.get(key=request.data['allocation_key'], trash=False)
|
||||
request.data.pop('allocation_key')
|
||||
if allocation.charge == True:
|
||||
if allocation.allocate_from == 'LiveStockProvinceJahad':
|
||||
if request.data['weight'] < allocation.weight:
|
||||
|
||||
allocations = LiveStockAllocations.objects.filter(jahad=allocation.jahad,product=allocation.product, trash=False)
|
||||
charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
|
||||
'total'] or 0) + request.data['weight']
|
||||
jahad_alocations = allocations.filter(charge=False).aggregate(total=Sum('weight'))['total'] or 0
|
||||
|
||||
if charge < jahad_alocations:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
else:
|
||||
allocations = LiveStockAllocations.objects.filter(cooperative=allocation.cooperative,product=allocation.product, trash=False)
|
||||
charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
|
||||
'total'] or 0) + request.data['weight']
|
||||
|
||||
if request.data['weight'] < allocation.weight:
|
||||
|
||||
if charge < allocation.product.total_allocated_weight:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و فروش امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
elif request.data['weight'] > allocation.weight:
|
||||
if charge > allocation.product.total_receipt_weight:
|
||||
return Response(
|
||||
{
|
||||
"result": "به علت عدم همخوانی سهمیه دریافتی و موجودی انبار امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
else:
|
||||
if request.data['weight'] > allocation.weight:
|
||||
if allocation.allocate_from == 'LiveStockProvinceJahad':
|
||||
jahad_products = allocation.product
|
||||
dif = request.data['weight'] - allocation.weight
|
||||
if dif > jahad_products.total_remain_weight:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
else:
|
||||
union_products = allocation.product
|
||||
dif = request.data['weight'] - allocation.weight
|
||||
if dif > union_products.total_remain_weight:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
elif request.data['weight'] < allocation.weight:
|
||||
dif = allocation.weight - request.data['weight']
|
||||
|
||||
if allocation.allocate_to == 'Union':
|
||||
union_role_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product, trash=False)
|
||||
if dif > union_role_product.total_remain_weight:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
elif allocation.allocate_to == 'Cooperative':
|
||||
cooperative_role_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product,
|
||||
trash=False)
|
||||
|
||||
if dif > (cooperative_role_product.total_receipt_weight - cooperative_role_product.total_weight):
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
serializer = self.serializer_class(allocation)
|
||||
serializer.update(instance=allocation, validated_data=request.data)
|
||||
product = allocation.product
|
||||
if allocation.allocate_from == 'LiveStockProvinceJahad':
|
||||
jahad_warehousing(product)
|
||||
|
||||
elif allocation.allocate_from == 'Cooperative':
|
||||
pass
|
||||
else:
|
||||
union_warehousing(product)
|
||||
if allocation.allocate_to == 'Union':
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
|
||||
union=allocation.union)
|
||||
union_warehousing(reciver_product)
|
||||
elif allocation.allocate_to == 'Cooperative':
|
||||
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
|
||||
cooperative=allocation.cooperative)
|
||||
cooperative_warehousing(reciver_product)
|
||||
else:
|
||||
pass
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
name =products[request.GET.get('name')]
|
||||
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
|
||||
if request.GET['role'] == 'LiveStockProvinceJahad':
|
||||
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, allocate_from="LiveStockProvinceJahad",
|
||||
trash=False, product__parent_product=product).order_by(
|
||||
'id').exclude(allocate_to='LiveStockProvinceJahad')
|
||||
elif request.GET['role'] == 'Union':
|
||||
allocations = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_from="Union",
|
||||
product__parent_product=product).order_by('id')
|
||||
|
||||
else:
|
||||
allocations = LiveStockAllocations.objects.filter(cooperative__user=user, charge=False,
|
||||
allocate_to="Cooperative",
|
||||
trash=False, product__parent_product=product).order_by(
|
||||
'id')
|
||||
|
||||
date1 = request.GET.get('date1')
|
||||
date2 = request.GET.get('date2')
|
||||
if date1 and date2:
|
||||
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
|
||||
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
allocations = allocations.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
|
||||
page_size = request.query_params.get('page_size', None)
|
||||
if page_size:
|
||||
self.pagination_class.page_size = int(page_size)
|
||||
|
||||
page = self.paginate_queryset(allocations)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(allocations, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def destroy(self, request, pk=None, *args, **kwargs):
|
||||
allocation = LiveStockAllocations.objects.get(key=request.GET["allocation_key"])
|
||||
product = allocation.product
|
||||
|
||||
if allocation.allocate_from == 'LiveStockProvinceJahad':
|
||||
if allocation.allocate_to == 'LiveStockProvinceJahad':
|
||||
roles_product = allocation.product
|
||||
elif allocation.allocate_to == 'Union':
|
||||
roles_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product)
|
||||
else:
|
||||
roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)
|
||||
|
||||
if allocation.weight > roles_product.total_remain_weight:
|
||||
if allocation.allocate_to == 'Cooperative':
|
||||
if roles_product.total_receipt_weight >= allocation.weight:
|
||||
pass
|
||||
else:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
elif allocation.allocate_from == 'Union':
|
||||
if allocation.allocate_to == 'Union':
|
||||
roles_product = allocation.product
|
||||
else:
|
||||
roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)
|
||||
|
||||
if allocation.weight > roles_product.total_remain_weight:
|
||||
if allocation.allocate_to == 'Cooperative':
|
||||
if roles_product.total_receipt_weight >= allocation.weight:
|
||||
pass
|
||||
else:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
|
||||
else:
|
||||
|
||||
cooperative_roles_product = allocation.product
|
||||
if allocation.weight > cooperative_roles_product.total_remain_weight:
|
||||
return Response(
|
||||
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
allocation.trash = True
|
||||
allocation.save()
|
||||
if allocation.allocate_from == 'LiveStockProvinceJahad':
|
||||
jahad_warehousing(product)
|
||||
|
||||
elif allocation.allocate_from == 'Cooperative':
|
||||
pass
|
||||
else:
|
||||
union_warehousing(product)
|
||||
if allocation.allocate_to == 'Union':
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
|
||||
union=allocation.union)
|
||||
union_warehousing(reciver_product)
|
||||
elif allocation.allocate_to == 'Cooperative':
|
||||
|
||||
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
|
||||
cooperative=allocation.cooperative)
|
||||
cooperative_warehousing(reciver_product)
|
||||
else:
|
||||
pass
|
||||
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class CooperativeProductsShareViewSet(viewsets.ModelViewSet):
|
||||
queryset = CooperativeProductsShare.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = CooperativeProductsShareSerializer
|
||||
pagination_class = CustomPagination
|
||||
filterset_class = CooperativeProductsShareFilterSet
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
share = CooperativeProductsShare.objects.get(key=request.data['share_key'], trash=False)
|
||||
request.data.pop('share_key')
|
||||
|
||||
serializer = self.serializer_class(share)
|
||||
serializer.update(instance=share, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
shares = CooperativeProductsShare.objects.filter(product__name=request.GET['name'], trash=False).order_by(
|
||||
'id')
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
shares = shares.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
|
||||
page_size = request.query_params.get('page_size', None)
|
||||
if page_size:
|
||||
self.pagination_class.page_size = int(page_size)
|
||||
|
||||
page = self.paginate_queryset(shares)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(shares, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class LiveStockProductViewset(viewsets.ModelViewSet):
|
||||
queryset = LiveStockProduct.objects.all()
|
||||
permission_classes = [AllowAny]
|
||||
serializer_class = LiveStockProductSerializer
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
name =products[request.GET.get('name')]
|
||||
|
||||
products = LiveStockProduct.objects.filter(trash=False, name=name).first()
|
||||
serializer = self.serializer_class(products)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
products = LiveStockProduct.objects.get(key=request.data['key'])
|
||||
request.data.pop('key')
|
||||
serializer = self.serializer_class(products)
|
||||
serializer.update(instance=products, validated_data=request.data)
|
||||
# todo:اگه نیاز شده با ترد بنویس تا همه دامدار ها اپدیت بشن
|
||||
# send = threading.Thread(target=update_quota_rancher_threading)
|
||||
# send.start()
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class DashboardLiveStockAllocationsViewSet(viewsets.ModelViewSet):
|
||||
queryset = LiveStockAllocations.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockAllocationsSerializer
|
||||
filterset_class = LiveStockAllocationsFilterSet
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
role = request.GET.get('role')
|
||||
name =products[request.GET.get('name')]
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
|
||||
if request.GET['role'] == 'LiveStockProvinceJahad':
|
||||
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
|
||||
product__parent_product=product).order_by('id')
|
||||
roles_new_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
|
||||
, parent_product=product).first()
|
||||
|
||||
|
||||
elif request.GET['role'] == 'Union':
|
||||
allocations = LiveStockAllocations.objects.filter(union__user=user, trash=False,
|
||||
product__parent_product=product).order_by('id')
|
||||
|
||||
roles_new_product = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
|
||||
parent_product=product).first()
|
||||
|
||||
else:
|
||||
allocations = LiveStockAllocations.objects.filter(cooperative__user=user, trash=False,
|
||||
product__parent_product=product).order_by('id')
|
||||
roles_new_product = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
|
||||
parent_product=product).first()
|
||||
|
||||
date1 = request.GET.get('date1')
|
||||
date2 = request.GET.get('date2')
|
||||
if date1 and date2:
|
||||
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
|
||||
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
allocations = allocations.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
jahat_to_union = allocations.filter(jahad__isnull=False, allocate_to='Union')
|
||||
jahat_to_cooperative = allocations.filter(jahad__isnull=False, allocate_to='Cooperative')
|
||||
union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_to='Cooperative')
|
||||
if role == 'Union':
|
||||
union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False,trash=False, allocate_to='Cooperative')
|
||||
|
||||
jahat_to_union_weight = jahat_to_union.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
jahat_to_union_real_weight = jahat_to_union.aggregate(total=Sum('real_weight'))[
|
||||
'total'] or 0
|
||||
jahat_to_cooperative_weight = jahat_to_cooperative.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
jahat_to_cooperative_real_weight = jahat_to_cooperative.aggregate(total=Sum('real_weight'))[
|
||||
'total'] or 0
|
||||
union_to_cooperative_weight = union_to_cooperative.aggregate(total=Sum('weight'))[
|
||||
'total'] or 0
|
||||
union_to_cooperative_real_weight = union_to_cooperative.aggregate(total=Sum('real_weight'))[
|
||||
'total'] or 0
|
||||
|
||||
if role =='Union':
|
||||
role_product_union = roles_new_product.total_remain_weight
|
||||
role_product_cooperative = 0
|
||||
role_product_cooperative_receipt_weight = 0
|
||||
|
||||
elif role == 'Cooperative':
|
||||
role_product_union = 0
|
||||
role_product_cooperative = roles_new_product.total_remain_weight
|
||||
role_product_cooperative_receipt_weight = roles_new_product.total_receipt_weight
|
||||
|
||||
else:
|
||||
roles_product = LiveStockRolseProduct.objects.filter(trash=False, parent_product=product)
|
||||
union_remain = roles_product.filter(union__isnull=False)
|
||||
cooperative_remain = roles_product.filter(cooperative__isnull=False)
|
||||
role_product_union = union_remain.aggregate(total=Sum('total_remain_weight'))[
|
||||
'total'] or 0
|
||||
role_product_cooperative = cooperative_remain.aggregate(total=Sum('total_remain_weight'))[
|
||||
'total'] or 0
|
||||
role_product_cooperative_receipt_weight = cooperative_remain.aggregate(total=Sum('total_receipt_weight'))[
|
||||
'total'] or 0
|
||||
|
||||
if allocations:
|
||||
dict1 = {
|
||||
"total_weight": roles_new_product.total_weight,
|
||||
"jahad_to_union": jahat_to_union_weight,
|
||||
"jahat_to_union_real_weight": jahat_to_union_real_weight,
|
||||
"jahat_to_cooperative": jahat_to_cooperative_weight,
|
||||
"jahat_to_cooperative_real_weight": jahat_to_cooperative_real_weight,
|
||||
|
||||
"allocation_count": roles_new_product.total_allocated_weight,
|
||||
"union_to_cooperative": union_to_cooperative_weight,
|
||||
"union_to_cooperative_real_weight": union_to_cooperative_real_weight,
|
||||
"total_remain_weight_jahad": roles_new_product.total_remain_weight,
|
||||
"total_remain_weight_union": role_product_union,
|
||||
"total_remain_weight_cooperative": role_product_cooperative,
|
||||
"role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,
|
||||
"total_remain_weight": roles_new_product.total_remain_weight,
|
||||
}
|
||||
else:
|
||||
dict1 = {
|
||||
"total_weight": 0,
|
||||
"jahad_to_union": 0,
|
||||
"jahat_to_cooperative": 0,
|
||||
|
||||
"allocation_count": 0,
|
||||
"union_to_cooperative": 0,
|
||||
"total_remain_weight_jahad": 0,
|
||||
"total_remain_weight_union": 0,
|
||||
"total_remain_weight_cooperative": 0,
|
||||
"total_remain_weight": 0,
|
||||
"jahat_to_union_real_weight": 0,
|
||||
"union_to_cooperative_real_weight": 0,
|
||||
"jahat_to_cooperative_real_weight": 0,
|
||||
"role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,
|
||||
|
||||
}
|
||||
return Response(dict1, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class LiveStockWarehouseChargeAllocationsViewSet(viewsets.ModelViewSet):
|
||||
queryset = LiveStockAllocations.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockAllocationsSerializer
|
||||
pagination_class = CustomPagination
|
||||
filterset_class = LiveStockAllocationsFilterSet
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
products = {
|
||||
"bran":"سبوس",
|
||||
"barley":"جو",
|
||||
"soy":"سویا",
|
||||
"corn":"ذرت",
|
||||
"sheep_concentrate":"کنسانتره گوسفندی",
|
||||
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
|
||||
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
|
||||
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
|
||||
}
|
||||
name =products[request.GET.get('name')]
|
||||
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
|
||||
if request.GET['role'] == 'LiveStockProvinceJahad':
|
||||
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
|
||||
product__parent_product=product,
|
||||
allocate_to='LiveStockProvinceJahad').order_by('id')
|
||||
|
||||
elif request.GET['role'] == 'Union':
|
||||
allocations = LiveStockAllocations.objects.filter(allocate_from='LiveStockProvinceJahad', union__isnull=False,
|
||||
trash=False, product__parent_product=product).order_by(
|
||||
'id')
|
||||
|
||||
else:
|
||||
# allocations = LiveStockAllocations.objects.filter(
|
||||
# allocate_from__in=('LiveStockProvinceJahad', 'Union', 'Cooperative'), cooperative__user=user,
|
||||
# trash=False, product__parent_product=product).order_by('id')
|
||||
allocations = LiveStockAllocations.objects.filter(
|
||||
charge=True, cooperative__user=user,
|
||||
trash=False, product__parent_product=product).order_by('id')
|
||||
|
||||
date1 = request.GET.get('date1')
|
||||
date2 = request.GET.get('date2')
|
||||
if date1 and date2:
|
||||
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
|
||||
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
allocations = allocations.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
|
||||
page_size = request.query_params.get('page_size', None)
|
||||
if page_size:
|
||||
self.pagination_class.page_size = int(page_size)
|
||||
|
||||
page = self.paginate_queryset(allocations)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(allocations, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@csrf_exempt
|
||||
@permission_classes([TokenHasReadWriteScope])
|
||||
def get_user_live_stock(request):
|
||||
type = request.GET['type']
|
||||
if type == 'Union':
|
||||
unions = Union.objects.filter(trash=False).order_by('id')
|
||||
serializer = UnionSerializer(unions, many=True)
|
||||
|
||||
else:
|
||||
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
|
||||
serializer = RancherSerializer(cooperatives, many=True)
|
||||
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
0
LiveStock/LiveStoksAndPoultry/__init__.py
Normal file
0
LiveStock/LiveStoksAndPoultry/__init__.py
Normal file
174
LiveStock/LiveStoksAndPoultry/excel_processing.py
Normal file
174
LiveStock/LiveStoksAndPoultry/excel_processing.py
Normal file
@@ -0,0 +1,174 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
|
||||
import openpyxl
|
||||
import requests
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.db.models import Q
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.models import LiveStock, Rancher, Cooperative
|
||||
|
||||
#todo:فعلا چون دامدار تکراری داریم نمیشه ثبت کر باید از طریف آدرس بریم
|
||||
from authentication.models import SystemUserProfile, Province, City, SystemAddress
|
||||
from authentication.register import ARTA_REGISTER
|
||||
from panel.admin import PROJECT_API_KEY
|
||||
from panel.convert_date import convert_to_shamsi
|
||||
|
||||
|
||||
def add_rancher_to_live_stock(request):
|
||||
livestock=LiveStock.objects.filter(trash=False)
|
||||
for l in livestock:
|
||||
rancher=Rancher.objects.filter(trash=False,herd_code=l.herd_code).first()
|
||||
l.rancher=rancher
|
||||
l.save()
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def create_live_stock_and_rancher_from_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
read = openpyxl.load_workbook(BytesIO(file), data_only=True)
|
||||
sheet = read.active
|
||||
group = Group.objects.get(name='Rancher')
|
||||
password = '123456'
|
||||
result_list=[]
|
||||
yesterday= datetime.datetime.now().date() - datetime.timedelta(days=1)
|
||||
birth_day=convert_to_shamsi(day=yesterday.day,
|
||||
month=yesterday.month,
|
||||
year=yesterday.year).replace('-','/')
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i <= 1:
|
||||
continue
|
||||
first_name = row[1]
|
||||
last_name = row[2]
|
||||
rancher_name = row[3]
|
||||
type_rancher = row[4]
|
||||
herd_code = row[5]
|
||||
epidemiological_code = row[6]
|
||||
postal_code = row[7]
|
||||
type_live_stock = row[8]
|
||||
gender = row[9]
|
||||
national_id = row[10]
|
||||
mobile = row[11]
|
||||
city = row[12]
|
||||
range_live_stock = row[13]
|
||||
if not herd_code:
|
||||
herd_code = '0000' + str(national_id)
|
||||
mobile = str(mobile)
|
||||
|
||||
if len(mobile) < 10:
|
||||
continue
|
||||
if len(mobile) == 10:
|
||||
mobile = '0' + mobile
|
||||
|
||||
try:
|
||||
city_id = City.objects.filter(trash=False, name=city).first()
|
||||
province = Province.objects.filter(trash=False,key=city_id.province.key).first()
|
||||
|
||||
if not Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
|
||||
,trash=False).exists():
|
||||
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
|
||||
hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
|
||||
data = {
|
||||
"username": mobile,
|
||||
"first_name": first_name,
|
||||
"last_name": last_name,
|
||||
"password": hashed_password,
|
||||
"national_code": national_id,
|
||||
"role": "Rancher",
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
|
||||
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=mobile,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
fullname=first_name+' ' + last_name,
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password=password,
|
||||
birthday=datetime.datetime.now().date(),
|
||||
city=city_id,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
system_profile.role.add(group)
|
||||
address = SystemAddress(
|
||||
province=province,
|
||||
city=city_id,
|
||||
address='',
|
||||
|
||||
)
|
||||
address.save()
|
||||
system_profile=SystemUserProfile.objects.filter(trash=False, mobile=mobile).first()
|
||||
cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
|
||||
rancher = Rancher(
|
||||
user=system_profile,
|
||||
cooperative=cooperative,
|
||||
name=rancher_name,
|
||||
mobile=mobile,
|
||||
fullname=first_name + ' ' + last_name,
|
||||
city=city,
|
||||
herd_name=rancher_name,
|
||||
postal_code=postal_code,
|
||||
epidemiological_code=epidemiological_code,
|
||||
herd_code=herd_code,
|
||||
national_id=national_id,
|
||||
type='rural' if type_rancher == 'روستایی' else 'industrial'
|
||||
|
||||
|
||||
)
|
||||
rancher.save()
|
||||
rancher = Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
|
||||
,trash=False).first()
|
||||
if rancher:
|
||||
live_stock_count = LiveStock.objects.filter(trash=False, herd_code=rancher.herd_code,
|
||||
type=type_live_stock)\
|
||||
.count()
|
||||
if live_stock_count > int(range_live_stock):
|
||||
new_range = live_stock_count - range_live_stock
|
||||
for _i in range(new_range):
|
||||
live_stock = LiveStock.objects.filter(
|
||||
herd_code=rancher.herd_code,
|
||||
type=type_live_stock,
|
||||
trash=False
|
||||
).first()
|
||||
live_stock.trash = True
|
||||
live_stock.save()
|
||||
elif live_stock_count < int(range_live_stock):
|
||||
new_range = range_live_stock - live_stock_count
|
||||
for _i in range(new_range):
|
||||
live_stock = LiveStock(
|
||||
herd_code=rancher.herd_code,
|
||||
type=type_live_stock,
|
||||
birth_day=birth_day,
|
||||
birth_day_gh=yesterday,
|
||||
gender=gender,
|
||||
|
||||
)
|
||||
live_stock.save()
|
||||
except:
|
||||
result_list.append(rancher_name)
|
||||
|
||||
return Response(result_list)
|
||||
22
LiveStock/LiveStoksAndPoultry/filterset.py
Normal file
22
LiveStock/LiveStoksAndPoultry/filterset.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import LiveStock
|
||||
|
||||
|
||||
class LiveStockFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = LiveStock
|
||||
fields = [
|
||||
'national_id_livestock_code',
|
||||
'herd_code',
|
||||
'type',
|
||||
'gender',
|
||||
'contractor_code',
|
||||
'unique_identifier',
|
||||
'agent',
|
||||
'registering_user',
|
||||
'rancher__user__mobile',
|
||||
'rancher__user__first_name',
|
||||
'rancher__user__last_name',
|
||||
'rancher__user__fullname'
|
||||
]
|
||||
19
LiveStock/LiveStoksAndPoultry/helpers.py
Normal file
19
LiveStock/LiveStoksAndPoultry/helpers.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from django.http import HttpResponse
|
||||
|
||||
from LiveStock.helpers import convert_to_miladi
|
||||
from LiveStock.models import LiveStock, LiveStockRolseProduct, LiveStockProduct, Rancher
|
||||
|
||||
|
||||
def add_birthday(reqeust):
|
||||
live_stock=LiveStock.objects.filter(trash=False,birth_day_gh__isnull=True).only('birth_day')
|
||||
for l in live_stock:
|
||||
birth_day=l.birth_day.split('/')
|
||||
birth_day_gh=convert_to_miladi(year=int(birth_day[0]),month=int(birth_day[1]),day=int(birth_day[2]))
|
||||
l.birth_day_gh=birth_day_gh
|
||||
l.save()
|
||||
return HttpResponse('ok')
|
||||
|
||||
def add_live_stock(request):
|
||||
rancher=Rancher.objects.get(herd_code='139894930',trash=False)
|
||||
for _i in rancher(110):
|
||||
pass
|
||||
36
LiveStock/LiveStoksAndPoultry/serializers.py
Normal file
36
LiveStock/LiveStoksAndPoultry/serializers.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from django.db.models import Sum
|
||||
from rest_framework import serializers
|
||||
|
||||
from LiveStock.Cooperative.serializers import CooperativeSerializer
|
||||
from LiveStock.Rancher.serializers import RancherSerializer
|
||||
from LiveStock.models import LiveStock, Rancher
|
||||
import datetime
|
||||
|
||||
class LiveStockSerializer(serializers.ModelSerializer):
|
||||
rancher = serializers.SerializerMethodField('get_rancher')
|
||||
age = serializers.SerializerMethodField('get_age')
|
||||
|
||||
class Meta:
|
||||
model = LiveStock
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
|
||||
def get_rancher(self,instance):
|
||||
rancher=Rancher.objects.filter(herd_code=instance.herd_code).first()
|
||||
ser_data=RancherSerializer(rancher)
|
||||
return ser_data.data
|
||||
|
||||
def get_age(self,instance):
|
||||
if instance.birth_day_gh:
|
||||
now=datetime.datetime.now().date()
|
||||
age=(now - instance.birth_day_gh.date()).days
|
||||
return age
|
||||
else:
|
||||
return None
|
||||
|
||||
class PosLiveStockSerializer(serializers.ModelSerializer):
|
||||
cooperative=CooperativeSerializer(read_only=True)
|
||||
class Meta:
|
||||
model = Rancher
|
||||
fields = ['key','fullname','cooperative','mobile','city','herd_code','national_id','allow_buy','weight_allocation_heavy','weight_allocation_light']
|
||||
28
LiveStock/LiveStoksAndPoultry/urls.py
Normal file
28
LiveStock/LiveStoksAndPoultry/urls.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.LiveStoksAndPoultry import views as live_stock_views
|
||||
from LiveStock.LiveStoksAndPoultry.excel_processing import create_live_stock_and_rancher_from_excel
|
||||
from LiveStock.LiveStoksAndPoultry.helpers import add_birthday
|
||||
from LiveStock.LiveStoksAndPoultry.views import dashboard_live_stock
|
||||
from LiveStock.Rancher.excel_processing import get_rancher_excel, get_union_excel, get_cooperative_excel
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'live-stock-view',
|
||||
live_stock_views.LiveStockViewSet,
|
||||
basename="live-stock-view"
|
||||
)
|
||||
router.register(
|
||||
r'pos-live-stock',
|
||||
live_stock_views.PosLiveStockViewSet,
|
||||
basename="pos-live-stock"
|
||||
)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('dashboard_live_stock/', dashboard_live_stock),
|
||||
path('add_birthday/', add_birthday),
|
||||
path('create_live_stock_and_rancher_from_excel/', create_live_stock_and_rancher_from_excel),
|
||||
|
||||
]
|
||||
459
LiveStock/LiveStoksAndPoultry/views.py
Normal file
459
LiveStock/LiveStoksAndPoultry/views.py
Normal file
@@ -0,0 +1,459 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import jdatetime
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django.db.models import Count, Q
|
||||
from django.http import HttpResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.LiveStoksAndPoultry.filterset import LiveStockFilterSet
|
||||
from LiveStock.LiveStoksAndPoultry.serializers import LiveStockSerializer, PosLiveStockSerializer
|
||||
from LiveStock.Rancher.helpers import update_one_rancher
|
||||
from LiveStock.helpers import build_query, CustomPagination, convert_to_miladi
|
||||
from LiveStock.models import LiveStock, Rancher, LiveStockProduct, LiveStockRolseProduct, Cooperative, Union, \
|
||||
CooperativeProductsShare
|
||||
from authentication.models import SystemUserProfile
|
||||
from panel.models import POSMachine, PosMachineTransactions
|
||||
from panel.validate_headers import PosDeviceValidator
|
||||
|
||||
|
||||
class LiveStockViewSet(viewsets.ModelViewSet):
|
||||
queryset = LiveStock.objects.filter(trash=False).order_by('-birth_day_gh')
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = LiveStockSerializer
|
||||
filterset_class = LiveStockFilterSet
|
||||
pagination_class = CustomPagination
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
role = request.GET['role']
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
type=request.GET.get('type')
|
||||
if type == 'archive':
|
||||
live_stocks=LiveStock.objects.filter(trash=True,archive=True).order_by('-birth_day_gh')
|
||||
else:
|
||||
live_stocks=LiveStock.objects.filter(trash=False).order_by('-birth_day_gh')
|
||||
|
||||
if role == 'Cooperative':
|
||||
# todo:فعلا چون دامدار تکراری داریم نمیشه از طریق دامدار پیداکرد باید از طریف آدرس بریم
|
||||
cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
|
||||
flat=True).distinct()
|
||||
live_stocks = live_stocks.filter(herd_code__in=ranchers)
|
||||
|
||||
date1 = request.GET.get('date1')
|
||||
date2 = request.GET.get('date2')
|
||||
if date1 and date2:
|
||||
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
live_stocks = live_stocks.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
page = self.paginate_queryset(live_stocks)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(live_stocks, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
rancher = Rancher.objects.get(key=request.data['rancher_key'])
|
||||
request.data.pop('rancher_key')
|
||||
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
live_stock = serializer.create(validated_data=request.data)
|
||||
live_stock.rancher = rancher
|
||||
live_stock.herd_code = rancher.herd_code
|
||||
live_stock.contractor_code = rancher.contractor_code
|
||||
live_stock.save()
|
||||
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
user=SystemUserProfile.objects.filter(trash=False,user=request.user).first()
|
||||
|
||||
filter_kwargs = {'key': request.data['live_stock_key']}
|
||||
if 'return_from_archive' in request.data.keys():
|
||||
filter_kwargs['trash']=True
|
||||
filter_kwargs['archive']=True
|
||||
else:
|
||||
filter_kwargs['trash'] = False
|
||||
|
||||
live_stock = LiveStock.objects.get(**filter_kwargs)
|
||||
live_stocks = LiveStock.objects.filter(herd_code=live_stock.herd_code, trash=False)
|
||||
rancher = Rancher.objects.get(herd_code=live_stock.herd_code)
|
||||
|
||||
request.data.pop('live_stock_key')
|
||||
serializer = self.serializer_class(live_stock)
|
||||
if 'herd_code' in request.data.keys() and request.data['herd_code']:
|
||||
rancher.herd_code = request.data['herd_code']
|
||||
rancher.save()
|
||||
live_stocks.update(herd_code=request.data['herd_code'])
|
||||
if 'return_from_archive' in request.data.keys():
|
||||
live_stock.archive = False
|
||||
live_stock.trash = False
|
||||
live_stock.returner_from_archive=user.fullname
|
||||
live_stock.return_from_archive_date=datetime.now()
|
||||
live_stock.save()
|
||||
request.data.pop('return_from_archive')
|
||||
|
||||
serializer.update(instance=live_stock, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
user=SystemUserProfile.objects.filter(trash=False,user=request.user).first()
|
||||
live_stock = LiveStock.objects.get(key=request.GET['live_stock_key'], trash=False)
|
||||
if not live_stock.birth_day_gh:
|
||||
year, month, day = map(int, live_stock.birth_day.split('/'))
|
||||
live_stock.birth_day_gh = convert_to_miladi(year, month, day)
|
||||
live_stock.save()
|
||||
live_stock.trash=True
|
||||
live_stock.archive=True
|
||||
live_stock.archiver=user.fullname
|
||||
live_stock.archive_date=datetime.now()
|
||||
live_stock.age_of_archive=(datetime.now().date() - live_stock.birth_day_gh.date()).days
|
||||
live_stock.save()
|
||||
|
||||
return Response({"result":"با موفقیت بایگانی شد."}, status=status.HTTP_200_OK)
|
||||
|
||||
class PosLiveStockViewSet(viewsets.ModelViewSet):
|
||||
queryset = Rancher.objects.all()
|
||||
permission_classes = [AllowAny]
|
||||
serializer_class = PosLiveStockSerializer
|
||||
|
||||
def get_transactions_month(self,natcode):
|
||||
import json
|
||||
transactions = PosMachineTransactions.objects.filter(natcode=natcode,paid=True,live_stock=True, trash=False)
|
||||
|
||||
has_month_data = False
|
||||
last_month = None
|
||||
earliest_transaction_date = None
|
||||
|
||||
for transaction in transactions:
|
||||
try:
|
||||
additional_data = json.loads(transaction.additional)
|
||||
if 'month' in additional_data and isinstance(additional_data['month'], list):
|
||||
has_month_data = True
|
||||
for month in additional_data['month']:
|
||||
if last_month is None or month > last_month:
|
||||
last_month = month
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
pass
|
||||
|
||||
if hasattr(transaction, 'create_date'):
|
||||
created_date = transaction.create_date
|
||||
if earliest_transaction_date is None or created_date < earliest_transaction_date:
|
||||
earliest_transaction_date = created_date
|
||||
|
||||
future_months = []
|
||||
|
||||
if not transactions:
|
||||
base_date = jdatetime.date.today().togregorian() - relativedelta(months=1)
|
||||
include_current = True
|
||||
elif has_month_data and last_month:
|
||||
year = int(str(last_month)[:4])
|
||||
month = int(str(last_month)[4:6])
|
||||
base_date = jdatetime.date(year, month, 1).togregorian()
|
||||
include_current = False
|
||||
else:
|
||||
if earliest_transaction_date:
|
||||
base_date = earliest_transaction_date
|
||||
else:
|
||||
base_date = jdatetime.date.today().togregorian()
|
||||
include_current = False
|
||||
|
||||
start_offset = 0 if include_current else 1
|
||||
|
||||
for i in range(start_offset, start_offset + 6):
|
||||
future_date = base_date + relativedelta(months=i)
|
||||
jd_future = jdatetime.date.fromgregorian(date=future_date)
|
||||
future_months.append(int(f"{jd_future.year}{jd_future.month:02d}"))
|
||||
|
||||
|
||||
|
||||
return future_months
|
||||
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
validator = PosDeviceValidator(request)
|
||||
validation_error = validator.validation_version()
|
||||
if validation_error:
|
||||
return validation_error
|
||||
|
||||
validation_device = validator.validation_device()
|
||||
if not validation_device:
|
||||
return Response({"result": "نشست شما منقضی شده لطفا محدد وارد شوید!"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
pos = POSMachine.objects.get(pos_id=validation_device)
|
||||
if pos.cooperative is None:
|
||||
return Response({"result": "دستگاه شما برای مدیریت امور دام تعریف نشده است!"},
|
||||
status=403)
|
||||
|
||||
if int(validator.device_version) < 218:
|
||||
return Response(
|
||||
{"result": "لطفا جهت بروزرسانی نسخه دستگاه کارت خوان با پشتیبانی دستگاه ارتباط بگیرید!"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if 'nath_id' in request.GET:
|
||||
ranchers = Rancher.objects.filter(national_id=request.GET['nath_id'], trash=False).first()
|
||||
if not ranchers:
|
||||
return Response({"result": "دامدار یافت نشد!"},
|
||||
status=403)
|
||||
|
||||
union = Union.objects.filter(trash=False).first()
|
||||
if 'product_key' in request.GET:
|
||||
product = LiveStockRolseProduct.objects.filter(key=request.GET['product_key'], trash=False).select_related(
|
||||
'parent_product').only('parent_product__price', 'parent_product__name', 'parent_product__image',
|
||||
'parent_product__light_wight', 'parent_product__heavy_wight',
|
||||
'parent_product__shipping_price', 'parent_product__union_price',
|
||||
'parent_product__cooperative_price').first()
|
||||
else:
|
||||
product = LiveStockRolseProduct.objects.filter(cooperative=pos.cooperative, trash=False).select_related(
|
||||
'parent_product').only('parent_product__price', 'parent_product__name', 'parent_product__image',
|
||||
'parent_product__light_wight', 'parent_product__heavy_wight',
|
||||
'parent_product__shipping_price', 'parent_product__union_price',
|
||||
'parent_product__cooperative_price').first()
|
||||
main_product = product.parent_product
|
||||
share = CooperativeProductsShare.objects.get(product=main_product, cooperative=pos.cooperative, trash=False)
|
||||
|
||||
if ranchers.type == 'rural':
|
||||
heavy_rate= product.parent_product.heavy_wight
|
||||
light_rate= product.parent_product.light_wight
|
||||
else:
|
||||
heavy_rate= product.parent_product.heavy_wight_industrial
|
||||
light_rate= product.parent_product.light_wight_industrial
|
||||
|
||||
|
||||
|
||||
month_list = self.get_transactions_month(request.GET['nath_id'])
|
||||
shares_list = []
|
||||
if share.union_price > 0:
|
||||
|
||||
shares_list.append({
|
||||
"name":'union',
|
||||
"shaba":union.account,
|
||||
"price":share.union_price,
|
||||
})
|
||||
if share.company_price > 0:
|
||||
|
||||
shares_list.append({
|
||||
"name":'company',
|
||||
"shaba":"IR170150000003100050545702",
|
||||
"price":share.company_price,
|
||||
})
|
||||
|
||||
if pos.cooperative.first_sub_cooperative_price > 0:
|
||||
|
||||
shares_list.append({
|
||||
"name":'first_sub_cooperative',
|
||||
"shaba":pos.cooperative.first_sub_cooperative_account,
|
||||
"price":pos.cooperative.first_sub_cooperative_price,
|
||||
})
|
||||
|
||||
if pos.cooperative.second_sub_cooperative_price > 0:
|
||||
|
||||
shares_list.append({
|
||||
"name":'second_sub_cooperative',
|
||||
"shaba":pos.cooperative.second_sub_cooperative_price,
|
||||
"price":pos.cooperative.second_sub_cooperative_price,
|
||||
})
|
||||
|
||||
|
||||
|
||||
dict1 = {
|
||||
"title": [
|
||||
{"key": "نام و نام خانوادگی", "value": ranchers.fullname if ranchers.fullname else ranchers.user.fullname},
|
||||
{"key": "موبایل", "value": ranchers.mobile},
|
||||
{"key": "وزن کل خریداری شده", "value": str(ranchers.total_weight)}
|
||||
],
|
||||
"key": ranchers.key,
|
||||
"herd_code": ranchers.herd_code,
|
||||
"national_id": ranchers.national_id,
|
||||
"fullname": ranchers.fullname if ranchers.fullname else ranchers.user.fullname,
|
||||
"type": ranchers.type,
|
||||
"mobile": ranchers.mobile,
|
||||
"allow_buy": ranchers.allow_buy,
|
||||
"more_than_inventory": True,
|
||||
"pos_owners": [],
|
||||
"allow_buy_message": " ",
|
||||
"real_light_livestock": ranchers.light_livestock, # تعداد تعیین شده دام توسط سامانه
|
||||
"real_heavy_livestock": ranchers.heavy_livestock, # تعداد تعیین شده دام توسط سامانه
|
||||
"real_dhi_livestock": 0, # تعداد تعیین شده دام توسط سامانه
|
||||
"weight_quota_heavy": ranchers.weight_quota_heavy, # سهمیه قابل دریافت
|
||||
"weight_quota_light": ranchers.weight_quota_light, # سهمیه قابل دریافت
|
||||
"weight_quota_dhi": ranchers.dhi_amount, # سهمیه قابل دریافت
|
||||
"heavy_rate": heavy_rate, # نرخ تبدیل جهت دریافت سهمیه
|
||||
"light_rate": light_rate, # نرخ تبدیل جهت دریافت سهمیه
|
||||
"dhi_rate": product.parent_product.heavy_wight_dha, # نرخ تبدیل جهت دریافت سهمیه
|
||||
"round_rate": 1, # مضرب رند کردن فروش
|
||||
"total_weight": ranchers.total_weight, # کل خرید دامدار ریم د دمش
|
||||
|
||||
"product_total_weight": product.total_weight,
|
||||
"product_total_allocated_weight": product.total_allocated_weight,
|
||||
"product_total_remain_weight": product.total_remain_weight,
|
||||
"product_name": product.parent_product.name,
|
||||
"product_image": product.parent_product.image,
|
||||
"product_price": share.price,
|
||||
"cooperative_price_with_shipping": share.price + share.shipping_price + share.cooperative_price,
|
||||
"cooperative_price_without_shipping": share.price + share.cooperative_price,
|
||||
"union_price": share.union_price,
|
||||
"union_shaba": union.account,
|
||||
"shares": shares_list,
|
||||
"cooperative_shaba": pos.cooperative.account,
|
||||
"month_list": month_list,
|
||||
|
||||
}
|
||||
return Response(dict1, status=status.HTTP_200_OK)
|
||||
|
||||
return Response({"resut": "کد ملی وارد نشده است!"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
# class DashboardLiveStockViewSet(viewsets.ModelViewSet):
|
||||
# queryset = LiveStock.objects.filter(trash=False)
|
||||
# permission_classes = [TokenHasReadWriteScope]
|
||||
# serializer_class = LiveStockSerializer
|
||||
# filterset_class = LiveStockFilterSet
|
||||
#
|
||||
# def list(self, request, *args, **kwargs):
|
||||
# role = request.GET['role']
|
||||
# user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
# if role == 'Cooperative':
|
||||
# # todo:فعلا چون دامدار تکراری داریم نمیشه از طریق دامدار پیداکرد باید از طریف آدرس بریم
|
||||
# cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
# ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
|
||||
# flat=True).distinct()
|
||||
# live_stocks = self.queryset.filter(herd_code__in=ranchers)
|
||||
# else:
|
||||
# live_stocks = self.queryset
|
||||
# date1 = request.GET.get('date1')
|
||||
# date2 = request.GET.get('date2')
|
||||
# if date1 and date2:
|
||||
# date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
# date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
# live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
|
||||
#
|
||||
# value = request.GET.get('value')
|
||||
# search = request.GET.get('search')
|
||||
# if value and search == 'filter':
|
||||
# if search != 'undefined' and search.strip():
|
||||
# live_stocks = live_stocks.filter(
|
||||
# build_query(self.filterset_class.Meta.fields, value)
|
||||
# )
|
||||
# sheep = live_stocks.filter(type='گوسفند').count()
|
||||
# goat = live_stocks.filter(type='بز').count()
|
||||
# cow = live_stocks.filter(type='گاو').count()
|
||||
# horse = live_stocks.filter(type='اسب').count()
|
||||
# camel = live_stocks.filter(type='شتر').count()
|
||||
# light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
|
||||
# heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
|
||||
#
|
||||
# dict1={
|
||||
# 'live_stocks_count':live_stocks.count(),
|
||||
# "sheep":sheep,
|
||||
# "goat":goat,
|
||||
# "cow":cow,
|
||||
# "horse":horse,
|
||||
# "camel":camel,
|
||||
# "light_livestock":light_livestock,
|
||||
# "heavy_livestock":heavy_livestock,
|
||||
#
|
||||
# }
|
||||
# return Response(dict1, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@csrf_exempt
|
||||
@permission_classes([TokenHasReadWriteScope])
|
||||
def dashboard_live_stock(request):
|
||||
role = request.GET['role']
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
type = request.GET.get('type')
|
||||
if type == 'archive':
|
||||
live_stocks = LiveStock.objects.filter(trash=True, archive=True).only('type')
|
||||
else:
|
||||
live_stocks = LiveStock.objects.filter(trash=False).only('type')
|
||||
|
||||
if role == 'Cooperative':
|
||||
cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
|
||||
flat=True).distinct()
|
||||
live_stocks = live_stocks.filter(herd_code__in=ranchers)
|
||||
|
||||
date1 = request.GET.get('date1')
|
||||
date2 = request.GET.get('date2')
|
||||
if date1 and date2:
|
||||
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
|
||||
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
|
||||
live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
live_stocks = live_stocks.filter(
|
||||
build_query(LiveStockFilterSet.Meta.fields, value)
|
||||
)
|
||||
counts = live_stocks.values('type').annotate(total=Count('id'))
|
||||
count_dict = {item['type']: item['total'] for item in counts}
|
||||
|
||||
light_livestock = count_dict.get('بز', 0) + count_dict.get('گوسفند', 0)
|
||||
heavy_livestock = count_dict.get('گاو', 0) + count_dict.get('اسب', 0) + count_dict.get('شتر', 0)
|
||||
|
||||
result = {
|
||||
'live_stocks_count': sum(count_dict.values()),
|
||||
"sheep": count_dict.get('گوسفند', 0),
|
||||
"goat": count_dict.get('بز', 0),
|
||||
"cow": count_dict.get('گاو', 0),
|
||||
"horse": count_dict.get('اسب', 0),
|
||||
"camel": count_dict.get('شتر', 0),
|
||||
"light_livestock": light_livestock,
|
||||
"heavy_livestock": heavy_livestock,
|
||||
}
|
||||
|
||||
return Response(result, status=status.HTTP_200_OK)
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
def archive_live_stock(request):
|
||||
today = date.today()
|
||||
archive_msg = 'بایگانی خودکار به علت سن بالا'
|
||||
|
||||
stocks_to_convert = LiveStock.objects.filter(trash=False, birth_day_gh__isnull=True)
|
||||
for stock in stocks_to_convert:
|
||||
try:
|
||||
year, month, day = map(int, stock.birth_day.split('/'))
|
||||
stock.birth_day_gh = convert_to_miladi(year, month, day)
|
||||
stock.save()
|
||||
except:
|
||||
continue
|
||||
|
||||
archive_conditions = Q(
|
||||
Q(type__in=['بز', 'گوسفند'], gender='نر') & Q(birth_day_gh__lte=today - timedelta(days=425)) |
|
||||
Q(type__in=['بز', 'گوسفند'], gender='ماده') & Q(birth_day_gh__lte=today - timedelta(days=1825)) |
|
||||
Q(type='گاو') & Q(birth_day_gh__lte=today - timedelta(days=3285)) |
|
||||
Q(type='اسب') & Q(birth_day_gh__lte=today - timedelta(days=4380))
|
||||
)
|
||||
|
||||
archived_count = LiveStock.objects.filter(
|
||||
trash=False,
|
||||
birth_day_gh__isnull=False
|
||||
).filter(archive_conditions).update(
|
||||
trash=True,
|
||||
archive=True,
|
||||
archiver=archive_msg
|
||||
)
|
||||
|
||||
|
||||
|
||||
return HttpResponse('ok')
|
||||
0
LiveStock/Rancher/__init__.py
Normal file
0
LiveStock/Rancher/__init__.py
Normal file
608
LiveStock/Rancher/excel_processing.py
Normal file
608
LiveStock/Rancher/excel_processing.py
Normal file
@@ -0,0 +1,608 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
|
||||
import requests
|
||||
from django.contrib.auth.models import User, Group
|
||||
from django.db.models import Count
|
||||
from django.http import HttpResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment
|
||||
from rest_framework import status
|
||||
import openpyxl
|
||||
from io import BytesIO
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import permission_classes, api_view
|
||||
from rest_framework.permissions import AllowAny
|
||||
|
||||
from LiveStock.Rancher.helpers import update_one_rancher
|
||||
from LiveStock.helpers import convert_to_miladi
|
||||
from LiveStock.models import Rancher, Cooperative, Union, Contractor, LiveStockRolseProduct, LiveStockProvinceJahad, \
|
||||
LiveStock
|
||||
from authentication.models import SystemUserProfile, Province, SystemAddress, City
|
||||
from authentication.register import ARTA_REGISTER
|
||||
from panel.admin import PROJECT_API_KEY
|
||||
from panel.helper_excel import create_header, excel_description, create_header_freez, create_value
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_rancher_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
group = Group.objects.get(name__exact="Rancher")
|
||||
system_user = SystemUserProfile.objects.filter(trash=False)
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i < 1:
|
||||
continue
|
||||
herd_code = row[0]
|
||||
epidemiological_code = row[1]
|
||||
postal_code = row[2]
|
||||
unit_id = row[3]
|
||||
herd_name = row[4]
|
||||
national_id = row[5]
|
||||
name = row[6]
|
||||
mobile = row[7]
|
||||
city = row[9]
|
||||
lng = row[10]
|
||||
lot = row[11]
|
||||
registering_user = row[12]
|
||||
mobile = str(mobile)
|
||||
|
||||
if len(mobile) < 10:
|
||||
continue
|
||||
if len(mobile) == 10:
|
||||
mobile = '0' + mobile
|
||||
|
||||
full_name = name.split(':')
|
||||
if not system_user.filter(mobile=mobile).exists():
|
||||
if not User.objects.filter(username=mobile).exists():
|
||||
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
|
||||
data = {
|
||||
"username": mobile,
|
||||
"first_name": full_name[0],
|
||||
"last_name": full_name[1],
|
||||
"password": hashed_password,
|
||||
"national_code": national_id,
|
||||
"role": "Rancher",
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
province = Province.objects.filter(trash=False).first()
|
||||
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1],
|
||||
password=hashed_password)
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
city_id = City.objects.filter(trash=False, id=city).first()
|
||||
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=mobile,
|
||||
first_name=full_name[0],
|
||||
last_name=full_name[1],
|
||||
fullname=name,
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password='1404',
|
||||
birthday=datetime.datetime.now().date(),
|
||||
city=city_id,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
system_profile.role.add(group)
|
||||
address = SystemAddress(
|
||||
province=province,
|
||||
city=city_id,
|
||||
address=city,
|
||||
postal_code=postal_code
|
||||
|
||||
)
|
||||
address.save()
|
||||
cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
|
||||
if not Rancher.objects.filter(trash=False, herd_code=herd_code).exists():
|
||||
rancher = Rancher(
|
||||
user=system_profile,
|
||||
address=address,
|
||||
cooperative=cooperative,
|
||||
name=name,
|
||||
registering_user=registering_user,
|
||||
lng=lng,
|
||||
lot=lot,
|
||||
mobile=mobile,
|
||||
fullname=name,
|
||||
city=city,
|
||||
herd_name=herd_name,
|
||||
unit_id=unit_id,
|
||||
postal_code=postal_code,
|
||||
epidemiological_code=epidemiological_code,
|
||||
herd_code=herd_code,
|
||||
national_id=national_id,
|
||||
|
||||
)
|
||||
rancher.save()
|
||||
|
||||
return Response({"result": "ok"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_union_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
group = Group.objects.get(name__exact="Union")
|
||||
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i < 3:
|
||||
continue
|
||||
type = row[4]
|
||||
address = row[5]
|
||||
|
||||
name = row[2]
|
||||
mobile = row[6]
|
||||
|
||||
mobile = str(mobile)
|
||||
|
||||
if len(mobile) < 10:
|
||||
continue
|
||||
if len(mobile) == 10:
|
||||
mobile = '0' + mobile
|
||||
print(mobile)
|
||||
full_name = name.split(' ')
|
||||
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
|
||||
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
|
||||
data = {
|
||||
"username": mobile,
|
||||
"first_name": full_name[0],
|
||||
"last_name": full_name[1],
|
||||
"password": hashed_password,
|
||||
"national_code": '0',
|
||||
"role": "Union",
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
province = Province.objects.filter(trash=False).first()
|
||||
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1], password=hashed_password)
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
city_id = City.objects.filter(trash=False, name='همدان').first()
|
||||
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=mobile,
|
||||
first_name=full_name[0],
|
||||
last_name=full_name[1],
|
||||
fullname=name,
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password='1404',
|
||||
birthday=datetime.datetime.now().date(),
|
||||
city=city_id,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
system_profile.role.add(group)
|
||||
address = SystemAddress(
|
||||
province=province,
|
||||
city=city_id,
|
||||
address=address,
|
||||
|
||||
)
|
||||
address.save()
|
||||
if not Union.objects.filter(trash=False, user__mobile=mobile).exists():
|
||||
union = Union(
|
||||
user=system_profile,
|
||||
address=address,
|
||||
name=name,
|
||||
mobile=mobile,
|
||||
type=type,
|
||||
|
||||
)
|
||||
union.save()
|
||||
# role_product=LiveStockRolseProduct(union=union)
|
||||
# role_product.save()
|
||||
|
||||
return Response({"result": "ok"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_cooperative_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
group = Group.objects.get(name__exact="Cooperative")
|
||||
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i < 3:
|
||||
continue
|
||||
city = row[3]
|
||||
address = row[5]
|
||||
|
||||
name = row[4]
|
||||
mobile = row[6]
|
||||
national_id = row[7]
|
||||
|
||||
mobile = str(mobile)
|
||||
|
||||
if len(mobile) < 10:
|
||||
continue
|
||||
if len(mobile) == 10:
|
||||
mobile = '0' + mobile
|
||||
print(mobile)
|
||||
full_name = name.split(' ')
|
||||
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
|
||||
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
|
||||
data = {
|
||||
"username": mobile,
|
||||
"first_name": full_name[0],
|
||||
"last_name": full_name[1],
|
||||
"password": hashed_password,
|
||||
"national_code": national_id,
|
||||
"role": "Cooperative",
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
province = Province.objects.filter(trash=False).first()
|
||||
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1:], password=hashed_password)
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
city_id = City.objects.filter(trash=False, name__contains=city).first()
|
||||
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=mobile,
|
||||
first_name=full_name[0],
|
||||
last_name=full_name[1],
|
||||
fullname=name,
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password='1404',
|
||||
birthday=datetime.datetime.now().date(),
|
||||
city=city_id,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
system_profile.role.add(group)
|
||||
address = SystemAddress(
|
||||
province=province,
|
||||
city=city_id,
|
||||
address=address,
|
||||
|
||||
)
|
||||
address.save()
|
||||
if not Cooperative.objects.filter(trash=False, user__mobile=mobile).exists():
|
||||
cooperative = Cooperative(
|
||||
user=system_profile,
|
||||
address=address,
|
||||
name=name,
|
||||
mobile=mobile,
|
||||
national_id=national_id,
|
||||
|
||||
)
|
||||
cooperative.save()
|
||||
# role_product=LiveStockRolseProduct(union=union)
|
||||
# role_product.save()
|
||||
|
||||
return Response({"result": "ok"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
def hgsahgsad(request):
|
||||
rancher = Cooperative.objects.all().order_by('id')
|
||||
for r in rancher:
|
||||
m=LiveStockRolseProduct(
|
||||
cooperative=r
|
||||
)
|
||||
m.save()
|
||||
return HttpResponse('ok')
|
||||
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def generate_random_phone_number():
|
||||
prefix = "0908"
|
||||
used_numbers = set()
|
||||
|
||||
while True:
|
||||
suffix = ''.join([str(random.randint(0, 9)) for _ in range(7)])
|
||||
full_number = prefix + suffix
|
||||
|
||||
if not SystemUserProfile.objects.filter(mobile=full_number):
|
||||
used_numbers.add(full_number)
|
||||
return full_number
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_contractor_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
group = Group.objects.get(name__exact="Cooperative")
|
||||
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i < 1:
|
||||
continue
|
||||
contractor_code = row[0]
|
||||
first_name = row[1]
|
||||
last_name = row[2]
|
||||
full_name=first_name+ ' ' + last_name
|
||||
entity_code=row[3]
|
||||
city=row[4]
|
||||
national_id=row[5]
|
||||
postal_code=row[7]
|
||||
company_name=row[8]
|
||||
|
||||
mobile = str(generate_random_phone_number())
|
||||
|
||||
|
||||
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
|
||||
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
|
||||
data = {
|
||||
"username": mobile,
|
||||
"first_name": first_name,
|
||||
"last_name": last_name,
|
||||
"password": hashed_password,
|
||||
"national_code": national_id,
|
||||
"role": "Contractor",
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
province = Province.objects.filter(trash=False).first()
|
||||
user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
city_id = City.objects.filter(trash=False, id=city).first()
|
||||
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=mobile,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
fullname=full_name,
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password='1404',
|
||||
birthday=datetime.datetime.now().date(),
|
||||
city=city_id,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
system_profile.role.add(group)
|
||||
address = SystemAddress(
|
||||
province=province,
|
||||
city=city_id,
|
||||
postal_code=postal_code,
|
||||
|
||||
)
|
||||
address.save()
|
||||
if not Contractor.objects.filter(trash=False, user__mobile=mobile).exists():
|
||||
contractor = Contractor(
|
||||
user=system_profile,
|
||||
address=address,
|
||||
contractor_code=contractor_code,
|
||||
fullname=full_name,
|
||||
entity_code=entity_code,
|
||||
national_id=national_id,
|
||||
company_name=company_name
|
||||
|
||||
)
|
||||
contractor.save()
|
||||
# role_product=LiveStockRolseProduct(union=union)
|
||||
# role_product.save()
|
||||
|
||||
return Response({"result": "ok"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
def kjdfjsd(request):
|
||||
live=LiveStock.objects.filter(birth_day_gh__isnull=True).count()
|
||||
return HttpResponse(live)
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_live_stock_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
|
||||
existing_codes = set(LiveStock.objects.filter(trash=False).values_list('national_id_livestock_code', flat=True))
|
||||
|
||||
live_stocks_to_create = []
|
||||
l = 0
|
||||
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
if i < 1:
|
||||
continue
|
||||
|
||||
national_id_livestock_code = row[0]
|
||||
if national_id_livestock_code not in existing_codes:
|
||||
birth_day = row[3].split('/')
|
||||
birth_day_ghamari = convert_to_miladi(
|
||||
year=int(birth_day[0]),
|
||||
month=int(birth_day[1]),
|
||||
day=int(birth_day[2])
|
||||
)
|
||||
|
||||
live_stock = LiveStock(
|
||||
national_id_livestock_code=row[0],
|
||||
herd_code=row[1],
|
||||
type=row[2],
|
||||
birth_day=row[3],
|
||||
birth_day_gh=birth_day_ghamari,
|
||||
gender=row[4],
|
||||
contractor_code=row[5],
|
||||
unique_identifier=row[6],
|
||||
agent=row[7],
|
||||
registering_user=row[8],
|
||||
registering_date=row[9],
|
||||
)
|
||||
live_stocks_to_create.append(live_stock)
|
||||
l += 1
|
||||
|
||||
LiveStock.objects.bulk_create(live_stocks_to_create)
|
||||
|
||||
return Response({"result": l}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([AllowAny])
|
||||
@csrf_exempt
|
||||
def get_cooepritive_or_rural_excel(request):
|
||||
file = request.FILES['file'].read()
|
||||
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
|
||||
sheet = wb_obj.active
|
||||
rancher=Rancher.objects.filter(trash=False).only('national_id','type')
|
||||
l=0
|
||||
for i, row in enumerate(sheet.iter_rows(values_only=True)):
|
||||
national_id= row[0]
|
||||
|
||||
new_rancher=rancher.filter(national_id=national_id)
|
||||
if new_rancher:
|
||||
if len(new_rancher) >1:
|
||||
for r in new_rancher:
|
||||
r.type='industrial'
|
||||
r.save()
|
||||
else:
|
||||
n=new_rancher.first()
|
||||
n.type = 'industrial'
|
||||
n.save()
|
||||
l+=1
|
||||
|
||||
return Response({"result": l}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
def rancher_repetitive_excel(request):
|
||||
|
||||
|
||||
duplicates = Rancher.objects.filter(trash=False).values('national_id').annotate(
|
||||
count=Count('national_id')
|
||||
).filter(count__gt=1)
|
||||
# حالا رکوردهایی که national_id تکراری دارند را استخراج میکنیم
|
||||
duplicate_records = Rancher.objects.filter(
|
||||
national_id__in=[item['national_id'] for item in duplicates],
|
||||
trash=False
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
excel_options = [
|
||||
'ردیف',
|
||||
'نام دامدار',
|
||||
'شماره ملی',
|
||||
'کد گله',
|
||||
'تعداد دام سبک',
|
||||
'تعداد دام سنگین',
|
||||
|
||||
|
||||
]
|
||||
|
||||
|
||||
output = BytesIO()
|
||||
workbook = Workbook()
|
||||
worksheet = workbook.active
|
||||
worksheet.sheet_view.rightToLeft = True
|
||||
worksheet.insert_rows(1)
|
||||
cell = worksheet.cell(row=1, column=1)
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center')
|
||||
|
||||
|
||||
|
||||
excel_description(worksheet, 'B1', f'انبار', color='red', row2='C1')
|
||||
|
||||
create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)
|
||||
|
||||
|
||||
l = 5
|
||||
m = 1
|
||||
if duplicate_records:
|
||||
for data in duplicate_records:
|
||||
|
||||
while True:
|
||||
update_ranchers = update_one_rancher(data)
|
||||
if update_ranchers:
|
||||
break
|
||||
list1 = [
|
||||
m,
|
||||
data.fullname,
|
||||
data.national_id,
|
||||
data.herd_code,
|
||||
data.light_livestock,
|
||||
data.heavy_livestock,
|
||||
|
||||
|
||||
]
|
||||
m += 1
|
||||
l += 1
|
||||
create_value(worksheet, list1, l + 1, 1, border_style='thin')
|
||||
|
||||
|
||||
workbook.save(output)
|
||||
output.seek(0)
|
||||
|
||||
response = HttpResponse(
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
response[
|
||||
'Content-Disposition'] = f'attachment; filename="تکراری.xlsx"'.encode(
|
||||
'utf-8')
|
||||
response.write(output.getvalue())
|
||||
return response
|
||||
|
||||
def create_live_stovk(request):
|
||||
l=0
|
||||
for _i in range(60):
|
||||
live_stock=LiveStock(
|
||||
national_id_livestock_code=random.randint(10**9, 10**10 - 1),
|
||||
herd_code='000005307',
|
||||
type='اسب',
|
||||
birth_day='1402/12/27',
|
||||
birth_day_gh=datetime.datetime.now() - datetime.timedelta(days=360),
|
||||
gender='نر',
|
||||
unique_identifier='0000053070',
|
||||
)
|
||||
live_stock.save()
|
||||
l+=1
|
||||
return HttpResponse(l)
|
||||
25
LiveStock/Rancher/filterset.py
Normal file
25
LiveStock/Rancher/filterset.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import Rancher
|
||||
|
||||
|
||||
class RancherFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = Rancher
|
||||
fields = [
|
||||
'fullname',
|
||||
'herd_code',
|
||||
'mobile',
|
||||
'city',
|
||||
'national_id',
|
||||
'herd_code',
|
||||
'user__mobile',
|
||||
'user__first_name',
|
||||
'user__last_name',
|
||||
'user__fullname',
|
||||
'registering_user',
|
||||
'unit_id',
|
||||
'epidemiological_code',
|
||||
'postal_code',
|
||||
|
||||
]
|
||||
110
LiveStock/Rancher/helpers.py
Normal file
110
LiveStock/Rancher/helpers.py
Normal file
@@ -0,0 +1,110 @@
|
||||
from django.http import HttpResponse
|
||||
from django.db.models import Count, Q
|
||||
|
||||
from LiveStock.models import Rancher, LiveStock, LiveStockProduct
|
||||
|
||||
|
||||
|
||||
def update_quota_rancher_threading():
|
||||
rancher=Rancher.objects.filter(trash=False).only('trash').order_by('id')
|
||||
for rancher in rancher:
|
||||
rancher.save()
|
||||
|
||||
|
||||
def get_live_stock_info(request):
|
||||
rancher=Rancher.objects.filter(trash=False,has_script=False).only('cow','sheep','goat','horse','camel','light_livestock','heavy_livestock','has_script'
|
||||
)
|
||||
rachers=rancher.values_list('herd_code',flat=True).distinct()
|
||||
live_stocks = LiveStock.objects.filter(trash=False,herd_code__in=rachers ).only('type')
|
||||
for r in rancher:
|
||||
live_stock=live_stocks.filter(herd_code=r.herd_code).only('type')
|
||||
if live_stock:
|
||||
sheep=live_stock.filter(type='گوسفند').count()
|
||||
goat=live_stock.filter(type='بز').count()
|
||||
cow=live_stock.filter(type='گاو').count()
|
||||
horse=live_stock.filter(type='اسب').count()
|
||||
camel=live_stock.filter(type='شتر').count()
|
||||
light_livestock = live_stock.filter(type__in=('بز', 'گوسفند')).count()
|
||||
heavy_livestock = live_stock.filter(type__in=('گاو','اسب','شتر')).count()
|
||||
product = LiveStockProduct.objects.filter(trash=False, name='سبوس').first()
|
||||
|
||||
r.sheep=sheep
|
||||
r.horse=horse
|
||||
r.camel=camel
|
||||
r.light_livestock=light_livestock
|
||||
r.heavy_livestock=heavy_livestock
|
||||
r.goat=goat
|
||||
r.cow=cow
|
||||
r.has_script=True
|
||||
r.weight_quota_heavy = product.heavy_wight * heavy_livestock
|
||||
r.weight_quota_light = product.light_wight * light_livestock
|
||||
r.save()
|
||||
|
||||
return HttpResponse('ok')
|
||||
|
||||
|
||||
def update_rancher(rancherss):
|
||||
for ranchers in rancherss:
|
||||
live_stocks = LiveStock.objects.filter(trash=False, herd_code=ranchers.herd_code).only('type')
|
||||
|
||||
sheep = live_stocks.filter(type='گوسفند').count()
|
||||
goat = live_stocks.filter(type='بز').count()
|
||||
cow = live_stocks.filter(type='گاو').count()
|
||||
horse = live_stocks.filter(type='اسب').count()
|
||||
camel = live_stocks.filter(type='شتر').count()
|
||||
light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
|
||||
heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
|
||||
product = LiveStockProduct.objects.filter(name='سبوس', trash=False).first()
|
||||
|
||||
ranchers.sheep = sheep
|
||||
ranchers.horse = horse
|
||||
ranchers.camel = camel
|
||||
ranchers.light_livestock = light_livestock
|
||||
ranchers.heavy_livestock = heavy_livestock
|
||||
ranchers.goat = goat
|
||||
ranchers.cow = cow
|
||||
ranchers.weight_quota_heavy = product.heavy_wight * heavy_livestock
|
||||
ranchers.weight_quota_light = product.light_wight * light_livestock
|
||||
ranchers.save()
|
||||
return True
|
||||
|
||||
|
||||
def al_get_live_stock_info(request):
|
||||
rancher = Rancher.objects.filter(trash=False, has_script=False).only('cow', 'sheep', 'goat', 'horse', 'camel',
|
||||
'light_livestock', 'heavy_livestock',
|
||||
'has_script'
|
||||
).count()
|
||||
return HttpResponse(rancher)
|
||||
|
||||
|
||||
def update_one_rancher(ranchers):
|
||||
counts = LiveStock.objects.filter(
|
||||
trash=False,
|
||||
herd_code=ranchers.herd_code
|
||||
).aggregate(
|
||||
sheep_count=Count('id', filter=Q(type='گوسفند')),
|
||||
goat_count=Count('id', filter=Q(type='بز')),
|
||||
cow_count=Count('id', filter=Q(type='گاو')),
|
||||
horse_count=Count('id', filter=Q(type='اسب')),
|
||||
camel_count=Count('id', filter=Q(type='شتر')),
|
||||
light_count=Count('id', filter=Q(type__in=('بز', 'گوسفند'))),
|
||||
heavy_count=Count('id', filter=Q(type__in=('گاو', 'اسب', 'شتر')))
|
||||
)
|
||||
|
||||
product = LiveStockProduct.objects.filter(name='سبوس', trash=False).first()
|
||||
|
||||
ranchers.sheep = counts['sheep_count']
|
||||
ranchers.goat = counts['goat_count']
|
||||
ranchers.cow = counts['cow_count']
|
||||
ranchers.horse = counts['horse_count']
|
||||
ranchers.camel = counts['camel_count']
|
||||
ranchers.light_livestock = counts['light_count']
|
||||
ranchers.heavy_livestock = counts['heavy_count']
|
||||
|
||||
ranchers.weight_quota_heavy = product.heavy_wight * counts['heavy_count']
|
||||
ranchers.weight_quota_light = product.light_wight * counts['light_count']
|
||||
|
||||
ranchers.has_script = True
|
||||
ranchers.save()
|
||||
|
||||
return True
|
||||
40
LiveStock/Rancher/serializers.py
Normal file
40
LiveStock/Rancher/serializers.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from rest_framework import serializers
|
||||
from LiveStock.models import Rancher, LiveStock, LiveStockProduct
|
||||
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
|
||||
from authentication.serializers import SystemAddressSerializer
|
||||
|
||||
|
||||
class RancherSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
# address = SystemAddressSerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Rancher
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class RancherForBazrasiSerializer(serializers.ModelSerializer):
|
||||
heavy_livestock = serializers.SerializerMethodField()
|
||||
light_livestock = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Rancher
|
||||
fields = [
|
||||
'herd_code',
|
||||
'fullname',
|
||||
'mobile',
|
||||
'lot',
|
||||
'lng',
|
||||
'heavy_livestock',
|
||||
'light_livestock',
|
||||
'type'
|
||||
|
||||
]
|
||||
|
||||
def get_heavy_livestock(self, obj):
|
||||
heavy_counts = self.context.get('heavy_counts') or {}
|
||||
return heavy_counts.get(obj.herd_code, 0)
|
||||
|
||||
def get_light_livestock(self, obj):
|
||||
light_counts = self.context.get('light_counts') or {}
|
||||
return light_counts.get(obj.herd_code, 0)
|
||||
40
LiveStock/Rancher/urls.py
Normal file
40
LiveStock/Rancher/urls.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.Rancher import views as rancher_views
|
||||
from LiveStock.Rancher.excel_processing import get_rancher_excel, get_union_excel, get_cooperative_excel, hgsahgsad, \
|
||||
get_contractor_excel, kjdfjsd, get_live_stock_excel, get_cooepritive_or_rural_excel, rancher_repetitive_excel, \
|
||||
create_live_stovk
|
||||
from LiveStock.Rancher.helpers import get_live_stock_info
|
||||
from LiveStock.Rancher.views import get_detail_rancher, dashboard_rancher
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'rancher-view',
|
||||
rancher_views.RancherViewSet,
|
||||
basename="rancher-view"
|
||||
)
|
||||
|
||||
router.register(
|
||||
r'bazrasi-rancher-view',
|
||||
rancher_views.RancherForBazrasiViewSet,
|
||||
basename="bazrasi-rancher-view"
|
||||
)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('get_rancher_excel/', get_rancher_excel),
|
||||
path('get_union_excel/', get_union_excel),
|
||||
path('get_cooperative_excel/', get_cooperative_excel),
|
||||
path('hgsahgsad/', hgsahgsad),
|
||||
path('get_contractor_excel/', get_contractor_excel),
|
||||
path('get_live_stock_info/', get_live_stock_info),
|
||||
path('get_detail_rancher/', get_detail_rancher),
|
||||
path('dashboard_rancher/', dashboard_rancher),
|
||||
path('kjdfjsd/', kjdfjsd),
|
||||
path('get_live_stock_excel/', get_live_stock_excel),
|
||||
path('get_cooepritive_or_rural_excel/', get_cooepritive_or_rural_excel),
|
||||
path('rancher_repetitive_excel/', rancher_repetitive_excel),
|
||||
path('create_live_stovk/', create_live_stovk),
|
||||
|
||||
]
|
||||
352
LiveStock/Rancher/views.py
Normal file
352
LiveStock/Rancher/views.py
Normal file
@@ -0,0 +1,352 @@
|
||||
from django.db.models import Sum, Count, Q
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.Rancher.filterset import RancherFilterSet
|
||||
from LiveStock.Rancher.serializers import RancherSerializer, RancherForBazrasiSerializer
|
||||
from LiveStock.helpers import CustomPagination, build_query
|
||||
from LiveStock.models import Rancher, Cooperative, LiveStock
|
||||
from authentication.models import SystemUserProfile, City, Province
|
||||
from LiveStock.Rancher.helpers import update_rancher, update_one_rancher
|
||||
from django.contrib.auth.models import User, Group
|
||||
|
||||
from authentication.views import ARTA_URL_REGISTER, ARTA_URL_CHANGE_MOBILE_NUMBER
|
||||
from panel.admin import PROJECT_API_KEY
|
||||
import requests
|
||||
|
||||
|
||||
class RancherViewSet(viewsets.ModelViewSet):
|
||||
queryset = Rancher.objects.filter(trash=False).only('herd_code', 'epidemiological_code', 'postal_code', 'unit_id',
|
||||
'herd_name', 'national_id',
|
||||
'fullname', 'mobile', 'contractor_code', 'city',
|
||||
'registering_user', 'light_livestock', 'heavy_livestock', 'cow',
|
||||
'goat', 'sheep', 'horse', 'camel', 'lot', 'lng',
|
||||
'allow_buy').order_by('id')
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = RancherSerializer
|
||||
pagination_class = CustomPagination
|
||||
filterset_class = RancherFilterSet
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
if 'profile' in request.GET:
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
|
||||
rancher = user.rancher_user.all()
|
||||
|
||||
serializer = self.serializer_class(rancher[0])
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
if request.GET['role'] == 'Cooperative':
|
||||
cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
ranchers = Rancher.objects.filter(trash=False, city=cooperative.address.city.name).only('herd_code',
|
||||
'epidemiological_code',
|
||||
'postal_code',
|
||||
'unit_id',
|
||||
'herd_name',
|
||||
'national_id',
|
||||
'fullname',
|
||||
'mobile',
|
||||
'contractor_code',
|
||||
'city',
|
||||
'registering_user',
|
||||
'light_livestock',
|
||||
'heavy_livestock',
|
||||
'cow',
|
||||
'goat', 'sheep',
|
||||
'horse', 'camel',
|
||||
'lot', 'lng',
|
||||
'allow_buy').order_by(
|
||||
'id')
|
||||
|
||||
else:
|
||||
ranchers = Rancher.objects.filter(trash=False).only('herd_code', 'epidemiological_code', 'postal_code',
|
||||
'unit_id', 'herd_name', 'national_id',
|
||||
'fullname', 'mobile', 'contractor_code', 'city',
|
||||
'registering_user', 'light_livestock',
|
||||
'heavy_livestock', 'cow',
|
||||
'goat', 'sheep', 'horse', 'camel', 'lot', 'lng',
|
||||
'allow_buy').order_by('id')
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
ranchers = ranchers.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
|
||||
page_size = request.query_params.get('page_size', None)
|
||||
if page_size:
|
||||
self.pagination_class.page_size = int(page_size)
|
||||
|
||||
page = self.paginate_queryset(ranchers)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
|
||||
serializer = self.serializer_class(ranchers.first())
|
||||
# serializer = self.serializer_class(ranchers, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
group = Group.objects.get(name__exact="Rancher")
|
||||
city = City.objects.get(name=request.data['city'])
|
||||
request.data.pop('city')
|
||||
province = Province.objects.get(key=city.province.key)
|
||||
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
|
||||
if system_profile:
|
||||
if Rancher.objects.filter(user=system_profile, trash=False).exists():
|
||||
return Response({"result": "این اتحادیه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
else:
|
||||
password = "123456"
|
||||
data = {
|
||||
"username": request.data['mobile'],
|
||||
"password": password,
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_URL_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'])
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=request.data['mobile'],
|
||||
first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'],
|
||||
fullname=request.data['first_name'] + " " + request.data['last_name'],
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password=password,
|
||||
national_id=request.data['national_id'],
|
||||
city=city,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
else:
|
||||
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
|
||||
system_profile.role.add(group)
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
rancher = serializer.create(validated_data=request.data)
|
||||
rancher.user = system_profile
|
||||
rancher.save()
|
||||
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
rancher = Rancher.objects.get(key=request.data['key'], trash=False)
|
||||
if 'first_name' in request.data.keys():
|
||||
# system_user_profile = SystemUserProfile.objects.get(key=rancher.user.key, trash=False)
|
||||
# system_user_profile.first_name = request.data['first_name']
|
||||
# system_user_profile.last_name = request.data['last_name']
|
||||
# system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
|
||||
# system_user_profile.save()
|
||||
# first_mobile_number = system_user_profile.mobile
|
||||
# second_mobile_number = request.data['mobile']
|
||||
# if first_mobile_number != second_mobile_number:
|
||||
# if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
|
||||
# return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
|
||||
# status=status.HTTP_403_FORBIDDEN)
|
||||
# data = {
|
||||
# "first_mobile_number": first_mobile_number,
|
||||
# "second_mobile_number": second_mobile_number,
|
||||
# }
|
||||
# req = requests.post(
|
||||
# url=ARTA_URL_CHANGE_MOBILE_NUMBER,
|
||||
# data=data,
|
||||
# verify=False
|
||||
# )
|
||||
# if req.status_code == 200:
|
||||
# second_mobile_number = second_mobile_number
|
||||
# user = User.objects.get(id=system_user_profile.user.id)
|
||||
# user.username = second_mobile_number
|
||||
# user.save()
|
||||
# system_user_profile.mobile = second_mobile_number
|
||||
# system_user_profile.save()
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
|
||||
serializer = self.serializer_class(rancher)
|
||||
serializer.update(instance=rancher, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
def destroy(self, request, pk=None, *args, **kwargs):
|
||||
rancher = Rancher.objects.get(key=request.GET["rancher_key"])
|
||||
rancher.trash = True
|
||||
rancher.save()
|
||||
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
# def update(self, request, *args, **kwargs):
|
||||
# rancher = self.queryset.get(key=request.data['key'], trash=False)
|
||||
# request.data.pop('key')
|
||||
#
|
||||
# serializer = self.serializer_class(rancher)
|
||||
# serializer.update(instance=rancher, validated_data=request.data)
|
||||
# return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@csrf_exempt
|
||||
@permission_classes([TokenHasReadWriteScope])
|
||||
def get_detail_rancher(request):
|
||||
ranchers = Rancher.objects.filter(herd_code=request.GET['herd_code']).first()
|
||||
while True:
|
||||
update_ranchers = update_one_rancher(ranchers)
|
||||
if update_ranchers:
|
||||
break
|
||||
dict1 = {
|
||||
"light_livestock": ranchers.light_livestock,
|
||||
"heavy_livestock": ranchers.heavy_livestock,
|
||||
"sheep": ranchers.sheep,
|
||||
"goat": ranchers.goat,
|
||||
"cow": ranchers.cow,
|
||||
"camel": ranchers.camel,
|
||||
"horse": ranchers.horse
|
||||
}
|
||||
return Response(dict1, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class RancherForBazrasiViewSet(viewsets.ModelViewSet):
|
||||
queryset = Rancher.objects.filter(trash=False, type='industrial').only(
|
||||
'herd_code',
|
||||
'fullname',
|
||||
'mobile',
|
||||
'lot',
|
||||
'lng',
|
||||
'industrial',
|
||||
'heavy_livestock',
|
||||
'light_livestock'
|
||||
).order_by('-industrial', 'id')
|
||||
permission_classes = [AllowAny]
|
||||
serializer_class = RancherForBazrasiSerializer
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
type_filter = request.GET.get('type')
|
||||
queryset = Rancher.objects.filter(trash=False).only(
|
||||
'herd_code',
|
||||
'fullname',
|
||||
'mobile',
|
||||
'lot',
|
||||
'lng',
|
||||
'industrial',
|
||||
'heavy_livestock',
|
||||
'light_livestock',
|
||||
'type'
|
||||
).order_by('-industrial', 'id')
|
||||
|
||||
if type_filter in ('industrial', 'rural'):
|
||||
queryset = queryset.filter(type=type_filter)
|
||||
|
||||
herd_codes = list(queryset.values_list('herd_code', flat=True))
|
||||
|
||||
heavy_counts = {}
|
||||
light_counts = {}
|
||||
valid_herd_codes = set()
|
||||
if herd_codes:
|
||||
heavy_types = ('گاو', 'اسب', 'شتر')
|
||||
light_types = ('بز', 'گوسفند')
|
||||
livestock_counts = (
|
||||
LiveStock.objects.filter(
|
||||
trash=False,
|
||||
herd_code__in=herd_codes,
|
||||
type__in=heavy_types + light_types
|
||||
)
|
||||
.values('herd_code', 'type')
|
||||
.annotate(total=Count('id'))
|
||||
)
|
||||
for item in livestock_counts:
|
||||
herd_code = item['herd_code']
|
||||
livestock_type = item['type']
|
||||
total = item['total']
|
||||
if livestock_type in heavy_types:
|
||||
heavy_counts[herd_code] = heavy_counts.get(herd_code, 0) + total
|
||||
elif livestock_type in light_types:
|
||||
light_counts[herd_code] = light_counts.get(herd_code, 0) + total
|
||||
|
||||
valid_herd_codes = set(heavy_counts.keys()) | set(light_counts.keys())
|
||||
|
||||
if valid_herd_codes:
|
||||
queryset = queryset.filter(herd_code__in=valid_herd_codes)
|
||||
else:
|
||||
queryset = queryset.none()
|
||||
|
||||
serializer = self.get_serializer(
|
||||
queryset,
|
||||
many=True,
|
||||
context={
|
||||
'heavy_counts': heavy_counts,
|
||||
'light_counts': light_counts
|
||||
}
|
||||
)
|
||||
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@csrf_exempt
|
||||
@permission_classes([TokenHasReadWriteScope])
|
||||
def dashboard_rancher(request):
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
role = request.GET.get('role')
|
||||
|
||||
ranchers = Rancher.objects.filter(trash=False).values_list('herd_code', flat=True).distinct()
|
||||
|
||||
live_stocks = LiveStock.objects.filter(trash=False, herd_code__in=ranchers).only('type')
|
||||
|
||||
if role == 'Cooperative':
|
||||
cooperative = Cooperative.objects.get(user=user, trash=False)
|
||||
ranchers = Rancher.objects.filter(trash=False, city=cooperative.address.city.name).values_list('herd_code',
|
||||
flat=True).distinct()
|
||||
live_stocks = live_stocks.filter(herd_code__in=ranchers)
|
||||
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
ranchers = ranchers.filter(build_query(RancherFilterSet.Meta.fields, value))
|
||||
|
||||
counts = live_stocks.values('type').annotate(total=Count('id'))
|
||||
count_dict = {item['type']: item['total'] for item in counts}
|
||||
|
||||
light_livestock = count_dict.get('بز', 0) + count_dict.get('گوسفند', 0)
|
||||
heavy_livestock = count_dict.get('گاو', 0) + count_dict.get('اسب', 0) + count_dict.get('شتر', 0)
|
||||
total_ranchers = len(ranchers)
|
||||
dhi_amount = ranchers.filter(dhi_amount__gt=1,trash=False).aggregate(total=Sum('dhi_amount'))['total'] or 0
|
||||
|
||||
result = {
|
||||
'rancher_count': total_ranchers,
|
||||
'live_stocks_count': sum(count_dict.values()),
|
||||
"sheep": count_dict.get('گوسفند', 0),
|
||||
"goat": count_dict.get('بز', 0),
|
||||
"cow": count_dict.get('گاو', 0),
|
||||
"horse": count_dict.get('اسب', 0),
|
||||
"camel": count_dict.get('شتر', 0),
|
||||
"light_livestock": light_livestock,
|
||||
"heavy_livestock": heavy_livestock,
|
||||
"dhi_amount": dhi_amount,
|
||||
|
||||
}
|
||||
|
||||
return Response(result, status=status.HTTP_200_OK)
|
||||
0
LiveStock/Union/__init__.py
Normal file
0
LiveStock/Union/__init__.py
Normal file
0
LiveStock/Union/excel_processing.py
Normal file
0
LiveStock/Union/excel_processing.py
Normal file
17
LiveStock/Union/filterset.py
Normal file
17
LiveStock/Union/filterset.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from django_filters import rest_framework as filters
|
||||
|
||||
from LiveStock.models import Union
|
||||
|
||||
|
||||
class UnionFilterSet(filters.FilterSet):
|
||||
class Meta:
|
||||
model = Union
|
||||
fields = [
|
||||
'address__city__name',
|
||||
'name',
|
||||
'mobile',
|
||||
'user__mobile',
|
||||
'user__first_name',
|
||||
'user__last_name',
|
||||
'user__fullname'
|
||||
]
|
||||
0
LiveStock/Union/helpers.py
Normal file
0
LiveStock/Union/helpers.py
Normal file
15
LiveStock/Union/serializers.py
Normal file
15
LiveStock/Union/serializers.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from LiveStock.models import Union
|
||||
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
|
||||
from authentication.serializers import SystemAddressSerializer
|
||||
|
||||
|
||||
class UnionSerializer(serializers.ModelSerializer):
|
||||
user = SystemUserProfileForInspectionSerializer(read_only=True)
|
||||
address = SystemAddressSerializer(read_only=True)
|
||||
user_bank_info = BankCardSerializer(required=False)
|
||||
|
||||
class Meta:
|
||||
model = Union
|
||||
fields = '__all__'
|
||||
14
LiveStock/Union/urls.py
Normal file
14
LiveStock/Union/urls.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import path, include
|
||||
from LiveStock.Union import views as union_views
|
||||
router = DefaultRouter()
|
||||
router.register(
|
||||
r'union-view',
|
||||
union_views.UnionViewSet,
|
||||
basename="union"
|
||||
)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
181
LiveStock/Union/views.py
Normal file
181
LiveStock/Union/views.py
Normal file
@@ -0,0 +1,181 @@
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from LiveStock.Union.filterset import UnionFilterSet
|
||||
from LiveStock.Union.serializers import UnionSerializer
|
||||
from LiveStock.helpers import build_query, CustomPagination
|
||||
from LiveStock.models import Union
|
||||
from authentication.models import SystemUserProfile, City, Province, SystemAddress
|
||||
from django.contrib.auth.models import User, Group
|
||||
|
||||
from authentication.views import ARTA_URL_REGISTER, ARTA_URL_CHANGE_MOBILE_NUMBER
|
||||
from panel.admin import PROJECT_API_KEY
|
||||
import requests
|
||||
|
||||
|
||||
class UnionViewSet(viewsets.ModelViewSet):
|
||||
queryset = Union.objects.all()
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
serializer_class = UnionSerializer
|
||||
filterset_class = UnionFilterSet
|
||||
pagination_class = CustomPagination
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
if 'profile' in request.GET:
|
||||
user = SystemUserProfile.objects.get(user=request.user, trash=False)
|
||||
|
||||
union = user.union_user.all()
|
||||
|
||||
serializer = self.serializer_class(union[0])
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
unions = Union.objects.filter(trash=False).order_by('id')
|
||||
value = request.GET.get('value')
|
||||
search = request.GET.get('search')
|
||||
if value and search == 'filter':
|
||||
if search != 'undefined' and search.strip():
|
||||
unions = unions.filter(
|
||||
build_query(self.filterset_class.Meta.fields, value)
|
||||
)
|
||||
page = self.paginate_queryset(unions)
|
||||
if page is not None:
|
||||
serializer = self.serializer_class(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.serializer_class(unions, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
group = Group.objects.get(name__exact="Union")
|
||||
city = City.objects.get(name=request.data['city'])
|
||||
request.data.pop('city')
|
||||
province = Province.objects.get(key=city.province.key)
|
||||
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
|
||||
if system_profile:
|
||||
if Union.objects.filter(user=system_profile, trash=False).exists():
|
||||
return Response({"result": "این اتحادیه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
else:
|
||||
password = "123456"
|
||||
data = {
|
||||
"username": request.data['mobile'],
|
||||
"password": password,
|
||||
"api_key": PROJECT_API_KEY
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_URL_REGISTER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if req.status_code == 200:
|
||||
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'])
|
||||
user.save()
|
||||
base_id = SystemUserProfile.objects.all()
|
||||
if base_id.count() > 0:
|
||||
base_id = int(base_id.last().base_order) + 1
|
||||
else:
|
||||
base_id = 1000
|
||||
system_profile = SystemUserProfile(
|
||||
mobile=request.data['mobile'],
|
||||
first_name=request.data['first_name'],
|
||||
last_name=request.data['last_name'],
|
||||
fullname=request.data['first_name'] + " " + request.data['last_name'],
|
||||
user=user,
|
||||
base_order=base_id,
|
||||
password=password,
|
||||
national_id=request.data['national_id'],
|
||||
city=city,
|
||||
province=province
|
||||
)
|
||||
system_profile.save()
|
||||
else:
|
||||
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
|
||||
address = SystemAddress(city=city, province=province, address=request.data['address'],
|
||||
postal_code=request.data['postal_code'])
|
||||
address.save()
|
||||
system_profile.role.add(group)
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
request.data.pop('address')
|
||||
request.data.pop('postal_code')
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
union = serializer.create(validated_data=request.data)
|
||||
union.user = system_profile
|
||||
union.address = address
|
||||
union.save()
|
||||
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
union = Union.objects.get(key=request.data['union_key'], trash=False)
|
||||
address = SystemAddress.objects.get(key=union.address.key, trash=False)
|
||||
request.data.pop('union_key')
|
||||
if 'first_name' in request.data.keys():
|
||||
system_user_profile = SystemUserProfile.objects.get(key=union.user.key, trash=False)
|
||||
system_user_profile.first_name = request.data['first_name']
|
||||
system_user_profile.last_name = request.data['last_name']
|
||||
system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
|
||||
system_user_profile.save()
|
||||
first_mobile_number = system_user_profile.mobile
|
||||
second_mobile_number = request.data['mobile']
|
||||
if first_mobile_number != second_mobile_number:
|
||||
if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
|
||||
return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
data = {
|
||||
"first_mobile_number": first_mobile_number,
|
||||
"second_mobile_number": second_mobile_number,
|
||||
}
|
||||
req = requests.post(
|
||||
url=ARTA_URL_CHANGE_MOBILE_NUMBER,
|
||||
data=data,
|
||||
verify=False
|
||||
)
|
||||
if req.status_code == 200:
|
||||
second_mobile_number = second_mobile_number
|
||||
user = User.objects.get(id=system_user_profile.user.id)
|
||||
user.username = second_mobile_number
|
||||
user.save()
|
||||
system_user_profile.mobile = second_mobile_number
|
||||
system_user_profile.save()
|
||||
city = City.objects.get(name=request.data['city'])
|
||||
province = Province.objects.get(key=city.province.key)
|
||||
address.city = city
|
||||
address.province = province
|
||||
address.address = request.data['address']
|
||||
address.postal_code = request.data['postal_code']
|
||||
address.save()
|
||||
request.data.pop('first_name')
|
||||
request.data.pop('last_name')
|
||||
request.data.pop('address')
|
||||
request.data.pop('city')
|
||||
|
||||
serializer = self.serializer_class(union)
|
||||
serializer.update(instance=union, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
# def update(self, request, *args, **kwargs):
|
||||
# union = Union.objects.get(key=request.data['key'], trash=False)
|
||||
# request.data.pop('key')
|
||||
# if 'city' in request.data:
|
||||
# city_key=request.data['city']
|
||||
# request.data.pop('city')
|
||||
# city=City.objects.filter(key=city_key,trash=False).first()
|
||||
# union.address.city=city
|
||||
# union.address.save()
|
||||
# serializer = self.serializer_class(union)
|
||||
#
|
||||
# serializer.update(instance=union, validated_data=request.data)
|
||||
# return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def destroy(self, request, pk=None, *args, **kwargs):
|
||||
union = Union.objects.get(key=request.GET["key"])
|
||||
union.trash = True
|
||||
union.save()
|
||||
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
|
||||
0
LiveStock/__init__.py
Normal file
0
LiveStock/__init__.py
Normal file
3
LiveStock/admin.py
Normal file
3
LiveStock/admin.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
6
LiveStock/apps.py
Normal file
6
LiveStock/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class LivestockConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'LiveStock'
|
||||
19
LiveStock/helpers.py
Normal file
19
LiveStock/helpers.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import jdatetime
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
|
||||
|
||||
class CustomPagination(PageNumberPagination):
|
||||
page_size = 10
|
||||
|
||||
|
||||
def convert_to_miladi(year=None, month=None, day=None):
|
||||
date = jdatetime.datetime(year, month, day).togregorian()
|
||||
return date
|
||||
|
||||
|
||||
def build_query(fields, value):
|
||||
from django.db.models import Q
|
||||
query = Q()
|
||||
for field in fields:
|
||||
query |= Q(**{f"{field}__icontains": value})
|
||||
return query
|
||||
187
LiveStock/migrations/0001_initial.py
Normal file
187
LiveStock/migrations/0001_initial.py
Normal file
@@ -0,0 +1,187 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-03 20:36
|
||||
|
||||
import datetime
|
||||
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 = [
|
||||
('authentication', '0050_auto_20250303_2036'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Cooperative',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('mobile', models.CharField(max_length=200, null=True)),
|
||||
('type', models.CharField(max_length=200, null=True)),
|
||||
('account', models.CharField(max_length=200, null=True)),
|
||||
('national_id', models.CharField(max_length=100, null=True)),
|
||||
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_address', to='authentication.systemaddress')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_user', to='authentication.systemuserprofile')),
|
||||
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_bank_info', to='authentication.bankcard')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LiveStockProduct',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('image', models.CharField(max_length=500, null=True)),
|
||||
('unit', models.CharField(max_length=200, null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockproduct_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockproduct_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LiveStockProvinceJahad',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('mobile', models.CharField(max_length=200, null=True)),
|
||||
('type', models.CharField(max_length=200, null=True)),
|
||||
('account', models.CharField(max_length=200, null=True)),
|
||||
('national_id', models.CharField(max_length=100, null=True)),
|
||||
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_address', to='authentication.systemaddress')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockprovincejahad_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockprovincejahad_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_user', to='authentication.systemuserprofile')),
|
||||
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_bank_info', to='authentication.bankcard')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Union',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('mobile', models.CharField(max_length=200, null=True)),
|
||||
('type', models.CharField(max_length=200, null=True)),
|
||||
('account', models.CharField(max_length=200, null=True)),
|
||||
('national_id', models.CharField(max_length=100, null=True)),
|
||||
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_address', to='authentication.systemaddress')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_user', to='authentication.systemuserprofile')),
|
||||
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_bank_info', to='authentication.bankcard')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Rancher',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('registering_user', models.CharField(max_length=200, null=True)),
|
||||
('lng', models.FloatField(default=0)),
|
||||
('lot', models.FloatField(default=0)),
|
||||
('mobile', models.CharField(max_length=200, null=True)),
|
||||
('fullname', models.CharField(max_length=200, null=True)),
|
||||
('city', models.CharField(max_length=200, null=True)),
|
||||
('herd_name', models.CharField(max_length=200, null=True)),
|
||||
('unit_id', models.CharField(max_length=100, null=True)),
|
||||
('postal_code', models.CharField(max_length=100, null=True)),
|
||||
('epidemiological_code', models.CharField(max_length=100, null=True)),
|
||||
('herd_code', models.CharField(max_length=100, null=True)),
|
||||
('national_id', models.CharField(max_length=100, null=True)),
|
||||
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_address', to='authentication.systemaddress')),
|
||||
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_cooperative', to='LiveStock.cooperative')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_user', to='authentication.systemuserprofile')),
|
||||
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_bank_info', to='authentication.bankcard')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LiveStockRolseProduct',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(max_length=200, null=True)),
|
||||
('total_weight', models.BigIntegerField(default=0)),
|
||||
('total_allocated_weight', models.BigIntegerField(default=0)),
|
||||
('total_remain_weight', models.CharField(max_length=500, null=True)),
|
||||
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_product', to='LiveStock.cooperative')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockrolseproduct_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('jahad', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='jahad_product', to='LiveStock.livestockprovincejahad')),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockrolseproduct_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('parent_product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='parents_product', to='LiveStock.livestockproduct')),
|
||||
('union', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_product', to='LiveStock.union')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LiveStockAllocations',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('state', models.CharField(default='pending', max_length=200)),
|
||||
('weight', models.BigIntegerField(default=0)),
|
||||
('real_weight', models.BigIntegerField(default=0)),
|
||||
('date', models.DateTimeField(default=datetime.datetime.now)),
|
||||
('allocate_from', models.CharField(max_length=200, null=True)),
|
||||
('allocate_to', models.CharField(max_length=200, null=True)),
|
||||
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_allocation', to='LiveStock.cooperative')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockallocations_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('jahad', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='jahad_allocation', to='LiveStock.livestockprovincejahad')),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockallocations_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='product_allocation', to='LiveStock.livestockrolseproduct')),
|
||||
('union', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_allocation', to='LiveStock.union')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
43
LiveStock/migrations/0002_livestock.py
Normal file
43
LiveStock/migrations/0002_livestock.py
Normal file
@@ -0,0 +1,43 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-04 13:40
|
||||
|
||||
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),
|
||||
('LiveStock', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='LiveStock',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('national_id_livestock_code', models.CharField(max_length=200, null=True)),
|
||||
('herd_code', models.CharField(max_length=100, null=True)),
|
||||
('type', models.CharField(max_length=200, null=True)),
|
||||
('birth_day', models.DateField(null=True)),
|
||||
('gender', models.CharField(max_length=100, null=True)),
|
||||
('contractor_code', models.CharField(max_length=100, null=True)),
|
||||
('unique_identifier', models.CharField(max_length=100, null=True)),
|
||||
('agent', models.CharField(max_length=100, null=True)),
|
||||
('registering_user', models.CharField(max_length=200, null=True)),
|
||||
('registering_date', models.DateTimeField(null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestock_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestock_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('rancher', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='LiveStock.rancher')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0003_auto_20250305_1353.py
Normal file
23
LiveStock/migrations/0003_auto_20250305_1353.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-05 13:53
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0002_livestock'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='livestock',
|
||||
name='birth_day',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='livestock',
|
||||
name='registering_date',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
]
|
||||
28
LiveStock/migrations/0004_auto_20250305_1721.py
Normal file
28
LiveStock/migrations/0004_auto_20250305_1721.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-05 17:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0003_auto_20250305_1353'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='allow_buy',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='weight_allocation_heavy',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='weight_allocation_light',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
38
LiveStock/migrations/0005_auto_20250305_2028.py
Normal file
38
LiveStock/migrations/0005_auto_20250305_2028.py
Normal file
@@ -0,0 +1,38 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-05 20:28
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0004_auto_20250305_1721'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='cooperative_percent',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='union_percent',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='weight_quota_heavy',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='weight_quota_light',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0006_auto_20250306_0023.py
Normal file
23
LiveStock/migrations/0006_auto_20250306_0023.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-06 00:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0005_auto_20250305_2028'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='total_weight',
|
||||
field=models.BigIntegerField(default=0),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='livestockrolseproduct',
|
||||
name='total_remain_weight',
|
||||
field=models.BigIntegerField(default=0),
|
||||
),
|
||||
]
|
||||
45
LiveStock/migrations/0007_auto_20250306_1213.py
Normal file
45
LiveStock/migrations/0007_auto_20250306_1213.py
Normal file
@@ -0,0 +1,45 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-06 12:13
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('authentication', '0051_auto_20250306_1213'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('LiveStock', '0006_auto_20250306_0023'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='contractor_code',
|
||||
field=models.CharField(max_length=100, null=True),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Contractor',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('contractor_code', models.CharField(max_length=100, null=True)),
|
||||
('fullname', models.CharField(max_length=200, null=True)),
|
||||
('entity_code', models.CharField(max_length=200, null=True)),
|
||||
('national_id', models.CharField(max_length=100, null=True)),
|
||||
('company_name', models.CharField(max_length=200, null=True)),
|
||||
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_user', to='authentication.systemaddress')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_user', to='authentication.systemuserprofile')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0008_auto_20250307_0930.py
Normal file
23
LiveStock/migrations/0008_auto_20250307_0930.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-07 09:30
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0007_auto_20250306_1213'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='heavy_wight',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='light_wight',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
25
LiveStock/migrations/0009_auto_20250307_1059.py
Normal file
25
LiveStock/migrations/0009_auto_20250307_1059.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-07 10:59
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0008_auto_20250307_0930'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='rancher',
|
||||
name='address',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='rancher',
|
||||
name='cooperative',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='rancher',
|
||||
name='user_bank_info',
|
||||
),
|
||||
]
|
||||
48
LiveStock/migrations/0010_auto_20250307_1107.py
Normal file
48
LiveStock/migrations/0010_auto_20250307_1107.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-07 11:07
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0009_auto_20250307_1059'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='camel',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='cow',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='goat',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='heavy_livestock',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='horse',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='light_livestock',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='sheep',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
39
LiveStock/migrations/0011_auto_20250307_1322.py
Normal file
39
LiveStock/migrations/0011_auto_20250307_1322.py
Normal file
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-07 13:22
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0010_auto_20250307_1107'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='contractor',
|
||||
name='cooperative',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_cooperative', to='LiveStock.cooperative'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='contractor',
|
||||
name='heavy_livestock',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='contractor',
|
||||
name='light_livestock',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='contractor',
|
||||
name='number_of_rancher',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='has_script',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
47
LiveStock/migrations/0012_auto_20250307_2135.py
Normal file
47
LiveStock/migrations/0012_auto_20250307_2135.py
Normal file
@@ -0,0 +1,47 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-07 21:35
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0011_auto_20250307_1322'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='livestockproduct',
|
||||
name='cooperative_percent',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='livestockproduct',
|
||||
name='union_percent',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='company_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='cooperative_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='shipping_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='union_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='cooperative',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_cooperative', to='LiveStock.cooperative'),
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0013_auto_20250308_1617.py
Normal file
23
LiveStock/migrations/0013_auto_20250308_1617.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-08 16:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0012_auto_20250307_2135'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestockallocations',
|
||||
name='description',
|
||||
field=models.TextField(null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockallocations',
|
||||
name='place',
|
||||
field=models.TextField(null=True),
|
||||
),
|
||||
]
|
||||
33
LiveStock/migrations/0014_auto_20250309_1654.py
Normal file
33
LiveStock/migrations/0014_auto_20250309_1654.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-09 16:54
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0013_auto_20250308_1617'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='cooperative',
|
||||
name='active',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockallocations',
|
||||
name='charge',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockallocations',
|
||||
name='code',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockrolseproduct',
|
||||
name='total_receipt_weight',
|
||||
field=models.BigIntegerField(default=0),
|
||||
),
|
||||
]
|
||||
58
LiveStock/migrations/0015_auto_20250310_1820.py
Normal file
58
LiveStock/migrations/0015_auto_20250310_1820.py
Normal file
@@ -0,0 +1,58 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-10 18:20
|
||||
|
||||
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),
|
||||
('LiveStock', '0014_auto_20250309_1654'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='active',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='active',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='union',
|
||||
name='active',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='livestockallocations',
|
||||
name='description',
|
||||
field=models.TextField(blank=True, null=True),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='CooperativeProductsShare',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('price', models.IntegerField(default=0)),
|
||||
('shipping_price', models.IntegerField(default=0)),
|
||||
('union_price', models.IntegerField(default=0)),
|
||||
('cooperative_price', models.IntegerField(default=0)),
|
||||
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_share_product', to='LiveStock.cooperative')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperativeproductsshare_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperativeproductsshare_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_share_product', to='LiveStock.livestockproduct')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0016_auto_20250311_1055.py
Normal file
23
LiveStock/migrations/0016_auto_20250311_1055.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-11 10:55
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0015_auto_20250310_1820'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='birth_day_gh',
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='registering_date_gh',
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
]
|
||||
37
LiveStock/migrations/0017_posseller.py
Normal file
37
LiveStock/migrations/0017_posseller.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-11 13:36
|
||||
|
||||
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),
|
||||
('LiveStock', '0016_auto_20250311_1055'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='PosSeller',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('full_name', models.CharField(max_length=200, null=True)),
|
||||
('mobile', models.CharField(max_length=50, null=True)),
|
||||
('national_id', models.CharField(max_length=50, null=True)),
|
||||
('city', models.CharField(max_length=100, null=True)),
|
||||
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='seller_pos_cooperative', to='LiveStock.cooperative')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posseller_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posseller_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
18
LiveStock/migrations/0018_rancher_type.py
Normal file
18
LiveStock/migrations/0018_rancher_type.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-12 11:12
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0017_posseller'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='type',
|
||||
field=models.CharField(default='rural', max_length=200),
|
||||
),
|
||||
]
|
||||
33
LiveStock/migrations/0019_auto_20250312_1429.py
Normal file
33
LiveStock/migrations/0019_auto_20250312_1429.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-12 14:29
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0018_rancher_type'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='heavy_wight_dha',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='heavy_wight_industrial',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='light_wight_dha',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestockproduct',
|
||||
name='light_wight_industrial',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0020_auto_20250312_1459.py
Normal file
23
LiveStock/migrations/0020_auto_20250312_1459.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-03-12 14:59
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0019_auto_20250312_1429'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='dhi_amount',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rancher',
|
||||
name='industrial',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
23
LiveStock/migrations/0021_auto_20250412_1613.py
Normal file
23
LiveStock/migrations/0021_auto_20250412_1613.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.2.13 on 2025-04-12 16:13
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0020_auto_20250312_1459'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='archive',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='archiver',
|
||||
field=models.CharField(max_length=250, null=True),
|
||||
),
|
||||
]
|
||||
38
LiveStock/migrations/0022_auto_20250528_1439.py
Normal file
38
LiveStock/migrations/0022_auto_20250528_1439.py
Normal file
@@ -0,0 +1,38 @@
|
||||
# Generated by Django 3.2.13 on 2025-05-28 14:39
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0021_auto_20250412_1613'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='cooperativeproductsshare',
|
||||
name='company_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='age_of_archive',
|
||||
field=models.IntegerField(default=1),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='archive_date',
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='return_from_archive_date',
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='livestock',
|
||||
name='returner_from_archive',
|
||||
field=models.CharField(max_length=250, null=True),
|
||||
),
|
||||
]
|
||||
33
LiveStock/migrations/0023_auto_20250810_1134.py
Normal file
33
LiveStock/migrations/0023_auto_20250810_1134.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 3.2.13 on 2025-08-10 11:34
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('LiveStock', '0022_auto_20250528_1439'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='cooperative',
|
||||
name='first_sub_cooperative_account',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='cooperative',
|
||||
name='first_sub_cooperative_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='cooperative',
|
||||
name='second_sub_cooperative_account',
|
||||
field=models.CharField(max_length=200, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='cooperative',
|
||||
name='second_sub_cooperative_price',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
||||
0
LiveStock/migrations/__init__.py
Normal file
0
LiveStock/migrations/__init__.py
Normal file
372
LiveStock/models.py
Normal file
372
LiveStock/models.py
Normal file
@@ -0,0 +1,372 @@
|
||||
import datetime
|
||||
|
||||
from authentication.models import BaseModel, SystemUserProfile, SystemAddress, BankCard
|
||||
from django.db import models
|
||||
|
||||
|
||||
class LiveStockProvinceJahad(BaseModel):
|
||||
user = models.ForeignKey(
|
||||
SystemUserProfile,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="live_stock_jahad_user",
|
||||
null=True
|
||||
)
|
||||
address = models.ForeignKey(
|
||||
SystemAddress,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="live_stock_jahad_address",
|
||||
null=True
|
||||
)
|
||||
user_bank_info = models.ForeignKey(
|
||||
BankCard,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="live_stock_jahad_bank_info",
|
||||
null=True
|
||||
)
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
mobile = models.CharField(max_length=200, null=True)
|
||||
type = models.CharField(max_length=200, null=True)
|
||||
account = models.CharField(max_length=200, null=True)
|
||||
national_id = models.CharField(max_length=100, null=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(LiveStockProvinceJahad, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class Union(BaseModel):
|
||||
user = models.ForeignKey(
|
||||
SystemUserProfile,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="union_user",
|
||||
null=True
|
||||
)
|
||||
address = models.ForeignKey(
|
||||
SystemAddress,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="union_address",
|
||||
null=True
|
||||
)
|
||||
user_bank_info = models.ForeignKey(
|
||||
BankCard,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="union_bank_info",
|
||||
null=True
|
||||
)
|
||||
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
mobile = models.CharField(max_length=200, null=True)
|
||||
type = models.CharField(max_length=200, null=True)
|
||||
account = models.CharField(max_length=200, null=True)
|
||||
national_id = models.CharField(max_length=100, null=True)
|
||||
active = models.BooleanField(default=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(Union, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class Cooperative(BaseModel):
|
||||
user = models.ForeignKey(
|
||||
SystemUserProfile,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_user",
|
||||
null=True
|
||||
)
|
||||
address = models.ForeignKey(
|
||||
SystemAddress,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_address",
|
||||
null=True
|
||||
)
|
||||
user_bank_info = models.ForeignKey(
|
||||
BankCard,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_bank_info",
|
||||
null=True
|
||||
)
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
mobile = models.CharField(max_length=200, null=True)
|
||||
type = models.CharField(max_length=200, null=True)
|
||||
account = models.CharField(max_length=200, null=True)
|
||||
national_id = models.CharField(max_length=100, null=True)
|
||||
active = models.BooleanField(default=True)
|
||||
first_sub_cooperative_price = models.IntegerField(default=0)
|
||||
first_sub_cooperative_account = models.CharField(max_length=200, null=True)
|
||||
second_sub_cooperative_price = models.IntegerField(default=0)
|
||||
second_sub_cooperative_account = models.CharField(max_length=200, null=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(Cooperative, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class Rancher(BaseModel):
|
||||
user = models.ForeignKey(
|
||||
SystemUserProfile,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="rancher_user",
|
||||
null=True
|
||||
)
|
||||
# address = models.ForeignKey(
|
||||
# SystemAddress,
|
||||
# on_delete=models.CASCADE,
|
||||
# related_name="rancher_address",
|
||||
# null=True
|
||||
# )
|
||||
# user_bank_info = models.ForeignKey(
|
||||
# BankCard,
|
||||
# on_delete=models.CASCADE,
|
||||
# related_name="rancher_bank_info",
|
||||
# null=True
|
||||
# )
|
||||
# contractor = models.ForeignKey(
|
||||
# Contractor,
|
||||
# on_delete=models.CASCADE,
|
||||
# related_name="rancher_contractor",
|
||||
# null=True
|
||||
# )
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="rancher_cooperative",
|
||||
null=True
|
||||
)
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
registering_user = models.CharField(max_length=200, null=True)
|
||||
lng = models.FloatField(default=0)
|
||||
lot = models.FloatField(default=0)
|
||||
mobile = models.CharField(max_length=200, null=True)
|
||||
fullname = models.CharField(max_length=200, null=True)
|
||||
city = models.CharField(max_length=200, null=True)
|
||||
herd_name = models.CharField(max_length=200, null=True)
|
||||
unit_id = models.CharField(max_length=100, null=True)
|
||||
postal_code = models.CharField(max_length=100, null=True)
|
||||
epidemiological_code = models.CharField(max_length=100, null=True)
|
||||
herd_code = models.CharField(max_length=100, null=True)
|
||||
national_id = models.CharField(max_length=100, null=True)
|
||||
allow_buy = models.BooleanField(default=True)
|
||||
weight_allocation_light = models.IntegerField(default=0)
|
||||
weight_allocation_heavy = models.IntegerField(default=0)
|
||||
weight_quota_heavy = models.IntegerField(default=0)
|
||||
weight_quota_light = models.IntegerField(default=0)
|
||||
total_weight = models.BigIntegerField(default=0)
|
||||
contractor_code = models.CharField(max_length=100, null=True)
|
||||
sheep = models.IntegerField(default=0)
|
||||
goat = models.IntegerField(default=0)
|
||||
cow = models.IntegerField(default=0)
|
||||
horse = models.IntegerField(default=0)
|
||||
camel = models.IntegerField(default=0)
|
||||
light_livestock = models.IntegerField(default=0)
|
||||
heavy_livestock = models.IntegerField(default=0)
|
||||
has_script = models.BooleanField(default=False)
|
||||
active = models.BooleanField(default=True)
|
||||
type = models.CharField(max_length=200, default='rural')
|
||||
industrial = models.BooleanField(default=False)
|
||||
dhi_amount = models.IntegerField(default=0)
|
||||
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# live_stocks = LiveStock.objects.filter(trash=False, herd_code=self.herd_code).only('type')
|
||||
# light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
|
||||
# heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
|
||||
# product = LiveStockProduct.objects.filter(trash=False, name='سبوس').first()
|
||||
# self.weight_quota_heavy=product.heavy_wight * heavy_livestock
|
||||
# self.weight_quota_light=product.light_wight * light_livestock
|
||||
super(Rancher, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class LiveStock(BaseModel):
|
||||
rancher = models.ForeignKey(Rancher, on_delete=models.CASCADE, null=True)
|
||||
national_id_livestock_code = models.CharField(max_length=200, null=True)
|
||||
herd_code = models.CharField(max_length=100, null=True)
|
||||
type = models.CharField(max_length=200, null=True)
|
||||
birth_day = models.CharField(max_length=200, null=True)
|
||||
gender = models.CharField(max_length=100, null=True)
|
||||
contractor_code = models.CharField(max_length=100, null=True)
|
||||
unique_identifier = models.CharField(max_length=100, null=True)
|
||||
agent = models.CharField(max_length=100, null=True)
|
||||
registering_user = models.CharField(max_length=200, null=True)
|
||||
registering_date = models.CharField(max_length=200, null=True)
|
||||
active = models.BooleanField(default=True)
|
||||
birth_day_gh = models.DateTimeField(null=True)
|
||||
registering_date_gh = models.DateTimeField(null=True)
|
||||
archive=models.BooleanField(default=False)
|
||||
age_of_archive=models.IntegerField(default=1)
|
||||
archiver=models.CharField(max_length=250,null=True)
|
||||
archive_date=models.DateTimeField(null=True)
|
||||
returner_from_archive=models.CharField(max_length=250,null=True)
|
||||
return_from_archive_date=models.DateTimeField(null=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(LiveStock, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class LiveStockProduct(BaseModel):
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
image = models.CharField(max_length=500, null=True)
|
||||
unit = models.CharField(max_length=200, null=True)
|
||||
price = models.IntegerField(default=0)
|
||||
light_wight = models.IntegerField(default=0)
|
||||
heavy_wight = models.IntegerField(default=0)
|
||||
company_price = models.IntegerField(default=0)
|
||||
shipping_price = models.IntegerField(default=0)
|
||||
union_price = models.IntegerField(default=0)
|
||||
cooperative_price = models.IntegerField(default=0)
|
||||
light_wight_industrial = models.IntegerField(default=0)
|
||||
heavy_wight_industrial = models.IntegerField(default=0)
|
||||
light_wight_dha = models.IntegerField(default=0)
|
||||
heavy_wight_dha = models.IntegerField(default=0)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(LiveStockProduct, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class CooperativeProductsShare(BaseModel):
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_share_product",
|
||||
null=True
|
||||
)
|
||||
product = models.ForeignKey(
|
||||
LiveStockProduct,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_share_product",
|
||||
null=True
|
||||
)
|
||||
price = models.IntegerField(default=0)
|
||||
shipping_price = models.IntegerField(default=0)
|
||||
union_price = models.IntegerField(default=0)
|
||||
cooperative_price = models.IntegerField(default=0)
|
||||
company_price = models.IntegerField(default=0)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(CooperativeProductsShare, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class LiveStockRolseProduct(BaseModel):
|
||||
parent_product = models.ForeignKey(
|
||||
LiveStockProduct,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="parents_product",
|
||||
null=True
|
||||
)
|
||||
jahad = models.ForeignKey(
|
||||
LiveStockProvinceJahad,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="jahad_product",
|
||||
null=True
|
||||
)
|
||||
union = models.ForeignKey(
|
||||
Union,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="union_product",
|
||||
null=True
|
||||
)
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_product",
|
||||
null=True
|
||||
)
|
||||
# rancher = models.ForeignKey(
|
||||
# Rancher,
|
||||
# on_delete=models.CASCADE,
|
||||
# related_name="rancher_product",
|
||||
# null=True
|
||||
# )
|
||||
name = models.CharField(max_length=200, null=True)
|
||||
total_weight = models.BigIntegerField(default=0)
|
||||
total_receipt_weight = models.BigIntegerField(default=0)
|
||||
total_allocated_weight = models.BigIntegerField(default=0)
|
||||
total_remain_weight = models.BigIntegerField(default=0)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
self.total_remain_weight = self.total_weight - self.total_allocated_weight
|
||||
super(LiveStockRolseProduct, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class LiveStockAllocations(BaseModel):
|
||||
product = models.ForeignKey(
|
||||
LiveStockRolseProduct,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="product_allocation",
|
||||
null=True
|
||||
)
|
||||
jahad = models.ForeignKey(
|
||||
LiveStockProvinceJahad,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="jahad_allocation",
|
||||
null=True
|
||||
)
|
||||
union = models.ForeignKey(
|
||||
Union,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="union_allocation",
|
||||
null=True
|
||||
)
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="cooperative_allocation",
|
||||
null=True
|
||||
)
|
||||
state = models.CharField(max_length=200, default='pending')
|
||||
weight = models.BigIntegerField(default=0)
|
||||
real_weight = models.BigIntegerField(default=0)
|
||||
date = models.DateTimeField(default=datetime.datetime.now)
|
||||
allocate_from = models.CharField(max_length=200, null=True)
|
||||
allocate_to = models.CharField(max_length=200, null=True)
|
||||
place = models.TextField(null=True)
|
||||
charge = models.BooleanField(default=False)
|
||||
code = models.CharField(max_length=200, null=True)
|
||||
description = models.TextField(null=True, blank=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(LiveStockAllocations, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class Contractor(BaseModel):
|
||||
user = models.ForeignKey(
|
||||
SystemUserProfile,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="contractor_user",
|
||||
null=True
|
||||
)
|
||||
address = models.ForeignKey(
|
||||
SystemAddress,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="contractor_user",
|
||||
null=True
|
||||
)
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="contractor_cooperative",
|
||||
null=True
|
||||
)
|
||||
contractor_code = models.CharField(max_length=100, null=True)
|
||||
fullname = models.CharField(max_length=200, null=True)
|
||||
entity_code = models.CharField(max_length=200, null=True)
|
||||
national_id = models.CharField(max_length=100, null=True)
|
||||
company_name = models.CharField(max_length=200, null=True)
|
||||
number_of_rancher = models.IntegerField(default=0)
|
||||
heavy_livestock = models.IntegerField(default=0)
|
||||
light_livestock = models.IntegerField(default=0)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(Contractor, self).save(*args, **kwargs)
|
||||
|
||||
|
||||
class PosSeller(BaseModel):
|
||||
cooperative = models.ForeignKey(
|
||||
Cooperative,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="seller_pos_cooperative",
|
||||
null=True
|
||||
)
|
||||
full_name=models.CharField(max_length=200,null=True)
|
||||
mobile=models.CharField(max_length=50,null=True)
|
||||
national_id=models.CharField(max_length=50,null=True)
|
||||
city=models.CharField(max_length=100,null=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(PosSeller, self).save(*args, **kwargs)
|
||||
31
LiveStock/sms_management.py
Normal file
31
LiveStock/sms_management.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import requests
|
||||
from django.http import HttpResponse
|
||||
|
||||
from LiveStock.models import Cooperative
|
||||
from authentication.sahandsms.sms import USERNAME_SMS, PASSWORD_SMS, USERNAME_SMS_FINANCIAL, PASSWORD_SMS_FINANCIAL
|
||||
from panel.helper import check_mobile_number
|
||||
|
||||
|
||||
def send_sms_for_cooperative(request):
|
||||
cooperative=Cooperative.objects.filter(trash=False)
|
||||
for c in cooperative:
|
||||
mobile=c.user.mobile
|
||||
password=c.user.password
|
||||
message = 'کاربر گرامی' \
|
||||
f'\n' \
|
||||
f'اطلاعات کاربری شما در سامانه به شرح زیر میباشد:' \
|
||||
f'\n' \
|
||||
f'\n' \
|
||||
f'نام کاربری: {mobile}' \
|
||||
f'\n' \
|
||||
f'رمز عبور: {password}' \
|
||||
f'\n' \
|
||||
f'(سامانه رصدیار)' \
|
||||
|
||||
check_mobile = check_mobile_number(mobile)
|
||||
if check_mobile:
|
||||
u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
|
||||
USERNAME_SMS, PASSWORD_SMS,
|
||||
mobile, message)
|
||||
|
||||
return HttpResponse('pk')
|
||||
3
LiveStock/tests.py
Normal file
3
LiveStock/tests.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
10
LiveStock/urls.py
Normal file
10
LiveStock/urls.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from django.urls import path, include
|
||||
|
||||
urlpatterns = [
|
||||
path('jahad/', include('LiveStock.Jahad.urls')),
|
||||
path('union/', include('LiveStock.Union.urls')),
|
||||
path('cooperative/', include('LiveStock.Cooperative.urls')),
|
||||
path('rancher/', include('LiveStock.Rancher.urls')),
|
||||
path('live-stock/', include('LiveStock.LiveStoksAndPoultry.urls')),
|
||||
path('contractor/', include('LiveStock.Contractor.urls')),
|
||||
]
|
||||
3
LiveStock/views.py
Normal file
3
LiveStock/views.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
||||
0
RasadyaarBale/__init__.py
Normal file
0
RasadyaarBale/__init__.py
Normal file
3
RasadyaarBale/admin.py
Normal file
3
RasadyaarBale/admin.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
6
RasadyaarBale/apps.py
Normal file
6
RasadyaarBale/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class RasadyaarbaleConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'RasadyaarBale'
|
||||
1
RasadyaarBale/helper.py
Normal file
1
RasadyaarBale/helper.py
Normal file
@@ -0,0 +1 @@
|
||||
Token="1092215072:Dg6DpySANPbpARwBRzftJzmMLKBRiFS7yIoXsTig"
|
||||
39
RasadyaarBale/migrations/0001_initial.py
Normal file
39
RasadyaarBale/migrations/0001_initial.py
Normal file
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 3.2.13 on 2025-05-27 10:54
|
||||
|
||||
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 = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='User_Bale',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('chat_id', models.BigIntegerField(unique=True)),
|
||||
('first_name', models.CharField(blank=True, max_length=100, null=True)),
|
||||
('last_name', models.CharField(blank=True, max_length=100, null=True)),
|
||||
('phone_number', models.CharField(blank=True, max_length=20, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('super_admin', models.BooleanField(default=False)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_bale_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_bale_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
20
RasadyaarBale/migrations/0002_user_bale_rasadyar_user.py
Normal file
20
RasadyaarBale/migrations/0002_user_bale_rasadyar_user.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# Generated by Django 3.2.13 on 2025-05-27 12:02
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('authentication', '0053_auto_20250527_1202'),
|
||||
('RasadyaarBale', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='user_bale',
|
||||
name='rasadyar_user',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rasadyar_user', to='authentication.systemuserprofile'),
|
||||
),
|
||||
]
|
||||
0
RasadyaarBale/migrations/__init__.py
Normal file
0
RasadyaarBale/migrations/__init__.py
Normal file
19
RasadyaarBale/models.py
Normal file
19
RasadyaarBale/models.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
from authentication.models import BaseModel, SystemUserProfile
|
||||
|
||||
|
||||
class User_Bale(BaseModel):
|
||||
rasadyar_user = models.ForeignKey(SystemUserProfile, on_delete=models.CASCADE,
|
||||
related_name="rasadyar_user",
|
||||
null=True)
|
||||
chat_id = models.BigIntegerField(unique=True)
|
||||
first_name = models.CharField(max_length=100, null=True, blank=True)
|
||||
last_name = models.CharField(max_length=100, null=True, blank=True)
|
||||
phone_number = models.CharField(max_length=20, null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
super_admin = models.BooleanField(default=False)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(User_Bale, self).save(*args, **kwargs)
|
||||
3
RasadyaarBale/tests.py
Normal file
3
RasadyaarBale/tests.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
15
RasadyaarBale/urls.py
Normal file
15
RasadyaarBale/urls.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from RasadyaarBale.views import bale_set_webhook, BaleWebhookView
|
||||
|
||||
router = DefaultRouter()
|
||||
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('set_webhook/', bale_set_webhook),
|
||||
path('webhook/', BaleWebhookView.as_view()),
|
||||
|
||||
]
|
||||
230
RasadyaarBale/views.py
Normal file
230
RasadyaarBale/views.py
Normal file
@@ -0,0 +1,230 @@
|
||||
import json
|
||||
|
||||
import requests
|
||||
from django.http import HttpResponse
|
||||
from rest_framework import status
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from authentication.models import SystemUserProfile
|
||||
from general_urls import base_url_for_sms_report
|
||||
from panel.convert_date import convert_to_shamsi
|
||||
from panel.models import PosCompany, ProductsTransactions
|
||||
from .helper import Token
|
||||
from .models import User_Bale
|
||||
|
||||
|
||||
class BaleWebhookView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
data = request.data
|
||||
|
||||
if 'message' in data:
|
||||
message = data['message']
|
||||
chat_id = message['chat']['id']
|
||||
user_info = message.get('from', {})
|
||||
|
||||
user, created = User_Bale.objects.update_or_create(
|
||||
chat_id=chat_id,
|
||||
defaults={
|
||||
'first_name': user_info.get('first_name'),
|
||||
'last_name': user_info.get('last_name'),
|
||||
}
|
||||
)
|
||||
|
||||
text = message.get('text', '')
|
||||
contact = message.get('contact', '')
|
||||
|
||||
if text == '/start':
|
||||
welcome_message = "سلام! به ربات هوشمند سامانه رصدیار خوش آمدید. لطفاً برای ادامه شماره تلفن خود را ثبت کنید."
|
||||
|
||||
keyboard = {
|
||||
"keyboard": [[{
|
||||
"text": "📱 ارسال شماره تلفن",
|
||||
"request_contact": True
|
||||
}]],
|
||||
"resize_keyboard": True,
|
||||
"one_time_keyboard": True
|
||||
}
|
||||
|
||||
self.send_message(
|
||||
chat_id,
|
||||
welcome_message,
|
||||
reply_markup=keyboard
|
||||
)
|
||||
elif contact:
|
||||
phone = contact['phone_number']
|
||||
if phone.startswith('98'):
|
||||
phone = '0' + phone[2:]
|
||||
system_user=SystemUserProfile.objects.filter(trash=False,mobile=phone).first()
|
||||
if system_user:
|
||||
user.rasadyar_user=system_user
|
||||
user.phone_number = phone
|
||||
user.save()
|
||||
|
||||
keyboard = {
|
||||
"keyboard": [
|
||||
[{"text": "ℹ️ درباره ما"},
|
||||
{"text": "📬 تماس با ما"}
|
||||
]
|
||||
],
|
||||
"resize_keyboard": True,
|
||||
"one_time_keyboard": False
|
||||
}
|
||||
|
||||
self.send_message(
|
||||
chat_id,
|
||||
f"شماره شما ثبت شد: {phone}",
|
||||
reply_markup=keyboard
|
||||
)
|
||||
elif text == "ℹ️ درباره ما":
|
||||
self.send_message(
|
||||
chat_id,
|
||||
"ربات هوشمند ساخته شده با پایتون \n\n"
|
||||
"توسعه دهنده: شرکت هوشمندسازان فرآیند های نوین ماداکتو"
|
||||
)
|
||||
elif text == "📬 تماس با ما":
|
||||
self.send_message(
|
||||
chat_id,
|
||||
"برای ارتباط با ما:\n\n"
|
||||
"📧 ایمیل: info@mnpc.ir\n"
|
||||
"☎️ تلفن: 28421237-021\n"
|
||||
"🌐 وبسایت: https://mnpc.ir/ \n"
|
||||
)
|
||||
|
||||
else:
|
||||
self.send_message(chat_id, f"لطفا از دکمه های راهنما استفاده کنید.")
|
||||
|
||||
return Response({'status': 'ok'}, status=status.HTTP_200_OK)
|
||||
|
||||
except Exception as e:
|
||||
print("خطا:", e)
|
||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def send_message(self, chat_id, text, reply_markup=None):
|
||||
url = f"https://tapi.bale.ai/bot{Token}/sendMessage"
|
||||
payload = {
|
||||
"chat_id": chat_id,
|
||||
"text": text
|
||||
}
|
||||
|
||||
if reply_markup:
|
||||
payload["reply_markup"] = reply_markup
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
|
||||
try:
|
||||
response = requests.post(url, data=json.dumps(payload), headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
print("خطا در ارسال پیام:", e)
|
||||
return None
|
||||
|
||||
|
||||
def bale_set_webhook(request):
|
||||
response = requests.post(
|
||||
f"https://tapi.bale.ai/bot{Token}/setWebhook",
|
||||
json={"url": f"https://{base_url_for_sms_report}backend.rasadyaar.ir/bale/webhook/"}
|
||||
)
|
||||
|
||||
return HttpResponse(response.json())
|
||||
|
||||
|
||||
def send_message_for_bale(chat_id, text, reply_markup=None):
|
||||
url = f"https://tapi.bale.ai/bot{Token}/sendMessage"
|
||||
payload = {
|
||||
"chat_id": chat_id,
|
||||
"text": text
|
||||
}
|
||||
|
||||
if reply_markup:
|
||||
payload["reply_markup"] = reply_markup
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
|
||||
try:
|
||||
response = requests.post(url, data=json.dumps(payload), headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
print("خطا در ارسال پیام:", e)
|
||||
return None
|
||||
|
||||
|
||||
def send_transaction(transaction, chat_ids):
|
||||
try:
|
||||
if transaction.paid or transaction.status in (0, 1):
|
||||
pos_company = PosCompany.objects.filter(trash=False, en_name__exact=transaction.posProvider).first()
|
||||
if pos_company:
|
||||
pos_company_name = pos_company.name
|
||||
else:
|
||||
pos_company_name = 'ناشناس'
|
||||
if transaction.pos.kill_house:
|
||||
dict_info = {
|
||||
'name': transaction.pos.kill_house.name,
|
||||
'mobile': transaction.pos.kill_house.kill_house_operator.user.mobile,
|
||||
'fullname': transaction.pos.kill_house.kill_house_operator.user.fullname,
|
||||
'city': transaction.pos.kill_house.kill_house_operator.user.city.name,
|
||||
'province': transaction.pos.kill_house.kill_house_operator.user.province.name,
|
||||
'national_code': transaction.pos.kill_house.kill_house_operator.user.national_code,
|
||||
'type': 'کشتارگاه',
|
||||
}
|
||||
elif transaction.pos.guild:
|
||||
dict_info = {
|
||||
'name': transaction.pos.guild.guilds_name,
|
||||
'mobile': transaction.pos.guild.user.mobile,
|
||||
'fullname': transaction.pos.guild.user.fullname,
|
||||
'city': transaction.pos.guild.user.city.name,
|
||||
'province': transaction.pos.guild.user.province.name,
|
||||
'national_code': transaction.pos.guild.user.national_code,
|
||||
'type': 'صنف',
|
||||
}
|
||||
else:
|
||||
dict_info = {
|
||||
'name': transaction.pos.cooperative.name,
|
||||
'mobile': transaction.pos.cooperative.user.mobile,
|
||||
'fullname': transaction.pos.cooperative.user.fullname,
|
||||
'city': transaction.pos.cooperative.user.city.name,
|
||||
'province': transaction.pos.cooperative.user.province.name,
|
||||
'national_code': transaction.pos.cooperative.user.national_code,
|
||||
'type': 'سامانه دام',
|
||||
}
|
||||
|
||||
price = "{:,}".format(int(transaction.price))
|
||||
|
||||
alert_message = (
|
||||
f"*---* {transaction.result} *---*\n"
|
||||
f"{dict_info['type']} : *{dict_info['name']}*\n"
|
||||
f"آدرس : *{dict_info['province']}* - *{dict_info['city']}*\n"
|
||||
f"درگاه : *{pos_company_name}*\n"
|
||||
f"زمان : *{convert_to_shamsi(datetime=transaction.date, in_value=True)}*\n"
|
||||
f"مبلغ کل : *{price}* ریال\n\n"
|
||||
)
|
||||
products = ProductsTransactions.objects.filter(trash=False, transaction=transaction)
|
||||
for prd in products:
|
||||
if prd.live_stack_products:
|
||||
fi_prd_price = "{:,}".format(int(int(prd.cur_price) / int(prd.cur_weight)) if prd.cur_weight > 0 else 0)
|
||||
else:
|
||||
fi_prd_price = "{:,}".format(int(prd.price))
|
||||
cur_weight = "{:,}".format(int(prd.cur_weight))
|
||||
cur_price = "{:,}".format(int(prd.cur_price))
|
||||
if prd.cur_weight != 1:
|
||||
alert_message += (
|
||||
f"*{prd.name}* (فی {fi_prd_price} ریال)\n"
|
||||
f"وزن خریداری شده:({cur_weight}{prd.targetunit}) \n"
|
||||
f"مبلغ: *{cur_price}* ریال\n\n"
|
||||
)
|
||||
else:
|
||||
alert_message += (
|
||||
f"*{prd.name}* \n"
|
||||
f"خریداری شده : *{cur_price}* ریال\n\n"
|
||||
)
|
||||
|
||||
for i in chat_ids:
|
||||
send_message_for_bale(chat_id=i, text=alert_message)
|
||||
except:
|
||||
pass
|
||||
BIN
Users.xlsx
Normal file
BIN
Users.xlsx
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user