diff --git a/gates/src/main/java/ru/mlokoin/gates/controller/v1/CretareaController.java b/gates/src/main/java/ru/mlokoin/gates/controller/v1/CretareaController.java index 4a94abb..5fd80e7 100644 --- a/gates/src/main/java/ru/mlokoin/gates/controller/v1/CretareaController.java +++ b/gates/src/main/java/ru/mlokoin/gates/controller/v1/CretareaController.java @@ -18,13 +18,22 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; +import ru.mlokoin.gates.model.building.Building; +import ru.mlokoin.gates.model.course.Course; import ru.mlokoin.gates.model.cretarea.ProgramCretarea; import ru.mlokoin.gates.model.cretarea.ProgramCretareaWraper; +import ru.mlokoin.gates.model.education.EducatonEntry; +import ru.mlokoin.gates.model.fs.Post; import ru.mlokoin.gates.model.fs.xlsx.XlsxCell; import ru.mlokoin.gates.model.fs.xlsx.XlsxDocument; +import ru.mlokoin.gates.model.organization.Organization; +import ru.mlokoin.gates.model.program.Program; +import ru.mlokoin.gates.model.student.Student; +import ru.mlokoin.gates.model.teacher.Teacher; import ru.mlokoin.gates.repository.Storage; import ru.mlokoin.gates.teh.strings.Stringer; @@ -48,6 +57,42 @@ public class CretareaController { @Autowired private Storage storage; + /** + * Просмотр списка критериев из xlsx + * @param model + * @param postId + * @return + */ + @GetMapping("/list-from-xlsx") + public String listFromXlsx(Model model, @RequestParam(name="PostId", required = true) String postId) { + System.out.println("Получение списка критериев из xlsx-файла ..."); + Post post = storage.getPostById(Integer.parseInt(postId)); + + List programCretareas = storage.getProgramCretareasFromFile(post); + ProgramCretareaWraper programCretareaWraper = new ProgramCretareaWraper(programCretareas); + + model.addAttribute("programCretareaWraper", programCretareaWraper); + model.addAttribute("post", post); + + // model.addAttribute("cretareas", programCretareas); + return "cretareas-list-from-xlsx"; + } + + @GetMapping("/list-from-base") + public String listFromBase(Model model, @RequestParam(name="PostId", required = true) String postId) { + System.out.println("Получение списка критериев из базы данных ..."); + Post post = storage.getPostById(Integer.parseInt(postId)); + List programCretareas = storage.getProgramCretareasFromBase(); + ProgramCretareaWraper programCretareaWraper = new ProgramCretareaWraper(programCretareas); + + model.addAttribute("programCretareaWraper", programCretareaWraper); + model.addAttribute("post", post); + return "cretareas-list-from-base"; + } + + + + /** * Проверка критериев xlsx-файла: * - получание списка уникальных критериев из файла @@ -61,7 +106,7 @@ public class CretareaController { * @return */ @GetMapping("/check/{id}") - public String checkCretareas(Model model, @PathVariable String id) { + public String checkCretareas(Model model, @PathVariable("id") String id) { System.out.println("Проверка критериев, для внесения в базу ..."); System.out.println("Получение перечня критериев из xlsx-файла ..."); XlsxDocument xlsx = storage.getXlsxDocument(id); @@ -70,7 +115,7 @@ public class CretareaController { Map> map = xlsx.getData(); for (Map.Entry> entry : map.entrySet()) { ProgramCretarea pc = new ProgramCretarea(); - pc.setName_short(Stringer.clear(entry + pc.setNameShort(Stringer.clear(entry .getValue() .get(12) .getContent())); @@ -83,8 +128,8 @@ public class CretareaController { System.out.println("Список уникальных сокращенных наименований критериев из файла:"); Set xlsx_ccs = new HashSet<>(); for (ProgramCretarea pc : xlsx_cretareaSet) { - System.out.println(pc.getName_short()); - xlsx_ccs.add(pc.getName_short()); + System.out.println(pc.getNameShort()); + xlsx_ccs.add(pc.getNameShort()); } //Получение перечня критериев из базы @@ -100,8 +145,8 @@ public class CretareaController { System.out.println("Список уникальных сокращенных наименований критериев из базы:"); Set base_ccs = new HashSet<>(); for (ProgramCretarea pc : base_cretareaSet) { - System.out.println(pc.getName_short()); - base_ccs.add(pc.getName_short()); + System.out.println(pc.getNameShort()); + base_ccs.add(pc.getNameShort()); } //Удаление критериев присутствующих в базе @@ -114,7 +159,7 @@ public class CretareaController { ArrayList list = new ArrayList<>(); for (String string : xlsx_ccs) { ProgramCretarea pc = new ProgramCretarea(); - pc.setName_short(string); + pc.setNameShort(string); list.add(pc); } @@ -129,6 +174,19 @@ public class CretareaController { return "redirect:/document/educations/view/" + id; } + /** + * + * @param model + * @param postId + * @return + */ + @GetMapping("/check") + public String checkParam(Model model, @RequestParam(name="PostId", required = true) String postId) { + //нет реализации + System.out.println("нет реализации для проверки критериев ..."); + return "redirect:/document/educations/info?PostID=" + postId; + } + /** * Добавление всех критериев скопом * @param wraper @@ -150,7 +208,7 @@ public class CretareaController { for (ProgramCretarea cretarea : wraper.getList()) { //Проверка наличия краткого наименования критерия в базе - if (!cretarea.getName_short().equals("")) { + if (!cretarea.getNameShort().equals("")) { client.post() .uri("http://resource-service-api:8181/cretarea/create") .body(Mono.just(cretarea), ProgramCretarea.class) diff --git a/gates/src/main/java/ru/mlokoin/gates/controller/v1/EducationsController.java b/gates/src/main/java/ru/mlokoin/gates/controller/v1/EducationsController.java index f9c99db..e2d9e50 100644 --- a/gates/src/main/java/ru/mlokoin/gates/controller/v1/EducationsController.java +++ b/gates/src/main/java/ru/mlokoin/gates/controller/v1/EducationsController.java @@ -57,28 +57,19 @@ public class EducationsController { */ @GetMapping("/info/{PostID}") public String info(Model model, @PathVariable String PostID) { - // создание списка ошибок - List errors = new ArrayList<>(); - - System.out.println("PostID: " + PostID); - - Long DocumentID = storage.getPostById(PostID).getDocument().getId(); - // List posts = storage.getPostList(); - // for (Post post : posts) { - // if (post.getId() == Integer.parseInt(PostID)) { - // DocumentID = post.getDocument().getId(); - // } - // } - - - System.out.println("DocumentID: " + DocumentID); model.addAttribute("post", storage.getPostById(PostID)); model.addAttribute("baseReview", new BaseReview(storage)); - // model.addAttribute("xlsxReview", new XlsxReview(reestr)); - // model.addAttribute("absentReview", new AbsentReview(reestr, storage)); return "educations-xlsx-info"; } - + + @GetMapping("/info") + public String infoParam(Model model, @RequestParam(name="PostID", required = false) int PostID) { + Post post = storage.getPostById(PostID); + model.addAttribute("post", post); + model.addAttribute("xlsxReview", new XlsxReview(post, storage)); + model.addAttribute("baseReview", new BaseReview(storage)); + return "educations-xlsx-info"; + } /** * Предоставление пользователю формы "view-as-educations" diff --git a/gates/src/main/java/ru/mlokoin/gates/controller/v1/ProgramController.java b/gates/src/main/java/ru/mlokoin/gates/controller/v1/ProgramController.java index 3a564be..91d591b 100644 --- a/gates/src/main/java/ru/mlokoin/gates/controller/v1/ProgramController.java +++ b/gates/src/main/java/ru/mlokoin/gates/controller/v1/ProgramController.java @@ -60,7 +60,7 @@ public class ProgramController { for (Program program : unique_programs) { for (ProgramCretarea cretarea : base_cretareas) { if (program.getCretarea().isSimilar(cretarea)) { - System.out.println("Найдено совпадение: " + program.getCretarea().getName_short()); + System.out.println("Найдено совпадение: " + program.getCretarea().getNameShort()); program.setCretarea(cretarea); break; } diff --git a/gates/src/main/java/ru/mlokoin/gates/model/course/Course.java b/gates/src/main/java/ru/mlokoin/gates/model/course/Course.java index 3f6d39b..0e2359c 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/course/Course.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/course/Course.java @@ -11,6 +11,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import ru.mlokoin.gates.model.building.Building; +import ru.mlokoin.gates.model.education.Headers; import ru.mlokoin.gates.model.fs.xlsx.XlsxCell; import ru.mlokoin.gates.model.program.Program; import ru.mlokoin.gates.model.teacher.Teacher; @@ -58,21 +59,22 @@ public class Course { } public Course(Entry> entry) { - this.setPlace(Stringer.clear(entry.getValue().get(5).getContent())); + this.setPlace(Stringer.clear(entry.getValue() + .get(Headers.COURSE_PLACE.column()).getContent())); try { - this.setStart_date(new Date(Long.parseLong(Stringer.clear(entry.getValue().get(7).getContent())))); + this.setStart_date(new Date(Long.parseLong(Stringer.clear(entry.getValue().get(Headers.COURSE_START_DATE.column()).getContent())))); } catch (Exception e) { this.setStart_date(null); } try { - this.setProtocol_date(new Date(Long.parseLong(Stringer.clear(entry.getValue().get(9).getContent())))); + this.setProtocol_date(new Date(Long.parseLong(Stringer.clear(entry.getValue().get(Headers.COURSE_PROTOCOL_DATE.column()).getContent())))); } catch (Exception e) { this.setProtocol_date(null); } - this.setProtocol_number(Stringer.clear(entry.getValue().get(13).getContent())); - this.setReport_period(Stringer.clear(entry.getValue().get(17).getContent())); + this.setProtocol_number(Stringer.clear(entry.getValue().get(Headers.COURSE_PROTOCOL_NUMBER.column()).getContent())); + this.setReport_period(Stringer.clear(entry.getValue().get(Headers.COURSE_REPORT_PERIOD.column()).getContent())); this.setTeacher(new Teacher(entry)); this.setProgram(new Program(entry)); this.setBuilding(new Building(entry)); @@ -225,8 +227,7 @@ public class Course { * - program * - building * - * @param course1 - * @param course2 + * @param course - курс для сравнения * @return true - если курсы эквивалентны * false - если курсы различаются */ @@ -253,4 +254,18 @@ public class Course { } return false; } + + /** + * Проверка на пустой курс + * проверка происходит по полю start_date + * + * + * @return true - если курс пустой + */ + // public boolean isEmpty() { + // if (this.getStart_date() == null){ + // return true; + // } + // return false; + // } } diff --git a/gates/src/main/java/ru/mlokoin/gates/model/cretarea/ProgramCretarea.java b/gates/src/main/java/ru/mlokoin/gates/model/cretarea/ProgramCretarea.java index 2518a21..440f560 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/cretarea/ProgramCretarea.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/cretarea/ProgramCretarea.java @@ -16,7 +16,7 @@ import ru.mlokoin.gates.teh.strings.Stringer; public class ProgramCretarea implements Serializable{ private long id; private String name;//Наименование - private String name_short;//Наименование : сокращенно + private String nameShort;//Наименование : сокращенно /** * подготовить конструкторы на все варианты внесения информации о преподавателях @@ -26,19 +26,26 @@ public class ProgramCretarea implements Serializable{ */ public ProgramCretarea(String name, String name_short) { this.name = name; - this.name_short = name_short; + this.nameShort = name_short; } public ProgramCretarea(Entry> entry) { // исключаем строку заголовка if (entry.getKey() != 0) { String cretarea = Stringer.clear(entry.getValue().get(12).getContent()); - this.name_short = cretarea; + this.nameShort = cretarea; } } public boolean isSimilar(ProgramCretarea programCretarea) { - return this.name_short.equals(programCretarea.getName_short()); + return this.nameShort.equals(programCretarea.getNameShort()); + } + + public boolean isEmpty() { + if(nameShort == null){ + return true; + } + return nameShort.equals(""); } } diff --git a/gates/src/main/java/ru/mlokoin/gates/model/education/EducatonEntry.java b/gates/src/main/java/ru/mlokoin/gates/model/education/EducatonEntry.java index 578612d..5b43dc4 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/education/EducatonEntry.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/education/EducatonEntry.java @@ -134,4 +134,12 @@ public class EducatonEntry { } return false; } + + // public boolean isEmpty() { + // if (this.getCourse() == null + // || this.getStudent() == null) { + // return true; + // } + // return false; + // } } \ No newline at end of file diff --git a/gates/src/main/java/ru/mlokoin/gates/model/education/Headers.java b/gates/src/main/java/ru/mlokoin/gates/model/education/Headers.java new file mode 100644 index 0000000..d60dd17 --- /dev/null +++ b/gates/src/main/java/ru/mlokoin/gates/model/education/Headers.java @@ -0,0 +1,46 @@ +package ru.mlokoin.gates.model.education; + +/** + * Список заголовков таблицы + * добавить поле, для хранения типа данных столбца + */ +public enum Headers { + + ORGANIZATION_TYPE(0, "Тип организации"), + ORGANIZATION_NAME_FULL(1, "ПСК"), + STUDENT_DIRECTION(2, "Структурное подразделение"), + STUDENT_FULL_NAME(3, "ФИО обучающегося"), + STUDENT_PROFESSION(4, "Профессия"), + COURSE_PLACE(5, "Место проведения обучения"), + PROGRAM_NAME(6, "Программа обучения"), + COURSE_START_DATE(7, "Дата начала обучения"), + PROGRAM_LENGHT(8, "Продолжительность программы"), + COURSE_PROTOCOL_DATE(9, "Дата протокола"), + STUDENT_CATEGORY(10, "Категория обучаемых"), + PROGRAMM_STADY_DIRECTION(11, "Направление обучения"), + CRETAREA_NAME_SHORT(12, "Критерий"), + COURSE_PROTOCOL_NUMBER(13, "Номер протокола"), + EDUCATION_SERTIFICATE_NUMBER(14, "Номер удостоверения"), + PROGRAM_PRICE(15, "Стоимость обучения"), + EDUCATIONS_ONES(16, "Единички"), + COURSE_REPORT_PERIOD(17, "Отчетный период"), + TEACHER_FULL_NAME(18, "Преподаватель"), + BUILDING_NAME_SHORT(19, "Объект"); + + + private Headers(int column, String title) { + this.column = column; + this.title = title; + } + + public int column() { + return column; + } + + public String title() { + return title; + } + + private int column; + private String title; +} diff --git a/gates/src/main/java/ru/mlokoin/gates/model/fs/xlsx/XlsxDocumentReestr.java b/gates/src/main/java/ru/mlokoin/gates/model/fs/xlsx/XlsxDocumentReestr.java index 4bc410a..68b0c7d 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/fs/xlsx/XlsxDocumentReestr.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/fs/xlsx/XlsxDocumentReestr.java @@ -86,7 +86,7 @@ public class XlsxDocumentReestr extends XlsxDocument { List programCretareas = getCretareasAsIs(); List unique = new ArrayList<>(); for (ProgramCretarea programCretarea : programCretareas) { - if (!unique.contains(programCretarea) && programCretarea.getName_short() != "") { + if (!unique.contains(programCretarea) && programCretarea.getNameShort() != "") { unique.add(programCretarea); } } diff --git a/gates/src/main/java/ru/mlokoin/gates/model/monitor/XlsxReview.java b/gates/src/main/java/ru/mlokoin/gates/model/monitor/XlsxReview.java index 40eb013..fee8e65 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/monitor/XlsxReview.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/monitor/XlsxReview.java @@ -1,11 +1,25 @@ package ru.mlokoin.gates.model.monitor; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import ru.mlokoin.gates.model.building.Building; +import ru.mlokoin.gates.model.course.Course; +import ru.mlokoin.gates.model.cretarea.ProgramCretarea; +import ru.mlokoin.gates.model.education.EducatonEntry; +import ru.mlokoin.gates.model.fs.Post; +import ru.mlokoin.gates.model.fs.xlsx.XlsxCell; import ru.mlokoin.gates.model.fs.xlsx.XlsxDocumentReestr; +import ru.mlokoin.gates.model.organization.Organization; +import ru.mlokoin.gates.model.program.Program; +import ru.mlokoin.gates.model.student.Student; +import ru.mlokoin.gates.model.teacher.Teacher; +import ru.mlokoin.gates.repository.Storage; @NoArgsConstructor @AllArgsConstructor @@ -20,6 +34,11 @@ public class XlsxReview implements Serializable { private int organizationsCount; private int programCretareaCount; + /** + * Конструктор + * - забираем все данные из файла, обрабатываем их на стороне gates + * @param xlsx + */ public XlsxReview(XlsxDocumentReestr xlsx){ setBuildingsCount(xlsx.getBuildingsCount()); setCoursesCount(xlsx.getCoursesCount()); @@ -29,7 +48,81 @@ public class XlsxReview implements Serializable { setTeachersCount(xlsx.getTeachersCount()); setOrganizationsCount(xlsx.getOrganizationsCount()); setProgramCretareaCount(xlsx.getCretareasCount()); - } + /** + * Конструктор + * - забираем данные из хранилища по кускам + * @param post + * @param storage + */ + public XlsxReview(Post post, Storage storage) { + List programs = new ArrayList<>(); + List buildings = new ArrayList<>(); + List teachers = new ArrayList<>(); + List organizations = new ArrayList<>(); + List programCretareas = new ArrayList<>(); + List students = new ArrayList<>(); + List courses = new ArrayList<>(); + List educations = new ArrayList<>(); + int max = storage.getDocumentContentLenght(String.valueOf(post.getDocument().getId())); + int portion = 10000; + int from = 0; + while (from < max) { + portion = Math.min(max - from, portion); + Map> cells = storage.getDocumentContentByParts(post.getDocument().getId().toString(), from, portion); + for (Map.Entry> entry : cells.entrySet()) { + + // private int programsCount; + Program program = new Program(entry); + if(!programs.contains(program)){ + programs.add(program); + } + // private int buildingsCount; + Building building = new Building(entry); + if(!buildings.contains(building)){ + buildings.add(building); + } + // private int teachersCount; + Teacher teacher = new Teacher(entry); + if(!teachers.contains(teacher)){ + teachers.add(teacher); + } + // private int organizationsCount; + Organization organization = new Organization(entry); + if(!organizations.contains(organization)){ + organizations.add(organization); + } + // private int programCretareaCount; + ProgramCretarea programCretarea = new ProgramCretarea(entry); + if(!programCretareas.contains(programCretarea) + && !programCretarea.isEmpty()){ + programCretareas.add(programCretarea); + } + + Student student = new Student(entry); + if(!students.contains(student)){ + students.add(student); + } + Course course = new Course(entry); + if(!courses.contains(course)){ + courses.add(course); + } + EducatonEntry education = new EducatonEntry(entry); + if(!educations.contains(education)){ + educations.add(education); + } + } + from += portion; + } + + this.programsCount = programs.size() - 1;//убрали строку заголовков + this.buildingsCount = buildings.size() - 1; + this.teachersCount = teachers.size() - 1; + this.organizationsCount = organizations.size() - 1; + this.programCretareaCount = programCretareas.size() - 1; + this.studentsCount = students.size() - 1;//убрали строку заголовков + this.coursesCount = courses.size() - 1; + this.educationsCount = educations.size() - 1; + } } diff --git a/gates/src/main/java/ru/mlokoin/gates/model/program/Program.java b/gates/src/main/java/ru/mlokoin/gates/model/program/Program.java index 045af6a..dd3340c 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/program/Program.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/program/Program.java @@ -7,6 +7,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import ru.mlokoin.gates.model.cretarea.ProgramCretarea; +import ru.mlokoin.gates.model.education.Headers; import ru.mlokoin.gates.model.fs.xlsx.XlsxCell; import ru.mlokoin.gates.teh.strings.Stringer; @@ -50,11 +51,11 @@ public class Program { } public Program(Entry> entry) { - this.setName(Stringer.clear(entry.getValue().get(6).getContent())); + this.setName(Stringer.clear(entry.getValue().get(Headers.PROGRAM_NAME.column()).getContent())); //устанавливаем длительность программы try { - String s = Stringer.clear(entry.getValue().get(8).getContent()); + String s = Stringer.clear(entry.getValue().get(Headers.PROGRAM_LENGHT.column()).getContent()); if (s == "") { s = 0 + ""; } else { @@ -66,11 +67,11 @@ public class Program { } - this.setStudy_direction(Stringer.clear(entry.getValue().get(11).getContent())); + this.setStudy_direction(Stringer.clear(entry.getValue().get(Headers.PROGRAMM_STADY_DIRECTION.column()).getContent())); //устанавливаем стоимость обучения try { - String s = Stringer.clear(entry.getValue().get(15).getContent()); + String s = Stringer.clear(entry.getValue().get(Headers.PROGRAM_PRICE.column()).getContent()); if (s == "") { s = 0 + ""; } else { diff --git a/gates/src/main/java/ru/mlokoin/gates/model/student/Student.java b/gates/src/main/java/ru/mlokoin/gates/model/student/Student.java index 9ecacbc..4a0266e 100644 --- a/gates/src/main/java/ru/mlokoin/gates/model/student/Student.java +++ b/gates/src/main/java/ru/mlokoin/gates/model/student/Student.java @@ -113,4 +113,11 @@ public class Student implements Serializable{ } return false; } + // public boolean isEmpty() { + // return first_name == null + // || first_name.isEmpty() + // || first_name.trim().isEmpty() + // || first_name.equals("") + // || first_name.equals("Нет"); + // } } diff --git a/gates/src/main/java/ru/mlokoin/gates/repository/Storage.java b/gates/src/main/java/ru/mlokoin/gates/repository/Storage.java index a22747a..4c70bcb 100644 --- a/gates/src/main/java/ru/mlokoin/gates/repository/Storage.java +++ b/gates/src/main/java/ru/mlokoin/gates/repository/Storage.java @@ -1,5 +1,6 @@ package ru.mlokoin.gates.repository; +import java.net.URI; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; @@ -15,6 +16,7 @@ import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; + import ru.mlokoin.gates.model.building.Building; import ru.mlokoin.gates.model.course.Course; import ru.mlokoin.gates.model.cretarea.ProgramCretarea; @@ -36,7 +38,9 @@ import ru.mlokoin.gates.teh.strings.Stringer; */ @Service public class Storage { + private String programCretareaCountFromBaseLink = "http://resource-service-api:8181/cretarea/count"; private String storageLink = "http://storage-rs:8282/api/document/content/"; + private String storageDocumentContentLink = "http://storage-rs:8282/api/document/content/"; private String storageListLink = "http://resource-service-api:8181/storage-entry/list"; private String postListLink = "http://resource-service-api:8181/post/list"; private String programsLink = "http://resource-service-api:8181/program/list"; @@ -116,11 +120,151 @@ public class Storage { return result; } + public Post getPostById(int postID) { + // TODO: добавить линк в storage-rs, для получения поста по id + List posts = client.method(HttpMethod.GET) + .uri(postListLink) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >(){}) + .block(); + Post result = new Post(); + for (Post post : posts) { + if (post.getId() == postID) { + result = post; + } + } + return result; + } + public int getPostCount(){ - // TODO: добавить линк в storage-rs, для получения количества постов + // TODO: добавить линк в resource-service, для получения количества постов return getPostList().size(); } + /** + * Получение содержимого xlsx-файла в виде Map> + * @param docId + * @return + */ + public Map> getDocumentContentAsMap(String docId) { + System.out.println("Получение данных xlsx-файла в виде Map> ..."); + String url = storageDocumentContentLink + "?filename=" + docId + ".xlsx"; + Map> cells = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >>(){}) + .block(); + return cells; + } + + /** + * Получение строки из xlsx-файла + * @param docId + * @param line + * @return + */ + public List getDocumentContentByLines(String docId, String line) { + System.out.println("Получение данных xlsx-файла в виде List по строке ..."); + String url = storageDocumentContentLink + "/line" + "?filename=" + docId + ".xlsx&line=" + line; + List cells = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >(){}) + .block(); + return cells; + } + + /** + * Получение частей из xlsx-файла + * @param docId + * @param from + * @param count + * @return + */ + public Map> getDocumentContentByParts(String docId, int from, int count) { + System.out.println("Получение данных xlsx-файла в виде Map> по частям ..."); + String url = storageDocumentContentLink + "/part" + "?filename=" + docId + ".xlsx&from=" + from + "&count=" + count; + Map> cells = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >>(){}) + .block(); + return cells; + } + + /** + * Получение количества записей в xlsx-файле + * @param docId + * @return + */ + public Integer getDocumentContentLenght(String docId) { + System.out.println("Получение количества записей в xlsx-файле ..."); + String url = storageDocumentContentLink + "/lenght" + "?filename=" + docId + ".xlsx"; + Integer count = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(Integer.class) + .block(); + return count; + } + + /** + * Получение столбца из xlsx-файла + * @param docId + * @param column + * @return + */ + public List getDocumentContentByColumn(Integer docId, Integer column) { + System.out.println("Получение данных xlsx-файла в виде List по столбцу ..."); + String url = storageDocumentContentLink + "/column" + "?filename=" + docId + ".xlsx&column=" + column; + List cells = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >(){}) + .block(); + return cells; + } + + public List getUniqueDocumentContentByColumn(int docId, int column) { + System.out.println("Получение уникальных данных xlsx-файла в виде List по столбцу #" + column + " ..."); + String url = storageDocumentContentLink + "/column/unique" + "?filename=" + docId + ".xlsx&column=" + column; + List cells = client.method(HttpMethod.GET) + .uri(url) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >(){}) + .block(); + return cells; + } + + + /*********************************************************************** */ + /* + * Извлечение данных (списков моделей) из xlsx - перебор xlsx по кускам + */ + public List getProgramCretareasFromFile(Post post) { + List programCretareas = new ArrayList<>(); + int max = this.getDocumentContentLenght(String.valueOf(post.getDocument().getId())); + int portion = 10000; + int from = 0; + while (from < max) { + portion = Math.min(max - from, portion); + Map> cells = this.getDocumentContentByParts(post.getDocument().getId().toString(), from, portion); + for (Map.Entry> entry : cells.entrySet()) { + ProgramCretarea programCretarea = new ProgramCretarea(entry); + if(!programCretareas.contains(programCretarea) + && !programCretarea.isEmpty()){ + programCretareas.add(programCretarea); + } + } + from += portion; + } + programCretareas.sort(Comparator.comparing(ProgramCretarea::getNameShort)); + + return programCretareas; + } + + + /*********************************************************************** */ /** * Получение всего содержимого xlsx-файла из файлового хранилища * по id документа в хранилище @@ -387,7 +531,7 @@ public class Storage { for (ProgramCretarea xlsxCretarea : xlsxList) { for (ProgramCretarea baseCretarea : baseList) { - if (xlsxCretarea.getName_short().equals(baseCretarea.getName_short())) { + if (xlsxCretarea.getNameShort().equals(baseCretarea.getNameShort())) { result.remove(xlsxCretarea); break; } @@ -555,6 +699,25 @@ public class Storage { return getBaseOrganizations().size(); } + public List getProgramCretareasFromBase() { + System.out.println("Получение списка критериев из баз данных ..."); + List list = client.method(HttpMethod.GET) + .uri(cretareasLink) + .retrieve() + .bodyToMono(new ParameterizedTypeReference >(){}) + .block(); + return list; + } + + public Integer getProgramCretareaCountFromBase(){ + int count = client.method(HttpMethod.GET) + .uri(programCretareaCountFromBaseLink) + .retrieve() + .bodyToMono(Integer.class) + .block(); + return count; + } + diff --git a/gates/src/main/resources/templates/cretareas-check.html b/gates/src/main/resources/templates/cretareas-check.html index 73bb233..3efb540 100644 --- a/gates/src/main/resources/templates/cretareas-check.html +++ b/gates/src/main/resources/templates/cretareas-check.html @@ -45,7 +45,7 @@ - + diff --git a/gates/src/main/resources/templates/cretareas-list-from-base.html b/gates/src/main/resources/templates/cretareas-list-from-base.html new file mode 100644 index 0000000..583ac42 --- /dev/null +++ b/gates/src/main/resources/templates/cretareas-list-from-base.html @@ -0,0 +1,60 @@ + + + + + cretareas-list-from-base + + + + + + +
+
+
+ +
+ +

Критерии, извлеченные из БД:

+ + + + + + + + + + + + + + + + +
+ + + КРАТКО + + ПОЛНО +
+ + + + + + + +
+ +
+
+
+ + \ No newline at end of file diff --git a/gates/src/main/resources/templates/cretareas-list-from-xlsx.html b/gates/src/main/resources/templates/cretareas-list-from-xlsx.html new file mode 100644 index 0000000..0ba0327 --- /dev/null +++ b/gates/src/main/resources/templates/cretareas-list-from-xlsx.html @@ -0,0 +1,57 @@ + + + + + cretareas-list-from-xlsx + + + + + + +
+
+
+ +
+ +

Критерии, извлеченные из XLSX:

+ + + + + + + + + + + + + + + +
+ + + КРАТКО +
+ + + +
+ +
+
+
+ + \ No newline at end of file diff --git a/gates/src/main/resources/templates/documents.html b/gates/src/main/resources/templates/documents.html index 188509b..b466858 100644 --- a/gates/src/main/resources/templates/documents.html +++ b/gates/src/main/resources/templates/documents.html @@ -42,17 +42,22 @@ xmlns:th="http://www.thymeleaf.org"> - - - - - + + + + + + + + + + @@ -74,7 +79,6 @@ xmlns:th="http://www.thymeleaf.org"> @@ -83,11 +87,18 @@ xmlns:th="http://www.thymeleaf.org"> - + + + - + - - - - - - - - - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + + + + + +
idnameextensionsize(bytes) - - Номер загрузки (post.id)Вид документа (type)Документ в базе (document.id)Наименование в хранилище (name)Расширение (extension)Размер в байтах (size)***
+ +
-
+ + +
+ + +
ПараметрВ файле: В базе данных:
Критерии: - Критерии: +
- Программы: +
- Преподаватели: - Программы:
- Объекты строительства: - Преподаватели:
- Организации: - Объекты строительства:
- Курсы: - Организации:
- Студенты: - Курсы:
- Обучения: - Студенты:
Обучения:
diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/BuildingController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/BuildingController.java deleted file mode 100644 index 79e939d..0000000 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/BuildingController.java +++ /dev/null @@ -1,77 +0,0 @@ -package ru.molokoin.resourceserviceapi.controllers; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import ru.molokoin.resourceserviceapi.entities.Building; -import ru.molokoin.resourceserviceapi.repositories.BuildingFace; - -@RestController -@RequestMapping(path = "/", consumes = {"*/*"}) -public class BuildingController { - @Autowired - private BuildingFace repo; - - /** - * Получение перечня объектов строительства - * @return - */ - @GetMapping("/building/list") - public ResponseEntity> getBuildings(){ - return new ResponseEntity<>(repo.findAll(), HttpStatus.OK); - } - - /** - * Получение сведений по объекту строительства - * @param id - * @return - */ - @GetMapping("/building/{id}") - public ResponseEntity getBuildingByID(@PathVariable Integer id){ - return new ResponseEntity<>(repo.findBuildingById(id), HttpStatus.OK); - } - - /** - * Создание запис о новом объекте строительства - * @param building - * @return - */ - @PostMapping(path = "/building/create", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity saveBuilding(@RequestBody Building building) { - repo.save(building); - return new ResponseEntity<>(building, HttpStatus.CREATED); - } - - @PostMapping(path = "/building/update/{id}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateBuilding(@PathVariable Integer id, @RequestBody Building building) { - Building b = repo.findBuildingById(id); - b.setName_full(building.getName_full()); - b.setName_short(building.getName_short()); - b.setCode_full(building.getCode_full()); - b.setCode_short(building.getCode_short()); - repo.save(b); - return new ResponseEntity<>(repo.findBuildingById(id), HttpStatus.CREATED); - } - - @DeleteMapping("/building/delete/{id}") - public ResponseEntity deleteBuilding(@PathVariable Long id){ - Building b = repo.findBuildingById(id); - repo.delete(b); - return new ResponseEntity<>("Запись id#" + id + " удалена ... ", HttpStatus.OK); - } -} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramCretareaController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramCretareaController.java deleted file mode 100644 index af371cd..0000000 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramCretareaController.java +++ /dev/null @@ -1,65 +0,0 @@ -package ru.molokoin.resourceserviceapi.controllers; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import ru.molokoin.resourceserviceapi.entities.ProgramCretarea; -import ru.molokoin.resourceserviceapi.repositories.ProgramCretareaRepositoryFace; - -@RestController -@RequestMapping(path = "/", consumes = {"*/*"}) -public class ProgramCretareaController { - @Autowired - private ProgramCretareaRepositoryFace repo; - - @GetMapping("/cretarea/list") - public ResponseEntity> getTeachers(){ - return new ResponseEntity<>(repo.findAll(), HttpStatus.OK); - } - - @GetMapping("/cretarea/{id}") - public ResponseEntity getTeacherByID(@PathVariable Integer id){ - return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.OK); - } - - @PostMapping(path = "/cretarea/create", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity saveTeacher(@RequestBody ProgramCretarea cretarea) { - repo.save(cretarea); - return new ResponseEntity<>(cretarea, HttpStatus.CREATED); - } - - @PutMapping(path = "/cretarea/update/{id}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateCretarea(@PathVariable Integer id, @RequestBody ProgramCretarea cretarea) { - ProgramCretarea pc = repo.findCretareaById(id); - pc.setName(cretarea.getName()); - pc.setName_short(cretarea.getName_short()); - repo.save(pc); - return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.CREATED); - } - - @DeleteMapping("/cretarea/delete/{id}") - public ResponseEntity deleteCretarea(@PathVariable Long id){ - ProgramCretarea pc = repo.findCretareaById(id); - System.out.println(pc.toString()); - repo.delete(pc); - return new ResponseEntity<>("Запись id#" + id + " удалена ... ", HttpStatus.OK); - } - - -} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/BuildingController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/BuildingController.java new file mode 100644 index 0000000..d47e02f --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/BuildingController.java @@ -0,0 +1,187 @@ +package ru.molokoin.resourceserviceapi.controllers.api; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import ru.molokoin.resourceserviceapi.entities.Building; +import ru.molokoin.resourceserviceapi.repositories.BuildingRepository; +import org.springframework.web.bind.annotation.RequestParam; + + +@RestController +@RequestMapping(path = "/building", consumes = {"*/*"}) +public class BuildingController { + @Autowired + private BuildingRepository repo; + + public BuildingController(BuildingRepository repo) { + this.repo = repo; + } + + @GetMapping("/pages") + public Page page(@RequestParam(name = "page", required = false) Integer pageNo, + @RequestParam(name = "size", required = false) Long pageSize, + @RequestParam(name = "sortBy", required = false) String sortBy) { + if (pageNo == null || pageNo < 0) pageNo = 0; + if (pageSize == null || pageSize < 0) pageSize = repo.count(); + if (sortBy == null) sortBy = "id"; + + Sort sort = Sort.by(sortBy); + Pageable pageable = PageRequest.of(pageNo, pageSize == null ? null : Math.toIntExact(pageSize), sort); + try{ + return repo.findAll(pageable); + }catch(PropertyReferenceException e){ + sortBy = "id"; + sort = Sort.by(sortBy); + pageable = PageRequest.of(pageNo, pageSize == null ? null : Math.toIntExact(pageSize), sort); + return repo.findAll(pageable); + } + } + + @GetMapping("/count") + public ResponseEntity getСretareasCount(){ + return new ResponseEntity<>(repo.count(), HttpStatus.OK); + } + + @GetMapping("") + public ResponseEntity building(@RequestParam(name="id", required = false) Long id, + @RequestParam(name="nameShort", required = false) String nameShort){ + boolean exists = false; + if(id != null && repo.existsById(id)){ + return new ResponseEntity<>(repo.findById(id), HttpStatus.OK); + } + if (nameShort != null && repo.existsByNameShort(nameShort)){ + return new ResponseEntity<>(repo.findByNameShort(nameShort), HttpStatus.OK); + } + return new ResponseEntity<>(exists, HttpStatus.OK); + } + + @GetMapping("/exists") + public ResponseEntity exists(@RequestBody Building building){ + return new ResponseEntity<>(repo.existsByNameShort(building.getNameShort()), HttpStatus.OK); + } + + @GetMapping("/absent") + public Page absent(@RequestBody List buildings) { + List absent = new ArrayList<>(); + //проверяем наличие объекта строительства в базе + for (Building building : buildings) { + if (!repo.existsByNameShort(building.getNameShort())) { + //если не найден - добавляем в список + absent.add(building); + } + } + //сортируем краткие наименования по алфавиту + absent.sort(Comparator.comparing(Building::getNameShort)); + + //подготавливаем страницу для ответа + Page absentPage = new PageImpl<>(absent); + return absentPage; + } + + /** + * Создание записи о новом объекте строительства + * @param building + * @return + */ + @PostMapping(path = "/create", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity saveBuilding(@RequestBody Building building) { + repo.save(building); + return new ResponseEntity<>(building, HttpStatus.CREATED); + } + + @PostMapping(path = "/update/{id}", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateBuilding(@PathVariable Integer id, @RequestBody Building building) { + Building b = repo.findById(id); + b.setNameFull(building.getNameFull()); + b.setNameShort(building.getNameShort()); + b.setCodeFull(building.getCodeFull()); + b.setCodeShort(building.getCodeShort()); + repo.save(b); + return new ResponseEntity<>(repo.findById(id), HttpStatus.CREATED); + } + + @PostMapping(path = "/update", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity update(@RequestParam(name="id", required = true) Integer id, + @RequestBody Building building) { + Building b = repo.findById(id); + b.setNameFull(building.getNameFull()); + b.setNameShort(building.getNameShort()); + b.setCodeFull(building.getCodeFull()); + b.setCodeShort(building.getCodeShort()); + repo.save(b); + return new ResponseEntity<>(repo.findById(id), HttpStatus.CREATED); + } + + + @DeleteMapping("/delete/{id}") + public ResponseEntity deleteBuilding(@PathVariable Long id){ + Boolean success = false; + if (id != null && id > 0) { + repo.deleteById(id); + } + success = true; + return new ResponseEntity<>(success, HttpStatus.OK); + } + + @DeleteMapping("/delete") + public ResponseEntity delete(@RequestParam(name="id", required = true) Long id){ + Boolean success = false; + Building pc = repo.findById(id).get(); + try{ + repo.delete(pc); + success = true; + } catch(Exception e){ + System.out.println("Error: " + e.getMessage()); + success = false; + } + return new ResponseEntity<>(success, HttpStatus.OK); + } + + + + + // /** + // * Получение перечня объектов строительства + // * @return + // */ + // @GetMapping("/list") + // public ResponseEntity> getBuildings(){ + // return new ResponseEntity<>(repo.findAll(), HttpStatus.OK); + // } + + // /** + // * Получение сведений по объекту строительства + // * @param id + // * @return + // */ + // @GetMapping("/{id}") + // public ResponseEntity getBuildingByID(@PathVariable Integer id){ + // return new ResponseEntity<>(repo.findBuildingById(id), HttpStatus.OK); + // } +} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/CourseController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/CourseController.java similarity index 88% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/CourseController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/CourseController.java index c0678eb..7875326 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/CourseController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/CourseController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -48,10 +48,10 @@ public class CourseController { public ResponseEntity updateCourse(@PathVariable Integer id, @RequestBody Course course) { Course c = repo.findCourseById(id); c.setPlace(course.getPlace()); - c.setStart_date(course.getStart_date()); - c.setProtocol_date(course.getProtocol_date()); - c.setProtocol_number(course.getProtocol_number()); - c.setReport_period(course.getReport_period()); + c.setStartDate(course.getStartDate()); + c.setProtocolDate(course.getProtocolDate()); + c.setProtocolNumber(course.getProtocolNumber()); + c.setReportPeriod(course.getReportPeriod()); c.setTeacher(course.getTeacher()); c.setProgram(course.getProgram()); c.setBuilding(course.getBuilding()); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/EducationEntryController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/EducationEntryController.java similarity index 89% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/EducationEntryController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/EducationEntryController.java index 2aa9b12..6ee2de3 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/EducationEntryController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/EducationEntryController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -47,9 +47,9 @@ public class EducationEntryController { produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateEducationEntry(@PathVariable Integer id, @RequestBody EducationEntry educationEntry) { EducationEntry ee = repo.findEducationEntryById(id); - ee.setSertificate_number(educationEntry.getSertificate_number()); - ee.setFrdo_number(educationEntry.getFrdo_number()); - ee.setEisot_number(educationEntry.getEisot_number()); + ee.setSertificateNumber(educationEntry.getSertificateNumber()); + ee.setFrdoNumber(educationEntry.getFrdoNumber()); + ee.setEisotNumber(educationEntry.getEisotNumber()); ee.setOnes(educationEntry.getOnes()); ee.setCourse(educationEntry.getCourse()); ee.setStudent(educationEntry.getStudent()); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/HelloController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/HelloController.java similarity index 77% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/HelloController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/HelloController.java index 7bb0bb2..7a54050 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/HelloController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/HelloController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/OrganizationController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/OrganizationController.java similarity index 92% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/OrganizationController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/OrganizationController.java index dd56969..69327c0 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/OrganizationController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/OrganizationController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -67,8 +67,8 @@ public class OrganizationController { public ResponseEntity updateOrganization(@PathVariable Integer id, @RequestBody Organization organization) { Organization org = repo.findOrganizationById(id); org.setOwnership(organization.getOwnership()); - org.setName_short(organization.getName_short()); - org.setName_full(organization.getName_full()); + org.setNameShort(organization.getNameShort()); + org.setNameFull(organization.getNameFull()); org.setType(organization.getType()); org.setInn(organization.getInn()); repo.save(org); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramController.java similarity index 93% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramController.java index 487b633..ebb2bb3 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/ProgramController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -49,7 +49,7 @@ public class ProgramController { Program p = repo.findProgramById(id); p.setName(program.getName()); p.setLenght(program.getLenght()); - p.setStudy_direction(program.getStudy_direction()); + p.setStudyDirection(program.getStudyDirection()); p.setPrice(program.getPrice()); p.setCretarea(program.getCretarea()); repo.save(p); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramCretareaController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramCretareaController.java new file mode 100644 index 0000000..abab518 --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/ProgramCretareaController.java @@ -0,0 +1,250 @@ +package ru.molokoin.resourceserviceapi.controllers.api; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import ru.molokoin.resourceserviceapi.entities.ProgramCretarea; +import ru.molokoin.resourceserviceapi.repositories.ProgramCretareaRepository; + +@RestController +@RequestMapping(path = "/cretarea", consumes = {"*/*"}) +public class ProgramCretareaController { + @Autowired + private final ProgramCretareaRepository repo; + + public ProgramCretareaController(ProgramCretareaRepository repo) { + this.repo = repo; + } + + /** + * Получение списка критериев постранично (предпочтительно) + * первая страница - 0 + * размер страницы по умолчанию - количество критериев в базе + * сортировка по умолчанию - id + * + * Если в запросе указано неприменимое поле sortBy - вполняется сортировка по умолчанию + * + * @param pageNo + * @param pageSize + * @param sortBy + * @return Page + */ + @GetMapping("/pages") + public Page + page(@RequestParam(name = "page", required = false) Integer pageNo, + @RequestParam(name = "size", required = false) Long pageSize, + @RequestParam(name = "sortBy", required = false) String sortBy){ + + + if (pageNo == null || pageNo < 0) pageNo = 0; + if (pageSize == null || pageSize < 0) pageSize = repo.count(); + if (sortBy == null) sortBy = "id"; + + Sort sort = Sort.by(sortBy); + Pageable pageable = PageRequest.of(pageNo, pageSize == null ? null : Math.toIntExact(pageSize), sort); + try{ + return repo.findAll(pageable); + }catch(PropertyReferenceException e){ + sortBy = "id"; + sort = Sort.by(sortBy); + pageable = PageRequest.of(pageNo, pageSize == null ? null : Math.toIntExact(pageSize), sort); + return repo.findAll(pageable); + } + } + + /** + * Получение количества критериев в базе + * - можно получить из объекта Page getСretareasPage() + * @return + */ + @GetMapping("/count") + public ResponseEntity getСretareasCount(){ + return new ResponseEntity<>(repo.count(), HttpStatus.OK); + } + + /** + * Получение объекта + * - по id (приоритетный параметр) + * - по nameShort (проверяет при отсутствии id в запросе) + * + * При вызове запроса нужно быть готовым получить либо булевый ответ, либо объект Критерия + * Метод может быть использован для проверки наличия Критерия в базе + * + * @param id + * @param nameShort + * @return false + * - В случае указания отсутствующих/не верных параметров + * - в случае отсутствия параметров + */ + @GetMapping("") + public ResponseEntity cretarea(@RequestParam(name="id", required = false) Long id, @RequestParam(name="nameShort", required = false) String nameShort){ + boolean exists = false; + if(id != null && repo.existsById(id)){ + return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.OK); + } + if (nameShort != null && repo.existsByNameShort(nameShort)){ + return new ResponseEntity<>(repo.findCretareaByNameShort(nameShort), HttpStatus.OK); + } + return new ResponseEntity<>(exists, HttpStatus.OK); + } + + /** + * Проверка наличия критерия в базе + * + * @param cretarea + * @return true если критерий в базе найден, иначе false + */ + @GetMapping("/exists") + public ResponseEntity exists(@RequestBody ProgramCretarea cretarea){ + return new ResponseEntity<>(repo.existsByNameShort(cretarea.getNameShort()), HttpStatus.OK); + } + + /** + * Получение списка отсутствующих в базе критериев + * @param cretareas + * @return + */ + @GetMapping("/absent") + public Page absent(@RequestBody List cretareas) { + List absent = new ArrayList<>(); + //проверяем наличие критериев в базе + for (ProgramCretarea cretarea : cretareas) { + if (!repo.existsByNameShort(cretarea.getNameShort())) { + //если не найден - добавляем в список + absent.add(cretarea); + } + } + //сортируем краткие наименования по алфавиту + absent.sort(Comparator.comparing(ProgramCretarea::getNameShort)); + + //gподготавливаем страницу для ответа + Page absentPage = new PageImpl<>(absent); + return absentPage; + } + + /** + * Сохранение Критерия в базе + * @param cretarea + * @return + */ + @PostMapping(path = "/create", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity save(@RequestBody ProgramCretarea cretarea) { + repo.save(cretarea); + return new ResponseEntity<>(cretarea, HttpStatus.CREATED); + } + + /** + * Обновление Критерия + * @param id + * @param cretarea + * @return + */ + @PutMapping(path = "/update/{id}", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateCretarea(@PathVariable Integer id, @RequestBody ProgramCretarea cretarea) { + ProgramCretarea pc = repo.findCretareaById(id); + pc.setName(cretarea.getName()); + pc.setNameShort(cretarea.getNameShort()); + repo.save(pc); + return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.CREATED); + } + + /** + * Обновление Критерия - с параметрами + * @param id + * @param cretarea + * @return обновленный критерий + */ + @PutMapping(path = "/update", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity update(@RequestParam(name="id", required = true) Integer id, @RequestBody ProgramCretarea cretarea) { + ProgramCretarea pc = repo.findCretareaById(id); + pc.setName(cretarea.getName()); + pc.setNameShort(cretarea.getNameShort()); + repo.save(pc); + return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.CREATED); + } + + /** + * Удаление Критерия + * @param id + * @return + */ + @DeleteMapping("/delete/{id}") + public ResponseEntity deleteCretarea(@PathVariable Long id){ + Boolean success = false; + if (id != null && id > 0) { + repo.deleteById(id); + } + success = true; + return new ResponseEntity<>(success, HttpStatus.OK); + } + + + /** + * Удаление Критерия - с параметрами + * @param id + * @return + */ + @DeleteMapping("/delete") + public ResponseEntity delete(@RequestParam(name="id", required = true) Long id){ + Boolean success = false; + ProgramCretarea pc = repo.findCretareaById(id); + try{ + repo.delete(pc); + success = true; + } catch(Exception e){ + System.out.println("Error: " + e.getMessage()); + success = false; + } + return new ResponseEntity<>(success, HttpStatus.OK); + } + + // /** + // * Получение объекта по ID (параметр в адресе) + // * @param id + // * @return + // */ + // @GetMapping("/{id}") + // public ResponseEntity getCretareaByID(@PathVariable Integer id){ + // return new ResponseEntity<>(repo.findCretareaById(id), HttpStatus.OK); + // } + + /** + * Получение общего списка критериев (не рекомендуется) + * @return List + */ + // @GetMapping("/list") + // public ResponseEntity> getСretareas(){ + // return new ResponseEntity<>(repo.findAll(), HttpStatus.OK); + // } + + + +} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StorageController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StorageController.java similarity index 96% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StorageController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StorageController.java index 7be24f7..5e81920 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StorageController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StorageController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StudentController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StudentController.java similarity index 90% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StudentController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StudentController.java index 9f78f5e..e07e63f 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/StudentController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/StudentController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -47,9 +47,9 @@ public class StudentController { produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateStudent(@PathVariable Integer id, @RequestBody Student student) { Student s = repo.findStudentById(id); - s.setFirst_name(student.getFirst_name()); - s.setSecond_name(student.getSecond_name()); - s.setLast_name(student.getLast_name()); + s.setFirstName(student.getFirstName()); + s.setSecondName(student.getSecondName()); + s.setLastName(student.getLastName()); s.setProfession(student.getProfession()); s.setCategory(student.getCategory()); s.setDirection(student.getDirection()); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/TeacherController.java similarity index 88% rename from resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java rename to resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/TeacherController.java index b0e7a90..8ba14f8 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/api/TeacherController.java @@ -1,4 +1,4 @@ -package ru.molokoin.resourceserviceapi.controllers; +package ru.molokoin.resourceserviceapi.controllers.api; import java.util.List; @@ -55,10 +55,10 @@ public class TeacherController { produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateTeacher(@PathVariable Integer id, @RequestBody Teacher teacher) { Teacher t = repo.findTeacherById(id); - t.setFirst_name(teacher.getFirst_name()); - t.setSecond_name(teacher.getSecond_name()); - t.setLast_name(teacher.getLast_name()); - t.setEmployee_id(teacher.getEmployee_id()); + t.setFirstName(teacher.getFirstName()); + t.setSecondName(teacher.getSecondName()); + t.setLastName(teacher.getLastName()); + t.setEmployeeId(teacher.getEmployeeId()); t.setSnils(teacher.getSnils()); repo.save(t); return new ResponseEntity<>(repo.findTeacherById(id), HttpStatus.CREATED); diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Building.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Building.java index 1e64de9..e137728 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Building.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Building.java @@ -21,16 +21,16 @@ public class Building { @GeneratedValue(strategy=GenerationType.AUTO) private long id; @Column(length=50) - private String name_short;//Сокращенное наименование - private String name_full;//Полное наименование - private String code_short;//Краткий код - private String code_full;//Полный код + private String nameShort;//Сокращенное наименование + private String nameFull;//Полное наименование + private String codeShort;//Краткий код + private String codeFull;//Полный код // подготовить конструкторы на все варианты внесения информации о преподавателях public Building(String name_short, String name_full, String code_short, String code_full){ - this.name_short = name_short; - this.name_full = name_full; - this.code_short = code_short; - this.code_full = code_full; + this.nameShort = name_short; + this.nameFull = name_full; + this.codeShort = code_short; + this.codeFull = code_full; } } diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Course.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Course.java index 168cc36..d61ff38 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Course.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Course.java @@ -28,10 +28,10 @@ public class Course { @GeneratedValue(strategy=GenerationType.AUTO) private long id;//уникальный идентификатор курса private String place;//место проведения занятий - private Date start_date;//дата начала курса - private Date protocol_date;//дата протокола - private String protocol_number;//номер протоколаssss - private String report_period;//отчетный период (наименование месяца) + private Date startDate;//дата начала курса + private Date protocolDate;//дата протокола + private String protocolNumber;//номер протоколаssss + private String reportPeriod;//отчетный период (наименование месяца) @ManyToOne(fetch = FetchType.EAGER, optional = false) @OnDelete(action = OnDeleteAction.SET_NULL) diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/EducationEntry.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/EducationEntry.java index e9e9c29..99d960d 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/EducationEntry.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/EducationEntry.java @@ -21,9 +21,9 @@ public class EducationEntry { @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; - private String sertificate_number;//Номер удостоверения - private String frdo_number;//ФРДО номер по реестру - private String eisot_number;//ЕИСОТ номер по реестру + private String sertificateNumber;//Номер удостоверения + private String frdoNumber;//ФРДО номер по реестру + private String eisotNumber;//ЕИСОТ номер по реестру private String ones;//Единички (вспомогатльный столбец) @ManyToOne(fetch = FetchType.EAGER, optional = false) diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Organization.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Organization.java index 126e0ee..bf44443 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Organization.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Organization.java @@ -21,8 +21,8 @@ public class Organization { @GeneratedValue(strategy=GenerationType.AUTO) private long id; private String ownership;//Форма собственности ПСК - private String name_short;//Сокращенное наименование - private String name_full;//Полное наименование + private String nameShort;//Сокращенное наименование + private String nameFull;//Полное наименование private String type;//вид ПСК - производственная/сервисная private String inn;//ИНН организации @@ -36,8 +36,8 @@ public class Organization { */ public Organization(String ownership, String name_short, String name_full, String type, String inn) { this.ownership = ownership; - this.name_short = name_short; - this.name_full = name_full; + this.nameShort = name_short; + this.nameFull = name_full; this.type = type; this.inn = inn; } diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Program.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Program.java index ec7bde1..151a50e 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Program.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Program.java @@ -23,7 +23,7 @@ public class Program { private long id; private String name;//Наименование private Integer lenght;//длительность программы - private String study_direction;//направление обучения: обязательное-производственное (учесть в ограничениях) + private String studyDirection;//направление обучения: обязательное-производственное (учесть в ограничениях) private Integer price; @ManyToOne(fetch = FetchType.EAGER, optional = false) diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/ProgramCretarea.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/ProgramCretarea.java index b06addc..5041800 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/ProgramCretarea.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/ProgramCretarea.java @@ -29,7 +29,7 @@ public class ProgramCretarea { // @Column(length=500) private String name;//Наименование // @Column(length=5) - private String name_short;//Наименование : сокращенно + private String nameShort;//Наименование : сокращенно /** * подготовить конструкторы на все варианты внесения информации о преподавателях @@ -37,8 +37,8 @@ public class ProgramCretarea { * @param name * @param name_short */ - public ProgramCretarea(String name, String name_short) { + public ProgramCretarea(String name, String nameShort) { this.name = name; - this.name_short = name_short; + this.nameShort = nameShort; } } diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Student.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Student.java index 7d1eb04..a05901a 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Student.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Student.java @@ -26,9 +26,9 @@ public class Student { @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; - private String first_name;//Имя - private String second_name;//Отчество - private String last_name;//Фамилия + private String firstName;//Имя + private String secondName;//Отчество + private String lastName;//Фамилия private String profession;//Профессия private String category;//Категория (ИТР или рабочий) private String direction;//Структурное подразделение diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Teacher.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Teacher.java index 25fc467..c908109 100644 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Teacher.java +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/entities/Teacher.java @@ -26,16 +26,16 @@ public class Teacher{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; - private String second_name;//Фамилия - private String first_name;//Имя - private String last_name;//Отчество - private String employee_id; + private String secondName;//Фамилия + private String firstName;//Имя + private String lastName;//Отчество + private String employeeId; private String snils; // подготовить конструкторы на все варианты внесения информации о преподавателях public Teacher(String second_name, String first_name, String last_name){ - this.second_name = second_name; - this.first_name = first_name; - this.last_name = last_name; + this.secondName = second_name; + this.firstName = first_name; + this.lastName = last_name; } } diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingFace.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingFace.java deleted file mode 100644 index 7a91edf..0000000 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingFace.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.molokoin.resourceserviceapi.repositories; - -import java.util.List; - -import org.springframework.data.repository.ListCrudRepository; -import org.springframework.stereotype.Repository; - -import ru.molokoin.resourceserviceapi.entities.Building; - -@Repository -public interface BuildingFace extends ListCrudRepository{ - List findAll(); - Building findBuildingById(long id); -} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingRepository.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingRepository.java new file mode 100644 index 0000000..9797876 --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/BuildingRepository.java @@ -0,0 +1,13 @@ +package ru.molokoin.resourceserviceapi.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import ru.molokoin.resourceserviceapi.entities.Building; + +@Repository +public interface BuildingRepository extends JpaRepository{ + Building findById(long id); + Building findByNameShort(String nameShort); + Boolean existsByNameShort(String nameShort); +} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepository.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepository.java new file mode 100644 index 0000000..d832e7a --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepository.java @@ -0,0 +1,13 @@ +package ru.molokoin.resourceserviceapi.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import ru.molokoin.resourceserviceapi.entities.ProgramCretarea; + +@Repository +public interface ProgramCretareaRepository extends JpaRepository{ + ProgramCretarea findCretareaById(long id); + ProgramCretarea findCretareaByNameShort(String nameShort); + Boolean existsByNameShort(String nameShort); +} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepositoryFace.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepositoryFace.java deleted file mode 100644 index 5e80f6b..0000000 --- a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/repositories/ProgramCretareaRepositoryFace.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.molokoin.resourceserviceapi.repositories; - -import java.util.List; - -import org.springframework.data.repository.ListCrudRepository; -import org.springframework.stereotype.Repository; - -import ru.molokoin.resourceserviceapi.entities.ProgramCretarea; - -@Repository -public interface ProgramCretareaRepositoryFace extends ListCrudRepository{ - List findAll(); - ProgramCretarea findCretareaById(long id); -} diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/BuildingService.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/BuildingService.java new file mode 100644 index 0000000..519449d --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/BuildingService.java @@ -0,0 +1,37 @@ +package ru.molokoin.resourceserviceapi.services; + +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import ru.molokoin.resourceserviceapi.entities.Building; +import ru.molokoin.resourceserviceapi.repositories.BuildingRepository; + +public class BuildingService { + private final BuildingRepository repo; + + public BuildingService(BuildingRepository repo) { + this.repo = repo; + } + + public Page findAll(Pageable pageable) { + return repo.findAll(pageable); + } + + public List findAll() { + return repo.findAll(); + } + + public Building findById(long id) { + return repo.findById(id); + } + + public Building findByNameShort(String nameShort) { + return repo.findByNameShort(nameShort); + } + + public Boolean existsByNameShort(String nameShort) { + return repo.existsByNameShort(nameShort); + } +} \ No newline at end of file diff --git a/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/ProgramCretareaService.java b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/ProgramCretareaService.java new file mode 100644 index 0000000..efc00e2 --- /dev/null +++ b/resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/services/ProgramCretareaService.java @@ -0,0 +1,38 @@ +package ru.molokoin.resourceserviceapi.services; + +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import ru.molokoin.resourceserviceapi.entities.ProgramCretarea; +import ru.molokoin.resourceserviceapi.repositories.ProgramCretareaRepository; + +public class ProgramCretareaService { + private final ProgramCretareaRepository repo; + + public ProgramCretareaService(ProgramCretareaRepository repo) { + this.repo = repo; + } + + public Page findAll(Pageable pageable) { + return repo.findAll(pageable); + } + + public List findAll() { + return repo.findAll(); + } + + public ProgramCretarea findCretareaById(int id) { + return repo.findCretareaById(id); + } + + public ProgramCretarea findCretareaByMameShort(String nameShort) { + return repo.findCretareaByNameShort(nameShort); + } + + public Boolean existsByNameShort(String nameShort) { + return repo.existsByNameShort(nameShort); + } + +} diff --git a/storage-rs/src/main/java/ru/molokoin/storagers/controller/StorageController.java b/storage-rs/src/main/java/ru/molokoin/storagers/controller/StorageController.java index ad64071..fa9ff0a 100644 --- a/storage-rs/src/main/java/ru/molokoin/storagers/controller/StorageController.java +++ b/storage-rs/src/main/java/ru/molokoin/storagers/controller/StorageController.java @@ -151,6 +151,18 @@ public class StorageController { return new ResponseEntity<>(storage.find(filename), HttpStatus.OK); } + /** + * Получение метаданных о файле, + * по имени файла, используя запрос с параметрами + * + * @param filename + * @return + */ + @GetMapping("/api/document/metadata") + public ResponseEntity getDocumentMetadataByFilename(@RequestParam(name="filename",required = false) String filename){ + return new ResponseEntity<>(storage.find(filename), HttpStatus.OK); + } + /** * Получение содержимого файла в json формате * @param filename @@ -163,6 +175,14 @@ public class StorageController { return new ResponseEntity<>(xlsx, HttpStatus.OK); } + @GetMapping("/api/document/content") + public ResponseEntity getDocumentContentAsMap(@RequestParam(name="filename", required = false) String filename){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + Map> cells = parts.lines(0, parts.getLineCount()-1); + return new ResponseEntity<>(cells, HttpStatus.OK); + } + /** * Получение содержимого файла в json формате * данные предоставляются построчно @@ -177,16 +197,44 @@ public class StorageController { return new ResponseEntity<>(cells, HttpStatus.OK); } + @GetMapping("/api/document/content/line") + public ResponseEntity getParamDocumentContentByLines(@RequestParam(name="filename", required = false) String filename, + @RequestParam(name="line", required = false) Integer line){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + List cells = parts.line(line); + + return new ResponseEntity<>(cells, HttpStatus.OK); + } + + /** + * + * @param filename + * @param from + * @param count + * @return + */ @GetMapping("/api/document/{filename}/content/part/{from}/{count}") public ResponseEntity getDocumentContentByParts(@PathVariable String filename, @PathVariable String from, @PathVariable String count){ Document doc = storage.find(filename); XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); - // System.out.println(parts.getLineCount()); Map> cells = parts.lines(Integer.parseInt(from), Integer.parseInt(count)); return new ResponseEntity<>(cells, HttpStatus.OK); } + @GetMapping("/api/document/content/part") + public ResponseEntity getParamDocumentContentByParts(@RequestParam(name = "filename", required = false) String filename, + @RequestParam(name = "from", required = false) Integer from, + @RequestParam(name = "count", required = false) Integer count){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + Map> cells = parts.lines(from, count); + return new ResponseEntity<>(cells, HttpStatus.OK); + } + + + @GetMapping("/api/document/{filename}/content/length") public ResponseEntity getDocumentContentLenght(@PathVariable String filename){ Document doc = storage.find(filename); @@ -194,6 +242,15 @@ public class StorageController { return new ResponseEntity<>(parts.getLineCount(), HttpStatus.OK); } + @GetMapping("/api/document/content/lenght") + public ResponseEntity getParamDocumentContentLenght(@RequestParam(name = "filename", required = false) String filename){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + return new ResponseEntity<>(parts.getLineCount(), HttpStatus.OK); + } + + + /** * Получение одного столбца в json формате * @param filename @@ -207,6 +264,16 @@ public class StorageController { return new ResponseEntity<>(cells, HttpStatus.OK); } + + @GetMapping("/api/document/content/column") + public ResponseEntity getParamDocumentContentByColumn(@RequestParam(name = "filename", required = false) String filename, + @RequestParam(name = "column", required = false) Integer num){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + List cells = parts.column(num); + return new ResponseEntity<>(cells, HttpStatus.OK); + } + /** * получение списка уникальных эементов в столбце * @param filename @@ -220,9 +287,19 @@ public class StorageController { return new ResponseEntity<>(cells, HttpStatus.OK); } + + @GetMapping("/api/document/content/column/unique") + public ResponseEntity getParamDocumentContentByColumnUnique(@RequestParam(name = "filename", required = false) String filename, + @RequestParam(name = "column", required = false) Integer num){ + Document doc = storage.find(filename); + XlsxMultipartDocument parts = new XlsxMultipartDocument(doc); + List cells = parts.columnUnique(num); + return new ResponseEntity<>(cells, HttpStatus.OK); + } + /* * TODO : сортировка - * - получение уникальных элементов столбца, + * * отсортированных по алфавиту * отсортированных по возростанию/убыванию * diff --git a/storage-rs/src/main/java/ru/molokoin/storagers/model/XlsxMultipartDocument.java b/storage-rs/src/main/java/ru/molokoin/storagers/model/XlsxMultipartDocument.java index 2f235a7..98e1721 100644 --- a/storage-rs/src/main/java/ru/molokoin/storagers/model/XlsxMultipartDocument.java +++ b/storage-rs/src/main/java/ru/molokoin/storagers/model/XlsxMultipartDocument.java @@ -13,6 +13,7 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Service; import lombok.AllArgsConstructor; import lombok.Builder;