Skip to content

Commit

Permalink
Merge pull request #49 from jkuznik/Task-42-Day-SMS-Limit
Browse files Browse the repository at this point in the history
Task 42 day sms limit
  • Loading branch information
jkuznik authored Nov 21, 2024
2 parents f42dbf3 + cd767e5 commit 1ce2799
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 16 deletions.
14 changes: 13 additions & 1 deletion .github/workflows/self-host-CD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,16 @@ jobs:
- name: Delete old docker container
run: sudo docker rm -f disaster-alert-container || true
- name: Run new docker container
run: sudo docker run -d -p 8080:8080 --name disaster-alert-container --network disaster-net jkuznik/disaster-alert
env:
TWILIO_ACCOUNT_SID: ${{secrets.TWILIO_ACCOUNT_SID}}
TWILIO_AUTH_TOKEN: ${{secrets.TWILIO_AUTH_TOKEN}}
TWILIO_PHONE_NUMBER: ${{secrets.TWILIO_PHONE_NUMBER}}
OPENAI_API_KEY: ${{secrets.OPENAI_API_KEY}}
run: sudo docker run -d -p 8080:8080 \
--name disaster-alert-container \
--network disaster-net \
-e TWILIO_ACCOUNT_SID=${{secrets.TWILIO_ACCOUNT_SID}} \
-e TWILIO_AUTH_TOKEN=${{secrets.TWILIO_AUTH_TOKEN}} \
-e TWILIO_PHONE_NUMBER=${{secrets.TWILIO_PHONE_NUMBER}} \
-e OPENAI_API_KEY=${{secrets.OPENAI_API_KEY}} \
jkuznik/disaster-alert
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ void sendNotifications(AlertAddDTO alertAddDTO) {
Set<UserDTO> interestedUsers = userFacade.getInterestedUsers(alertAddDTO.location());

notificationManager.addEmailService();
// notificationManager.addSMSService(); //TODO: after test functionality temporary mute and TODO: add logic for handling dynamic user preference changes
notificationManager.addSMSService();
notificationManager.createAlert(alertAddDTO, interestedUsers);

notificationManager.removeEmailService();
Expand Down
106 changes: 92 additions & 14 deletions src/main/java/pl/ateam/disasteralerts/disasteralert/SMSService.java
Original file line number Diff line number Diff line change
@@ -1,45 +1,123 @@
package pl.ateam.disasteralerts.disasteralert;

import lombok.RequiredArgsConstructor;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.ateam.disasteralerts.disasteralert.dto.AlertAddDTO;
import pl.ateam.disasteralerts.user.dto.UserDTO;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import pl.ateam.disasteralerts.util.EntityAudit;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

@Service
@RequiredArgsConstructor
class SMSService implements AlertListener {

private final SMSLimitService smsLimitService;

public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
public static final String MY_PHONE_NUMBER = System.getenv("MY_PHONE_NUMBER");
public static final String TWILIO_PHONE_NUMBER = System.getenv("TWILIO_PHONE_NUMBER");

@Override
public void addedAlert(AlertAddDTO alertAddDTO, Set<UserDTO> interestedUsers) {
interestedUsers.forEach(userDTO -> {
sendSMS(alertAddDTO.description(), userDTO.phoneNumber());
});
}

public void sendSMS(String alertDescription, String phoneNumber) {
LocalDateTime today = LocalDateTime.now();

if(smsLimitService.isLimitReached(today)){
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

Message message = Message
.creator(
new PhoneNumber(phoneNumber),
new PhoneNumber(TWILIO_PHONE_NUMBER),
alertDescription
)
.create();

System.out.println(message.getSid());

smsLimitService.increaseLimit(today);
} else {
throw new RuntimeException("Day SMS limit reached");
}
}
}

@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sms_limits")
class SMSLimit extends EntityAudit {

@Column(nullable = false)
private int limitCounter;

// TODO: docelowo powinna zadziałać powyższa część kodu, poniżej do testu podaję swój nr
// sendSMS(alertAddDTO.description(), MY_PHONE_NUMBER);
public void increaseCounter(){
limitCounter++;
}
}

public static void sendSMS(String alertDescription, String phoneNumber) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
@Repository
interface SMSLimitRepository extends JpaRepository<SMSLimit, UUID> {
@Query(value = "SELECT * FROM sms_limits WHERE CAST(create_date AS date) = CAST(:date AS date)", nativeQuery = true)
Optional<SMSLimit> findByExactDay(@Param("date") LocalDateTime date);
}

Message message = Message
.creator(
new PhoneNumber(phoneNumber),
new PhoneNumber(TWILIO_PHONE_NUMBER),
alertDescription
)
.create();
@RequiredArgsConstructor
@Service
class SMSLimitService {

private final SMSLimitRepository smsLimitRepository;

@Transactional
boolean isLimitReached(LocalDateTime date) {
boolean result = false;

Optional<SMSLimit> byExactDay = smsLimitRepository.findByExactDay(date);
if(byExactDay.isPresent()){
result = byExactDay.get().getLimitCounter() < Integer.parseInt(System.getenv("DAY_SMS_LIMIT")); //TODO: ktoś z Was już próbował podpowiedzianego rozwiązania z sterowaniem konfiguracji aplikacji z poziomu application.properties? tutaj by mi się to przydało
} else {
createLimiter();
}

return result;
}

@Transactional
void increaseLimit(LocalDateTime date) {
SMSLimit smsLimit = smsLimitRepository.findByExactDay(date).orElseThrow(
() -> new RuntimeException("Something go wrong with increase " + date + " SMS limit")
);

smsLimit.increaseCounter();
}

System.out.println(message.getSid());
@Transactional
private void createLimiter() {
smsLimitRepository.save(SMSLimit.builder()
.limitCounter(0)
.build());
}
}
11 changes: 11 additions & 0 deletions src/main/resources/db/changelog/dev.sql
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,14 @@ UPDATE users SET last_name = 'Nieznane';

-- changeset Slawek84PL:1730494287010-25
ALTER TABLE users ALTER COLUMN last_name SET NOT NULL;

-- changeset jkuznik:1728934675080-25
CREATE TABLE sms_limits
(
id UUID NOT NULL,
version BIGINT NOT NULL,
create_date TIMESTAMP WITHOUT TIME ZONE,
update_date TIMESTAMP WITHOUT TIME ZONE,
limit_counter INT NOT NULL,
CONSTRAINT pk_sms_limits PRIMARY KEY (id)
);

0 comments on commit 1ce2799

Please sign in to comment.