Skip to content

Commit

Permalink
Merge pull request #610 from 5sControl/609-in-orders-view-there-is-no…
Browse files Browse the repository at this point in the history
…-sorting-when-selecting-assets

609 in orders view there is no sorting when selecting assets
  • Loading branch information
pkostukevich authored Aug 26, 2024
2 parents 03d62dd + d0d7c1e commit 31f0f40
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 119 deletions.
90 changes: 17 additions & 73 deletions src/pages/OrdersViewD3/OrdersViewD3.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ import { useAppSelector } from '../../store/hooks';
import moment from 'moment';
import {
getFiltrationData,
getStatusData,
getOrderViewOperations,
patchFiltrationData,
patchStatusData,
} from '../../api/orderView';
import { getData } from '../../api/reportsRequest';
import { useCookies } from 'react-cookie';
import { getSelectedZone } from '../../api/cameraRequest';
import { Modal } from '../../components/modal';
import { Cross } from '../../assets/svg/SVGcomponent';
import { Button } from '../../components/button';
import { Checkbox } from '../../components/checkbox';
import { SelectConnection } from './components/selectConnection';
import { SelectParam } from './components/selectParam';

export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
const { filterDateData } = useAppSelector(selectOrdersList);
Expand All @@ -32,7 +30,8 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
const [cookies] = useCookies(['token']);
const [workPlaceList, setWorkPlaceList] = useState([]);
const [changeConnectionHandler, setChangeConnectionHandler] = useState(false);
// const [defaultBaseType, setDefaultBaseType] = useState('');
const [zoomParam, setZoomParam] = useState(1);
const [openZoomModal, setOpenZoomModal] = useState(false);

const changeHandler = (index) => {
const workplaces = workPlaceList;
Expand All @@ -53,13 +52,6 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
setWorkPlaceList([...workplaces]);
};

// const changeSelectType = (type) => {
// patchStatusData(window.location.hostname, cookies.token, { type: type }).then((response) => {
// setDefaultBaseType(type);
// setIsOpenFilter(false);
// });
// };

const submitHandler = () => {
patchFiltrationData(window.location.hostname, cookies.token, workPlaceList)
.then((response) => {
Expand All @@ -73,13 +65,7 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
setEndDate(moment(filterDateData.to).format('YYYY-MM-DD'));
}, [filterDateData]);

// console.log(data);

useEffect(() => {
// getStatusData(window.location.hostname, cookies.token).then((response) => {
// setDefaultBaseType(response.data.type);
// });

getFiltrationData(window.location.hostname, cookies.token)
.then((res) => {
const response = res.data;
Expand All @@ -100,59 +86,8 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
endDate
);
const dataToD3 = response.data;
const dates = [];
const currentDate = moment(startDate);
while (currentDate.isSameOrBefore(endDate)) {
dates.push(currentDate.format('YYYY-MM-DD'));
currentDate.add(1, 'day');
}

// const dataPromises = dates.map((date) =>
// getData(
// window.location.hostname,
// cookies.token,
// date,
// '06:00:00',
// '20:00:00',
// 'machine_control'
// )
// );
const dataPromises = [];

const responses = await Promise.all(dataPromises);
const data = responses.flatMap((response) =>
response.data
.filter((e) => e.extra?.zoneId)
.map((el) => ({
id: el.extra?.zoneId,
zoneId: el.extra?.zoneId,
zoneName: el.extra.zoneName,
sTime: el.start_tracking,
eTime: el.stop_tracking,
camera: el.camera?.id,
cameraName: el.camera?.name,
algorithm: el.algorithm?.name,
}))
);

const grouped = data.reduce((acc, obj) => {
const zoneName = obj.zoneName.trim();
if (acc[zoneName]) {
acc[zoneName].push(obj);
} else {
acc[zoneName] = [obj];
}
return acc;
}, {});

const answer = Object.entries(grouped).map(([zoneName, zoneData]) => ({
inverse: true,
oprName: zoneName,
oprs: zoneData,
zoneId: zoneData[0].zoneId,
}));

const newDataPromises = answer.map(async (zone) => {
const newDataPromises = dataToD3.map(async (zone) => {
try {
const res = await getSelectedZone(
window.location.hostname,
Expand Down Expand Up @@ -205,8 +140,7 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
};
} else {
console.error(error);
// Обработка других ошибок
throw error; // Перебросить ошибку для дальнейшей обработки
throw error;
}
}
});
Expand All @@ -223,6 +157,10 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
}
}, [endDate, startDate, isOpenFilter]);

const handleZoomParamChange = (value) => {
setZoomParam(parseInt(value));
};

return (
<>
{filterDateData && endDate && startDate && (
Expand All @@ -241,6 +179,12 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
selectOrder={selectOrder}
preloader={preloader}
machineData={machineData}
zoomParam={zoomParam}
/>
<SelectParam
options={['1x', '2x', '4x', '8x', '16x']}
selectedValue={`${zoomParam}x`}
onChange={handleZoomParamChange}
/>
</div>
)}
Expand All @@ -263,8 +207,8 @@ export const TimelineComponent = ({ setIsOpenFilter, isOpenFilter }) => {
<li key={index}>
<Checkbox
id={index}
name={`${place.name}`}
label={`${place.name}`}
name={place.name}
label={place.name}
isChecked={place.is_active}
onChange={() => changeHandler(index)}
/>
Expand Down
84 changes: 48 additions & 36 deletions src/pages/OrdersViewD3/components/VerticalTimeline.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@ function getDuration(milli) {
return days * size;
}

const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, machineData }) => {
const VerticalTimeline = ({
data,
minDate,
maxDate,
selectOrder,
preloader,
machineData,
zoomParam,
}) => {
const [update, setUpdate] = useState(data);
const [operationOV, setOperationOV] = useState(false);
const days = moment(maxDate).diff(minDate, 'days');
Expand All @@ -39,33 +47,34 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach

useEffect(() => {
if (data.length > 0 || machineData.length > 0) {
let first =
data.length > 0
? data.filter(
(order) => order.oprs && JSON.stringify(order.oprs).includes(`"${selectOrder}"`)
)
: [];
let end =
data.length > 0
? data.filter(
(order) => order.oprs && !JSON.stringify(order.oprs).includes(`"${selectOrder}"`)
)
: [];
machineData.forEach((machineItem) => {
if (first.some((item) => item.oprTypeID === machineItem.oprTypeID)) {
first.unshift(machineItem);
} else {
end.push(machineItem);
}
});
machineData = machineData.filter((machineItem) => {
const foundInFirst = first.some((item) => item.oprTypeID === machineItem.oprTypeID);
const foundInEnd = end.some((item) => item.oprTypeID === machineItem.oprTypeID);
return !foundInFirst && !foundInEnd;
});
first = first.sort((a, b) => b.oprTypeID - a.oprTypeID);
end = end.sort((a, b) => b.oprTypeID - a.oprTypeID);
setUpdate([...first, ...end].sort((a, b) => (a.oprName > b.oprName ? 1 : -1)));
// let first =
// data.length > 0
// ? data.filter(
// (order) => order.oprs && JSON.stringify(order.oprs).includes(`"${selectOrder}"`)
// )
// : [];
// let end =
// data.length > 0
// ? data.filter(
// (order) => order.oprs && !JSON.stringify(order.oprs).includes(`"${selectOrder}"`)
// )
// : [];
// machineData.forEach((machineItem) => {
// if (first.some((item) => item.oprTypeID === machineItem.oprTypeID)) {
// first.unshift(machineItem);
// } else {
// end.push(machineItem);
// }
// });
// machineData = machineData.filter((machineItem) => {
// const foundInFirst = first.some((item) => item.oprTypeID === machineItem.oprTypeID);
// const foundInEnd = end.some((item) => item.oprTypeID === machineItem.oprTypeID);
// return !foundInFirst && !foundInEnd;
// });
// first = first.sort((a, b) => b.oprTypeID - a.oprTypeID);
// end = end.sort((a, b) => b.oprTypeID - a.oprTypeID);
// setUpdate([...first, ...end].sort((a, b) => (a.oprName > b.oprName ? 1 : -1)));
setUpdate(data);
} else {
setUpdate([]);
}
Expand Down Expand Up @@ -134,7 +143,8 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
useEffect(() => {
if (timelineRef.current && update.length > 0 && !preloader) {
const margin = { top: 10, right: 0, bottom: 0, left: 0 };
const height = getDuration(maxDate - minDate);
const proportion = 1 - Math.abs((days * 10) / ((days + 1) * 24 - 10));
const height = getDuration(maxDate - minDate) * proportion * zoomParam + (days + 1) * 18;
const width = update.length * fieldWidth;

const svg = d3
Expand Down Expand Up @@ -189,7 +199,7 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
.attr('height', 19)
.attr('fill', '#f5f5f5')
.attr('transform', (d, i) => {
return `translate(0, ${(ind + 1) * (400 * proportion) + ind * 18} )`;
return `translate(0, ${(ind + 1) * (400 * proportion * zoomParam) + ind * 18} )`;
})
.attr('display', days > 0 ? 'block' : 'none');
});
Expand Down Expand Up @@ -222,7 +232,6 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
.attr('opacity', selectOrder.length === 0 || d.orId === selectOrder ? 1 : 0.4)
.attr('fill', '#87BC45');
});

bars
.append('rect')
.attr('x', index * fieldWidth + 35)
Expand All @@ -231,7 +240,8 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
.attr('height', (d) => {
return y(parseDate(new Date(d.eTime), d)) - y(parseDate(new Date(d.sTime), d)) < 0
? 0
: y(parseDate(new Date(d.eTime), d)) - y(parseDate(new Date(d.sTime), d));
: (y(parseDate(new Date(d.eTime), d)) - y(parseDate(new Date(d.sTime), d))) *
zoomParam;
})
.attr('fill', '#87BC45')
.attr('opacity', (d) => (selectOrder.length === 0 || d.orId === selectOrder ? 1 : 0.4))
Expand Down Expand Up @@ -268,8 +278,8 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
style={{
position: 'absolute',
top: '10px',
left: `${fieldWidth * index + 30}px`,
width: `${fieldWidth - 60}px`,
left: `${fieldWidth * index + 10}px`,
width: `${fieldWidth - 20}px`,
transform: `translateX(${position * fieldWidth}px)`,
color: `${element.inverse ? '#666666' : '#26272B'}`,
}}
Expand Down Expand Up @@ -312,7 +322,9 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
ref={timelineRef}
style={{
width: `${update.length * fieldWidth}px`,
height: `${getDuration(maxDate - minDate) * proportion + (days + 1) * 20}px`,
height: `${
(getDuration(maxDate - minDate) * proportion + (days + 1) * 20) * zoomParam
}px`,
transform: `translateX(${position * fieldWidth}px)`,
}}
></div>
Expand All @@ -327,7 +339,7 @@ const VerticalTimeline = ({ data, minDate, maxDate, selectOrder, preloader, mach
</div>
{!preloader && update.length > 0 && update.length > 0 && (
<div className={styles.datetime}>
<Timeline minDate={minDate} maxDate={maxDate} />
<Timeline minDate={minDate} maxDate={maxDate} zoomParam={zoomParam} />
</div>
)}
</div>
Expand Down
5 changes: 2 additions & 3 deletions src/pages/OrdersViewD3/components/ordersList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,8 @@ export const OrdersList = ({ setSelectOrder, selectOrder, startDate, endDate, re
String(item.orId).toLowerCase().includes(searchText.toLowerCase()) && (
<div
key={index}
className={`${styles.orders__item} ${
selectOrder === item.orId ? styles.select : ''
}`}
className={`${styles.orders__item}
${selectOrder === item.orId ? styles.select : ''}`}
onClick={() => setSelectOrder(item.orId)}
>
{`№${item.orId}`}
Expand Down
25 changes: 19 additions & 6 deletions src/pages/OrdersViewD3/components/scale.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,29 @@ import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';
import moment from 'moment';

const Timeline = ({ minDate, maxDate }) => {
const Timeline = ({ minDate, maxDate, zoomParam }) => {
const svgRef = useRef(null);

function getDuration(milli) {
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
let size = days > 1 ? 400 : window.innerHeight - 190;
let size = days > 1 ? 400 : window.innerHeight - 188;
return days * size;
}

function calcTimeInterval(d3) {
switch (zoomParam) {
case 1:
return d3.timeHour.every(1);
case 2:
return d3.timeMinute.every(30);
case 4:
return d3.timeMinute.every(10);
case 8:
case 16:
return d3.timeMinute.every(5);
}
}
const days = moment(maxDate).diff(minDate, 'days');
const proportion = 1 - Math.abs((days * 10) / ((days + 1) * 24 - 10));
useEffect(() => {
Expand All @@ -25,7 +38,7 @@ const Timeline = ({ minDate, maxDate }) => {
// Определение размеров графика
const margin = { top: 10, right: 20, bottom: 0, left: 60 };
const width = 100 - margin.left - margin.right;
const height = getDuration(maxDate - minDate) * proportion;
const height = getDuration(maxDate - minDate) * proportion * zoomParam;
// Создание шкалы времени для оси Y - первый диапазон
const parseTime = d3.timeParse('%Y-%m-%dT%H:%M:%S');

Expand All @@ -45,9 +58,9 @@ const Timeline = ({ minDate, maxDate }) => {
// Создание оси Y для первого диапазона
const yAxis1 = d3
.axisRight(yScale1)
.ticks(d3.timeHour.every(1))
.ticks(calcTimeInterval(d3))
.tickFormat((date, index) => {
if (index === 0 || index === 14) {
if (index === 0) {
return d3.timeFormat('%d.%m, %H:%M')(date);
} else {
return d3.timeFormat('%H:%M')(date);
Expand Down
Loading

0 comments on commit 31f0f40

Please sign in to comment.