001: /*
002: *
003: * JMoney - A Personal Finance Manager
004: * Copyright (c) 2004 Johann Gyger <jgyger@users.sf.net>
005: *
006: *
007: * This program is free software; you can redistribute it and/or modify
008: * it under the terms of the GNU General Public License as published by
009: * the Free Software Foundation; either version 2 of the License, or
010: * (at your option) any later version.
011: *
012: * This program is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of
014: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015: * GNU General Public License for more details.
016: *
017: * You should have received a copy of the GNU General Public License
018: * along with this program; if not, write to the Free Software
019: * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
020: *
021: */
022: package net.sf.jmoney.reconciliation.reconcilePage;
023:
024: import java.util.Collection;
025: import java.util.Vector;
026: import java.util.regex.Matcher;
027:
028: import net.sf.jmoney.IBookkeepingPage;
029: import net.sf.jmoney.entrytable.CellBlock;
030: import net.sf.jmoney.entrytable.EntryData;
031: import net.sf.jmoney.entrytable.OtherEntriesPropertyBlock;
032: import net.sf.jmoney.entrytable.PropertyBlock;
033: import net.sf.jmoney.entrytable.RowSelectionTracker;
034: import net.sf.jmoney.isolation.TransactionManager;
035: import net.sf.jmoney.model2.CurrencyAccount;
036: import net.sf.jmoney.model2.Entry;
037: import net.sf.jmoney.model2.EntryInfo;
038: import net.sf.jmoney.model2.ExtendableObject;
039: import net.sf.jmoney.model2.IncomeExpenseAccount;
040: import net.sf.jmoney.model2.ScalarPropertyAccessor;
041: import net.sf.jmoney.model2.Session;
042: import net.sf.jmoney.model2.Transaction;
043: import net.sf.jmoney.model2.TransactionInfo;
044: import net.sf.jmoney.reconciliation.BankStatement;
045: import net.sf.jmoney.reconciliation.IBankStatementSource;
046: import net.sf.jmoney.reconciliation.MemoPattern;
047: import net.sf.jmoney.reconciliation.ReconciliationAccount;
048: import net.sf.jmoney.reconciliation.ReconciliationAccountInfo;
049: import net.sf.jmoney.reconciliation.ReconciliationEntryInfo;
050: import net.sf.jmoney.reconciliation.ReconciliationPlugin;
051: import net.sf.jmoney.views.NodeEditor;
052:
053: import org.eclipse.core.runtime.CoreException;
054: import org.eclipse.core.runtime.IConfigurationElement;
055: import org.eclipse.core.runtime.IExtension;
056: import org.eclipse.core.runtime.IExtensionPoint;
057: import org.eclipse.core.runtime.IExtensionRegistry;
058: import org.eclipse.core.runtime.Platform;
059: import org.eclipse.jface.dialogs.Dialog;
060: import org.eclipse.swt.SWT;
061: import org.eclipse.swt.events.SelectionAdapter;
062: import org.eclipse.swt.events.SelectionEvent;
063: import org.eclipse.swt.graphics.Point;
064: import org.eclipse.swt.graphics.Rectangle;
065: import org.eclipse.swt.layout.FormAttachment;
066: import org.eclipse.swt.layout.FormData;
067: import org.eclipse.swt.layout.FormLayout;
068: import org.eclipse.swt.layout.GridData;
069: import org.eclipse.swt.layout.GridLayout;
070: import org.eclipse.swt.widgets.Button;
071: import org.eclipse.swt.widgets.Combo;
072: import org.eclipse.swt.widgets.Composite;
073: import org.eclipse.swt.widgets.Event;
074: import org.eclipse.swt.widgets.Listener;
075: import org.eclipse.swt.widgets.Menu;
076: import org.eclipse.swt.widgets.MenuItem;
077: import org.eclipse.swt.widgets.MessageBox;
078: import org.eclipse.swt.widgets.Sash;
079: import org.eclipse.swt.widgets.ToolBar;
080: import org.eclipse.swt.widgets.ToolItem;
081: import org.eclipse.ui.IMemento;
082: import org.eclipse.ui.forms.IManagedForm;
083: import org.eclipse.ui.forms.editor.FormPage;
084: import org.eclipse.ui.forms.widgets.ScrolledForm;
085:
086: /**
087: * Implementation of the page that reconciles bank accounts.
088: *
089: * @author Nigel Westbury
090: */
091: public class ReconcilePage extends FormPage implements IBookkeepingPage {
092:
093: /**
094: * The id for this page. This must match the value given
095: * by the ID attribute in plugin.xml.
096: */
097: public static final String PAGE_ID = "reconcile";
098:
099: protected NodeEditor fEditor;
100:
101: /**
102: * The account being shown in this page.
103: */
104: protected ReconciliationAccount account = null;
105:
106: protected Vector<CellBlock> allEntryDataObjects = new Vector<CellBlock>();
107:
108: protected StatementsSection fStatementsSection;
109: protected StatementSection fStatementSection;
110: protected UnreconciledSection fUnreconciledSection;
111:
112: /**
113: * The statement currently being shown in this page.
114: * Null indicates that no statement is currently showing.
115: */
116: BankStatement statement;
117:
118: /**
119: * the transaction currently being edited, or null
120: * if no transaction is being edited
121: */
122: protected Transaction currentTransaction = null;
123:
124: /**
125: * Create a new page to edit entries.
126: *
127: * @param editor Parent editor
128: */
129: public ReconcilePage(NodeEditor editor) {
130: super (editor, PAGE_ID, "Reconciliation");
131: fEditor = editor;
132: }
133:
134: /* (non-Javadoc)
135: * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
136: */
137: @Override
138: protected void createFormContent(IManagedForm managedForm) {
139: account = ((CurrencyAccount) fEditor.getSelectedObject())
140: .getExtension(ReconciliationAccountInfo
141: .getPropertySet(), true);
142:
143: /*
144: * Set the statement to show initially. If there are any entries in
145: * statements after the last reconciled statement, set the first such
146: * unreconciled statement in this view. Otherwise set the statement to
147: * null to indicate no statement is to be shown.
148: */
149: // TODO: implement this
150: statement = null;
151:
152: // Build an array of all possible properties that may be
153: // displayed in the table.
154:
155: // Add properties from the transaction.
156: for (final ScalarPropertyAccessor propertyAccessor : TransactionInfo
157: .getPropertySet().getScalarProperties3()) {
158: allEntryDataObjects.add(new PropertyBlock<EntryData>(
159: propertyAccessor, "transaction") {
160: @Override
161: public ExtendableObject getObjectContainingProperty(
162: EntryData data) {
163: return data.getEntry().getTransaction();
164: }
165: });
166: }
167:
168: // Add properties from this entry.
169: // For time being, this is all the properties except the account
170: // which come from the other entry, and the amount which is shown in the debit and
171: // credit columns.
172: for (ScalarPropertyAccessor<?> propertyAccessor : EntryInfo
173: .getPropertySet().getScalarProperties3()) {
174: if (propertyAccessor != EntryInfo.getAccountAccessor()
175: && propertyAccessor != EntryInfo
176: .getAmountAccessor()) {
177: allEntryDataObjects.add(new PropertyBlock<EntryData>(
178: propertyAccessor, "this") {
179: @Override
180: public ExtendableObject getObjectContainingProperty(
181: EntryData data) {
182: return data.getEntry();
183: }
184: });
185: }
186: }
187:
188: /* Add properties that show values from the other entries.
189: * These are the account, description, and amount properties.
190: *
191: * I don't know what to do if there are other capital accounts
192: * (a transfer or a purchase with money coming from more than one account).
193: */
194: allEntryDataObjects.add(new OtherEntriesPropertyBlock(EntryInfo
195: .getAccountAccessor()));
196: allEntryDataObjects.add(new OtherEntriesPropertyBlock(EntryInfo
197: .getMemoAccessor(), "description"));
198:
199: ScrolledForm form = managedForm.getForm();
200: GridLayout layout = new GridLayout();
201: layout.numColumns = 2;
202: form.getBody().setLayout(layout);
203:
204: fStatementsSection = new StatementsSection(form.getBody(),
205: managedForm.getToolkit(), account.getBaseObject());
206: GridData data = new GridData(GridData.FILL_VERTICAL);
207: data.verticalSpan = 2;
208: fStatementsSection.getSection().setLayoutData(data);
209: managedForm.addPart(fStatementsSection);
210: fStatementsSection.initialize(managedForm);
211:
212: // Listen for double clicks.
213: // Double clicking on a statement from the list will show
214: // that statement in the statement table.
215: fStatementsSection.addSelectionListener(new SelectionAdapter() {
216: @Override
217: public void widgetDefaultSelected(SelectionEvent e) {
218: StatementDetails statementDetails = (StatementDetails) e.item
219: .getData();
220: statement = statementDetails.statement;
221:
222: // Refresh the statement section
223: fStatementSection.setStatement(
224: statementDetails.statement,
225: statementDetails.openingBalance);
226: }
227: });
228:
229: Composite actionbarContainer = new Composite(form.getBody(), 0);
230:
231: GridLayout actionbarLayout = new GridLayout();
232: actionbarLayout.numColumns = 4;
233: actionbarContainer.setLayout(actionbarLayout);
234:
235: final Combo fStatementsViewCombo = new Combo(
236: actionbarContainer, SWT.DROP_DOWN);
237: fStatementsViewCombo
238: .setItems(new String[] {
239: ReconciliationPlugin
240: .getResourceString("ToolbarSection.hideStatements"),
241: ReconciliationPlugin
242: .getResourceString("ToolbarSection.showStatementsWithoutBalances"),
243: ReconciliationPlugin
244: .getResourceString("ToolbarSection.showStatementsWithBalances"), });
245: fStatementsViewCombo.select(2);
246: fStatementsViewCombo
247: .addSelectionListener(new SelectionAdapter() {
248: @Override
249: public void widgetSelected(SelectionEvent e) {
250: GridData gd = (GridData) fStatementsSection
251: .getSection().getLayoutData();
252: switch (fStatementsViewCombo
253: .getSelectionIndex()) {
254: case 0:
255: gd.heightHint = 0;
256: gd.widthHint = 0;
257: break;
258: case 1:
259: gd.heightHint = SWT.DEFAULT;
260: gd.widthHint = SWT.DEFAULT;
261: fStatementsSection.showBalance(false);
262: break;
263: case 2:
264: gd.heightHint = SWT.DEFAULT;
265: gd.widthHint = SWT.DEFAULT;
266: fStatementsSection.showBalance(true);
267: break;
268: }
269:
270: getManagedForm().getForm().getBody().layout(
271: true);
272: }
273: });
274:
275: Button newStatementButton = new Button(actionbarContainer,
276: SWT.PUSH);
277: newStatementButton.setText("New Statement...");
278: newStatementButton.addSelectionListener(new SelectionAdapter() {
279: @Override
280: public void widgetSelected(SelectionEvent e) {
281: StatementDetails lastStatement = fStatementsSection
282: .getLastStatement();
283: NewStatementDialog messageBox = new NewStatementDialog(
284: getSite().getShell(),
285: lastStatement == null ? null
286: : lastStatement.statement);
287: if (messageBox.open() == Dialog.OK) {
288: statement = messageBox.getValue();
289: long openingBalanceOfNewStatement = lastStatement == null ? account
290: .getStartBalance()
291: : lastStatement.getClosingBalance();
292: fStatementSection.setStatement(statement,
293: openingBalanceOfNewStatement);
294: }
295: }
296: });
297:
298: final ToolBar toolBar = new ToolBar(actionbarContainer,
299: SWT.FLAT);
300: final ToolItem importButton = new ToolItem(toolBar,
301: SWT.DROP_DOWN);
302: importButton.setText("Import");
303: final Menu menu = new Menu(getSite().getShell(), SWT.POP_UP);
304:
305: // The list of sources are taken from the net.sf.jmoney.reconciliation.bankstatements
306: // extension point.
307:
308: // Load the extensions
309: IExtensionRegistry registry = Platform.getExtensionRegistry();
310: IExtensionPoint extensionPoint = registry
311: .getExtensionPoint("net.sf.jmoney.reconciliation.bankstatements");
312: IExtension[] extensions = extensionPoint.getExtensions();
313:
314: for (int i = 0; i < extensions.length; i++) {
315: IConfigurationElement[] elements = extensions[i]
316: .getConfigurationElements();
317: for (int j = 0; j < elements.length; j++) {
318: if (elements[j].getName().equals("statement-source")) {
319: String description = elements[j]
320: .getAttribute("description");
321:
322: MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
323: menuItem.setText(description);
324:
325: final IConfigurationElement this Element = elements[j];
326:
327: menuItem
328: .addSelectionListener(new SelectionAdapter() {
329: @Override
330: public void widgetSelected(
331: SelectionEvent event) {
332: try {
333: // Load the extension point listener for the selected source
334: IBankStatementSource statementSource = (IBankStatementSource) this Element
335: .createExecutableExtension("class");
336: Collection<IBankStatementSource.EntryData> importedEntries = statementSource
337: .importEntries(
338: getSite()
339: .getShell(),
340: getAccount());
341: if (importedEntries != null) {
342: /*
343: * Create a transaction to be used to import the entries. This allows the entries to
344: * be more efficiently written to the back-end datastore and it also groups
345: * the entire import as a single change for undo/redo purposes.
346: */
347: TransactionManager transactionManager = new TransactionManager(
348: account
349: .getDataManager());
350: CurrencyAccount accountInTransaction = transactionManager
351: .getCopyInTransaction(account
352: .getBaseObject());
353: IncomeExpenseAccount defaultCategoryInTransaction = accountInTransaction
354: .getPropertyValue(ReconciliationAccountInfo
355: .getDefaultCategoryAccessor());
356: Session sessionInTransaction = accountInTransaction
357: .getSession();
358:
359: for (IBankStatementSource.EntryData entryData : importedEntries) {
360: Transaction transaction = sessionInTransaction
361: .createTransaction();
362: Entry entry1 = transaction
363: .createEntry();
364: Entry entry2 = transaction
365: .createEntry();
366: entry1
367: .setAccount(accountInTransaction);
368: entry1
369: .setPropertyValue(
370: ReconciliationEntryInfo
371: .getStatementAccessor(),
372: getStatement());
373:
374: /*
375: * Scan for a match in the patterns. If a match is found,
376: * use the values for memo, description etc. from the pattern.
377: */
378: String text = entryData
379: .getTextToMatch();
380: for (MemoPattern pattern : account
381: .getPatternCollection()) {
382: Matcher m = pattern
383: .getCompiledPattern()
384: .matcher(
385: text);
386: System.out
387: .println(pattern
388: .getPattern()
389: + ", "
390: + text);
391: if (m.matches()) {
392: /*
393: * Group zero is the entire string and the groupCount method
394: * does not include that group, so there is really one more group
395: * than the number given by groupCount.
396: */
397: Object[] args = new Object[m
398: .groupCount() + 1];
399: for (int i = 0; i <= m
400: .groupCount(); i++) {
401: args[i] = m
402: .group(i);
403: }
404:
405: // TODO: What effect does the locale have in the following?
406: if (pattern
407: .getCheck() != null) {
408: entry1
409: .setCheck(new java.text.MessageFormat(
410: pattern
411: .getCheck(),
412: java.util.Locale.US)
413: .format(args));
414: }
415:
416: if (pattern
417: .getMemo() != null) {
418: entry1
419: .setMemo(new java.text.MessageFormat(
420: pattern
421: .getMemo(),
422: java.util.Locale.US)
423: .format(args));
424: }
425:
426: if (pattern
427: .getDescription() != null) {
428: entry2
429: .setMemo(new java.text.MessageFormat(
430: pattern
431: .getDescription(),
432: java.util.Locale.US)
433: .format(args));
434: }
435:
436: entry2
437: .setAccount(transactionManager
438: .getCopyInTransaction(pattern
439: .getAccount()));
440:
441: break;
442: }
443: }
444:
445: // If nothing matched, set the default account but no
446: // other property.
447: if (entry2.getAccount() == null) {
448: entry2
449: .setAccount(defaultCategoryInTransaction);
450: entry1
451: .setMemo(entryData
452: .getDefaultMemo());
453: entry2
454: .setMemo(entryData
455: .getDefaultDescription());
456:
457: }
458:
459: entryData
460: .assignPropertyValues(
461: transaction,
462: entry1,
463: entry2);
464: }
465:
466: /*
467: * All entries have been imported and all the properties
468: * have been set and should be in a valid state, so we
469: * can now commit the imported entries to the datastore.
470: */
471: transactionManager
472: .commit("Import Entries");
473: }
474: } catch (CoreException e) {
475: // TODO Auto-generated catch block
476: e.printStackTrace();
477: throw new RuntimeException(
478: "class attribute not found");
479: }
480: }
481: });
482: }
483: }
484: }
485:
486: importButton.addListener(SWT.Selection, new Listener() {
487: public void handleEvent(Event event) {
488: if (!account.isReconcilable()) {
489: MessageBox diag = new MessageBox(getSite()
490: .getShell());
491: diag.setText("Feature not Available");
492: diag
493: .setMessage("Before you can import entries from your bank's servers, you must first set the rules for the initial categories for the imported entries. Press the 'Options...' button to set this up.");
494: diag.open();
495: return;
496: }
497:
498: if (statement == null) {
499: MessageBox diag = new MessageBox(getSite()
500: .getShell());
501: diag.setText("Feature not Available");
502: diag
503: .setMessage("Before you can import entries from your bank's servers, you must first create or select a bank statement into which the entries will be imported.");
504: diag.open();
505: return;
506: }
507:
508: if (event.detail == SWT.ARROW) {
509: Rectangle rect = importButton.getBounds();
510: Point pt = new Point(rect.x, rect.y + rect.height);
511: menu.setLocation(toolBar.toDisplay(pt));
512: menu.setVisible(true);
513: }
514: }
515: });
516:
517: Button optionsButton = new Button(actionbarContainer, SWT.PUSH);
518: optionsButton.setText("Options...");
519: optionsButton.addSelectionListener(new SelectionAdapter() {
520: @Override
521: public void widgetSelected(SelectionEvent e) {
522: ImportOptionsDialog messageBox = new ImportOptionsDialog(
523: getSite().getShell(), account);
524: if (messageBox.open() == Dialog.OK) {
525: // TODO: update the list in the 'import...' dropdown
526: }
527: }
528: });
529:
530: Composite containerOfSash = new Composite(form.getBody(), 0);
531: containerOfSash.setLayout(new FormLayout());
532:
533: // Create the sash first, so the other controls
534: // can be attached to it.
535: final Sash sash = new Sash(containerOfSash, SWT.BORDER
536: | SWT.HORIZONTAL);
537: FormData formData = new FormData();
538: formData.left = new FormAttachment(0, 0); // Attach to left
539: formData.right = new FormAttachment(100, 0); // Attach to right
540: formData.top = new FormAttachment(50, 0); // Attach halfway down
541: sash.setLayoutData(formData);
542:
543: sash.addSelectionListener(new SelectionAdapter() {
544: @Override
545: public void widgetSelected(SelectionEvent event) {
546: final int mimimumHeight = 61; // In Windows, allows 3 lines minimum. TODO: Calculate this for other OS's
547: int y = event.y;
548: if (y < mimimumHeight) {
549: y = mimimumHeight;
550: }
551: if (y + sash.getSize().y > sash.getParent().getSize().y
552: - mimimumHeight) {
553: y = sash.getParent().getSize().y - mimimumHeight
554: - sash.getSize().y;
555: }
556:
557: // We re-attach to the top edge, and we use the y value of the event to
558: // determine the offset from the top
559: ((FormData) sash.getLayoutData()).top = new FormAttachment(
560: 0, y);
561:
562: // Until the parent window does a layout, the sash will not be redrawn in
563: // its new location.
564: sash.getParent().layout();
565: }
566: });
567:
568: GridData gridData1 = new GridData(GridData.FILL_BOTH);
569: gridData1.heightHint = 200; // TODO: tidy up???
570: gridData1.widthHint = 200; // TODO: tidy up???
571: gridData1.grabExcessHorizontalSpace = true;
572: gridData1.grabExcessVerticalSpace = true;
573: containerOfSash.setLayoutData(gridData1);
574:
575: /*
576: * The common row tracker. This is used by both tables, so that
577: * there is only one selection in the part.
578: */
579: RowSelectionTracker rowTracker = new RowSelectionTracker();
580:
581: fStatementSection = new StatementSection(this , containerOfSash,
582: rowTracker);
583: managedForm.addPart(fStatementSection);
584: fStatementSection.initialize(managedForm);
585:
586: formData = new FormData();
587: formData.top = new FormAttachment(0, 0);
588: formData.bottom = new FormAttachment(sash, 0);
589: formData.left = new FormAttachment(0, 0);
590: formData.right = new FormAttachment(100, 0);
591: fStatementSection.getSection().setLayoutData(formData);
592:
593: fUnreconciledSection = new UnreconciledSection(this ,
594: containerOfSash, rowTracker);
595: managedForm.addPart(fUnreconciledSection);
596: fUnreconciledSection.initialize(managedForm);
597:
598: formData = new FormData();
599: formData.top = new FormAttachment(sash, 0);
600: formData.bottom = new FormAttachment(100, 0);
601: formData.left = new FormAttachment(0, 0);
602: formData.right = new FormAttachment(100, 0);
603: fUnreconciledSection.getSection().setLayoutData(formData);
604:
605: form
606: .setText("Reconcile Entries against Bank Statement/Bank's Records");
607: /* probably no longer needed
608: IToolBarManager toolBarManager = form.getToolBarManager();
609: toolBarManager.add(
610: new Action("tree", JMoneyPlugin.createImageDescriptor("icons/TreeView.gif")) {
611: public void run() {
612: fStatementSection.setTreeView();
613: }
614: }
615: );
616:
617: toolBarManager.add(
618: new Action("table", JMoneyPlugin.createImageDescriptor("icons/TableView.gif")) {
619: public void run() {
620: fStatementSection.setTableView();
621: }
622: }
623: );
624:
625: toolBarManager.update(false);
626: */
627: }
628:
629: public CurrencyAccount getAccount() {
630: return account.getBaseObject();
631: }
632:
633: public BankStatement getStatement() {
634: return statement;
635: }
636:
637: public void saveState(IMemento memento) {
638: // Save view state (e.g. the sort order, the set of extension properties that are
639: // displayed in the table).
640: }
641:
642: public void deleteTransaction() {
643: // TODO Auto-generated method stub
644: System.out.println("delete transaction");
645: }
646:
647: public boolean isDeleteTransactionApplicable() {
648: // TODO Auto-generated method stub
649: return true;
650: }
651: }
|