Package lazy8ledger

Source Code of lazy8ledger.Lazy8LedgerPlugin

/*
* :tabSize=2:indentSize=2:noTabs=true:
* :folding=explicit:collapseFolds=1:
*
*  Copyright (C) 2009 Chaniel AB, Thomas Dilts This program is free
*  software; you can redistribute it and/or modify it under the terms of the
*  GNU General Public License as published by the Free Software Foundation;
*  either version 2 of the License, or (at your option) any later version. This
*  program is distributed in the hope that it will be useful, but WITHOUT ANY
*  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
*  FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
*  details. You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software Foundation,
*  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For more
*  information, surf to www.lazy8.nu or email support@lazy8.nu
*/

package lazy8ledger;

//{{{ imports
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.mckoi.database.Database;
import com.mckoi.database.DatabaseSystem;
import com.mckoi.database.control.DefaultDBConfig;
import nu.lazy8.ledger.forms.ChangeLanguagesDialogs;
import nu.lazy8.ledger.forms.CreateNewCompany;
import nu.lazy8.ledger.forms.CreateTestCompany;
import nu.lazy8.ledger.forms.DoYouWantToInstall;
import nu.lazy8.ledger.forms.GoToTutorialMessage;
import nu.lazy8.ledger.forms.StartUpDialogs;
import nu.lazy8.ledger.forms.Upgrade20Dialogs;
import nu.lazy8.ledger.forms.UseEquityHelpDialog;
import nu.lazy8.ledger.jdbc.DataConnection;
import nu.lazy8.ledger.jdbc.DatabaseBackup;
import nu.lazy8.ledger.jdbc.UniqNumGenerator;
import nu.lazy8.ledger.main.Lazy8Ledger;
import nu.lazy8.util.gen.Fileio;
import nu.lazy8.util.gen.SetupInfo;
import nu.lazy8.util.gen.SystemLog;
import nu.lazy8.util.gen.Translator;
import nu.lazy8.util.gen.WorkingDialog;
import org.gjt.sp.jedit.EditPlugin;
import org.gjt.sp.jedit.GUIUtilities;
import org.gjt.sp.jedit.OptionGroup;
import org.gjt.sp.jedit.gui.OptionsDialog;
import org.gjt.sp.jedit.jEdit;
import org.gjt.sp.util.Log;

import java.awt.Dimension;
import infoviewer.InfoViewer;
import org.gjt.sp.jedit.gui.DockableWindowManager;

//}}}

/**
*  Description of the Class
*
* @author     thomas
* @created    den 2 juli 2004
*/
public class Lazy8LedgerPlugin extends EditPlugin {
  private static boolean isFirstTimeStarting=false;
  public static boolean isInStart=false;

  //{{{ -ConvertDatabaseToNewestVersion() : void
    /**
   *  Description of the Method
   */
  private void ConvertDatabaseToNewestVersion() {
    String stringPass = SetupInfo.getProperty(SetupInfo.CONNECT_PASSWORD);
    String stringUser = SetupInfo.getProperty(SetupInfo.CONNECT_USERNAME);
    boolean isLoginRequired = SetupInfo.getBoolProperty(SetupInfo.REQUIRE_LOGIN);
    if (isLoginRequired) {
      DataConnection.PasswordDialog pDialog =
          new DataConnection.PasswordDialog(null, true, false);
      if (pDialog.bIsCancel) {
        return;
      }
      stringPass = new String(pDialog.jPass.getPassword());
      stringUser = new String(pDialog.jUser.getText());
      pDialog.dispose();
    }
    String stringDriver = SetupInfo.getProperty(SetupInfo.CONNECT_DRIVER);
    if (stringUser.length() == 0 || stringPass.length() == 0) {
      //mckoi requires some sort of password
      stringUser = "PasswordIsPass";
      stringPass = "Pass"; // FIXME: stringPass is never used
    }

    WorkingDialog workDialog = new WorkingDialog(null);
    workDialog.setVisible(true);
    workDialog.SetProgress(0);
    DatabaseSystem system = new DatabaseSystem();
    // Create a default configuration
    DefaultDBConfig config = new DefaultDBConfig();
    File ff;
    try {
      ff = Fileio.getFile("data", "data", false, false);
    } catch (Exception ee) {
      SystemLog.ErrorPrint("Cant find db.conf : " + ee.getMessage());
      workDialog.dispose();
      return;
    }
    config.setDatabasePath(ff.getAbsolutePath());
    config.setMinimumDebugLevel(Integer.MAX_VALUE);
    // Set up the log file
    system.setDebugLevel(Integer.MAX_VALUE);
    // Initialize the DatabaseSystem,
    // -----------------------------
    // This will throw an Error exception if the database system has already
    // been initialized.
    system.init(config);
    // Note, currently we only register one database, and it is named
    //   'DefaultDatabase'.
    Database database = new Database(system, "DefaultDatabase");
    boolean success = false;
    try {
      // Convert to the current version.
      success = database.convertToCurrent(System.out, stringUser);
    } catch (IOException e) {
      System.out.println("IO Error: " + e.getMessage());
      e.printStackTrace(System.out);
    }

    if (success) {
      System.out.println("-- Convert Successful --");
    } else {
      if (stringDriver.compareTo(DataConnection.MCKOI_DRIVER) != 0 &&
          stringUser.compareTo("PasswordIsPass") != 0) {
        //they are using another database, try again.
        try {
          // Convert to the current version.
          success = database.convertToCurrent(System.out, "PasswordIsPass");
        } catch (IOException e) {
          System.out.println("IO Error: " + e.getMessage());
          e.printStackTrace(System.out);
        }
      }
      if (success) {
        System.out.println("-- Convert Successful --");
      } else {
        System.out.println("-- Convert Failed --");
      }
    }

    SetupInfo.setBoolProperty(SetupInfo.IS_DATBASE_94_UPGRADE_DONE, success);
    SetupInfo.store();
    if (success) {
      UpgradeAccounts(workDialog);
      Upgrade20Dialogs up = new Upgrade20Dialogs(null, true, true,
          Translator.getTranslation("Upgrade to Lazy 8 Ledger 2.0."), 0);
    }
    workDialog.dispose();
  }//}}}

  //{{{ -_LoadLanguage(String)_ : void
    /**
   *  Description of the Method
   *
   * @param  newLanguage  Description of the Parameter
   */
  private static void LoadLanguage(String newLanguage) {
    //copy all language properties to the main jEdit property archive
    Properties jLazy8LangProps = new Properties();
    try {
      jLazy8LangProps.load(Fileio.getInputStream(
          newLanguage + ".bin", "lang"));
    } catch (IOException ee) {
      Log.log(Log.ERROR, null, "Cannot open file=" +
          newLanguage + ".bin  : error=" + ee);
    }
    String nameElement;
    for (Enumeration e = jLazy8LangProps.propertyNames(); e.hasMoreElements(); ) {
      nameElement = (String) e.nextElement();
      if (!nameElement.startsWith("lazy8ledgerTRANS-")) {
        jEdit.setTemporaryProperty(nameElement, jLazy8LangProps.getProperty(nameElement));
        //we must change the NAME of this plugin for the new jEdit API
        if (nameElement.equals("options.lazy8ledger-lazy8ledger.label")) {
          jEdit.setProperty("plugin.lazy8ledger.Lazy8LedgerPlugin.name", jLazy8LangProps.getProperty(nameElement));
        }
      }
    }
    Translator.reInitialize();
  }//}}}

  //{{{ -UpgradeAccounts(WorkingDialog) : void
    /**
   *  Description of the Method
   *
   * @param  workDialog  Description of the Parameter
   */
  private void UpgradeAccounts(WorkingDialog workDialog) {
    //convert all the accounts IsAsset field to show more asset/debt/income/expense
    try {
      DataConnection dc = new DataConnection(null);
      if (dc == null || !dc.bIsConnectionMade) {
        return;
      }
      Statement st = dc.con.createStatement();
      ResultSet rsAccounts = st.executeQuery(dc.filterSQL(
          "SELECT APP.Account.Account FROM APP.Account WHERE " +
          "(IsAsset=0 AND (APP.Account.Account<3000 OR APP.Account.Account>=10000)) " +
          "OR (IsAsset=1 AND (APP.Account.Account<1000 OR APP.Account.Account>=3000)) "));
      int numEuBasErrors = 0;
      if (rsAccounts.next()) {
        rsAccounts.last();
        numEuBasErrors = rsAccounts.getRow();
      }
      st = dc.con.createStatement();
      rsAccounts = st.executeQuery(dc.filterSQL(
          "SELECT CompId,APP.Account.Account,AccDesc,IsAsset FROM APP.Account"));
      int numRows = 0;
      if (rsAccounts.next()) {
        rsAccounts.last();
        numRows = rsAccounts.getRow();
        rsAccounts.beforeFirst();
      }
      if (numRows > 0) {
        int ACCOUNT_TYPE_ASSET = 0;
        int ACCOUNT_TYPE_DEBT = 1;
        int ACCOUNT_TYPE_INCOME = 2;
        int ACCOUNT_TYPE_EXPENSE = 3;
        boolean isEuBasAccounting = true;
        if ((numEuBasErrors * 100 / numRows) > 10) {
          //more then 10% errors
          isEuBasAccounting = false;
        }
        //attempt to see if this is a EU BAS 2000 account. system
        rsAccounts.beforeFirst();
        while (rsAccounts.next()) {
          //sum up account
          workDialog.SetProgress(100 * rsAccounts.getRow() / numRows);
          int oldIsAsset = rsAccounts.getInt(4);
          int defaultIsAsset = 0;
          int AccountNum = rsAccounts.getInt(2);
          if (isEuBasAccounting) {
            //assume this is the EU bas 2000 accounting system
            //these numbers are hard coded now because at this point, the AccountType
            //table does not exist.
            if (AccountNum < 2000) {
              defaultIsAsset = ACCOUNT_TYPE_ASSET;
            } else if (AccountNum >= 2000 && AccountNum < 3000) {
              defaultIsAsset = ACCOUNT_TYPE_DEBT;
            } else if ((AccountNum >= 3000 && AccountNum < 4000)
                 || (AccountNum >= 8000 && AccountNum < 8400)
                 || (AccountNum >= 8700 && AccountNum < 8750)
                 || (AccountNum >= 8800 && AccountNum < 8900)
                 || (AccountNum >= 8990 && AccountNum < 9000)) {
              defaultIsAsset = ACCOUNT_TYPE_INCOME;
            } else if ((AccountNum >= 4000 && AccountNum < 8000)
                 || (AccountNum >= 8400 && AccountNum < 8700)
                 || (AccountNum >= 8750 && AccountNum < 8800)
                 || (AccountNum >= 8900 && AccountNum < 8990)) {
              defaultIsAsset = ACCOUNT_TYPE_EXPENSE;
            } else {
              if (oldIsAsset == 0) {
                defaultIsAsset = ACCOUNT_TYPE_INCOME;
              } else {
                defaultIsAsset = ACCOUNT_TYPE_ASSET;
              }
            }
          } else {
            Statement st2 = dc.con.createStatement();
            ResultSet rsSumAccounts = st2.executeQuery(dc.filterSQL(
                "SELECT Sum(Amount.Amount * ((2 * Amount.IsDebit) - 1) ) AS SumOfAmount1 " +
                "FROM Amount WHERE CompId=" + rsAccounts.getInt(1)
                 + " AND Amount.Account=" + AccountNum));
            if (oldIsAsset == 0) {
              defaultIsAsset = ACCOUNT_TYPE_INCOME;
            } else {
              defaultIsAsset = ACCOUNT_TYPE_ASSET;
            }
            if (rsSumAccounts.next()) {
              double amount = rsSumAccounts.getDouble(1);
              if (oldIsAsset == 0) {
                if (amount >= 0) {
                  defaultIsAsset = ACCOUNT_TYPE_EXPENSE;
                } else {
                  defaultIsAsset = ACCOUNT_TYPE_INCOME;
                }
              } else {
                if (amount >= 0) {
                  defaultIsAsset = ACCOUNT_TYPE_ASSET;
                } else {
                  defaultIsAsset = ACCOUNT_TYPE_DEBT;
                }
              }
            }
          }
          Statement st3 = dc.con.createStatement();
          st3.executeUpdate(dc.filterSQL(
              "UPDATE APP.Account SET IsAsset=" + defaultIsAsset + " WHERE CompId="
               + rsAccounts.getInt(1) + " AND APP.Account.Account=" + AccountNum));
        }
      }
    } catch (Exception eee) {
      System.out.println("Fixing Account.isAsset field Error: " + eee.getMessage());
      eee.printStackTrace(System.out);
    }
  }//}}}

  //{{{ +_createBackupCompanyFrame(JFrame)_ : void
    /**
   *  Description of the Method
   *
   * @param  view  Description of the Parameter
   */
  public static void createBackupCompanyFrame(JFrame view) {
    DataConnection dc = DataConnection.getInstance(view);
    if (dc == null || !dc.bIsConnectionMade) {
      return;
    }
    DatabaseBackup db = new DatabaseBackup(
        dc.con);
    db.BackupDatabase(db.sTables, true);
  }//}}}

  //{{{ +_createBackupFrame(JFrame)_ : void
    /**
   *  Description of the Method
   *
   * @param  view  Description of the Parameter
   */
  public static void createBackupFrame(JFrame view) {
    DataConnection dc = DataConnection.getInstance(view);
    if (dc == null || !dc.bIsConnectionMade) {
      return;
    }
    DatabaseBackup db = new DatabaseBackup(
        dc.con);
    db.BackupDatabase(db.sTables, false);
  }//}}}

  //{{{ +createMenuItems(Vector) : void
    /**
   *  Description of the Method
   *
   * @param  menuItems  Description of the Parameter
   * TODO: Consider using Plugin menu item properties instead since createMenuItems(Vector menuItems) is deprecated
   */
  public void createMenuItems(Vector menuItems) {
    menuItems.addElement(GUIUtilities.loadMenu("lazy8ledger-menu"));
  }//}}}

  //{{{ +createOptionPanes(OptionsDialog) : void
    /**
   *  Description of the Method
   * TODO: Consider using Plugin option pane properties instead since createOptionPanes(OptionsDialog optionsDialog) is deprecated
   * @param  optionsDialog  Description of the Parameter
   */
  public void createOptionPanes(OptionsDialog optionsDialog) {
    OptionGroup og = new OptionGroup("lazy8ledger-lazy8ledger");
    JFrame view = GUIUtilities.getView(optionsDialog);
    og.addOptionPane(new LedgerGeneralOptionPane(view));
    og.addOptionPane(new LedgerNumberOptionPane(view));
    og.addOptionPane(new LedgerWarningsOptionPane(view));
    optionsDialog.addOptionGroup(og);
  }//}}}

  //{{{ +_createRestoreCompanyFrame(JFrame)_ : void
    /**
   *  Description of the Method
   *
   * @param  view  Description of the Parameter
   */
  public static void createRestoreCompanyFrame(JFrame view) {
    DataConnection dc = DataConnection.getInstance(view);
    if (dc == null || !dc.bIsConnectionMade) {
      return;
    }
    DatabaseBackup db = new DatabaseBackup(
        dc.con);
    db.RestoreDatabase(true, null, 0, view);
  }//}}}

  //{{{ +_createRestoreFile(Connection, boolean, String, int, JFrame)_ : void
    /**
   *  Description of the Method
   *
   * @param  con                     Description of the Parameter
   * @param  bRestoreOneCompanyOnly  Description of the Parameter
   * @param  fileName                Description of the Parameter
   * @param  iNewCompany             Description of the Parameter
   * @param  view                    Description of the Parameter
   */
  public static void createRestoreFile(Connection con,
      boolean bRestoreOneCompanyOnly, String fileName, int iNewCompany, JFrame view) {
    DatabaseBackup db = new DatabaseBackup(con);
    db.RestoreDatabase(bRestoreOneCompanyOnly, fileName, iNewCompany, view);
  }//}}}

  //{{{ +_createRestoreFrame(JFrame)_ : void
    /**
   *  Description of the Method
   *
   * @param  view  Description of the Parameter
   */
  public static void createRestoreFrame(JFrame view) {
    DataConnection dc = DataConnection.getInstance(view);
    if (dc == null || !dc.bIsConnectionMade) {
      return;
    }
    DatabaseBackup db = new DatabaseBackup(
        dc.con);
    db.RestoreDatabase(false, null, 0, view);
  }//}}}

  //{{{ +_setAllTemporaryProperties()_ : void
    /**
   *  Sets the allTemporaryProperties attribute of the Lazy8LedgerPlugin class
   */
  public static void setAllTemporaryProperties() {
    //----------------menus-----------------
    int menuLevel = jEdit.getIntegerProperty("lazy8ledger.menu.level", 0);
    try {
      //must add the translations for the jEdit menus and dialogs.
      String nameElement;
      Translator.getTranslation("");
      //this will initialize Translator
      for (Enumeration e = Translator.presentLanguage.propertyNames(); e.hasMoreElements(); ) {
        nameElement = (String) e.nextElement();
        if (!nameElement.startsWith("lazy8ledgerTRANS")) {
          jEdit.setTemporaryProperty(nameElement, Translator.presentLanguage.getProperty(nameElement));
        }
      }
      //add all the new properties depending on the menu selection
      Properties jLazy8GenMenuProps = new Properties();
      jLazy8GenMenuProps.load(Fileio.getInputStream("programmeraccountant.bin", "props"));
      Properties jLazy8AccMenuProps = new Properties();
      jLazy8AccMenuProps.load(Fileio.getInputStream("accountant.bin", "props"));
      switch (menuLevel) {
        case 0:
          for (Enumeration e = jLazy8AccMenuProps.propertyNames(); e.hasMoreElements(); ) {
            nameElement = (String) e.nextElement();
            jEdit.setTemporaryProperty(nameElement, jLazy8AccMenuProps.getProperty(nameElement));
          }
        //bleed on over to the next case.  We need these properties also
        case 1:
          if (!SetupInfo.getBoolProperty(SetupInfo.ALL_WINDOWS_FLOATING)) {
            for (Enumeration e = jLazy8GenMenuProps.propertyNames(); e.hasMoreElements(); ) {
              nameElement = (String) e.nextElement();
              jEdit.setTemporaryProperty(nameElement, jLazy8GenMenuProps.getProperty(nameElement));
            }
          }
          break;
        case 2:
          //must remove all the translations for the jEdit menus and dialogs.
          for (Enumeration e = Translator.presentLanguage.propertyNames(); e.hasMoreElements(); ) {
            nameElement = (String) e.nextElement();
            if (!nameElement.startsWith("lazy8ledger")) {
              jEdit.resetProperty(nameElement);
            }
          }
          break;
      }
    } catch (IOException ee) {
    }
    //----------------languages-----------------------
    LoadLanguage(SetupInfo.getProperty(SetupInfo.PRESENT_LANGUAGE));
  }//}}}

  //{{{ +_saveAllTemporaryProperties()_ : void
    public static void saveAllTemporaryProperties() {
    int menuLevel = jEdit.getIntegerProperty("lazy8ledger.menu.level", 0);
    try {
      //add all the new properties depending on the menu selection
      Properties jLazy8GenMenuProps = new Properties();
      jLazy8GenMenuProps.load(Fileio.getInputStream("programmeraccountant.bin", "props"));
      Properties jLazy8AccMenuProps = new Properties();
      jLazy8AccMenuProps.load(Fileio.getInputStream("accountant.bin", "props"));
      String nameElement;
      switch (menuLevel) {
        case 0:
          for (Enumeration e = jLazy8AccMenuProps.propertyNames(); e.hasMoreElements(); ) {
            nameElement = (String) e.nextElement();
            jLazy8AccMenuProps.setProperty(nameElement,jEdit.getProperty(nameElement));
          }
          jLazy8AccMenuProps.store(new FileOutputStream(Fileio.getFile("accountant.bin", "props", true, false)),"Version 1.0");
        //bleed on over to the next case.  We need these properties also
        case 1:
          if (!SetupInfo.getBoolProperty(SetupInfo.ALL_WINDOWS_FLOATING)) {
            for (Enumeration e = jLazy8GenMenuProps.propertyNames(); e.hasMoreElements(); ) {
              nameElement = (String) e.nextElement();
              jLazy8GenMenuProps.setProperty(nameElement,jEdit.getProperty(nameElement));
            }
            jLazy8GenMenuProps.store(new FileOutputStream(Fileio.getFile("programmeraccountant.bin", "props", true, false)),"Version 1.0");
          }
          break;
      }
    } catch (Exception ee) {
      ee.printStackTrace();
    }
    //----------------languages-----------------------
    LoadLanguage(SetupInfo.getProperty(SetupInfo.PRESENT_LANGUAGE));
  }//}}}

  //{{{ +_showStartupInstallSequence()_ : boolean
    /**
   *  Description of the Method
   *
   * @return    Description of the Return Value
   */
  private static boolean showStartupInstallSequence() {
    /*
     *  start the whole setup sequence.......
     *  1.  Get what language.  First get from OS what is the OS language
     *  2.  Get the country and region in order to make changes in number formats
     *  3.  Get a password if desired.  highly recommended not to
     *  4.  Proffesional rules.  Dissallow changes in the database?
     *  5.  Get the menu type.  Bookkeeper, programmer bookeeper, programmer just testing this module.
     *  6.  Create a new company and period
     *  7.  Create a test company if desired.
     *  8.  Give them a message about the tutorial
     */
    boolean isInstalled = true;
    if (!SetupInfo.getBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE)) {
      DoYouWantToInstall inst = new DoYouWantToInstall(null);
      if (inst.isDoInstall) {
        //the newer database will be installed
        SetupInfo.setBoolProperty(SetupInfo.IS_DATBASE_94_UPGRADE_DONE, true);
        //change the flag so that we never come here again..!!
        SetupInfo.setBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE, true);
        //copy all language properties to the main jEdit property archive
        SetupInfo.setProperty(SetupInfo.PRESENT_LANGUAGE, "en");
        SetupInfo.store();
        setAllTemporaryProperties();
        new ChangeLanguagesDialogs(null, false);
        new UseEquityHelpDialog(null, false);
        new StartUpDialogs(null, false);
        new CreateNewCompany(null, false);
        new CreateTestCompany(null);
        new GoToTutorialMessage(null);
      } else {
        isInstalled = false;
      }
    }
    return isInstalled;
  }//}}}

  //{{{ +start() : void
    /**
   *  Description of the Method
   */
  public void start() {
    if (isInStart) return;
    isInStart=true;
   
    //must check for an upgrade from anything lower then 2.24..
    File dirNewConfig = EditPlugin.getPluginHome(jEdit.getPlugin("lazy8ledger.Lazy8LedgerPlugin"));
    if (!dirNewConfig.isDirectory()) {
      File dirOldConfig = new File(Fileio.get_OLD_HomeDir());
      if (dirOldConfig.isDirectory()) {
        //this may seem crazy but it is necessary to create all the path to our new home
        dirNewConfig.mkdirs();
        //now the crazy part. Delete the last directory in the path so the move will go smoothly.
        dirNewConfig.delete();
        //Must move entire lazy8 home directory
        if (!dirOldConfig.renameTo(dirNewConfig)){
          JOptionPane.showMessageDialog(null,"Cannot move directory " + Fileio.get_OLD_HomeDir() + " to " + dirNewConfig.getAbsolutePath()
            + "\n\nYou must do this manually before Lazy8Ledger will work." ,"Major Error in Lazy8Ledger",JOptionPane.PLAIN_MESSAGE);   
          isInStart=false;
          return;
        }
      }
    }
   
   
    //is the program installed in the previous version.
    //if so, we need to upgrade the database
    if (SetupInfo.getBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE)
         && !SetupInfo.getBoolProperty(SetupInfo.IS_DATBASE_94_UPGRADE_DONE)) {
      ConvertDatabaseToNewestVersion();
    }
    //if first time starting this program!!!
    if (!SetupInfo.getBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE)) {
      showStartupInstallSequence();
      //change the flag so that we never come here again..!!
      SetupInfo.setProperty("lazy8ledger.lastRunVersion",
          jEdit.getProperty("plugin.lazy8ledger.Lazy8LedgerPlugin.version"));
      SetupInfo.store();
      isFirstTimeStarting=true;
    } else if (SetupInfo.getBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE)) {
     
      //{{{ Update to 2.13
      if (SetupInfo.getProperty("lazy8ledger.lastRunVersion").compareTo("2.13") < 0) {
        //This will fix the messed up jedit menus.  Setting the defaults back to the original
        //erase all the menu properties
        Properties jLazy8GenMenuProps = new Properties();
        try {
          jLazy8GenMenuProps.load(Fileio.getInputStream("programmeraccountant.bin", "props"));
        } catch (Exception eee) {}
        for (Enumeration e = jLazy8GenMenuProps.propertyNames(); e.hasMoreElements(); ) {
          jEdit.resetProperty((String) (e.nextElement()));
        }
        Properties jLazy8AccMenuProps = new Properties();
        try {
          jLazy8AccMenuProps.load(Fileio.getInputStream("accountant.bin", "props"));
        } catch (Exception eeee) {}
        for (Enumeration e = jLazy8AccMenuProps.propertyNames(); e.hasMoreElements(); ) {
          jEdit.resetProperty((String) (e.nextElement()));
        }
        //this is a new property that needs a default of true
        SetupInfo.setBoolProperty(SetupInfo.DELETE_NULL_ACCOUNTS_IN_REPORTS, true);
      }//}}}

      //{{{ Update to 2.16
      if (SetupInfo.getProperty("lazy8ledger.lastRunVersion").compareTo("2.16") < 0) {
        //this new property needs a default of true!
        SetupInfo.setBoolProperty(SetupInfo.WARNING_BEFORE_RE_ADDING, true);
        SetupInfo.store();
        //lots of database changes to make
        //need a connection to the database
        try {
          DataConnection dc = new DataConnection(null);
          if (dc == null || !dc.bIsConnectionMade) {
            JOptionPane.showMessageDialog(null,
                Translator.getTranslation("Could not connect to the database.  Do not attempt to continue."),
                Translator.getTranslation("Must restart"),
                JOptionPane.PLAIN_MESSAGE);
            isInStart=false;
            return;
          }
          new UseEquityHelpDialog(null, false);
          //every company must have these new account types entered
          Statement st ;
          PreparedStatement prepSt;
          DataConnection.AddDefaultAccountTypes(0);
          //copy old Customer table into new Customer2 table
          st = dc.con.createStatement();
          ResultSet rsOldCustomers = st.executeQuery(dc.filterSQL(
              "SELECT CompId,CustId,CustName,CustDesc  FROM Customer"));
          while (rsOldCustomers.next()) {
            prepSt = dc.con.prepareStatement("INSERT INTO Customer2 (CompId,CustId,CustName,CustDesc,DefaultAcc) VALUES (?,?,?,?,?)");
            prepSt.setInt(1, rsOldCustomers.getInt(1));
            prepSt.setInt(2, rsOldCustomers.getInt(2));
            prepSt.setString(3, rsOldCustomers.getString(3));
            prepSt.setString(4, rsOldCustomers.getString(4));
            prepSt.setInt(5, 0);
            prepSt.executeUpdate();
            SystemLog.ErrorPrintln("Copied row from old customer to new=" + rsOldCustomers.getString(3));
          }
          //delete the old Customer table
          st = dc.con.createStatement();
          st.executeUpdate("DROP TABLE Customer");
          SystemLog.ErrorPrintln("Dropped old table Customer");
        } catch (Exception e) {
          e.printStackTrace();
          //we need to continue because otherwise this is a lock stoping proper usage of lazy8ledger forever
          //return;
        }
      }//}}}
     
      //{{{ Update to 2.20
      if (SetupInfo.getProperty("lazy8ledger.lastRunVersion").compareTo("2.20") < 0) {
        //lots of database changes to make
        //need a connection to the database
        WorkingDialog workDialog = new WorkingDialog(null);
        workDialog.setVisible(true);
        try {
          DataConnection dc = new DataConnection(null);
          if (dc == null || !dc.bIsConnectionMade) {
            JOptionPane.showMessageDialog(null,
                Translator.getTranslation("Could not connect to the database.  Do not attempt to continue."),
                Translator.getTranslation("Must restart"),
                JOptionPane.PLAIN_MESSAGE);
            isInStart=true;
            return;
          }
          //copy old Activity table into new Activity2 table
          //UniqNumGenerator uniqnum = new UniqNumGenerator(); // commented out since never used
          Statement st = dc.con.createStatement();
          ResultSet rsOldTrans = st.executeQuery(dc.filterSQL(
              "SELECT CompId,Act_id,RegDate,InvDate,Notes,FileInfo FROM Activity ORDER BY CompId,Act_id"));
          rsOldTrans.last();
          int numRecs=rsOldTrans.getRow();
          rsOldTrans.beforeFirst();
          while (rsOldTrans.next()) {
            PreparedStatement prepSt = dc.con.prepareStatement(
              "INSERT INTO Activity2 (CompId,Act_id,PeriodId,RegDate,InvDate,Notes,FileInfo) VALUES (?,?,?,?,?,?,?)");
            prepSt.setInt(1,rsOldTrans.getInt(1));
            prepSt.setInt(2, rsOldTrans.getInt(2));
            prepSt.setInt(3, 0);
            prepSt.setDate(4, rsOldTrans.getDate(3));
            prepSt.setDate(5, rsOldTrans.getDate(4));
            prepSt.setString(6, rsOldTrans.getString(5));
            prepSt.setString(7, rsOldTrans.getString(6));
            prepSt.executeUpdate();
            workDialog.SetProgress((rsOldTrans.getRow() * 100) / (numRecs));
          }
          //delete the old Activity table
          st = dc.con.createStatement();
          st.executeUpdate("DROP TABLE Activity");
          SystemLog.ErrorPrintln("Dropped old table Activity");
        } catch (Exception e) {
          e.printStackTrace();
          //we need to continue because otherwise this is a lock stoping proper usage of lazy8ledger forever
          //return;
        }
        workDialog.dispose();
        AdjustAllPeriodIds(0);
      }//}}}

      SetupInfo.setProperty("lazy8ledger.lastRunVersion",
          jEdit.getProperty("plugin.lazy8ledger.Lazy8LedgerPlugin.version"));
      SetupInfo.store();
    }
    if (SetupInfo.getBoolProperty(SetupInfo.IS_INSTALL_ROUTINE_DONE)) {
      setAllTemporaryProperties();
      if(jEdit.getIntegerProperty("lazy8ledger.menu.level", -1)!=-1
        && jEdit.getIntegerProperty("lazy8ledger.menu.level", -1)!=2)
      {
      //set the infoviewer window, But we must wait untill everything has loaded first.
        new Thread() {
          //{{{ +run() : void
          public void run(){
            try{
              sleep(6000);}catch(Exception e){}
            SystemLog.InformationPrintln("lazy8ledger is now showing the logviewer window.");
            org.gjt.sp.jedit.jEdit.getFirstView().getDockableWindowManager().showDockableWindow("infoviewer");
            Lazy8Ledger.ShowContextHelp(null,"welcome","");
            if(isFirstTimeStarting){
              DockableWindowManager mgr = org.gjt.sp.jedit.jEdit.getFirstView().getDockableWindowManager();
              InfoViewer iv = (InfoViewer) mgr.getDockable("infoviewer");
              Dimension d=iv.getParent().getSize();
              iv.getParent().setSize(new Dimension(250,(int)d.getHeight()));
            }
          }//}}}
        }.start();
      }
    } else {
      LoadLanguage("en");
    }
    isInStart=false;
  }//}}}

  //{{{ +_AdjustAllPeriodIds()_ : void
  /**
   *  Description of the Method
   * @param inCompId the company id
   */
  public static void AdjustAllPeriodIds(int inCompId) {
    WorkingDialog workDialog = new WorkingDialog(null);
    workDialog.setVisible(true);
    try {
      DataConnection dc = new DataConnection(null);
      if (dc == null || !dc.bIsConnectionMade) {
        return;
      }
      //get rid of all uniq num posts for period ids
      dc.con.createStatement().executeQuery(dc.filterSQL(
        "DELETE FROM UniqNum WHERE UniqName LIKE 'PeriodId=%'"));
      //adjust the periodid for each activity
      UniqNumGenerator uniqnum = new UniqNumGenerator();
      ResultSet rsPeriods=null;
      String select="SELECT CompId,Act_id,InvDate FROM Activity2 ";
      if (inCompId>0)
        select+=" WHERE CompId=" + inCompId;
      select+=" ORDER BY CompId,Act_id";
      ResultSet rsOldTrans = dc.con.createStatement().executeQuery(dc.filterSQL(select));
      int lastCompId=-1;
      rsOldTrans.last();
      int numRecs=rsOldTrans.getRow();
      rsOldTrans.beforeFirst();
      while (rsOldTrans.next()) {
        if (lastCompId!=rsOldTrans.getInt(1)){
          //get all the periods for the CompId
          lastCompId=rsOldTrans.getInt(1);
          rsPeriods=dc.con.createStatement().executeQuery(dc.filterSQL(
            "SELECT StartPeriod,EndPeriod FROM AccountingPeriods WHERE CompId=" + lastCompId));
        }
        Date invoiceDate=rsOldTrans.getDate(3);
        int periodId=0;
        rsPeriods.beforeFirst();
        //find the appropriate period if it exists.
        while (rsPeriods.next()) {
          if (invoiceDate.compareTo(rsPeriods.getDate(1))>=0 && invoiceDate.compareTo(rsPeriods.getDate(2))<=0){
            //increment period id counter
            periodId=uniqnum.GetUniqueNumber("PeriodId="+ rsPeriods.getDate(1) + "-"
              + rsPeriods.getDate(2), 1, 999999999,new Integer(lastCompId));
            break; //we found the period we need
          }
        }
        dc.con.createStatement().executeQuery(dc.filterSQL(
          "UPDATE Activity2 SET PeriodId=" + periodId + " WHERE CompId=" + lastCompId + " AND Act_id=" + rsOldTrans.getInt(2)));
        workDialog.SetProgress((rsOldTrans.getRow() * 100) / (numRecs));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    workDialog.dispose();
  }//}}}

  //{{{ +stop() : void
    /**
   *  Description of the Method
   */
  public void stop() {
    if (SetupInfo.getBoolProperty(SetupInfo.WARN_TO_DO_BACKUP)
         && DataConnection.isDatabaseChanged) {
      if (JOptionPane.CANCEL_OPTION != JOptionPane.showConfirmDialog(
          null,
          Translator.getTranslation("You have changed your database, do you want to make a backup copy?"),
          Translator.getTranslation("Lazy 8 ledger"),
          JOptionPane.OK_CANCEL_OPTION,
          JOptionPane.QUESTION_MESSAGE)) {
        createBackupFrame(null);
      }
    }
    //save overridden temporary properties.
    saveAllTemporaryProperties();
  }//}}}

}
TOP

Related Classes of lazy8ledger.Lazy8LedgerPlugin

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.