Scheduler.java 9.88 KB
Newer Older
1 2 3 4
package com.roshka.service;

import com.roshka.modelo.Beneficio;
import com.roshka.modelo.Birthday;
5
import com.roshka.modelo.Feriado;
6 7
import com.roshka.repositorio.BeneficioRepository;
import com.roshka.repositorio.BirthdayRepository;
8
import com.roshka.repositorio.FeriadoRepository;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.IOException;
26 27
import java.text.SimpleDateFormat;
import java.util.ArrayList;
28 29 30 31 32 33 34 35 36 37
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Configuration
@EnableScheduling
public class Scheduler {
    @Autowired
    BirthdayRepository birthdayRepository;
    @Autowired
38 39
    FeriadoRepository feriadoRepository;
    @Autowired
40 41 42 43
    BeneficioRepository beneficioRepository;
    @PersistenceContext
    private EntityManager entityManager;

44 45
    // @Scheduled(cron = "0 0 8 * * MON-FRI")
   @Scheduled(cron = "0 * * * * *")
46 47
    public void cumples() {
        String url = "https://hooks.slack.com/services/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";
48
        // Verificar que no sea feriado
49 50 51 52 53 54 55 56 57 58 59 60 61
        Feriado esFeriado = feriadoRepository.findByFecha(new Date());
        if (esFeriado != null){
            return;
        }

        int contador = 1;
        Date hoy = new Date();
        Date fechaAyer = new Date(hoy.getTime() - ((1000 * 60 * 60 * 24) * contador) );
        SimpleDateFormat f = new  SimpleDateFormat("EEEE");
        String diaAyer = f.format(fechaAyer);

        Boolean diaNoHabil = false;

62
        // Verificar que no sea Sábado ni domingo
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        if ((diaAyer.equals("sábado")) || (diaAyer.equals("domingo"))){
            diaNoHabil = true;
        }

        Feriado fechaNoHabil = feriadoRepository.findByFecha(fechaAyer);
        if (fechaNoHabil != null) {
            diaNoHabil = true;
        }

        List<Birthday> cumplesDiaNoHabiles = null;
        while(diaNoHabil) {
            List<Birthday> cumplesAyer = birthdayRepository.findAllByFecha(fechaAyer);

            if (cumplesDiaNoHabiles == null) {
                cumplesDiaNoHabiles = new ArrayList<>(cumplesAyer);
            } else {
               cumplesDiaNoHabiles.addAll(cumplesAyer);
            }
            contador++;
            diaNoHabil = false;
            hoy = new Date();
            fechaAyer = new Date(hoy.getTime() - ((1000 * 60 * 60 * 24) * contador) );
            f = new  SimpleDateFormat("EEEE");
            diaAyer = f.format(fechaAyer);
            if ((diaAyer.equals("sábado")) || (diaAyer.equals("domingo"))){
                diaNoHabil = true;
            }

            fechaNoHabil = feriadoRepository.findByFecha(fechaAyer);
            if (fechaNoHabil != null) {
                diaNoHabil = true;
            }
        }
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
       if (cumplesDiaNoHabiles != null )
       {
           for (Birthday cumple : cumplesDiaNoHabiles){

               SimpleDateFormat formato = new  SimpleDateFormat("dd/MM/yyyy");
               String fechaFormateada = formato.format(cumple.getFecha());
               String json = "{\n" +
                       "\"blocks\": [\n" +
                       "{\n" +
                       "\"type\": \"section\",\n" +
                       "\"text\": {\n" +
                       "\"type\": \"mrkdwn\",\n" +
                       "\"text\": \"Buenos días <!channel> \n En la fecha " + fechaFormateada + " estuvo de cumpleaños *" + cumple.getNombreCompleto() + "* <@" + cumple.getIdSlack() + ">. 🥳 ¡Que los cumplas muy feliz te desea Roshka! Que en la vida siempre encuentres razones para sonreír 🥳\",\n" +
                       "}" +
                       "}," +
                       "{" +
                       "\"type\": \"divider\"" +
                       "}," +
                       "{\n" +
                       "\"type\": \"image\",\n" +
                       "\"title\": {\n" +
                       "\"type\": \"plain_text\",\n" +
                       "\"text\": \"" + cumple.getNombreCompleto() + "\"\n" +
                       "},\n" +
                       "\"block_id\": \"image4\",\n" +
                       "\"image_url\": \"http://placekitten.com/500/500\",\n" +
                       "\"alt_text\": \"An incredibly cute kitten.\"\n" +
                       "}\n" +
                       "]\n" +
                       "}" +
                       "";
               String result = null;
               HttpPost httpPost = new HttpPost(url);
               httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));

               try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                   try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                       result = EntityUtils.toString(response.getEntity());
                   }

               } catch (IOException | ParseException e) {
                   e.printStackTrace();
138 139 140 141
               }

           }

142
       }
143

144
        // Verificar el cumpleaños de quién es
145 146 147 148 149 150 151 152
        List<Birthday> cumples = birthdayRepository.findAllByFecha(new Date());
        for (Birthday cumple : cumples) {
            String json = "{\n" +
                    "\"blocks\": [\n" +
                    "{\n" +
                    "\"type\": \"section\",\n" +
                    "\"text\": {\n" +
                    "\"type\": \"mrkdwn\",\n" +
153
                    "\"text\": \"Buenos días <!channel> \n Hoy está de cumpleaños *" + cumple.getNombreCompleto() + "* <@" + cumple.getIdSlack() + ">. 🥳 ¡Que los cumplas muy feliz te desea Roshka! Que en la vida siempre encuentres razones para sonreír 🥳\",\n" +
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
                    "}" +
                    "}," +
                    "{" +
                    "\"type\": \"divider\"" +
                    "}," +
                    "{\n" +
                    "\"type\": \"image\",\n" +
                    "\"title\": {\n" +
                    "\"type\": \"plain_text\",\n" +
                    "\"text\": \"" + cumple.getNombreCompleto() + "\"\n" +
                    "},\n" +
                    "\"block_id\": \"image4\",\n" +
                    "\"image_url\": \"http://placekitten.com/500/500\",\n" +
                    "\"alt_text\": \"An incredibly cute kitten.\"\n" +
                    "}\n" +
                    "]\n" +
                    "}" +
                    "";
            String result = null;
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));

            try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                    result = EntityUtils.toString(response.getEntity());
                }
180

181 182 183 184 185 186
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
        }
    }

187 188
//    @Scheduled(cron = "0 0 1 * * FRI")
  @Scheduled(cron = "0 * * * * *")
189 190
    public void beneficios() {
        String url = "https://hooks.slack.com/services/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";
191 192 193 194 195 196
        // Verificar que no sea feriado
        Feriado esFeriado = feriadoRepository.findByFecha(new Date());
        if (esFeriado != null){
            return;
        }

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        Beneficio beneficio = getRandomBeneficio();
        if (beneficio != null) {
            String json = "{" +
                    "\"blocks\": [" +
                    "{" +
                    "\"type\": \"section\"," +
                    "\"text\": {" +
                    "\"type\": \"mrkdwn\"," +
                    "\"text\": \"Te recordamos uno de nuestros beneficios <!channel>\"" +
                    "}" +
                    "}," +
                    "{" +
                    "\"type\": \"header\"," +
                    "\"text\": {" +
                    "\"type\": \"plain_text\"," +
                    "\"text\": \"" + beneficio.getTitulo() + "\"," +
                    "\"emoji\": true" +
                    "}" +
                    "}," +
                    "{" +
                    "\"type\": \"section\"," +
                    "\"text\": {" +
                    "\"type\": \"mrkdwn\"," +
                    "\"text\": \"" + beneficio.getDescripcion() + "\"" +
                    "}" +
                    "}" +
                    "]" +
                    "}";
            String result = null;
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));

            try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                    result = EntityUtils.toString(response.getEntity());
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
        }
    }

    public Beneficio  getRandomBeneficio() {
        String query = "SELECT o.id FROM Beneficio o ORDER BY random()";
        Query q = entityManager.createQuery(query);
        q.setMaxResults(1);
        Optional<Beneficio> beneficio = beneficioRepository.findById((Long) q.getSingleResult());
        if (beneficio.isPresent()) {
            return beneficio.get();
        }
        return null;
    }

}