Compare commits

..

1 Commits

7 changed files with 252 additions and 346 deletions
-121
View File
@@ -1,121 +0,0 @@
@import url('./../variables.css');
/* #modal-window__background{
position: fixed;
display: block;
width: 100%;
height: 100%;
background: #6a6a6ab5;
top: 0;
z-index: 99;
} */
.entity-hist-container{
position: fixed;
width: 50%;
top: 10%;
left: 25%;
z-index: 100;
background: white;
border-radius: 10px;
box-shadow: 0px 0px 15px 1px #9b9999;
&>.hist__header-block{
display: flex;
align-items: center;
justify-content: space-between;
background: var(--color_graphite_main);
min-height: 7%;
height: auto;
border-radius: 10px;
color: white;
padding: 10px;
&>.hist__header__buttons{
&>.header__buttons__close{
transform: rotate(45deg);
font-size: 2rem;
color: var(--color_ruby_main);
cursor: pointer;
}
}
}
&>.hist__content-block{
overflow-y: scroll;
padding: 10px;
max-height: 500px;
&>.hist-container__date-block{
display: flex;
&>.date-block__date{
flex-basis: 15%;
&>div{
position: sticky;
top: 0px;
padding: 3px;
background: var(--color_purple_main);
border-radius: 5px 0 0 5px;
color: white;
}
}
&>.date-block__changes{
flex-basis: 85%;
border-left: 2px solid black;
padding: 0 10px;
&>.changes__action-block{
& .action-block__action-name{
padding: 3px;
border-radius: 3px;
font-size: 1.2rem;
/* border-bottom: 3px solid var(--color_purple_main); */
background: color-mix(in srgb, var(--color_purple_main) 20%, transparent);
box-shadow: 0px 2px 3px 0px #c0bdd3;
}
&:last-child{
margin-bottom: 30px;
}
&>.changes__date-time-block{
display: flex;
justify-content: space-between;
margin: 5px 0px 10px 0px;
color: rgb(173 173 173);
}
&>.changes__details{
margin-bottom: 15px;
& .changes__details__el{
display: flex;
justify-content: space-between;
margin-bottom: 10px;
&>.changes__details__el__prop-name{
flex-basis: 30%;
font-weight: 500;
}
&>.changes__details__el__prop-val{
flex-basis: 70%;
background: #91919121;
border-radius: 5px;
padding: 5px;
}
}
}
}
}
}
}
}
+173
View File
@@ -0,0 +1,173 @@
@import url('./../variables.css');
#preloader_container {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.3);
z-index: 900;
backdrop-filter: blur(5px);
&.hide {
display: none;
}
&>#preloader{
width: 200px;
height: 200px;
background: none;
position: relative;
top: 30%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
&>.circle {
position: absolute;
border-radius: 50%;
box-sizing: border-box;
border: 10px solid transparent;
}
&>#circle_one {
width: 80%;
height: 80%;
border-top-width: 10px;
left: 5%;
top: 5%;
animation: roll_one 4.5s;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
animation-timing-function: linear;
&.preloader-emerald-circle{
border-top-color: var(--color_emerald_light);
}
&.preloader-ruby-circle{
border-top-color: var(--color_ruby_main);
}
&.preloader-graphite-circle{
border-top-color: var(--color_graphite_main);
}
}
&>#circle_two {
width: 70%;
height: 70%;
left: 10%;
top: 10%;
border-right-width: 10px;
animation: roll_two 2.5s;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
animation-timing-function: linear;
&.preloader-emerald-circle{
border-right-color: var(--color_emerald_light);
}
&.preloader-ruby-circle{
border-right-color: var(--color_ruby_main);
}
&.preloader-graphite-circle{
border-right-color: var(--color_graphite_main);
}
}
&>#circle_three {
width: 60%;
height: 60%;
left: 15%;
top: 15%;
border-bottom-width: 10px;
animation: roll_three 3s;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
animation-timing-function: linear;
&.preloader-emerald-circle{
border-bottom-color: var(--color_emerald_light);
}
&.preloader-ruby-circle{
border-bottom-color: var(--color_ruby_main);
}
&.preloader-graphite-circle{
border-bottom-color: var(--color_graphite_main);
}
}
&>#preloader_text {
width: 150%;
left: -25%;
font-size: 1.5rem;
position: absolute;
bottom: -50px;
text-align: center;
color: white;
}
&>#logo {
position: absolute;
background: none;
width: 40%;
height: 40%;
top: 25%;
left: 25%;
&>.logo_square {
position: absolute;
box-sizing: border-box;
}
&>#left-top {
width: 60%;
height: 70%;
top: 15%;
left: 20%;
border-left: 7px solid white;
border-top: 7px solid white;
border-top-left-radius: 45%;
}
&>#right-bottom {
width: 40%;
height: 50%;
top: 15%;
left: 40%;
border-right: 7px solid white;
border-bottom: 7px solid white;
border-bottom-right-radius: 45%;
border-bottom-left-radius: 10%;
}
}
}
}
@keyframes roll_one {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes roll_two {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(-360deg);
}
}
@keyframes roll_three {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(720deg);
}
}
@@ -1,120 +0,0 @@
import React, { useEffect, useMemo, useState, useContext } from "react";
import { createPortal } from "react-dom";
import './../../../css/components/entityHistory.css';
import { HistoryContext } from "../../contexts/HistoryContext";
//Тип с параметрами сущности, история по которой будет выводиться
export type EntityHistoryProps = {
changeAction: string, //Совершенное действие: создание, удаление, редактирование, архивирование и т.д.
changeAuthor: string, //Автор изменения: логин, сервисная УЗ
changeDate: Date //Объект даты изменения. В объекте будет либо время (тогда показываем), либо время будет отсутствовать (тогда не показываем) //что будем передавать? объект new Date или библиотечный объект для работы с датами?
changeTime?: string //Время изменений. Передавать не нужно, на этабе сборки компонента будет формироваться на основе пропса changeDate
// changeDetails?: HistoryEntityElDetails[] //Массив объектов с деталями изменений формата: изменяемое свойство(поле, например) - значение изменяемого свойства
changeDetails?: Record<string, string> //Массив объектов с деталями изменений формата: изменяемое свойство(поле, например) - значение изменяемого свойства
};
//Тип с деталями изменений
// type HistoryEntityElDetails = {
// propName: string, //Имя измененного свойства
// propValue: string //Значение измененного свойства
// }
//Компонент отображения истории изменений сущности
export default function EntityHistory ()
{
//ГАВРИЛОВ
//ИДЕНТИЧНЫЙ СПРАВОЧНИК УКАЗАН НА СТОРОНЕ ЛАРАВЕЛЬ APP/ENUMS/LOGBUSINESSEVENTS. ЕСТЬ ВОЗМОЖНОСТЬ ОБЪЕДИНИТЬ ИХ?
const HistoryActions = {
create: 'создание',
edit: 'редактирование',
archive: 'архивация',
restore: 'восстановление',
delete: 'удаление',
cancel: 'отмена',
}
const historyContext = useContext(HistoryContext);
//Перестраиваем объект с изменениями, группируя их по датам
const groupDataByDate = useMemo( () => {
let changesByDate = {},
historyContent = historyContext.content.length ? historyContext.content : []
//Сортируем все изменения от большего к меньшему по дате и времени
//ГАВРИЛОВ. или нужно отсортировать от меньшего к большему? мы хотим сверху самые актуальные данные а ниже менее актуальные или наоборот?
//ПРОВЕРИТЬ СОРТИРУЕТСЯ ЛИ ПО ДАТАМ
historyContent.sort( (a, b) => {return b.changeDate - a.changeDate} )
//console.log(historyContext)
historyContent.forEach( (changeEl: EntityHistoryProps) => {
let dateToString = changeEl.changeDate.toLocaleString('ru-RU').split(',')[0];
if ( !(dateToString in changesByDate) ) {
changesByDate[dateToString] = [];
}
changesByDate[dateToString].push(changeEl);
});
return changesByDate;
}, [historyContext.content]);
//Сокрытие блока показа истории
function hideHistoryBlock(){
historyContext.hideHistory()
}
return (
historyContext.content && historyContext.visible ?
createPortal(
<div>
<div className="entity-hist-container">
<div className="hist__header-block">
<div className="hist__header__title">
<h3>{ historyContext.headerText.length ? historyContext.headerText : `История изменений запроса ${historyContext.entityId}` }</h3>
</div>
<div className="hist__header__buttons" onClick={hideHistoryBlock}>
<i className="fa fa-plus header__buttons__close"></i>
</div>
</div>
<div className="hist__content-block">
{Object.entries(groupDataByDate).map( (dateChanges, dateIndex) =>
<div key={dateIndex} className="hist-container__date-block">
<div className="date-block__date">
<div>{ dateChanges[0] }</div>
</div>
<div className="date-block__changes">
{ dateChanges[1].map( (changeEl: EntityHistoryProps, elIndex: number) =>
<div className="changes__action-block" key={ elIndex }>
<div className="action-block__action-name">
{ HistoryActions[changeEl.changeAction] }
</div>
<div className="changes__date-time-block">
<div>
{ changeEl.changeAuthor }
</div>
<div>
{ changeEl.changeTime }
</div>
</div>
<div className="changes__details">
{Object.entries(changeEl.changeDetails).map( (detail, detailIndex) =>
<div className="changes__details__el" key={ detailIndex }>
<div className="changes__details__el__prop-name">
{ (historyContext.dataFields && historyContext.dataFields[detail[0]]) ? historyContext.dataFields[detail[0]] : detail[0] }
</div>
<div className="changes__details__el__prop-val">
{ detail[1] }
</div>
</div>
)}
</div>
</div>
)}
</div>
</div>
)}
</div>
</div>
</div>,
document.body
)
: ''
)
}
@@ -0,0 +1,39 @@
import "./../../../css/components/preloader.css";
import React from "react";
export default function Preloader ( props: {visible: boolean, text?: string | null}) {
const {text = 'загрузка'} = props;
let preloaderColorArray: string[] = ['preloader-ruby-circle', 'preloader-emerald-circle', 'preloader-graphite-circle'],
//Код ниже реализует возможность присваивать каждую перезагрузку разные классы с цветом полос
//Рандомное число, по которому получим первый класс
firstColorIndex: number = Math.floor(Math.random() * 3),
firstCircleClass: typeof preloaderColorArray[number] = preloaderColorArray[firstColorIndex],
secondCircleClass: typeof preloaderColorArray[number],
thirdCircleClass: typeof preloaderColorArray[number];
//Удалим уже используемый класс цвета из массива
preloaderColorArray.splice(firstColorIndex, 1);
//Оставшиеся 2 класса распределеяем в зависимости от проостой проверки четности/нечетности
if (Math.floor(Math.random() * 2) % 2 === 0) {
secondCircleClass = preloaderColorArray[0];
thirdCircleClass = preloaderColorArray[1];
} else {
secondCircleClass = preloaderColorArray[1];
thirdCircleClass = preloaderColorArray[0];
}
return (
props.visible ?
<div id='preloader_container'>
<div id='preloader'>
<div className={'circle ' + firstCircleClass} id='circle_one'></div>
<div className={'circle ' + secondCircleClass} id='circle_two'></div>
<div className={'circle ' + thirdCircleClass} id='circle_three'></div>
<div id='logo'>
<div className='logo_square' id='right-bottom'></div>
<div className='logo_square' id='left-top'></div>
</div>
<div id='preloader_text'>{ text }</div>
</div>
</div>
: null
)
}
-97
View File
@@ -1,97 +0,0 @@
import React, { createContext, useState, useContext } from "react";
import EntityHistory, { EntityHistoryProps } from "../components/entityHistory/EntityHistory";
import api from "../api";
import { PreloaderContext } from "./PreloaderContext";
//Тип с пропсами для взаимодействия с контекстом
interface HistoryContextType {
visible: boolean, //Пропс видимости компонента
historyDataFields: HistoryDataFields, //Объект с названиями полей, по которым было совершено изменение. В БД они будут храниться, скорее всего, на латинице, на фронте их надо расшифровать
hideHistory: () => void, //Колбек для сокрытия блока с историей
content: Record<string, string> | null, //Контент для отображения истории
headerText: string, //Текст в заголовке окна с историей
entityId: number, //Уникальный идентификатор сущности, по которой показываем историю (заявки, запрос и т.д.)
showHistory: (entityId: number, content: EntityHistoryProps[], windowHeader?: string) => void, //Колбек для вызова окна с историей
getHistoryFromMagic: (appname: string, subjectId: string | number, historyDataFields: HistoryDataFields, windowHeader?: string) => void //Метод получения истории из приложения Magic
}
type HistoryDataFields = Record<string, string>;
export const HistoryContext = createContext<HistoryContextType | null>(null);
export const HistoryProvider = ( {children} ) => {
const [historyVisible, setHistoryVisible] = useState<boolean>(false);
const [historyContent, setHistoryContent] = useState<EntityHistoryProps[] | []>( [] );
const [historyWindowHeader, setHistoryWindowHeader] = useState<string>('');
const [historyEntityId, setHistoryEntityId] = useState<number>();
const [historyDataFields, setHistoryDataFields] = useState<HistoryDataFields | null>( null );
/**
* Сокрытие окна с историей
*/
function hideHistoryBlock() {
setHistoryVisible(false);
setHistoryWindowHeader('');
setHistoryContent( [] );
setHistoryEntityId(0);
}
const preloaderContext = useContext(PreloaderContext);
//ГАВРИЛОВ. ПРАВИЛЬНО ЛИ В КОНТЕКСТЕ РЕАЛИЗОВЫВАТЬ ЛОГИКУ ФУНКЦИОНАЛА? ИЛИ ПРАВИЛЬНЕЕ ЕЕ РАЗМЕСТИТЬ В ФАЙЛЕ КОМПОНЕНТА?
async function getHistoryFromMagic(appName: string, subjectId: number | string, historyDataFields: HistoryDataFields, windowHeader?: string){
preloaderContext.setPreloaderVisible(true)
const appHistory = await api.get(`${appName}/history/${subjectId}`).then(history => history.data.data);
// console.log(appHistory)
if (appHistory) {
appHistory.forEach( changeData => {
changeData.changeDetails = JSON.parse(changeData.changeDetails)
});
//appHistory.changeDetails = JSON.parse(appHistory.changeDetails)
}
//ГАВРИЛОВ
//ПРОВЕРКА НА НАЛИЧИЕ НУЖНЫХ СВОЙСТВ. ЧТОБЫ ОБЪЕКТ СООТВЕТСТВОВАЛ ТИПУ
//УБРАТЬ CHANGE. ПРОСТО AUTHOR,DETAILS и так далее
// console.log(appHistory)
showHistoryBlock(subjectId, appHistory, historyDataFields, windowHeader)
// return appHistory;
}
/**
* Показываем историю
* @param entityId идентификатор бизнес-сущности
* @param content контент для отображения
* @param windowHeader заголовок для окна с историей
*/
//ГАВРИЛОВ. сделать пропс historyDataFields необязательным (пустой объект по умолчанию), так как details могут не передаваться, тогда и словарь не нужен (В ТОМ ЧИСЛЕ И В МЕТОДЕ getHistoryFromMagic). сделай интерфейс для аргументов идентичным
function showHistoryBlock(subjectId: number | string, content: EntityHistoryProps[], historyDataFields: HistoryDataFields, windowHeader?: string){
preloaderContext.setPreloaderVisible(true)
setHistoryVisible(true);
setHistoryEntityId(subjectId);
setHistoryContent(content);
windowHeader ? setHistoryWindowHeader(windowHeader) : true;
historyDataFields ? setHistoryDataFields(historyDataFields) : true;
preloaderContext.setPreloaderVisible(false)
}
const value = {
getHistoryFromMagic: getHistoryFromMagic,
showHistory: showHistoryBlock,
hideHistory: hideHistoryBlock,
visible: historyVisible,
content: historyContent,
headerText: historyWindowHeader,
entityId: historyEntityId,
dataFields: historyDataFields
};
return <HistoryContext.Provider value={value}>
{children}
<EntityHistory/>
</HistoryContext.Provider>
}
@@ -0,0 +1,40 @@
import React, { createContext, useState } from "react";
import Preloader from "../components/preloader/Preloader";
interface PreloaderProps{
setPreloaderVisible: (preloaderVisible: boolean) => void;
setPreloaderText: (preloaderText: string) => void;
}
export const PreloaderContext = createContext<PreloaderProps>({
setPreloaderVisible: () => {},
setPreloaderText: () => {},
});
export function PreloaderProvider({ children }){
const [visible, setVisible] = useState<boolean>(true);
const [text, setText] = useState<string>('Страница загружается');
function setPreloaderVisible(preloaderVisible: boolean){
setVisible(preloaderVisible);
}
function setPreloaderText(preloaderText: string){
setText(preloaderText);
}
let value = {
setPreloaderVisible: setPreloaderVisible,
setPreloaderText: setPreloaderText
}
return (
<PreloaderContext.Provider value={value}>
<Preloader
visible={visible}
text={text}
/>
{children}
</PreloaderContext.Provider>
)
}
-8
View File
@@ -1,8 +0,0 @@
<?php
use Illuminate\Support\Facades\Route;
use \App\Http\Controllers;
//Получение истории по сущности приложения
Route::get('{app_name}/history/{subject_id}', [Controllers\AppHistoryController::class, 'getAppHistory']);