Compare commits

..

2 Commits

Author SHA1 Message Date
zhoulongwang 58399fa227 srcw2
1 year ago
zhoulongwang 72d3df69e6 src3
1 year ago

@ -0,0 +1,73 @@
package crm.controller;
import crm.entity.Customer;
import crm.service.CustomerService;
import crm.utils.WriteCsvToResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@RestController
public class CSVController {
private CustomerService customerService;
public CSVController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping(value = "/customers", produces = "text/csv")
public void findCustomers(HttpServletResponse httpServletResponse) throws IOException {
List<Customer> customers = (List<Customer>) customerService.listAllCustomers();
WriteCsvToResponse.writeCustomers(httpServletResponse.getWriter(), customers);
}
@GetMapping(value = "/customers/{id}", produces = "text/csv")
public void findCustomer(@PathVariable Long id, HttpServletResponse httpServletResponse) throws IOException {
Customer customer = customerService.showCustomer(id);
WriteCsvToResponse.writeCustomer(httpServletResponse.getWriter(), customer);
}
// @GetMapping("/show-import")
// public String showImportCsvSite() {
// return "csv/import";
// }
/*@GetMapping("/import")
public String processRequestImportCsv(Model model) {
File document = ReadDataUtils.ReadFile("Select CSV file", null, "Only CSV Files", "csv");
// System.out.println(document.getName());
CSVReader reader;
List<String[]> data = new ArrayList<>();
try {
reader = new CSVReader(new FileReader(document));
String[] line;
while ((line = reader.readNext()) != null) {
// System.out.println(line[1] + "\t" + line[2]);
data.add(line);
// if(line[1].equals("QUICK SUB")){
// System.out.println(line[0] + "\t" + line[1] + "\t" + line[2]);
// }
}
model.addAttribute("data", data);
} catch (IOException e) {
e.printStackTrace();
}
*//*System.out.println(data.get(0)[1] + "\t" + data.get(0)[2]);
System.out.println(data.get(1)[1] + "\t" + data.get(1)[2]);*//*
return "csv/show";
}*/
// @GetMapping("/show")
// public String showPageWithCsvImported(@ModelAttribute List<String[]> data) {
// data.
// return "csv/show";
// }
}

@ -0,0 +1,504 @@
package crm.controller;
import crm.entity.Contract;
import crm.entity.Customer;
import crm.entity.User;
import crm.service.ContractService;
import crm.service.CustomerService;
import crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
@RequestMapping("/contract")
public class ContractController {
private ContractService contractService;
private CustomerService customerService;
private UserService userService;
public ContractController(ContractService contractService, CustomerService customerService, UserService userService) {
this.contractService = contractService;
this.customerService = customerService;
this.userService = userService;
}
/**
* /contract/list
* <p>
* Shows all contracts
*
* @param model model to add attributes to
* @return contract/list
*/
@GetMapping("/list")
public String showAllContracts(Model model) {
model.addAttribute("contracts", contractService.listAllContracts());
return "contract/list";
}
/**
* /contract/add
* <p>
* Shows add contract form
*
* @param model model to add attributes to
* @return contract/add
*/
@GetMapping("/add")
public String showFormAddContract(Model model) {
Iterable<Customer> customers = customerService.findAllByEnabledTrue();
Iterable<User> users = userService.listAllUsers();
model.addAttribute("contract", new Contract());
model.addAttribute("customers", customers);
model.addAttribute("users", users);
return "contract/add";
}
/**
* /contract/add
* <p>
* Processes add contract request
*
* @param contract variable type Contract
* @param bindingResult variable type BindingResult
* @return contract/success
*/
@PostMapping("/add")
public String processRequestAddContract(@Valid Contract contract, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/contract/add";
} else {
contractService.saveContract(contract);
return "contract/success";
}
}
/**
* /contract/edit/{id}
* <p>
* Shows edit contract form
*
* @param model model to add attributes to
* @param id variable type long contract id
* @return contract/edit
*/
@GetMapping("/edit/{id}")
public String showFormEditContract(Model model, @PathVariable Long id) {
model.addAttribute("contract", contractService.showContract(id));
return "contract/edit";
}
/**
* /contract/edit/{id}
* <p>
* Processes edit contract request
*
* @param id variable type long contract id
* @param contract variable type Contract
* @param bindingResult variable type BindingResult
* @return redirect:/contract/list
*/
@PostMapping("/edit/{id}")
public String processRequestEditContract(@PathVariable Long id, @Valid Contract contract,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/contract/edit/" + id;
} else {
contractService.saveContract(contract);
return "redirect:/contract/list";
}
}
/**
* /contract/name-search
* <p>
* Shows form to search contract by name
*
* @param model model to add attributes to
* @return contract/name-search
*/
@GetMapping("/name-search")
public String showNameSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/name-search";
}
/**
* /contract/name-search
* <p>
* Processes request searching by name
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show
*/
@PostMapping("/name-search")
public String processRequestNameSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contract", contractService.findByName(contract.getName()));
return "contract/show-one";
}
/**
* /contract/value-le-search
* <p>
* Shows form to search contract by value less equal than
*
* @param model model to add attributes to
* @return contract/value-le-search
*/
@GetMapping("/value-le-search")
public String showValueLeesThanEqualSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/value-le-search";
}
/**
* /contract/value-le-search
* <p>
* Processes request searching by value less equal than
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/value-le-search")
public String processRequestValueLessThanEqualSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByValueLessThanEqual(contract.getValue()));
return "contract/show-list";
}
/**
* /contract/value-ge-search
* <p>
* Shows form to search contract by value greater equal than
*
* @param model model to add attributes to
* @return contract/value-ge-search
*/
@GetMapping("/value-ge-search")
public String showValueGreaterThanEqualSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/value-ge-search";
}
/**
* /contract/value-ge-search
* <p>
* Processes request searching by value greater equal than
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/value-ge-search")
public String processRequestValueGreaterThanEqualSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByValueGreaterThanEqual(contract.getValue()));
return "contract/show-list";
}
/**
* /contract/begin-date-search
* <p>
* Shows form to search contract by begin date
*
* @param model model to add attributes to
* @return contract/begin-date-search
*/
@GetMapping("/begin-date-search")
public String showBeginDateSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/begin-date-search";
}
/**
* /contract/begin-date-search
* <p>
* Processes request searching by begin date
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/begin-date-search")
public String processRequestBeginDateSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByBeginDate(contract.getBeginDate()));
return "contract/show-list";
}
/**
* /contract/begin-date-before-search
* <p>
* Shows form to search contract by begin date before
*
* @param model model to add attributes to
* @return contract/begin-date-before-search
*/
@GetMapping("/begin-date-before-search")
public String showBeginDateBeforeSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/begin-date-before-search";
}
/**
* /contract/begin-date-before-search
* <p>
* Processes request searching by begin date before
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/begin-date-before-search")
public String processRequestBeginDateBeforeSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByBeginDateBefore(contract.getBeginDate()));
return "contract/show-list";
}
/**
* /contract/begin-date-after-search
* <p>
* Shows form to search contract by begin date after
*
* @param model model to add attributes to
* @return contract/begin-date-after-search
*/
@GetMapping("/begin-date-after-search")
public String showBeginDateAfterSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/begin-date-after-search";
}
/**
* /contract/begin-date-after-search
* <p>
* Processes request searching by begin date after
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/begin-date-after-search")
public String processRequestBeginDateAfterSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByBeginDateAfter(contract.getBeginDate()));
return "contract/show-list";
}
/**
* /contract/end-date-search
* <p>
* Shows form to search contract by end date
*
* @param model model to add attributes to
* @return contract/end-date-search
*/
@GetMapping("/end-date-search")
public String showEndDateSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/end-date-search";
}
/**
* /contract/end-date-search
* <p>
* Processes request searching by end date
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/end-date-search")
public String processRequestEndDateSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByEndDate(contract.getEndDate()));
return "contract/show-list";
}
/**
* /contract/end-date-before-search
* <p>
* Shows form to search contract by end date before
*
* @param model model to add attributes to
* @return contract/end-date-before-search
*/
@GetMapping("/end-date-before-search")
public String showEndDateBeforeSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/end-date-before-search";
}
/**
* /contract/end-date-before-search
* <p>
* Processes request searching by end date before
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/end-date-before-search")
public String processRequestEndDateBeforeSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByEndDateBefore(contract.getEndDate()));
return "contract/show-list";
}
/**
* /contract/end-date-after-search
* <p>
* Shows form to search contract by end date after
*
* @param model model to add attributes to
* @return contract/end-date-after-search
*/
@GetMapping("/end-date-after-search")
public String showEndDateAfterSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/end-date-after-search";
}
/**
* /contract/end-date-after-search
* <p>
* Processes request searching by end date after
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/end-date-after-search")
public String processRequestEndDateAfterSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByEndDateAfter(contract.getEndDate()));
return "contract/show-list";
}
/**
* /contract/status-search
* <p>
* Shows form to search contract by status
*
* @param model model to add attributes to
* @return contract/status-search
*/
@GetMapping("/status-search")
public String showStatusSearchForm(Model model) {
model.addAttribute("contract", new Contract());
return "contract/status-search";
}
/**
* /contract/status-search
* <p>
* Processes request searching by status
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/status-search")
public String processRequestStatusSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByStatus(contract.getStatus()));
return "contract/show-list";
}
/**
* /contract/customer-search
* <p>
* Shows form to search contract by customer
*
* @param model model to add attributes to
* @return contract/customer-search
*/
@GetMapping("/customer-search")
public String showCustomerSearchForm(Model model) {
Iterable<Customer> customers = customerService.findAllByEnabledTrue();
model.addAttribute("contract", new Contract());
model.addAttribute("customers", customers);
return "contract/customer-search";
}
/**
* /contract/customer-search
* <p>
* Processes request searching by customer
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/customer-search")
public String processRequestCustomerSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByCustomer(contract.getCustomer()));
return "contract/show-list";
}
/**
* /contract/customer-user-search
* <p>
* Shows form to search contract by customer and user
*
* @param model model to add attributes to
* @return contract/customer-user-search
*/
@GetMapping("/customer-user-search")
public String showCustomerUserSearchForm(Model model) {
Iterable<Customer> customers = customerService.findAllByEnabledTrue();
Iterable<User> users = userService.listAllUsers();
model.addAttribute("contract", new Contract());
model.addAttribute("customers", customers);
model.addAttribute("users", users);
return "contract/customer-user-search";
}
/**
* /contract/customer-user-search
* <p>
* Processes request searching by customer and user
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/customer-user-search")
public String processRequestCustomerUserSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByCustomerAndUser(contract.getCustomer(), contract.getUser()));
return "contract/show-list";
}
/**
* /contract/user-search
* <p>
* Shows form to search contract by user
*
* @param model model to add attributes to
* @return contract/user-search
*/
@GetMapping("/user-search")
public String showUserSearchForm(Model model) {
Iterable<User> users = userService.listAllUsers();
model.addAttribute("contract", new Contract());
model.addAttribute("users", users);
return "contract/user-search";
}
/**
* /contract/user-search
* <p>
* Processes request searching by user
*
* @param contract variable type Contract
* @param model model to add attributes to
* @return contract/show-list
*/
@PostMapping("/user-search")
public String processRequestUserSearch(@ModelAttribute Contract contract, Model model) {
model.addAttribute("contracts", contractService.findAllByUser(contract.getUser()));
return "contract/show-list";
}
}

@ -0,0 +1,386 @@
package crm.controller;
import crm.entity.Customer;
import crm.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
@RequestMapping("/customer")
public class CustomerController {
private CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
/**
* /customer/list
* <p>
* Shows all customers
*
* @param model model to add attributes to
* @return customer/list
*/
@GetMapping("/list")
public String showAllCustomers(Model model) {
model.addAttribute("customers", customerService.listAllCustomers());
return "customer/list";
}
/**
* /customer/add
* <p>
* Shows add customer form
*
* @param model model to add attributes to
* @return customer/add
*/
@GetMapping("/add")
public String showFormAddCustomer(Model model) {
model.addAttribute("customer", new Customer());
return "customer/add";
}
/**
* /customer/add
* <p>
* Processes add customer request
*
* @param customer variable type Customer
* @param bindingResult variable type BindingResult
* @return customer/success
*/
@PostMapping("/add")
public String processRequestAddCustomer(@Valid Customer customer, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/customer/add";
} else {
customerService.saveCustomer(customer);
return "customer/success";
}
}
/**
* /customer/edit/{id}
* <p>
* Shows edit customer form
*
* @param model model to add attributes to
* @param id variable type long customer id
* @return customer/edit
*/
@GetMapping("/edit/{id}")
public String showFormEditCustomer(Model model, @PathVariable Long id) {
model.addAttribute("customer", customerService.showCustomer(id));
return "customer/edit";
}
/**
* /customer/edit/{id}
* <p>
* Processes edit customer request
*
* @param id variable type long customer id
* @param customer variable type Customer
* @param bindingResult variable type BindingResult
* @return redirect:/customer/list
*/
@PostMapping("/edit/{id}")
public String processRequestEditCustomer(@PathVariable Long id, @Valid Customer customer,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/customer/edit/" + id;
} else {
customerService.saveCustomer(customer);
return "redirect:/customer/list";
}
}
/**
* /customer/addCustomerBasedOnAnotherOne/{id}
* <p>
* Shows create-customer-based-on-another-one form
*
* @param model model to add attributes to
* @param id variable type long reference customer id
* @return customer/add-customer-based-on-another-one
*/
@GetMapping("/addCustomerBasedOnAnotherOne/{id}")
public String showFormCreateCustomerBasedOnAnotherOne(Model model, @PathVariable Long id) {
model.addAttribute("customer", customerService.showCustomer(id));
return "customer/add-customer-based-on-another-one";
}
/**
* /customer/addCustomerBasedOnAnotherOne/{id}
* <p>
* Creates customer based on another one
*
* @param id variable type long reference customer id
* @param customer variable type Customer
* @param bindingResult variable type BindingResult
* @return redirect:/customer/list
*/
@PostMapping("/addCustomerBasedOnAnotherOne/{id}")
public String createCustomerBasedOnAnotherOne(@PathVariable Long id, @Valid Customer customer,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/customer/addCustomerBasedOnAnotherOne/" + id;
} else {
Customer newCustomer = new Customer(
customerService.getMaxId() + 1L,
customer.getName(),
customer.getEmail(),
customer.getPhone(),
customer.getCategories(),
customer.getFirstName(),
customer.getLastName(),
customer.getCity(),
customer.getAddress(),
customer.getEnabled());
customerService.saveCustomer(newCustomer);
return "redirect:/customer/list";
}
}
/**
* /customer/name-search
* <p>
* Shows form to search customer by name
*
* @param model model to add attributes to
* @return customer/name-search
*/
@GetMapping("/name-search")
public String showNameSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/name-search";
}
/**
* /customer/name-search
* <p>
* Processes request searching by name
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-one
*/
@PostMapping("/name-search")
public String processRequestNameSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customer", customerService.findOneByEnabledTrueAndName(customer.getName()));
return "customer/show-one";
}
/**
* /customer/email-search
* <p>
* Shows form to search customer by email
*
* @param model model to add attributes to
* @return customer/email-search
*/
@GetMapping("/email-search")
public String showEmailSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/email-search";
}
/**
* /customer/email-search
* <p>
* Processes request searching by city
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/email-search")
public String processRequestEmailSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers", customerService.findByEnabledTrueAndEmail(customer.getEmail()));
return "customer/show-list";
}
/**
* /customer/phone-search
* <p>
* Shows form to search customer by phone
*
* @param model model to add attributes to
* @return customer/phone-search
*/
@GetMapping("/phone-search")
public String showPhoneSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/phone-search";
}
/**
* /customer/phone-search
* <p>
* Processes request searching by phone
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/phone-search")
public String processRequestPhoneSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers", customerService.findByEnabledTrueAndPhone(customer.getPhone()));
return "customer/show-list";
}
/**
* /customer/first-name-search
* <p>
* Shows form to search customer by first name
*
* @param model model to add attributes to
* @return customer/first-name-search
*/
@GetMapping("/first-name-search")
public String showFirstNameSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/first-name-search";
}
/**
* /customer/first-name-search
* <p>
* Processes request searching by first name
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/first-name-search")
public String processRequestFirstNameSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers", customerService.findByEnabledTrueAndFirstName(customer.getFirstName()));
return "customer/show-list";
}
/**
* /customer/last-name-search
* <p>
* Shows form to search customer by last name
*
* @param model model to add attributes to
* @return customer/last-name-search
*/
@GetMapping("/last-name-search")
public String showLastNameSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/last-name-search";
}
/**
* /customer/last-name-search
* <p>
* Processes request searching by last name
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/last-name-search")
public String processRequestLastNameSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers", customerService.findByEnabledTrueAndLastName(customer.getLastName()));
return "customer/show-list";
}
/**
* /customer/first-name-last-name-search
* <p>
* Shows form to search customer by first name and last name
*
* @param model model to add attributes to
* @return customer/first-name-last-name-search
*/
@GetMapping("/first-name-last-name-search")
public String showFirstNameLastNameSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/first-name-last-name-search";
}
/**
* /customer/first-name-last-name-search
* <p>
* Processes request searching by first name and last name
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/first-name-last-name-search")
public String processRequestFirstNameLastNameSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers",
customerService.findByEnabledTrueAndFirstNameAndLastName(customer.getFirstName(), customer.getLastName()));
return "customer/show-list";
}
/**
* /customer/city-search
* <p>
* Shows form to search customer by city
*
* @param model model to add attributes to
* @return customer/city-search
*/
@GetMapping("/city-search")
public String showCitySearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/city-search";
}
/**
* /customer/city-search
* <p>
* Processes request searching by city
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/city-search")
public String processRequestCitySearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers", customerService.findByEnabledTrueAndCity(customer.getCity()));
return "customer/show-list";
}
/**
* /customer/city-address-search
* <p>
* Shows form to search customer by city and address
*
* @param model model to add attributes to
* @return customer/city-address-search
*/
@GetMapping("/city-address-search")
public String showCityAddressSearchForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer/city-address-search";
}
/**
* /customer/city-address-search
* <p>
* Processes request searching by city and address
*
* @param customer variable type Customer
* @param model model to add attributes to
* @return customer/show-list
*/
@PostMapping("/city-address-search")
public String processRequestCityAddressSearch(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customers",
customerService.findByEnabledTrueAndCityAndAddress(customer.getCity(), customer.getAddress()));
return "customer/show-list";
}
}

@ -0,0 +1,26 @@
package crm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
@Controller
@RequestMapping("/date")
public class DateTimeTestController {
@GetMapping("/test")
public String dateTimeTest(Model model) {
model.addAttribute("standardDate", new Date());
model.addAttribute("localDateTime", LocalDateTime.now());
model.addAttribute("localDate", LocalDate.now());
model.addAttribute("timestamp", Instant.now());
return "date/test";
}
}

@ -0,0 +1,26 @@
package crm.controller;
import crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class Export {
private UserService userService;
public Export(UserService userService) {
this.userService = userService;
}
/**
* Handle request to download an Excel document
*/
@GetMapping("/download")
public String download(Model model) {
model.addAttribute("users", userService.listAllUsers());
return "";
}
}

@ -0,0 +1,18 @@
package crm.controller;
//@Controller
public class ExportCustomers {
// @Autowired
// CustomerService customerService;
//
// /**
// * Handle request to download an Excel document
// */
// @GetMapping("/download")
// public String download(Model model) {
// model.addAttribute("customers", customerService.listAllCustomers());
// return "";
// }
}

@ -0,0 +1,22 @@
package crm.controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyErrorController implements ErrorController {
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public String error() {
return "Error handling";
}
@Override
public String getErrorPath() {
return PATH;
}
}

@ -0,0 +1,65 @@
package crm.controller;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import crm.entity.Pdf;
import crm.service.PdfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@Controller
@Slf4j
public class PdfController {
private PdfService pdfService;
public PdfController(PdfService pdfService) {
this.pdfService = pdfService;
}
private void generateSamplePdf(String fileName, String text) throws FileNotFoundException, DocumentException {
if (!fileName.endsWith(".pdf")) {
fileName += ".pdf";
}
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
Paragraph paragraph = new Paragraph(text);
document.add(paragraph);
document.close();
}
@GetMapping("/pdf-generator")
public String pdfGenerator(Model model) {
model.addAttribute("pdf", new Pdf());
return "pdf/generator";
}
@PostMapping("/pdf-generator")
public String generatePdf(@Valid Pdf pdf, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/pdf-generator";
} else {
try {
generateSamplePdf(pdf.getName(), pdf.getContent());
pdfService.savePdf(pdf);
} catch (FileNotFoundException e) {
log.info("File Not Found");
} catch (DocumentException e) {
log.info("Document");
}
return "pdf/success";
}
}
}

@ -0,0 +1,47 @@
package crm.controller;
import crm.entity.User;
import crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
@Controller
public class RegisterController {
private UserService userService;
public RegisterController(UserService userService) {
this.userService = userService;
}
@GetMapping("/register")
public String showRegistrationPage(Model model, User user){
model.addAttribute("user", user);
return "register";
}
@PostMapping("/register")
public String processRegistrationForm(Model model, @Valid User user, BindingResult bindingResult) {
User userFromDB = userService.findByUsername(user.getUsername());
if (userFromDB != null) {
model.addAttribute("alreadyRegisteredMessage",
"Oops! There is already a user registered with the email provided.");
bindingResult.reject("email");
return "register";
}
if (bindingResult.hasErrors()) {
return "redirect:/register";
} else {
userService.saveUser(user);
return "success";
}
}
}

@ -0,0 +1,92 @@
package crm.controller;
import crm.entity.User;
import crm.service.UserService;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.RequestMapping;
import javax.validation.Valid;
@Controller
@RequestMapping("/user")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
/**
* /user/list
* <p>
* Shows all users
*
* @param model model to attributes to
* @return user/list
*/
@GetMapping("/list")
public String showAllUsers(Model model, @AuthenticationPrincipal UserDetails currentUser) {
model.addAttribute("currentUser", userService.findByUsername(currentUser.getUsername()));
model.addAttribute("users", userService.listAllUsers());
return "user/list";
}
/**
* /user/edit/{id}
* <p>
* Shows edit user form
*
* @param model model to attributes to
* @param id variable type long user id
* @return user/edit
*/
@GetMapping("/edit/{id}")
public String showFormEditUser(Model model, @PathVariable Long id) {
model.addAttribute("user", userService.showUser(id));
return "user/edit";
}
/**
* /user/edit/{id}
* <p>
* Processes edit user request
*
* @param id variable type long user id
* @param user variable type User
* @param bindingResult variable type BindingResult
* @return redirect:/user/list
*/
@PostMapping("/edit/{id}")
public String processRequestEditUser(@PathVariable Long id, @Valid User user,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "redirect:/user/edit/" + id;
} else {
userService.editUser(user);
return "redirect:/user/list";
}
}
/**
* /user/delete/{id}
* <p>
* Deletes user
*
* @param id variable type long user id
* @return redirect:/user/list
*/
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(userService.showUser(id));
return "redirect:/user/list";
}
}

@ -0,0 +1,38 @@
package crm.csv;
import com.opencsv.CSVReader;
import crm.utils.ReadDataUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVTest {
public static void main(String[] args) {
File document = ReadDataUtils.ReadFile("Select CSV file", null, "Only CSV Files", "csv");
// System.out.println(document.getName());
CSVReader reader;
List<Object[]> data = new ArrayList<>();
try {
reader = new CSVReader(new FileReader(document));
String[] line;
while ((line = reader.readNext()) != null) {
// System.out.println(line[1] + "\t" + line[2]);
data.add(line);
if(line[1].equals("QUICK SUB")){
System.out.println(line[0] + "\t" + line[1] + "\t" + line[2]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
/*System.out.println(data.get(0)[1] + "\t" + data.get(0)[2]);
System.out.println(data.get(1)[1] + "\t" + data.get(1)[2]);*/
}
}

@ -0,0 +1,20 @@
package crm.entity;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "category_id")
private Long id;
@Column(name = "category")
private String name;
}

@ -0,0 +1,49 @@
package crm.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDate;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Contract {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
private String name;
private String content;
private BigDecimal value;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate beginDate;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate endDate;
@Enumerated(EnumType.STRING)
private Status status;
@ManyToOne
private Customer customer;
@ManyToOne
private User user;
// @Transient
// private DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
}

@ -0,0 +1,52 @@
package crm.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
@Data
public class CurrentUser implements UserDetails {
private User user;
private Set<GrantedAuthority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

@ -0,0 +1,54 @@
package crm.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Size;
import java.util.Set;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
@Size(min = 2)
private String name;
@Column(name = "email", nullable = false, unique = true)
@Email(message = "Please provide a valid e-mail")
@NotEmpty(message = "Please provide an e-mail")
private String email;
@Digits(fraction = 0, integer = 20)
private int phone;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "customer_category",
joinColumns = @JoinColumn(name = "customer_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private Set<Category> categories;
private String firstName;
private String lastName;
private String city;
private String address;
private int enabled;
}

@ -0,0 +1,29 @@
package crm.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.Size;
@Entity(name = "pdf")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Pdf {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
@Size(min = 2)
private String name;
@Transient
private String content;
}

@ -0,0 +1,25 @@
package crm.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Data
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private int id;
@Column(name = "role", unique = true)
private String name;
}

@ -0,0 +1,12 @@
package crm.entity;
public enum Status {
PROPOSED,
NEGOTIATED,
IMPLEMENTED,
DONE;
public static final Status[] ALL = {PROPOSED, NEGOTIATED, IMPLEMENTED, DONE};
}

@ -0,0 +1,58 @@
package crm.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
@Entity(name = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(name = "email", nullable = false, unique = true)
@Email(message = "Please provide a valid e-mail")
@NotEmpty(message = "Please provide an e-mail")
private String email;
private String firstName;
private String lastName;
private String password;
private int enabled;
@ManyToOne
private Role role;
public int getColumnCount() {
return getClass().getDeclaredFields().length;
}
public int getRole_id() {
return role.getId();
}
public String getRole_name() {
return role.getName();
}
public String getName() {
return firstName + " " + lastName;
}
}

@ -0,0 +1,18 @@
package crm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
@EntityScan(
basePackageClasses = {CrmApplication.class, Jsr310JpaConverters.class}
)
@SpringBootApplication
public class CrmApplication {
public static void main(String[] args) {
SpringApplication.run(CrmApplication.class, args);
}
}

@ -0,0 +1,48 @@
package crm;
import crm.service.SpringDataUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SpringDataUserDetailsService customUserDetailsService() {
return new SpringDataUserDetailsService();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService()).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**", "/user/delete/**").hasRole("ADMIN")
.antMatchers("/pdf-generator", "/search/**", "/customer/**", "/user/edit/**", "/user/list", "/contract/**").hasAnyRole( "ADMIN", "USER", "MANAGER", "OWNER")
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403");
}
}

@ -0,0 +1,165 @@
package crm;
import crm.viewResolver.CsvViewResolver;
import crm.viewResolver.ExcelViewResolver;
import crm.viewResolver.PdfViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.dialect.springdata.SpringDataDialect;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/").setViewName("index");
registry.addViewController("/user/menu").setViewName("user/user-menu");
registry.addViewController("/customer/menu").setViewName("customer/customer-menu");
registry.addViewController("/contract/menu").setViewName("contract/contract-menu");
registry.addViewController("/contract/search").setViewName("contract/search");
registry.addViewController("/admin").setViewName("admin/panel");
registry.addViewController("/search").setViewName("search");
registry.addViewController("/403").setViewName("403");
registry.addViewController("/logout").setViewName("logout");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.ignoreAcceptHeader(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.useJaf(false);
final Map<String,MediaType> mediaTypes = new HashMap<>();
mediaTypes.put("html", MediaType.TEXT_HTML);
mediaTypes.put("json", MediaType.APPLICATION_JSON);
mediaTypes.put("xls", MediaType.valueOf("application/vnd.ms-excel"));
mediaTypes.put("pdf", MediaType.APPLICATION_PDF);
mediaTypes.put("csv", new MediaType("text","csv", Charset.forName("utf-8")));
configurer.mediaTypes(mediaTypes);
}
/**
* Configure ContentNegotiatingViewResolver
*/
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolvers.add(excelViewResolver());
resolvers.add(pdfViewResolver());
resolvers.add(viewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setCacheable(false);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// add dialect spring security
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(new Java8TimeDialect());
engine.setTemplateResolver(templateResolver);
return engine;
}
@Bean
@Description("Thymeleaf view resolver")
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
/**
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
@Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
}
/**
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
@Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
/**
* Configure View resolver to provide Pdf output using iText library to
* generate pdf output for an object content
*/
@Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
}
@Bean
public SpringDataDialect springDataDialect() {
return new SpringDataDialect();
}
}

@ -0,0 +1,12 @@
package crm.repository;
import crm.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {
Category findByName(String name);
}

@ -0,0 +1,42 @@
package crm.repository;
import crm.entity.Contract;
import crm.entity.Customer;
import crm.entity.Status;
import crm.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.time.LocalDate;
@Repository
public interface ContractRepository extends JpaRepository<Contract, Long> {
Contract findByName(String contractName);
Iterable<Contract> findAllByValueLessThanEqual(BigDecimal value);
Iterable<Contract> findAllByValueGreaterThanEqual(BigDecimal value);
Iterable<Contract> findAllByBeginDate(LocalDate beginDate);
Iterable<Contract> findAllByBeginDateBefore(LocalDate beforeBeginDate);
Iterable<Contract> findAllByBeginDateAfter(LocalDate afterBeginDate);
Iterable<Contract> findAllByEndDate(LocalDate endDate);
Iterable<Contract> findAllByEndDateBefore(LocalDate beforeEndDate);
Iterable<Contract> findAllByEndDateAfter(LocalDate afterEndDate);
Iterable<Contract> findAllByStatus(Status status);
Iterable<Contract> findAllByCustomer(Customer customer);
Iterable<Contract> findAllByCustomerAndUser(Customer customer, User user);
Iterable<Contract> findAllByUser(User user);
}

@ -0,0 +1,55 @@
package crm.repository;
import crm.entity.Category;
import crm.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Set;
/**
* NOTICE
* <p>
* When some declaration
* does NOT HAVE Enabled param
* searching works for ALL customers
* also for NOT enabled (inactive) ones
*/
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query(value = "select max(id) from crm.customer", nativeQuery = true)
Long getMaxId();
Iterable<Customer> findAllByEnabled(int enabled);
Customer findOneByEnabledAndName(int enabled, String name);
Customer findOneByName(String name);
Iterable<Customer> findByEnabledAndEmail(int enabled, String email);
Iterable<Customer> findByEmail(String email);
Iterable<Customer> findByEnabledAndCity(int enabled, String city);
Iterable<Customer> findByCity(String city);
Iterable<Customer> findByEnabledAndCityAndAddress(int enabled, String city, String address);
Iterable<Customer> findByCityAndAddress(String city, String address);
Iterable<Customer> findByEnabledAndPhone(int enabled, int phone);
Iterable<Customer> findByPhone(int phone);
Iterable<Customer> findByEnabledAndFirstName(int enabled, String firstName);
Iterable<Customer> findByFirstName(String firstName);
Iterable<Customer> findByEnabledAndLastName(int enabled, String lastName);
Iterable<Customer> findByLastName(String lastName);
Iterable<Customer> findByEnabledAndFirstNameAndLastName(int enabled, String firstName, String lastName);
Iterable<Customer> findByFirstNameAndLastName(String firstName, String lastName);
Iterable<Customer> findByEnabledAndCategories(int enabled, Set<Category> category);
Iterable<Customer> findByCategories(Set<Category> category);
}

@ -0,0 +1,12 @@
package crm.repository;
import crm.entity.Pdf;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PdfRepository extends JpaRepository<Pdf, Long> {
Pdf findByName(String name);
}

@ -0,0 +1,12 @@
package crm.repository;
import crm.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer> {
Role findByName(String name);
}

@ -0,0 +1,14 @@
package crm.repository;
import crm.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
Iterable<User> findAllByEnabled (int enabled);
}

@ -0,0 +1,45 @@
package crm.service;
import crm.entity.Contract;
import crm.entity.Customer;
import crm.entity.Status;
import crm.entity.User;
import java.math.BigDecimal;
import java.time.LocalDate;
public interface ContractService {
Contract findByName(String contractName);
Iterable<Contract> listAllContracts();
Contract showContract(Long id);
Iterable<Contract> findAllByValueLessThanEqual(BigDecimal value);
Iterable<Contract> findAllByValueGreaterThanEqual(BigDecimal value);
Iterable<Contract> findAllByBeginDate(LocalDate beginDate);
Iterable<Contract> findAllByBeginDateBefore(LocalDate beforeBeginDate);
Iterable<Contract> findAllByBeginDateAfter(LocalDate afterBeginDate);
Iterable<Contract> findAllByEndDate(LocalDate endDate);
Iterable<Contract> findAllByEndDateBefore(LocalDate beforeEndDate);
Iterable<Contract> findAllByEndDateAfter(LocalDate afterEndDate);
Iterable<Contract> findAllByStatus(Status status);
Iterable<Contract> findAllByCustomer(Customer customer);
Iterable<Contract> findAllByCustomerAndUser(Customer customer, User user);
Iterable<Contract> findAllByUser(User user);
void saveContract(Contract contract);
}

@ -0,0 +1,110 @@
package crm.service;
import crm.entity.Contract;
import crm.entity.Customer;
import crm.entity.Status;
import crm.entity.User;
import crm.repository.ContractRepository;
import crm.repository.CustomerRepository;
import crm.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
@Service
public class ContractServiceImpl implements ContractService {
private ContractRepository contractRepository;
private CustomerRepository customerRepository;
private UserRepository userRepository;
public ContractServiceImpl(ContractRepository contractRepository, CustomerRepository customerRepository, UserRepository userRepository) {
this.contractRepository = contractRepository;
this.customerRepository = customerRepository;
this.userRepository = userRepository;
}
@Override
public Contract findByName(String contractName) {
return contractRepository.findByName(contractName);
}
@Override
public Iterable<Contract> listAllContracts() {
return contractRepository.findAll();
}
@Override
public Contract showContract(Long id) {
return contractRepository.findOne(id);
}
@Override
public Iterable<Contract> findAllByValueLessThanEqual(BigDecimal value) {
return contractRepository.findAllByValueLessThanEqual(value);
}
@Override
public Iterable<Contract> findAllByValueGreaterThanEqual(BigDecimal value) {
return contractRepository.findAllByValueGreaterThanEqual(value);
}
@Override
public Iterable<Contract> findAllByBeginDate(LocalDate beginDate) {
return contractRepository.findAllByBeginDate(beginDate);
}
@Override
public Iterable<Contract> findAllByBeginDateBefore(LocalDate beforeBeginDate) {
return contractRepository.findAllByBeginDateBefore(beforeBeginDate);
}
@Override
public Iterable<Contract> findAllByBeginDateAfter(LocalDate afterBeginDate) {
return contractRepository.findAllByBeginDateAfter(afterBeginDate);
}
@Override
public Iterable<Contract> findAllByEndDate(LocalDate endDate) {
return contractRepository.findAllByEndDate(endDate);
}
@Override
public Iterable<Contract> findAllByEndDateBefore(LocalDate beforeEndDate) {
return contractRepository.findAllByEndDateBefore(beforeEndDate);
}
@Override
public Iterable<Contract> findAllByEndDateAfter(LocalDate afterEndDate) {
return contractRepository.findAllByEndDateAfter(afterEndDate);
}
@Override
public Iterable<Contract> findAllByStatus(Status status) {
return contractRepository.findAllByStatus(status);
}
@Override
public Iterable<Contract> findAllByCustomer(Customer customer) {
return contractRepository.findAllByCustomer(customer);
}
@Override
public Iterable<Contract> findAllByCustomerAndUser(Customer customer, User user) {
return contractRepository.findAllByCustomerAndUser(customer, user);
}
@Override
public Iterable<Contract> findAllByUser(User user) {
return contractRepository.findAllByUser(user);
}
@Override
public void saveContract(Contract contract) {
customerRepository.save(customerRepository.findAll());
userRepository.save(userRepository.findAll());
contractRepository.save(contract);
}
}

@ -0,0 +1,70 @@
package crm.service;
import crm.entity.Category;
import crm.entity.Customer;
import java.util.Set;
/**
* NOTICE
* <p>
* When some declaration
* does NOT HAVE Enabled param
* searching works for ALL customers
* also for NOT enabled (inactive) ones
*/
public interface CustomerService {
Long getMaxId();
Iterable<Customer> listAllCustomers();
Customer showCustomer(Long id);
Iterable<Customer> findAllByEnabledTrue();
Iterable<Customer> findAllByEnabledFalse();
Customer findOneByEnabledTrueAndName(String name);
Customer findOneByEnabledFalseAndName(String name);
Customer findOneByName(String name);
Iterable<Customer> findByEnabledTrueAndEmail(String email);
Iterable<Customer> findByEnabledFalseAndEmail(String email);
Iterable<Customer> findByEmail(String email);
Iterable<Customer> findByEnabledTrueAndPhone(int phone);
Iterable<Customer> findByEnabledFalseAndPhone(int phone);
Iterable<Customer> findByPhone(int phone);
Iterable<Customer> findByEnabledTrueAndCategories(Set<Category> category);
Iterable<Customer> findByEnabledFalseAndCategories(Set<Category> category);
Iterable<Customer> findByCategories(Set<Category> category);
Iterable<Customer> findByEnabledTrueAndFirstName(String firstName);
Iterable<Customer> findByEnabledFalseAndFirstName(String firstName);
Iterable<Customer> findByFirstName(String firstName);
Iterable<Customer> findByEnabledTrueAndLastName(String lastName);
Iterable<Customer> findByEnabledFalseAndLastName(String lastName);
Iterable<Customer> findByLastName(String lastName);
Iterable<Customer> findByEnabledTrueAndFirstNameAndLastName(String firstName, String lastName);
Iterable<Customer> findByEnabledFalseAndFirstNameAndLastName(String firstName, String lastName);
Iterable<Customer> findByFirstNameAndLastName(String firstName, String lastName);
Iterable<Customer> findByEnabledTrueAndCity(String city);
Iterable<Customer> findByEnabledFalseAndCity(String city);
Iterable<Customer> findByCity(String city);
Iterable<Customer> findByEnabledTrueAndCityAndAddress(String city, String address);
Iterable<Customer> findByEnabledFalseAndCityAndAddress(String city, String address);
Iterable<Customer> findByCityAndAddress(String city, String address);
void saveCustomer(Customer customer);
//
// void editCustomer(Customer customer);
//
// void deleteCustomer(Customer customer);
}

@ -0,0 +1,196 @@
package crm.service;
import crm.entity.Category;
import crm.entity.Customer;
import crm.repository.CustomerRepository;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class CustomerServiceImpl implements CustomerService {
private CustomerRepository customerRepository;
public CustomerServiceImpl(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Override
public Long getMaxId() {
return customerRepository.getMaxId();
}
@Override
public Iterable<Customer> listAllCustomers() {
return customerRepository.findAll();
}
@Override
public Customer showCustomer(Long id) {
return customerRepository.findOne(id);
}
@Override
public Iterable<Customer> findAllByEnabledTrue() {
return customerRepository.findAllByEnabled(1);
}
@Override
public Iterable<Customer> findAllByEnabledFalse() {
return customerRepository.findAllByEnabled(0);
}
@Override
public Customer findOneByEnabledTrueAndName(String name) {
return customerRepository.findOneByEnabledAndName(1, name);
}
@Override
public Customer findOneByEnabledFalseAndName(String name) {
return customerRepository.findOneByEnabledAndName(0, name);
}
@Override
public Customer findOneByName(String name) {
return customerRepository.findOneByName(name);
}
@Override
public Iterable<Customer> findByEnabledTrueAndEmail(String email) {
return customerRepository.findByEnabledAndEmail(1, email);
}
@Override
public Iterable<Customer> findByEnabledFalseAndEmail(String email) {
return customerRepository.findByEnabledAndEmail(0, email);
}
@Override
public Iterable<Customer> findByEmail(String email) {
return customerRepository.findByEmail(email);
}
@Override
public Iterable<Customer> findByEnabledTrueAndPhone(int phone) {
return customerRepository.findByEnabledAndPhone(1, phone);
}
@Override
public Iterable<Customer> findByEnabledFalseAndPhone(int phone) {
return customerRepository.findByEnabledAndPhone(0, phone);
}
@Override
public Iterable<Customer> findByPhone(int phone) {
return customerRepository.findByPhone(phone);
}
@Override
public Iterable<Customer> findByEnabledTrueAndCategories(Set<Category> category) {
return customerRepository.findByEnabledAndCategories(1, category);
}
//
@Override
public Iterable<Customer> findByEnabledFalseAndCategories(Set<Category> category) {
return customerRepository.findByEnabledAndCategories(0, category);
}
@Override
public Iterable<Customer> findByCategories(Set<Category> category) {
return customerRepository.findByCategories(category);
}
@Override
public Iterable<Customer> findByEnabledTrueAndFirstName(String firstName) {
return customerRepository.findByEnabledAndFirstName(1, firstName);
}
@Override
public Iterable<Customer> findByEnabledFalseAndFirstName(String firstName) {
return customerRepository.findByEnabledAndFirstName(0, firstName);
}
@Override
public Iterable<Customer> findByFirstName(String firstName) {
return customerRepository.findByFirstName(firstName);
}
@Override
public Iterable<Customer> findByEnabledTrueAndLastName(String lastName) {
return customerRepository.findByEnabledAndLastName(1, lastName);
}
@Override
public Iterable<Customer> findByEnabledFalseAndLastName(String lastName) {
return customerRepository.findByEnabledAndLastName(0, lastName);
}
@Override
public Iterable<Customer> findByLastName(String lastName) {
return customerRepository.findByLastName(lastName);
}
@Override
public Iterable<Customer> findByEnabledTrueAndFirstNameAndLastName(String firstName, String lastName) {
return customerRepository.findByEnabledAndFirstNameAndLastName(1, firstName, lastName);
}
@Override
public Iterable<Customer> findByEnabledFalseAndFirstNameAndLastName(String firstName, String lastName) {
return customerRepository.findByEnabledAndFirstNameAndLastName(0, firstName, lastName);
}
@Override
public Iterable<Customer> findByFirstNameAndLastName(String firstName, String lastName) {
return customerRepository.findByFirstNameAndLastName(firstName, lastName);
}
@Override
public Iterable<Customer> findByEnabledTrueAndCity(String city) {
return customerRepository.findByEnabledAndCity(1, city);
}
@Override
public Iterable<Customer> findByEnabledFalseAndCity(String city) {
return customerRepository.findByEnabledAndCity(0, city);
}
@Override
public Iterable<Customer> findByCity(String city) {
return customerRepository.findByCity(city);
}
@Override
public Iterable<Customer> findByEnabledTrueAndCityAndAddress(String city, String address) {
return customerRepository.findByEnabledAndCityAndAddress(1, city, address);
}
@Override
public Iterable<Customer> findByEnabledFalseAndCityAndAddress(String city, String address) {
return customerRepository.findByEnabledAndCityAndAddress(0, city, address);
}
@Override
public Iterable<Customer> findByCityAndAddress(String city, String address) {
return customerRepository.findByCityAndAddress(city, address);
}
@Override
public void saveCustomer(Customer customer) {
customer.setEnabled(1);
customerRepository.save(customer);
}
//
// @Override
// public void editCustomer(Customer customer) {
// customerRepository.save(customer);
// }
//
// @Override
// public void deleteCustomer(Customer customer) {
// customer.setEnabled(0);
// customerRepository.save(customer);
// }
}

@ -0,0 +1,11 @@
package crm.service;
import crm.entity.Pdf;
public interface PdfService {
Pdf findByName(String name);
void savePdf(Pdf pdf);
}

@ -0,0 +1,26 @@
package crm.service;
import crm.entity.Pdf;
import crm.repository.PdfRepository;
import org.springframework.stereotype.Service;
@Service
public class PdfServiceImpl implements PdfService {
private PdfRepository pdfRepository;
public PdfServiceImpl(PdfRepository pdfRepository) {
this.pdfRepository = pdfRepository;
}
@Override
public Pdf findByName(String name) {
return pdfRepository.findByName(name);
}
@Override
public void savePdf(Pdf pdf) {
pdfRepository.save(pdf);
}
}

@ -0,0 +1,9 @@
package crm.service;
import crm.entity.Role;
public interface RoleService {
Iterable<Role> listAllRoles();
}

@ -0,0 +1,21 @@
package crm.service;
import crm.entity.Role;
import crm.repository.RoleRepository;
import org.springframework.stereotype.Service;
@Service
public class RoleServiceImpl implements RoleService {
private RoleRepository roleRepository;
public RoleServiceImpl(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Override
public Iterable<Role> listAllRoles() {
return roleRepository.findAll();
}
}

@ -0,0 +1,37 @@
package crm.service;
import crm.entity.CurrentUser;
import crm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
@Autowired
UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
String role = user.getRole().getName();
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(role));
CurrentUser currentUser = new CurrentUser();
currentUser.setUser(user);
currentUser.setAuthorities(grantedAuthorities);
return currentUser;
}
}

@ -0,0 +1,19 @@
package crm.service;
import crm.entity.User;
public interface UserService {
User findByUsername(String username);
Iterable<User> listAllUsers();
User showUser(Long id);
void saveUser(User user);
void editUser(User user);
void deleteUser(User user);
}

@ -0,0 +1,107 @@
package crm.service;
import crm.entity.Role;
import crm.entity.User;
import crm.repository.RoleRepository;
import crm.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
private BCryptPasswordEncoder passwordEncoder;
private AuthenticationManager authenticationManager;
private SpringDataUserDetailsService springDataUserDetailsService;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Autowired
public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Autowired
public void setSpringDataUserDetailsService(SpringDataUserDetailsService springDataUserDetailsService) {
this.springDataUserDetailsService = springDataUserDetailsService;
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public Iterable<User> listAllUsers() {
return userRepository.findAllByEnabled(1);
}
@Override
public User showUser(Long id) {
return userRepository.findOne(id);
}
@Override
public void saveUser(User user) {
Role userRole = roleRepository.findByName("ROLE_USER");
user.setRole(userRole);
user.setEnabled(1);
String password = user.getPassword();
user.setPassword(passwordEncoder.encode(password));
userRepository.save(user);
if (user.getId().equals(1L)) {
userRole = roleRepository.findByName("ROLE_ADMIN");
user.setRole(userRole);
userRepository.save(user);
}
UserDetails userDetails = springDataUserDetailsService.loadUserByUsername(user.getUsername());
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
@Override
public void editUser(User user) {
String password = user.getPassword();
user.setPassword(passwordEncoder.encode(password));
Role userRole = roleRepository.findByName("ROLE_USER");
try {
userRole = roleRepository.findOne(user.getRole().getId());
} catch (NullPointerException e) {
userRole = roleRepository.findByName("ROLE_USER");
} finally {
user.setRole(userRole);
user.setEnabled(1);
userRepository.save(user);
}
}
@Override
public void deleteUser(User user) {
user.setEnabled(0);
user.setPassword(null);
userRepository.save(user);
}
}
Loading…
Cancel
Save