BrightSide Workbench Full Report + Source Code
PrintBook.java
Go to the documentation of this file.
1 /*
2  * Turró i Cutiller Foundation. License notice.
3  * Copyright (C) 2012 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;
20 
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Collection;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.TimeZone;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32 import javax.activation.MimetypesFileTypeMap;
33 import jxl.Workbook;
34 import jxl.write.DateFormat;
35 import jxl.write.Label;
36 import jxl.write.WritableCellFormat;
37 import jxl.write.WritableSheet;
38 import jxl.write.WritableWorkbook;
39 import jxl.write.WriteException;
40 import net.sf.jasperreports.engine.JRException;
41 import org.amic.util.date.CheckDate;
42 import org.turro.command.Command;
43 import org.turro.command.Context;
44 import org.turro.contacts.Contact;
45 import org.turro.elephant.context.Application;
46 import org.turro.elephant.context.ElephantContext;
47 import org.turro.elephant.db.WhereClause;
48 import org.turro.elephant.util.DateFormats;
49 import org.turro.elephant.util.DecimalFormats;
50 import org.turro.financials.book.BookListbox;
51 import org.turro.financials.db.FinancialsPU;
52 import org.turro.financials.entity.BookDefinition;
53 import org.turro.financials.entity.BookRegister;
54 import org.turro.financials.entity.Company;
55 import org.turro.financials.entity.Contract;
56 import org.turro.financials.entity.Document;
57 import org.turro.financials.entity.DocumentLine;
58 import org.turro.financials.entity.LineType;
59 import org.turro.financials.entity.OperatingModifier;
60 import org.turro.financials.entity.Register;
61 import org.turro.financials.entity.RegisterView;
62 import org.turro.financials.model.business.CompanyWrapper;
63 import org.turro.financials.model.document.AmountTaxable;
64 import org.turro.financials.model.document.DocumentAmountsByBook;
65 import org.turro.financials.model.register.ViewWrapper;
66 import org.turro.i18n.I_;
67 import org.turro.jpa.Dao;
68 import org.turro.jpa.export.ExportQuery;
69 import org.turro.plugin.contacts.IContact;
70 import org.turro.zkoss.dialog.InputDialog;
71 import org.turro.zkoss.dialog.InputField;
72 import org.turro.zkoss.print.OnDemandBeanCollection;
73 import org.turro.zkoss.print.ReportMenuitem;
74 import org.turro.zkoss.print.ReportPrint;
75 import org.turro.zul.frame.Framework;
76 import org.zkoss.zk.ui.HtmlBasedComponent;
77 import org.zkoss.zk.ui.Page;
78 import org.zkoss.zul.Filedownload;
79 
84 public class PrintBook extends ReportMenuitem {
85 
86  private Integer year;
87 
88  public PrintBook() {
89  }
90 
91  @Override
92  protected void print(String type) {
93  doPrint(getPage(), year, type);
94  }
95 
96  public static void doPrint(Page page, Integer year, final String type) {
97  final RegisterView formalView = ViewWrapper.getFormalView();
98  Integer startPage = 1;
99  year = new CheckDate().getYear();
100 
102  Framework.getCurrent().getPage(),
103  I_.get("Books"),
104  new InputField[] {
105  new InputField("From", new CheckDate().setMonth(1).setDay(1).getDate(), null, 0),
106  new InputField("To", new CheckDate().setMonth(12).setDay(31).getDate(), null, 0),
107  new InputField("Start page", startPage, null, 0),
108  new InputField("Book", null, null, 0) {
109  @Override
110  protected HtmlBasedComponent createEditor() {
111  BookListbox bl = new BookListbox();
112  bl.setMold("select");
113  return bl;
114  }
115  },
116  new InputField("Export", Boolean.valueOf(false), null, 0)
117  }, new Command() {
118  @Override
119  public Object execute(Context context) {
120  BookDefinition bookDefinition = null;
121  Integer startPage = 1;
122  Date from = null, to = null;
123  Boolean export = false;
124  InputField[] fields = (InputField[]) context.get("fields");
125  if(fields.length > 0) {
126  for(InputField f : fields) {
127  if("From".equals(f.getLabel())) {
128  from = (Date) f.getValue();
129  } else if("To".equals(f.getLabel())) {
130  to = (Date) f.getValue();
131  } else if("Start page".equals(f.getLabel())) {
132  startPage = (Integer) f.getValue() - 1;
133  } else if("Book".equals(f.getLabel())) {
134  bookDefinition = (BookDefinition) f.getValue();
135  } else if("Export".equals(f.getLabel())) {
136  export = (Boolean) f.getValue();
137  }
138  }
139  if(from != null && to != null) {
140  if(bookDefinition.getId() == 4) {
141  Collection<Long> lines = getDocuments(formalView, from, to);
142  if(lines != null && lines.size() > 0) {
143  Map parameters = new HashMap();
144  int fractionDigits = CompanyWrapper.getCompanyCurrency().getDefaultFractionDigits();
145  Company company = CompanyWrapper.getDefaultCompany();
146  Contact companyContact = (Contact) company.getIContact().getContact();
147  parameters.put("labels", Application.getStringMap());
148  parameters.put("i_", I_.api());
149  parameters.put("i", I_.map());
150  parameters.put("k", I_.byKeyMap());
151  parameters.put("bookDef", bookDefinition);
152  parameters.put("majors", getMajorBook(bookDefinition));
153  parameters.put("title", I_.get("Book") + ": " + bookDefinition.getDescription());
154  parameters.put("company", company);
155  parameters.put("companyContact", companyContact);
156  parameters.put("dateFormat", DateFormats.getDefaultFormat());
157  parameters.put("currencyFormat", DecimalFormats.getStringFormat(fractionDigits));
158  parameters.put("exportFormat", type);
159  parameters.put("from", from);
160  parameters.put("to", to);
161  if(export) {
162  String name = ElephantContext.getSiteName() + "_Book" + bookDefinition.getDescription() + ".xls";
163  Filedownload.save(getExcelForDocuments(name, lines, parameters), new MimetypesFileTypeMap().getContentType(name), name);
164  } else {
165 // parameters.put("startPage", startPage);
166 // parameters.put("SUBREPORT_DIR", "../_reports/financials/accounting/");
167 // String file = "/WEB-INF/_reports/financials/accounting/PrintBookDocuments.jasper";
168 // OnDemandBeanCollection collection = new OnDemandBeanCollection(lines) {
169 // @Override
170 // protected Object getRealBean(Object bean) {
171 // return new FinancialsPU().find(BookRegister.class, (Long) bean);
172 // }
173 // };
174 // try {
175 // ReportPrint.print(I_.get("Books"),
176 // collection, parameters, file, null,
177 // type, null);
178 // } catch (JRException ex) {
179 // Logger.getLogger(PrintBook.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
180 // }
181  }
182  }
183 
184 
185  } else {
186  Collection<Long> lines = getBookRegisters(formalView, from, to, bookDefinition);
187  if(lines != null && lines.size() > 0) {
188  Map parameters = new HashMap();
189  int fractionDigits = CompanyWrapper.getCompanyCurrency().getDefaultFractionDigits();
190  Company company = CompanyWrapper.getDefaultCompany();
191  Contact companyContact = (Contact) company.getIContact().getContact();
192  parameters.put("labels", Application.getStringMap());
193  parameters.put("i_", I_.api());
194  parameters.put("i", I_.map());
195  parameters.put("k", I_.byKeyMap());
196  parameters.put("bookDef", bookDefinition);
197  parameters.put("majors", getMajorBook(bookDefinition));
198  parameters.put("title", I_.get("Book") + ": " + bookDefinition.getDescription());
199  parameters.put("company", company);
200  parameters.put("companyContact", companyContact);
201  parameters.put("dateFormat", DateFormats.getDefaultFormat());
202  parameters.put("currencyFormat", DecimalFormats.getStringFormat(fractionDigits));
203  parameters.put("exportFormat", type);
204  parameters.put("from", from);
205  parameters.put("to", to);
206  if(export) {
207  String name = ElephantContext.getSiteName() + "_Book" + bookDefinition.getDescription() + ".xls";
208  Filedownload.save(getExcel(name, lines, parameters), new MimetypesFileTypeMap().getContentType(name), name);
209  } else {
210  parameters.put("startPage", startPage);
211  parameters.put("SUBREPORT_DIR", "../_reports/financials/accounting/");
212  String file = "/WEB-INF/_reports/financials/accounting/PrintBookDocuments.jasper";
213  OnDemandBeanCollection collection = new OnDemandBeanCollection(lines) {
214  @Override
215  protected Object getRealBean(Object bean) {
216  return new FinancialsPU().find(BookRegister.class, (Long) bean);
217  }
218  };
219  try {
220  ReportPrint.print(I_.get("Books"),
221  collection, parameters, file, null,
222  type, null);
223  } catch (JRException ex) {
224  Logger.getLogger(PrintBook.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
225  }
226  }
227  }
228  }
229  }
230  }
231  return null;
232  }
233  });
234  }
235 
236  private static Collection<Long> getBookRegisters(RegisterView formalView, Date from, Date to, BookDefinition bookDefinition) {
237  WhereClause wc = new WhereClause();
238  wc.addClause("select breg.id");
239  wc.addClause("from BookRegister breg");
240  wc.addClause("where breg.bookDefinition = :bookDef");
241  wc.addNamedValue("bookDef", bookDefinition);
242  wc.addClause("and breg.register.view = :view");
243  wc.addNamedValue("view", formalView);
244  wc.addClause("and breg.register.registerDate >= :from");
245  wc.addNamedValue("from", from);
246  wc.addClause("and breg.register.registerDate <= :to");
247  wc.addNamedValue("to", to);
248  wc.addClause("order by breg.bookOrder");
249 
250  Dao dao = new FinancialsPU();
251  return dao.getResultList(wc);
252  }
253 
254  private static Collection<String> getMajorBook(BookDefinition bookDefinition) {
255  WhereClause wc = new WhereClause();
256  wc.addClause("select ma.account");
257  wc.addClause("from MajorAccount ma");
258  wc.addClause("where ma.bookDefinition = :bookDef");
259  wc.addNamedValue("bookDef", bookDefinition);
260  wc.addClause("order by ma.account desc");
261 
262  Dao dao = new FinancialsPU();
263  return dao.getResultList(wc);
264  }
265 
266  private static Collection<Long> getDocuments(RegisterView formalView, Date from, Date to) {
267  WhereClause wc = new WhereClause();
268  wc.addClause("select doc.id");
269  wc.addClause("from Document doc");
270  wc.addClause("where doc.contract.operatingModifier = :opMod");
271  wc.addNamedValue("opMod", OperatingModifier.OPMOD_INTRACOMMUNITY);
272  wc.addClause("and doc.documentDefinition.id = 1");
273  wc.addClause("and doc.forcedView is null");
274  wc.addClause("and doc.receiptDate >= :from");
275  wc.addNamedValue("from", from);
276  wc.addClause("and doc.receiptDate <= :to");
277  wc.addNamedValue("to", to);
278  wc.addClause("order by doc.receiptDate");
279 
280  Dao dao = new FinancialsPU();
281  return dao.getResultList(wc);
282  }
283 
284  public static InputStream getExcel(String sheetName, Collection<Long> bookRegisters, Map parameters) {
285  try {
286  ByteArrayOutputStream baos = new ByteArrayOutputStream();
287  WritableWorkbook ww = Workbook.createWorkbook(baos);
288  WritableSheet ws = ww.createSheet(sheetName, 0);
289  writeSheet(ws, bookRegisters, parameters);
290  ww.write();
291  ww.close();
292  baos.close();
293  return new ByteArrayInputStream(baos.toByteArray());
294  } catch (WriteException | IOException ex) {
295  Logger.getLogger(ExportQuery.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
296  }
297  return null;
298  }
299 
300  private static void writeSheet(WritableSheet ws, Collection<Long> bookRegisters, Map parameters) throws WriteException {
301  int countCols = 0, countRows = 0;
302  BookDefinition bookDefinition = (BookDefinition) parameters.get("bookDef");
303  String[] columns = new String[] {
304  "No.Registre","No.Factura","Data recepció","Data","NIF / CIF","Expedidor","Tipus","IVA%","Base imposable","IVA","IRPF","Quota","Import"
305  };
306  for(String s : columns) {
307  ws.addCell(new Label(countCols++, countRows, s));
308  }
309  Dao dao = new FinancialsPU();
310  DateFormat df = new DateFormat("dd/MM/yyyy");
311  df.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"));
312  WritableCellFormat dateFmt = new WritableCellFormat(df);
313  for(Long bookRegisterId : bookRegisters) {
314  BookRegister bookRegister = dao.find(BookRegister.class, bookRegisterId);
315  if(bookRegister != null) {
316  Register register = bookRegister.getRegister();
317  Document document = register.getDocument();
318  if(document != null) {
319  Contract contract = document.getContract();
320  IContact contractor = contract.getIContractor();
321  DocumentAmountsByBook da = document.getAmountsByBook(bookDefinition);
322  for(AmountTaxable at : da.getTaxables()) {
323  if(at.getTax() == 0) {
324  for(DocumentLine dl : document.getDocumentLines()) {
325  LineType lt = dl.getLineType();
326  if(lt != null && lt.getId() == 183) {
327  countRows++;
328  ws.addCell(new jxl.write.Number(0, countRows, bookRegister.getBookOrder()));
329  ws.addCell(new jxl.write.Label(1, countRows, document.getDocumentNumber()));
330  ws.addCell(new jxl.write.DateTime(2, countRows, register.getRegisterDate(), dateFmt));
331  ws.addCell(new jxl.write.DateTime(3, countRows, document.getDocumentDate(), dateFmt));
332  ws.addCell(new jxl.write.Label(4, countRows, contractor.getGlobalId()));
333  ws.addCell(new jxl.write.Label(5, countRows, contractor.getName()));
334  ws.addCell(new jxl.write.Label(6, countRows, I_.byKey(OperatingModifier.OPMOD_EXTRACOMMUNITY.toString())));
335  ws.addCell(new jxl.write.Number(9, countRows, dl.getPrice()));
336  }/* else if(dl.getPrice() != 0.0) {
337  countRows++;
338  ws.addCell(new jxl.write.Number(0, countRows, bookRegister.getBookOrder()));
339  ws.addCell(new jxl.write.Label(1, countRows, document.getDocumentNumber()));
340  ws.addCell(new jxl.write.DateTime(2, countRows, register.getRegisterDate(), dateFmt));
341  ws.addCell(new jxl.write.DateTime(3, countRows, document.getDocumentDate(), dateFmt));
342  ws.addCell(new jxl.write.Label(4, countRows, contractor.getGlobalId()));
343  ws.addCell(new jxl.write.Label(5, countRows, contractor.getName()));
344  ws.addCell(new jxl.write.Label(6, countRows, Application.getString(contract.getOperatingModifier().toString())));
345  ws.addCell(new jxl.write.Number(8, countRows, dl.getPrice()));
346  ws.addCell(new jxl.write.Number(11, countRows, dl.getPrice()));
347  }*/
348  }
349  } else {
350  countRows++;
351  ws.addCell(new jxl.write.Number(0, countRows, bookRegister.getBookOrder()));
352  ws.addCell(new jxl.write.Label(1, countRows, document.getDocumentNumber()));
353  ws.addCell(new jxl.write.DateTime(2, countRows, register.getRegisterDate(), dateFmt));
354  ws.addCell(new jxl.write.DateTime(3, countRows, document.getDocumentDate(), dateFmt));
355  ws.addCell(new jxl.write.Label(4, countRows, contractor.getGlobalId()));
356  ws.addCell(new jxl.write.Label(5, countRows, contractor.getName()));
357  ws.addCell(new jxl.write.Label(6, countRows, I_.byKey(contract.getOperatingModifier().toString())));
358  ws.addCell(new jxl.write.Number(7, countRows, at.getTax()));
359  ws.addCell(new jxl.write.Number(8, countRows, at.getTaxable()));
360  ws.addCell(new jxl.write.Number(9, countRows, at.getTaxAmount()));
361  ws.addCell(new jxl.write.Number(10, countRows, da.getRetentions().getRetained()));
362  ws.addCell(new jxl.write.Number(11, countRows, at.getTaxRealAmount()-at.getTaxAmount()));
363  ws.addCell(new jxl.write.Number(12, countRows, at.getTotal()));
364  }
365  }
366  }
367  }
368  }
369  }
370 
371  public static InputStream getExcelForDocuments(String sheetName, Collection<Long> documentIds, Map parameters) {
372  try {
373  ByteArrayOutputStream baos = new ByteArrayOutputStream();
374  WritableWorkbook ww = Workbook.createWorkbook(baos);
375  WritableSheet ws = ww.createSheet(sheetName, 0);
376  writeSheetForDocuments(ws, documentIds, parameters);
377  ww.write();
378  ww.close();
379  baos.close();
380  return new ByteArrayInputStream(baos.toByteArray());
381  } catch (WriteException | IOException ex) {
382  Logger.getLogger(ExportQuery.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
383  }
384  return null;
385  }
386 
387  private static void writeSheetForDocuments(WritableSheet ws, Collection<Long> documentIds, Map parameters) throws WriteException {
388  int countCols = 0, countRows = 0;
389  BookDefinition bookDefinition = (BookDefinition) parameters.get("bookDef");
390  String[] columns = new String[] {
391  "No.Registre","No.Factura","Data recepció","Data","NIF / CIF","Expedidor","Tipus","IVA%","Base imposable","IVA","Quota","Import"
392  };
393  for(String s : columns) {
394  ws.addCell(new Label(countCols++, countRows, s));
395  }
396  Dao dao = new FinancialsPU();
397  DateFormat df = new DateFormat("dd/MM/yyyy");
398  df.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"));
399  WritableCellFormat dateFmt = new WritableCellFormat(df);
400  for(Long documentId : documentIds) {
401  Document document = dao.find(Document.class, documentId);
402  if(document != null) {
403  Contract contract = document.getContract();
404  IContact contractor = contract.getIContractor();
405  DocumentAmountsByBook da = document.getAmountsByBook(bookDefinition);
406  for(AmountTaxable at : da.getTaxables()) {
407  countRows++;
408  ws.addCell(new jxl.write.Label(1, countRows, document.getDocumentNumber()));
409  ws.addCell(new jxl.write.DateTime(2, countRows, document.getReceiptDate(), dateFmt));
410  ws.addCell(new jxl.write.DateTime(3, countRows, document.getDocumentDate(), dateFmt));
411  ws.addCell(new jxl.write.Label(4, countRows, contractor.getGlobalId()));
412  ws.addCell(new jxl.write.Label(5, countRows, contractor.getName()));
413  ws.addCell(new jxl.write.Label(6, countRows, I_.byKey(contract.getOperatingModifier().toString())));
414  ws.addCell(new jxl.write.Number(8, countRows, at.getTaxable()));
415  ws.addCell(new jxl.write.Number(11, countRows, at.getTotal()));
416  }
417  }
418  }
419  }
420 
421 }
static InputStream getExcel(String sheetName, Collection< Long > bookRegisters, Map parameters)
Definition: PrintBook.java:284
static InputStream getExcelForDocuments(String sheetName, Collection< Long > documentIds, Map parameters)
Definition: PrintBook.java:371
static void doPrint(Page page, Integer year, final String type)
Definition: PrintBook.java:96
static String get(String msg)
Definition: I_.java:41
static void getInput(Page page, String title, String label, Object value, String format, int scale, final Command onOk)
static Framework getCurrent()
Definition: Framework.java:203