Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save almcarvalho/0655a45846c963fae2484973db3d06af to your computer and use it in GitHub Desktop.
Save almcarvalho/0655a45846c963fae2484973db3d06af to your computer and use it in GitHub Desktop.
import "./PoliceHelper.css";
import React, {useContext, useEffect, useRef, useState} from "react";
import img from "./../../../assets/images/PoliceHelperNovo.png"
import LabelAndInputHorizontal from "../../../themes/LabelAndInputHorizontal/LabelAndInputHorizontal";
import {AuthContext} from "../../../contexts/AuthContext";
import * as dataConstants from "../../../constants/data";
import { Row, Col, Checkbox } from 'antd';
import LoadingAction from "../../../themes/LoadingAction/LoadingAction";
import axios from "axios";
const listCrimes = dataConstants.listCrimes;
const removeAccentsAndLowerCase = dataConstants.removeAccentsAndLowerCase
const initialPoliceHelper = {
id: '',
idMeliante: '',
rgMeliante: '',
nomeMeliante: '',
local: '',
horario: '',
urlFoto: '',
crimes: [],
pena: 0,
multa: 0,
nomeDosPCs: [],
nomeDosPMs: [],
idEnvolvidos: '',
bail: 0,
}
const initErrorField = {
idMeliante: undefined,
rgMeliante: undefined,
nomeMeliante: undefined,
local: undefined,
horario: undefined,
urlFoto: undefined,
crimes: undefined,
pena: undefined,
multa: undefined,
nomeDosPCs: undefined,
nomeDosPMs: undefined,
idEnvolvidos: undefined,
bail: undefined
}
function PoliceHelper() {
const {
authInfo,
setDataPointA,
} = useContext(AuthContext)
const {
dataUser
} = authInfo;
const plainTextEl = useRef<HTMLInputElement | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [dataPoliceHelper, setDataPoliceHelper] = useState({...initialPoliceHelper})
const [error, setError] = useState<any>(null);
const [success, setSuccess] = useState(false);
const [errorField, setErrorField] = useState({...initErrorField});
const [keySearch, setKeySearch] = useState('');
const [listIndexChecked, setListIndexChecked] = useState<number[]>([])
const [listDataCrimes, setListDataCrimes] = useState([...listCrimes])
const [listDataCrimesIdFilter, setListDataCrimesIdFilter] = useState<(number | null)[]>([])
const [copy, setCopy] = useState(false)
const onResetForm = () => {
setDataPoliceHelper({...initialPoliceHelper});
setKeySearch('');
setListIndexChecked([]);
setSuccess(false)
setCopy(false)
setError(null)
}
useEffect(() => {
const listId:(number | null)[] = listDataCrimes.map((item, index) => {
if (item["CRIME DESCRIPTION"] && removeAccentsAndLowerCase(item["CRIME DESCRIPTION"]).indexOf(keySearch.toLowerCase())>-1) {
return index;
}
return null;
}).filter(item => item !== null)
setListDataCrimesIdFilter(listId)
}, [keySearch])
useEffect(() => {
let bail = 0;
let multa = 0;
let pena = 0;
let breakFor = false;
let breakForMulta = false;
let listKey:any[] = [];
let has50 = false;
listDataCrimes.forEach((item, index) => {
if (listIndexChecked.includes(index)) {
if (!breakFor) {
if (Number(item["BAIL"]) === 0) {
bail = 0
breakFor = true
} else {
bail += Number(item["BAIL"])
}
}
if (!breakForMulta) {
if (Number(item["FINE"]) === 0) {
// multa = 0
breakForMulta = true
} else {
multa += Number(item["FINE"])
}
}
let dataItem = item["CRIME DESCRIPTION"].toString().toLowerCase();
if (!listKey.includes(dataItem)) {
listKey.push(dataItem)
if (Number(item["TIME"]) === 50) {
has50 = true;
}
pena += Number(item["TIME"]);
}
}
})
setDataPoliceHelper(prev => {
return {
...prev,
bail: bail,
pena: pena > (has50 ? 50 : 30) ? (has50 ? 50 : 30) : pena,
multa: multa > 300000 ? 300000: multa,
}
})
}, [listIndexChecked])
const onChange = (e: React.FormEvent<HTMLInputElement>) => {
const name = e.currentTarget.name;
let newValue = e.currentTarget.value;
setSuccess(false)
if (name === "rgMeliante") {
newValue = newValue.toUpperCase()
}
if (name === "rgMeliante") {
if (newValue.length > 8) {
newValue = dataPoliceHelper.rgMeliante;
}
}
setDataPoliceHelper(prev => {
return {
...prev,
[name]: newValue
}
})
setErrorField(prev => {
return {
...prev,
[name]: null
}
})
setError(null)
}
const onChangeKeySearch = (e: React.FormEvent<HTMLInputElement>) => {
let newValue = e.currentTarget.value;
setKeySearch(newValue)
}
const onChangeCheckBox = (checked: boolean, index: number) => {
if (checked) {
setListIndexChecked(prev => [
...prev,
index
])
} else {
setListIndexChecked(prev => prev.filter(item => item !== index))
}
}
const onSubmitPoliceHelper = () => {
axios.get(`${process.env.REACT_APP_API_BASE_URL}/logged_discord`)
.then((response) => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
let dataErrorField = {};
if (dataPoliceHelper.idMeliante.toString().trim() === '') {
dataErrorField = {
...dataErrorField,
idMeliante: 'ID é obrigatório.'
}
}
if (!(dataPoliceHelper.rgMeliante !== "" && dataPoliceHelper.rgMeliante.trim().length === 8)) {
dataErrorField = {
...dataErrorField,
rgMeliante: 'RG Inválido. Ex: ABCD1238'
}
}
if (Number(dataPoliceHelper.pena) > 50) {
dataErrorField = {
...dataErrorField,
pena: 'o valor máximo é 50'
}
}
if (Number(dataPoliceHelper.multa) > 300000) {
dataErrorField = {
...dataErrorField,
multa: 'o valor máximo é 300000'
}
}
if (Object.keys(dataErrorField).length === 0) {
let crimes = listDataCrimes.filter((item, index) => listIndexChecked.includes(index)).map((item, index) => {
return item["CRIME DESCRIPTION"];
})
const data:any = {
idMeliante: Number(dataPoliceHelper.idMeliante),
rgMeliante: dataPoliceHelper.rgMeliante,
nomeMeliante: dataPoliceHelper.nomeMeliante,
crimes: crimes.join(', '),
local: dataPoliceHelper.local,
nomeDosPCs: dataPoliceHelper.nomeDosPCs.join(', '),
nomeDosPMs: dataPoliceHelper.nomeDosPMs.join(', '),
pena: Number(dataPoliceHelper.pena),
multa: Number(dataPoliceHelper.multa),
horario: dataPoliceHelper.horario,
idEnvolvidos: dataPoliceHelper.idEnvolvidos,
usuarioId: dataUser?.id,
urlFoto: dataPoliceHelper.urlFoto,
}
setIsLoading(true);
setError(null)
axios.post(`${process.env.REACT_APP_API_BASE_URL}/registrarapreensao`, data)
.then(res => {
if (res.status === 200) {
onResetForm();
setSuccess(true)
setIsLoading(false)
} else {
throw new Error();
}
})
.catch(err => {
setIsLoading(false)
setError(err.response?.data?.error ?? "erro" )
})
} else {
setErrorField(prev => {
return {
...prev,
...dataErrorField
}
})
setError("aconteceu algum erro ao tentar registrar")
}
}
let crimes = listDataCrimes.filter((item, index) => listIndexChecked.includes(index)).map((item, index) => {
return item["CRIME DESCRIPTION"];
})
return (
<div className="PoliceHelperWrapper">
{isLoading && <LoadingAction />}
<div className="PoliceHelperTitle">
Police Helper
</div>
<div className="PoliceHelperBody">
<div className="PoliceHelperForm">
<div className="PoliceHelperFormLeft">
<LabelAndInputHorizontal
label="PENA"
input={
<input
placeholder="35"
value={dataPoliceHelper.pena}
name="pena"
onChange={onChange}
type="number"
/>
}
validate={errorField.pena}
/>
<LabelAndInputHorizontal
label="MULTA"
input={
<input
placeholder="35030"
value={dataPoliceHelper.multa}
name="multa"
onChange={onChange}
type="number"
/>
}
validate={errorField.multa}
/>
<LabelAndInputHorizontal
label="FIANÇA"
input={
<input
placeholder="0"
value={dataPoliceHelper.bail}
name="bail"
onChange={onChange}
type="number"
/>
}
validate={errorField.bail}
/>
<LabelAndInputHorizontal
label="ID"
input={
<input
placeholder=""
value={dataPoliceHelper.idMeliante}
name="idMeliante"
onChange={onChange}
type="number"
/>
}
validate={errorField.idMeliante}
/>
<LabelAndInputHorizontal
label="RG"
input={
<input
placeholder=""
value={dataPoliceHelper.rgMeliante}
name="rgMeliante"
onChange={onChange}
type="text"
/>
}
validate={errorField.rgMeliante}
/>
<LabelAndInputHorizontal
label="Picture Url"
input={
<input
placeholder="Lightshot Link"
value={dataPoliceHelper.urlFoto}
name="urlFoto"
type="text"
/>
}
/>
<div className="PoliceHelperFormBtn" style={{
backgroundColor: '#3BE7FF'
}} onClick={() => {
if (plainTextEl.current ) {
navigator.clipboard.writeText(plainTextEl.current?.innerText)
setCopy(true)
}
}}>
COPIAR TEXTO
</div>
<div className="PoliceHelperFormBtn" style={{
backgroundColor: '#2871F6'
}} onClick={() => {
onSubmitPoliceHelper()
}}>
REGISTRAR
</div>
<div className="PoliceHelperFormBtn" style={{
backgroundColor: '#DB8C28'
}} onClick={() => {
onResetForm();
}}>
RESET
</div>
{
success && <div className="PoliceHelperSuccess">
Apreensão Registrada com Sucesso
</div>
}
{
error && <div className="PoliceHelperError">
Error: {error}
</div>
}
{
copy && <div className="PoliceHelperCopy">
Texto copiado
</div>
}
</div>
<div className="PoliceHelperFormRight">
<div className="PoliceHelperFormPlantext" ref={plainTextEl}>
Nome dos PMs: {dataPoliceHelper.nomeDosPMs}<br />
Nome dos PCs: {dataPoliceHelper.nomeDosPCs}<br />
ID: {dataPoliceHelper.idMeliante}<br />
RG: {dataPoliceHelper.rgMeliante}<br />
Crimes: {crimes.join(', ')}<br />
Pena: {dataPoliceHelper.pena}<br />
Multa: {dataPoliceHelper.multa}<br />
Passaporte dos Envolvidos:<br />
</div>
</div>
</div>
<div className="PoliceHelperCrimesBottom">
<div className="PoliceHelperCrimesLabel">
CRIMES
</div>
<div className="PoliceHelperFilterCrimes">
<div className="PoliceHelperInputSearch">
<LabelAndInputHorizontal
label="Buscar"
input={
<input
placeholder=""
value={keySearch}
name="keySearch"
onChange={onChangeKeySearch}
type="text"
/>
}
/>
</div>
<div className="PoliceHelperCrimesView">
<Row>
{listDataCrimes.map((item, index) => {
if (listDataCrimesIdFilter.includes(index)) {
return (
<Col xs={24} md={12} lg={8} xl={6} style={{
padding: '10px 5px'
}}>
<div className="PoliceHelperCrimesViewItem" onClick={() => {
onChangeCheckBox(listIndexChecked.includes(index) ? false : true, index)
}}>
<input onChange={(event) => {
onChangeCheckBox(event.target.checked, index)
}} type="checkbox" name="checkbox" checked={listIndexChecked.includes(index)} />
<div className="labelCrime"title={`ART - ${item['ARTICLE']} OBS. ${item['NOTE']} TEMPO: ${item['TIME']} MESES. MULTA: ${item['FINE']} MIL. - FIANÇA:${item['BAIL']}`}>{item["CRIME DESCRIPTION"]}</div>
</div>
</Col>
)
}
return (<></>)
})}
</Row>
</div>
</div>
</div>
</div>
</div>
)
}
export default PoliceHelper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment