001 /*****************************************************************************
002
003 jBudget.
004 Copyright (C) 2006 Dmitri Petrov
005
006 This program is free software: you can redistribute it and/or modify
007 it under the terms of the GNU General Public License as published by
008 the Free Software Foundation, either version 3 of the License, or
009 (at your option) any later version.
010
011 This program is distributed in the hope that it will be useful,
012 but WITHOUT ANY WARRANTY; without even the implied warranty of
013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 GNU General Public License for more details.
015
016 You should have received a copy of the GNU General Public License
017 along with this program. If not, see <http://www.gnu.org/licenses/>.
018
019 /*****************************************************************************
020
021 /*
022 * AccountEditorPanel.java
023 *
024 * Created on July 18, 2006, 6:45 AM
025 */
026 package org.jbudget.gui.budget;
027
028 import java.awt.BorderLayout;
029 import java.awt.Container;
030 import java.awt.event.ActionEvent;
031 import java.awt.event.ActionListener;
032 import java.awt.event.MouseAdapter;
033 import java.awt.event.MouseEvent;
034 import java.beans.PropertyChangeEvent;
035 import java.beans.PropertyChangeListener;
036 import java.text.DateFormat;
037 import java.text.NumberFormat;
038 import java.text.ParseException;
039 import java.util.ArrayList;
040 import java.util.Date;
041 import java.util.LinkedList;
042 import java.util.List;
043 import javax.swing.DefaultComboBoxModel;
044 import javax.swing.JFrame;
045 import javax.swing.JMenuItem;
046 import javax.swing.JOptionPane;
047 import javax.swing.JPopupMenu;
048 import org.jbudget.Core.Account;
049 import org.jbudget.Core.User;
050 import org.jbudget.gui.templ.AccountEditorPanelTempl;
051 import org.jbudget.gui.user.UserSelectorDialog;
052 import org.jbudget.gui.user.UserSelectorModel;
053 import org.jbudget.gui.user.UserSelectorPanel;
054 import org.jbudget.io.DataManager;
055 import org.jbudget.util.CurrencyFormater;
056 import org.jbudget.util.Pair;
057 import org.jdesktop.swingx.JXTaskPane;
058
059 /**
060 *
061 * @author petrov
062 */
063 public class AccountEditorPanel extends AccountEditorPanelTempl
064 {
065
066 private Account account;
067 private boolean editable = true;
068 private final List<Pair<Integer, String>> holdersInfo =
069 new LinkedList<Pair<Integer, String>>();
070 private final UserSelectorModel selectorModel;
071 private final UserSelectorPanel selectorPanel;
072 private final JPopupMenu userMenu = new JPopupMenu();
073 private final JMenuItem addAccountHolder = new JMenuItem("Add");
074 private final JMenuItem removeAccountHolder = new JMenuItem("Remove");
075 private final Object[] accountTypes =
076 {
077 Account.AccountType.DEBIT,
078 Account.AccountType.CREDIT,
079 Account.AccountType.UNKNOWN
080 };
081 private final DefaultComboBoxModel acctTypeModel =
082 new DefaultComboBoxModel(accountTypes);
083
084 /** Creates a new instance of AcountPanel that is not
085 * connected to any account.
086 */
087 public AccountEditorPanel()
088 {
089 initialize();
090 selectorModel = new UserSelectorModel(holdersInfo);
091 selectorPanel = new UserSelectorPanel(selectorModel);
092 holdersPanel.add(selectorPanel, BorderLayout.CENTER);
093 initActions();
094 }
095
096 /** Creates a new instance of AcountPanel that is initialized by an
097 * existing account. By default the account can be edited.
098 */
099 public AccountEditorPanel(Account account)
100 {
101 this.account = account;
102 initialize();
103 selectorModel = new UserSelectorModel(holdersInfo);
104 selectorPanel = new UserSelectorPanel(selectorModel);
105 holdersPanel.add(selectorPanel, BorderLayout.CENTER);
106 initActions();
107 }
108
109 /** Creates a new instance of AcountPanel that is initialized by an
110 * existing account.
111 * @param editable if true, the account can be edited.
112 */
113 public AccountEditorPanel(Account account, boolean editable)
114 {
115 this.account = account;
116 this.editable = editable;
117 initialize();
118 selectorModel = new UserSelectorModel(holdersInfo);
119 selectorPanel = new UserSelectorPanel(selectorModel);
120 holdersPanel.add(selectorPanel, BorderLayout.CENTER);
121 initActions();
122 }
123
124 /** Initializes the GUI. If account is not null sets all the fields
125 * info from the account.
126 */
127 private void initialize()
128 {
129 acctTypeComboBox.setModel(acctTypeModel);
130 if (account == null)
131 {
132 numberField.setText("");
133 bankNameText.setText("");
134 bankPhoneText.setText("");
135 bankAddressText.setText("");
136 openedOnText.setText("");
137 closedOnText.setText("");
138
139 acctTypeComboBox.setSelectedItem(Account.AccountType.UNKNOWN);
140 limitLabel.setEnabled(false);
141 limitField.setEnabled(false);
142 interestRateLabel.setEnabled(true);
143 interestField.setEnabled(false);
144
145 limitField.setText("");
146 interestField.setText("");
147 statementDayText.setText("");
148
149 noteTextPane.setText("");
150 }
151 else
152 {
153 accountNameText.setText(account.getName());
154 //accountNameText.setEditable(false);
155
156 idValueLabel.setText(Integer.toString((account.getID())));
157
158 numberField.setText(account.getAccountNumber());
159 bankNameText.setText(account.getBankName());
160 bankPhoneText.setText(account.getBankPhone());
161 bankAddressText.setText(account.getBankAddress());
162 Date date = account.getOpeningDate();
163 if (date != null)
164 {
165 openedOnText.setText(DateFormat.getDateInstance().format(date));
166 }
167 else
168 {
169 openedOnText.setText("unknown");
170 }
171 date = account.getClosingDate();
172 if (date != null)
173 {
174 closedOnText.setText(DateFormat.getDateInstance().format(date));
175 }
176 else
177 {
178 closedOnText.setText("Open");
179 }
180 List<Integer> holderIds = account.getAccountHolderUids();
181 List<Pair<Integer, String>> allUsers =
182 DataManager.getInstance().getValidUsers();
183
184 for (Pair<Integer, String> user_info : allUsers)
185 {
186 if (holderIds.contains(user_info.first()))
187 {
188 holdersInfo.add(user_info);
189 }
190 }
191 acctTypeComboBox.setSelectedItem(account.getType());
192 limitLabel.setEnabled(account.getType() != Account.AccountType.UNKNOWN);
193 limitField.setEnabled(account.getType() != Account.AccountType.UNKNOWN);
194 interestRateLabel.setEnabled(account.getType() != Account.AccountType.UNKNOWN);
195 interestField.setEnabled(account.getType() != Account.AccountType.UNKNOWN);
196
197 if (account.getLimit() < 0)
198 {
199 limitField.setText("");
200 }
201 else
202 {
203 limitField.setText(CurrencyFormater.format(account.getLimit()));
204 }
205 if (account.getInterestRate() < 0)
206 {
207 interestField.setText("");
208 }
209 else
210 {
211 NumberFormat formater = NumberFormat.getPercentInstance();
212 formater.setMaximumFractionDigits(2);
213 interestField.setText(formater.format(account.getInterestRate() / 10000.0));
214 }
215
216 if (account.getStatementDay() > 0)
217 {
218 this.statementDayText.setText(Integer.toString(account.getStatementDay()));
219 }
220 else
221 {
222 statementDayText.setText("");
223 }
224 if (account.getName() != null)
225 {
226 noteTextPane.setText(account.getNote());
227 }
228 }
229
230 accountNameText.setEditable(editable);
231 numberField.setEditable(editable);
232 bankNameText.setEditable(editable);
233 bankPhoneText.setEditable(editable);
234 bankAddressText.setEditable(editable);
235 openedOnText.setEditable(editable);
236 closedOnText.setEditable(editable);
237 noteTextPane.setEditable(editable);
238 statementDayText.setEditable(editable);
239 interestField.setEditable(editable);
240 limitField.setEditable(editable);
241 acctTypeComboBox.setEditable(false);
242 acctTypeComboBox.setEnabled(editable);
243 }
244
245 /** Initializing GUI actions. */
246 private void initActions()
247 {
248 // Allow only one expanded panel.
249 PropertyChangeListener expansionListener = new PropertyChangeListener()
250 {
251
252 JXTaskPane[] panes =
253 {
254 generalInfoPanel,
255 miscInfoTaskPane,
256 bankInfoPanel,
257 notePanel
258 };
259
260 public void propertyChange(PropertyChangeEvent event)
261 {
262 if (!event.getPropertyName().equals("collapsed"))
263 {
264 return;
265 }
266 if (((Boolean) event.getNewValue()).booleanValue())
267 {
268 return;
269 }
270 for (JXTaskPane panel : panes)
271 {
272 if (event.getSource() != panel)
273 {
274 panel.setCollapsed(true);
275 }
276 }
277 }
278 };
279
280 generalInfoPanel.addPropertyChangeListener(expansionListener);
281 miscInfoTaskPane.addPropertyChangeListener(expansionListener);
282 bankInfoPanel.addPropertyChangeListener(expansionListener);
283 notePanel.addPropertyChangeListener(expansionListener);
284
285
286 if (!editable)
287 {
288 return;
289 }
290 addAccountHolder.setToolTipText("Add an account holder");
291 removeAccountHolder.setToolTipText("Remove an account holder");
292
293 userMenu.add(addAccountHolder);
294 userMenu.add(removeAccountHolder);
295
296 addAccountHolder.addActionListener(new ActionListener()
297 {
298 public void actionPerformed(ActionEvent ev)
299 {
300 Container parent = AccountEditorPanel.this.getParent();
301 while (parent != null && !(parent instanceof JFrame))
302 {
303 parent = parent.getParent();
304 }
305 int uid = UserSelectorDialog.showDialog((JFrame) parent);
306 if (uid < 0)
307 {
308 return;
309 }
310 User user = DataManager.getInstance().getUser(uid);
311 if (user == null)
312 {
313 return;
314 }
315 selectorModel.addToList(user);
316 }
317 });
318
319 removeAccountHolder.addActionListener(new ActionListener()
320 {
321 public void actionPerformed(ActionEvent ev)
322 {
323 int uid = selectorPanel.getSelectedUID();
324 if (uid < 0)
325 {
326 return;
327 }
328 User user = DataManager.getInstance().getUser(uid);
329 if (user == null)
330 {
331 return;
332 }
333 selectorModel.removeFromList(user);
334 }
335 });
336
337 selectorPanel.addMouseListener(new MouseAdapter()
338 {
339 @Override
340 public void mousePressed(MouseEvent ev)
341 {
342 checkPopup(ev);
343 }
344
345 @Override
346 public void mouseReleased(MouseEvent ev)
347 {
348 checkPopup(ev);
349 }
350
351 private void checkPopup(MouseEvent ev)
352 {
353 int x = ev.getX();
354 int y = ev.getY();
355 if (ev.isPopupTrigger())
356 {
357 userMenu.show(selectorPanel, x, y);
358 }
359 }
360 });
361
362 this.acctTypeComboBox.addActionListener(new ActionListener()
363 {
364
365 public void actionPerformed(ActionEvent ev)
366 {
367 boolean flag = acctTypeComboBox.getSelectedObjects()[0] != Account.AccountType.UNKNOWN;
368 limitLabel.setEnabled(flag);
369 limitField.setEnabled(flag);
370 interestRateLabel.setEnabled(flag);
371 interestField.setEnabled(flag);
372
373 if (acctTypeComboBox.getSelectedObjects()[0] == Account.AccountType.DEBIT)
374 {
375 limitLabel.setText("Minimum Balance:");
376 }
377 if (acctTypeComboBox.getSelectedObjects()[0] == Account.AccountType.CREDIT)
378 {
379 limitLabel.setText("Credit Limit:");
380 }
381 }
382 });
383 }
384
385 /** You need to call this! */
386 public void dispose()
387 {
388 selectorModel.dispose();
389 }
390
391 /** Returns edited or new account. If the panel has an account associated
392 * with it, this function will first synchronize this object with the
393 * information on in the GUI and then return it. If there is no account
394 * associated with this panel, a new account will be created and returned.
395 * This function also saves the new version of the account using
396 * {@link org.petrov.dmitri.jbudget.io.DataManager DataManager}.
397 */
398 public Account getAccount()
399 {
400 return account;
401 }
402
403 /** updates the account from the gui. */
404 public boolean updateAccount() throws ParseException
405 {
406 if (account == null)
407 {
408 String name = accountNameText.getText();
409 account = new Account(name);
410 idValueLabel.setText(Integer.toString((account.getID())));
411 }
412 boolean changed = false;
413
414 // Account Name
415 String newAccountName = accountNameText.getText();
416 String oldAccountName = account.getName();
417
418 if ((oldAccountName == null && (!newAccountName.equals(""))) ||
419 (oldAccountName != null && (!newAccountName.equals(oldAccountName))))
420 {
421 changed = true;
422 account.setName(newAccountName);
423 }
424
425 // Account Type
426 Account.AccountType oldType = account.getType();
427 Account.AccountType newType =
428 (Account.AccountType) acctTypeComboBox.getSelectedObjects()[0];
429 if (oldType != newType)
430 {
431 changed = true;
432 account.setType(newType);
433 }
434
435 // Interest rate
436 try
437 {
438 int oldRate = account.getInterestRate();
439 String rateString = interestField.getText();
440 if (rateString.equals("") || rateString.equals(" ") ||
441 rateString.equalsIgnoreCase("unknown") ||
442 rateString.equals("none"))
443 {
444 account.setInterestRate(-1);
445 if (oldRate >= 0)
446 {
447 changed = true;
448 }
449 }
450 else
451 {
452 if (!rateString.endsWith("%"))
453 {
454 rateString = rateString + "%";
455 }
456 Number rate = NumberFormat.getPercentInstance().parse(rateString);
457 int newRate = (int) (rate.doubleValue() * 10000.0 + 0.5);
458 if (newRate != oldRate)
459 {
460 account.setInterestRate(newRate);
461 changed = true;
462 }
463 }
464
465 }
466 catch (ParseException ex)
467 {
468 JOptionPane.showMessageDialog(this,
469 "Could not undertand the interest rate value.", "Parsing Error",
470 JOptionPane.ERROR_MESSAGE);
471
472 throw ex;
473 }
474
475 // Minimum balance / credit limit
476 try
477 {
478 long oldLimit = account.getLimit();
479 String limitStr = limitField.getText();
480 if (limitStr.equals("") || limitStr.equals(" ") ||
481 limitStr.equalsIgnoreCase("unknown") ||
482 limitStr.equalsIgnoreCase("none"))
483 {
484 account.setLimit(-1L);
485 if (oldLimit != -1)
486 {
487 changed = true;
488 }
489 }
490 else
491 {
492 long newLimit = CurrencyFormater.parseExpression(limitStr);
493 if (newLimit != oldLimit)
494 {
495 account.setLimit(newLimit);
496 changed = true;
497 }
498 }
499 }
500 catch (ParseException ex)
501 {
502 JOptionPane.showMessageDialog(this,
503 "Could not undertand the minimum balance or credit limit value.",
504 "Parsing Error",
505 JOptionPane.ERROR_MESSAGE);
506
507 throw ex;
508 }
509
510 // Statement closing day.
511
512 try
513 {
514 int oldStatementClosingDay = account.getStatementDay();
515 String statementClosingDayStr = statementDayText.getText();
516 if (statementClosingDayStr.equals("") ||
517 statementClosingDayStr.equals(" ") ||
518 statementClosingDayStr.equalsIgnoreCase("unknown") ||
519 statementClosingDayStr.equalsIgnoreCase("none"))
520 {
521 account.setStatementDay(0);
522 if (oldStatementClosingDay > 0)
523 {
524 changed = true;
525 }
526 }
527 else
528 {
529 int newStatementClosingDay = Integer.parseInt(statementClosingDayStr);
530 if (newStatementClosingDay != oldStatementClosingDay)
531 {
532 if (newStatementClosingDay > 31)
533 {
534 JOptionPane.showMessageDialog(this,
535 "Strange statement closing day. There are only so many days in a month...",
536 "Error",
537 JOptionPane.ERROR_MESSAGE);
538 }
539 account.setStatementDay(newStatementClosingDay);
540 changed = true;
541 }
542 }
543 }
544 catch (NumberFormatException ex)
545 {
546 JOptionPane.showMessageDialog(this,
547 "Could not parse the 'Statement Closing Day' value",
548 "Error",
549 JOptionPane.ERROR_MESSAGE);
550 throw new ParseException(statementDayText.getText(), 0);
551 }
552
553 // Account number
554 String newAccountNumber = numberField.getText();
555 String oldAccountNumber = account.getAccountNumber();
556
557 if ((oldAccountNumber == null &&
558 (!newAccountNumber.equals(""))) ||
559 (oldAccountNumber != null &&
560 (!newAccountNumber.equals(oldAccountNumber))))
561 {
562 changed = true;
563 account.setAccountNumber(newAccountNumber);
564 }
565
566 // Bank name
567 String newBankName = bankNameText.getText();
568 String oldBankName = account.getBankName();
569
570 if ((oldBankName == null &&
571 (!newBankName.equals(""))) ||
572 (oldBankName != null &&
573 (!newBankName.equals(oldBankName))))
574 {
575 changed = true;
576 account.setBankName(newBankName);
577 }
578
579
580 // Bank phone
581 String newBankPhone = bankPhoneText.getText();
582 String oldBankPhone = account.getBankPhone();
583
584 if ((oldBankPhone == null &&
585 (!newBankPhone.equals(""))) ||
586 (oldBankPhone != null &&
587 (!newBankPhone.equals(oldBankPhone))))
588 {
589 changed = true;
590 account.setBankPhone(newBankPhone);
591 }
592
593
594 // bank address
595 String newBankAddress = bankAddressText.getText();
596 String oldBankAddress = account.getBankAddress();
597
598 if ((oldBankAddress == null &&
599 (!newBankAddress.equals(""))) ||
600 (oldBankAddress != null &&
601 (!newBankAddress.equals(oldBankAddress))))
602 {
603 changed = true;
604 account.setBankAddress(newBankAddress);
605 }
606
607
608 // Opened on
609 String openedOn = openedOnText.getText();
610 try
611 {
612
613 Date oldOpeningDate = account.getOpeningDate();
614
615 if (openedOn.equals("") || openedOn.equals(" ") ||
616 openedOn.equalsIgnoreCase("unknown"))
617 {
618 if (oldOpeningDate != null)
619 {
620 changed = true;
621 account.setOpeningDate(null);
622 }
623 }
624 else
625 {
626 Date newOpeningDate = DateFormat.getDateInstance().parse(openedOn);
627
628 if (!newOpeningDate.equals(oldOpeningDate))
629 {
630 changed = true;
631 account.setOpeningDate(newOpeningDate);
632 }
633 }
634
635 }
636 catch (ParseException ex)
637 {
638 JOptionPane.showMessageDialog(this,
639 "Could not understand the 'Opened on' date. \n The date format is Jan 1, 2001", "Parsing Error",
640 JOptionPane.ERROR_MESSAGE);
641
642 throw ex;
643 }
644
645
646 // Closed on
647 String closedOn = closedOnText.getText();
648 try
649 {
650 Date oldClosingDate = account.getClosingDate();
651
652 if (closedOn.equals("") || closedOn.equals(" ") ||
653 closedOn.equalsIgnoreCase("unknown") ||
654 closedOn.equalsIgnoreCase("open") ||
655 closedOn.equalsIgnoreCase("still open"))
656 {
657 if (oldClosingDate != null)
658 {
659 changed = true;
660 account.setClosingDate(null);
661 }
662 }
663 else
664 {
665 Date newClosingDate = DateFormat.getDateInstance().parse(closedOn);
666
667 if (!newClosingDate.equals(oldClosingDate))
668 {
669 changed = true;
670 account.setClosingDate(newClosingDate);
671 }
672 }
673 }
674 catch (ParseException ex)
675 {
676 JOptionPane.showMessageDialog(this,
677 "Could not understand the 'Closed on' date. \n The date format is Jan 1, 2001", "Parsing Error",
678 JOptionPane.ERROR_MESSAGE);
679
680 throw ex;
681 }
682
683 // Account Holders
684 List<Integer> oldUids = account.getAccountHolderUids();
685 List<Integer> newUids = new ArrayList<Integer>(holdersInfo.size());
686 for (Pair<Integer, String> hi : holdersInfo)
687 {
688 Integer uid = hi.first();
689 newUids.add(uid);
690 }
691
692 boolean holdersChanged = !oldUids.equals(newUids);
693
694
695 if (holdersChanged)
696 {
697 changed = true;
698 account.setAccountHolderUids(newUids);
699 }
700
701 // note
702 String oldNote = account.getNote();
703 String newNote = noteTextPane.getText();
704 if (newNote.equals(""))
705 {
706 account.setNote(null);
707 if (oldNote != null)
708 {
709 changed = true;
710 }
711 }
712 else
713 {
714 if (!newNote.equals(oldNote))
715 {
716 account.setNote(newNote);
717 changed = true;
718 }
719 }
720
721 if (changed)
722 {
723 DataManager.getInstance().updateAccount(account);
724 }
725 return changed;
726 }
727 }