Skip to content

Commit

Permalink
Merge pull request #231 from 5sControl/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
Dimskay1988 authored May 24, 2023
2 parents de7bbe5 + 75200e4 commit 1c395d8
Show file tree
Hide file tree
Showing 23 changed files with 166 additions and 54 deletions.
3 changes: 0 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,4 @@ EXPOSE 80

RUN ["chmod", "+x", "/usr/src/app/entrypoint.sh"]

# run the command
# ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

CMD ./entrypoint.sh
2 changes: 0 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ fill:
python manage.py createadmin
startprocess:
python manage.py startprocess
mssql-get:
python manage.py inspectdb --database=mssql Skany > src/Order/models.py
all:
make migrate
make fill
Expand Down
2 changes: 1 addition & 1 deletion config/settings/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
},
"file": {
"class": "logging.FileHandler",
"filename": "logs.log",
"filename": "log/logs.log",
},
},
"loggers": {
Expand Down
19 changes: 10 additions & 9 deletions entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
#!/bin/sh

# create tables
python manage.py migrate

# fill algorithm table
celery -A config.celery worker -l info &
celery -A config.celery beat -l info &

python manage.py runserver 0.0.0.0:80 &

sleep 5

python manage.py algorithm
python manage.py createadmin

# setup config
python manage.py startprocess

# run celery
celery -A config.celery worker -l info &
celery -A config.celery beat -l info &

# run server
python manage.py runserver 0.0.0.0:80
while true; do
sleep 1
done
Empty file added log/.gitkeep
Empty file.
20 changes: 12 additions & 8 deletions src/CameraAlgorithms/services/cameraalgorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

from typing import Any, Dict, Iterable, List

from src.Core.const import SERVER_URL
from src.Core.exceptions import InvalidResponseError, SenderError
from src.Core.exceptions import InvalidResponseError, SenderError, CameraConnectionError
from src.Core.utils import Sender
from src.Inventory.models import Items
from src.OrderView.models import IndexOperations
from src.CompanyLicense.decorators import check_active_cameras, check_active_algorithms

from ..models import Camera
from ..models import Algorithm, CameraAlgorithm
Expand All @@ -16,6 +16,8 @@
logger = logging.getLogger(__name__)


@check_active_cameras
@check_active_algorithms
def CreateCameraAlgorithms(camera_algorithm_data: Dict[str, Any]) -> None:
camera: Dict[str, str] = camera_algorithm_data["camera"]
algorithms: List[Dict[str, Any]] = camera_algorithm_data["algorithms"]
Expand All @@ -34,15 +36,15 @@ def check_connection(camera_data: Dict[str, str]) -> bool:
return response["status"]


def DeleteCamera(camera_instance):
def DeleteCamera(camera_instance: Camera) -> Dict[str, Any]:
query_list_cameraalgorithms: Iterable[
CameraAlgorithm
] = CameraAlgorithm.objects.filter(camera=camera_instance)

for camera_algorithm in query_list_cameraalgorithms:
pid: int = camera_algorithm.process_id
if camera_algorithm.algorithm.name == "operation_control":
IndexOperations.objects.get(camera=camera_algorithm.camera).delete()
IndexOperations.objects.filter(camera=camera_algorithm.camera).delete()
stop_camera_algorithm(pid)
update_status_algorithm(pid)

Expand Down Expand Up @@ -74,7 +76,8 @@ def create_camera(camera: Dict[str, str]) -> None:
if is_camera_exist:
return

check_connection({"ip": ip, "username": username, "password": password})
if not check_connection({"ip": ip, "username": username, "password": password}):
raise CameraConnectionError(ip)

try:
camera_obj_to_update = Camera.objects.get(id=ip)
Expand Down Expand Up @@ -171,12 +174,12 @@ def create_camera_algorithms(
)
pid: int = algorithm.process_id

if algorithm_name == "operation_control":
IndexOperations.objects.get(camera=camera_obj).delete()

stop_camera_algorithm(pid)
update_status_algorithm(pid)

if algorithm_name == "operation_control":
IndexOperations.objects.filter(camera=camera_obj).delete()

logger.warning(f"Successfully deleted -> {algorithm_name} with pid {pid}")


Expand All @@ -186,6 +189,7 @@ def camera_rtsp_link(id: str) -> str:


def send_run_request(request: Dict[str, Any]) -> Dict[str, Any]:
logger.warning(f"Request data for algorithm {request}")
try:
response = Sender("run", request)
except requests.exceptions.HTTPError as e:
Expand Down
1 change: 1 addition & 0 deletions src/CompanyLicense/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def check_active_algorithms(view_func):
@wraps(view_func)
def wrapped_view(request, *args, **kwargs):
company = Company.objects.last()
print("!!!!!!")

if not company.is_active:
return HttpResponseBadRequest("Your license is inactive.")
Expand Down
1 change: 0 additions & 1 deletion src/CompanyLicense/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User


class Company(models.Model):
Expand Down
7 changes: 6 additions & 1 deletion src/CompanyLicense/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ def get(self, request):
return Response({"error": "Company not found"}, status=404)

is_license_active = f"{company.valid_until - timezone.now().date()}"

count_days = int(is_license_active.split(",")[0].split(" ")[0])
if count_days < 0:
count_days = 0

active_cameras_count = Camera.objects.filter(is_active=True).count()
active_algorithms_count = (
CameraAlgorithm.objects.values("algorithm").distinct().count()
Expand All @@ -63,7 +68,7 @@ def get(self, request):
"licence_neurons_active": company.neurons_active,
"company_active_count_cameras": active_cameras_count,
"company_active_count_neurons": active_algorithms_count,
"days_left": is_license_active.split(",")[0],
"days_left": f"{count_days} days",
}
return Response(response_data, status=200)

Expand Down
8 changes: 8 additions & 0 deletions src/Core/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib import admin

from .models import SystemMessage


@admin.register(SystemMessage)
class SystemMessageAdmin(admin.ModelAdmin):
list_filter = ["title"]
6 changes: 6 additions & 0 deletions src/Core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,9 @@ class DatabaseConnectioneError(Exception):
def __init__(self, func_name):
self.func_name = func_name
super().__init__(f"Database connection error. Function: {func_name}")


class CameraConnectionError(Exception):
def __class__(self, camera_ip):
self.camera_ip = camera_ip
super().__init__(f"Camera {camera_ip} connection error")
5 changes: 3 additions & 2 deletions src/Core/management/commands/createadmin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from django.core.management.base import BaseCommand
import logging

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

from src.Core.logger import logger
logger = logging.getLogger(__name__)


class Command(BaseCommand):
Expand Down
29 changes: 29 additions & 0 deletions src/Core/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 4.1.4 on 2023-05-22 13:54

from django.db import migrations, models


class Migration(migrations.Migration):
initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="SystemMessage",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=150)),
("content", models.TextField()),
("created_at", models.DateTimeField(auto_now_add=True)),
],
),
]
Empty file added src/Core/migrations/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions src/Core/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.db import models


class SystemMessage(models.Model):
title = models.CharField(max_length=150)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
6 changes: 6 additions & 0 deletions src/Core/paginators.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,9 @@ def get_paginated_response(self, data):
]
)
)


class SystemMessagesPaginator(PageNumberPagination):
page_size = 25
page_size_query_param = "page_size"
max_page_size = 100
15 changes: 15 additions & 0 deletions src/Core/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from rest_framework import serializers

from src.Core.models import SystemMessage


class SystemMessagesSerializer(serializers.ModelSerializer):
created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S.%f")

class Meta:
model = SystemMessage
fields = [
"title",
"content",
"created_at",
]
19 changes: 11 additions & 8 deletions src/Core/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from django.urls import path
from .views import FindCameraAPIView, CheckMemoryStatus
from rest_framework.routers import DefaultRouter

from django.urls import path, include

from .views import FindCameraAPIView, SystemMessagesApiView

api_router = DefaultRouter()

api_router.register('system-message', SystemMessagesApiView, basename='system-message')

urlpatterns = [
path(
"is_enough_memory/",
CheckMemoryStatus.as_view(),
name="memory_available",
),
path("find_cameras/", FindCameraAPIView.as_view(), name="find cameras"),
path('', include(api_router.urls)),
path("find_cameras/", FindCameraAPIView.as_view(), name="find-cameras"),
]
28 changes: 13 additions & 15 deletions src/Core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,12 @@
import requests

from rest_framework.response import Response
from rest_framework import status, generics
from rest_framework import status, generics, viewsets, mixins

from src.Core.const import SERVER_URL


class CheckMemoryStatus(generics.GenericAPIView):
def get(self, request):
usage_stats = os.statvfs(os.getcwd())

block_size = usage_stats.f_frsize
available_blocks = usage_stats.f_bavail
available_space_gb = available_blocks * block_size / (1000**3)

has_enough_space = available_space_gb > 15

return Response({"has_enough_space": has_enough_space})
from .const import SERVER_URL
from .serializers import SystemMessagesSerializer
from .models import SystemMessage
from .paginators import SystemMessagesPaginator


class FindCameraAPIView(generics.GenericAPIView):
Expand All @@ -32,3 +22,11 @@ def get(self, request, *args, **kwargs):

response_data = {"results": cameras}
return Response(response_data, status=status.HTTP_200_OK)


class SystemMessagesApiView(mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
serializer_class = SystemMessagesSerializer
queryset = SystemMessage.objects.order_by("-id")
pagination_class = SystemMessagesPaginator
11 changes: 11 additions & 0 deletions src/Inventory/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,21 @@ def process_item_status(data):
else:
item.current_stock_level = min_item - 1
item_data["count"] = min_item - 1

if item.prev_status == "In stock":
try:
item.prev_status = None
send_email(item, image_path, min_item, item_status)
except Exception as e:
print(f"Email notification errors: {e}")
item.prev_status = "Low stock level"

else:
item_status = "In stock"
item.current_stock_level = min_item + 1
item_data["count"] = min_item + 1
item.prev_status = "In stock"

else:
if count == 0:
item_status = "Out of stock"
Expand Down
6 changes: 3 additions & 3 deletions src/OrderView/services/order_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,19 +175,19 @@ def transform_result(self, result):
{
"indeks": data[0],
"data": datetime.strptime(
data[1], "%Y-%m-%d %H:%M:%S.%f"
data[1].strftime("%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d %H:%M:%S.%f"
).replace(tzinfo=timezone.utc)
if data[1] is not None
else None,
"zlecenie": data[2].strip(),
"klient": data[3].strip(),
"datawejscia": datetime.strptime(
data[4], "%Y-%m-%d %H:%M:%S.%f"
data[4].strftime("%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d %H:%M:%S.%f"
).replace(tzinfo=timezone.utc)
if data[4]
else None,
"datazakonczenia": datetime.strptime(
data[5], "%Y-%m-%d %H:%M:%S.%f"
data[5].strftime("%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d %H:%M:%S.%f"
).replace(tzinfo=timezone.utc)
if data[5]
else None,
Expand Down
23 changes: 23 additions & 0 deletions src/Reports/migrations/0002_alter_report_camera.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.1.4 on 2023-05-22 13:18

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
dependencies = [
("CameraAlgorithms", "0001_initial"),
("Reports", "0001_initial"),
]

operations = [
migrations.AlterField(
model_name="report",
name="camera",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="CameraAlgorithms.camera",
),
),
]
Loading

0 comments on commit 1c395d8

Please sign in to comment.