summaryrefslogtreecommitdiff
path: root/src/main/java/com/stileeducation/markr/service/TestService.java
blob: f42da1ad637c29a00b2d2348073519350468a835 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.stileeducation.markr.service;

import com.stileeducation.markr.entity.Test;
import com.stileeducation.markr.repository.TestRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class TestService {

  final
  TestRepository testRepository;

  public TestService(TestRepository testRepository) {
    this.testRepository = testRepository;
  }

  @Transactional
  public Optional<Test> findTest(String testId) {
    return testRepository.findByTestId(testId);
  }

  @Transactional
  public Test findOrCreateTest(String testId, Integer marksAvailable) {
    Optional<Test> optionalTest = testRepository.findByTestId(testId);

    if (optionalTest.isPresent()) {
      Test test = optionalTest.get();
      if (marksAvailable > test.getMarksAvailable()) {
        test.setMarksAvailable(marksAvailable);
        test.setCreated(false);
        test.setUpdated(true);
        return testRepository.save(test);
      } else {
        test.setCreated(false);
        test.setUpdated(false);
        return test;
      }
    } else {
      Test test = new Test();
      test.setTestId(testId);
      test.setMarksAvailable(marksAvailable);
      test.setCreated(true);
      return testRepository.save(test);
    }
  }
}