1 | package finki.it.terapijamkbackend.spring.controllers;
|
---|
2 | import finki.it.terapijamkbackend.spring.entities.Coupon;
|
---|
3 | import finki.it.terapijamkbackend.spring.services.CouponsService;
|
---|
4 | import jakarta.persistence.EntityNotFoundException;
|
---|
5 | import org.springframework.beans.factory.annotation.Autowired;
|
---|
6 | import org.springframework.http.HttpStatus;
|
---|
7 | import org.springframework.http.ResponseEntity;
|
---|
8 | import org.springframework.web.bind.annotation.*;
|
---|
9 |
|
---|
10 | import java.util.List;
|
---|
11 | import java.util.Optional;
|
---|
12 |
|
---|
13 | @RestController
|
---|
14 | @RequestMapping("/api/coupons")
|
---|
15 | public class CouponController {
|
---|
16 | @Autowired
|
---|
17 | private CouponsService couponService;
|
---|
18 |
|
---|
19 | @PutMapping("/createCoupon")
|
---|
20 | public ResponseEntity<Coupon> updateCoupon(@RequestBody Coupon couponItem) {
|
---|
21 | if (couponItem.getTitle() == null || couponItem.getCode() == null) {
|
---|
22 | return ResponseEntity.badRequest().build();
|
---|
23 | }
|
---|
24 | Coupon createdCoupon = couponService.saveCoupon(couponItem);
|
---|
25 | return ResponseEntity.ok(createdCoupon);
|
---|
26 | }
|
---|
27 | @GetMapping("/getAllCoupons")
|
---|
28 | public ResponseEntity<List<Coupon>>getAllCoupons(){
|
---|
29 | List<Coupon> couponList=couponService.getAllCoupons();
|
---|
30 | return ResponseEntity.ok(couponList);
|
---|
31 | }
|
---|
32 | @DeleteMapping("/deleteCoupon")
|
---|
33 | public ResponseEntity<?>deleteEntity(@RequestParam String userId){
|
---|
34 | try{
|
---|
35 | couponService.deleteById(userId);
|
---|
36 | return ResponseEntity.ok().build();
|
---|
37 | }
|
---|
38 | catch(EntityNotFoundException e){
|
---|
39 | return ResponseEntity.notFound().build();
|
---|
40 | }
|
---|
41 | }
|
---|
42 |
|
---|
43 | @PostMapping("/editCoupon")
|
---|
44 | public ResponseEntity<Void> editCoupon(@RequestParam String identifier, @RequestBody Coupon newCouponData) {
|
---|
45 | Optional<Coupon> couponOptional = couponService.findByIdentifier(identifier);
|
---|
46 | if (couponOptional.isEmpty()) {
|
---|
47 | return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
|
---|
48 | }
|
---|
49 | Coupon coupon = couponOptional.get();
|
---|
50 | coupon.setTitle(newCouponData.getTitle());
|
---|
51 | coupon.setCode(newCouponData.getCode());
|
---|
52 | coupon.setDescription(newCouponData.getDescription());
|
---|
53 | couponService.save(coupon);
|
---|
54 |
|
---|
55 | return ResponseEntity.ok().build();
|
---|
56 | }
|
---|
57 |
|
---|
58 |
|
---|
59 | @GetMapping("/getCouponNames")
|
---|
60 | public ResponseEntity<List<String>> getCouponNames() {
|
---|
61 | List<String> couponNames = couponService.getCouponNames();
|
---|
62 | return ResponseEntity.ok(couponNames);
|
---|
63 | }
|
---|
64 | }
|
---|