вывод показаний весов
This commit is contained in:
parent
49d18079e3
commit
3613fc3351
@ -13,7 +13,7 @@ class FabricWorkTimeAdmin(admin.ModelAdmin):
|
||||
|
||||
@admin.register(ScalesControl)
|
||||
class ScalesControlAdmin(admin.ModelAdmin):
|
||||
list_display = ['date_created', 'name', 'values']
|
||||
list_display = ['date_created', 'name', 'value']
|
||||
list_filter = ['date', 'name']
|
||||
ordering = ['-date', ]
|
||||
|
||||
|
||||
@ -35,7 +35,7 @@ class ScalesControl(models.Model):
|
||||
Поле value хранит числовое значение в тоннах
|
||||
"""
|
||||
name = models.CharField(db_column='Name', max_length=150, blank=True, null=True)
|
||||
values = models.CharField(db_column='Values', max_length=150, blank=True, null=True)
|
||||
value = models.DecimalField(db_column='Values', decimal_places=6, max_digits=50, blank=True, null=True)
|
||||
date = models.DateTimeField(db_column='Date', blank=True, null=True)
|
||||
check = models.BooleanField(db_column='Check', default=False)
|
||||
|
||||
@ -46,7 +46,7 @@ class ScalesControl(models.Model):
|
||||
def json(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'values': self.values,
|
||||
'values': self.value,
|
||||
'date': self.date,
|
||||
}
|
||||
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
from datetime import datetime, date, time
|
||||
import json
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django.core.serializers import serialize
|
||||
from django.db.models import Max, QuerySet
|
||||
from django.db.models import Max, QuerySet, Q
|
||||
from django.forms import model_to_dict
|
||||
from django.http import JsonResponse
|
||||
|
||||
@ -71,18 +72,46 @@ def get_scales_value(positions: QuerySet, interval: str) -> dict:
|
||||
for position in positions:
|
||||
try:
|
||||
obj = ScalesControl.objects.filter(name__endswith=f'{position.tag}.{interval}').latest('date')
|
||||
res[position.title] = obj.values
|
||||
res[position.title] = int(obj.value)
|
||||
except ScalesControl.DoesNotExist:
|
||||
res[position.title] = '0'
|
||||
return res
|
||||
|
||||
|
||||
def get_scales_value_by_shifts(positions: QuerySet, interval: str) -> dict:
|
||||
res = {}
|
||||
current_work_shift = {}
|
||||
previous_work_shift = {}
|
||||
now = timezone.now()
|
||||
today = now.date()
|
||||
start_of_today = timezone.make_aware(datetime.combine(today, time.min), timezone.get_current_timezone())
|
||||
eight_am_today = timezone.make_aware(datetime.combine(today, time(8, 0)), timezone.get_current_timezone())
|
||||
for position in positions:
|
||||
try:
|
||||
previous_work_shift_scale_data = ScalesControl.objects.filter(name__endswith=f'{position.tag}.{interval}',
|
||||
date__range=(
|
||||
start_of_today, eight_am_today)).latest(
|
||||
'date')
|
||||
previous_work_shift[position.title] = int(previous_work_shift_scale_data.value)
|
||||
except ScalesControl.DoesNotExist:
|
||||
previous_work_shift[position.title] = '0'
|
||||
try:
|
||||
current_work_shift_scale_data = ScalesControl.objects.filter(
|
||||
name__endswith=f'{position.tag}.{interval}').latest('date')
|
||||
current_work_shift[position.title] = int(current_work_shift_scale_data.value)
|
||||
except ScalesControl.DoesNotExist:
|
||||
current_work_shift[position.title] = '0'
|
||||
res['previous_work_shift'] = previous_work_shift
|
||||
res['current_work_shift'] = current_work_shift
|
||||
return res
|
||||
|
||||
|
||||
@base_view
|
||||
def get_scales_data(request):
|
||||
positions = Position.objects.all()
|
||||
monthly = get_scales_value(positions, 'Month')
|
||||
productivity = get_scales_value(positions, 'Productivity')
|
||||
daily = get_scales_value(positions, 'Sutki')
|
||||
productivity = get_scales_value_by_shifts(positions, 'Productivity')
|
||||
daily = get_scales_value_by_shifts(positions, 'Sutki')
|
||||
return JsonResponse({'daily': daily, 'monthly': monthly, 'productivity': productivity})
|
||||
|
||||
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import psycopg2
|
||||
from datetime import datetime
|
||||
import pytz
|
||||
from django.utils.timezone import make_aware
|
||||
|
||||
@ -20,12 +21,10 @@ def get_scales_data() -> list:
|
||||
cursor.execute("""
|
||||
SELECT "Name", "Values", "Date", "Check"
|
||||
FROM public.vesi
|
||||
WHERE "Date" BETWEEN '2024-06-09' AND '2024-06-10';
|
||||
ORDER BY id DESC
|
||||
LIMIT 5000;
|
||||
""")
|
||||
# SELECT "Name", "Values", "Date", "Check"
|
||||
# FROM public.vesi
|
||||
# ORDER BY "Date" DESC
|
||||
# LIMIT 30000;
|
||||
|
||||
data = cursor.fetchall()
|
||||
|
||||
conn_postgres.close()
|
||||
@ -43,45 +42,51 @@ def write_scales_data(data: list):
|
||||
try:
|
||||
with postgres_conn.cursor() as cursor:
|
||||
for row in data:
|
||||
name, value, date, check = row
|
||||
cursor.execute("""
|
||||
DO $$
|
||||
DECLARE
|
||||
value_exists BOOLEAN;
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM public.main_scalescontrol
|
||||
WHERE "Name" = %s AND date_trunc('second', "Date") = date_trunc('second', %s::timestamp)
|
||||
) THEN
|
||||
IF %s = ANY(
|
||||
SELECT "Values" FROM public.main_scalescontrol
|
||||
WHERE "Name" = %s AND date_trunc('second', "Date") = date_trunc('second', %s::timestamp)
|
||||
) THEN
|
||||
UPDATE public.main_scalescontrol
|
||||
SET "Date" = %s
|
||||
WHERE "Name" = %s AND date_trunc('second', "Date") = date_trunc('second', %s::timestamp);
|
||||
ELSE
|
||||
INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check")
|
||||
VALUES (%s, %s, date_trunc('second', %s::timestamp), %s);
|
||||
END IF;
|
||||
-- Check if the value already exists in the existing record
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM public.main_scalescontrol
|
||||
WHERE "Name" = %s AND "Values" = %s
|
||||
) INTO value_exists;
|
||||
|
||||
IF value_exists THEN
|
||||
UPDATE public.main_scalescontrol
|
||||
SET "Date" = %s
|
||||
WHERE "Name" = %s AND "Values" = %s;
|
||||
ELSE
|
||||
INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check")
|
||||
VALUES (%s, %s, date_trunc('second', %s::timestamp), %s);
|
||||
VALUES (%s, %s, %s, %s);
|
||||
END IF;
|
||||
END $$;
|
||||
""", (
|
||||
row[0],
|
||||
row[2],
|
||||
row[1], row[0], row[2],
|
||||
row[2], row[0], row[2],
|
||||
row[0], row[1], row[2], row[3],
|
||||
row[0], row[1], row[2], row[3]
|
||||
name, value, # Check if value exists
|
||||
date, name, value, # Update date if value exists
|
||||
name, value, date, check # Insert new record if value does not exist
|
||||
))
|
||||
postgres_conn.commit()
|
||||
except Exception:
|
||||
print(traceback.format_exc())
|
||||
print(row)
|
||||
postgres_conn.close()
|
||||
finally:
|
||||
postgres_conn.close()
|
||||
|
||||
|
||||
def main():
|
||||
while True:
|
||||
print(f"Task started at {datetime.now()}")
|
||||
scales_data = get_scales_data()
|
||||
print(f"Task: selected data at {datetime.now()}")
|
||||
write_scales_data(scales_data)
|
||||
print(f"Task performed at {datetime.now()}")
|
||||
time.sleep(600)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
scales_data = get_scales_data()
|
||||
write_scales_data(scales_data)
|
||||
main()
|
||||
|
||||
@ -3,6 +3,8 @@ import django
|
||||
from datetime import datetime, timedelta
|
||||
import random
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.main.models.dashboard_models import FabricWorkTime
|
||||
|
||||
# Устанавливаем переменную окружения для настроек Django
|
||||
@ -12,9 +14,9 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'repcofkk.settings')
|
||||
django.setup()
|
||||
|
||||
# Дата начала (1 мая текущего года)
|
||||
start_date = datetime(datetime.now().year, 5, 1)
|
||||
start_date = timezone.make_aware(datetime(datetime.now().year, 5, 11))
|
||||
# Количество дней
|
||||
num_days = 40
|
||||
num_days = 90
|
||||
# Шаг времени в минутах
|
||||
time_step = timedelta(minutes=5)
|
||||
|
||||
|
||||
@ -7,10 +7,10 @@
|
||||
const DailyBarOptions = {
|
||||
series: [{
|
||||
name: 'Текущая смена',
|
||||
data: [100, 200, 300]
|
||||
data: []
|
||||
}, {
|
||||
name: 'Предыдущая смена',
|
||||
data: [100, 200, 300]
|
||||
data: []
|
||||
}],
|
||||
colors: ['var(--success)', 'var(--primary)', 'var(--danger)'],
|
||||
chart: {
|
||||
@ -53,7 +53,7 @@
|
||||
categories: positions,
|
||||
},
|
||||
legend: {
|
||||
position: 'top',
|
||||
position: 'bottom',
|
||||
},
|
||||
fill: {
|
||||
opacity: 1
|
||||
@ -102,9 +102,10 @@
|
||||
enabled: true,
|
||||
style: {
|
||||
fontSize: '13px',
|
||||
fontWeight: 900
|
||||
fontWeight: 900,
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
}
|
||||
},
|
||||
},
|
||||
@ -113,13 +114,23 @@
|
||||
categories: positions,
|
||||
},
|
||||
legend: {
|
||||
position: 'top',
|
||||
position: 'bottom',
|
||||
},
|
||||
fill: {
|
||||
opacity: 1
|
||||
},
|
||||
title: {
|
||||
text: 'тонн за месяц'
|
||||
},
|
||||
tooltip: {
|
||||
y: {
|
||||
formatter: function (val) {
|
||||
return val + 'тонн'
|
||||
}
|
||||
}
|
||||
},
|
||||
noData: {
|
||||
text: 'Загрузка...'
|
||||
}
|
||||
};
|
||||
const monthlyScalesChart = new ApexCharts(document.querySelector("#monthlyScales"), monthlyBarOptions);
|
||||
@ -128,10 +139,10 @@
|
||||
const hoursBarOptions = {
|
||||
series: [{
|
||||
name: 'Текущая смена',
|
||||
data: [255, 106, 472]
|
||||
data: []
|
||||
}, {
|
||||
name: 'Предыдущая смена',
|
||||
data: [211, 101, 415]
|
||||
data: []
|
||||
},
|
||||
],
|
||||
chart: {
|
||||
@ -140,13 +151,25 @@
|
||||
},
|
||||
plotOptions: {
|
||||
bar: {
|
||||
horizontal: false,
|
||||
horizontal: true,
|
||||
columnWidth: '55%',
|
||||
endingShape: 'rounded'
|
||||
},
|
||||
},
|
||||
dataLabels: {
|
||||
enabled: true
|
||||
enabled: true,
|
||||
textAnchor: 'start',
|
||||
offsetX: 6,
|
||||
dropShadow: {
|
||||
enabled: false // Disable drop shadow to avoid white edges
|
||||
},
|
||||
formatter: function (val) {
|
||||
// Custom formatter to return an empty string for certain values
|
||||
if (val === 100 || val === 200) {
|
||||
return ''; // Remove white labels
|
||||
}
|
||||
return val; // Keep black labels
|
||||
}
|
||||
},
|
||||
stroke: {
|
||||
show: true,
|
||||
@ -168,6 +191,9 @@
|
||||
},
|
||||
title: {
|
||||
text: 'часовая нагрузка'
|
||||
},
|
||||
noData: {
|
||||
text: 'Загрузка...'
|
||||
}
|
||||
}
|
||||
const hoursBarChart = new ApexCharts(document.querySelector("#byHourScales"), hoursBarOptions);
|
||||
@ -180,9 +206,28 @@
|
||||
name: 'Месяц',
|
||||
data: Object.values(json.monthly)
|
||||
}])
|
||||
|
||||
hoursBarChart.updateSeries([{
|
||||
name: 'Текущая смена',
|
||||
data: Object.values(json.productivity.current_work_shift)
|
||||
},
|
||||
{
|
||||
name: 'Предыдущая смена',
|
||||
data: Object.values(json.productivity.previous_work_shift)
|
||||
}])
|
||||
|
||||
dailyScalesChart.updateSeries([{
|
||||
name: 'Текущая смена',
|
||||
data: Object.values(json.daily.current_work_shift)
|
||||
}, {
|
||||
name: 'Предыдущая смена',
|
||||
data: Object.values(json.daily.previous_work_shift)
|
||||
}])
|
||||
})
|
||||
|
||||
})();
|
||||
|
||||
})
|
||||
();
|
||||
|
||||
|
||||
(function () {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user