repcofkk/app/static/js/charts/scaleControl.js
2024-08-28 15:49:12 +07:00

645 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(async function () {
const positions = await fetch('positions/').then(response => {
return response.json()
})
const boldLabel = {
show: true,
maxHeight: 120,
style: {
fontSize: '13px',
cssClass: 'apexcharts-xaxis-label bold'
}
}
const locales = [{
name: 'ru',
options: {
months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентрябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
shortMonths: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июнь', 'Июль ', 'Авг', 'Сент', 'Окт', 'Нояб', 'Дек'],
days: ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'],
shortDays: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
toolbar: {
exportToSVG: 'Скачать SVG',
exportToPNG: 'Скачать PNG',
exportToCSV: 'Скачать CSV',
menu: 'Меню',
selection: 'Выборка',
selectionZoom: 'Приближение выборки',
zoomIn: 'Приблизить',
zoomOut: 'Отдалить',
pan: 'Панорамирование',
reset: 'Сбросить приближение'
}
}
}]
const colors = ['var(--success)', 'var(--primary)', 'var(--danger)']
const commonChartOptions = {
colors,
chart: {
type: 'bar',
height: 300,
locales,
defaultLocale: 'ru'
},
fill: {
opacity: 1
},
xaxis: {
categories: positions
},
noData: {
text: 'Загрузка...'
}
}
const commonRadialBarOptions = {
chart: {
type: 'radialBar',
height: 220
},
labels: ['т. смена ', 'пр. смена '],
series: [],
plotOptions: {
radialBar: {
size: undefined,
inverseOrder: false,
hollow: {
margin: 5,
size: '48%',
background: 'transparent'
},
track: {
show: true,
background: '#40475D',
strokeWidth: '10%',
opacity: 1,
margin: 3
},
dataLabels: {
name: {
show: true,
color: '#888',
fontSize: '12px',
fontWeight: 400
},
value: {
color: '#111',
offsetY: -2,
fontSize: '12px',
fontWeight: 400,
show: true
}
}
}
},
colors,
legend: {
show: true,
position: 'bottom',
formatter: function (val, opts) {
return val + ' - ' + opts.w.globals.series[opts.seriesIndex] + '%'
}
},
noData: {
text: 'Загрузка...'
}
}
const hoursBarOptions = {
...commonChartOptions,
series: [{
name: 'Текущая смена',
data: []
}, {
name: 'Предыдущая смена',
data: []
}],
plotOptions: {
bar: {
horizontal: true
}
},
dataLabels: {
enabled: true,
textAnchor: 'start',
offsetX: -7,
dropShadow: {
enabled: false
},
animation: {
enabled: false
}
},
stroke: {
show: true,
width: 2,
colors: ['transparent']
},
tooltip: {
y: {
formatter: function (val) {
return val + ' т/ч'
}
}
},
title: {
text: 'часовая нагрузка'
}
}
const dailyBarOptions = {
...commonChartOptions,
series: [],
chart: {
...commonChartOptions.chart,
stacked: true,
toolbar: {
show: true
}
},
responsive: [{
breakpoint: 480,
options: {
legend: {
position: 'bottom',
offsetX: -10,
offsetY: 0
}
}
}],
plotOptions: {
bar: {
horizontal: false,
dataLabels: {
total: {
enabled: true,
style: {
fontSize: '13px',
fontWeight: 900
}
}
}
}
},
legend: {
position: 'bottom'
},
title: {
text: 'тонн за сутки'
},
tooltip: {
y: {
formatter: function (val) {
return val + ' т.'
}
}
}
}
const monthlyBarOptions = {
...commonChartOptions,
series: [],
chart: {
...commonChartOptions.chart,
stacked: true,
toolbar: {
show: true
},
zoom: {
enabled: true
}
},
responsive: [{
breakpoint: 480,
options: {
legend: {
position: 'bottom',
offsetX: 10,
offsetY: 20
}
}
}],
plotOptions: {
bar: {
dataLabels: {
total: {
enabled: true,
style: {
fontSize: '13px',
fontWeight: 900
}
}
},
columnWidth: '60%'
}
},
dataLabels: {
enabled: true,
style: {
colors: ['rgba(0,0,0,0)']
},
offsetY: 0,
offsetX: 0,
textAnchor: 'start',
formatter: function (val) {
return val
}
},
legend: {
position: 'bottom'
},
title: {
text: 'тонн за месяц'
},
tooltip: {
y: {
formatter: function (val) {
return val + ' т.'
}
}
}
}
const hourOptionsCircle1 = {
...commonRadialBarOptions,
labels: ['Y к-та', 'Y отсева'],
title: {
text: 'т. смена'
}
}
const hourOptionsCircle2 = {
...commonRadialBarOptions,
labels: ['Y к-та', 'Y отсева'],
title: {
text: 'пр. смена'
}
}
const doubleOptionsCircle = {
...commonRadialBarOptions,
labels: ['Y к-та', 'Y отсева'],
legend: {
...commonRadialBarOptions.legend,
position: 'left'
}
}
const optionsFabricGoal = {
chart: {
height: 70,
width: '100%',
type: 'bar',
stacked: true,
sparkline: {
enabled: true
}
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '40%',
colors: {
backgroundBarColors: ['#40475D']
}
}
},
dataLabels: {
enabled: true,
formatter: function (val, opts) {
return val + ' т.'
},
style: {
colors: ['#fff'],
fontSize: '16px',
fontWeight: 'bold'
},
textAnchor: 'start'
},
colors,
stroke: {
width: 0
},
series: [
{
name: 'Факт',
data: [
{
x: 'Тонн за месяц',
y: 0,
goals: [
{
name: 'План',
value: 250000,
strokeHeight: 15,
strokeColor: 'var(--danger)'
}
]
}
]
}
],
noData: 'Загрузка...',
title: {
floating: true,
offsetX: -10,
offsetY: 5,
text: 'Пераработанное сырье',
style: {
fontSize: '14px'
}
},
subtitle: {
floating: true,
align: 'right',
offsetY: 3,
text: '',
style: {
fontSize: '15px'
}
},
tooltip: {
y: {
formatter: function (val) {
return val + ' т.'
}
},
enabled: true,
shared: true,
intersect: false
},
xaxis: {
categories: ['Тонн за месяц']
},
yaxis: {
max: 400000
}
}
const optionsDoubleProgress = {
chart: {
height: 70,
width: '100%',
type: 'bar',
stacked: false,
sparkline: {
enabled: true
}
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '50%',
colors: {
backgroundBarColors: ['#40475D']
}
}
},
dataLabels: {
enabled: true,
formatter: function (val, opts) {
if (val !== 0) {
const title = opts.config.series[opts.seriesIndex].name
return title + ' ' + val + '%'
} else {
return ''
}
},
style: {
colors: ['#fff'],
fontSize: '15px',
fontWeight: 'bold'
},
textAnchor: 'middle',
offsetX: 35
},
colors,
stroke: {
width: 0
},
series: [{
name: 'Концентрат',
data: [0]
}, {
name: 'Отсев',
data: [0]
}],
noData: 'Загрузка...',
title: {
floating: true,
offsetX: -10,
offsetY: 5,
text: 'Выход отсева и концентрата',
style: {
fontSize: '14px'
}
},
subtitle: {
floating: true,
align: 'right',
offsetY: 3,
text: '',
style: {
fontSize: '15px'
}
},
tooltip: {
enabled: true,
shared: true,
intersect: false,
y: {
formatter: function (val) {
return val + '%'
}
}
},
xaxis: {
categories: ['Выход отсева и концентрата за смену']
},
yaxis: {
max: 100
}
}
const GoalProgressChart = new ApexCharts(document.querySelector('#GoalProgress'), optionsFabricGoal)
await GoalProgressChart.render()
const DropoutAndConcentrateChart = new ApexCharts(
document.querySelector('#DropoutAndConcentrate'),
optionsDoubleProgress)
// Рендерится не сразу
const hoursBarChart = new ApexCharts(document.querySelector('#byHourScales'), hoursBarOptions)
await hoursBarChart.render()
hoursBarChart.updateOptions({
yaxis: {
labels: { ...boldLabel }
}
})
const dailyScalesChart = new ApexCharts(document.querySelector('#dailyScales'), dailyBarOptions)
await dailyScalesChart.render()
dailyScalesChart.updateOptions({
xaxis: {
labels: { ...boldLabel }
}
})
const monthlyScalesChart = new ApexCharts(document.querySelector('#monthlyScales'), monthlyBarOptions)
await monthlyScalesChart.render()
monthlyScalesChart.updateOptions({
xaxis: {
labels: { ...boldLabel }
}
})
const hourChartCircle1 = new ApexCharts(document.querySelector('#HourCircle_1'), hourOptionsCircle1)
await hourChartCircle1.render()
const hourChartCircle2 = new ApexCharts(document.querySelector('#HourCircle_2'), hourOptionsCircle2)
await hourChartCircle2.render()
const dailyDoubleChartCircle2 = new ApexCharts(document.querySelector('#dailyCircle'), doubleOptionsCircle)
await dailyDoubleChartCircle2.render()
const monthlyDoubleChartCircle2 = new ApexCharts(document.querySelector('#monthlyCircle'), doubleOptionsCircle)
await monthlyDoubleChartCircle2.render()
async function getChartsData () {
const response = await fetch('scales/')
return response.json()
}
function setChartsData (response) {
GoalProgressChart.updateOptions({
subtitle: {
text: response.plan.percent
},
yaxis: {
max: response.plan.goal + 100000
}
})
GoalProgressChart.updateSeries([
{
name: 'Факт',
data: [
{
x: 'Тонн за месяц',
y: response.plan.value,
goals: [
{
name: 'План',
value: response.plan.goal,
strokeHeight: 15,
strokeColor: 'var(--danger)'
}
]
}
]
}
])
if (response.concentrate_and_dropout !== false) {
DropoutAndConcentrateChart.render()
DropoutAndConcentrateChart.updateSeries([{
name: 'Концентрат',
data: [response.concentrate_and_dropout.concentrate]
}, {
name: 'Отсев',
data: [response.concentrate_and_dropout.dropout]
}])
} else {
const widgetDiv = document.querySelector('#DropoutAndConcentrate')
widgetDiv.classList.add('d-flex', 'justify-content-between', 'align-items-center', 'h-100')
widgetDiv.textContent = 'Для отображения виджета необходимо'
widgetDiv.insertAdjacentHTML('beforeend', '<button type="button" class="btn btn-primary btn-sm roboto" data-toggle="modal" data-target="#m_modal_3" id="launchModalBtn">Ввести данные</button>')
}
monthlyScalesChart.updateSeries([{
name: 'Месяц',
data: Object.values(response.monthly.scales)
}], true)
hoursBarChart.updateSeries([{
name: 'Текущая смена',
data: Object.values(response.average.current_work_shift)
}, {
name: 'Предыдущая смена',
data: Object.values(response.average.previous_work_shift)
}])
dailyScalesChart.updateSeries([{
name: 'Текущая смена',
data: Object.values(response.daily.current_work_shift)
}, {
name: 'Предыдущая смена',
data: Object.values(response.daily.previous_work_shift)
}], true)
for (const item of ['daily', 'monthly', 'average']) {
const latestDate = document.querySelector(`#${item}LatestDate`)
const dateObj = new Date(response[`${item}`].latest_date)
const padZero = (num) => num.toString().padStart(2, '0')
const day = padZero(dateObj.getDate())
const month = padZero(dateObj.getMonth() + 1)
const year = dateObj.getFullYear()
const hours = padZero(dateObj.getHours())
const minutes = padZero(dateObj.getMinutes())
const seconds = padZero(dateObj.getSeconds())
latestDate.textContent = `Данные от ${day}.${month}.${year} ${hours}:${minutes}:${seconds}`
}
hourChartCircle1.updateSeries(Object.values(response.average.percent_values.current_shift))
hourChartCircle2.updateSeries(Object.values(response.average.percent_values.previous_shift))
dailyDoubleChartCircle2.updateSeries(Object.values(response.daily.percent_values.current_shift))
monthlyDoubleChartCircle2.updateSeries(Object.values(response.monthly.percent_values))
}
async function buildCharts () {
const response = await getChartsData()
setChartsData(response)
}
await buildCharts()
setInterval(buildCharts, 5000)
})()
const kekInput = document.querySelector('#kekInput')
const breedInput = document.querySelector('#breedInput')
const submitBtn = document.querySelector('#submitBtn')
submitBtn.addEventListener('click', async (e) => {
const data = {
kek: kekInput.value,
breed: breedInput.value
}
const response = await fetch('scales/kek_and_breed/recieve', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'X-CSRFToken': window.getCookie('csrftoken')
},
body: JSON.stringify(data)
})
const responseJson = await response.json()
const kekAndBreedModalAlerts = document.querySelector('#kekAndBreedModalAlerts')
kekAndBreedModalAlerts.innerHTML = ''
const alert = document.createElement('div')
alert.classList.add('alert', 'roboto', 'bold')
alert.setAttribute('role', 'alert')
alert.textContent = `${responseJson.message}`
kekAndBreedModalAlerts.appendChild(alert)
if (responseJson.success) {
alert.classList.add('alert-success')
// Спрятать модальное окно
document.getElementById('m_modal_3').classList.remove('show')
document.querySelectorAll('.modal-backdrop').forEach(el => el.remove())
} else {
// Отобразить ошибку
alert.classList.add('alert-danger')
}
})