migrar creacion del reporte semanal al backend

feature/ConsolidarPedimentos_20231229
Felix Morales 10 months ago
parent 65d997fc3c
commit 02587dd9d4
  1. 134
      src/Components/ReportesClientes/ReporteSemanalNewel.tsx
  2. 3
      src/Services/Reportes/reportesNewell.services.ts

@ -6,6 +6,10 @@ import CTrafDataService from '../../Services/Corresponsalias/Corresponsales.Traf
import { MsgInformativo } from "../Utils/Toast/msgInformativo";
import { FaRegFileExcel } from "react-icons/fa";
import IReporteOperacionesNewell from "../../Interfaces/ReportesClientes/IReporteOperacionesNewell";
import axios from "axios";
import { TargetURL } from "../../Constants/TargetURL";
import reportesNewellServices from "../../Services/Reportes/reportesNewell.services";
import FileManagerServices from "../../Services/Utils/FileManager.Services";
export const ReporteSemanalNewell: React.FC<{}> = () => {
@ -17,6 +21,13 @@ export const ReporteSemanalNewell: React.FC<{}> = () => {
const [msg, setMsg] = useState('')
const [msgColor, setMsgColor] = useState('primary')
const [File, setFile] = useState<File | null>();
const URL = new TargetURL()
const [UserId, setUserId] = useState(() => {
const stickyValue = window.localStorage.getItem('UserId')
return stickyValue !== null ? JSON.parse(stickyValue) : 0
});
const token = localStorage.getItem('token');
const [FileId, setFileId] = useState(0);
function currentDate(days: number): string {
var today = new Date()
@ -27,78 +38,57 @@ export const ReporteSemanalNewell: React.FC<{}> = () => {
return yyyy + '-' + mm + '-' + dd
}
const readFile = () => {
if (!File) return;
var ext = File!.name.substr(File!.name.lastIndexOf('.') + 1)
const uploadFile = (file: File) => {
const formData = new FormData()
formData.append('name', file.name)
formData.append('file', file)
axios.post(
URL.get() + `/FileManager/AppendFileByProcess?IdUsuario=${UserId}&Proceso=${42}&Tags=${0}&crud=1`,
formData, {
headers:{
'Authorization': 'Bearer ' + token
}
}
)
.then((res) => {
if (res.data.id > 0) {
setFileId(res.data.id);
} else {
setHeader('Error')
setMsg('No se guardo el archivo, favor de verificar que no este vacio')
setShowMsg(true)
return
}
})
.catch((err) => alert('File Upload Error ' + err))
}
if (!(ext === 'xls') && !(ext === 'xlsx')) {
const downloadReporte = () => {
reportesNewellServices.getReporteSemanal(FileId)
.then(resp => {
const url = window.URL.createObjectURL(new Blob([resp.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `ReporteSemanal_${Inicio}_${Fin}.xlsx`);
document.body.appendChild(link);
link.click();
}).catch(e => {
setHeader('Error')
setMsg('Seleccione un archivo valido.')
setMsg('Ocurrio un error al generar el reporte. Por favor, intentelo de nuevo.')
setShowMsg(true)
return;
}
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(File);
fileReader.onload = async (e: any) => {
let encabezadosTemp = [//Se crean los encabezados temporales que se usaran mas adelante.
[
'aduana','patente','pedimento','fechaDeEntrada', 'fechaDePago',
'valorComercialMxn','valorComercialDlls','valorAduana','clave','iva',
'dta','prv','lgi','factura','tc','proveedor','taxId','producto',
'gc', 'contenedor', 'cuentaDeGastos', 'razon', 'maniobras'
]
]
const bufferArray = e?.target.result
const oldWorkBook = XLSX.read(bufferArray, { type: "buffer" })//Se lee el archivo
const oldWorkSheetName = oldWorkBook.SheetNames[0]//se toma el nombre de la primer hoja del archivo
const oldWorkSheet = oldWorkBook.Sheets[oldWorkSheetName]//Se crea una referencia a la misma hoja
XLSX.utils.sheet_add_aoa(oldWorkSheet,encabezadosTemp,{origin:'A1'});//Se cambian los encabezados originales por los temporales para que las columnas coincidan con las propiedades del dto IReporteSemanalNewell
const rows = XLSX.utils.sheet_to_json<IReporteOperacionesNewell>(oldWorkSheet)//aqui es donde los renglones pasan a ser un array de objetos
//Se obtienen los datos faltantes del reporte
let newWorkBookData = await getDataByPedimento(rows);
await exportReporteSemanal(newWorkBookData);
}
}
const getDataByPedimento = async (rows: IReporteOperacionesNewell[]) => {
let data = [...rows];
data=[];
await Promise.all(
rows.map( async (row) => {
await CTrafDataService.GetByPedimento(row.pedimento).then((response) => {
row.gc = response.data.gc;
row.contenedor = response.data.contenedor;
row.cuentaDeGastos = response.data.cuentaDeGastos;
row.razon = response.data.razon;
row.maniobras = response.data.maniobras;
})
data.push(row);
})
)
data = data.sort((a,b) => {
return +a.aduana - +b.aduana || +a.pedimento - +b.pedimento
return
})
return data;
}
const exportReporteSemanal = async (jsonData: any[]) => {
let encabezados = [
[
'Aduana','Patente','Pedimento','Fecha de Entrada', 'Fecha de Pago',
'Valor Comercial Mxn','Valor Comercial Dlls','Valor Aduana','Clave','Iva',
'Dta','Prv','lgi','Factura','TC.','Proveedor','Tax Id','Producto',
'GC', 'Contenedor', 'Cuenta de Gastos', 'Razon', 'Maniobras'
]
]
const newWorkBook = XLSX.utils.book_new()
const newWorkBookSheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet([])
XLSX.utils.sheet_add_aoa(newWorkBookSheet, encabezados,{origin:'A1'})
XLSX.utils.sheet_add_json(newWorkBookSheet, jsonData, { origin: 'A2', skipHeader: true })
XLSX.utils.book_append_sheet(newWorkBook, newWorkBookSheet, 'Sheet1')
XLSX.writeFile(newWorkBook, `Reporte_Semanal-${Inicio}_${Fin}.xlsx`);
const deleteFile = () => {
FileManagerServices.DeleteFile(FileId)
.then(resp => {
if(resp.status === 200 && hiddenFileInputRef.current !== null ) {
hiddenFileInputRef.current.value = "";
setFile(null);
setFileId(0)
}
})
}
return (
@ -155,12 +145,13 @@ export const ReporteSemanalNewell: React.FC<{}> = () => {
>
<input type="file" ref={hiddenFileInputRef} style={{display:'none'}}
onChange={(e:any) => {
uploadFile(e.target.files[0]);
setFile(e.target.files[0]);
}}
/>
{
!File ? <>
FileId === 0 ? <>
<MdCloudUpload style={{fontSize:'60px', color:'#1475cf'}}/>
<span style={{display:'block', paddingTop:'10px'}}>Seleccione un archivo...</span>
</>
@ -173,15 +164,10 @@ export const ReporteSemanalNewell: React.FC<{}> = () => {
</Row>
</Card.Body>
<Card.Footer style={{textAlign:'end'}}>
<Button variant="danger" onClick={() => {
if(hiddenFileInputRef.current !== null ) {
hiddenFileInputRef.current.value = "";
setFile(null);
}
}} title="Quitar archivo cargado" style={{marginRight:'10px'}}>
<Button variant="danger" onClick={deleteFile} title="Quitar archivo cargado" style={{marginRight:'10px'}}>
Borrar <MdDeleteForever style={{marginLeft:'5px', fontSize:'20px'}}/>
</Button>
<Button className="primary" onClick={readFile} title="Descargar reporte">
<Button className="primary" onClick={downloadReporte} title="Descargar reporte">
Generar <MdCloudDownload style={{marginLeft:'5px'}}/>
</Button>
</Card.Footer>

@ -5,6 +5,9 @@ class ReportesNewellService{
getReporteMensual(IdTrailasFile: number, IdOpCdAcunaFile: number, IdOpMyMFile: number){
return http.get(`reportesNewell/ReporteMensual?idTrailasFile=${IdTrailasFile}&idRptCdAcunaFile=${IdOpCdAcunaFile}&idRptLazaroCardenasFile=${IdOpMyMFile}`, {responseType: 'blob'});
}
getReporteSemanal(idRptSemanalFile: number){
return http.get(`reportesNewell/ReporteSemanal?idRptSemanalFile=${idRptSemanalFile}`, {responseType: 'blob'});
}
}
export default new ReportesNewellService();
Loading…
Cancel
Save