From 1887214ed2983ca128241c8b6f7e5dc1799111f2 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Wed, 11 Sep 2024 15:27:09 -0400 Subject: [PATCH 01/26] =?UTF-8?q?#17=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Laboral=20(VISTA)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../views/WorkDocumentsView.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index de23e08..ac29094 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -1,6 +1,11 @@ package com.primefactorsolutions.views; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; @@ -13,4 +18,30 @@ import org.springframework.context.annotation.Scope; @PageTitle("WorkDocuments") @Route(value = "/work-documents/me", layout = MainLayout.class) public class WorkDocumentsView extends Main { + + public WorkDocumentsView() { + HorizontalLayout row1 = new HorizontalLayout(); + row1.add(createSection("Pay Slips"), createSection("Employment Contract")); + HorizontalLayout row2 = new HorizontalLayout(); + row2.add(createSection("Work Certificates"), createSection("NDA")); + HorizontalLayout row3 = new HorizontalLayout(); + row3.add(createSection("Memorandums"), createSection("Contract Approval MTEPS")); + add(row1, row2, row3); + } + + private Div createSection(String sectionTitle) { + Div section = new Div(); + section.add(new H2(sectionTitle)); + HorizontalLayout row1 = new HorizontalLayout(); + row1.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + row1.add(new Button("View"), new Button("Upload"), new Button("Save")); + HorizontalLayout row2 = new HorizontalLayout(); + row2.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + row2.add(new Button("Edit"), new Button("Print"), new Button("Delete")); + HorizontalLayout row3 = new HorizontalLayout(); + row3.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + row3.add(new Button("Download")); + section.add(row1, row2, row3); + return section; + } } From 5bbdb5f2ee252ce342cb10e2b7677972fe607a8a Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sat, 14 Sep 2024 15:30:51 -0400 Subject: [PATCH 02/26] =?UTF-8?q?#17=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Laboral=20(Funcion?= =?UTF-8?q?alidades=20save=20y=20upload)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/BaseEntity.java | 5 + .../primefactorsolutions/model/Document.java | 20 ++- .../model/DocumentType.java | 6 + .../repositories/DocumentRepository.java | 9 ++ .../service/DocumentService.java | 44 +++++++ .../views/GovernmentDocumentsView.java | 63 +++++++++ .../views/WorkDocumentsView.java | 123 +++++++++++++++--- 7 files changed, 239 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/primefactorsolutions/repositories/DocumentRepository.java create mode 100644 src/main/java/com/primefactorsolutions/service/DocumentService.java diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index ddc143e..98b58d2 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -14,6 +14,7 @@ public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.UUID) private UUID id; + private String fileName; @Version private int version; @@ -48,4 +49,8 @@ public abstract class BaseEntity { } return super.equals(that); } + + public String getFileName() { + return fileName; + } } diff --git a/src/main/java/com/primefactorsolutions/model/Document.java b/src/main/java/com/primefactorsolutions/model/Document.java index d162230..ce944b6 100644 --- a/src/main/java/com/primefactorsolutions/model/Document.java +++ b/src/main/java/com/primefactorsolutions/model/Document.java @@ -1,12 +1,8 @@ package com.primefactorsolutions.model; -import jakarta.annotation.Nullable; -import jakarta.persistence.Entity; -import jakarta.persistence.ManyToOne; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; +import jakarta.persistence.*; + +import lombok.*; @Entity @Data @@ -14,10 +10,10 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class Document extends BaseEntity { - @Nullable - private String description; - private String location; + private String fileName; + @Enumerated(EnumType.STRING) private DocumentType documentType; - @ManyToOne - private Employee employee; + @Lob + @Column(columnDefinition = "BLOB") + private byte[] fileData; } diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index 645beeb..007d080 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -3,5 +3,11 @@ package com.primefactorsolutions.model; public enum DocumentType { ID_CARD, PAY_STUB, + PAY_SLIPS, + EMPLOYMENT_CONTRACT, + WORK_CERTIFICATES, + NDA, + MEMORANDUMS, + CONTRACT_APPROVAL_MTEPS, OTHER } diff --git a/src/main/java/com/primefactorsolutions/repositories/DocumentRepository.java b/src/main/java/com/primefactorsolutions/repositories/DocumentRepository.java new file mode 100644 index 0000000..4a2bc88 --- /dev/null +++ b/src/main/java/com/primefactorsolutions/repositories/DocumentRepository.java @@ -0,0 +1,9 @@ +package com.primefactorsolutions.repositories; + +import com.primefactorsolutions.model.Document; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface DocumentRepository extends JpaRepository { +} diff --git a/src/main/java/com/primefactorsolutions/service/DocumentService.java b/src/main/java/com/primefactorsolutions/service/DocumentService.java new file mode 100644 index 0000000..a5cda38 --- /dev/null +++ b/src/main/java/com/primefactorsolutions/service/DocumentService.java @@ -0,0 +1,44 @@ +package com.primefactorsolutions.service; + +//import com.primefactorsolutions.model.Candidate; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.repositories.DocumentRepository; +//import lombok.AllArgsConstructor; +//import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +//import java.io.IOException; +//import java.sql.Connection; +//import java.sql.PreparedStatement; +//import java.sql.ResultSet; +//import java.sql.SQLException; +//import javax.sql.DataSource; +//import javax.sql.DataSource; +import org.springframework.transaction.annotation.Transactional; +//import org.springframework.web.multipart.MultipartFile; + +//import java.io.InputStream; +import java.util.List; +import java.util.UUID; +import java.util.Optional; + +@Service +public class DocumentService { + private final DocumentRepository documentRepository; + + public DocumentService(DocumentRepository documentRepository) { + this.documentRepository = documentRepository; + } + + public void saveDocument(Document newDocument) { + documentRepository.save(newDocument); + } + + public List getAllDocuments() { + return documentRepository.findAll(); + } + + public Optional getDocumentById(UUID id) { + return documentRepository.findById(id); + } +} diff --git a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java index a06e4bf..da65534 100644 --- a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java @@ -1,16 +1,79 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.html.Anchor; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +//import com.vaadin.flow.component.orderedlayout.FlexComponent; +//import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; +import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.ByteArrayInputStream; +import java.io.IOException; +//import java.io.InputStream; +import java.util.UUID; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("GovernmentDocumentsView") @Route(value = "/government-documents/me", layout = MainLayout.class) public class GovernmentDocumentsView extends Main { + + private final DocumentService documentService; + private final Div documentListDiv = new Div(); + + public GovernmentDocumentsView(DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + private void initializeLayout() { + setSizeFull(); + add(new H2("Document Management")); + + // Upload Component + MemoryBuffer buffer = new MemoryBuffer(); + Upload upload = new Upload(buffer); + upload.addSucceededListener(event -> { + try { + String fileName = event.getFileName(); + byte[] content = buffer.getInputStream().readAllBytes(); +// documentService.saveDocument(fileName, content); + Notification.show("File uploaded successfully"); + updateDocumentList(); + } catch (IOException e) { + Notification.show("Error uploading file: " + e.getMessage()); + } + }); + + // Add Upload component + add(upload); + + // Display documents + updateDocumentList(); + } + + private void updateDocumentList() { + documentListDiv.removeAll(); + for (Document document : documentService.getAllDocuments()) { + // Create a view link for each document +// StreamResource streamResource = new StreamResource(document.getName(), () -> new ByteArrayInputStream(document.getContent())); +// Anchor viewLink = new Anchor(streamResource, "View " + document.getName()); +// viewLink.getElement().setAttribute("target", "_blank"); +// documentListDiv.add(viewLink); + } + add(documentListDiv); + } } diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index ac29094..dfad0df 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -1,47 +1,132 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; + + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("WorkDocuments") @Route(value = "/work-documents/me", layout = MainLayout.class) public class WorkDocumentsView extends Main { - - public WorkDocumentsView() { - HorizontalLayout row1 = new HorizontalLayout(); - row1.add(createSection("Pay Slips"), createSection("Employment Contract")); - HorizontalLayout row2 = new HorizontalLayout(); - row2.add(createSection("Work Certificates"), createSection("NDA")); - HorizontalLayout row3 = new HorizontalLayout(); - row3.add(createSection("Memorandums"), createSection("Contract Approval MTEPS")); + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private boolean fileUploaded = false; + private String lastUploadedFileName = null; + public WorkDocumentsView(DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + private void initializeLayout() { + HorizontalLayout row1 = createRow("PaySlips", "Employment Contract"); + HorizontalLayout row2 = createRow("Work Certificates", "NDA"); + HorizontalLayout row3 = createRow("Memorandums", "Contract Approval MTEPS"); add(row1, row2, row3); } - + private HorizontalLayout createRow(String... sectionTitles) { + HorizontalLayout row = new HorizontalLayout(); + for (String title : sectionTitles) { + row.add(createSection(title)); + } + return row; + } private Div createSection(String sectionTitle) { Div section = new Div(); section.add(new H2(sectionTitle)); - HorizontalLayout row1 = new HorizontalLayout(); - row1.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - row1.add(new Button("View"), new Button("Upload"), new Button("Save")); - HorizontalLayout row2 = new HorizontalLayout(); - row2.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - row2.add(new Button("Edit"), new Button("Print"), new Button("Delete")); - HorizontalLayout row3 = new HorizontalLayout(); - row3.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - row3.add(new Button("Download")); - section.add(row1, row2, row3); + Upload upload = createUploadComponent(); + boolean hasDocument = documentService.getAllDocuments() + .stream() + .anyMatch(doc -> doc.getFileName().equalsIgnoreCase(sectionTitle + ".pdf")); + Button viewButton = new Button("View"); + viewButton.setEnabled(hasDocument); + Button saveButton = createSaveButton(sectionTitle, viewButton); + HorizontalLayout uploadLayout = createLayoutWithComponent(upload); + HorizontalLayout actionButtonsLayout = createLayoutWithComponents( + viewButton, new Button("Edit"), saveButton + ); + HorizontalLayout additionalButtonsLayout = createLayoutWithComponents( + new Button("Print"), new Button("Download"), new Button("Delete") + ); + section.add(uploadLayout, actionButtonsLayout, additionalButtonsLayout); return section; } + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf", ".doc", ".docx"); + upload.addSucceededListener(event -> { + fileUploaded = true; + lastUploadedFileName = event.getFileName(); + Notification.show("File uploaded successfully"); + }); + return upload; + } + private Button createSaveButton(String sectionTitle, Button viewButton) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(clickEvent -> saveFile(sectionTitle, )); + return saveButton; + } + private HorizontalLayout createLayoutWithComponent(com.vaadin.flow.component.Component component) { + HorizontalLayout layout = new HorizontalLayout(); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + layout.add(component); + return layout; + } + private HorizontalLayout createLayoutWithComponents(com.vaadin.flow.component.Component... components) { + HorizontalLayout layout = new HorizontalLayout(); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + layout.add(components); + return layout; + } + private void saveFile(String sectionTitle, Button viewButton) { + if (fileUploaded) { + try { + String fileName = lastUploadedFileName; + byte[] content = buffer.getInputStream().readAllBytes(); + if (content != null) { + DocumentType documentType = determineDocumentType(sectionTitle); + Document document = new Document(fileName, documentType, content); + documentService.saveDocument(document); + fileUploaded = false; + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } else { + Notification.show("No file content found."); + } + } catch (IOException e) { + Notification.show("Error reading file content: " + e.getMessage()); + } + } else { + Notification.show("Please upload a file first."); + } + } + private DocumentType determineDocumentType(String sectionTitle) { + return switch (sectionTitle) { + case "PaySlips" -> DocumentType.PAY_SLIPS; + case "Employment Contract" -> DocumentType.EMPLOYMENT_CONTRACT; + case "Work Certificates" -> DocumentType.WORK_CERTIFICATES; + case "NDA" -> DocumentType.NDA; + case "Memorandums" -> DocumentType.MEMORANDUMS; + case "Contract Approval MTEPS" -> DocumentType.CONTRACT_APPROVAL_MTEPS; + default -> DocumentType.OTHER; + }; + } } From 64d62a06dbc5c7952416701cfb730107f4e7e371 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sat, 14 Sep 2024 15:33:33 -0400 Subject: [PATCH 03/26] =?UTF-8?q?#17=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Laboral=20(Funcion?= =?UTF-8?q?alidades=20save=20y=20upload=20v2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/primefactorsolutions/views/WorkDocumentsView.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index dfad0df..d0ec2b0 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -81,7 +81,7 @@ public class WorkDocumentsView extends Main { } private Button createSaveButton(String sectionTitle, Button viewButton) { Button saveButton = new Button("Save"); - saveButton.addClickListener(clickEvent -> saveFile(sectionTitle, )); + saveButton.addClickListener(clickEvent -> saveFile(sectionTitle, viewButton)); return saveButton; } private HorizontalLayout createLayoutWithComponent(com.vaadin.flow.component.Component component) { From 97c07a45583fffc5c1c4ee26f4b5e0eb10a68031 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 02:25:38 -0400 Subject: [PATCH 04/26] =?UTF-8?q?#17=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Laboral=20(Ver=20d?= =?UTF-8?q?ocumento)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/BaseEntity.java | 15 +- .../views/WorkDocumentsView.java | 176 +++++++++++------- 2 files changed, 115 insertions(+), 76 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index 98b58d2..89f73b4 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -1,10 +1,6 @@ package com.primefactorsolutions.model; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.MappedSuperclass; -import jakarta.persistence.Version; +import jakarta.persistence.*; import java.util.UUID; @@ -15,6 +11,11 @@ public abstract class BaseEntity { @GeneratedValue(strategy = GenerationType.UUID) private UUID id; private String fileName; + @Lob + @Column(columnDefinition = "BLOB") + private byte[] fileData; + @Enumerated(EnumType.STRING) + private DocumentType documentType; @Version private int version; @@ -53,4 +54,8 @@ public abstract class BaseEntity { public String getFileName() { return fileName; } + + public byte[] getFileData() { return fileData; } + + public DocumentType getDocumentType() { return documentType; } } diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index d0ec2b0..b9e5b1b 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -3,13 +3,17 @@ package com.primefactorsolutions.views; import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; @@ -19,7 +23,7 @@ import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; import java.io.IOException; - +import java.util.Base64; @SpringComponent @PermitAll @@ -29,104 +33,134 @@ import java.io.IOException; public class WorkDocumentsView extends Main { private final DocumentService documentService; private final MemoryBuffer buffer = new MemoryBuffer(); - private boolean fileUploaded = false; private String lastUploadedFileName = null; + private DocumentType currentDocumentType = null; + public WorkDocumentsView(DocumentService documentService) { this.documentService = documentService; initializeLayout(); } + private void initializeLayout() { - HorizontalLayout row1 = createRow("PaySlips", "Employment Contract"); - HorizontalLayout row2 = createRow("Work Certificates", "NDA"); - HorizontalLayout row3 = createRow("Memorandums", "Contract Approval MTEPS"); - add(row1, row2, row3); + add(createRow("PaySlips", DocumentType.PAY_SLIPS, + "Employment Contract", DocumentType.EMPLOYMENT_CONTRACT)); + add(createRow("Work Certificates", DocumentType.WORK_CERTIFICATES, + "NDA", DocumentType.NDA)); + add(createRow("Memorandums", DocumentType.MEMORANDUMS, + "Contract Approval MTEPS", DocumentType.CONTRACT_APPROVAL_MTEPS)); } - private HorizontalLayout createRow(String... sectionTitles) { + + private HorizontalLayout createRow(String title1, DocumentType type1, String title2, DocumentType type2) { HorizontalLayout row = new HorizontalLayout(); - for (String title : sectionTitles) { - row.add(createSection(title)); - } + row.add(createDocumentSection(title1, type1), createDocumentSection(title2, type2)); return row; } - private Div createSection(String sectionTitle) { + + private Div createDocumentSection(String title, DocumentType documentType) { Div section = new Div(); - section.add(new H2(sectionTitle)); + section.add(new H2(title)); + Upload upload = createUploadComponent(); - boolean hasDocument = documentService.getAllDocuments() - .stream() - .anyMatch(doc -> doc.getFileName().equalsIgnoreCase(sectionTitle + ".pdf")); - Button viewButton = new Button("View"); - viewButton.setEnabled(hasDocument); - Button saveButton = createSaveButton(sectionTitle, viewButton); - HorizontalLayout uploadLayout = createLayoutWithComponent(upload); - HorizontalLayout actionButtonsLayout = createLayoutWithComponents( - viewButton, new Button("Edit"), saveButton - ); - HorizontalLayout additionalButtonsLayout = createLayoutWithComponents( - new Button("Print"), new Button("Download"), new Button("Delete") - ); - section.add(uploadLayout, actionButtonsLayout, additionalButtonsLayout); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); return section; } + private Upload createUploadComponent() { Upload upload = new Upload(buffer); upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf", ".doc", ".docx"); - upload.addSucceededListener(event -> { - fileUploaded = true; - lastUploadedFileName = event.getFileName(); - Notification.show("File uploaded successfully"); - }); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); return upload; } - private Button createSaveButton(String sectionTitle, Button viewButton) { + + private Button createViewButton(DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(Button viewButton, DocumentType documentType) { Button saveButton = new Button("Save"); - saveButton.addClickListener(clickEvent -> saveFile(sectionTitle, viewButton)); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); return saveButton; } - private HorizontalLayout createLayoutWithComponent(com.vaadin.flow.component.Component component) { - HorizontalLayout layout = new HorizontalLayout(); + + private void handleUploadSuccess(String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - layout.add(component); return layout; } - private HorizontalLayout createLayoutWithComponents(com.vaadin.flow.component.Component... components) { - HorizontalLayout layout = new HorizontalLayout(); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - layout.add(components); - return layout; + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); } - private void saveFile(String sectionTitle, Button viewButton) { - if (fileUploaded) { - try { - String fileName = lastUploadedFileName; - byte[] content = buffer.getInputStream().readAllBytes(); - if (content != null) { - DocumentType documentType = determineDocumentType(sectionTitle); - Document document = new Document(fileName, documentType, content); - documentService.saveDocument(document); - fileUploaded = false; - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } else { - Notification.show("No file content found."); - } - } catch (IOException e) { - Notification.show("Error reading file content: " + e.getMessage()); - } - } else { + + private void saveFile(DocumentType documentType, Button viewButton) { + if (lastUploadedFileName == null) { Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); } } - private DocumentType determineDocumentType(String sectionTitle) { - return switch (sectionTitle) { - case "PaySlips" -> DocumentType.PAY_SLIPS; - case "Employment Contract" -> DocumentType.EMPLOYMENT_CONTRACT; - case "Work Certificates" -> DocumentType.WORK_CERTIFICATES; - case "NDA" -> DocumentType.NDA; - case "Memorandums" -> DocumentType.MEMORANDUMS; - case "Contract Approval MTEPS" -> DocumentType.CONTRACT_APPROVAL_MTEPS; - default -> DocumentType.OTHER; - }; + + private boolean documentExists(DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); } } From 443299453b8a9d6567cfdd714538017792b2fc4a Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 02:47:52 -0400 Subject: [PATCH 05/26] =?UTF-8?q?#17=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Laboral=20(Revisi?= =?UTF-8?q?=C3=B2n)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/BaseEntity.java | 8 ++- .../service/DocumentService.java | 20 +----- .../views/GovernmentDocumentsView.java | 63 ------------------- .../views/WorkDocumentsView.java | 37 ++++++----- 4 files changed, 31 insertions(+), 97 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index 89f73b4..38f3d3f 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -55,7 +55,11 @@ public abstract class BaseEntity { return fileName; } - public byte[] getFileData() { return fileData; } + public byte[] getFileData() { + return fileData; + } - public DocumentType getDocumentType() { return documentType; } + public DocumentType getDocumentType() { + return documentType; + } } diff --git a/src/main/java/com/primefactorsolutions/service/DocumentService.java b/src/main/java/com/primefactorsolutions/service/DocumentService.java index a5cda38..838840f 100644 --- a/src/main/java/com/primefactorsolutions/service/DocumentService.java +++ b/src/main/java/com/primefactorsolutions/service/DocumentService.java @@ -1,23 +1,9 @@ package com.primefactorsolutions.service; -//import com.primefactorsolutions.model.Candidate; import com.primefactorsolutions.model.Document; import com.primefactorsolutions.repositories.DocumentRepository; -//import lombok.AllArgsConstructor; -//import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -//import java.io.IOException; -//import java.sql.Connection; -//import java.sql.PreparedStatement; -//import java.sql.ResultSet; -//import java.sql.SQLException; -//import javax.sql.DataSource; -//import javax.sql.DataSource; -import org.springframework.transaction.annotation.Transactional; -//import org.springframework.web.multipart.MultipartFile; - -//import java.io.InputStream; import java.util.List; import java.util.UUID; import java.util.Optional; @@ -26,11 +12,11 @@ import java.util.Optional; public class DocumentService { private final DocumentRepository documentRepository; - public DocumentService(DocumentRepository documentRepository) { + public DocumentService(final DocumentRepository documentRepository) { this.documentRepository = documentRepository; } - public void saveDocument(Document newDocument) { + public void saveDocument(final Document newDocument) { documentRepository.save(newDocument); } @@ -38,7 +24,7 @@ public class DocumentService { return documentRepository.findAll(); } - public Optional getDocumentById(UUID id) { + public Optional getDocumentById(final UUID id) { return documentRepository.findById(id); } } diff --git a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java index da65534..a06e4bf 100644 --- a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java @@ -1,79 +1,16 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.html.Anchor; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -//import com.vaadin.flow.component.orderedlayout.FlexComponent; -//import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; -import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.ByteArrayInputStream; -import java.io.IOException; -//import java.io.InputStream; -import java.util.UUID; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("GovernmentDocumentsView") @Route(value = "/government-documents/me", layout = MainLayout.class) public class GovernmentDocumentsView extends Main { - - private final DocumentService documentService; - private final Div documentListDiv = new Div(); - - public GovernmentDocumentsView(DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); - } - - private void initializeLayout() { - setSizeFull(); - add(new H2("Document Management")); - - // Upload Component - MemoryBuffer buffer = new MemoryBuffer(); - Upload upload = new Upload(buffer); - upload.addSucceededListener(event -> { - try { - String fileName = event.getFileName(); - byte[] content = buffer.getInputStream().readAllBytes(); -// documentService.saveDocument(fileName, content); - Notification.show("File uploaded successfully"); - updateDocumentList(); - } catch (IOException e) { - Notification.show("Error uploading file: " + e.getMessage()); - } - }); - - // Add Upload component - add(upload); - - // Display documents - updateDocumentList(); - } - - private void updateDocumentList() { - documentListDiv.removeAll(); - for (Document document : documentService.getAllDocuments()) { - // Create a view link for each document -// StreamResource streamResource = new StreamResource(document.getName(), () -> new ByteArrayInputStream(document.getContent())); -// Anchor viewLink = new Anchor(streamResource, "View " + document.getName()); -// viewLink.getElement().setAttribute("target", "_blank"); -// documentListDiv.add(viewLink); - } - add(documentListDiv); - } } diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index b9e5b1b..29421d8 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -34,9 +34,8 @@ public class WorkDocumentsView extends Main { private final DocumentService documentService; private final MemoryBuffer buffer = new MemoryBuffer(); private String lastUploadedFileName = null; - private DocumentType currentDocumentType = null; - public WorkDocumentsView(DocumentService documentService) { + public WorkDocumentsView(final DocumentService documentService) { this.documentService = documentService; initializeLayout(); } @@ -50,13 +49,21 @@ public class WorkDocumentsView extends Main { "Contract Approval MTEPS", DocumentType.CONTRACT_APPROVAL_MTEPS)); } - private HorizontalLayout createRow(String title1, DocumentType type1, String title2, DocumentType type2) { + private HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + HorizontalLayout row = new HorizontalLayout(); - row.add(createDocumentSection(title1, type1), createDocumentSection(title2, type2)); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); return row; } - private Div createDocumentSection(String title, DocumentType documentType) { + private Div createDocumentSection(final String title, final DocumentType documentType) { Div section = new Div(); section.add(new H2(title)); @@ -78,25 +85,25 @@ public class WorkDocumentsView extends Main { return upload; } - private Button createViewButton(DocumentType documentType) { + private Button createViewButton(final DocumentType documentType) { Button viewButton = new Button("View"); viewButton.setEnabled(documentExists(documentType)); viewButton.addClickListener(event -> viewDocument(documentType)); return viewButton; } - private Button createSaveButton(Button viewButton, DocumentType documentType) { + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { Button saveButton = new Button("Save"); saveButton.addClickListener(event -> saveFile(documentType, viewButton)); return saveButton; } - private void handleUploadSuccess(String fileName) { + private void handleUploadSuccess(final String fileName) { lastUploadedFileName = fileName; Notification.show("File uploaded successfully"); } - private HorizontalLayout createLayout(Component... components) { + private HorizontalLayout createLayout(final Component... components) { if (components.length != 1 && components.length != 3) { throw new IllegalArgumentException("This method only accepts 1 or 3 components."); } @@ -109,7 +116,7 @@ public class WorkDocumentsView extends Main { return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); } - private void saveFile(DocumentType documentType, Button viewButton) { + private void saveFile(final DocumentType documentType, final Button viewButton) { if (lastUploadedFileName == null) { Notification.show("Please upload a file first."); return; @@ -124,24 +131,24 @@ public class WorkDocumentsView extends Main { } } - private boolean documentExists(DocumentType documentType) { + private boolean documentExists(final DocumentType documentType) { return documentService.getAllDocuments().stream() .anyMatch(doc -> doc.getDocumentType() == documentType); } - private void viewDocument(DocumentType documentType) { + private void viewDocument(final DocumentType documentType) { documentService.getAllDocuments().stream() .filter(doc -> doc.getDocumentType() == documentType) .findFirst() .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); } - private void showPdfDialog(Document document) { + private void showPdfDialog(final Document document) { Dialog dialog = createDialog(document.getFileData()); dialog.open(); } - private Dialog createDialog(byte[] fileData) { + private Dialog createDialog(final byte[] fileData) { Dialog dialog = new Dialog(); dialog.setModal(true); dialog.setCloseOnEsc(true); @@ -160,7 +167,7 @@ public class WorkDocumentsView extends Main { return dialog; } - private String createPdfResource(byte[] fileData) { + private String createPdfResource(final byte[] fileData) { return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); } } From ca307e2c0bf9379cd9baebe742bbcc700fb65101 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 03:09:38 -0400 Subject: [PATCH 06/26] =?UTF-8?q?#20=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Personal=20(Ver,?= =?UTF-8?q?=20cargar=20y=20guardar)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/DocumentType.java | 4 + .../views/PersonalDocumentsView.java | 162 ++++++++++++++++++ 2 files changed, 166 insertions(+) diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index 007d080..f6e0bc8 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -9,5 +9,9 @@ public enum DocumentType { NDA, MEMORANDUMS, CONTRACT_APPROVAL_MTEPS, + BACKGROUND_CHECK_CERTIFICATE, + PRE_EMPLOYMENT_EVALUATION, + INSURANCE_REGISTRATION_FORM, + INSURANCE_CANCELLATION_FORM, OTHER } diff --git a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java index 433b5c5..ca31c9e 100644 --- a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java @@ -1,16 +1,178 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; +import java.util.Base64; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("PersonalDocuments") @Route(value = "/personal-documents/me", layout = MainLayout.class) public class PersonalDocumentsView extends Main { + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private String lastUploadedFileName = null; + + public PersonalDocumentsView(final DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + private void initializeLayout() { + add(createRow("Identity Card", DocumentType.ID_CARD, + "Background check certificate", DocumentType.BACKGROUND_CHECK_CERTIFICATE)); + add(createRow("Pre-employment evaluation", DocumentType.PRE_EMPLOYMENT_EVALUATION, + "Insurance registration form", DocumentType.INSURANCE_REGISTRATION_FORM)); + add(createRow()); + } + + private HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + + HorizontalLayout row = new HorizontalLayout(); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); + return row; + } + + private HorizontalLayout createRow() { + HorizontalLayout row = new HorizontalLayout(); + row.add(createDocumentSection("Insurance cancellation form", DocumentType.INSURANCE_CANCELLATION_FORM)); + return row; + } + + private Div createDocumentSection(final String title, final DocumentType documentType) { + Div section = new Div(); + section.add(new H2(title)); + + Upload upload = createUploadComponent(); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); + return section; + } + + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); + return upload; + } + + private Button createViewButton(final DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + return saveButton; + } + + private void handleUploadSuccess(final String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(final Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + return layout; + } + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); + } + + private void saveFile(final DocumentType documentType, final Button viewButton) { + if (lastUploadedFileName == null) { + Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); + } + } + + private boolean documentExists(final DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(final DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(final Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(final byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(final byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + } } From 0744e16dea0fcd15975f807568ebb6d5b08fee2b Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 03:22:18 -0400 Subject: [PATCH 07/26] =?UTF-8?q?#21=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Profesional=20(Ver?= =?UTF-8?q?,=20cargar=20y=20guardar)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/DocumentType.java | 6 + .../views/ProfessionalDocumentsView.java | 157 ++++++++++++++++++ 2 files changed, 163 insertions(+) diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index f6e0bc8..e8f64d9 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -13,5 +13,11 @@ public enum DocumentType { PRE_EMPLOYMENT_EVALUATION, INSURANCE_REGISTRATION_FORM, INSURANCE_CANCELLATION_FORM, + PROFESSIONAL_DEGREE_1, + PROFESSIONAL_CERTIFICATE_1, + PROFESSIONAL_DEGREE_2, + PROFESSIONAL_CERTIFICATE_2, + PROFESSIONAL_DEGREE_3, + PROFESSIONAL_CERTIFICATE_3, OTHER } diff --git a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java index 2b2badd..3148b50 100644 --- a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java @@ -1,16 +1,173 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; +import java.util.Base64; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("ProfessionalDocuments") @Route(value = "/professional-documents/me", layout = MainLayout.class) public class ProfessionalDocumentsView extends Main { + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private String lastUploadedFileName = null; + + public ProfessionalDocumentsView(final DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + private void initializeLayout() { + add(createRow("Professional Degree 1", DocumentType.PROFESSIONAL_DEGREE_1, + "Professional Certificate 1", DocumentType.PROFESSIONAL_CERTIFICATE_1)); + add(createRow("Professional Degree 2", DocumentType.PROFESSIONAL_DEGREE_2, + "Professional Certificate 2", DocumentType.PROFESSIONAL_CERTIFICATE_2)); + add(createRow("Professional Degree 3", DocumentType.PROFESSIONAL_DEGREE_3, + "Professional Certificate 3", DocumentType.PROFESSIONAL_CERTIFICATE_3)); + } + + private HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + + HorizontalLayout row = new HorizontalLayout(); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); + return row; + } + + private Div createDocumentSection(final String title, final DocumentType documentType) { + Div section = new Div(); + section.add(new H2(title)); + + Upload upload = createUploadComponent(); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); + return section; + } + + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); + return upload; + } + + private Button createViewButton(final DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + return saveButton; + } + + private void handleUploadSuccess(final String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(final Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + return layout; + } + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); + } + + private void saveFile(final DocumentType documentType, final Button viewButton) { + if (lastUploadedFileName == null) { + Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); + } + } + + private boolean documentExists(final DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(final DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(final Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(final byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(final byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + } } From 109ddde243d5ebbead20dec482fd148e525fc410 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 17:52:43 -0400 Subject: [PATCH 08/26] =?UTF-8?q?#18=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Carga=20de=20Documentaci=C3=B3n=20Corporativa=20(Ver?= =?UTF-8?q?,=20cargar=20y=20guardar)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/DocumentType.java | 6 + .../views/CorporateDocumentsView.java | 157 ++++++++++++++++++ 2 files changed, 163 insertions(+) diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index e8f64d9..ac1a994 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -19,5 +19,11 @@ public enum DocumentType { PROFESSIONAL_CERTIFICATE_2, PROFESSIONAL_DEGREE_3, PROFESSIONAL_CERTIFICATE_3, + GENERAL_LABOR_REGULATIONS, + REMOTE_WORK_GUIDELINES, + SAFETY_REGULATIONS, + HUMAN_RESOURCES_GUIDELINES, + ADMINISTRATION_FUNCTIONS_MANUAL, + ENGINEERING_FUNCTIONS_MANUAL, OTHER } diff --git a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java b/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java index 7806438..c1e5c56 100644 --- a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java @@ -1,16 +1,173 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; +import java.util.Base64; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("CorporateDocuments") @Route(value = "/corporate-documents/me", layout = MainLayout.class) public class CorporateDocumentsView extends Main { + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private String lastUploadedFileName = null; + + public CorporateDocumentsView(final DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + private void initializeLayout() { + add(createRow("General Labor Regulations", DocumentType.GENERAL_LABOR_REGULATIONS, + "Remote Work Guidelines", DocumentType.REMOTE_WORK_GUIDELINES)); + add(createRow("Safety Regulations", DocumentType.SAFETY_REGULATIONS, + "Human Resources Guidelines", DocumentType.HUMAN_RESOURCES_GUIDELINES)); + add(createRow("Administration Functions Manual", DocumentType.ADMINISTRATION_FUNCTIONS_MANUAL, + "Engineering Functions Manual", DocumentType.ENGINEERING_FUNCTIONS_MANUAL)); + } + + private HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + + HorizontalLayout row = new HorizontalLayout(); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); + return row; + } + + private Div createDocumentSection(final String title, final DocumentType documentType) { + Div section = new Div(); + section.add(new H2(title)); + + Upload upload = createUploadComponent(); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); + return section; + } + + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); + return upload; + } + + private Button createViewButton(final DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + return saveButton; + } + + private void handleUploadSuccess(final String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(final Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + return layout; + } + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); + } + + private void saveFile(final DocumentType documentType, final Button viewButton) { + if (lastUploadedFileName == null) { + Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); + } + } + + private boolean documentExists(final DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(final DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(final Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(final byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(final byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + } } From f2a1d53e4a71aa2a8a4abf0b65b042a345cc8b1d Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Sun, 15 Sep 2024 18:13:11 -0400 Subject: [PATCH 09/26] =?UTF-8?q?#19=20Perfil=20de=20Personal=20Administra?= =?UTF-8?q?tivo=20-=20Cargar=20Documentaci=C3=B3n=20de=20Gobierno=20(Ver,?= =?UTF-8?q?=20cargar=20y=20guardar)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/BaseEntity.java | 9 + .../model/DocumentType.java | 6 + .../primefactorsolutions/model/Employee.java | 93 +++++----- .../views/EmployeesListView.java | 6 - .../views/GovernmentDocumentsView.java | 165 ++++++++++++++++++ 5 files changed, 223 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index 38f3d3f..09b1382 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -10,6 +10,7 @@ public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.UUID) private UUID id; + private Employee.Status status; private String fileName; @Lob @Column(columnDefinition = "BLOB") @@ -62,4 +63,12 @@ public abstract class BaseEntity { public DocumentType getDocumentType() { return documentType; } + + public void setStatus(Employee.Status status) { + this.status = status; + } + + public Employee.Status getStatus() { + return status; + } } diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index ac1a994..138439e 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -25,5 +25,11 @@ public enum DocumentType { HUMAN_RESOURCES_GUIDELINES, ADMINISTRATION_FUNCTIONS_MANUAL, ENGINEERING_FUNCTIONS_MANUAL, + GENERAL_LABOR_LAW, + SUPREME_DECREE, + REGULATORY_RESOLUTION, + COMPLEMENTARY_REGULATION, + HEALTH_SAFETY_LAW, + INTERNSHIP_RULES, OTHER } diff --git a/src/main/java/com/primefactorsolutions/model/Employee.java b/src/main/java/com/primefactorsolutions/model/Employee.java index 4f5a49e..be9d163 100644 --- a/src/main/java/com/primefactorsolutions/model/Employee.java +++ b/src/main/java/com/primefactorsolutions/model/Employee.java @@ -1,52 +1,45 @@ - package com.primefactorsolutions.model; - import jakarta.persistence.*; - import lombok.AllArgsConstructor; - import lombok.Data; - import lombok.EqualsAndHashCode; - import lombok.NoArgsConstructor; +package com.primefactorsolutions.model; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import java.time.LocalDate; - import java.time.LocalDate; - - @Data - @Entity - @AllArgsConstructor - @NoArgsConstructor - @EqualsAndHashCode(callSuper = true) - public class Employee extends BaseEntity { - private String userName; - private String firstName; - private String lastName; - private LocalDate birthday; - private String birthCity; - @Enumerated(EnumType.STRING) - private MaritalStatus maritalStatus; - private String residenceAddress; - private String phoneNumber; - private String personalEmail; - private String position; - private String team; - private String emergencyCName; - private String emergencyCAddress; - private String emergencyCPhone; - private String emergencyCEmail; - @Column(columnDefinition = "TEXT") - private String profileImage; - @Enumerated(EnumType.STRING) - private Status status; - public enum Status { - ACTIVE, - INACTIVE - } - public enum MaritalStatus { - SINGLE, - MARRIED, - WIDOWED, - DIVORCED - } - public Status getStatus() { - return status; - } - public void setStatus(final Status status) { - this.status = status; - } +@Data +@Entity +@AllArgsConstructor +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +public class Employee extends BaseEntity { + private String userName; + private String firstName; + private String lastName; + private LocalDate birthday; + private String birthCity; + @Enumerated(EnumType.STRING) + private MaritalStatus maritalStatus; + private String residenceAddress; + private String phoneNumber; + private String personalEmail; + private String position; + private String team; + private String emergencyCName; + private String emergencyCAddress; + private String emergencyCPhone; + private String emergencyCEmail; + @Column(columnDefinition = "TEXT") + private String profileImage; + @Enumerated(EnumType.STRING) + private Status status; + public enum Status { + ACTIVE, + INACTIVE } + public enum MaritalStatus { + SINGLE, + MARRIED, + WIDOWED, + DIVORCED + } +} \ No newline at end of file diff --git a/src/main/java/com/primefactorsolutions/views/EmployeesListView.java b/src/main/java/com/primefactorsolutions/views/EmployeesListView.java index fed246b..15fc02a 100644 --- a/src/main/java/com/primefactorsolutions/views/EmployeesListView.java +++ b/src/main/java/com/primefactorsolutions/views/EmployeesListView.java @@ -47,12 +47,6 @@ public class EmployeesListView extends Main { setupPagingGrid(); } - private void updateEmployeeStatus(final Employee employee, final boolean isActive) { - employee.setStatus(isActive ? Employee.Status.ACTIVE : Employee.Status.INACTIVE); - employeeService.createOrUpdate(employee); - refreshGrid(); - } - private void addEditButtonColumn(final String label, final ButtonClickHandler handler) { table.addComponentColumn(employee -> createButton(label, () -> handler.handle(employee))); } diff --git a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java index a06e4bf..e3ad798 100644 --- a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java @@ -1,16 +1,181 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; +import java.util.Base64; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("GovernmentDocumentsView") @Route(value = "/government-documents/me", layout = MainLayout.class) public class GovernmentDocumentsView extends Main { + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private String lastUploadedFileName = null; + + public GovernmentDocumentsView(final DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + private void initializeLayout() { + add(createRow( + "General Labor Law", DocumentType.GENERAL_LABOR_LAW, + "Supreme Decrees", DocumentType.SUPREME_DECREE + )); + + add(createRow( + "Regulatory Resolutions/Provisions", DocumentType.REGULATORY_RESOLUTION, + "Complementary Regulations", DocumentType.COMPLEMENTARY_REGULATION + )); + + add(createRow( + "General Law on Hygiene, Health, Occupational Safety, and Well-being", DocumentType.HEALTH_SAFETY_LAW, + "Regulatory Framework for Internship Development", DocumentType.INTERNSHIP_RULES + )); + } + + private HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + + HorizontalLayout row = new HorizontalLayout(); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); + return row; + } + + private Div createDocumentSection(final String title, final DocumentType documentType) { + Div section = new Div(); + section.add(new H2(title)); + + Upload upload = createUploadComponent(); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); + return section; + } + + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); + return upload; + } + + private Button createViewButton(final DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + return saveButton; + } + + private void handleUploadSuccess(final String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(final Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + return layout; + } + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); + } + + private void saveFile(final DocumentType documentType, final Button viewButton) { + if (lastUploadedFileName == null) { + Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); + } + } + + private boolean documentExists(final DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(final DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(final Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(final byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(final byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + } } From 13c81de48c14a47d411b6db65565cd1cb15dd7c4 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Mon, 16 Sep 2024 20:09:16 -0400 Subject: [PATCH 10/26] Correcciones --- src/main/java/com/primefactorsolutions/model/BaseEntity.java | 5 +++-- .../java/com/primefactorsolutions/views/EmployeeView.java | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index 09b1382..065f3fe 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -10,6 +10,7 @@ public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.UUID) private UUID id; + @Enumerated(EnumType.STRING) private Employee.Status status; private String fileName; @Lob @@ -64,11 +65,11 @@ public abstract class BaseEntity { return documentType; } - public void setStatus(Employee.Status status) { + public void setStatusEmployee(Employee.Status status) { this.status = status; } - public Employee.Status getStatus() { + public Employee.Status getStatusEmployee() { return status; } } diff --git a/src/main/java/com/primefactorsolutions/views/EmployeeView.java b/src/main/java/com/primefactorsolutions/views/EmployeeView.java index 8b18f3b..42e95e2 100644 --- a/src/main/java/com/primefactorsolutions/views/EmployeeView.java +++ b/src/main/java/com/primefactorsolutions/views/EmployeeView.java @@ -199,7 +199,7 @@ public class EmployeeView extends BeanValidationForm implements HasUrl private void saveEmployee() { if (validateForm()) { Employee employee = getEntity(); - employee.setStatus(status.getValue()); + employee.setStatusEmployee(status.getValue()); employeeService.createOrUpdate(employee); Notification.show(NOTIFICATION_SAVE_SUCCESS); getUI().ifPresent(ui -> ui.navigate(EmployeesListView.class)); @@ -233,7 +233,7 @@ public class EmployeeView extends BeanValidationForm implements HasUrl if ("edit".equals(action) && !s.isEmpty()) { saveButton.setVisible(true); editButton.setVisible(false); - status.setValue(employee.getStatus()); + status.setValue(employee.getStatusEmployee()); setFieldsEditable(); } else if ("view".equals(action) && !s.isEmpty()) { setFieldsReadOnly(); From 613221dfb6631979496774f48444db58558fb038 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Thu, 19 Sep 2024 00:56:44 -0400 Subject: [PATCH 11/26] Refactorizacion del modulo de documentos --- .../model/BaseEntity.java | 28 --- .../primefactorsolutions/model/Document.java | 2 +- .../views/CorporateDocumentsView.java | 150 +---------------- .../views/DocumentsView.java | 159 +++++++++++++++++- .../views/EmployeeView.java | 4 +- .../views/GovernmentDocumentsView.java | 150 +---------------- .../views/PersonalDocumentsView.java | 158 +---------------- .../views/ProfessionalDocumentsView.java | 150 +---------------- .../views/WorkDocumentsView.java | 150 +---------------- 9 files changed, 182 insertions(+), 769 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/BaseEntity.java b/src/main/java/com/primefactorsolutions/model/BaseEntity.java index 065f3fe..381a9c6 100644 --- a/src/main/java/com/primefactorsolutions/model/BaseEntity.java +++ b/src/main/java/com/primefactorsolutions/model/BaseEntity.java @@ -10,14 +10,6 @@ public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.UUID) private UUID id; - @Enumerated(EnumType.STRING) - private Employee.Status status; - private String fileName; - @Lob - @Column(columnDefinition = "BLOB") - private byte[] fileData; - @Enumerated(EnumType.STRING) - private DocumentType documentType; @Version private int version; @@ -52,24 +44,4 @@ public abstract class BaseEntity { } return super.equals(that); } - - public String getFileName() { - return fileName; - } - - public byte[] getFileData() { - return fileData; - } - - public DocumentType getDocumentType() { - return documentType; - } - - public void setStatusEmployee(Employee.Status status) { - this.status = status; - } - - public Employee.Status getStatusEmployee() { - return status; - } } diff --git a/src/main/java/com/primefactorsolutions/model/Document.java b/src/main/java/com/primefactorsolutions/model/Document.java index ce944b6..3b8b200 100644 --- a/src/main/java/com/primefactorsolutions/model/Document.java +++ b/src/main/java/com/primefactorsolutions/model/Document.java @@ -4,8 +4,8 @@ import jakarta.persistence.*; import lombok.*; -@Entity @Data +@Entity @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = true) diff --git a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java b/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java index c1e5c56..9810e85 100644 --- a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java @@ -1,46 +1,26 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; -import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.IOException; -import java.util.Base64; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("CorporateDocuments") @Route(value = "/corporate-documents/me", layout = MainLayout.class) -public class CorporateDocumentsView extends Main { - private final DocumentService documentService; - private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; +public class CorporateDocumentsView extends DocumentsView { public CorporateDocumentsView(final DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); + super(documentService); } - private void initializeLayout() { + @Override + protected void initializeLayout() { add(createRow("General Labor Regulations", DocumentType.GENERAL_LABOR_REGULATIONS, "Remote Work Guidelines", DocumentType.REMOTE_WORK_GUIDELINES)); add(createRow("Safety Regulations", DocumentType.SAFETY_REGULATIONS, @@ -48,126 +28,4 @@ public class CorporateDocumentsView extends Main { add(createRow("Administration Functions Manual", DocumentType.ADMINISTRATION_FUNCTIONS_MANUAL, "Engineering Functions Manual", DocumentType.ENGINEERING_FUNCTIONS_MANUAL)); } - - private HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; - } - - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; - } - - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; - } - - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; - } - - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { - Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); - return saveButton; - } - - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); - } - - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; - } - - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); - } - } - - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); - } - - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); - } - - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); - } - - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; - } - - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); - } } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsView.java b/src/main/java/com/primefactorsolutions/views/DocumentsView.java index 6a41a66..545472c 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsView.java @@ -1,17 +1,174 @@ package com.primefactorsolutions.views; +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.service.DocumentService; +import com.vaadin.flow.component.Component; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.H2; +import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.FlexComponent; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.upload.Upload; +import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import java.io.IOException; +import java.util.Base64; + @SpringComponent @PermitAll @Scope("prototype") @PageTitle("Documents") @Route(value = "/documents/me", layout = MainLayout.class) -public class DocumentsView extends Main { +public abstract class DocumentsView extends Main { + private final DocumentService documentService; + private final MemoryBuffer buffer = new MemoryBuffer(); + private String lastUploadedFileName = null; + + public DocumentsView(final DocumentService documentService) { + this.documentService = documentService; + initializeLayout(); + } + + protected abstract void initializeLayout(); + + protected HorizontalLayout createRow( + final String title1, + final DocumentType type1, + final String title2, + final DocumentType type2) { + + HorizontalLayout row = new HorizontalLayout(); + row.add( + createDocumentSection(title1, type1), + createDocumentSection(title2, type2) + ); + return row; + } + + protected HorizontalLayout createRow(final String title1, final DocumentType type1) { + HorizontalLayout row = new HorizontalLayout(); + row.add(createDocumentSection(title1, type1)); + return row; + } + + private Div createDocumentSection(final String title, final DocumentType documentType) { + Div section = new Div(); + section.add(new H2(title)); + + Upload upload = createUploadComponent(); + Button viewButton = createViewButton(documentType); + Button saveButton = createSaveButton(viewButton, documentType); + + section.add(createLayout(upload), + createLayout(viewButton, new Button("Edit"), saveButton), + createAdditionalButtons()); + return section; + } + + private Upload createUploadComponent() { + Upload upload = new Upload(buffer); + upload.setMaxFiles(1); + upload.setAcceptedFileTypes(".pdf"); + upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); + return upload; + } + + private Button createViewButton(final DocumentType documentType) { + Button viewButton = new Button("View"); + viewButton.setEnabled(documentExists(documentType)); + viewButton.addClickListener(event -> viewDocument(documentType)); + return viewButton; + } + + private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + Button saveButton = new Button("Save"); + saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + return saveButton; + } + + private void handleUploadSuccess(final String fileName) { + lastUploadedFileName = fileName; + Notification.show("File uploaded successfully"); + } + + private HorizontalLayout createLayout(final Component... components) { + if (components.length != 1 && components.length != 3) { + throw new IllegalArgumentException("This method only accepts 1 or 3 components."); + } + HorizontalLayout layout = new HorizontalLayout(components); + layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); + return layout; + } + + private HorizontalLayout createAdditionalButtons() { + return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); + } + + private void saveFile(final DocumentType documentType, final Button viewButton) { + if (lastUploadedFileName == null) { + Notification.show("Please upload a file first."); + return; + } + try { + byte[] content = buffer.getInputStream().readAllBytes(); + documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + Notification.show("File saved successfully."); + viewButton.setEnabled(true); + } catch (IOException e) { + Notification.show("Error saving file: " + e.getMessage()); + } + } + + private boolean documentExists(final DocumentType documentType) { + return documentService.getAllDocuments().stream() + .anyMatch(doc -> doc.getDocumentType() == documentType); + } + + private void viewDocument(final DocumentType documentType) { + documentService.getAllDocuments().stream() + .filter(doc -> doc.getDocumentType() == documentType) + .findFirst() + .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + } + + private void showPdfDialog(final Document document) { + Dialog dialog = createDialog(document.getFileData()); + dialog.open(); + } + + private Dialog createDialog(final byte[] fileData) { + Dialog dialog = new Dialog(); + dialog.setModal(true); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + + IFrame pdfFrame = new IFrame(); + pdfFrame.setSrc(createPdfResource(fileData)); + pdfFrame.setWidth("800px"); + pdfFrame.setHeight("600px"); + + Button closeButton = new Button("Close", event -> dialog.close()); + VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); + layout.setAlignItems(FlexComponent.Alignment.CENTER); + + dialog.add(layout); + return dialog; + } + + private String createPdfResource(final byte[] fileData) { + return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + } + } diff --git a/src/main/java/com/primefactorsolutions/views/EmployeeView.java b/src/main/java/com/primefactorsolutions/views/EmployeeView.java index 42e95e2..8b18f3b 100644 --- a/src/main/java/com/primefactorsolutions/views/EmployeeView.java +++ b/src/main/java/com/primefactorsolutions/views/EmployeeView.java @@ -199,7 +199,7 @@ public class EmployeeView extends BeanValidationForm implements HasUrl private void saveEmployee() { if (validateForm()) { Employee employee = getEntity(); - employee.setStatusEmployee(status.getValue()); + employee.setStatus(status.getValue()); employeeService.createOrUpdate(employee); Notification.show(NOTIFICATION_SAVE_SUCCESS); getUI().ifPresent(ui -> ui.navigate(EmployeesListView.class)); @@ -233,7 +233,7 @@ public class EmployeeView extends BeanValidationForm implements HasUrl if ("edit".equals(action) && !s.isEmpty()) { saveButton.setVisible(true); editButton.setVisible(false); - status.setValue(employee.getStatusEmployee()); + status.setValue(employee.getStatus()); setFieldsEditable(); } else if ("view".equals(action) && !s.isEmpty()) { setFieldsReadOnly(); diff --git a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java index e3ad798..826be3d 100644 --- a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java @@ -1,46 +1,26 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; -import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.IOException; -import java.util.Base64; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("GovernmentDocumentsView") @Route(value = "/government-documents/me", layout = MainLayout.class) -public class GovernmentDocumentsView extends Main { - private final DocumentService documentService; - private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; +public class GovernmentDocumentsView extends DocumentsView { public GovernmentDocumentsView(final DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); + super(documentService); } - private void initializeLayout() { + @Override + protected void initializeLayout() { add(createRow( "General Labor Law", DocumentType.GENERAL_LABOR_LAW, "Supreme Decrees", DocumentType.SUPREME_DECREE @@ -56,126 +36,4 @@ public class GovernmentDocumentsView extends Main { "Regulatory Framework for Internship Development", DocumentType.INTERNSHIP_RULES )); } - - private HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; - } - - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; - } - - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; - } - - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; - } - - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { - Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); - return saveButton; - } - - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); - } - - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; - } - - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); - } - } - - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); - } - - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); - } - - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); - } - - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; - } - - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); - } } diff --git a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java index ca31c9e..b56535e 100644 --- a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java @@ -1,178 +1,30 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; -import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.IOException; -import java.util.Base64; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("PersonalDocuments") @Route(value = "/personal-documents/me", layout = MainLayout.class) -public class PersonalDocumentsView extends Main { - private final DocumentService documentService; - private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; +public class PersonalDocumentsView extends DocumentsView { public PersonalDocumentsView(final DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); + super(documentService); } - private void initializeLayout() { + @Override + protected void initializeLayout() { add(createRow("Identity Card", DocumentType.ID_CARD, "Background check certificate", DocumentType.BACKGROUND_CHECK_CERTIFICATE)); add(createRow("Pre-employment evaluation", DocumentType.PRE_EMPLOYMENT_EVALUATION, "Insurance registration form", DocumentType.INSURANCE_REGISTRATION_FORM)); - add(createRow()); - } - - private HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; - } - - private HorizontalLayout createRow() { - HorizontalLayout row = new HorizontalLayout(); - row.add(createDocumentSection("Insurance cancellation form", DocumentType.INSURANCE_CANCELLATION_FORM)); - return row; - } - - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; - } - - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; - } - - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; - } - - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { - Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); - return saveButton; - } - - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); - } - - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; - } - - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); - } - } - - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); - } - - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); - } - - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); - } - - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; - } - - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + add(createRow("Insurance cancellation form", DocumentType.INSURANCE_CANCELLATION_FORM)); } } diff --git a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java index 3148b50..9f8ec85 100644 --- a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java @@ -1,46 +1,26 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; -import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.IOException; -import java.util.Base64; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("ProfessionalDocuments") @Route(value = "/professional-documents/me", layout = MainLayout.class) -public class ProfessionalDocumentsView extends Main { - private final DocumentService documentService; - private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; +public class ProfessionalDocumentsView extends DocumentsView { public ProfessionalDocumentsView(final DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); + super(documentService); } - private void initializeLayout() { + @Override + protected void initializeLayout() { add(createRow("Professional Degree 1", DocumentType.PROFESSIONAL_DEGREE_1, "Professional Certificate 1", DocumentType.PROFESSIONAL_CERTIFICATE_1)); add(createRow("Professional Degree 2", DocumentType.PROFESSIONAL_DEGREE_2, @@ -48,126 +28,4 @@ public class ProfessionalDocumentsView extends Main { add(createRow("Professional Degree 3", DocumentType.PROFESSIONAL_DEGREE_3, "Professional Certificate 3", DocumentType.PROFESSIONAL_CERTIFICATE_3)); } - - private HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; - } - - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; - } - - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; - } - - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; - } - - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { - Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); - return saveButton; - } - - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); - } - - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; - } - - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); - } - } - - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); - } - - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); - } - - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); - } - - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; - } - - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); - } } diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java index 29421d8..c3b7892 100644 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java @@ -1,46 +1,26 @@ package com.primefactorsolutions.views; -import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; -import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; -import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; -import com.vaadin.flow.component.html.Main; -import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; -import com.vaadin.flow.component.upload.Upload; -import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; -import java.io.IOException; -import java.util.Base64; - @SpringComponent @PermitAll @Scope("prototype") @PageTitle("WorkDocuments") @Route(value = "/work-documents/me", layout = MainLayout.class) -public class WorkDocumentsView extends Main { - private final DocumentService documentService; - private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; +public class WorkDocumentsView extends DocumentsView { public WorkDocumentsView(final DocumentService documentService) { - this.documentService = documentService; - initializeLayout(); + super(documentService); } - private void initializeLayout() { + @Override + protected void initializeLayout() { add(createRow("PaySlips", DocumentType.PAY_SLIPS, "Employment Contract", DocumentType.EMPLOYMENT_CONTRACT)); add(createRow("Work Certificates", DocumentType.WORK_CERTIFICATES, @@ -48,126 +28,4 @@ public class WorkDocumentsView extends Main { add(createRow("Memorandums", DocumentType.MEMORANDUMS, "Contract Approval MTEPS", DocumentType.CONTRACT_APPROVAL_MTEPS)); } - - private HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; - } - - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; - } - - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; - } - - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; - } - - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { - Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); - return saveButton; - } - - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); - } - - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; - } - - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); - Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); - } - } - - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); - } - - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); - } - - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); - } - - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; - } - - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); - } } From e349503fb48890d3e0c29fe3b8088843a9bcee7a Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Mon, 23 Sep 2024 13:50:27 -0400 Subject: [PATCH 12/26] Change menu --- .../views/CorporateDocumentsView.java | 31 --------------- .../views/GovernmentDocumentsView.java | 39 ------------------- .../views/MainLayout.java | 22 ++--------- .../views/PersonalDocumentsView.java | 30 -------------- .../views/ProfessionalDocumentsView.java | 31 --------------- .../views/WorkDocumentsView.java | 31 --------------- 6 files changed, 3 insertions(+), 181 deletions(-) delete mode 100644 src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java delete mode 100644 src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java delete mode 100644 src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java delete mode 100644 src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java delete mode 100644 src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java diff --git a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java b/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java deleted file mode 100644 index 9810e85..0000000 --- a/src/main/java/com/primefactorsolutions/views/CorporateDocumentsView.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.primefactorsolutions.views; - -import com.primefactorsolutions.model.DocumentType; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; -import com.vaadin.flow.spring.annotation.SpringComponent; -import jakarta.annotation.security.PermitAll; -import org.springframework.context.annotation.Scope; - -@SpringComponent -@PermitAll -@Scope("prototype") -@PageTitle("CorporateDocuments") -@Route(value = "/corporate-documents/me", layout = MainLayout.class) -public class CorporateDocumentsView extends DocumentsView { - - public CorporateDocumentsView(final DocumentService documentService) { - super(documentService); - } - - @Override - protected void initializeLayout() { - add(createRow("General Labor Regulations", DocumentType.GENERAL_LABOR_REGULATIONS, - "Remote Work Guidelines", DocumentType.REMOTE_WORK_GUIDELINES)); - add(createRow("Safety Regulations", DocumentType.SAFETY_REGULATIONS, - "Human Resources Guidelines", DocumentType.HUMAN_RESOURCES_GUIDELINES)); - add(createRow("Administration Functions Manual", DocumentType.ADMINISTRATION_FUNCTIONS_MANUAL, - "Engineering Functions Manual", DocumentType.ENGINEERING_FUNCTIONS_MANUAL)); - } -} diff --git a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java b/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java deleted file mode 100644 index 826be3d..0000000 --- a/src/main/java/com/primefactorsolutions/views/GovernmentDocumentsView.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.primefactorsolutions.views; - -import com.primefactorsolutions.model.DocumentType; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; -import com.vaadin.flow.spring.annotation.SpringComponent; -import jakarta.annotation.security.PermitAll; -import org.springframework.context.annotation.Scope; - -@SpringComponent -@PermitAll -@Scope("prototype") -@PageTitle("GovernmentDocumentsView") -@Route(value = "/government-documents/me", layout = MainLayout.class) -public class GovernmentDocumentsView extends DocumentsView { - - public GovernmentDocumentsView(final DocumentService documentService) { - super(documentService); - } - - @Override - protected void initializeLayout() { - add(createRow( - "General Labor Law", DocumentType.GENERAL_LABOR_LAW, - "Supreme Decrees", DocumentType.SUPREME_DECREE - )); - - add(createRow( - "Regulatory Resolutions/Provisions", DocumentType.REGULATORY_RESOLUTION, - "Complementary Regulations", DocumentType.COMPLEMENTARY_REGULATION - )); - - add(createRow( - "General Law on Hygiene, Health, Occupational Safety, and Well-being", DocumentType.HEALTH_SAFETY_LAW, - "Regulatory Framework for Internship Development", DocumentType.INTERNSHIP_RULES - )); - } -} diff --git a/src/main/java/com/primefactorsolutions/views/MainLayout.java b/src/main/java/com/primefactorsolutions/views/MainLayout.java index 78e3e50..b5bbcf6 100644 --- a/src/main/java/com/primefactorsolutions/views/MainLayout.java +++ b/src/main/java/com/primefactorsolutions/views/MainLayout.java @@ -81,25 +81,10 @@ public class MainLayout extends AppLayout { SideNavItem admin = new SideNavItem("Admin", MainView.class, LineAwesomeIcon.SUPERSCRIPT_SOLID.create()); - admin.addItem(new SideNavItem("Requests", RequestsListView.class, - LineAwesomeIcon.TASKS_SOLID.create())); - admin.addItem(new SideNavItem("Timesheets", TimesheestReportView.class, - LineAwesomeIcon.HOURGLASS_END_SOLID.create())); - admin.addItem(new SideNavItem("Employees", EmployeesListView.class, + admin.addItem(new SideNavItem("Employees", EmployeeView.class, LineAwesomeIcon.USER_EDIT_SOLID.create())); - - SideNavItem documents = new SideNavItem("Documents", MainView.class, - LineAwesomeIcon.FILE_ALT_SOLID.create()); - documents.addItem(new SideNavItem("Personal Documents", PersonalDocumentsView.class, - LineAwesomeIcon.ID_CARD_SOLID.create())); - documents.addItem(new SideNavItem("Professional Documents", ProfessionalDocumentsView.class, - LineAwesomeIcon.BRIEFCASE_SOLID.create())); - documents.addItem(new SideNavItem("Work Documents", WorkDocumentsView.class, - LineAwesomeIcon.FOLDER_OPEN_SOLID.create())); - documents.addItem(new SideNavItem("Corporate Documents", CorporateDocumentsView.class, - LineAwesomeIcon.BUILDING_SOLID.create())); - documents.addItem(new SideNavItem("Government Documents", GovernmentDocumentsView.class, - LineAwesomeIcon.BALANCE_SCALE_SOLID.create())); + admin.addItem(new SideNavItem("Documents", DocumentsView.class, + LineAwesomeIcon.FILE_ALT_SOLID.create())); SideNavItem timeOff = new SideNavItem("My Time-off", TimeoffView.class, LineAwesomeIcon.PLANE_DEPARTURE_SOLID.create()); @@ -110,7 +95,6 @@ public class MainLayout extends AppLayout { nav.addItem(new SideNavItem("Home", MainView.class, LineAwesomeIcon.HOME_SOLID.create())); nav.addItem(admin); - nav.addItem(documents); nav.addItem(recruiting); nav.addItem(profile); nav.addItem(timesheet); diff --git a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java deleted file mode 100644 index b56535e..0000000 --- a/src/main/java/com/primefactorsolutions/views/PersonalDocumentsView.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.primefactorsolutions.views; - -import com.primefactorsolutions.model.DocumentType; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; -import com.vaadin.flow.spring.annotation.SpringComponent; -import jakarta.annotation.security.PermitAll; -import org.springframework.context.annotation.Scope; - -@SpringComponent -@PermitAll -@Scope("prototype") -@PageTitle("PersonalDocuments") -@Route(value = "/personal-documents/me", layout = MainLayout.class) -public class PersonalDocumentsView extends DocumentsView { - - public PersonalDocumentsView(final DocumentService documentService) { - super(documentService); - } - - @Override - protected void initializeLayout() { - add(createRow("Identity Card", DocumentType.ID_CARD, - "Background check certificate", DocumentType.BACKGROUND_CHECK_CERTIFICATE)); - add(createRow("Pre-employment evaluation", DocumentType.PRE_EMPLOYMENT_EVALUATION, - "Insurance registration form", DocumentType.INSURANCE_REGISTRATION_FORM)); - add(createRow("Insurance cancellation form", DocumentType.INSURANCE_CANCELLATION_FORM)); - } -} diff --git a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java b/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java deleted file mode 100644 index 9f8ec85..0000000 --- a/src/main/java/com/primefactorsolutions/views/ProfessionalDocumentsView.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.primefactorsolutions.views; - -import com.primefactorsolutions.model.DocumentType; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; -import com.vaadin.flow.spring.annotation.SpringComponent; -import jakarta.annotation.security.PermitAll; -import org.springframework.context.annotation.Scope; - -@SpringComponent -@PermitAll -@Scope("prototype") -@PageTitle("ProfessionalDocuments") -@Route(value = "/professional-documents/me", layout = MainLayout.class) -public class ProfessionalDocumentsView extends DocumentsView { - - public ProfessionalDocumentsView(final DocumentService documentService) { - super(documentService); - } - - @Override - protected void initializeLayout() { - add(createRow("Professional Degree 1", DocumentType.PROFESSIONAL_DEGREE_1, - "Professional Certificate 1", DocumentType.PROFESSIONAL_CERTIFICATE_1)); - add(createRow("Professional Degree 2", DocumentType.PROFESSIONAL_DEGREE_2, - "Professional Certificate 2", DocumentType.PROFESSIONAL_CERTIFICATE_2)); - add(createRow("Professional Degree 3", DocumentType.PROFESSIONAL_DEGREE_3, - "Professional Certificate 3", DocumentType.PROFESSIONAL_CERTIFICATE_3)); - } -} diff --git a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java b/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java deleted file mode 100644 index c3b7892..0000000 --- a/src/main/java/com/primefactorsolutions/views/WorkDocumentsView.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.primefactorsolutions.views; - -import com.primefactorsolutions.model.DocumentType; -import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; -import com.vaadin.flow.spring.annotation.SpringComponent; -import jakarta.annotation.security.PermitAll; -import org.springframework.context.annotation.Scope; - -@SpringComponent -@PermitAll -@Scope("prototype") -@PageTitle("WorkDocuments") -@Route(value = "/work-documents/me", layout = MainLayout.class) -public class WorkDocumentsView extends DocumentsView { - - public WorkDocumentsView(final DocumentService documentService) { - super(documentService); - } - - @Override - protected void initializeLayout() { - add(createRow("PaySlips", DocumentType.PAY_SLIPS, - "Employment Contract", DocumentType.EMPLOYMENT_CONTRACT)); - add(createRow("Work Certificates", DocumentType.WORK_CERTIFICATES, - "NDA", DocumentType.NDA)); - add(createRow("Memorandums", DocumentType.MEMORANDUMS, - "Contract Approval MTEPS", DocumentType.CONTRACT_APPROVAL_MTEPS)); - } -} From 2caa878c07399d38829f83a53f38e4921347b3c7 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 12:30:03 -0400 Subject: [PATCH 13/26] =?UTF-8?q?#30=20Perfil=20de=20Usuario=20Administrat?= =?UTF-8?q?ivo=20-=20A=C3=B1adir=20NUEVO=20Documento?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/EmployeeService.java | 4 + .../views/DocumentsView.java | 201 ++++++++---------- .../views/MainLayout.java | 8 +- 3 files changed, 95 insertions(+), 118 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/service/EmployeeService.java b/src/main/java/com/primefactorsolutions/service/EmployeeService.java index c30f9b8..45f3cd2 100644 --- a/src/main/java/com/primefactorsolutions/service/EmployeeService.java +++ b/src/main/java/com/primefactorsolutions/service/EmployeeService.java @@ -87,4 +87,8 @@ public class EmployeeService { ldapTemplate.modifyAttributes(buildDn(employee), new ModificationItem[] {item}); } + + public List findAllEmployees() { + return employeeRepository.findAll(); + } } \ No newline at end of file diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsView.java b/src/main/java/com/primefactorsolutions/views/DocumentsView.java index 545472c..37b11b5 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsView.java @@ -2,18 +2,16 @@ package com.primefactorsolutions.views; import com.primefactorsolutions.model.Document; import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.service.DocumentService; -import com.vaadin.flow.component.Component; +import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.button.Button; -import com.vaadin.flow.component.dialog.Dialog; -import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.IFrame; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; -import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.PageTitle; @@ -23,152 +21,129 @@ import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; import java.io.IOException; -import java.util.Base64; +import java.util.List; @SpringComponent @PermitAll @Scope("prototype") @PageTitle("Documents") -@Route(value = "/documents/me", layout = MainLayout.class) -public abstract class DocumentsView extends Main { - private final DocumentService documentService; +@Route(value = "/documents", layout = MainLayout.class) +public class DocumentsView extends Main { + + private final TextField fileName = new TextField("Document Name"); + private final ComboBox documentType = new ComboBox<>("Document Type"); + private final ComboBox employeeComboBox = new ComboBox<>("Employee"); private final MemoryBuffer buffer = new MemoryBuffer(); - private String lastUploadedFileName = null; + private final Upload uploadButton = new Upload(buffer); + private final DocumentService documentService; + private final EmployeeService employeeService; + private boolean fileUploaded = false; - public DocumentsView(final DocumentService documentService) { + public DocumentsView(final DocumentService documentService, final EmployeeService employeeService) { this.documentService = documentService; - initializeLayout(); + this.employeeService = employeeService; + initializeView(); + addComponents(); } - protected abstract void initializeLayout(); - - protected HorizontalLayout createRow( - final String title1, - final DocumentType type1, - final String title2, - final DocumentType type2) { - - HorizontalLayout row = new HorizontalLayout(); - row.add( - createDocumentSection(title1, type1), - createDocumentSection(title2, type2) - ); - return row; + private void initializeView() { + setFileNameProperties(); + setDocumentTypeProperties(); + setEmployeeComboBoxProperties(); + setUploadButtonProperties(); } - protected HorizontalLayout createRow(final String title1, final DocumentType type1) { - HorizontalLayout row = new HorizontalLayout(); - row.add(createDocumentSection(title1, type1)); - return row; + private void setFileNameProperties() { + fileName.setWidthFull(); } - private Div createDocumentSection(final String title, final DocumentType documentType) { - Div section = new Div(); - section.add(new H2(title)); - - Upload upload = createUploadComponent(); - Button viewButton = createViewButton(documentType); - Button saveButton = createSaveButton(viewButton, documentType); - - section.add(createLayout(upload), - createLayout(viewButton, new Button("Edit"), saveButton), - createAdditionalButtons()); - return section; + private void setDocumentTypeProperties() { + documentType.setItems(DocumentType.values()); + documentType.setWidthFull(); } - private Upload createUploadComponent() { - Upload upload = new Upload(buffer); - upload.setMaxFiles(1); - upload.setAcceptedFileTypes(".pdf"); - upload.addSucceededListener(event -> handleUploadSuccess(event.getFileName())); - return upload; + private void setEmployeeComboBoxProperties() { + List employees = employeeService.findAllEmployees(); + employeeComboBox.setItems(employees); + employeeComboBox.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName()); + employeeComboBox.setWidthFull(); } - private Button createViewButton(final DocumentType documentType) { - Button viewButton = new Button("View"); - viewButton.setEnabled(documentExists(documentType)); - viewButton.addClickListener(event -> viewDocument(documentType)); - return viewButton; + private void setUploadButtonProperties() { + uploadButton.setMaxFiles(1); + uploadButton.setAcceptedFileTypes(".pdf"); + uploadButton.addSucceededListener(event -> handleUploadSuccess()); } - private Button createSaveButton(final Button viewButton, final DocumentType documentType) { + private void addComponents() { + H2 title = new H2("Edit Documents"); + Button saveButton = createSaveButton(); + Button closeButton = createCloseButton(); + HorizontalLayout buttonLayout = new HorizontalLayout(saveButton, closeButton); + + add(title, fileName, documentType, employeeComboBox, uploadButton, buttonLayout); + } + + private Button createSaveButton() { Button saveButton = new Button("Save"); - saveButton.addClickListener(event -> saveFile(documentType, viewButton)); + saveButton.addClickListener(event -> saveDocument()); return saveButton; } - private void handleUploadSuccess(final String fileName) { - lastUploadedFileName = fileName; - Notification.show("File uploaded successfully"); + private Button createCloseButton() { + Button closeButton = new Button("Close"); + closeButton.addClickListener(event -> closeForm()); + return closeButton; } - private HorizontalLayout createLayout(final Component... components) { - if (components.length != 1 && components.length != 3) { - throw new IllegalArgumentException("This method only accepts 1 or 3 components."); - } - HorizontalLayout layout = new HorizontalLayout(components); - layout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER); - return layout; + private void handleUploadSuccess() { + fileUploaded = true; + Notification.show("File uploaded successfully."); } - private HorizontalLayout createAdditionalButtons() { - return createLayout(new Button("Print"), new Button("Download"), new Button("Delete")); - } - - private void saveFile(final DocumentType documentType, final Button viewButton) { - if (lastUploadedFileName == null) { - Notification.show("Please upload a file first."); - return; - } - try { - byte[] content = buffer.getInputStream().readAllBytes(); - documentService.saveDocument(new Document(lastUploadedFileName, documentType, content)); + private void saveDocument() { + if (isFormValid()) { + Document document = createDocument(); + documentService.saveDocument(document); Notification.show("File saved successfully."); - viewButton.setEnabled(true); - } catch (IOException e) { - Notification.show("Error saving file: " + e.getMessage()); + clearForm(); + } else { + Notification.show("Save failed: Please complete all fields and upload a file."); } } - private boolean documentExists(final DocumentType documentType) { - return documentService.getAllDocuments().stream() - .anyMatch(doc -> doc.getDocumentType() == documentType); + private boolean isFormValid() { + return !fileName.isEmpty() + && documentType.getValue() != null + && employeeComboBox.getValue() != null + && fileUploaded; } - private void viewDocument(final DocumentType documentType) { - documentService.getAllDocuments().stream() - .filter(doc -> doc.getDocumentType() == documentType) - .findFirst() - .ifPresentOrElse(this::showPdfDialog, () -> Notification.show("Document not found.")); + private Document createDocument() { + Document document = new Document(); + document.setFileName(fileName.getValue()); + document.setDocumentType(documentType.getValue()); + document.setFileData(readFileData()); + return document; } - private void showPdfDialog(final Document document) { - Dialog dialog = createDialog(document.getFileData()); - dialog.open(); + private byte[] readFileData() { + try { + return buffer.getInputStream().readAllBytes(); + } catch (IOException e) { + Notification.show("Error reading file data."); + return new byte[0]; + } } - private Dialog createDialog(final byte[] fileData) { - Dialog dialog = new Dialog(); - dialog.setModal(true); - dialog.setCloseOnEsc(true); - dialog.setCloseOnOutsideClick(true); - - IFrame pdfFrame = new IFrame(); - pdfFrame.setSrc(createPdfResource(fileData)); - pdfFrame.setWidth("800px"); - pdfFrame.setHeight("600px"); - - Button closeButton = new Button("Close", event -> dialog.close()); - VerticalLayout layout = new VerticalLayout(pdfFrame, closeButton); - layout.setAlignItems(FlexComponent.Alignment.CENTER); - - dialog.add(layout); - return dialog; + private void clearForm() { + fileName.clear(); + documentType.clear(); + employeeComboBox.clear(); + fileUploaded = false; } - private String createPdfResource(final byte[] fileData) { - return "data:application/pdf;base64," + Base64.getEncoder().encodeToString(fileData); + private void closeForm() { + clearForm(); } - } - diff --git a/src/main/java/com/primefactorsolutions/views/MainLayout.java b/src/main/java/com/primefactorsolutions/views/MainLayout.java index b5bbcf6..36aaa54 100644 --- a/src/main/java/com/primefactorsolutions/views/MainLayout.java +++ b/src/main/java/com/primefactorsolutions/views/MainLayout.java @@ -18,9 +18,7 @@ import com.vaadin.flow.theme.lumo.LumoUtility; import org.springframework.security.core.userdetails.UserDetails; import org.vaadin.lineawesome.LineAwesomeIcon; -/** - * The main view is a top-level placeholder for other views. - */ + public class MainLayout extends AppLayout { private final transient AuthenticationContext authContext; @@ -81,8 +79,8 @@ public class MainLayout extends AppLayout { SideNavItem admin = new SideNavItem("Admin", MainView.class, LineAwesomeIcon.SUPERSCRIPT_SOLID.create()); - admin.addItem(new SideNavItem("Employees", EmployeeView.class, - LineAwesomeIcon.USER_EDIT_SOLID.create())); +// admin.addItem(new SideNavItem("Employees", EmployeeView.class, +// LineAwesomeIcon.USER_EDIT_SOLID.create())); admin.addItem(new SideNavItem("Documents", DocumentsView.class, LineAwesomeIcon.FILE_ALT_SOLID.create())); From 514e4eaf4937a539fa72108f8f4706bd3b0d9e3e Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 17:07:53 -0400 Subject: [PATCH 14/26] #29 Perfil de Empleado Administrativo - LISTAR Documentos --- .../primefactorsolutions/model/Document.java | 3 + .../service/DocumentService.java | 34 ++++- .../{DocumentsView.java => DocumentView.java} | 62 +++++--- .../views/DocumentsListView.java | 143 ++++++++++++++++++ .../views/MainLayout.java | 2 +- 5 files changed, 215 insertions(+), 29 deletions(-) rename src/main/java/com/primefactorsolutions/views/{DocumentsView.java => DocumentView.java} (73%) create mode 100644 src/main/java/com/primefactorsolutions/views/DocumentsListView.java diff --git a/src/main/java/com/primefactorsolutions/model/Document.java b/src/main/java/com/primefactorsolutions/model/Document.java index 3b8b200..2e3b222 100644 --- a/src/main/java/com/primefactorsolutions/model/Document.java +++ b/src/main/java/com/primefactorsolutions/model/Document.java @@ -13,6 +13,9 @@ public class Document extends BaseEntity { private String fileName; @Enumerated(EnumType.STRING) private DocumentType documentType; + @ManyToOne + @JoinColumn(name = "employee_id", nullable = false) + private Employee employee; @Lob @Column(columnDefinition = "BLOB") private byte[] fileData; diff --git a/src/main/java/com/primefactorsolutions/service/DocumentService.java b/src/main/java/com/primefactorsolutions/service/DocumentService.java index 838840f..efdf0cc 100644 --- a/src/main/java/com/primefactorsolutions/service/DocumentService.java +++ b/src/main/java/com/primefactorsolutions/service/DocumentService.java @@ -2,20 +2,20 @@ package com.primefactorsolutions.service; import com.primefactorsolutions.model.Document; import com.primefactorsolutions.repositories.DocumentRepository; +import lombok.AllArgsConstructor; +import org.apache.commons.beanutils.BeanComparator; import org.springframework.stereotype.Service; +import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Optional; @Service +@AllArgsConstructor public class DocumentService { private final DocumentRepository documentRepository; - public DocumentService(final DocumentRepository documentRepository) { - this.documentRepository = documentRepository; - } - public void saveDocument(final Document newDocument) { documentRepository.save(newDocument); } @@ -24,7 +24,29 @@ public class DocumentService { return documentRepository.findAll(); } - public Optional getDocumentById(final UUID id) { - return documentRepository.findById(id); + public Document getDocument(final UUID id) { + Optional employee = documentRepository.findById(id); + return employee.orElse(null); + } + + public List findDocuments( + final int start, final int pageSize, final String sortProperty, final boolean asc) { + List documents = documentRepository.findAll(); + + int end = Math.min(start + pageSize, documents.size()); + documents.sort(new BeanComparator<>(sortProperty)); + + if (!asc) { + Collections.reverse(documents); + } + + return documents.subList(start, end); + } + + public List findDocuments(final int start, final int pageSize) { + List employees = documentRepository.findAll(); + + int end = Math.min(start + pageSize, employees.size()); + return employees.subList(start, end); } } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java similarity index 73% rename from src/main/java/com/primefactorsolutions/views/DocumentsView.java rename to src/main/java/com/primefactorsolutions/views/DocumentView.java index 37b11b5..4b9014f 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -5,31 +5,32 @@ import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.service.DocumentService; import com.primefactorsolutions.service.EmployeeService; +import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.html.H2; -import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.notification.Notification; -import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; -import com.vaadin.flow.router.PageTitle; -import com.vaadin.flow.router.Route; +import com.vaadin.flow.router.*; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import org.vaadin.firitin.form.BeanValidationForm; import java.io.IOException; import java.util.List; +import java.util.UUID; @SpringComponent @PermitAll @Scope("prototype") -@PageTitle("Documents") -@Route(value = "/documents", layout = MainLayout.class) -public class DocumentsView extends Main { +@PageTitle("Document") +@Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) +public class DocumentView extends BeanValidationForm implements HasUrlParameter { + private final H2 title = new H2("Edit Documents"); private final TextField fileName = new TextField("Document Name"); private final ComboBox documentType = new ComboBox<>("Document Type"); private final ComboBox employeeComboBox = new ComboBox<>("Employee"); @@ -39,11 +40,11 @@ public class DocumentsView extends Main { private final EmployeeService employeeService; private boolean fileUploaded = false; - public DocumentsView(final DocumentService documentService, final EmployeeService employeeService) { + public DocumentView(final DocumentService documentService, final EmployeeService employeeService) { + super(Document.class); this.documentService = documentService; this.employeeService = employeeService; initializeView(); - addComponents(); } private void initializeView() { @@ -75,27 +76,27 @@ public class DocumentsView extends Main { uploadButton.addSucceededListener(event -> handleUploadSuccess()); } - private void addComponents() { - H2 title = new H2("Edit Documents"); - Button saveButton = createSaveButton(); - Button closeButton = createCloseButton(); - HorizontalLayout buttonLayout = new HorizontalLayout(saveButton, closeButton); - - add(title, fileName, documentType, employeeComboBox, uploadButton, buttonLayout); - } - - private Button createSaveButton() { + protected Button createSaveButton() { Button saveButton = new Button("Save"); saveButton.addClickListener(event -> saveDocument()); return saveButton; } - private Button createCloseButton() { + protected Button createCloseButton() { Button closeButton = new Button("Close"); closeButton.addClickListener(event -> closeForm()); return closeButton; } + + private void closeForm() { + navigateToDocumentsListView(); + } + + private void navigateToDocumentsListView() { + getUI().ifPresent(ui -> ui.navigate(DocumentsListView.class)); + } + private void handleUploadSuccess() { fileUploaded = true; Notification.show("File uploaded successfully."); @@ -104,6 +105,7 @@ public class DocumentsView extends Main { private void saveDocument() { if (isFormValid()) { Document document = createDocument(); + document.setEmployee(employeeComboBox.getValue()); documentService.saveDocument(document); Notification.show("File saved successfully."); clearForm(); @@ -143,7 +145,23 @@ public class DocumentsView extends Main { fileUploaded = false; } - private void closeForm() { - clearForm(); + + @Override + public void setParameter(final BeforeEvent beforeEvent, final String action) { + final RouteParameters params = beforeEvent.getRouteParameters(); + final String s = params.get("documentId").orElse(null); + + if ("new".equals(action)) { + setEntityWithEnabledSave(new Document()); + } else { + UUID documentId = UUID.fromString(s); + var document = documentService.getDocument(documentId); + setEntityWithEnabledSave(document); + } + } + + @Override + protected List getFormComponents() { + return List.of(title, fileName, documentType, employeeComboBox, uploadButton, createCloseButton()); } } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java new file mode 100644 index 0000000..0a311b1 --- /dev/null +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -0,0 +1,143 @@ +package com.primefactorsolutions.views; + +import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.model.Employee; +import com.primefactorsolutions.service.DocumentService; +import com.primefactorsolutions.service.EmployeeService; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.combobox.ComboBox; +import com.vaadin.flow.component.html.Main; +import com.vaadin.flow.component.html.Span; +import com.vaadin.flow.router.PageTitle; +import com.vaadin.flow.router.Route; +import com.vaadin.flow.spring.annotation.SpringComponent; +import org.vaadin.firitin.components.grid.PagingGrid; +import com.vaadin.flow.component.grid.GridSortOrder; +import com.vaadin.flow.data.provider.SortDirection; +import jakarta.annotation.security.PermitAll; +import org.springframework.context.annotation.Scope; + +import java.util.List; + + +@SpringComponent +@Scope("prototype") +@PageTitle("Documents") +@Route(value = "/documents", layout = MainLayout.class) +@PermitAll +public class DocumentsListView extends Main { + + private final DocumentService documentService; + private final EmployeeService employeeService; + private final PagingGrid documentGrid = new PagingGrid<>(Document.class); + + public DocumentsListView(final DocumentService documentService, final EmployeeService employeeService) { + this.documentService = documentService; + this.employeeService = employeeService; + initializeView(); + updateDocumentGrid(); + } + + private void initializeView() { + configureDocumentGrid(); + add(createActionButton("Add Document", this::navigateToAddDocumentView)); + add(createDocumentTypeFilter()); + add(createEmployeeFilter()); + add(documentGrid); + } + + private void configureDocumentGrid() { + documentGrid.setColumns("fileName", "documentType"); + documentGrid.addComponentColumn(this::createEmployeeSpan).setHeader("Employee"); + addDocumentActionColumn("View", this::navigateToDocumentView); + addDocumentActionColumn("Edit", this::navigateToEditDocumentView); + addDocumentActionColumn("Download", this::navigateToDownloadDocumentView); + configurePagination(); + } + + private Span createEmployeeSpan(final Document document) { + Employee employee = document.getEmployee(); + String employeeName = employee.getFirstName() + " " + employee.getLastName(); + return new Span(employeeName); + } + + + private void addDocumentActionColumn(final String label, final DocumentActionHandler handler) { + documentGrid.addComponentColumn(document -> createActionButton(label, () -> handler.handle(document))); + } + + private Button createActionButton(final String label, final Runnable onClickAction) { + Button actionButton = new Button(label); + actionButton.addClickListener(event -> onClickAction.run()); + return actionButton; + } + + private ComboBox createDocumentTypeFilter() { + ComboBox documentTypeFilter = new ComboBox<>("Document Type"); + documentTypeFilter.setItems(DocumentType.values()); + documentTypeFilter.addValueChangeListener(event -> updateDocumentGrid()); + return documentTypeFilter; + } + + private ComboBox createEmployeeFilter() { + ComboBox employeeFilter = new ComboBox<>("Employee"); + List employees = employeeService.findAllEmployees(); + employeeFilter.setItems(employees); + employeeFilter.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName()); + employeeFilter.addValueChangeListener(event -> updateDocumentGrid()); + return employeeFilter; + } + + private void navigateToEditDocumentView(final Document document) { + navigateToDocumentView(document, "edit"); + } + + private void navigateToDocumentView(final Document document) { + navigateToDocumentView(document, "view"); + } + + private void navigateToDocumentView(final Document document, final String action) { + getUI().ifPresent(ui -> ui.navigate(DocumentView.class, document.getId().toString() + "/" + action)); + } + + private void navigateToDownloadDocumentView(final Document document) { + // No operation + } + + private void navigateToAddDocumentView() { + getUI().ifPresent(ui -> ui.navigate(DocumentView.class, "new")); + } + + private void configurePagination() { + documentGrid.setPaginationBarMode(PagingGrid.PaginationBarMode.BOTTOM); + documentGrid.setPageSize(5); + } + + private void updateDocumentGrid() { + documentGrid.setPagingDataProvider((page, pageSize) -> fetchDocuments((int) page, pageSize)); + } + + private List fetchDocuments(final int page, final int size) { + int startIndex = page * size; + return isSortOrderPresent() + ? fetchSortedDocuments(startIndex, size) + : documentService.findDocuments(startIndex, size); + } + + private boolean isSortOrderPresent() { + return !documentGrid.getSortOrder().isEmpty(); + } + + private List fetchSortedDocuments(final int start, final int pageSize) { + GridSortOrder sortOrder = documentGrid.getSortOrder().getFirst(); + return documentService.findDocuments(start, pageSize, + sortOrder.getSorted().getKey(), + sortOrder.getDirection() == SortDirection.ASCENDING); + } + + @FunctionalInterface + private interface DocumentActionHandler { + void handle(Document document); + } +} \ No newline at end of file diff --git a/src/main/java/com/primefactorsolutions/views/MainLayout.java b/src/main/java/com/primefactorsolutions/views/MainLayout.java index 36aaa54..42abb45 100644 --- a/src/main/java/com/primefactorsolutions/views/MainLayout.java +++ b/src/main/java/com/primefactorsolutions/views/MainLayout.java @@ -81,7 +81,7 @@ public class MainLayout extends AppLayout { LineAwesomeIcon.SUPERSCRIPT_SOLID.create()); // admin.addItem(new SideNavItem("Employees", EmployeeView.class, // LineAwesomeIcon.USER_EDIT_SOLID.create())); - admin.addItem(new SideNavItem("Documents", DocumentsView.class, + admin.addItem(new SideNavItem("Documents", DocumentsListView.class, LineAwesomeIcon.FILE_ALT_SOLID.create())); SideNavItem timeOff = new SideNavItem("My Time-off", TimeoffView.class, From 45987ccad989c939f004bb15a6bb88d1c5fb14dd Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 17:25:43 -0400 Subject: [PATCH 15/26] #29 Perfil de Empleado Administrativo - LISTAR Documentos (correccionse) --- .../com/primefactorsolutions/views/DocumentsListView.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index 0a311b1..101197d 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -7,16 +7,16 @@ import com.primefactorsolutions.service.DocumentService; import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; +import com.vaadin.flow.component.grid.GridSortOrder; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; +import com.vaadin.flow.data.provider.SortDirection; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.spring.annotation.SpringComponent; -import org.vaadin.firitin.components.grid.PagingGrid; -import com.vaadin.flow.component.grid.GridSortOrder; -import com.vaadin.flow.data.provider.SortDirection; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import org.vaadin.firitin.components.grid.PagingGrid; import java.util.List; From f3bda474d0dad80474ff54654bd13fa00e888483 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 19:07:58 -0400 Subject: [PATCH 16/26] #32 Perfil de Personal Administrativo - VER Documento --- .../com/primefactorsolutions/views/DocumentView.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index 4b9014f..b2b84ca 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -157,9 +157,21 @@ public class DocumentView extends BeanValidationForm implements HasUrl UUID documentId = UUID.fromString(s); var document = documentService.getDocument(documentId); setEntityWithEnabledSave(document); + + if ("edit".equals(action) && !s.isEmpty()) { + setFieldsReadOnly(false); + } else if ("view".equals(action) && !s.isEmpty()) { + setFieldsReadOnly(true); + } } } + private void setFieldsReadOnly(final boolean option) { + fileName.setReadOnly(option); + documentType.setReadOnly(option); + employeeComboBox.setReadOnly(option); + } + @Override protected List getFormComponents() { return List.of(title, fileName, documentType, employeeComboBox, uploadButton, createCloseButton()); From af3f13773bb06977a64fc5546089a9ca561410c4 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 19:26:18 -0400 Subject: [PATCH 17/26] #29 Perfil de Empleado Administrativo - LISTAR Documentos (implementacion de download) --- .../views/DocumentsListView.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index 101197d..229d333 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -18,6 +18,7 @@ import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; import org.vaadin.firitin.components.grid.PagingGrid; +import java.util.Base64; import java.util.List; @@ -52,7 +53,7 @@ public class DocumentsListView extends Main { documentGrid.addComponentColumn(this::createEmployeeSpan).setHeader("Employee"); addDocumentActionColumn("View", this::navigateToDocumentView); addDocumentActionColumn("Edit", this::navigateToEditDocumentView); - addDocumentActionColumn("Download", this::navigateToDownloadDocumentView); + addDocumentActionColumn("Download", this::downloadDocument); configurePagination(); } @@ -136,6 +137,26 @@ public class DocumentsListView extends Main { sortOrder.getDirection() == SortDirection.ASCENDING); } + private void downloadDocument(final Document document) { + String base64Data = Base64.getEncoder().encodeToString(document.getFileData()); + String jsCode = "var byteCharacters = atob('" + base64Data + "');" + + "var byteNumbers = new Array(byteCharacters.length);" + + "for (var i = 0; i < byteCharacters.length; i++) {" + + " byteNumbers[i] = byteCharacters.charCodeAt(i);" + + "}" + + "var byteArray = new Uint8Array(byteNumbers);" + + "var blob = new Blob([byteArray], { type: 'application/pdf' });" + + "var url = URL.createObjectURL(blob);" + + "var a = document.createElement('a');" + + "a.href = url;" + + "a.download = '" + document.getFileName() + "';" + + "document.body.appendChild(a);" + + "a.click();" + + "document.body.removeChild(a);" + + "URL.revokeObjectURL(url);"; + getElement().executeJs(jsCode); + } + @FunctionalInterface private interface DocumentActionHandler { void handle(Document document); From f0b41743c752f1689ff28fb39cd2982529ddf1f7 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 24 Sep 2024 20:44:16 -0400 Subject: [PATCH 18/26] =?UTF-8?q?#30=20Perfil=20de=20Usuario=20Administrat?= =?UTF-8?q?ivo=20-=20A=C3=B1adir=20NUEVO=20Documento=20(agregar=20creador?= =?UTF-8?q?=20del=20registro=20del=20doc)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../primefactorsolutions/model/Document.java | 1 + .../views/DocumentView.java | 12 ++++++- .../views/DocumentsListView.java | 32 +++++++++---------- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/Document.java b/src/main/java/com/primefactorsolutions/model/Document.java index 2e3b222..61620fa 100644 --- a/src/main/java/com/primefactorsolutions/model/Document.java +++ b/src/main/java/com/primefactorsolutions/model/Document.java @@ -19,4 +19,5 @@ public class Document extends BaseEntity { @Lob @Column(columnDefinition = "BLOB") private byte[] fileData; + private String creator; } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index b2b84ca..fdf29d5 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -17,7 +17,9 @@ import com.vaadin.flow.router.*; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; +import org.springframework.security.core.userdetails.UserDetails; import org.vaadin.firitin.form.BeanValidationForm; +import com.vaadin.flow.spring.security.AuthenticationContext; import java.io.IOException; import java.util.List; @@ -38,12 +40,16 @@ public class DocumentView extends BeanValidationForm implements HasUrl private final Upload uploadButton = new Upload(buffer); private final DocumentService documentService; private final EmployeeService employeeService; + private final AuthenticationContext authContext; private boolean fileUploaded = false; - public DocumentView(final DocumentService documentService, final EmployeeService employeeService) { + public DocumentView(final DocumentService documentService, + final EmployeeService employeeService, + final AuthenticationContext authContext) { super(Document.class); this.documentService = documentService; this.employeeService = employeeService; + this.authContext = authContext; initializeView(); } @@ -106,6 +112,10 @@ public class DocumentView extends BeanValidationForm implements HasUrl if (isFormValid()) { Document document = createDocument(); document.setEmployee(employeeComboBox.getValue()); + authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { + String creator = user.getUsername(); + document.setCreator(creator); // Asignar el nombre del creador al documento + }); documentService.saveDocument(document); Notification.show("File saved successfully."); clearForm(); diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index 229d333..64c5f9f 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -49,7 +49,7 @@ public class DocumentsListView extends Main { } private void configureDocumentGrid() { - documentGrid.setColumns("fileName", "documentType"); + documentGrid.setColumns("fileName", "documentType", "creator"); documentGrid.addComponentColumn(this::createEmployeeSpan).setHeader("Employee"); addDocumentActionColumn("View", this::navigateToDocumentView); addDocumentActionColumn("Edit", this::navigateToEditDocumentView); @@ -139,21 +139,21 @@ public class DocumentsListView extends Main { private void downloadDocument(final Document document) { String base64Data = Base64.getEncoder().encodeToString(document.getFileData()); - String jsCode = "var byteCharacters = atob('" + base64Data + "');" + - "var byteNumbers = new Array(byteCharacters.length);" + - "for (var i = 0; i < byteCharacters.length; i++) {" + - " byteNumbers[i] = byteCharacters.charCodeAt(i);" + - "}" + - "var byteArray = new Uint8Array(byteNumbers);" + - "var blob = new Blob([byteArray], { type: 'application/pdf' });" + - "var url = URL.createObjectURL(blob);" + - "var a = document.createElement('a');" + - "a.href = url;" + - "a.download = '" + document.getFileName() + "';" + - "document.body.appendChild(a);" + - "a.click();" + - "document.body.removeChild(a);" + - "URL.revokeObjectURL(url);"; + String jsCode = "var byteCharacters = atob('" + base64Data + "');" + + "var byteNumbers = new Array(byteCharacters.length);" + + "for (var i = 0; i < byteCharacters.length; i++) {" + + " byteNumbers[i] = byteCharacters.charCodeAt(i);" + + "}" + + "var byteArray = new Uint8Array(byteNumbers);" + + "var blob = new Blob([byteArray], { type: 'application/pdf' });" + + "var url = URL.createObjectURL(blob);" + + "var a = document.createElement('a');" + + "a.href = url;" + + "a.download = '" + document.getFileName() + "';" + + "document.body.appendChild(a);" + + "a.click();" + + "document.body.removeChild(a);" + + "URL.revokeObjectURL(url);"; getElement().executeJs(jsCode); } From 4241e7b52b1d7f9958aa6b70d5d8c4f733dca0f5 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Wed, 25 Sep 2024 18:50:59 -0400 Subject: [PATCH 19/26] #29 Perfil de Empleado Administrativo - LISTAR Documentos (correccion download, view, edit) --- .../views/DocumentView.java | 30 +++++++++++++++---- .../views/DocumentsListView.java | 29 ++++++++---------- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index fdf29d5..fe8d8a5 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -42,6 +42,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl private final EmployeeService employeeService; private final AuthenticationContext authContext; private boolean fileUploaded = false; + private Button saveButton; public DocumentView(final DocumentService documentService, final EmployeeService employeeService, @@ -83,7 +84,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl } protected Button createSaveButton() { - Button saveButton = new Button("Save"); + saveButton = new Button("Save"); saveButton.addClickListener(event -> saveDocument()); return saveButton; } @@ -110,13 +111,18 @@ public class DocumentView extends BeanValidationForm implements HasUrl private void saveDocument() { if (isFormValid()) { - Document document = createDocument(); + Document document = getEntity(); // Obtenemos el documento actual del formulario + document.setFileName(fileName.getValue()); + document.setDocumentType(documentType.getValue()); document.setEmployee(employeeComboBox.getValue()); + document.setFileData(readFileData()); // Actualizamos el archivo si es necesario + authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { String creator = user.getUsername(); - document.setCreator(creator); // Asignar el nombre del creador al documento + document.setCreator(creator); // Asignar el nombre del creador al documento si corresponde }); - documentService.saveDocument(document); + + documentService.saveDocument(document); // Guardamos el documento actualizado Notification.show("File saved successfully."); clearForm(); } else { @@ -155,6 +161,18 @@ public class DocumentView extends BeanValidationForm implements HasUrl fileUploaded = false; } + private void checkFormModifications() { + boolean hasModifications = !fileName.isEmpty() + && documentType.getValue() != null + && employeeComboBox.getValue() != null; + + if (hasModifications || fileUploaded) { + saveButton.setEnabled(true); + } else { + saveButton.setEnabled(false); + } + } + @Override public void setParameter(final BeforeEvent beforeEvent, final String action) { @@ -166,7 +184,8 @@ public class DocumentView extends BeanValidationForm implements HasUrl } else { UUID documentId = UUID.fromString(s); var document = documentService.getDocument(documentId); - setEntityWithEnabledSave(document); + setEntity(document); + employeeComboBox.setValue(document.getEmployee()); if ("edit".equals(action) && !s.isEmpty()) { setFieldsReadOnly(false); @@ -174,6 +193,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl setFieldsReadOnly(true); } } + checkFormModifications(); } private void setFieldsReadOnly(final boolean option) { diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index 64c5f9f..7159229 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -8,16 +8,20 @@ import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.grid.GridSortOrder; +import com.vaadin.flow.component.html.Anchor; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.data.provider.SortDirection; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; +import com.vaadin.flow.server.StreamRegistration; +import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.spring.annotation.SpringComponent; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; import org.vaadin.firitin.components.grid.PagingGrid; +import java.io.ByteArrayInputStream; import java.util.Base64; import java.util.List; @@ -138,23 +142,14 @@ public class DocumentsListView extends Main { } private void downloadDocument(final Document document) { - String base64Data = Base64.getEncoder().encodeToString(document.getFileData()); - String jsCode = "var byteCharacters = atob('" + base64Data + "');" - + "var byteNumbers = new Array(byteCharacters.length);" - + "for (var i = 0; i < byteCharacters.length; i++) {" - + " byteNumbers[i] = byteCharacters.charCodeAt(i);" - + "}" - + "var byteArray = new Uint8Array(byteNumbers);" - + "var blob = new Blob([byteArray], { type: 'application/pdf' });" - + "var url = URL.createObjectURL(blob);" - + "var a = document.createElement('a');" - + "a.href = url;" - + "a.download = '" + document.getFileName() + "';" - + "document.body.appendChild(a);" - + "a.click();" - + "document.body.removeChild(a);" - + "URL.revokeObjectURL(url);"; - getElement().executeJs(jsCode); + StreamResource resource = new StreamResource(document.getFileName(), + () -> new ByteArrayInputStream(document.getFileData())); + resource.setContentType("application/pdf"); + resource.setHeader("Content-Disposition", "attachment; filename=\"" + document.getFileName() + ".pdf\""); + getUI().ifPresent(ui -> { + StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource); + ui.getPage().open(registration.getResourceUri().toString()); + }); } @FunctionalInterface From 1519d8299382a151db9ec9d846f1cdc8806e2300 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Fri, 27 Sep 2024 00:07:27 -0400 Subject: [PATCH 20/26] #29 Perfil de Empleado Administrativo - LISTAR Documentos (filtar por tipo de documento y empleado) --- .../model/DocumentType.java | 1 + .../service/DocumentService.java | 19 ++++ .../views/DocumentsListView.java | 86 ++++++++++++++----- 3 files changed, 85 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/model/DocumentType.java b/src/main/java/com/primefactorsolutions/model/DocumentType.java index 138439e..96c8ce3 100644 --- a/src/main/java/com/primefactorsolutions/model/DocumentType.java +++ b/src/main/java/com/primefactorsolutions/model/DocumentType.java @@ -1,6 +1,7 @@ package com.primefactorsolutions.model; public enum DocumentType { + All, ID_CARD, PAY_STUB, PAY_SLIPS, diff --git a/src/main/java/com/primefactorsolutions/service/DocumentService.java b/src/main/java/com/primefactorsolutions/service/DocumentService.java index efdf0cc..78f5717 100644 --- a/src/main/java/com/primefactorsolutions/service/DocumentService.java +++ b/src/main/java/com/primefactorsolutions/service/DocumentService.java @@ -1,6 +1,8 @@ package com.primefactorsolutions.service; import com.primefactorsolutions.model.Document; +import com.primefactorsolutions.model.DocumentType; +import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.repositories.DocumentRepository; import lombok.AllArgsConstructor; import org.apache.commons.beanutils.BeanComparator; @@ -10,6 +12,7 @@ import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Optional; +import java.util.stream.Collectors; @Service @AllArgsConstructor @@ -49,4 +52,20 @@ public class DocumentService { int end = Math.min(start + pageSize, employees.size()); return employees.subList(start, end); } + + public List findDocumentBy(DocumentType documentType, Employee employee, int start, int pageSize) { + List documents = documentRepository.findAll(); + if (documentType != null) { + documents = documents.stream() + .filter(doc -> doc.getDocumentType().equals(documentType)) + .collect(Collectors.toList()); + } + if (employee != null) { + documents = documents.stream() + .filter(doc -> doc.getEmployee().equals(employee)) + .collect(Collectors.toList()); + } + int end = Math.min(start + pageSize, documents.size()); + return documents.subList(start, end); + } } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index 7159229..c786ca6 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -5,12 +5,13 @@ import com.primefactorsolutions.model.DocumentType; import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.service.DocumentService; import com.primefactorsolutions.service.EmployeeService; +import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.grid.GridSortOrder; -import com.vaadin.flow.component.html.Anchor; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; +import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.data.provider.SortDirection; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; @@ -22,7 +23,6 @@ import org.springframework.context.annotation.Scope; import org.vaadin.firitin.components.grid.PagingGrid; import java.io.ByteArrayInputStream; -import java.util.Base64; import java.util.List; @@ -36,12 +36,14 @@ public class DocumentsListView extends Main { private final DocumentService documentService; private final EmployeeService employeeService; private final PagingGrid documentGrid = new PagingGrid<>(Document.class); + private ComboBox employeeFilter; + private ComboBox documentTypeFilter; public DocumentsListView(final DocumentService documentService, final EmployeeService employeeService) { this.documentService = documentService; this.employeeService = employeeService; initializeView(); - updateDocumentGrid(); + updateDocumentGrid(null, null); } private void initializeView() { @@ -55,9 +57,7 @@ public class DocumentsListView extends Main { private void configureDocumentGrid() { documentGrid.setColumns("fileName", "documentType", "creator"); documentGrid.addComponentColumn(this::createEmployeeSpan).setHeader("Employee"); - addDocumentActionColumn("View", this::navigateToDocumentView); - addDocumentActionColumn("Edit", this::navigateToEditDocumentView); - addDocumentActionColumn("Download", this::downloadDocument); + addActionColumns(); configurePagination(); } @@ -67,6 +67,11 @@ public class DocumentsListView extends Main { return new Span(employeeName); } + private void addActionColumns() { + addDocumentActionColumn("View", this::navigateToDocumentView); + addDocumentActionColumn("Edit", this::navigateToEditDocumentView); + addDocumentActionColumn("Download", this::downloadDocument); + } private void addDocumentActionColumn(final String label, final DocumentActionHandler handler) { documentGrid.addComponentColumn(document -> createActionButton(label, () -> handler.handle(document))); @@ -79,21 +84,38 @@ public class DocumentsListView extends Main { } private ComboBox createDocumentTypeFilter() { - ComboBox documentTypeFilter = new ComboBox<>("Document Type"); + documentTypeFilter = new ComboBox<>("Document Type"); documentTypeFilter.setItems(DocumentType.values()); - documentTypeFilter.addValueChangeListener(event -> updateDocumentGrid()); + documentTypeFilter.setValue(DocumentType.values()[0]); + documentTypeFilter.addValueChangeListener(event -> { + updateDocumentGrid(event.getValue(), employeeFilter.getValue()); + }); return documentTypeFilter; } private ComboBox createEmployeeFilter() { - ComboBox employeeFilter = new ComboBox<>("Employee"); + employeeFilter = new ComboBox<>("Employee"); List employees = employeeService.findAllEmployees(); + employees.addFirst(createAllEmployeesOption()); employeeFilter.setItems(employees); - employeeFilter.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName()); - employeeFilter.addValueChangeListener(event -> updateDocumentGrid()); + employeeFilter.setItemLabelGenerator(this::getEmployeeLabel); + employeeFilter.setValue(employees.getFirst()); + employeeFilter.addValueChangeListener(event -> { + updateDocumentGrid(documentTypeFilter.getValue(), event.getValue()); + }); return employeeFilter; } + private Employee createAllEmployeesOption() { + Employee allEmployeesOption = new Employee(); + allEmployeesOption.setFirstName("All"); + return allEmployeesOption; + } + + private String getEmployeeLabel(Employee employee) { + return employee.getFirstName().equals("All") ? "All" : employee.getFirstName() + " " + employee.getLastName(); + } + private void navigateToEditDocumentView(final Document document) { navigateToDocumentView(document, "edit"); } @@ -106,10 +128,6 @@ public class DocumentsListView extends Main { getUI().ifPresent(ui -> ui.navigate(DocumentView.class, document.getId().toString() + "/" + action)); } - private void navigateToDownloadDocumentView(final Document document) { - // No operation - } - private void navigateToAddDocumentView() { getUI().ifPresent(ui -> ui.navigate(DocumentView.class, "new")); } @@ -119,8 +137,27 @@ public class DocumentsListView extends Main { documentGrid.setPageSize(5); } - private void updateDocumentGrid() { - documentGrid.setPagingDataProvider((page, pageSize) -> fetchDocuments((int) page, pageSize)); + private void updateDocumentGrid(DocumentType documentType, Employee employee) { + DocumentType finalDocumentType = isValidDocumentType(documentType) ? documentType : null; + Employee finalEmployee = isValidEmployee(employee) ? employee : null; + documentGrid.setPagingDataProvider((page, pageSize) -> + (finalDocumentType == null && finalEmployee == null) ? + fetchDocuments((int) page, pageSize) : + fetchFilteredDocuments((int) page, pageSize, finalDocumentType, finalEmployee) + ); + documentGrid.getDataProvider().refreshAll(); + } + + private boolean isValidDocumentType(DocumentType documentType) { + return documentType != null && !"All".equals(documentType.name()); + } + + private boolean isValidEmployee(Employee employee) { + return employee != null && !"All".equals(employee.getFirstName()); + } + + private List fetchFilteredDocuments(int page, int pageSize, final DocumentType documentType, final Employee employee) { + return documentService.findDocumentBy(documentType, employee, page, pageSize); } private List fetchDocuments(final int page, final int size) { @@ -142,14 +179,21 @@ public class DocumentsListView extends Main { } private void downloadDocument(final Document document) { + StreamResource resource = createDocumentStreamResource(document); + getUI().ifPresent(ui -> openDocumentStream(resource, ui)); + } + + private StreamResource createDocumentStreamResource(final Document document) { StreamResource resource = new StreamResource(document.getFileName(), () -> new ByteArrayInputStream(document.getFileData())); resource.setContentType("application/pdf"); resource.setHeader("Content-Disposition", "attachment; filename=\"" + document.getFileName() + ".pdf\""); - getUI().ifPresent(ui -> { - StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource); - ui.getPage().open(registration.getResourceUri().toString()); - }); + return resource; + } + + private void openDocumentStream(StreamResource resource, UI ui) { + StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource); + ui.getPage().open(registration.getResourceUri().toString()); } @FunctionalInterface From 6d9a2f65e5b67d6d3f361ceaff47d09b29eb2f3b Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Fri, 27 Sep 2024 03:29:26 -0400 Subject: [PATCH 21/26] #32 Perfil de Personal Administrativo - VER Documento (agregar boton ver documento) --- .../service/DocumentService.java | 9 +- .../views/DocumentView.java | 155 +++++++++++------- .../views/DocumentsListView.java | 22 +-- 3 files changed, 119 insertions(+), 67 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/service/DocumentService.java b/src/main/java/com/primefactorsolutions/service/DocumentService.java index 78f5717..3e808b0 100644 --- a/src/main/java/com/primefactorsolutions/service/DocumentService.java +++ b/src/main/java/com/primefactorsolutions/service/DocumentService.java @@ -23,6 +23,10 @@ public class DocumentService { documentRepository.save(newDocument); } + public void deleteDocument(final UUID id) { + documentRepository.deleteById(id); + } + public List getAllDocuments() { return documentRepository.findAll(); } @@ -53,7 +57,10 @@ public class DocumentService { return employees.subList(start, end); } - public List findDocumentBy(DocumentType documentType, Employee employee, int start, int pageSize) { + public List findDocumentBy(final DocumentType documentType, + final Employee employee, + final int start, + final int pageSize) { List documents = documentRepository.findAll(); if (documentType != null) { documents = documents.stream() diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index fe8d8a5..e78a8a5 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -10,11 +10,15 @@ import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.*; import com.vaadin.flow.spring.annotation.SpringComponent; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.JsonObject; import jakarta.annotation.security.PermitAll; import org.springframework.context.annotation.Scope; import org.springframework.security.core.userdetails.UserDetails; @@ -22,6 +26,7 @@ import org.vaadin.firitin.form.BeanValidationForm; import com.vaadin.flow.spring.security.AuthenticationContext; import java.io.IOException; +import java.util.Base64; import java.util.List; import java.util.UUID; @@ -41,8 +46,10 @@ public class DocumentView extends BeanValidationForm implements HasUrl private final DocumentService documentService; private final EmployeeService employeeService; private final AuthenticationContext authContext; + private boolean fileUploaded = false; private Button saveButton; + private Button viewDocumentButton; public DocumentView(final DocumentService documentService, final EmployeeService employeeService, @@ -55,10 +62,14 @@ public class DocumentView extends BeanValidationForm implements HasUrl } private void initializeView() { + configureComponents(); + configureUploadButton(); + } + + private void configureComponents() { setFileNameProperties(); setDocumentTypeProperties(); setEmployeeComboBoxProperties(); - setUploadButtonProperties(); } private void setFileNameProperties() { @@ -77,24 +88,53 @@ public class DocumentView extends BeanValidationForm implements HasUrl employeeComboBox.setWidthFull(); } - private void setUploadButtonProperties() { + private void configureUploadButton() { uploadButton.setMaxFiles(1); uploadButton.setAcceptedFileTypes(".pdf"); uploadButton.addSucceededListener(event -> handleUploadSuccess()); } - protected Button createSaveButton() { + protected Button createSaveButton() { saveButton = new Button("Save"); saveButton.addClickListener(event -> saveDocument()); return saveButton; } - protected Button createCloseButton() { + protected Button createCloseButton() { Button closeButton = new Button("Close"); closeButton.addClickListener(event -> closeForm()); return closeButton; } + protected Button createViewDocumentButton() { + viewDocumentButton = new Button("View Document"); + viewDocumentButton.setEnabled(false); + viewDocumentButton.addClickListener(event -> viewDocument()); + return viewDocumentButton; + } + + private void viewDocument() { + Document document = getEntity(); + if (document.getFileData() != null && document.getFileData().length > 0) { + String base64Data = Base64.getEncoder().encodeToString(document.getFileData()); + String jsCode = createJsCodeForDocument(base64Data); + getElement().executeJs(jsCode); + } else { + Notification.show("No file data available to view."); + } + } + + private String createJsCodeForDocument(final String base64Data) { + return "var byteCharacters = atob('" + base64Data + "');" + + "var byteNumbers = new Array(byteCharacters.length);" + + "for (var i = 0; i < byteCharacters.length; i++) {" + + " byteNumbers[i] = byteCharacters.charCodeAt(i);" + + "}" + + "var byteArray = new Uint8Array(byteNumbers);" + + "var blob = new Blob([byteArray], { type: 'application/pdf' });" + + "var url = URL.createObjectURL(blob);" + + "window.open(url, '_blank');"; + } private void closeForm() { navigateToDocumentsListView(); @@ -107,22 +147,19 @@ public class DocumentView extends BeanValidationForm implements HasUrl private void handleUploadSuccess() { fileUploaded = true; Notification.show("File uploaded successfully."); + viewDocumentButton.setEnabled(true); } private void saveDocument() { if (isFormValid()) { - Document document = getEntity(); // Obtenemos el documento actual del formulario + Document document = getEntity(); document.setFileName(fileName.getValue()); document.setDocumentType(documentType.getValue()); document.setEmployee(employeeComboBox.getValue()); - document.setFileData(readFileData()); // Actualizamos el archivo si es necesario + document.setFileData(readFileData()); + setDocumentCreator(document); - authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { - String creator = user.getUsername(); - document.setCreator(creator); // Asignar el nombre del creador al documento si corresponde - }); - - documentService.saveDocument(document); // Guardamos el documento actualizado + documentService.saveDocument(document); Notification.show("File saved successfully."); clearForm(); } else { @@ -130,6 +167,12 @@ public class DocumentView extends BeanValidationForm implements HasUrl } } + private void setDocumentCreator(final Document document) { + authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { + document.setCreator(user.getUsername()); + }); + } + private boolean isFormValid() { return !fileName.isEmpty() && documentType.getValue() != null @@ -137,14 +180,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl && fileUploaded; } - private Document createDocument() { - Document document = new Document(); - document.setFileName(fileName.getValue()); - document.setDocumentType(documentType.getValue()); - document.setFileData(readFileData()); - return document; - } - private byte[] readFileData() { try { return buffer.getInputStream().readAllBytes(); @@ -159,41 +194,8 @@ public class DocumentView extends BeanValidationForm implements HasUrl documentType.clear(); employeeComboBox.clear(); fileUploaded = false; - } - - private void checkFormModifications() { - boolean hasModifications = !fileName.isEmpty() - && documentType.getValue() != null - && employeeComboBox.getValue() != null; - - if (hasModifications || fileUploaded) { - saveButton.setEnabled(true); - } else { - saveButton.setEnabled(false); - } - } - - - @Override - public void setParameter(final BeforeEvent beforeEvent, final String action) { - final RouteParameters params = beforeEvent.getRouteParameters(); - final String s = params.get("documentId").orElse(null); - - if ("new".equals(action)) { - setEntityWithEnabledSave(new Document()); - } else { - UUID documentId = UUID.fromString(s); - var document = documentService.getDocument(documentId); - setEntity(document); - employeeComboBox.setValue(document.getEmployee()); - - if ("edit".equals(action) && !s.isEmpty()) { - setFieldsReadOnly(false); - } else if ("view".equals(action) && !s.isEmpty()) { - setFieldsReadOnly(true); - } - } - checkFormModifications(); + uploadButton.getElement().setPropertyJson("files", Json.createArray()); + viewDocumentButton.setEnabled(false); } private void setFieldsReadOnly(final boolean option) { @@ -202,8 +204,49 @@ public class DocumentView extends BeanValidationForm implements HasUrl employeeComboBox.setReadOnly(option); } + private void preLoadFile(final Document document) { + JsonArray jsonArray = Json.createArray(); + JsonObject jsonObject = Json.createObject(); + jsonObject.put("name", document.getFileName()); + jsonObject.put("progress", 100); + jsonObject.put("complete", true); + jsonArray.set(0, jsonObject); + uploadButton.getElement().setPropertyJson("files", jsonArray); + } + + @Override + public void setParameter(final BeforeEvent beforeEvent, final String action) { + final RouteParameters params = beforeEvent.getRouteParameters(); + final String documentIdString = params.get("documentId").orElse(null); + + if ("new".equals(action)) { + setEntityWithEnabledSave(new Document()); + } else { + UUID documentId = UUID.fromString(documentIdString); + Document document = documentService.getDocument(documentId); + setEntity(document); + employeeComboBox.setValue(document.getEmployee()); + preLoadFile(document); + configureViewOrEditAction(action, documentIdString); + } + } + + private void configureViewOrEditAction(final String action, final String documentIdString) { + if ("edit".equals(action) && !documentIdString.isEmpty()) { + setFieldsReadOnly(false); + preLoadFile(getEntity()); + } else if ("view".equals(action) && !documentIdString.isEmpty()) { + setFieldsReadOnly(true); + saveButton.setEnabled(false); + viewDocumentButton.setEnabled(true); + } + } + @Override protected List getFormComponents() { - return List.of(title, fileName, documentType, employeeComboBox, uploadButton, createCloseButton()); + HorizontalLayout buttonLayout = new HorizontalLayout(); + buttonLayout.add(uploadButton, createViewDocumentButton()); + buttonLayout.setSpacing(true); + return List.of(title, fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); } } diff --git a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java index c786ca6..c95e917 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentsListView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentsListView.java @@ -11,7 +11,6 @@ import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.grid.GridSortOrder; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; -import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.data.provider.SortDirection; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; @@ -112,7 +111,7 @@ public class DocumentsListView extends Main { return allEmployeesOption; } - private String getEmployeeLabel(Employee employee) { + private String getEmployeeLabel(final Employee employee) { return employee.getFirstName().equals("All") ? "All" : employee.getFirstName() + " " + employee.getLastName(); } @@ -137,26 +136,29 @@ public class DocumentsListView extends Main { documentGrid.setPageSize(5); } - private void updateDocumentGrid(DocumentType documentType, Employee employee) { + private void updateDocumentGrid(final DocumentType documentType, final Employee employee) { DocumentType finalDocumentType = isValidDocumentType(documentType) ? documentType : null; Employee finalEmployee = isValidEmployee(employee) ? employee : null; documentGrid.setPagingDataProvider((page, pageSize) -> - (finalDocumentType == null && finalEmployee == null) ? - fetchDocuments((int) page, pageSize) : - fetchFilteredDocuments((int) page, pageSize, finalDocumentType, finalEmployee) + (finalDocumentType == null && finalEmployee == null) + ? fetchDocuments((int) page, pageSize) + : fetchFilteredDocuments((int) page, pageSize, finalDocumentType, finalEmployee) ); documentGrid.getDataProvider().refreshAll(); } - private boolean isValidDocumentType(DocumentType documentType) { + private boolean isValidDocumentType(final DocumentType documentType) { return documentType != null && !"All".equals(documentType.name()); } - private boolean isValidEmployee(Employee employee) { + private boolean isValidEmployee(final Employee employee) { return employee != null && !"All".equals(employee.getFirstName()); } - private List fetchFilteredDocuments(int page, int pageSize, final DocumentType documentType, final Employee employee) { + private List fetchFilteredDocuments(final int page, + final int pageSize, + final DocumentType documentType, + final Employee employee) { return documentService.findDocumentBy(documentType, employee, page, pageSize); } @@ -191,7 +193,7 @@ public class DocumentsListView extends Main { return resource; } - private void openDocumentStream(StreamResource resource, UI ui) { + private void openDocumentStream(final StreamResource resource, final UI ui) { StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource); ui.getPage().open(registration.getResourceUri().toString()); } From 9b67ee39020287722cef577533848bae11e66adc Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Mon, 30 Sep 2024 19:28:44 -0400 Subject: [PATCH 22/26] =?UTF-8?q?Perfil=20de=20Personal=20Administrativo?= =?UTF-8?q?=20-=20VER,=20EDITAR,=20A=C3=91ADIR=20Documento=20(Correccion?= =?UTF-8?q?=20en=20el=20el=20boton=20view=20document)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../views/DocumentView.java | 186 ++++++++++-------- 1 file changed, 99 insertions(+), 87 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index e78a8a5..b854b7e 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -15,6 +15,8 @@ import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.router.*; +import com.vaadin.flow.server.StreamRegistration; +import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.spring.annotation.SpringComponent; import elemental.json.Json; import elemental.json.JsonArray; @@ -25,10 +27,12 @@ import org.springframework.security.core.userdetails.UserDetails; import org.vaadin.firitin.form.BeanValidationForm; import com.vaadin.flow.spring.security.AuthenticationContext; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Base64; import java.util.List; import java.util.UUID; +import java.io.InputStream; @SpringComponent @PermitAll @@ -36,7 +40,6 @@ import java.util.UUID; @PageTitle("Document") @Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) public class DocumentView extends BeanValidationForm implements HasUrlParameter { - private final H2 title = new H2("Edit Documents"); private final TextField fileName = new TextField("Document Name"); private final ComboBox documentType = new ComboBox<>("Document Type"); @@ -46,7 +49,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl private final DocumentService documentService; private final EmployeeService employeeService; private final AuthenticationContext authContext; - private boolean fileUploaded = false; private Button saveButton; private Button viewDocumentButton; @@ -66,34 +68,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl configureUploadButton(); } - private void configureComponents() { - setFileNameProperties(); - setDocumentTypeProperties(); - setEmployeeComboBoxProperties(); - } - - private void setFileNameProperties() { - fileName.setWidthFull(); - } - - private void setDocumentTypeProperties() { - documentType.setItems(DocumentType.values()); - documentType.setWidthFull(); - } - - private void setEmployeeComboBoxProperties() { - List employees = employeeService.findAllEmployees(); - employeeComboBox.setItems(employees); - employeeComboBox.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName()); - employeeComboBox.setWidthFull(); - } - - private void configureUploadButton() { - uploadButton.setMaxFiles(1); - uploadButton.setAcceptedFileTypes(".pdf"); - uploadButton.addSucceededListener(event -> handleUploadSuccess()); - } - protected Button createSaveButton() { saveButton = new Button("Save"); saveButton.addClickListener(event -> saveDocument()); @@ -113,43 +87,59 @@ public class DocumentView extends BeanValidationForm implements HasUrl return viewDocumentButton; } + private void setFileNameProperties() { + fileName.setWidthFull(); + } + + private void setDocumentTypeProperties() { + documentType.setItems(DocumentType.values()); + documentType.setWidthFull(); + } + + private void setEmployeeComboBoxProperties() { + List employees = employeeService.findAllEmployees(); + employeeComboBox.setItems(employees); + employeeComboBox.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName()); + employeeComboBox.setWidthFull(); + } + + private void setDocumentCreator(final Document document) { + authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { + document.setCreator(user.getUsername()); + }); + } + + private void setFieldsReadOnly(final boolean option) { + fileName.setReadOnly(option); + documentType.setReadOnly(option); + employeeComboBox.setReadOnly(option); + } + private void viewDocument() { - Document document = getEntity(); - if (document.getFileData() != null && document.getFileData().length > 0) { - String base64Data = Base64.getEncoder().encodeToString(document.getFileData()); - String jsCode = createJsCodeForDocument(base64Data); - getElement().executeJs(jsCode); - } else { - Notification.show("No file data available to view."); + StreamResource resource; + try { + InputStream inputStream = buffer.getInputStream(); + if (inputStream != null && inputStream.available() > 0) { + resource = new StreamResource(fileName.getValue(), () -> new ByteArrayInputStream(readFileData())); + } else { + byte[] fileData = getEntity().getFileData(); + resource = new StreamResource(fileName.getValue(), () -> new ByteArrayInputStream(fileData)); + } + resource.setContentType("application/pdf"); + getUI().ifPresent(ui -> { + StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource); + ui.getPage().open(registration.getResourceUri().toString()); + }); + } catch (IOException e) { + e.printStackTrace(); + Notification.show("Error al leer el archivo."); } } - private String createJsCodeForDocument(final String base64Data) { - return "var byteCharacters = atob('" + base64Data + "');" - + "var byteNumbers = new Array(byteCharacters.length);" - + "for (var i = 0; i < byteCharacters.length; i++) {" - + " byteNumbers[i] = byteCharacters.charCodeAt(i);" - + "}" - + "var byteArray = new Uint8Array(byteNumbers);" - + "var blob = new Blob([byteArray], { type: 'application/pdf' });" - + "var url = URL.createObjectURL(blob);" - + "window.open(url, '_blank');"; - } - - private void closeForm() { - navigateToDocumentsListView(); - } - private void navigateToDocumentsListView() { getUI().ifPresent(ui -> ui.navigate(DocumentsListView.class)); } - private void handleUploadSuccess() { - fileUploaded = true; - Notification.show("File uploaded successfully."); - viewDocumentButton.setEnabled(true); - } - private void saveDocument() { if (isFormValid()) { Document document = getEntity(); @@ -167,10 +157,8 @@ public class DocumentView extends BeanValidationForm implements HasUrl } } - private void setDocumentCreator(final Document document) { - authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> { - document.setCreator(user.getUsername()); - }); + private void closeForm() { + navigateToDocumentsListView(); } private boolean isFormValid() { @@ -180,15 +168,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl && fileUploaded; } - private byte[] readFileData() { - try { - return buffer.getInputStream().readAllBytes(); - } catch (IOException e) { - Notification.show("Error reading file data."); - return new byte[0]; - } - } - private void clearForm() { fileName.clear(); documentType.clear(); @@ -198,10 +177,13 @@ public class DocumentView extends BeanValidationForm implements HasUrl viewDocumentButton.setEnabled(false); } - private void setFieldsReadOnly(final boolean option) { - fileName.setReadOnly(option); - documentType.setReadOnly(option); - employeeComboBox.setReadOnly(option); + private byte[] readFileData() { + try { + return buffer.getInputStream().readAllBytes(); + } catch (IOException e) { + Notification.show("Error reading file data."); + return new byte[0]; + } } private void preLoadFile(final Document document) { @@ -210,8 +192,49 @@ public class DocumentView extends BeanValidationForm implements HasUrl jsonObject.put("name", document.getFileName()); jsonObject.put("progress", 100); jsonObject.put("complete", true); + jsonObject.put("fileData", Base64.getEncoder().encodeToString(document.getFileData())); jsonArray.set(0, jsonObject); uploadButton.getElement().setPropertyJson("files", jsonArray); + fileUploaded = true; + } + + private void handleUploadSuccess() { + fileUploaded = true; + Notification.show("File uploaded successfully."); + viewDocumentButton.setEnabled(true); + } + + private void handleFileRemoval() { + fileUploaded = false; + Notification.show("File removed."); + viewDocumentButton.setEnabled(false); + uploadButton.setReceiver(new MemoryBuffer()); + } + + private void configureComponents() { + setFileNameProperties(); + setDocumentTypeProperties(); + setEmployeeComboBoxProperties(); + } + + private void configureUploadButton() { + uploadButton.setMaxFiles(1); + uploadButton.setAcceptedFileTypes(".pdf"); + uploadButton.addSucceededListener(event -> handleUploadSuccess()); + uploadButton.getElement().addEventListener("file-remove", event -> handleFileRemoval()); + } + + private void configureViewOrEditAction(final String action, final String documentIdString) { + if ("edit".equals(action) && !documentIdString.isEmpty()) { + setFieldsReadOnly(false); + preLoadFile(getEntity()); + viewDocumentButton.setEnabled(true); + } else if ("view".equals(action) && !documentIdString.isEmpty()) { + setFieldsReadOnly(true); + preLoadFile(getEntity()); + saveButton.setEnabled(false); + viewDocumentButton.setEnabled(true); + } } @Override @@ -231,17 +254,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl } } - private void configureViewOrEditAction(final String action, final String documentIdString) { - if ("edit".equals(action) && !documentIdString.isEmpty()) { - setFieldsReadOnly(false); - preLoadFile(getEntity()); - } else if ("view".equals(action) && !documentIdString.isEmpty()) { - setFieldsReadOnly(true); - saveButton.setEnabled(false); - viewDocumentButton.setEnabled(true); - } - } - @Override protected List getFormComponents() { HorizontalLayout buttonLayout = new HorizontalLayout(); From dccc3ea09df2c4610a87e4bd71a4b36b5e74c43a Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 1 Oct 2024 13:27:49 -0400 Subject: [PATCH 23/26] #31 Perfil de Usuario Administrativo - EDITAR Documentos (Correccion validacion para editar) --- .../views/DocumentView.java | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index b854b7e..de4457e 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -8,7 +8,6 @@ import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; -import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.TextField; @@ -40,7 +39,6 @@ import java.io.InputStream; @PageTitle("Document") @Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) public class DocumentView extends BeanValidationForm implements HasUrlParameter { - private final H2 title = new H2("Edit Documents"); private final TextField fileName = new TextField("Document Name"); private final ComboBox documentType = new ComboBox<>("Document Type"); private final ComboBox employeeComboBox = new ComboBox<>("Employee"); @@ -53,6 +51,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl private Button saveButton; private Button viewDocumentButton; + public DocumentView(final DocumentService documentService, final EmployeeService employeeService, final AuthenticationContext authContext) { @@ -131,8 +130,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl ui.getPage().open(registration.getResourceUri().toString()); }); } catch (IOException e) { - e.printStackTrace(); - Notification.show("Error al leer el archivo."); + Notification.show("Error reading file."); } } @@ -198,30 +196,36 @@ public class DocumentView extends BeanValidationForm implements HasUrl fileUploaded = true; } - private void handleUploadSuccess() { - fileUploaded = true; - Notification.show("File uploaded successfully."); - viewDocumentButton.setEnabled(true); - } - - private void handleFileRemoval() { - fileUploaded = false; - Notification.show("File removed."); - viewDocumentButton.setEnabled(false); - uploadButton.setReceiver(new MemoryBuffer()); + private void updateSaveButtonState() { + boolean isModified = !fileName.getValue().equals(getEntity().getFileName()) + || documentType.getValue() != getEntity().getDocumentType() + || employeeComboBox.getValue() != getEntity().getEmployee() + || fileUploaded; + saveButton.setEnabled(isModified); } private void configureComponents() { setFileNameProperties(); setDocumentTypeProperties(); setEmployeeComboBoxProperties(); + fileName.addValueChangeListener(e -> updateSaveButtonState()); + documentType.addValueChangeListener(e -> updateSaveButtonState()); + employeeComboBox.addValueChangeListener(e -> updateSaveButtonState()); + uploadButton.addSucceededListener(e -> updateSaveButtonState()); + uploadButton.getElement().addEventListener("file-remove", event -> updateSaveButtonState()); } private void configureUploadButton() { uploadButton.setMaxFiles(1); uploadButton.setAcceptedFileTypes(".pdf"); - uploadButton.addSucceededListener(event -> handleUploadSuccess()); - uploadButton.getElement().addEventListener("file-remove", event -> handleFileRemoval()); + uploadButton.addSucceededListener(event -> { + fileUploaded = true; + updateSaveButtonState(); + }); + uploadButton.getElement().addEventListener("file-remove", event -> { + fileUploaded = false; + updateSaveButtonState(); + }); } private void configureViewOrEditAction(final String action, final String documentIdString) { @@ -245,6 +249,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl if ("new".equals(action)) { setEntityWithEnabledSave(new Document()); } else { + assert documentIdString != null; UUID documentId = UUID.fromString(documentIdString); Document document = documentService.getDocument(documentId); setEntity(document); @@ -259,6 +264,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.add(uploadButton, createViewDocumentButton()); buttonLayout.setSpacing(true); - return List.of(title, fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); + return List.of(fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); } } From e77e63491ad1212d7aba5fc91c781906c709fed9 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 1 Oct 2024 17:57:26 -0400 Subject: [PATCH 24/26] Resuelve construccion fallido --- src/main/java/com/primefactorsolutions/views/MainLayout.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/MainLayout.java b/src/main/java/com/primefactorsolutions/views/MainLayout.java index e0dd6f6..4867ea3 100644 --- a/src/main/java/com/primefactorsolutions/views/MainLayout.java +++ b/src/main/java/com/primefactorsolutions/views/MainLayout.java @@ -113,8 +113,6 @@ public class MainLayout extends AppLayout { LineAwesomeIcon.HOURGLASS_START_SOLID.create()); SideNavItem profile = new SideNavItem("My Profile", ProfileView.class, LineAwesomeIcon.USER_EDIT_SOLID.create()); - SideNavItem documents = new SideNavItem("My Documents", DocumentsView.class, - LineAwesomeIcon.SUITCASE_SOLID.create()); nav.addItem(new SideNavItem("Home", MainView.class, LineAwesomeIcon.HOME_SOLID.create())); nav.addItem(admin); From 78f41d59e0c159162bcba303842c233d4d55abfa Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Tue, 1 Oct 2024 18:35:52 -0400 Subject: [PATCH 25/26] Coreccion del enlace a documentos --- .../views/DocumentView.java | 41 ++++++++----------- .../views/MainLayout.java | 6 +-- 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index de4457e..b854b7e 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -8,6 +8,7 @@ import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; +import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.TextField; @@ -39,6 +40,7 @@ import java.io.InputStream; @PageTitle("Document") @Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) public class DocumentView extends BeanValidationForm implements HasUrlParameter { + private final H2 title = new H2("Edit Documents"); private final TextField fileName = new TextField("Document Name"); private final ComboBox documentType = new ComboBox<>("Document Type"); private final ComboBox employeeComboBox = new ComboBox<>("Employee"); @@ -51,7 +53,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl private Button saveButton; private Button viewDocumentButton; - public DocumentView(final DocumentService documentService, final EmployeeService employeeService, final AuthenticationContext authContext) { @@ -130,7 +131,8 @@ public class DocumentView extends BeanValidationForm implements HasUrl ui.getPage().open(registration.getResourceUri().toString()); }); } catch (IOException e) { - Notification.show("Error reading file."); + e.printStackTrace(); + Notification.show("Error al leer el archivo."); } } @@ -196,36 +198,30 @@ public class DocumentView extends BeanValidationForm implements HasUrl fileUploaded = true; } - private void updateSaveButtonState() { - boolean isModified = !fileName.getValue().equals(getEntity().getFileName()) - || documentType.getValue() != getEntity().getDocumentType() - || employeeComboBox.getValue() != getEntity().getEmployee() - || fileUploaded; - saveButton.setEnabled(isModified); + private void handleUploadSuccess() { + fileUploaded = true; + Notification.show("File uploaded successfully."); + viewDocumentButton.setEnabled(true); + } + + private void handleFileRemoval() { + fileUploaded = false; + Notification.show("File removed."); + viewDocumentButton.setEnabled(false); + uploadButton.setReceiver(new MemoryBuffer()); } private void configureComponents() { setFileNameProperties(); setDocumentTypeProperties(); setEmployeeComboBoxProperties(); - fileName.addValueChangeListener(e -> updateSaveButtonState()); - documentType.addValueChangeListener(e -> updateSaveButtonState()); - employeeComboBox.addValueChangeListener(e -> updateSaveButtonState()); - uploadButton.addSucceededListener(e -> updateSaveButtonState()); - uploadButton.getElement().addEventListener("file-remove", event -> updateSaveButtonState()); } private void configureUploadButton() { uploadButton.setMaxFiles(1); uploadButton.setAcceptedFileTypes(".pdf"); - uploadButton.addSucceededListener(event -> { - fileUploaded = true; - updateSaveButtonState(); - }); - uploadButton.getElement().addEventListener("file-remove", event -> { - fileUploaded = false; - updateSaveButtonState(); - }); + uploadButton.addSucceededListener(event -> handleUploadSuccess()); + uploadButton.getElement().addEventListener("file-remove", event -> handleFileRemoval()); } private void configureViewOrEditAction(final String action, final String documentIdString) { @@ -249,7 +245,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl if ("new".equals(action)) { setEntityWithEnabledSave(new Document()); } else { - assert documentIdString != null; UUID documentId = UUID.fromString(documentIdString); Document document = documentService.getDocument(documentId); setEntity(document); @@ -264,6 +259,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.add(uploadButton, createViewDocumentButton()); buttonLayout.setSpacing(true); - return List.of(fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); + return List.of(title, fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); } } diff --git a/src/main/java/com/primefactorsolutions/views/MainLayout.java b/src/main/java/com/primefactorsolutions/views/MainLayout.java index 4867ea3..81fa7f6 100644 --- a/src/main/java/com/primefactorsolutions/views/MainLayout.java +++ b/src/main/java/com/primefactorsolutions/views/MainLayout.java @@ -100,12 +100,10 @@ public class MainLayout extends AppLayout { SideNavItem admin = new SideNavItem("Admin", MainView.class, LineAwesomeIcon.SUPERSCRIPT_SOLID.create()); - admin.addItem(new SideNavItem("Requests", RequestsListView.class, - LineAwesomeIcon.TASKS_SOLID.create())); - admin.addItem(new SideNavItem("Timesheets", TimesheestReportView.class, - LineAwesomeIcon.HOURGLASS_END_SOLID.create())); admin.addItem(new SideNavItem("Employees", EmployeesListView.class, LineAwesomeIcon.USER_EDIT_SOLID.create())); + admin.addItem(new SideNavItem("Documents", DocumentsListView.class, + LineAwesomeIcon.FILE_ALT_SOLID.create())); SideNavItem timeOff = new SideNavItem("My Time-off", TimeoffView.class, LineAwesomeIcon.PLANE_DEPARTURE_SOLID.create()); From 2d4dbbd02347d28d2d5902adcef710837ed15b79 Mon Sep 17 00:00:00 2001 From: ricardo051199 Date: Wed, 2 Oct 2024 16:06:59 -0400 Subject: [PATCH 26/26] Coreccion cambios ver documento --- .../views/DocumentView.java | 45 +++++++++++-------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/primefactorsolutions/views/DocumentView.java b/src/main/java/com/primefactorsolutions/views/DocumentView.java index b854b7e..49c44a3 100644 --- a/src/main/java/com/primefactorsolutions/views/DocumentView.java +++ b/src/main/java/com/primefactorsolutions/views/DocumentView.java @@ -8,7 +8,6 @@ import com.primefactorsolutions.service.EmployeeService; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; -import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.textfield.TextField; @@ -40,7 +39,6 @@ import java.io.InputStream; @PageTitle("Document") @Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) public class DocumentView extends BeanValidationForm implements HasUrlParameter { - private final H2 title = new H2("Edit Documents"); private final TextField fileName = new TextField("Document Name"); private final ComboBox documentType = new ComboBox<>("Document Type"); private final ComboBox employeeComboBox = new ComboBox<>("Employee"); @@ -53,6 +51,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl private Button saveButton; private Button viewDocumentButton; + public DocumentView(final DocumentService documentService, final EmployeeService employeeService, final AuthenticationContext authContext) { @@ -131,8 +130,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl ui.getPage().open(registration.getResourceUri().toString()); }); } catch (IOException e) { - e.printStackTrace(); - Notification.show("Error al leer el archivo."); + Notification.show("Error reading file."); } } @@ -198,30 +196,40 @@ public class DocumentView extends BeanValidationForm implements HasUrl fileUploaded = true; } - private void handleUploadSuccess() { - fileUploaded = true; - Notification.show("File uploaded successfully."); - viewDocumentButton.setEnabled(true); - } - - private void handleFileRemoval() { - fileUploaded = false; - Notification.show("File removed."); - viewDocumentButton.setEnabled(false); - uploadButton.setReceiver(new MemoryBuffer()); + private void updateSaveButtonState() { + boolean isModified = !fileName.getValue().equals(getEntity().getFileName()) + || documentType.getValue() != getEntity().getDocumentType() + || employeeComboBox.getValue() != getEntity().getEmployee() + || fileUploaded; + saveButton.setEnabled(isModified); } private void configureComponents() { setFileNameProperties(); setDocumentTypeProperties(); setEmployeeComboBoxProperties(); + fileName.addValueChangeListener(e -> updateSaveButtonState()); + documentType.addValueChangeListener(e -> updateSaveButtonState()); + employeeComboBox.addValueChangeListener(e -> updateSaveButtonState()); + uploadButton.addSucceededListener(e -> updateSaveButtonState()); + uploadButton.getElement().addEventListener("file-remove", event -> updateSaveButtonState()); } private void configureUploadButton() { uploadButton.setMaxFiles(1); uploadButton.setAcceptedFileTypes(".pdf"); - uploadButton.addSucceededListener(event -> handleUploadSuccess()); - uploadButton.getElement().addEventListener("file-remove", event -> handleFileRemoval()); + uploadButton.addSucceededListener(event -> { + fileUploaded = true; + Notification.show("File uploaded successfully."); + viewDocumentButton.setEnabled(true); + updateSaveButtonState(); + }); + uploadButton.getElement().addEventListener("file-remove", event -> { + fileUploaded = false; + Notification.show("File removed."); + viewDocumentButton.setEnabled(false); + updateSaveButtonState(); + }); } private void configureViewOrEditAction(final String action, final String documentIdString) { @@ -245,6 +253,7 @@ public class DocumentView extends BeanValidationForm implements HasUrl if ("new".equals(action)) { setEntityWithEnabledSave(new Document()); } else { + assert documentIdString != null; UUID documentId = UUID.fromString(documentIdString); Document document = documentService.getDocument(documentId); setEntity(document); @@ -259,6 +268,6 @@ public class DocumentView extends BeanValidationForm implements HasUrl HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.add(uploadButton, createViewDocumentButton()); buttonLayout.setSpacing(true); - return List.of(title, fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); + return List.of(fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); } }