Skip to content
Open

req #14

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/frontend/src/MainApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ const MainApp = () => {
};
useEffect(() => {
console.log("This is token from MainApp", access_token);
setLoggedIn(localStorage.getItem("token"));
}, []);

return (
<div>
{loggedIn
// { (localStorage.getItem("loggedIn") != null)
? (
role === 'ADMIN' ? (
<AdminMainForma
Expand Down
11 changes: 11 additions & 0 deletions src/frontend/src/api/upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

export const handleUpload = async (formData, token, year, kvartal, typeOfObrazac) => {
console.log("From handleUpload")
await fetch(`/api/upload/${year}/${kvartal}/${typeOfObrazac}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: formData,
});
};
2 changes: 1 addition & 1 deletion src/frontend/src/components/MainContentSection.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";
import Kvartal from "./Kvartal";
import ObrazacIO from "./ObrazacIO";
import ZakljucniList from "./ZakljucniList";
import ZakljucniList from "./ZakljucniList1";
import Obrazac5 from "./Obrazac5";
import StornoAndStatusSection from "./StornoAndStatusSection";

Expand Down
202 changes: 202 additions & 0 deletions src/frontend/src/components/ZakljucniList1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import React, { useState, useEffect } from "react";
import * as XLSX from "xlsx";
import { saveZakljucni } from "../api/client-api";
import {
successNotification,
errorNotification,
warningNotification,
} from "./Notification";
import { handleUpload } from "../api/upload";


function ZakljucniList({ kvartal, setKvartal, access_token, selectedItem, setSelectedItem }) {
const [excelFile, setExcelFile] = useState(null);
const [excelFileError, setExcelFileError] = useState(null);
const [excelData, setExcelData] = useState(null);
const [message, setMessage] = useState("");
const [activeButton, setActiveButton] = useState(false);
const [excelFileUpload, setExcelFileUpload] = useState(null);


useEffect(() => {
console.log("This is token from Zakljucni List", access_token);
//setKvartal(0);
}, []);

const handleFile = (e) => {
let selectedFile = e.target.files[0];
if (selectedFile) {
if (
selectedFile.type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
selectedFile.name.endsWith(".xls")
) {
let reader = new FileReader();
reader.readAsArrayBuffer(selectedFile);
reader.onload = (e) => {
setExcelFileError(null);
setExcelFile(e.target.result);
setExcelFileUpload(selectedFile);

// setExcelFileUpload(new Blob([e.target.result]));
setActiveButton(true);
};
} else {
console.log(selectedFile.type);
setExcelFileError("Izabrani dokument nije XLSX ili XLS!");
setExcelFile(null);
}
} else {
console.log("Plz select your file");
}
setActiveButton(true);
};


///submit
const handleSubmit = (e) => {
setMessage("");
e.preventDefault();
if (excelFile !== null) {
const workbook = XLSX.read(excelFile, { type: "buffer" });
const worksheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[worksheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {
header: 1,
range: 5,
});

const filteredData = jsonData.filter(
(row) => typeof row[0] !== "undefined",
);

const headers = filteredData[0];
const data = filteredData.slice(1).map((row) => {
let obj = {};

headers.slice(0, 8).forEach((header, index) => {
let value = row[index];
if (typeof value === "undefined" || value === "") {
value = 0;
}
obj[`prop${index + 1}`] = value === null ? 0 : value;
});
return obj;
});

const year = worksheet["E4"]?.v || "";
const jbbks = worksheet["B3"]?.v || "";
const excelKvartal = worksheet["B4"]?.v || "";

console.log("godina:", year);
console.log("excelKvartal :", excelKvartal);

if (excelKvartal != kvartal) {
errorNotification(
"Izabrani kvartal se razlikuje od kvartala sa excel fajla!",
);
setExcelData(null);
setKvartal(0);
setSelectedItem(null);
return;
}
let token = localStorage.getItem("token");
const formData = new FormData();
if (excelFileUpload) {

formData.append('file', excelFileUpload);}

handleUpload(formData, token, year, excelKvartal, selectedItem );

saveZakljucni(data, kvartal, jbbks, year, token)
.then((response) => {
console.log(response);
return response.text(); // Get the text content from the response
})
.then((text) => {
// console.log(res);
if (text === "") {
successNotification("Obrazac je uspesno ucitan!");
} else {
console.log("responseText:", text);
warningNotification(
text,
"Obrazac je učitan ali postoje greške. \n ",
);
}
// Handle successful response if needed
})
.catch((error) => {
errorNotification("Neuspešno učitavanje!", error.message);
console.log("This is error message", error.message);
setKvartal(0);
});
} else {
setExcelData(null);
}
setKvartal(0);
// setExcelFile(null);
// setExcelFileError(null);
// setExcelData(null);
// setActiveButton(false);
setSelectedItem(null);
};
//
// const onFinishFailed = (errorInfo) => {
// alert(JSON.stringify(errorInfo, null, 2));
// };

return (
<div>
<form className="form-group" autoComplete="off" onSubmit={handleSubmit}>
<label>
<h5>Izaberi Zakljucni List</h5>
</label>
<br></br>
<input
disabled={kvartal === 0}
type="file"
className="form-control"
onChange={handleFile}
lang="sr"
placeholder="Unesite tekst"
required
></input>
{excelFileError && (
<div className="text-danger" style={{ marginTop: 5 + "px" }}>
{excelFileError}
</div>
)}
<br />

<button
type="submit"
className="btn btn-primary"
style={{ marginTop: 15 + "px" }}
disabled={!activeButton || kvartal === 0}
style={{ backgroundColor: "#98b4d4" }}
>
Učitaj Zakljucni List
</button>

</form>
<div>
<br></br>
<hr></hr>
<h5>{message}</h5>
{/*} {false &&
<div className="viewer">
{excelData === null && <>Nije izabran nijedan dokument</>}
{excelData !== null && (
<div className="table">
<pre>{excelData}</pre>
</div>
)}
</div>
} */}
</div>
</div>
);
}

export default ZakljucniList;
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package psf.ucitavanje.obrazaca.fileUpload;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
public class FileUploadController {

// @Value("${upload.path}") // Configure this in your application properties
// private String uploadPath;

private final FileUploadService service;


@PostMapping("/{year}/{kvartal}/{typeOfObrazac}")
public String uploadFile(@RequestParam("file") MultipartFile file,
@PathVariable(name = "year") Integer year,
@PathVariable(name = "kvartal") Integer kvartal,
@PathVariable(name = "typeOfObrazac") String typeOfObrazac
) {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();
String uploadPath = service.createPath(year, email, kvartal,typeOfObrazac);

try {
String filePath = uploadPath + File.separator + service.getDateAndTimeAsPartOfFilePath() + " " +
file.getOriginalFilename();
file.transferTo(new File(filePath));
return "File uploaded successfully!";
} catch (Exception e) {
e.printStackTrace();
return "File upload failed.";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package psf.ucitavanje.obrazaca.fileUpload;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import psf.ucitavanje.obrazaca.zakljucniList.zb.ZakljucniListZbService;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@RequiredArgsConstructor
public class FileUploadService {

@Value("${upload.path}") // Configure this in your application properties
private String uploadPath;

private final ZakljucniListZbService zakljucniListZbService;

public String getDateAndTimeAsPartOfFilePath() {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm");
return LocalDateTime.now().format(formatter);
}

public String createPath(Integer year, String email, Integer kvartal, String typeOfObrazac ) {

Integer jbbk = zakljucniListZbService.getJbbksIBK(email);
String path = uploadPath + "/" + year;
File directory = new File(path);
if (!directory.exists()) {
boolean result =
directory.mkdir();
}
path += "/" + jbbk;
File directoryJbbk = new File(path);
if (!directoryJbbk.exists()) {
boolean result =
directoryJbbk.mkdir();
}
path += "/kvartal" + kvartal;
File directoryKvartal = new File(path);
if (!directoryKvartal.exists()) {
boolean result =
directoryKvartal.mkdir();
}
path += "/" + typeOfObrazac;
File directoryType = new File(path);
if (!directoryType.exists()) {
boolean result =
directoryType.mkdir();
}
return path;

}
}
34 changes: 0 additions & 34 deletions src/main/java/psf/ucitavanje/obrazaca/kontni_plan/KontniPlan.java

This file was deleted.

This file was deleted.

Loading