BrightSide Workbench Full Report + Source Code
BankAccounts.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2015 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.financials.account.logic;
20 
21 import java.io.BufferedReader;
22 import java.io.File;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.text.DateFormat;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Date;
31 import java.util.List;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34 import jxl.Cell;
35 import jxl.CellType;
36 import jxl.DateCell;
37 import jxl.LabelCell;
38 import jxl.NumberCell;
39 import jxl.Sheet;
40 import jxl.Workbook;
41 import jxl.WorkbookSettings;
42 import jxl.read.biff.BiffException;
43 import org.turro.command.Command;
44 import org.turro.command.Context;
45 import org.turro.elephant.context.ElephantContext;
46 import org.turro.elephant.impl.util.FileUtil;
47 import org.turro.file.FileWrapper;
48 import org.turro.financials.db.FinancialsPU;
49 import org.turro.financials.entity.BankAccount;
50 import org.turro.financials.entity.Contract;
51 import org.turro.jpa.Dao;
52 import org.turro.math.Round;
53 import org.zkoss.lang.Strings;
54 
59 public class BankAccounts {
60 
61  private static final String BANK_IMPORT = "/WEB-INF/bank/n43.txt";
62 
63  public static Collection<StatementEntry> getMovements(String account, Date start, Date end) {
64  Contract contract = null;
65  if(!Strings.isBlank(account) && account.length() == 10) {
66  contract = getContract(account);
67  }
68  ArrayList<StatementEntry> list = new ArrayList<>();
69  if(contract != null) {
70  Dao dao = new FinancialsPU();
71  for(BankAccount ba : (List<BankAccount>) dao.getResultList(
72  "select ba from BankAccount ba " +
73  "where ba.contract = ? " +
74  "and ba.transactionDate >= ? " +
75  "and ba.transactionDate <= ?",
76  new Object[] {
77  contract, start, end
78  })) {
79  list.add(new BankEntry(ba));
80  }
81  }
82  return list;
83  }
84 
85  public static void importN43(final Contract contract) {
86  final File n43 = new File(ElephantContext.getRealPath(BANK_IMPORT));
87  FileWrapper fw = new FileWrapper(n43);
88  fw.uploadContent(new Command() {
89  @Override
90  public Object execute(Context context) {
91  if(!importFromXls(contract, n43)) {
92  try {
93  importFromFile(contract, n43);
94  } catch (IOException ex) {
95  Logger.getLogger(BankAccounts.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
96  }
97  }
98  return null;
99  }
100 
101  });
102  }
103 
104  private static void importFromFile(Contract contract, File n43) throws FileNotFoundException, IOException {
105  Dao dao = new FinancialsPU();
106  try (BufferedReader br = FileUtil.getBufferedFile(n43)) {
107  String line;
108  double balance = 0;
109  long order = 0;
110  BankAccount bankAccount = null;
111  while ((line = br.readLine()) != null) {
112  if(line.startsWith("11")) {
113  if(Strings.isBlank(contract.getGlobalId())) {
114  contract.setGlobalId(line.substring(10, 20));
115  }
116  balance = Double.valueOf(line.substring(33, 47)) / 100;
117  if(line.charAt(32) == '1') {
118  balance = -balance;
119  }
120  deleteFromTo(contract, getDate(line.substring(20, 26)), getDate(line.substring(26, 32)));
121  } else if(line.startsWith("22")) {
122  if(bankAccount != null) {
123  dao.saveObject(bankAccount);
124  }
125  bankAccount = new BankAccount();
126  bankAccount.setContract(contract);
127  bankAccount.setTransactionDate(getDate(line.substring(10, 16)));
128  bankAccount.setValueDate(getDate(line.substring(16, 22)));
129  bankAccount.setRegisterOrder(order++);
130  if(line.charAt(27) == '1') {
131  bankAccount.setCredit(Double.valueOf(line.substring(28, 42)) / 100);
132  balance = new Round(balance - bankAccount.getCredit()).decimals(2).value();
133  bankAccount.setBalance(balance);
134  } else {
135  bankAccount.setDebit(Double.valueOf(line.substring(28, 42)) / 100);
136  balance = new Round(balance + bankAccount.getDebit()).decimals(2).value();
137  bankAccount.setBalance(balance);
138  }
139  } else if(line.startsWith("23")) {
140  if(Strings.isBlank(bankAccount.getConcept())) {
141  bankAccount.setConcept(line.substring(4).replaceAll("\\s+", " "));
142  }
143  } else if(line.startsWith("88")) {
144  if(bankAccount != null) {
145  dao.saveObject(bankAccount);
146  }
147  }
148  }
149  }
150  }
151 
152  private static boolean importFromXls(Contract contract, File n43) {
153  Dao dao = new FinancialsPU();
154  try {
155  WorkbookSettings wsRead = new WorkbookSettings();
156  wsRead.setEncoding("ISO-8859-1");
157  Workbook workbook = Workbook.getWorkbook(n43, wsRead);
158  Sheet sheet = workbook.getSheet(0);
159  for (int row = 3; row < sheet.getRows(); row++) {
160  BankAccount bankAccount = new BankAccount();
161  bankAccount.setContract(contract);
162  Cell cell = sheet.getCell(1, row);
163  if (cell.getType().equals(CellType.DATE)) {
164  bankAccount.setTransactionDate(((DateCell) cell).getDate());
165  }
166  cell = sheet.getCell(2, row);
167  if (cell.getType().equals(CellType.DATE)) {
168  bankAccount.setValueDate(((DateCell) cell).getDate());
169  }
170  bankAccount.setRegisterOrder(row - 3);
171  cell = sheet.getCell(4, row);
172  if (cell.getType().equals(CellType.NUMBER)) {
173  double num = ((NumberCell) cell).getValue();
174  if (num < 0) {
175  bankAccount.setCredit(-num);
176  } else {
177  bankAccount.setDebit(num);
178  }
179  }
180  cell = sheet.getCell(5, row);
181  if (cell.getType().equals(CellType.NUMBER)) {
182  double num = ((NumberCell) cell).getValue();
183  bankAccount.setBalance(num);
184  }
185  cell = sheet.getCell(0, row);
186  if (cell.getType().equals(CellType.LABEL)) {
187  LabelCell label = (LabelCell) cell;
188  bankAccount.setConcept(label.getString());
189  }
190  dao.saveObject(bankAccount);
191  }
192  } catch (IOException | BiffException ex) {
193  Logger.getLogger(BankAccounts.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
194  return false;
195  }
196  return true;
197  }
198 
199  private static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
200  @Override
201  protected DateFormat initialValue() {
202  return new SimpleDateFormat("yyMMdd");
203  }
204  };
205 
206  private static Date getDate(String date) {
207  try {
208  return dateFormat.get().parse(date);
209  } catch (ParseException ex) {
210  Logger.getLogger(BankAccounts.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(date), ex);
211  return null;
212  }
213  }
214 
215  private static void deleteFromTo(Contract contract, Date start, Date end) {
216  Dao dao = new FinancialsPU();
217  dao.executeUpdate(
218  "delete from BankAccount ba " +
219  "where ba.contract = ? " +
220  "and ba.transactionDate >= ? " +
221  "and ba.transactionDate <= ?",
222  new Object[] {
223  contract, start, end
224  });
225  }
226 
227  private static Contract getContract(String account) {
228  Dao dao = new FinancialsPU();
229  return (Contract) dao.getSingleResultOrNull(
230  "select c from Contract c where c.id = ? " +
231  "and c.contractDefinition.asCash = ?",
232  new Object[] {
233  Long.valueOf(account.substring(5)),
234  account.substring(0, 3)
235  });
236  }
237 
238 }
static BufferedReader getBufferedFile(String folder, String file)
Definition: FileUtil.java:146
void uploadContent(final Command command)
static void importN43(final Contract contract)
static Collection< StatementEntry > getMovements(String account, Date start, Date end)
void setRegisterOrder(long registerOrder)
void setTransactionDate(Date transactionDate)
void setContract(Contract contract)