BrightSide Workbench Full Report + Source Code
DiaryReport.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 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 package org.turro.financials.account;
19 
20 import java.io.File;
21 import java.io.IOException;
22 import java.util.*;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 import javax.activation.MimetypesFileTypeMap;
26 import org.amic.util.date.CheckDate;
27 import org.turro.action.IMailSender;
28 import org.turro.action.MailSenders;
29 import org.turro.auth.Authentication;
30 import org.turro.command.Command;
31 import org.turro.command.Context;
32 import org.turro.contacts.Contact;
33 import org.turro.elephant.context.ElephantContext;
34 import org.turro.elephant.db.WhereClause;
35 import org.turro.elephant.util.DateFormats;
36 import org.turro.elephant.util.DecimalFormats;
37 import org.turro.financials.db.FinancialsPU;
38 import org.turro.financials.entity.Company;
39 import org.turro.financials.entity.Register;
40 import org.turro.financials.entity.RegisterView;
41 import org.turro.financials.model.business.CompanyWrapper;
42 import org.turro.financials.model.register.ViewWrapper;
43 import org.turro.financials.view.ViewListbox;
44 import org.turro.i18n.I_;
45 import org.turro.jpa.Dao;
46 import org.turro.jpa.export.ExportAsStream;
47 import org.turro.jpa.export.ExportQuery;
48 import org.turro.message.MessageQueue;
49 import org.turro.plugin.contacts.IContact;
50 import org.turro.print.Print;
51 import org.turro.sql.SqlClause;
52 import org.turro.zkoss.dialog.InputDialog;
53 import org.turro.zkoss.dialog.InputField;
54 import org.turro.zkoss.print.ReportMenuitem;
55 import org.turro.zul.frame.Framework;
56 import org.zkoss.zhtml.Filedownload;
57 import org.zkoss.zk.ui.HtmlBasedComponent;
58 
63 public class DiaryReport extends ReportMenuitem {
64 
65  private Integer year, startPage;
66  private RegisterView view;
67  private Dao dao;
68 
69  public DiaryReport() {
70  }
71 
72  @Override
73  protected void print(final String type) {
74  if(view == null) {
75  view = ViewWrapper.getFormalView();
76  }
77  year = new CheckDate().getYear();
78  startPage = 1;
79 
81  Framework.getCurrent().getPage(),
82  I_.get("Diary book"),
83  new InputField[] {
84  new InputField("Year", year, null, 0),
85  new InputField("Start page", startPage, null, 0),
86  new InputField("View", null, null, 0) {
87  @Override
88  protected HtmlBasedComponent createEditor() {
89  ViewListbox vl = new ViewListbox();
90  vl.setMold("select");
91  return vl;
92  }
93  }
94  }, new Command() {
95  @Override
96  public Object execute(Context context) {
97  InputField[] fields = (InputField[]) context.get("fields");
98  if(fields.length > 0) {
99  for(InputField f : fields) {
100  if("Year".equals(f.getLabel())) {
101  year = (Integer) f.getValue();
102  } else if("Start page".equals(f.getLabel())) {
103  startPage = (Integer) f.getValue() - 1;
104  } else if("View".equals(f.getLabel())) {
105  view = (RegisterView) f.getValue();
106  }
107  }
108  if(year != null) {
109  IContact contact = Authentication.getIContact();
110  MailSenders.getHeavy()
111  .addContact(contact)
112  .onStart(s -> MessageQueue.pushMessage(contact, I_.get("Report will be sent by email")))
113  .onCancel(s -> MessageQueue.pushMessage(contact, I_.get("Task already running")))
114  .onBuild(s -> print2execute((IMailSender) s))
115  .send(I_.get("Diary book"), I_.get("Diary book"));
116  }
117  }
118  return null;
119  }
120  });
121  }
122 
123  private void print2execute(IMailSender sender) {
124  Collection<Long> lines = getRegisters();
125  if(lines != null && lines.size() > 0) {
126  Map parameters = new HashMap();
127  int fractionDigits = CompanyWrapper.getCompanyCurrency().getDefaultFractionDigits();
128  Company company = CompanyWrapper.getDefaultCompany();
129  Contact companyContact = (Contact) company.getIContact().getContact();
130  parameters.put("company", company);
131  parameters.put("companyContact", companyContact);
132  parameters.put("dateFormat", DateFormats.getDefaultFormat());
133  parameters.put("currencyFormat", DecimalFormats.getStringFormat(fractionDigits));
134  parameters.put("exportFormat", "pdf");
135  parameters.put("year", year);
136  parameters.put("startPage", startPage);
137  parameters.put("SUBREPORT_DIR", "../_reports/financials/accounting/");
138  String file = "/WEB-INF/_reports/financials/accounting/DiaryBook.jasper";
139  try {
140  dao = new FinancialsPU();
141  File result = File.createTempFile("report", "_Diary.pdf");
142  Print.getInstance()
143  .setTemplate(ElephantContext.getRealPath(file))
144  .setCollection(lines)
145  .setParameters(parameters)
146  .onRead(bean -> dao.find(Register.class, (Long) bean))
147  .toFile(result);
148  sender.addAttachment(result);
149  sender.onFinish(x -> sender.removeAttachments());
150  } catch (IOException ex) {
151  Logger.getLogger(DiaryReport.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
152  }
153  }
154  }
155 
156  public Collection<Long> getRegisters() {
157  WhereClause wc = new WhereClause();
158  wc.addClause("select reg.id");
159  wc.addClause("from Register reg");
160  wc.addClause("where reg.view = :view");
161  wc.addNamedValue("view", view);
162  wc.addClause("and year(reg.registerDate) = :year");
163  wc.addNamedValue("year", year);
164  wc.addClause("order by reg.idRegister");
165 
166  Dao dao = new FinancialsPU();
167  return dao.getResultList(wc);
168  }
169 
171  WhereClause wc = new WhereClause();
172  wc.addClause("select reg");
173  wc.addClause("from Register reg");
174  wc.addClause("where reg.view = :view");
175  wc.addNamedValue("view", view);
176  wc.addClause("and year(reg.registerDate) = :year");
177  wc.addNamedValue("year", year);
178  wc.addClause("order by reg.idRegister");
179 
180  return wc;
181  }
182 
183  public static void exportDiary() {
184  IContact contact = Authentication.getIContact();
186  .addContact(contact)
187  .onStart(s -> MessageQueue.pushMessage(contact, I_.get("Report will be sent by email")))
188  .onCancel(s -> MessageQueue.pushMessage(contact, I_.get("Task already running")))
189  .onBuild(s -> diaryToExcel((IMailSender) s))
190  .send(I_.get("Export diary"), I_.get("Export diary"));
191  }
192 
193  private static void diaryToExcel(IMailSender sender) {
194  WhereClause wc = new WhereClause();
195  wc.addClause("select r.view.name, year(r.registerDate), month(r.registerDate),day(r.registerDate), ");
196  wc.addClause("substring(re.account.id, 1, 1), (select ma1.description from MajorAccount ma1 where ma1.account = substring(re.account.id, 1, 1)),");
197  wc.addClause("substring(re.account.id, 1, 2), (select ma2.description from MajorAccount ma2 where ma2.account = substring(re.account.id, 1, 2)),");
198  wc.addClause("substring(re.account.id, 1, 3), (select ma3.description from MajorAccount ma3 where ma3.account = substring(re.account.id, 1, 3)),");
199  wc.addClause("ma.account, ma.description, re.account.id,");
200  wc.addClause("re.account.description, re.debit, re.credit");
201  wc.addClause("from RegisterEntry re join re.register r, MajorAccount ma");
202  wc.addClause("where ma.account = (select max(m.account) from MajorAccount as m");
203  wc.addClause("where re.account.id like concat(m.account, '%'))");
204  wc.addClause("order by r.view.name, r.registerDate");
205 
206  List<String> l = Arrays.asList(new String[] {
207  I_.get("View"),
208  I_.get("Year"),
209  I_.get("Month"),
210  I_.get("Day"),
211  "M1", "M1Desc", "M2", "M2Desc", "M3", "M3Desc",
212  I_.get("Major account"),
213  I_.get("Name"),
214  I_.get("Account"),
215  I_.get("Description"),
216  I_.get("Debit"),
217  I_.get("Credit")
218  });
219  try {
220  Dao dao = new FinancialsPU();
221  ExportAsStream eq = new ExportAsStream(dao, l, wc);
222  File result = File.createTempFile("report", "_Diary.xls");
223  eq.generateExcel(result);
224  sender.addAttachment(result);
225  sender.onFinish(x -> sender.removeAttachments());
226  } catch (IOException ex) {
227  Logger.getLogger(DiaryReport.class.getName()).log(Level.SEVERE, null, ex);
228  }
229  }
230 
231  public static void exportAccountBalance(int year, int month, boolean carry, boolean breakdown) {
232  WhereClause wc = new WhereClause();
233  wc.addClause("select r.view.name,");
234  if(breakdown) {
235  wc.addClause("year(r.registerDate),");
236  wc.addClause("month(r.registerDate),");
237  }
238  wc.addClause("substring(re.account.id, 1, 1), (select ma1.description from MajorAccount ma1 where ma1.account = substring(re.account.id, 1, 1)),");
239  wc.addClause("substring(re.account.id, 1, 2), (select ma2.description from MajorAccount ma2 where ma2.account = substring(re.account.id, 1, 2)),");
240  wc.addClause("substring(re.account.id, 1, 3), (select ma3.description from MajorAccount ma3 where ma3.account = substring(re.account.id, 1, 3)),");
241  wc.addClause("ma.account, ma.description, re.account.id,");
242  wc.addClause("re.account.description, sum(re.debit), sum(re.credit)");
243  wc.addClause("from RegisterEntry re join re.register r, MajorAccount ma");
244  wc.addClause("where ma.account = (select max(m.account) from MajorAccount as m");
245  wc.addClause("where re.account.id like concat(m.account, '%'))");
246  wc.addClause("and r.registerDate < :date");
247  wc.addNamedValue("date", new CheckDate(year, month, 1, 0, 0, 0).addMonths(1).getDate());
248  if(carry) {
249  wc.addClause("and year(r.registerDate) >= :carry");
250  wc.addNamedValue("carry", getLastInitialSince(year));
251  wc.addClause("and not (r.exclude = TRUE and year(r.registerDate) = :year)");
252  wc.addNamedValue("year", year);
253  } else {
254  wc.addClause("and year(r.registerDate) = :carry");
255  wc.addNamedValue("carry", year);
256  wc.addClause("and not (r.exclude = TRUE or r.closing = TRUE)");
257  }
258  if(breakdown) {
259  wc.addClause("group by r.view.name, year(r.registerDate), month(r.registerDate), re.account.id, ma.account, ma.description");
260  } else {
261  wc.addClause("group by r.view.name, re.account.id, ma.account, ma.description");
262  }
263  wc.addClause("order by re.account.id");
264 
265  List<String> l;
266  if(breakdown) {
267  l = Arrays.asList(new String[] {
268  I_.get("View"),
269  I_.get("Year"),
270  I_.get("Month"),
271  "M1", "M1Desc", "M2", "M2Desc", "M3", "M3Desc",
272  I_.get("Major account"),
273  I_.get("Name"),
274  I_.get("Account"),
275  I_.get("Description"),
276  I_.get("Debit"),
277  I_.get("Credit")
278  });
279  } else {
280  l = Arrays.asList(new String[] {
281  I_.get("View"),
282  "M1", "M1Desc", "M2", "M2Desc", "M3", "M3Desc",
283  I_.get("Major account"),
284  I_.get("Name"),
285  I_.get("Account"),
286  I_.get("Description"),
287  I_.get("Debit"),
288  I_.get("Credit")
289  });
290  }
291  Dao dao = new FinancialsPU();
292  String name = ElephantContext.getSiteName() + "_AccountBalance.xls";
293  ExportQuery eq = new ExportQuery(l, dao.getResultList(wc));
294  Filedownload.save(eq.getExcel(name), new MimetypesFileTypeMap().getContentType(name), name);
295  }
296 
297  public static Integer getLastInitialSince(int year) {
298  return SqlClause.select("year(max(registerDate))").from("Register")
299  .where().equal("closing", true)
300  .and().equal("exclude", false)
301  .and().smallerOrEqual("year(registerDate)", year)
302  .and().equal("view.id", 1L)
303  .dao(new FinancialsPU())
304  .singleResult(Integer.class);
305  }
306 
307 }
static IMailSender getHeavy()
void addNamedValue(String name, Object value)
static void exportAccountBalance(int year, int month, boolean carry, boolean breakdown)
static Integer getLastInitialSince(int year)
static String get(String msg)
Definition: I_.java:41
InputStream getExcel(String sheetName)
static void pushMessage(IContact contact, String msg)
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
T addContact(IContact contact)
IMailSender onFinish(Consumer command)
IMailSender addAttachment(File file)