
Ejemplos de Código
1
2 static async uploading_masive_files(req, res) {
3 console.log("uploading_masive_files...");
4 console.log("Request body:", req.body);
5
6 try {
7 const periodoId = req.body.period_id;
8
9 if (!req.files || Object.keys(req.files).length === 0) {
10 return res.status(400).json({ error: "No se ha subido ningún archivo" });
11 }
12
13 const period = await Payroll_Period.findOne({
14 where: { payroll_period_id: periodoId },
15 });
16
17 if (!period) {
18 return res.status(400).json({ error: "Periodo no encontrado" });
19 }
20
21 const periodName = period.payroll_period_name;
22 const extractionPath = path.join(
23 process.cwd(),
24 "public",
25 "receipment_nominas",
26 periodName
27 );
28 const uploadedFiles = [];
29 const discardedFiles = [];
30 const userFileDetails = {};
31
32 const uploadedFile = req.files.file;
33 const fileType = path.extname(uploadedFile.name).toLowerCase();
34
35 if (!fs.existsSync(extractionPath)) {
36 fs.mkdirSync(extractionPath, { recursive: true });
37 }
38
39 const handleFile = async (fileData, fileName) => {
40 const parts = fileName.split("_");
41 const rfc = parts[1];
42
43 console.log(`Procesando archivo: ${fileName}`);
44 console.log(`RFC extraído: ${rfc},`);
45
46 const collaborator = await Collaborator.findOne({
47 where: {
48 [Sequelize.Op.or]: [
49 { collaborator_rfc: rfc },
50 ],
51 },
52 });
53
54 if (collaborator) {
55 console.log(
56 `Colaborador encontrado: ${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`
57 );
58 const userId = collaborator.user_id;
59 const tempFilePath = path.join(extractionPath, fileName);
60
61 console.log(`file temporal: ${tempFilePath}`)
62
63 if (!uploadedFiles.some(file => file.fileName === fileName)) {
64 if (fileData instanceof Readable) {
65 await new Promise((resolve, reject) => {
66 fileData
67 .pipe(fs.createWriteStream(tempFilePath))
68 .on("finish", resolve)
69 .on("error", reject);
70 });
71 } else {
72 fs.writeFileSync(tempFilePath, fileData);
73 }
74
75 uploadedFiles.push({ userId, userName: `${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`, fileName, tempFilePath });
76 userFileDetails[fileName] = { userId, userName: `${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`, fileName, tempFilePath };
77
78 console.log(`Archivo procesado y agregado: ${fileName}`);
79 } else {
80 console.log(`Archivo duplicado ignorado: ${fileName}`);
81 }
82 } else {
83 console.log(`No se encontró colaborador con RFC: ${rfc}`);
84 discardedFiles.push(fileName);
85 }
86 };
87
88 if (fileType === ".zip") {
89 console.log('entramos a la condición del zip');
90 const fileStream = new Readable();
91 fileStream.push(uploadedFile.data);
92 fileStream.push(null);
93
94 const zipStream = fileStream.pipe(unzipper.Parse());
95 const promises = [];
96
97 zipStream.on("entry", (entry) => {
98 const fileName = entry.path;
99 promises.push(handleFile(entry, fileName).then(() => entry.autodrain()));
100 });
101
102 zipStream.on("close", async () => {
103 await Promise.all(promises);
104 res.status(200).json({
105 archivos_subidos: uploadedFiles,
106 archivos_descartados: discardedFiles,
107 userFileDetails,
108 });
109 });
110 } else if (fileType === ".pdf" || fileType === ".xml") {
111 await handleFile(uploadedFile.data, uploadedFile.name);
112
113 res.status(200).json({
114 archivos_subidos: uploadedFiles,
115 archivos_descartados: discardedFiles,
116 userFileDetails,
117 });
118 } else {
119 return res
120 .status(400)
121 .json({ error: "Tipo de archivo no soportado. Por favor sube un archivo ZIP, PDF o XML." });
122 }
123
124 } catch (error) {
125 console.error("Error al procesar el archivo:", error);
126 res.status(500).json({ error: "Ocurrió un error al procesar el archivo" });
127 }
128 }
129
130 static async insert_files(req, res) {
131 console.log("Inserting files...");
132 try {
133 const filesToInsert = req.body.files;
134
135 if (!filesToInsert || filesToInsert.length === 0) {
136 return res.status(400).json({ error: "No hay archivos para insertar" });
137 }
138
139 const directoryPromises = [];
140
141 for (const file of filesToInsert) {
142 const { fileName, userId, periodId, tempFilePath } = file;
143
144 if (!periodId) {
145 return res
146 .status(400)
147 .json({ error: "Periodo no definido para la inserción" });
148 }
149
150 if (!tempFilePath) {
151 console.error(
152 `tempFilePath no definido para el archivo: ${fileName}`
153 );
154 continue;
155 }
156
157 const existingFile = await Payroll_Invoice_File.findOne({
158 where: {
159 payroll_invoice_file_name: fileName,
160 user_id: userId,
161 payroll_period_id: periodId,
162 },
163 });
164
165 if (existingFile) {
166 console.log(
167 `El archivo ${fileName} ya existe para el usuario ${userId} en el periodo ${periodId}.`
168 );
169 continue;
170 }
171
172 const relativePath = path.relative(process.cwd(), tempFilePath);
173 const savePromise = await Payroll_Invoice_File.create({
174 payroll_invoice_file_name: fileName,
175 payroll_invoice_file_path: relativePath,
176 payroll_invoice_file_date: new Date().toISOString(),
177 payroll_invoice_file_status: "A",
178 user_id: userId,
179 payroll_period_id: periodId,
180 });
181
182 console.log(savePromise);
183
184 directoryPromises.push(savePromise);
185 }
186
187 await Promise.all(directoryPromises);
188 res.status(200).json({ message: "Archivos insertados correctamente" });
189 } catch (error) {
190 console.error("Error al insertar los archivos:", error);
191 res
192 .status(500)
193 .json({ error: "Ocurrió un error al insertar los archivos" });
194 }
195 }
196
1
2static async uploading_masive_files(req, res) {
3 console.log("uploading_masive_files...");
4 console.log("Request body:", req.body);
5
6 try {
7 const periodoId = req.body.period_id;
8
9 if (!req.files || Object.keys(req.files).length === 0) {
10 return res.status(400).json({ error: "No se ha subido ningún archivo" });
11 }
12
13 const period = await Payroll_Period.findOne({
14 where: { payroll_period_id: periodoId },
15 });
16
17 if (!period) {
18 return res.status(400).json({ error: "Periodo no encontrado" });
19 }
20
21 const periodName = period.payroll_period_name;
22 const extractionPath = path.join(
23 process.cwd(),
24 "public",
25 "receipment_nominas",
26 periodName
27 );
28 const uploadedFiles = [];
29 const discardedFiles = [];
30 const userFileDetails = {};
31
32 const uploadedFile = req.files.file;
33 const fileType = path.extname(uploadedFile.name).toLowerCase();
34
35 if (!fs.existsSync(extractionPath)) {
36 fs.mkdirSync(extractionPath, { recursive: true });
37 }
38
39 const handleFile = async (fileData, fileName) => {
40 const parts = fileName.split("_");
41 const rfc = parts[1];
42
43 console.log(`Procesando archivo: ${fileName}`);
44 console.log(`RFC extraído: ${rfc},`);
45
46 const collaborator = await Collaborator.findOne({
47 where: {
48 [Sequelize.Op.or]: [
49 { collaborator_rfc: rfc },
50 ],
51 },
52 });
53
54 if (collaborator) {
55 console.log(
56 `Colaborador encontrado: ${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`
57 );
58 const userId = collaborator.user_id;
59 const tempFilePath = path.join(extractionPath, fileName);
60
61 console.log(`file temporal: ${tempFilePath}`)
62
63 if (!uploadedFiles.some(file => file.fileName === fileName)) {
64 if (fileData instanceof Readable) {
65 await new Promise((resolve, reject) => {
66 fileData
67 .pipe(fs.createWriteStream(tempFilePath))
68 .on("finish", resolve)
69 .on("error", reject);
70 });
71 } else {
72 fs.writeFileSync(tempFilePath, fileData);
73 }
74
75 uploadedFiles.push({ userId, userName: `${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`, fileName, tempFilePath });
76 userFileDetails[fileName] = { userId, userName: `${collaborator.collaborator_name} ${collaborator.collaborator_last_name_p}`, fileName, tempFilePath };
77
78 console.log(`Archivo procesado y agregado: ${fileName}`);
79 } else {
80 console.log(`Archivo duplicado ignorado: ${fileName}`);
81 }
82 } else {
83 console.log(`No se encontró colaborador con RFC: ${rfc}`);
84 discardedFiles.push(fileName);
85 }
86 };
87
88 if (fileType === ".zip") {
89 console.log('entramos a la condición del zip');
90 const fileStream = new Readable();
91 fileStream.push(uploadedFile.data);
92 fileStream.push(null);
93
94 const zipStream = fileStream.pipe(unzipper.Parse());
95 const promises = [];
96
97 zipStream.on("entry", (entry) => {
98 const fileName = entry.path;
99 promises.push(handleFile(entry, fileName).then(() => entry.autodrain()));
100 });
101
102 zipStream.on("close", async () => {
103 await Promise.all(promises);
104 res.status(200).json({
105 archivos_subidos: uploadedFiles,
106 archivos_descartados: discardedFiles,
107 userFileDetails,
108 });
109 });
110 } else if (fileType === ".pdf" || fileType === ".xml") {
111 await handleFile(uploadedFile.data, uploadedFile.name);
112
113 res.status(200).json({
114 archivos_subidos: uploadedFiles,
115 archivos_descartados: discardedFiles,
116 userFileDetails,
117 });
118 } else {
119 return res
120 .status(400)
121 .json({ error: "Tipo de archivo no soportado. Por favor sube un archivo ZIP, PDF o XML." });
122 }
123
124 } catch (error) {
125 console.error("Error al procesar el archivo:", error);
126 res.status(500).json({ error: "Ocurrió un error al procesar el archivo" });
127 }
128}
129
130static async insert_files(req, res) {
131 console.log("Inserting files...");
132 try {
133 const filesToInsert = req.body.files;
134
135 if (!filesToInsert || filesToInsert.length === 0) {
136 return res.status(400).json({ error: "No hay archivos para insertar" });
137 }
138
139 const directoryPromises = [];
140
141 for (const file of filesToInsert) {
142 const { fileName, userId, periodId, tempFilePath } = file;
143
144 if (!periodId) {
145 return res
146 .status(400)
147 .json({ error: "Periodo no definido para la inserción" });
148 }
149
150 if (!tempFilePath) {
151 console.error(
152 `tempFilePath no definido para el archivo: ${fileName}`
153 );
154 continue;
155 }
156
157 const existingFile = await Payroll_Invoice_File.findOne({
158 where: {
159 payroll_invoice_file_name: fileName,
160 user_id: userId,
161 payroll_period_id: periodId,
162 },
163 });
164
165 if (existingFile) {
166 console.log(
167 `El archivo ${fileName} ya existe para el usuario ${userId} en el periodo ${periodId}.`
168 );
169 continue;
170 }
171
172 const relativePath = path.relative(process.cwd(), tempFilePath);
173 const savePromise = await Payroll_Invoice_File.create({
174 payroll_invoice_file_name: fileName,
175 payroll_invoice_file_path: relativePath,
176 payroll_invoice_file_date: new Date().toISOString(),
177 payroll_invoice_file_status: "A",
178 user_id: userId,
179 payroll_period_id: periodId,
180 });
181
182 console.log(savePromise);
183
184 directoryPromises.push(savePromise);
185 }
186
187 await Promise.all(directoryPromises);
188 res.status(200).json({ message: "Archivos insertados correctamente" });
189 } catch (error) {
190 console.error("Error al insertar los archivos:", error);
191 res
192 .status(500)
193 .json({ error: "Ocurrió un error al insertar los archivos" });
194 }
195}
196
© 2025 Efrain May. Todos los derechos Reservados.