Subversion Repositories Integrator Subversion

Rev

Rev 761 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
760 blopes 1
package br.com.sl.core;
2
 
3
import java.io.FileInputStream;
4
import java.io.IOException;
5
import java.math.BigDecimal;
6
import java.nio.file.Path;
7
import java.time.LocalDate;
8
import java.time.LocalDateTime;
9
import java.time.LocalTime;
10
import java.time.format.DateTimeFormatter;
11
import java.util.HashMap;
12
import java.util.Map;
13
 
14
import org.apache.poi.ss.usermodel.Cell;
15
import org.apache.poi.ss.usermodel.CellType;
16
import org.apache.poi.ss.usermodel.CellValue;
17
import org.apache.poi.ss.usermodel.DateUtil;
18
import org.apache.poi.ss.usermodel.FormulaEvaluator;
19
import org.apache.poi.ss.usermodel.Row;
20
import org.apache.poi.ss.usermodel.Sheet;
21
import org.apache.poi.ss.usermodel.Workbook;
22
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
23
 
24
import br.com.sl.domain.dto.robo.ProfitTick;
25
 
26
public class ExcelProfitDataProvider implements ProfitDataProvider {
27
 
28
    private final Path excelFile;
29
    private final String sheetName;
30
 
31
    // índices de coluna (0 = A, 1 = B, etc.)
32
    private final int colAsset = 0;
33
    private final int colDate  = 1;
34
    private final int colTime  = 2;
35
    private final int colLast  = 3;
36
 
37
    // formatos da data e hora, conforme Excel
38
    private final DateTimeFormatter fmtData = DateTimeFormatter.ofPattern("dd/MM/yyyy");
39
    private final DateTimeFormatter fmtHora = DateTimeFormatter.ofPattern("HH:mm:ss");
40
 
41
    public ExcelProfitDataProvider(Path excelFile, String sheetName) {
42
        this.excelFile = excelFile;
43
        this.sheetName = sheetName;
44
    }
45
 
46
    @Override
47
    public Map<String, ProfitTick> readCurrentTicks() {
48
        Map<String, ProfitTick> ticks = new HashMap<>();
49
 
50
        try (FileInputStream fis = new FileInputStream(excelFile.toFile()); Workbook workbook = new XSSFWorkbook(fis)) {
51
            Sheet sheet = (sheetName != null)
52
                    ? workbook.getSheet(sheetName)
53
                    : workbook.getSheetAt(0);
54
 
55
            if (sheet == null) {
56
                System.err.println("[ExcelProfitDataProvider] Aba não encontrada: " + sheetName);
57
                return ticks;
58
            }
59
 
60
            int firstRow = sheet.getFirstRowNum() + 1; // pula cabeçalho
61
            int lastRow = sheet.getLastRowNum();
62
 
63
            for (int i = firstRow; i <= lastRow; i++) {
64
                Row row = sheet.getRow(i);
65
                if (row == null) continue;
66
 
67
                Cell cellAsset = row.getCell(colAsset);
68
                if (cellAsset == null) continue;
69
 
70
                String asset = cellAsset.toString().trim();
71
                if (asset.isEmpty()) continue;
72
 
73
                LocalDate date = lerData(row.getCell(colDate));
74
                LocalTime time = lerHora(row.getCell(colTime));
75
                BigDecimal price = lerPreco(row.getCell(colLast));
76
 
77
                if (date == null || time == null || price == null) {
78
                    continue;
79
                }
80
 
81
                LocalDateTime dateTime = LocalDateTime.of(date, time);
82
                ProfitTick tick = new ProfitTick(asset, dateTime, price);
83
 
84
                // Se tiver mais de uma linha por ativo, você pode decidir
85
                // se guarda o último (maior horário) ou o primeiro; aqui guardo o último
86
                ProfitTick tickExistente = ticks.get(asset);
87
                if (tickExistente == null || tick.getDateTime().isAfter(tickExistente.getDateTime())) {
88
                    ticks.put(asset, tick);
89
                }
90
            }
91
 
92
        } catch (IOException e) {
93
            System.err.println("[ExcelProfitDataProvider] Erro ao ler Excel: " + e.getMessage());
94
        }
95
 
96
        return ticks;
97
    }
98
 
99
    private LocalDate lerData(Cell cell) {
100
        if (cell == null) return null;
101
 
102
        try {
103
            int t = cell.getCellType();
104
 
105
            // 1) Se for fórmula RTD
106
            if (t == CellType.FORMULA.getCode()) {
107
                int ct = cell.getCachedFormulaResultType();
108
 
109
                if (ct == CellType.NUMERIC.getCode()) {
110
                    double dv = cell.getNumericCellValue();
111
                    java.util.Date d = DateUtil.getJavaDate(dv);
112
                    return d.toInstant()
113
                            .atZone(java.time.ZoneId.systemDefault())
114
                            .toLocalDate();
115
                }
116
 
117
                if (ct == CellType.STRING.getCode()) {
118
                    String text = cell.getStringCellValue().trim();
119
                    if (text.isEmpty()) return null;
120
 
121
                    DateTimeFormatter[] patterns = {
122
                            DateTimeFormatter.ofPattern("dd/MM/yyyy"),
123
                            DateTimeFormatter.ofPattern("dd-MM-yyyy"),
124
                            DateTimeFormatter.ofPattern("yyyy-MM-dd"),
125
                            DateTimeFormatter.ofPattern("yyyy/MM/dd")
126
                    };
127
 
128
                    for (DateTimeFormatter p : patterns) {
129
                        try {
130
                            return LocalDate.parse(text, p);
131
                        } catch (Exception ignored) {}
132
                    }
133
                }
134
            }
135
 
136
            // 2) Se for numérico formatado como data
137
            if (t == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
138
                java.util.Date d = cell.getDateCellValue();
139
                return d.toInstant()
140
                        .atZone(java.time.ZoneId.systemDefault())
141
                        .toLocalDate();
142
            }
143
 
144
            // 3) Se vier como texto
145
            String text = cell.toString().trim();
146
            if (text.isEmpty()) return null;
147
 
148
            DateTimeFormatter[] patterns = {
149
                    DateTimeFormatter.ofPattern("dd/MM/yyyy"),
150
                    DateTimeFormatter.ofPattern("dd-MM-yyyy"),
151
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"),
152
                    DateTimeFormatter.ofPattern("yyyy/MM/dd")
153
            };
154
 
155
            for (DateTimeFormatter p : patterns) {
156
                try {
157
                    return LocalDate.parse(text, p);
158
                } catch (Exception ignored) {}
159
            }
160
 
161
        } catch (Exception e) {
162
            System.out.println("[lerData] erro: " + e.getMessage());
163
        }
164
 
165
        return null;
166
    }
167
 
168
 
169
    private LocalTime lerHora(Cell cell) {
170
        if (cell == null) return null;
171
 
172
        try {
173
            // 1) Fórmula RTD
174
            if (cell.getCellType() == CellType.FORMULA.getCode()) {
175
 
176
                if (cell.getCachedFormulaResultType() == CellType.NUMERIC.getCode()) {
177
                    java.util.Date d = DateUtil.getJavaDate(cell.getNumericCellValue());
178
                    return d.toInstant()
179
                            .atZone(java.time.ZoneId.systemDefault())
180
                            .toLocalTime();
181
                }
182
 
183
                if (cell.getCachedFormulaResultType() == CellType.STRING.getCode()) {
184
                    String text = cell.getStringCellValue().trim();
185
                    if (text.isEmpty()) return null;
186
 
187
                    DateTimeFormatter[] patterns = {
188
                            DateTimeFormatter.ofPattern("HH:mm:ss"),
189
                            DateTimeFormatter.ofPattern("H:mm:ss"),
190
                            DateTimeFormatter.ofPattern("HH:mm"),
191
                            DateTimeFormatter.ofPattern("H:mm")
192
                    };
193
 
194
                    for (DateTimeFormatter p : patterns) {
195
                        try { return LocalTime.parse(text, p); }
196
                        catch (Exception ignored) {}
197
                    }
198
                }
199
            }
200
 
201
            // 2) Numérico com formato de data/hora
202
            if (cell.getCellType() == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
203
                java.util.Date d = cell.getDateCellValue();
204
                return d.toInstant()
205
                        .atZone(java.time.ZoneId.systemDefault())
206
                        .toLocalTime();
207
            }
208
 
209
            // 3) Texto simples
210
            String text = cell.toString().trim();
211
            if (text.isEmpty()) return null;
212
 
213
            DateTimeFormatter[] patterns = {
214
                    DateTimeFormatter.ofPattern("HH:mm:ss"),
215
                    DateTimeFormatter.ofPattern("H:mm:ss"),
216
                    DateTimeFormatter.ofPattern("HH:mm"),
217
                    DateTimeFormatter.ofPattern("H:mm")
218
            };
219
 
220
            for (DateTimeFormatter p : patterns) {
221
                try { return LocalTime.parse(text, p); }
222
                catch (Exception ignored) {}
223
            }
224
 
225
        } catch (Exception e) {
226
            System.out.println("[lerHora] erro: " + e.getMessage());
227
        }
228
 
229
        return null;
230
    }
231
 
232
 
233
    private BigDecimal lerPreco(Cell cell) {
234
        if (cell == null) return null;
235
 
236
        try {
237
            // 1) Fórmula RTD
238
            if (cell.getCellType() == CellType.FORMULA.getCode()) {
239
 
240
                if (cell.getCachedFormulaResultType() == CellType.NUMERIC.getCode()) {
241
                    return BigDecimal.valueOf(cell.getNumericCellValue());
242
                }
243
 
244
                if (cell.getCachedFormulaResultType() == CellType.STRING.getCode()) {
245
                    String text = cell.getStringCellValue().trim();
246
                    if (text.isEmpty()) return null;
247
                    text = text.replace(".", "").replace(",", ".");
248
                    return new BigDecimal(text);
249
                }
250
            }
251
 
252
            // 2) Numérico simples
253
            if (cell.getCellType() == CellType.NUMERIC.getCode()) {
254
                return BigDecimal.valueOf(cell.getNumericCellValue());
255
            }
256
 
257
            // 3) Texto
258
            String text = cell.toString().trim();
259
            if (text.isEmpty()) return null;
260
 
261
            text = text.replace(".", "").replace(",", ".");
262
            return new BigDecimal(text);
263
 
264
        } catch (Exception e) {
265
            System.out.println("[lerPreco] erro: " + e.getMessage());
266
        }
267
 
268
        return null;
269
    }
270
 
271
 
272
}