Skip to content

Calculate hits per day

I need help to implement hits per day based on the user selected package. This is what I made so far but it’s not working properly:

Entity:

@Entity
@Table(name = "users")
public class UsersModel implements Serializable {

    @Column(name = "plan")
    private String plan;

    @Column(name = "plan_last_activity")
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime planLastActivity;
}

Code:

public boolean calculateClickTimes() {

    String userName = SecurityUtils.getSubject().getPrincipal().toString();
    QueryDashboardHelper queryHelper = new QueryDashboardHelper();
    UsersModel user = queryHelper.getUserByUserName(userName);

    String plan = user.getPlan(); // silver/gold/platinum/diamond
    int todayHits = user.getTradesPerDay();
    LocalDateTime lastHit = user.getPlanLastActivity();

    LocalDateTime now = LocalDateTime.now();
    LocalDateTime tenSecondsLater = now.plusDays(1);

    long diff = ChronoUnit.DAYS.between(lastHit, tenSecondsLater);

    switch(plan) {

      case "diamond":

        if(diff >= 1 && todayHits >= 20) {
            todayHits = 0;
            return true;
        }       
        break;

      case "platinum":

        if(diff >= 1 && todayHits >= 15) {
            todayHits = 0;
            return true;
        }       
        break;  

      case "gold":

        if(diff >= 1 && todayHits >= 10) {
            todayHits = 0;
            return true;
        }             
        break;  

      case "silver":

        if(diff >= 1 && todayHits >= 5) {
            // User has clicked 5 times today
            todayHits = 0;
            return true;
        }
        break;

      default:

    }

    return false;
}

The general idea is that users should be limited to perform hits in web page based on the selected package (silver/gold/platinum/diamond) and based on the data from the database plan, tradesPerDay and planLastActivity the allowed hits should be limited for the current day. Can you give me some advice how to implement this code properly, please?

Answer

You can do it on the database level:

create table users (
    id bigint primary key ,
    plan character varying,
    trades_today int
);

insert into users (id, plan, trades_today)
values (1, 'diamond', 15),
       (2, 'silver', 5),
       (3, 'gold', 0);

with packages(package_type, max_hits) as (
    values ('diamond', 20),
           ('platinum', 15),
           ('gold', 10),
           ('silver', 5)
)

select u.id, trades_today < p.max_hits
from users u
inner join packages p on u.plan = p.package_type;

This results in:

+--+--------+
|id|?column?|
+--+--------+
|1 |true    |
|2 |false   |
|3 |true    |
+--+--------+

Every time a hit is done, the counter is increased. The counter is reset every midnight