OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 24 → Rev 25

/trunk/OpenConcerto/Configuration/Template/Default/VenteFacture.xml
95,8 → 95,8
<element location="B63" type="fill">
<field base="Societe" table="SAISIE_VENTE_FACTURE" name="ID_MODE_REGLEMENT">
 
<field base="Societe" table="MODE_REGLEMENT" name="NOM" prefix="Règlement souhaité" conditionField="COMPTANT" conditionExpValue="false" display="false"/>
<field base="Societe" table="MODE_REGLEMENT" name="NOM" prefix="Facture acquitée par" conditionField="COMPTANT" conditionExpValue="true" display="false"/>
<field base="Societe" table="MODE_REGLEMENT" name="NOM" prefix="Règlement souhaité" conditionField="COMPTANT" conditionExpValue="true" display="false"/>
<field base="Societe" table="MODE_REGLEMENT" name="NOM" prefix="Facture acquitée par" conditionField="COMPTANT" conditionExpValue="false" display="false"/>
 
<field base="Societe" table="MODE_REGLEMENT" name="ID_TYPE_REGLEMENT">
<field base="Societe" table="TYPE_REGLEMENT" name="NOM" valuesExpected="Indéfini"/>
112,6 → 112,10
 
<element location="B64" type="fill">
<field base="Societe" table="SAISIE_VENTE_FACTURE" name="DATE" type="DateEcheance" prefix="Règlement de cette facture au plus tard le " valuesExpected=" "/>
</element>
 
<element location="B64" type="fill">
<field base="Societe" table="SAISIE_VENTE_FACTURE" name="ID_MODE_REGLEMENT">
 
<field base="Societe" table="MODE_REGLEMENT" name="NOM" prefix="Règlement à date de réception de facture" conditionField="COMPTANT" conditionExpValue="false" display="false"/>
118,11 → 122,7
</field>
</element>
 
<element location="B64" type="fill">
<field base="Societe" table="SAISIE_VENTE_FACTURE" name="DATE" type="DateEcheance" prefix="Règlement de cette facture au plus tard le " valuesExpected=" "/>
</element>
 
<table endPageLine="65" firstLine="63" endLine="65" lastColumn="I" base="Societe" table="TVA">
<element location="I" name="NOM" prefix="Total ">
</element>
/trunk/OpenConcerto/src/org/openconcerto/erp/config/InstallationPanel.java
228,6 → 228,7
@Override
public Object create() throws SQLException {
fixUnboundedVarchar(root);
fixUnboundedNumeric(root);
updateSocieteSchema(root);
updateToV1Dot2(root);
return null;
424,10 → 425,48
 
// c.gridy++;
// this.add(bd, c);
 
c.gridy++;
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
c.insets = new Insets(10, 3, 2, 2);
this.add(new JLabelBold("Paramètrages de la base de données"), c);
c.gridy++;
c.weightx = 0;
c.anchor = GridBagConstraints.EAST;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.insets = DefaultGridBagConstraints.getDefaultInsets();
JButton buttonPL = new JButton("Lancer");
buttonPL.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (!finderPanel.getServerConfig().getType().equals(ServerFinderConfig.POSTGRESQL)) {
 
} else {
final ComptaPropsConfiguration conf = ComptaPropsConfiguration.create(true);
try {
final SQLDataSource ds = conf.getSystemRoot().getDataSource();
ds.execute("CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler AS '$libdir/plpgsql' LANGUAGE C;" + "\n"
+ "CREATE FUNCTION plpgsql_validator(oid) RETURNS void AS '$libdir/plpgsql' LANGUAGE C;" + "\n"
+ "CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql HANDLER plpgsql_call_handler VALIDATOR plpgsql_validator;");
} catch (Exception ex) {
System.err.println("Impossible d'ajouter le langage PLPGSQL. Peut etre est il déjà installé.");
}
}
JOptionPane.showConfirmDialog(null, "Paramètrage terminé.");
}
});
this.add(buttonPL, c);
 
c.gridy++;
c.gridx = 0;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.WEST;
c.gridwidth = GridBagConstraints.REMAINDER;
c.insets = new Insets(10, 3, 2, 2);
this.add(new JLabelBold("Mise à niveau de la base OpenConcerto"), c);
c.gridy++;
this.add(this.bar, c);
451,6 → 490,64
this.add(comp, c);
}
 
private void fixUnboundedNumeric(DBRoot root) throws SQLException {
 
final List<AlterTable> alters = new ArrayList<AlterTable>();
{
SQLTable tableAvoir = root.getTable("AVOIR_CLIENT_ELEMENT");
final AlterTable alter = new AlterTable(tableAvoir);
SQLField fieldAcompteAvoir = tableAvoir.getField("POURCENT_ACOMPTE");
if (fieldAcompteAvoir.getType().getSize() > 500) {
final String fName = fieldAcompteAvoir.getName();
alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "100", false);
}
 
SQLField fieldRemiseAvoir = tableAvoir.getField("POURCENT_REMISE");
if (fieldRemiseAvoir.getType().getSize() > 500) {
final String fName = fieldRemiseAvoir.getName();
alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
}
 
if (!alter.isEmpty())
alters.add(alter);
}
 
{
SQLTable tableFacture = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
final AlterTable alter = new AlterTable(tableFacture);
SQLField fieldAcompteFacture = tableFacture.getField("POURCENT_ACOMPTE");
if (fieldAcompteFacture.getType().getSize() > 500) {
final String fName = fieldAcompteFacture.getName();
alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "100", false);
}
 
SQLField fieldRemiseFacture = tableFacture.getField("POURCENT_REMISE");
if (fieldRemiseFacture.getType().getSize() > 500) {
final String fName = fieldRemiseFacture.getName();
alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
}
 
if (tableFacture.getFieldsName().contains("REPARTITION_POURCENT")) {
SQLField fieldRepFacture = tableFacture.getField("REPARTITION_POURCENT");
if (fieldRepFacture.getType().getSize() > 500) {
final String fName = fieldRepFacture.getName();
alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
}
}
 
if (!alter.isEmpty())
alters.add(alter);
 
}
if (alters.size() > 0) {
final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
for (final String sql : ChangeTable.cat(alters, root.getName())) {
ds.execute(sql);
}
root.refetch();
}
}
 
private void fixUnboundedVarchar(DBRoot root) throws SQLException {
final Set<String> namesSet = CollectionUtils.createSet("NOM", "PRENOM", "SURNOM", "LOGIN", "PASSWORD");
final List<AlterTable> alters = new ArrayList<AlterTable>();
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerFinderConfig.java
31,6 → 31,7
private String ip;
private File file;
private String port;
private String systemRoot = "OpenConcerto";
 
private String dbLogin;
private String dbPassword;
40,6 → 41,14
private String product;
private String error;
 
public String getSystemRoot() {
return systemRoot;
}
 
public void setSystemRoot(String systemRoot) {
this.systemRoot = systemRoot;
}
 
public String getType() {
return type;
}
245,4 → 254,5
return this.getType() + ":" + this.getIp() + ":" + this.getPort() + " file:" + this.getFile() + " " + this.getOpenconcertoLogin() + "/" + this.getOpenconcertoPassword() + " ["
+ this.getDbLogin() + "/" + this.getDbPassword() + "]";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ComptaPropsConfiguration.java
100,6 → 100,7
import org.openconcerto.erp.core.sales.invoice.element.EcheanceClientSQLElement;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
import org.openconcerto.erp.core.sales.order.element.CommandeClientElementSQLElement;
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.erp.core.sales.pos.element.CaisseTicketSQLElement;
148,10 → 149,12
import org.openconcerto.erp.injector.FactureBonSQLInjector;
import org.openconcerto.erp.injector.FactureCommandeSQLInjector;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.erp.rights.ComptaTotalUserRight;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.ShowAs;
import org.openconcerto.sql.element.ElementMapper;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.SharedSQLElement;
import org.openconcerto.sql.model.DBRoot;
341,7 → 344,7
@Override
protected String getAppIDSuffix() {
if (inWebstart())
// so we don't remove files of a normal OpenConcerto
// so we don't remove files of a normal GestionNX
return super.getAppIDSuffix() + "-webstart";
else
return super.getAppIDSuffix();
403,7 → 406,6
 
@Override
protected ShowAs createShowAs() {
System.out.println("ComptaPropsConfiguration.createShowAszzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz()");
final ShowAs showAs = super.createShowAs();
 
showAs.show("ADRESSE_COMMON", SQLRow.toList("RUE,VILLE"));
731,6 → 733,7
}
setSocieteShowAs();
setSocieteSQLInjector();
setMapper();
String sfe = DefaultNXProps.getInstance().getStringProperty("ArticleSFE");
Boolean bSfe = Boolean.valueOf(sfe);
boolean isSFE = bSfe != null && bSfe.booleanValue();
740,7 → 743,7
trans.load(rootSociete, inSFE);
}
}
 
TemplateNXProps.getInstance();
// Chargement du graphe
new Thread() {
public void run() {
750,6 → 753,21
}.start();
}
 
private void setMapper() {
ElementMapper mapper = ElementMapper.getInstance();
mapper.map("customerrelationship.name", "Relation client");
mapper.map("customerrelationship.customer.list.table", "CLIENT");
mapper.map("customerrelationship.contact.list.table", "CONTACT");
mapper.map("accounting.name", "Comptabilité");
mapper.map("sales.name", "Gestion commerciale");
mapper.map("sales.invoice.name", "Factures client");
mapper.map("sales.invoice.list.table", "SAISIE_VENTE_FACTURE");
mapper.map("sales.quote.name", "Devis client");
mapper.map("sales.quote.list.table", "DEVIS");
mapper.map("sales.invoice.list.table.editor", SaisieVenteFactureItemTable.class);
mapper.dump();
}
 
private void closeSocieteConnexion() {
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/MainFrame.java
59,6 → 59,8
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesCommerciauxAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSalariesAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSecretairesAction;
import org.openconcerto.erp.core.humanresources.employe.action.N4DSAction;
import org.openconcerto.erp.core.humanresources.employe.report.N4DS;
import org.openconcerto.erp.core.humanresources.payroll.action.ClotureMensuellePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.EditionFichePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesProfilsPayeAction;
456,6 → 458,7
menu.add(new JSeparator());
menu.add(new EtatChargeAction());
menu.add(new CompteResultatBilanAction());
menu.add(new N4DSAction());
if (rights.haveRight(ComptaUserRight.MENU)) {
result.add(menu);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/Gestion.java
37,7 → 37,6
import org.openconcerto.ui.component.WaitIndeterminatePanel;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.protocol.Helper;
 
import java.awt.AWTEvent;
71,6 → 70,8
 
public class Gestion {
 
public static final File MODULES_DIR = new File("Modules");
 
/**
* When this system property is set to <code>true</code>, Gestion will hide most of its normal
* UI. E.g. no SOCIETE selection in the login panel, minimalist menu bar, etc.
212,17 → 213,7
} catch (Exception e) {
System.out.println("Init phase 1 error:" + (System.currentTimeMillis() - t4) + "ms");
ExceptionHandler.die("Erreur de connexion à la base de données", e);
// since we're not in the EDT, the previous call doesn't block,
// so return (it won't quit the VM since a dialog is displaying)
return;
}
try {
final File moduleDir = new File("Modules");
moduleDir.mkdir();
ModuleManager.getInstance().addFactories(moduleDir);
} catch (Throwable e) {
ExceptionHandler.handle("Erreur d'accès aux modules", e);
}
System.out.println("Init phase 1:" + (System.currentTimeMillis() - t1) + "ms");
SwingUtilities.invokeLater(new Runnable() {
 
283,21 → 274,12
 
// needed so that we can uninstall modules
System.setProperty(SQLBase.ALLOW_OBJECT_REMOVAL, "true");
ModuleManager.getInstance().invoke(new IClosure<ModuleManager>() {
@Override
public void executeChecked(ModuleManager mngr) {
try {
final Exception exn = mngr.setup();
// OK to continue without all modules started
if (exn != null)
ExceptionHandler.handle(MainFrame.getInstance(), "Impossible de démarrer les modules", exn);
} catch (Exception e) {
// not OK to continue without required elements
ExceptionHandler.die("Impossible de démarrer les modules requis", e);
ModuleManager.getInstance().addFactories(MODULES_DIR);
} catch (Throwable e) {
ExceptionHandler.handle("Erreur d'accès aux modules", e);
}
}
});
}
 
/**
* Si la base est 127.0.0.1 ou localhost alors on essaye de lancer postgres.
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerFinderPanel.java
73,6 → 73,7
private JTextField textIP;
private JTextField textPort;
private JTextField textFile;
private JTextField textBase;
Properties props;
private JButton buttonDir;
private JTabbedPane tabbedPane;
146,6 → 147,7
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Impossible de lire le fichier " + this.confFile + " \n" + e.getLocalizedMessage());
}
 
String serverIp = this.props.getProperty("server.ip", "127.0.0.1:5432");
String serverDriver = this.props.getProperty("server.driver", "postgresql").toLowerCase();
if (serverDriver.startsWith("h2")) {
158,7 → 160,7
updateUIForMode(ServerFinderConfig.POSTGRESQL);
this.textPort.setText("5432");
}
 
this.textBase.setText(this.props.getProperty("systemRoot", "OpenConcerto"));
if (serverIp.contains("file:")) {
this.textFile.setText(serverIp.substring(5));
} else {
405,6 → 407,19
c.gridy++;
c.gridx = 0;
c.weightx = 0;
p.add(new JLabel("Base de données", SwingConstants.RIGHT), c);
c.gridx++;
c.weighty = 0;
c.gridwidth = 1;
this.textBase = new JTextField();
this.textBase.setEditable(false);
p.add(this.textBase, c);
 
// L4: file
c.gridy++;
c.gridx = 0;
c.weightx = 0;
c.gridwidth = 1;
p.add(new JLabel("Dossier de base de données", SwingConstants.RIGHT), c);
c.gridx++;
c.weighty = 0;
648,18 → 663,12
return p;
}
 
private JPanel createPanelInstallation() {
final JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
p.setOpaque(false);
return p;
}
 
public ServerFinderConfig getServerConfig() {
final ServerFinderConfig conf = new ServerFinderConfig();
conf.setType(ServerFinderPanel.this.comboMode.getSelectedItem().toString());
conf.setIp(ServerFinderPanel.this.textIP.getText());
conf.setPort(ServerFinderPanel.this.textPort.getText());
conf.setSystemRoot(this.textBase.getText());
return conf;
}
 
690,6 → 699,7
public ServerFinderConfig createServerFinderConfig() {
ServerFinderConfig conf = new ServerFinderConfig();
conf.setType(this.comboMode.getSelectedItem().toString());
conf.setSystemRoot(this.textBase.getText());
if (!conf.getType().equals(ServerFinderConfig.H2)) {
conf.setIp(this.textIP.getText());
conf.setPort(this.textPort.getText());
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleFactory.java
13,6 → 13,8
package org.openconcerto.erp.modules;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.cc.IPredicate;
 
import java.io.IOException;
23,6 → 25,7
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
175,8 → 178,22
return (AbstractModule) c.getConstructor(ModuleFactory.class).newInstance(this);
}
 
public final Preferences getLocalPreferences() {
return this.getPreferences(true, null);
}
 
public final Preferences getSQLPreferences(final DBRoot root) {
return this.getPreferences(false, root);
}
 
public final Preferences getPreferences(final boolean local, final DBRoot root) {
final Preferences rootPrefs = local ? Preferences.userRoot() : new SQLPreferences(root);
// ID is a package name, transform to path to avoid bumping into the size limit
return rootPrefs.node(ModulePreferencePanel.getAppPrefPath() + this.getID().replace('.', '/'));
}
 
@Override
public String toString() {
return super.toString() + " " + getID() + " (" + getMajorVersion() + "." + getMinorVersion() + ")";
return getClass().getSimpleName() + " " + getID() + " (" + getMajorVersion() + "." + getMinorVersion() + ")";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleManager.java
17,9 → 17,11
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBFileCache;
import org.openconcerto.sql.model.DBItemFileCache;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRow;
27,6 → 29,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSyntax;
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.DirectedEdge;
37,13 → 40,14
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.cc.IdentityHashSet;
import org.openconcerto.utils.cc.IdentitySet;
 
import java.io.File;
import java.io.FileFilter;
60,10 → 64,9
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
 
import javax.swing.JMenuItem;
83,7 → 86,6
private static final Logger L = Logger.getLogger(ModuleManager.class.getPackage().getName());
 
private static final int MIN_VERSION = 0;
private static final int NO_VERSION = MIN_VERSION - 1;
private static final String MODULE_COLNAME = "MODULE_NAME";
private static final String MODULE_VERSION_COLNAME = "MODULE_VERSION";
private static final String TABLE_COLNAME = "TABLE";
105,6 → 107,9
private final Map<String, ComponentsContext> modulesComponents;
private final DirectedGraph<ModuleFactory, DirectedEdge<ModuleFactory>> dependencyGraph;
 
private DBRoot root;
private Configuration conf;
 
public ModuleManager() {
this.factories = new HashMap<String, ModuleFactory>();
this.runningModules = new HashMap<String, AbstractModule>();
116,6 → 121,9
});
this.modulesElements = new HashMap<String, Collection<SQLElement>>();
this.modulesComponents = new HashMap<String, ComponentsContext>();
 
this.root = null;
this.conf = null;
}
 
// *** factories (thread-safe)
122,7 → 130,7
 
public final int addFactories(final File dir) {
if (!dir.exists()) {
System.err.println("Warning: module factory directory not found: " + dir.getAbsolutePath());
L.warning("Module factory directory not found: " + dir.getAbsolutePath());
return 0;
}
final File[] jars = dir.listFiles(new FileFilter() {
138,7 → 146,7
this.addFactory(new JarModuleFactory(jar));
i++;
} catch (Exception e) {
System.err.println("Couldn't add " + jar);
L.warning("Couldn't add " + jar);
e.printStackTrace();
}
}
168,7 → 176,9
 
private final String addFactory(final ModuleFactory f, final boolean start, final boolean persistent) {
synchronized (this.factories) {
this.factories.put(f.getID(), f);
final ModuleFactory prev = this.factories.put(f.getID(), f);
if (prev != null)
L.info("Changing the factory for " + f.getID() + "\nfrom\t" + prev + "\nto\t" + f);
}
if (start)
this.invoke(new IClosure<ModuleManager>() {
185,11 → 195,16
}
 
public final Map<String, ModuleFactory> getFactories() {
return Collections.unmodifiableMap(this.factories);
synchronized (this.factories) {
return new HashMap<String, ModuleFactory>(this.factories);
}
}
 
private ModuleFactory getFactory(final String id) {
final ModuleFactory res = this.factories.get(id);
final ModuleFactory res;
synchronized (this.factories) {
res = this.factories.get(id);
}
if (res == null)
throw new IllegalArgumentException("No factory for " + id);
return res;
235,8 → 250,10
// *** modules (in EDT)
 
/**
* Call the passed closure at a time when modules can be started. In particular the
* {@link MainFrame#getInstance() main frame} has been created.
* Call the passed closure at a time when modules can be started. In particular this manager has
* been set up and the {@link MainFrame#getInstance() main frame} has been created.
*
* @param c the closure to execute.
*/
public void invoke(final IClosure<ModuleManager> c) {
MainFrame.invoke(new Runnable() {
251,14 → 268,14
// (e.g. if a module created a child table, as long as the table is in the database it needs to
// be archived along its parent)
private void registerRequiredModules() throws Exception {
assert SwingUtilities.isEventDispatchThread();
final List<String> modulesToStart = new ArrayList<String>();
try {
final Map<String, ModuleFactory> factories = this.getFactories();
for (final Entry<String, ModuleVersion> e : this.getDBInstalledModules().entrySet()) {
final String moduleID = e.getKey();
// modules that just add non-key fields are not required
if (this.areElementsNeeded(moduleID)) {
final ModuleFactory moduleFactory = this.getFactories().get(moduleID);
final ModuleFactory moduleFactory = factories.get(moduleID);
final String error;
if (moduleFactory == null)
error = "Module '" + moduleID + "' non disponible.";
269,8 → 286,7
error = null;
if (error != null) {
// TODO open GUI to resolve the issue
ExceptionHandler.handle(error);
return;
throw new Exception(error);
} else {
modulesToStart.add(moduleID);
}
277,30 → 293,40
}
}
} catch (Exception e) {
ExceptionHandler.die("Impossible de déterminer les modules requis", e);
return;
throw new Exception("Impossible de déterminer les modules requis", e);
}
final Tuple2<Map<String, AbstractModule>, Set<String>> modules = this.createModules(modulesToStart, false);
final Tuple2<Map<String, AbstractModule>, Set<String>> modules = this.createModules(modulesToStart, false, true);
if (modules.get1().size() > 0)
ExceptionHandler.die("Impossible de créer les modules " + modules.get1());
throw new Exception("Impossible de créer les modules " + modules.get1());
for (final AbstractModule m : modules.get0().values())
this.registerSQLElements(m);
}
 
/**
* Initialize the module manager.
* Initialise the module manager.
*
* @return the exception, if any, thrown when starting previously running modules.
* @param root the root where the modules install.
* @param conf the configuration the modules change.
* @throws Exception if required modules couldn't be registered.
*/
public final Exception setup() throws Exception {
public synchronized final void setup(final DBRoot root, final Configuration conf) throws Exception {
if (root == null || conf == null)
throw new NullPointerException();
if (this.root != null || getConf() != null)
throw new IllegalStateException("Already setup");
// modulesElements can be non empty, if a previous setup() failed
assert this.runningModules.isEmpty() && this.modulesComponents.isEmpty() : "Modules cannot start without root & conf";
this.root = root;
this.conf = conf;
try {
this.registerRequiredModules();
try {
this.startPreviouslyRunningModules();
return null;
} catch (Exception e) {
return e;
// allow setup() to be called again
this.root = null;
this.conf = null;
throw e;
}
assert this.runningModules.isEmpty() && this.modulesComponents.isEmpty() : "registerRequiredModules() should not start modules";
}
 
private Preferences getPrefs() {
307,7 → 333,7
// modules are installed per business entity (perhaps we could add a per user option, i.e.
// for all businesses of all databases)
final StringBuilder path = new StringBuilder(32);
for (final String item : DBFileCache.getJDBCAncestorNames(Configuration.getInstance().getRoot(), true)) {
for (final String item : DBFileCache.getJDBCAncestorNames(getRoot(), true)) {
path.append(StringUtils.getBoundedLengthString(DBItemFileCache.encode(item), Preferences.MAX_NAME_LENGTH));
path.append('/');
}
320,49 → 346,56
return getPrefs().node("toRun");
}
 
private Preferences getInstalledPrefs() {
return getPrefs().node("installed");
}
 
protected final boolean isModuleInstalledLocally(String id) {
return getInstalledPrefs().getLong(id, NO_VERSION) != NO_VERSION;
return getLocalVersionFile(id).exists();
}
 
protected final ModuleVersion getModuleVersionInstalledLocally(String id) {
final long v = getInstalledPrefs().getLong(id, NO_VERSION);
return v == NO_VERSION ? null : new ModuleVersion(v);
final File versionFile = getLocalVersionFile(id);
if (versionFile.exists()) {
try {
return new ModuleVersion(Long.valueOf(FileUtils.read(versionFile)));
} catch (IOException e) {
throw new IllegalStateException("Couldn't get installed version of " + id, e);
}
} else {
return null;
}
}
 
public final Collection<String> getModulesInstalledLocally() {
try {
return Arrays.asList(getInstalledPrefs().keys());
} catch (BackingStoreException e) {
throw new IllegalStateException("Couldn't fetch installed preferences", e);
return getModulesVersionInstalledLocally().keySet();
}
}
 
public final Map<String, ModuleVersion> getModulesVersionInstalledLocally() {
final Preferences prefs = getInstalledPrefs();
final Map<String, ModuleVersion> res = new HashMap<String, ModuleVersion>();
try {
for (final String key : prefs.keys())
res.put(key, new ModuleVersion(prefs.getLong(key, NO_VERSION)));
} catch (BackingStoreException e) {
throw new IllegalStateException("Couldn't fetch installed preferences", e);
final File dir = getLocalDirectory();
for (final File d : dir.listFiles()) {
final String id = d.getName();
final ModuleVersion version = getModuleVersionInstalledLocally(id);
if (version != null)
res.put(id, version);
}
return res;
}
 
private void setModuleInstalledLocally(ModuleFactory f, boolean b) {
try {
if (b) {
final ModuleVersion vers = f.getVersion();
if (vers.getMerged() < MIN_VERSION)
throw new IllegalStateException("Invalid version : " + vers);
getInstalledPrefs().putLong(f.getID(), vers.getMerged());
final File versionFile = getLocalVersionFile(f.getID());
FileUtils.mkdir_p(versionFile.getParentFile());
FileUtils.write(String.valueOf(vers.getMerged()), versionFile);
} else {
getInstalledPrefs().remove(f.getID());
// perhaps add a parameter to only remove the versionFile
FileUtils.rm_R(getLocalDirectory(f.getID()));
}
} catch (IOException e) {
throw new IllegalStateException("Couldn't change installed status of " + f, e);
}
}
 
private SQLTable getInstalledTable(final DBRoot r) throws SQLException {
if (!r.contains(FWK_MODULE_TABLENAME)) {
381,7 → 414,7
 
createTable.addUniqueConstraint("uniqModule", Arrays.asList(MODULE_COLNAME, TABLE_COLNAME, FIELD_COLNAME));
 
SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLFactory<Object>() {
SQLUtils.executeAtomic(getDS(), new SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
r.getDBSystemRoot().getDataSource().execute(createTable.asString());
395,10 → 428,34
return r.getTable(FWK_MODULE_TABLENAME);
}
 
private DBRoot getRoot() {
return ((ComptaBasePropsConfiguration) Configuration.getInstance()).getRootSociete();
protected final DBRoot getRoot() {
return this.root;
}
 
private SQLDataSource getDS() {
return getRoot().getDBSystemRoot().getDataSource();
}
 
protected final Configuration getConf() {
return this.conf;
}
 
private SQLElementDirectory getDirectory() {
return getConf().getDirectory();
}
 
private final File getLocalDirectory() {
return new File(this.getConf().getConfDir(getRoot()), "modules");
}
 
protected final File getLocalDirectory(final String id) {
return new File(this.getLocalDirectory(), id);
}
 
private final File getLocalVersionFile(final String id) {
return new File(this.getLocalDirectory(id), "version");
}
 
public final ModuleVersion getDBInstalledModuleVersion(final String id) throws SQLException {
return getDBInstalledModules(id).get(id);
}
531,40 → 588,91
return (Boolean) installedTable.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
}
 
private void install(final AbstractModule module) throws SQLException {
private void install(final AbstractModule module) throws Exception {
final ModuleFactory factory = module.getFactory();
if (!isModuleInstalledLocally(factory.getID())) {
final ModuleVersion localVersion = getModuleVersionInstalledLocally(factory.getID());
final ModuleVersion lastInstalledVersion = getDBInstalledModuleVersion(factory.getID());
if (lastInstalledVersion != null && module.getFactory().getVersion().compareTo(lastInstalledVersion) < 0)
throw new IllegalArgumentException("Module older than the one installed in the DB : " + module.getFactory().getVersion() + " < " + lastInstalledVersion);
SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLFactory<Object>() {
final ModuleVersion moduleVersion = module.getFactory().getVersion();
if (lastInstalledVersion != null && moduleVersion.compareTo(lastInstalledVersion) < 0)
throw new IllegalArgumentException("Module older than the one installed in the DB : " + moduleVersion + " < " + lastInstalledVersion);
if (localVersion != null && moduleVersion.compareTo(localVersion) < 0)
throw new IllegalArgumentException("Module older than the one installed locally : " + moduleVersion + " < " + localVersion);
if (!moduleVersion.equals(localVersion) || !moduleVersion.equals(lastInstalledVersion)) {
// local
final File localDir = getLocalDirectory(factory.getID());
// There are 2 choices to handle the update of files :
// 1. copy dir to a new one and pass it to DBContext, then either rename it to dir or
// rename it failed
// 2. copy dir to a backup, pass dir to DBContext, then either remove backup or rename
// it to dir
// Choice 2 is simpler since the module deals with the same directory in both install()
// and start()
final File backupDir;
// check if we need a backup
if (localDir.exists()) {
backupDir = FileUtils.addSuffix(localDir, ".backup");
FileUtils.rm_R(backupDir);
FileUtils.copyDirectory(localDir, backupDir);
} else {
backupDir = null;
FileUtils.mkdir_p(localDir);
}
assert localDir.exists();
try {
SQLUtils.executeAtomic(getDS(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object create() throws SQLException {
public Object handle(SQLDataSource ds) throws SQLException, IOException {
final Tuple2<Set<String>, Set<SQLName>> alreadyCreatedItems = getCreatedItems(factory.getID());
final DBContext ctxt = new DBContext(lastInstalledVersion, getRoot(), alreadyCreatedItems.get0(), alreadyCreatedItems.get1());
final DBContext ctxt = new DBContext(localDir, localVersion, getRoot(), lastInstalledVersion, alreadyCreatedItems.get0(), alreadyCreatedItems.get1());
// install local
module.install(ctxt);
 
// install local
setModuleInstalledLocally(factory, true);
if (!localDir.exists())
throw new IOException("Modules shouldn't remove their directory");
// install in DB
ctxt.execute();
updateModuleFields(factory, ctxt);
 
return null;
}
});
} catch (Exception e) {
// install did not complete successfully
if (getRoot().getServer().getSQLSystem() == SQLSystem.MYSQL)
L.warning("MySQL cannot rollback DDL statements");
// keep failed install files and restore previous files
final File failed = FileUtils.addSuffix(localDir, ".failed");
if (failed.exists() && !FileUtils.rmR(failed))
L.warning("Couldn't remove " + failed);
if (!localDir.renameTo(failed)) {
L.warning("Couldn't move " + localDir + " to " + failed);
} else {
assert !localDir.exists();
// restore if needed
if (backupDir != null && !backupDir.renameTo(localDir))
L.warning("Couldn't restore " + backupDir + " to " + localDir);
}
throw e;
}
// DB transaction was committed, remove backup files
assert localDir.exists();
if (backupDir != null)
FileUtils.rm_R(backupDir);
setModuleInstalledLocally(factory, true);
}
assert moduleVersion.equals(getModuleVersionInstalledLocally(factory.getID())) && moduleVersion.equals(getDBInstalledModuleVersion(factory.getID()));
}
 
private void registerSQLElements(final AbstractModule module) {
final String id = module.getFactory().getID();
synchronized (this.modulesElements) {
if (!this.modulesElements.containsKey(id)) {
final SQLElementDirectory dir = Configuration.getInstance().getDirectory();
final SQLElementDirectory dir = getDirectory();
final Map<SQLTable, SQLElement> beforeElements = new HashMap<SQLTable, SQLElement>(dir.getElementsMap());
module.setupElements(dir);
final Collection<SQLElement> elements = new ArrayList<SQLElement>();
final Collection<SQLElement> newElements = CollectionUtils.substract(new IdentityHashSet<SQLElement>(dir.getElements()), new IdentityHashSet<SQLElement>(beforeElements.values()));
for (final SQLElement elem : newElements) {
// use IdentitySet so as not to call equals() since it triggers initFF()
final IdentitySet<SQLElement> beforeElementsSet = new IdentityHashSet<SQLElement>(beforeElements.values());
for (final SQLElement elem : dir.getElements()) {
if (!beforeElementsSet.contains(elem)) {
// don't let elements be replaced (it's tricky to restore in unregister())
if (beforeElements.containsKey(elem.getTable())) {
L.warning("Trying to replace element for " + elem.getTable() + " with " + elem);
573,14 → 681,16
elements.add(elem);
}
}
}
this.modulesElements.put(id, elements);
}
}
}
 
private void setupComponents(final AbstractModule module) throws SQLException {
final String id = module.getFactory().getID();
if (!this.modulesComponents.containsKey(id)) {
final SQLElementDirectory dir = Configuration.getInstance().getDirectory();
final SQLElementDirectory dir = getDirectory();
final Tuple2<Set<String>, Set<SQLName>> alreadyCreatedItems = getCreatedItems(id);
final ComponentsContext ctxt = new ComponentsContext(dir, getRoot(), alreadyCreatedItems.get0(), alreadyCreatedItems.get1());
module.setupComponents(ctxt);
588,7 → 698,7
}
}
 
protected final void startPreviouslyRunningModules() throws Exception {
public final void startPreviouslyRunningModules() throws Exception {
final List<String> ids = Arrays.asList(getRunningIDsPrefs().keys());
startModules(ids);
}
615,15 → 725,16
}
 
private final Set<String> startModules(final Collection<String> ids) throws Exception {
return this.createModules(ids, true).get1();
return this.createModules(ids, true, false).get1();
}
 
// modules created, and the ones that couldn't
// i.e. if a module was already created it's in neither
private final Tuple2<Map<String, AbstractModule>, Set<String>> createModules(final Collection<String> ids, final boolean start) throws Exception {
assert SwingUtilities.isEventDispatchThread();
private final Tuple2<Map<String, AbstractModule>, Set<String>> createModules(final Collection<String> ids, final boolean start, final boolean inSetup) throws Exception {
// in setup we're not in the EDT, but it's OK since by definition no modules are started
assert SwingUtilities.isEventDispatchThread() || inSetup && this.runningModules.isEmpty();
// add currently running modules so that ModuleFactory can use them
final Map<String, AbstractModule> modules = new LinkedHashMap<String, AbstractModule>(this.runningModules);
final Map<String, AbstractModule> modules = inSetup ? new LinkedHashMap<String, AbstractModule>(ids.size() * 2) : new LinkedHashMap<String, AbstractModule>(this.runningModules);
final Set<String> cannotCreate = new HashSet<String>();
final LinkedHashMap<ModuleFactory, Boolean> map = new LinkedHashMap<ModuleFactory, Boolean>();
synchronized (this.factories) {
640,6 → 751,7
}
}
// only keep modules created by this method
if (!inSetup)
modules.keySet().removeAll(this.runningModules.keySet());
 
if (start) {
667,7 → 779,7
final InputStream labels = module.getClass().getResourceAsStream("labels.xml");
if (labels != null) {
try {
Configuration.getInstance().getTranslator().load(getRoot(), labels);
getConf().getTranslator().load(getRoot(), labels);
} finally {
labels.close();
}
735,13 → 847,15
 
private void unregisterSQLElements(final AbstractModule module) {
final String id = module.getFactory().getID();
synchronized (this.modulesElements) {
if (this.modulesElements.containsKey(id)) {
final Collection<SQLElement> elements = this.modulesElements.remove(id);
final SQLElementDirectory dir = Configuration.getInstance().getDirectory();
final SQLElementDirectory dir = getDirectory();
for (final SQLElement elem : elements)
dir.removeSQLElement(elem);
}
}
}
 
private void tearDownComponents(final AbstractModule module) {
final String id = module.getFactory().getID();
893,22 → 1007,22
 
final AbstractModule module;
if (!this.isModuleRunning(id)) {
module = this.createModules(Collections.singleton(id), false).get0().get(id);
module = this.createModules(Collections.singleton(id), false, false).get0().get(id);
} else {
module = this.runningModules.get(id);
this.stopModule(id, true);
}
 
SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLFactory<Object>() {
SQLUtils.executeAtomic(getDS(), new SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
module.uninstall();
final DBRoot root = getRoot();
module.uninstall(root);
unregisterSQLElements(module);
setModuleInstalledLocally(module.getFactory(), false);
 
// uninstall from DB
final Tuple2<Set<String>, Set<SQLName>> createdItems = getCreatedItems(id);
final DBRoot root = getRoot();
final List<ChangeTable<?>> l = new ArrayList<ChangeTable<?>>();
final Set<String> tableNames = createdItems.get0();
for (final SQLName field : createdItems.get1()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AvailableModulesPanel.java
13,19 → 13,25
package org.openconcerto.erp.modules;
 
import org.openconcerto.sql.view.AbstractFileTransfertHandler;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
 
public class AvailableModulesPanel extends JPanel {
private final AvailableModuleTableModel tm;
91,8 → 97,47
c.weighty = 1;
c.gridy++;
this.add(space, c);
this.setTransferHandler(new AbstractFileTransfertHandler() {
 
@Override
public void handleFile(File f) {
if (!f.getName().endsWith(".jar")) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'installer le module. Le fichier n'est pas un module.");
return;
}
File dir = new File("Modules");
dir.mkdir();
File out = null;
if (dir.canWrite()) {
try {
out = new File(dir, f.getName());
FileUtils.copyFile(f, out);
} catch (IOException e) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'installer le module.\n" + f.getAbsolutePath() + " vers " + dir.getAbsolutePath());
return;
}
} else {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'installer le module.\nVous devez disposer des droits en écriture sur le dossier:\n" + dir.getAbsolutePath());
return;
}
try {
ModuleManager.getInstance().addFactory(new JarModuleFactory(out));
} catch (IOException e) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'intégrer le module.\n" + e.getMessage());
return;
}
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
reload();
}
});
 
}
});
}
 
public void reload() {
this.tm.reload();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ComponentsContext.java
85,8 → 85,12
}
 
public final SQLElement getElement(final String tableName) {
return this.dir.getElement(this.getRoot().getTable(tableName));
final SQLElement element = this.dir.getElement(this.getRoot().getTable(tableName));
if (element == null) {
throw new IllegalArgumentException("Not element found for table " + tableName);
}
return element;
}
 
public final void putAdditionalField(final String tableName, final String name) {
final SQLElement elem = checkField(tableName, name);
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/DBContext.java
22,7 → 22,9
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.sql.utils.SQLCreateTableBase;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.cc.IClosure;
 
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
39,17 → 41,23
*/
public final class DBContext {
 
private final File dir;
private final ModuleVersion localVersion;
private final ModuleVersion lastInstalledVersion;
private final DBRoot root;
private final List<ChangeTable<?>> changeTables;
private final List<AlterTableRestricted> alterTables;
// Data Manipulation
private final List<IClosure<? super DBRoot>> dm;
 
private final Set<String> tables;
private final CollectionMap<String, SQLField> fields;
 
DBContext(ModuleVersion lastInstalledVersion, DBRoot root, final Set<String> tables, final Set<SQLName> fields) {
DBContext(final File dir, final ModuleVersion localVersion, final DBRoot root, final ModuleVersion dbVersion, final Set<String> tables, final Set<SQLName> fields) {
super();
this.lastInstalledVersion = lastInstalledVersion;
this.dir = dir;
this.localVersion = localVersion;
this.lastInstalledVersion = dbVersion;
this.root = root;
this.tables = Collections.unmodifiableSet(tables);
this.fields = new CollectionMap<String, SQLField>(new HashSet<SQLField>());
59,8 → 67,17
}
this.changeTables = new ArrayList<ChangeTable<?>>();
this.alterTables = new ArrayList<AlterTableRestricted>();
this.dm = new ArrayList<IClosure<? super DBRoot>>();
}
 
public final File getLocalDirectory() {
return this.dir;
}
 
public final ModuleVersion getLocalVersion() {
return this.localVersion;
}
 
public final ModuleVersion getLastInstalledVersion() {
return this.lastInstalledVersion;
}
95,7 → 112,10
SQLTable.setUndefID(getRoot().getSchema(), addedTable, null);
getRoot().refetch();
}
for (final IClosure<? super DBRoot> closure : this.dm) {
closure.executeChecked(getRoot());
}
}
 
// DDL
 
120,6 → 140,36
this.changeTables.add(new DropTable(this.root.getTable(name)));
}
 
// DML
 
/**
* The closure will be executed after the DDL statements. Note: you generally need to undo in
* {@link AbstractModule#uninstall()} what <code>closure</code> does (exceptions include
* inserting rows in a created table, since it will be automatically dropped).
*
* @param closure what to do.
*/
public final void manipulateData(final IClosure<? super DBRoot> closure) {
this.dm.add(closure);
}
 
/**
* The closure will be executed after the DDL statements. E.g. if you called
* {@link #getCreateTable(String)} this allows you to insert rows.
*
* @param name a table name.
* @param closure what to do.
* @see #manipulateData(IClosure)
*/
public final void manipulateTable(final String name, final IClosure<SQLTable> closure) {
this.manipulateData(new IClosure<DBRoot>() {
@Override
public void executeChecked(DBRoot input) {
closure.executeChecked(input.getTable(name));
}
});
}
 
// getter
 
final List<String> getAddedTables() {
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModulePreferencePanel.java
15,7 → 15,6
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.SQLSearchableTextCombo;
import org.openconcerto.sql.sqlobject.SQLSearchableTextCombo.ISQLListModel;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
27,7 → 26,6
import org.openconcerto.utils.PrefType;
 
import java.util.Date;
import java.util.prefs.Preferences;
 
import javax.swing.JCheckBox;
import javax.swing.JComponent;
34,11 → 32,11
 
public abstract class ModulePreferencePanel extends JavaPrefPreferencePanel {
 
static private DBRoot getRoot() {
static public DBRoot getRoot() {
return Configuration.getInstance().getRoot();
}
 
static private String getAppPrefPath() {
static String getAppPrefPath() {
return Configuration.getInstance().getAppID() + '/';
}
 
89,8 → 87,6
}
 
public final void init(final ModuleFactory module, final boolean local) {
final Preferences rootPrefs = local ? Preferences.userRoot() : new SQLPreferences(getRoot());
// ID is a package name, transform to path to avoid bumping into the size limit
this.setPrefs(rootPrefs.node(getAppPrefPath() + module.getID().replace('.', '/')));
this.setPrefs(module.getPreferences(local, getRoot()));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleLauncher.java
New file
0,0 → 1,71
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.modules;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.utils.FileUtils;
 
import java.io.File;
import java.io.IOException;
 
/**
* Package a module from a project and launch it. The system property {@link #MODULE_DIR_PROP} must
* be defined.
*
* @author Sylvain CUAZ
* @see ModulePackager
*/
public class ModuleLauncher {
/**
* Required system property, it must point to a directory with module classes in bin/, this
* class will put the packaged module in the dist/ subdirectory.
*/
public static final String MODULE_DIR_PROP = "module.dir";
/**
* System property to use if the module properties files isn't "module.properties" (this
* property is evaluated relative to {@link #MODULE_DIR_PROP}).
*/
public static final String MODULE_PROPS_FILE_PROP = "module.propsFile";
 
public static void main(String[] args) throws IOException {
final File moduleDir = new File(System.getProperty(MODULE_DIR_PROP));
final File propsFile = new File(moduleDir, System.getProperty(MODULE_PROPS_FILE_PROP, "module.properties"));
final boolean launchFromPackage = !Boolean.getBoolean("module.fromProject");
final File classes = new File(moduleDir, "bin");
 
// always update dist/ to avoid out of date problems
final File distDir = new File(moduleDir, "dist");
FileUtils.mkdir_p(distDir);
final File jar = new ModulePackager(propsFile, classes).writeToDir(distDir);
// to avoid out of date modules from OpenConcerto (e.g. when launching this module, the jars
// of MODULES_DIR are used for dependencies)
FileUtils.copyFile(jar, new File(Gestion.MODULES_DIR, jar.getName()));
 
final ModuleFactory factory;
if (launchFromPackage) {
factory = new JarModuleFactory(jar);
} else {
factory = new RuntimeModuleFactory(propsFile);
try {
Class.forName(factory.getMainClass());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Module classes are not in the classpath (they should be in " + classes + ")", e);
}
}
 
Gestion.main(args);
// add after main() otherwise we could be overwritten by an older jar
ModuleManager.getInstance().addFactoryAndStart(factory, false);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AlterTableRestricted.java
34,7 → 34,6
*/
public final class AlterTableRestricted {
 
private final DBContext ctxt;
private final SQLTable table;
private final Set<SQLField> previouslyCreatedFields;
private final AlterTable alter;
41,7 → 40,6
private final Set<String> addedColumns, removedColumns;
 
AlterTableRestricted(DBContext ctxt, String tableName) {
this.ctxt = ctxt;
this.table = ctxt.getRoot().getTable(tableName);
this.previouslyCreatedFields = ctxt.getFieldsPreviouslyCreated(tableName);
this.alter = new AlterTable(this.table);
108,14 → 106,8
}
 
public AlterTable addForeignColumn(String fk, SQLName tableName) {
SQLCreateTableBase<?> createTable;
if (tableName.getItemCount() == 1 && (createTable = this.ctxt.getCreateTables().get(tableName.getFirst())) != null) {
addCol(fk);
return this.alter.addForeignColumn(fk, createTable);
} else {
return this.addForeignColumn(fk, this.table.getDesc(tableName, SQLTable.class));
}
}
 
public AlterTable addForeignColumn(String fk, SQLTable foreignTable) {
addCol(fk);
122,6 → 114,11
return this.alter.addForeignColumn(fk, foreignTable);
}
 
public AlterTable addForeignColumn(String fk, SQLCreateTableBase<?> createTable) {
addCol(fk);
return this.alter.addForeignColumn(fk, createTable);
}
 
public AlterTable addUniqueConstraint(String name, List<String> cols) {
if (!this.addedColumns.containsAll(cols))
throw new IllegalArgumentException("Can only add constraint to added columns : " + CollectionUtils.substract(cols, this.addedColumns));
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AbstractModule.java
14,8 → 14,11
package org.openconcerto.erp.modules;
 
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.DBRoot;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
53,9 → 56,21
}
 
/**
* Should create permanent items. NOTE: all items created through <code>ctxt</code> will be
* dropped automatically, i.e. no action is necessary in {@link #uninstall()}.
* The directory this module should use while running. During installation use
* {@link DBContext#getLocalDirectory()}.
*
* @return the directory for this module.
*/
protected final File getLocalDirectory() {
return ModuleManager.getInstance().getLocalDirectory(this.getFactory().getID());
}
 
/**
* Should create permanent items. NOTE: all structure items created through <code>ctxt</code>
* will be dropped automatically, and similarly all files created in
* {@link DBContext#getLocalDirectory()} will be deleted automatically, i.e. no action is
* necessary in {@link #uninstall(DBRoot)}.
*
* @param ctxt to create database objects.
*/
protected void install(DBContext ctxt) {
64,9 → 79,9
 
/**
* Should add elements for the tables of this module. It's also the place to
* {@link SQLElement#setAction(String, org.openconcerto.sql.element.SQLElement.ReferenceAction)set actions}
* for foreign keys of this module. NOTE: this method is called as long as the module is
* installed in the database, even if it is stopped.
* {@link SQLElement#setAction(String, SQLElement.ReferenceAction) set actions} for foreign keys
* of this module. NOTE: this method is called as long as the module is installed in the
* database, even if it is stopped.
*
* @param dir the directory where to add elements.
*/
105,7 → 120,7
 
protected abstract void stop();
 
protected void uninstall() {
protected void uninstall(DBRoot root) {
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/JarModuleFactory.java
105,4 → 105,9
public AbstractModule createModule(Map<String, AbstractModule> alreadyCreated) throws Exception {
return createModule(new ModuleClassLoader(alreadyCreated).loadClass(this.getMainClass()));
}
 
@Override
public String toString() {
return super.toString() + " from " + this.jar;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction.java
22,6 → 22,7
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.humanresources.payroll.element.CaisseCotisationSQLElement;
import org.openconcerto.erp.element.objet.ClasseCompte;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.panel.ComptaTipsFrame;
import org.openconcerto.erp.utils.NXDatabaseAccessor;
import org.openconcerto.map.model.Ville;
113,7 → 114,16
}
comptaPropsConfiguration.setUpSocieteDataBaseConnexion(selectedSociete);
 
// finish filling the configuration before going any further, otherwise the
// SQLElementDirectory is not coherent
try {
ModuleManager.getInstance().setup(comptaPropsConfiguration.getRootSociete(), comptaPropsConfiguration);
} catch (Exception e) {
// not OK to continue without required elements
ExceptionHandler.die("Impossible de démarrer les modules requis", e);
}
 
 
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
127,6 → 137,15
f.setTitle(comptaPropsConfiguration.getAppName() + " " + version + socTitle);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
 
// start modules before displaying the frame (e.g. avoid modifying a
// visible menu bar)
try {
ModuleManager.getInstance().startPreviouslyRunningModules();
} catch (Exception exn) {
// OK to continue without all modules started
ExceptionHandler.handle(f, "Impossible de démarrer les modules", exn);
}
 
FrameUtil.show(f);
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/action/SauvegardeBaseAction.java
28,6 → 28,7
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirFournisseurXmlSheet;
74,47 → 75,15
locations.add(serverIp.substring(5));
}
 
final DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
 
locations.add(defaultLocation);
locations.add(SheetXml.getLocationForTuple(DevisXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(DevisXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(VenteFactureXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(VenteFactureXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(CommandeClientXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(CommandeClientXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(BonLivraisonXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(BonLivraisonXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(AvoirClientXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(AvoirClientXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(AvoirFournisseurXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(AvoirFournisseurXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(CommandeXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(CommandeXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(EtatVentesXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(EtatVentesXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(FicheClientXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(FicheClientXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(FicheRelanceSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(FicheRelanceSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(ReleveChequeSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(ReleveChequeSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(ReleveChequeEmisSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(ReleveChequeEmisSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(ListeFactureXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(ListeFactureXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(ListeVenteXmlSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(ListeVenteXmlSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(EtatChargesPayeSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(EtatChargesPayeSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(FichePayeSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(FichePayeSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(LivrePayeSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(LivrePayeSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(BalanceSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(BalanceSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(GrandLivreSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(GrandLivreSheet.getTuple2Location(), false));
locations.add(SheetXml.getLocationForTuple(JournauxSheet.getTuple2Location(), true));
locations.add(SheetXml.getLocationForTuple(JournauxSheet.getTuple2Location(), false));
for (File f : storage.getAllDocumentDirectories()) {
locations.add(f.getAbsolutePath());
}
for (File f : storage.getAllPDFDirectories()) {
locations.add(f.getAbsolutePath());
}
 
for (String string : locations) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/ReleveChequeSheet.java
15,13 → 15,11
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
39,7 → 37,7
private long total = 0;
private long nb = 0;
private boolean apercu = false;
 
private static final SQLTable tableCheque = base.getTable("CHEQUE_A_ENCAISSER");
private List<Integer> listeIds;
 
public ReleveChequeSheet(List<Integer> listeIds, Date date) {
46,16 → 44,11
this(listeIds, date, false);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationReleveChequeCli", "Relevé chéques clients");
public static final String TEMPLATE_ID = "ReleveCheque";
public static final String TEMPLATE_PROPERTY_NAME = "LocationReleveChequeCli";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
public ReleveChequeSheet(List<Integer> listeIds, Date date, boolean apercu) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.locationOO = SheetXml.getLocationForTuple(tuple, false);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true);
this.date = date;
this.apercu = apercu;
this.listeIds = listeIds;
62,11 → 55,14
}
 
@Override
public String getDefaultModele() {
return "ReleveCheque";
public String getName() {
return "ReleveCheque" + this.date.getTime();
}
 
private static final SQLTable tableCheque = base.getTable("CHEQUE_A_ENCAISSER");
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
protected void createListeValues() {
 
113,8 → 109,4
this.mapAllSheetValues.put(0, values);
}
 
public String getFileName() {
return getValidFileName("ReleveCheque" + this.date.getTime());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/AvoirClientXmlSheet.java
14,27 → 14,16
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class AvoirClientXmlSheet extends AbstractSheetXMLWithDate {
 
public class AvoirClientXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "Avoir";
public static final String TEMPLATE_PROPERTY_NAME = "LocationAvoir";
 
private String startName;
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationAvoir", "Avoir");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
public SQLRow getRowLanguage() {
SQLRow rowClient = this.row.getForeignRow("ID_CLIENT");
49,24 → 38,16
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
}
 
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
 
this.startName = "Avoir_";
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
@Override
public String getDefaultModele() {
 
return "Avoir";
public String getName() {
return "Avoir_" + this.row.getString("NUMERO");
}
 
public String getFileName() {
 
return getValidFileName(this.startName + this.row.getString("NUMERO"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/EtatVentesXmlSheet.java
14,6 → 14,7
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
25,6 → 26,7
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
46,12 → 48,12
 
private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
 
public static final String TEMPLATE_ID = "EtatVentes";
 
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private Timestamp du, au;
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public EtatVentesXmlSheet(Date du, Date au) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
du.setHours(0);
61,18 → 63,18
this.du = new Timestamp(du.getTime());
this.au = new Timestamp(au.getTime());
 
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
}
 
 
 
@Override
public String getDefaultModele() {
 
return "EtatVentes";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
return getValidFileName("EtatVentes" + new Date().getTime());
@Override
public String getName() {
return "EtatVentes" + new Date().getTime();
}
 
protected void createListeValues() {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/CommandeXmlSheet.java
13,25 → 13,16
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class CommandeXmlSheet extends AbstractSheetXMLWithDate {
 
public class CommandeXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "Commande";
public static final String TEMPLATE_PROPERTY_NAME = "LocationCmd";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationCmd", "Commande fournisseur");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
public SQLRow getRowLanguage() {
SQLRow rowFournisseur = this.row.getForeignRow("ID_FOURNISSEUR");
47,21 → 38,15
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("CmdPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("COMMANDE");
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
 
}
 
@Override
public String getDefaultModele() {
 
return "Commande";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
 
return getValidFileName("Commande_" + row.getString("NUMERO"));
@Override
public String getName() {
return "Commande_" + row.getString("NUMERO");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/AvoirFournisseurXmlSheet.java
13,42 → 13,29
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class AvoirFournisseurXmlSheet extends AbstractSheetXMLWithDate {
 
public class AvoirFournisseurXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "AvoirF";
public static final String TEMPLATE_PROPERTY_NAME = "LocationAvoirF";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationAvoirF", "Avoir Fournisseur");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
public AvoirFournisseurXmlSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("AVOIR_FOURNISSEUR");
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
}
 
@Override
public String getDefaultModele() {
// TODO Raccord de méthode auto-généré
return "AvoirF";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
return getValidFileName("AvoirF_" + this.row.getID());
@Override
public String getName() {
return "AvoirF_" + this.row.getID();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/PointageXmlSheet.java
14,7 → 14,6
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
36,16 → 35,18
 
public class PointageXmlSheet extends AbstractListeSheetXml {
 
public static final String TEMPLATE_ID = "Pointage";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
private Map<Integer, List<Map<String, Object>>> listAllSheetValues;
private Map<Integer, Map<Integer, String>> styleAllSheetValues;
private Map<Integer, Map<String, Object>> mapAllSheetValues;
private Calendar c = Calendar.getInstance();
private Date date = new Date();
private final long MILLIS_IN_HOUR = 3600000;
 
public PointageXmlSheet(int mois, int year) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.mapAllSheetValues = new HashMap<Integer, Map<String, Object>>();
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
this.c.set(Calendar.DAY_OF_MONTH, 1);
this.c.set(Calendar.YEAR, year);
this.c.set(Calendar.MONTH, mois);
57,11 → 58,14
}
 
@Override
public String getDefaultModele() {
return "Pointage";
public String getName() {
return "Pointage" + this.date;
}
 
private long oneHour = 3600000;
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
protected void createListeValues() {
SQLElement eltPointage = Configuration.getInstance().getDirectory().getElement("POINTAGE");
124,6 → 128,7
sel.setHaving(Where.createRaw("COUNT (\"POINTAGE\".\"ID_USER_COMMON\") > 0", tablePointage.getField("ID_USER_COMMON")));
sel.addFieldOrder(tableUser.getField("NOM"));
System.err.println(sel.asString());
@SuppressWarnings("unchecked")
List<SQLRow> listUser = (List<SQLRow>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableUser));
 
String entete = "Horaires de travail du mois de " + formatMonth.format(d1);
142,7 → 147,7
mapSheetValue.put("A1", userName);
mapSheetValue.put("F1", entete);
 
long tempsDePause = this.oneHour;
long tempsDePause = this.MILLIS_IN_HOUR;
 
// calcul du temps de pause si possible
if (row.getObject("HEURE_MATIN_D") != null && row.getObject("MINUTE_MATIN_D") != null && row.getObject("HEURE_MIDI_A") != null && row.getObject("MINUTE_MIDI_A") != null) {
173,8 → 178,8
// Temps travaillé dans la semaine
if (semaine > 0 && semaine != this.c.get(Calendar.WEEK_OF_YEAR)) {
Map<String, Object> mValues2 = new HashMap<String, Object>();
long hour = heureTotalSemaine / this.oneHour;
long minute = (heureTotalSemaine % this.oneHour) / 60000;
long hour = heureTotalSemaine / this.MILLIS_IN_HOUR;
long minute = (heureTotalSemaine % this.MILLIS_IN_HOUR) / 60000;
mValues2.put("HEURE_TOTAL", hour + "h" + minute);
heureTotalSemaine = 0;
listValues.add(mValues2);
207,6 → 212,7
sel2.setWhere(wDay);
sel2.addFieldOrder(table2.getField("DATE"));
 
@SuppressWarnings("unchecked")
List<SQLRow> list2 = (List<SQLRow>) Configuration.getInstance().getBase().getDataSource().execute(sel2.asString(), SQLRowListRSH.createFromSelect(sel2, table2));
 
if (list2.size() > 2) {
258,8 → 264,8
System.err.println("time " + time + " Worked :" + timeWorked);
heureTotalSemaine += timeWorked;
heureTotalMois += timeWorked;
long hour = timeWorked / this.oneHour;
long minute = (timeWorked % this.oneHour) / 60000;
long hour = timeWorked / this.MILLIS_IN_HOUR;
long minute = (timeWorked % this.MILLIS_IN_HOUR) / 60000;
mValues.put("HEURE_TOTAL", hour + "h" + minute);
 
} else {
278,8 → 284,8
 
// Heure de la derniere semaine
Map<String, Object> mValues2 = new HashMap<String, Object>();
long hour = heureTotalSemaine / this.oneHour;
long minute = (heureTotalSemaine % this.oneHour) / 60000;
long hour = heureTotalSemaine / this.MILLIS_IN_HOUR;
long minute = (heureTotalSemaine % this.MILLIS_IN_HOUR) / 60000;
mValues2.put("HEURE_TOTAL", hour + "h" + minute);
heureTotalSemaine = 0;
listValues.add(mValues2);
289,8 → 295,8
 
// Heure total du mois
Map<String, Object> mValuesMois = new HashMap<String, Object>();
hour = heureTotalMois / this.oneHour;
minute = (heureTotalMois % this.oneHour) / 60000;
hour = heureTotalMois / this.MILLIS_IN_HOUR;
minute = (heureTotalMois % this.MILLIS_IN_HOUR) / 60000;
mValuesMois.put("HEURE_TOTAL", hour + "h" + minute);
heureTotalMois = 0;
 
315,9 → 321,4
 
}
 
Date date = new Date();
 
public String getFileName() {
return getValidFileName("Pointage" + this.date);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/FicheRelanceSheet.java
14,11 → 14,9
package org.openconcerto.erp.generationDoc.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
31,29 → 29,23
public class FicheRelanceSheet extends AbstractListeSheetXml {
 
private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
private SQLRow row;
public static final String TEMPLATE_ID = "FicheRelance";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public FicheRelanceSheet(SQLRow row) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.row = row;
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
}
 
@Override
public String getDefaultModele() {
return "FicheRelance";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
@Override
protected void createListeValues() {
// TODO Auto-generated method stub
final Map<String, Object> values = new HashMap<String, Object>();
List<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>();
final List<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>();
 
final SQLRow clientRow = this.row.getForeignRow("ID_CLIENT");
final SQLRow factureRow = this.row.getForeignRow("ID_SAISIE_VENTE_FACTURE");
70,8 → 62,9
 
}
 
public String getFileName() {
return getValidFileName("FicheRelance" + new Date().getTime());
@Override
public String getName() {
return "FicheRelance" + new Date().getTime();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/CourrierClientSheet.java
15,12 → 15,10
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractJOOReportsSheet;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.Tuple2;
 
import java.util.Date;
import java.util.HashMap;
31,24 → 29,21
 
private SQLRow rowCourrier;
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationCourrier", "Courrier");
public static final String TEMPLATE_ID = "Courrier";
public static final String TEMPLATE_PROPERTY_NAME = "LocationCourrier";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
public CourrierClientSheet(SQLRow row) {
super();
this.rowCourrier = row;
Date d = (Date) this.rowCourrier.getObject("DATE");
String year = yearFormat.format(d);
init(year, "Courrier.odt", "CourrierPrinter", tuple);
init(year, "Courrier.odt", "CourrierPrinter");
}
 
/**
* @return une Map contenant les valeurs à remplacer dans la template
*/
protected Map createMap() {
protected Map<String, Object> createMap() {
 
Map<String, Object> m = new HashMap<String, Object>();
 
84,8 → 79,7
}
 
public String getFileName() {
String fileName = "Courrier_" + AbstractSheetXml.getValidFileName(this.rowCourrier.getString("NUMERO"));
return fileName;
return "Courrier_" + this.rowCourrier.getString("NUMERO");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/RelanceSheet.java
16,13 → 16,11
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.generationDoc.AbstractJOOReportsSheet;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.util.Date;
import java.util.HashMap;
33,11 → 31,9
 
private SQLRow rowRelance;
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationRelance", "Relance");
public static final String TEMPLATE_ID = "Relance";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
public static final String TEMPLATE_PROPERTY_NAME = "LocationRelance";
 
/**
* @return une Map contenant les valeurs à remplacer dans la template
122,10 → 118,11
sel.addSelect(this.rowRelance.getTable().getKey());
sel.setWhere(new Where(this.rowRelance.getTable().getField("ID_SAISIE_VENTE_FACTURE"), "=", this.rowRelance.getInt("ID_SAISIE_VENTE_FACTURE")));
sel.addFieldOrder(this.rowRelance.getTable().getField("DATE").getFullName());
List<Map> listResult = Configuration.getInstance().getBase().getDataSource().execute(sel.asString());
@SuppressWarnings("unchecked")
List<Map<String, Number>> listResult = Configuration.getInstance().getBase().getDataSource().execute(sel.asString());
if (listResult != null && listResult.size() > 0) {
Map o = listResult.get(0);
Number n = (Number) o.get(this.rowRelance.getTable().getKey().getName());
Map<String, Number> o = listResult.get(0);
Number n = o.get(this.rowRelance.getTable().getKey().getName());
SQLRow rowOldRelance = this.rowRelance.getTable().getRow(n.intValue());
Date dOldRelance = (Date) rowOldRelance.getObject("DATE");
map.put("DatePremiereRelance", dateFormat2.format(dOldRelance));
144,7 → 141,7
 
final String string = rowLettre.getString("MODELE");
System.err.println(this.locationTemplate + "/" + string);
init(year, string, "RelancePrinter", tuple);
init(year, string, "RelancePrinter");
}
 
protected boolean savePDF() {
152,7 → 149,6
}
 
public String getFileName() {
String fileName = "Relance_" + AbstractSheetXml.getValidFileName(this.rowRelance.getString("NUMERO"));
return fileName;
return "Relance_" + this.rowRelance.getString("NUMERO");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/ReleveChequeEmisSheet.java
41,19 → 41,23
createMap();
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationReleveCheque", "Relevé chéques émis");
public static final String TEMPLATE_ID = "ReleveChequeEmis";
public static final String TEMPLATE_PROPERTY_NAME = "LocationReleveCheque";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
private void init() {
this.modele = "ReleveChequeEmis.ods";
// this.printer = PrinterNXProps.getInstance().getStringProperty("FacturePrinter");
this.locationOO = SheetXml.getLocationForTuple(tuple, false);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true);
}
 
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
@Override
protected String getYear() {
return "";
}
 
protected void createMap() {
 
long montantTotal = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLField.java
179,7 → 179,7
String condField = this.elt.getAttributeValue("conditionField");
String condValue = this.elt.getAttributeValue("conditionExpValue");
 
boolean bIsCondValid = condValue == null || this.row.getObject(condField).toString().equalsIgnoreCase(condValue);
boolean bIsCondValid = condValue == null || !this.row.getObject(condField).toString().equalsIgnoreCase(condValue);
if (condValue == null) {
boolean bIsBooleanCondValid = false;
if (condField == null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DefaultLocalTemplateProvider.java
New file
0,0 → 1,66
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.io.File;
 
public class DefaultLocalTemplateProvider extends AbstractLocalTemplateProvider {
 
private File baseDirectory;
 
public DefaultLocalTemplateProvider() {
baseDirectory = new File("Configuration/Template/Default");
}
 
public void setBaseDirectory(File dir) {
this.baseDirectory = dir;
}
 
@Override
public File getTemplateFile(String templateId, String langage, String type) {
File file = getFile(templateId, langage, type);
if (!file.exists()) {
file = getFile(templateId + ".ods", langage, type);
}
return file;
}
 
private File getFile(String templateId, String langage, String type) {
String path = templateId;
if (type != null) {
path += type;
}
if (langage != null) {
path = langage + File.separatorChar + path;
}
File file = new File(baseDirectory, path);
if (!file.exists()) {
file = new File("Configuration/Template/Default", path);
}
return file;
}
 
@Override
public String getTemplatePath(String templateId, String langage, String type) {
String path = "Configuration/Template/Default";
if (type != null) {
path += type;
}
if (langage != null) {
path = langage + '/' + path;
}
return path;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/TemplateManager.java
New file
0,0 → 1,165
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class TemplateManager {
private static TemplateManager instance = new TemplateManager();
private List<TemplateProvider> providers = new ArrayList<TemplateProvider>();
private Map<String, TemplateProvider> defaultMap = new HashMap<String, TemplateProvider>();
private TemplateProvider defautProvider;
private List<String> knownTemplateIds = new ArrayList<String>();
 
public static TemplateManager getInstance() {
return instance;
}
 
public void add(TemplateProvider provider) {
this.providers.add(provider);
}
 
public void remove(TemplateProvider provider) {
this.providers.remove(provider);
final Set<String> keys = defaultMap.keySet();
for (String key : keys) {
if (defaultMap.get(key).equals(provider)) {
defaultMap.remove(key);
}
}
}
 
public void setDefaultProvider(String templateId, TemplateProvider provider) {
defaultMap.put(templateId, provider);
knownTemplateIds.add(templateId);
}
 
public void setDefaultProvider(TemplateProvider provider) {
this.defautProvider = provider;
}
 
/**
* Get the template using first the default template providers
*
*
* @return the template file, IllegalStateException if no template is found
* */
public InputStream getTemplate(String templateId, String language, String type) {
TemplateProvider provider = defaultMap.get(templateId);
if (provider == null) {
for (TemplateProvider pr : providers) {
InputStream stream = pr.getTemplate(templateId, language, type);
if (stream != null) {
return stream;
}
}
if (defautProvider == null) {
throw new IllegalStateException("Not default provider registered when using template id:" + templateId + " language:" + language + " type:" + type);
}
return defautProvider.getTemplate(templateId, language, type);
}
return provider.getTemplate(templateId, language, type);
}
 
/**
* Get the template print configuration using first the default template providers
*
*
* @return the template file, IllegalStateException if no template is found
* */
public InputStream getTemplatePrintConfiguration(String templateId, String language, String type) {
TemplateProvider provider = defaultMap.get(templateId);
if (provider == null) {
for (TemplateProvider pr : providers) {
InputStream stream = pr.getTemplatePrintConfiguration(templateId, language, type);
if (stream != null) {
return stream;
}
}
if (defautProvider == null) {
throw new IllegalStateException("Not default provider registered when using template id:" + templateId + " langage:" + language + " type:" + type);
}
return defautProvider.getTemplatePrintConfiguration(templateId, language, type);
}
return provider.getTemplatePrintConfiguration(templateId, language, type);
}
 
/**
* Get the template cofiguration using first the default template providers
*
*
* @return the template file, IllegalStateException if no template is found
* */
public InputStream getTemplateConfiguration(String templateId, String language, String type) {
TemplateProvider provider = defaultMap.get(templateId);
if (provider == null) {
for (TemplateProvider pr : providers) {
InputStream stream = pr.getTemplateConfiguration(templateId, language, type);
if (stream != null) {
return stream;
}
}
if (defautProvider == null) {
throw new IllegalStateException("Not default provider registered when using template id:" + templateId + " langage:" + language + " type:" + type);
}
return defautProvider.getTemplateConfiguration(templateId, language, type);
}
return provider.getTemplateConfiguration(templateId, language, type);
}
 
public InputStream getTemplate(String templateId) {
return getTemplate(templateId, null, null);
}
 
public void register(String templateId) {
knownTemplateIds.add(templateId);
}
 
public void dump() {
System.out.println(this.getClass().getCanonicalName());
System.out.println("Default provider: " + this.defautProvider);
System.out.println("Templates:");
for (String templateId : this.knownTemplateIds) {
try {
InputStream stream = this.getTemplate(templateId);
if (stream == null) {
System.out.println(rightAlign("'" + templateId + "'") + " : stream missing");
} else {
System.out.println(rightAlign("'" + templateId + "'") + " : ok");
}
} catch (Exception e) {
System.out.println(rightAlign("'" + templateId + "'") + ": stream error");
}
}
 
}
 
private String rightAlign(String s) {
String r = s;
int n = 20 - s.length();
for (int i = 0; i < n; i++) {
r = ' ' + r;
}
return r;
}
 
public boolean isKnwonTemplate(String templateId) {
return this.knownTemplateIds.contains(templateId);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractSheetXMLWithDate.java
New file
0,0 → 1,47
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.StringUtils;
 
import java.io.File;
import java.util.Calendar;
 
public abstract class AbstractSheetXMLWithDate extends AbstractSheetXml {
 
public AbstractSheetXMLWithDate(SQLRow row) {
super(row);
}
 
protected final String getYear() {
final Calendar cal = this.row.getDate("DATE");
return cal == null ? "Date inconnue" : String.valueOf(cal.get(Calendar.YEAR));
}
 
@Override
public File getDocumentOutputDirectoryP() {
return new File(DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(this.getTemplateId()), getYear());
}
 
@Override
public File getPDFOutputDirectoryP() {
return new File(DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.getTemplateId()), getYear());
}
 
@Override
public String getStoragePathP() {
return StringUtils.firstUp(this.elt.getPluralName() + File.separator + getYear());
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DocumentLocalStorageManager.java
New file
0,0 → 1,160
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class DocumentLocalStorageManager {
private static DocumentLocalStorageManager instance = new DocumentLocalStorageManager();
private Map<String, File> dirs = new HashMap<String, File>();
private Map<String, File> dirsPDF = new HashMap<String, File>();
private File documentDefaultDirectory;
private File PDFDefaultDirectory;
 
public static DocumentLocalStorageManager getInstance() {
return instance;
}
 
/**
* Returns the directory to store the document created from a template
*
* @param templateId : the id of the template used to create the document
* */
public File getDocumentOutputDirectory(String templateId) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
final File f = dirs.get(templateId);
if (f != null) {
return f;
}
return documentDefaultDirectory;
 
}
 
/**
* Returns the directory to store the PDF document created from a template
*
* @param templateId : the id of the template used to create the document
* */
public File getPDFOutputDirectory(String templateId) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
final File f = dirsPDF.get(templateId);
if (f != null) {
return f;
}
return PDFDefaultDirectory;
}
 
public void addDocumentDirectory(String templateId, File directory) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
this.dirs.put(templateId, directory);
TemplateManager.getInstance().register(templateId);
}
 
public void removeDocumentDirectory(String templateId, File directory) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
this.dirs.remove(templateId);
}
 
public void addPDFDirectory(String templateId, File directory) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
this.dirsPDF.put(templateId, directory);
TemplateManager.getInstance().register(templateId);
}
 
public void removePDFDirectory(String templateId, File directory) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
this.dirsPDF.remove(templateId);
}
 
public void setDocumentDefaultDirectory(File directory) {
this.documentDefaultDirectory = directory;
}
 
public void setPDFDefaultDirectory(File directory) {
this.PDFDefaultDirectory = directory;
}
 
public List<File> getAllPDFDirectories() {
List<File> list = new ArrayList<File>();
for (String id : this.dirsPDF.keySet()) {
list.add(this.dirsPDF.get(id));
}
return list;
}
 
public List<File> getAllDocumentDirectories() {
List<File> list = new ArrayList<File>();
for (String id : this.dirs.keySet()) {
list.add(this.dirs.get(id));
}
return list;
}
 
public void dump() {
System.out.println(this.getClass().getCanonicalName());
System.out.println("Default document directory: " + getAndTest(this.documentDefaultDirectory));
System.out.println("Default PFD directory : " + getAndTest(this.PDFDefaultDirectory));
System.out.println("Document directories:");
for (String key : this.dirs.keySet()) {
System.out.println(rightAlign("'" + key + "'") + " : " + getAndTest(this.dirs.get(key)));
}
System.out.println("PDF directories:");
for (String key : this.dirsPDF.keySet()) {
System.out.println(rightAlign("'" + key + "'") + " : " + getAndTest(this.dirsPDF.get(key)));
}
}
 
private String rightAlign(String s) {
String r = s;
int n = 20 - s.length();
for (int i = 0; i < n; i++) {
r = ' ' + r;
}
return r;
}
 
private String getAndTest(File dir) {
if (dir == null) {
return "null !!!!!!";
}
String r = "'" + dir.getAbsolutePath() + "'";
if (dir.exists()) {
if (!dir.isDirectory()) {
r += " is not a directory!!";
} else if (!dir.canWrite()) {
r += " is write protected!!";
}
} else {
r += " does not exist !!";
}
return r;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
73,8 → 73,8
 
private static int answer = JOptionPane.NO_OPTION;
 
public static synchronized File genere(String modele, String pathDest, final String fileDest, SQLRow row, SQLRow rowLanguage) {
 
public static synchronized File createDocument(String templateId, File outputDirectory, final String expectedFileName, SQLRow row, SQLRow rowLanguage) {
final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
cacheStyle.clear();
OOXMLCache.clearCache();
rowsEltCache.clear();
81,7 → 81,7
taxe.clear();
cacheForeign.clear();
 
File fDest = new File(pathDest, fileDest + ".ods");
File fDest = new File(outputDirectory, expectedFileName);
 
if (fDest.exists()) {
 
112,20 → 112,20
SAXBuilder builder = new SAXBuilder();
try {
 
if (needAnnexe(modele, row, rowLanguage)) {
try {
if (needAnnexe(templateId, row, rowLanguage)) {
// check if it exists
getOOTemplate(modele + "_annexe", rowLanguage);
modele += "_annexe";
System.err.println("modele With annexe " + modele);
} catch (FileNotFoundException e) {
 
final String annexeTemplateId = templateId + "_annexe";
InputStream annexeStream = TemplateManager.getInstance().getTemplate(annexeTemplateId, langage, null);
if (annexeStream != null) {
templateId = annexeTemplateId;
System.err.println("modele With annexe " + templateId);
}
}
 
System.err.println("modele " + modele);
System.err.println("Using template id: " + templateId);
final InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, langage, null);
 
Document doc = builder.build(getXmlTemplate(modele, rowLanguage));
Document doc = builder.build(xmlConfiguration);
 
// On initialise un nouvel élément racine avec l'élément racine du document.
Element racine = doc.getRootElement();
134,7 → 134,9
List<Element> listElts = racine.getChildren("element");
 
// Création et génération du fichier OO
SpreadSheet spreadSheet = SpreadSheet.create(new ODPackage(getOOTemplate(modele, rowLanguage)));
final InputStream template = TemplateManager.getInstance().getTemplate(templateId, langage, null);
 
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
try {
// On remplit les cellules de la feuille
parseElementsXML(listElts, row, spreadSheet);
147,10 → 149,10
parseTableauXML(tableChild, row, spreadSheet, rowLanguage);
}
} catch (Exception e) {
ExceptionHandler.handle("Impossible de remplir le document " + modele + " " + ((rowLanguage == null) ? "" : rowLanguage.getString("CHEMIN")), e);
ExceptionHandler.handle("Impossible de remplir le document " + templateId + " " + ((rowLanguage == null) ? "" : rowLanguage.getString("CHEMIN")), e);
}
// Sauvegarde du fichier
return saveSpreadSheet(spreadSheet, new File(pathDest), fileDest, modele, rowLanguage);
return saveSpreadSheet(spreadSheet, outputDirectory, expectedFileName, templateId, rowLanguage);
 
} catch (final JDOMException e) {
 
157,7 → 159,7
e.printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ExceptionHandler.handle("Erreur lors de la génération du fichier " + fileDest, e);
ExceptionHandler.handle("Erreur lors de la génération du fichier " + expectedFileName, e);
}
});
} catch (final IOException e) {
165,7 → 167,7
e.printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ExceptionHandler.handle("Erreur lors de la création du fichier " + fileDest, e);
ExceptionHandler.handle("Erreur lors de la création du fichier " + expectedFileName, e);
}
});
}
706,8 → 708,9
* @return un File pointant sur le fichier créé
* @throws IOException
*/
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String modele, SQLRow rowLanguage) throws IOException {
 
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
// Test des arguments
if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
throw new IllegalArgumentException();
720,7 → 723,7
pathDest.mkdirs();
}
 
fDest = SheetUtils.getInstance().convertToOldFile(fileName, pathDest, fDest);
fDest = SheetUtils.convertToOldFile(fileName, pathDest, fDest);
 
// Sauvegarde
try {
743,7 → 746,7
// Copie de l'odsp
try {
File odspOut = new File(pathDest, fileName + ".odsp");
InputStream odspIn = getTemplate(modele + ".odsp", rowLanguage);
final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, null);
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
}
753,18 → 756,6
return fDest;
}
 
public static InputStream getOOTemplate(String name, SQLRow language) throws FileNotFoundException {
return OOgenerationListeXML.getOOTemplate(name, language);
}
 
public static InputStream getXmlTemplate(String name, SQLRow language) throws FileNotFoundException {
return OOgenerationListeXML.getXmlTemplate(name, language);
}
 
public static InputStream getTemplate(String name, SQLRow language) throws FileNotFoundException {
return OOgenerationListeXML.getTemplate(name, language);
}
 
/**
* parcourt l'ensemble de la feuille pour trouver les style définit
*/
827,15 → 818,16
return mapStyleDef;
}
 
public static boolean needAnnexe(String modele, SQLRow row, SQLRow rowLanguage) {
 
SAXBuilder builder = new SAXBuilder();
public static boolean needAnnexe(String templateId, SQLRow row, SQLRow rowLanguage) {
final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
final SAXBuilder builder = new SAXBuilder();
try {
final InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, langage, null);
final Document doc = builder.build(xmlConfiguration);
final InputStream template = TemplateManager.getInstance().getTemplate(templateId, langage, null);
 
Document doc = builder.build(getXmlTemplate(modele, rowLanguage));
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
 
SpreadSheet spreadSheet = SpreadSheet.create(new ODPackage(getOOTemplate(modele, rowLanguage)));
 
// On initialise un nouvel élément racine avec l'élément racine du document.
Element racine = doc.getRootElement();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
49,34 → 49,32
// Cache pour la recherche des styles
private static Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<Sheet, Map<String, Map<Integer, String>>>();
 
public static File genere(String modele, String pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values) {
public static File genere(String modele, File pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values) {
return genere(modele, pathDest, fileDest, liste, values, new HashMap<Integer, Map<Integer, String>>(), null, null);
}
 
public static File genere(String modele, String pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values,
public static File genere(String templateId, File pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values,
Map<Integer, Map<Integer, String>> mapStyle, List<String> sheetName, SQLRow rowLanguage) {
// SQLRow row = elt.getTable().getRow(id);
cacheStyle.clear();
SAXBuilder builder = new SAXBuilder();
final SAXBuilder builder = new SAXBuilder();
try {
Document doc = builder.build(getXmlTemplate(modele, rowLanguage));
InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
Document doc = builder.build(xmlConfiguration);
 
// On initialise un nouvel élément racine avec l'élément racine du
// document.
Element racine = doc.getRootElement();
final Element racine = doc.getRootElement();
 
// Création et génération du fichier OO
SpreadSheet spreadSheet = SpreadSheet.create(new ODPackage(getOOTemplate(modele, rowLanguage)));
final InputStream template = TemplateManager.getInstance().getTemplate(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
 
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
Sheet sheet0 = spreadSheet.getSheet(0);
if (sheetName != null && sheetName.size() > 0) {
for (int i = 1; i < sheetName.size(); i++) {
sheet0.copy(i, (sheetName != null) ? sheetName.get(i) : "Feuille " + i);
}
 
spreadSheet.getSheet(0).setName(sheetName.get(0));
 
System.err.println("add " + sheetName.size() + " sheet");
 
}
 
for (Integer i : liste.keySet()) {
86,7 → 84,6
children = racine.getChildren("element");
}
parseElementsXML(children, sheet, values.get(i));
 
Element child = racine.getChild("table" + i);
if (child == null) {
child = racine.getChild("table");
94,15 → 91,11
parseListeXML(child, liste.get(i), sheet, mapStyle.get(i));
}
// Sauvegarde du fichier
return saveSpreadSheet(spreadSheet, new File(pathDest), fileDest, modele, rowLanguage);
return saveSpreadSheet(spreadSheet, pathDest, fileDest, templateId, rowLanguage);
 
} catch (JDOMException e) {
 
e.printStackTrace();
ExceptionHandler.handle("Erreur lors de la génération du fichier " + fileDest, e);
} catch (IOException e) {
 
e.printStackTrace();
ExceptionHandler.handle("Erreur lors de la création du fichier " + fileDest, e);
}
return null;
478,7 → 471,7
* @return un File pointant sur le fichier créé
* @throws IOException
*/
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String modele, SQLRow rowLanguage) throws IOException {
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
 
// Test des arguments
if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
492,7 → 485,7
pathDest.mkdirs();
}
 
SheetUtils.getInstance().convertToOldFile(fileName, pathDest, fDest);
SheetUtils.convertToOldFile(fileName, pathDest, fDest);
 
// Sauvegarde
try {
515,7 → 508,7
// Copie de l'odsp
try {
File odspOut = new File(pathDest, fileName + ".odsp");
InputStream odspIn = getTemplate(modele + ".odsp", rowLanguage);
InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
}
526,34 → 519,7
return fDest;
}
 
public static InputStream getOOTemplate(String name, SQLRow rowLanguage) throws FileNotFoundException {
return getTemplate(name + ".ods", rowLanguage);
}
 
public static InputStream getXmlTemplate(String name, SQLRow rowLanguage) throws FileNotFoundException {
return getTemplate(name + ".xml", rowLanguage);
}
 
/**
* Permet d'obtenir l'emplacement du modele passé en argument. Si le modéle ne se pas trouve
* dans le répertoire spécifié dans les préférences alors on recherche dans le répertoire par
* défaut des modéles.
*
* @param name nom du modéle à trouver
* @return le modéle
* @throws FileNotFoundException si le fichier est introuvable
*/
public static InputStream getTemplate(String name, SQLRow rowLanguage) throws FileNotFoundException {
String modelDir = TemplateNXProps.getInstance().getStringProperty("LocationTemplate");
 
if (rowLanguage != null) {
return ComptaBasePropsConfiguration.getStream(name, modelDir + File.separator + rowLanguage.getString("CHEMIN"), modelDir, SpreadSheetGenerator.defaultLocationTemplate);
} else {
return ComptaBasePropsConfiguration.getStream(name, modelDir, SpreadSheetGenerator.defaultLocationTemplate);
}
}
 
/**
* parcourt l'ensemble de la feuille pour trouver les style définit
*/
private static Map<String, Map<Integer, String>> searchStyle(Sheet sheet, int colEnd, int rowEnd) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractSheetXml.java
14,8 → 14,10
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.StringUtils;
 
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
 
23,35 → 25,36
import javax.swing.SwingUtilities;
 
public abstract class AbstractSheetXml extends SheetXml {
private File generatedOpenDocumentFile;
 
public AbstractSheetXml(SQLRow row) {
this.row = row;
}
 
public final Future<File> genere(final boolean visu, final boolean impression) {
Callable<File> c = new Callable<File>() {
@Override
public File call() throws Exception {
public final Future<SheetXml> createDocumentAsynchronous() {
Callable<SheetXml> c = new Callable<SheetXml>() {
@Override
public SheetXml call() throws Exception {
try {
String modele = getModele();
final String modeleFinal = modele;
try {
OOgenerationXML.getOOTemplate(modele, getRowLanguage());
} catch (Exception e) {
String templateId = getTemplateId();
final String modeleFinal = templateId;
 
String langage = getRowLanguage() != null ? getRowLanguage().getString("CHEMIN") : null;
InputStream templateStream = TemplateManager.getInstance().getTemplate(templateId, langage, getType());
if (templateStream == null) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
// TODO Raccord de méthode auto-généré
JOptionPane.showMessageDialog(null, "Impossible de trouver le modele " + modeleFinal + ". \n Le modéle par défaut sera utilisé!");
}
});
modele = getDefaultModele();
templateId = getDefaultTemplateId();
}
File fGen = OOgenerationXML.genere(modele, AbstractSheetXml.this.locationOO, getFileName(), AbstractSheetXml.this.row, getRowLanguage());
AbstractSheetXml.this.f = fGen;
useOO(fGen, visu, impression, getFileName());
return fGen;
AbstractSheetXml.this.generatedOpenDocumentFile = OOgenerationXML.createDocument(templateId, getDocumentOutputDirectory(), getValidFileName(getName()), AbstractSheetXml.this.row,
getRowLanguage());
 
} catch (Exception e) {
DEFAULT_HANDLER.uncaughtException(null, e);
// rethrow exception so that the unsuspecting caller can use this as the
59,11 → 62,27
throw e;
} catch (Throwable e) {
DEFAULT_HANDLER.uncaughtException(null, e);
return null;
}
 
}
return AbstractSheetXml.this;
}
};
return runnableQueue.submit(c);
}
 
public String getType() {
return null;
}
 
@Override
public String getStoragePathP() {
return StringUtils.firstUp(elt.getPluralName());
}
 
@Override
public File getGeneratedFile() {
if (this.generatedOpenDocumentFile == null)
this.generatedOpenDocumentFile = new File(getDocumentOutputDirectory(), getValidFileName(getName()) + ".ods");
return generatedOpenDocumentFile;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SpreadSheetGenerator.java
193,7 → 193,7
return null;
}
}
final SpreadSheet res = SpreadSheet.create(new ODPackage(f));
final SpreadSheet res = new ODPackage(f).getSpreadSheet();
f.close();
return res;
}
250,9 → 250,9
 
this.modele = sheet.modele;
this.mCell = sheet.mCell;
this.destDirOO = new File(sheet.locationOO);
this.destDirOO = sheet.getDocumentOutputDirectory();
this.destDirOO.mkdirs();
this.destDirPDF = new File(sheet.locationPDF);
this.destDirPDF = sheet.getPDFOutputDirectory();
this.destDirPDF.mkdirs();
this.nbPage = sheet.nbPage;
this.nbRowsPerPage = sheet.nbRowsPerPage;
272,7 → 272,7
try {
 
f = generateWithStyle();
 
final File pdfFileToCreate = new File(this.destDirPDF.getAbsolutePath(), this.destFileName + ".pdf");
try {
 
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
279,7 → 279,8
 
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, !this.visu);
if (this.exportPDF) {
doc.saveToPDF(new File(this.destDirPDF.getAbsolutePath(), this.destFileName + ".pdf"));
 
doc.saveToPDF(pdfFileToCreate);
}
 
if (this.impression) {
295,7 → 296,7
PreviewFrame.show(f);
}
 
SheetUtils.getInstance().convert2PDF(doc, f, this.destFileName);
SheetUtils.convert2PDF(doc, pdfFileToCreate);
if (this.impression) {
// Print !
DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractListeSheetXml.java
13,6 → 13,9
package org.openconcerto.erp.generationDoc;
 
import static org.openconcerto.erp.generationDoc.SheetXml.getValidFileName;
import org.openconcerto.utils.StringUtils;
 
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
35,16 → 38,21
// Nom des feuilles
protected List<String> sheetNames = new ArrayList<String>();
 
public final Future<File> genere(final boolean visu, final boolean impression) {
Callable<File> c = new Callable<File>() {
private File generatedOpenDocumentFile;
 
public AbstractListeSheetXml() {
generatedOpenDocumentFile = new File(getDocumentOutputDirectory(), getValidFileName(getName()) + ".ods");
}
 
public final Future<SheetXml> createDocumentAsynchronous() {
Callable<SheetXml> c = new Callable<SheetXml>() {
@Override
public File call() throws Exception {
public SheetXml call() throws Exception {
try {
createListeValues();
File fGen = OOgenerationListeXML.genere(getModele(), locationOO, getFileName(), listAllSheetValues, mapAllSheetValues, styleAllSheetValues, sheetNames, null);
AbstractListeSheetXml.this.f = fGen;
useOO(fGen, visu, impression, getFileName());
return fGen;
generatedOpenDocumentFile = OOgenerationListeXML.genere(getTemplateId(), getDocumentOutputDirectory(), getValidFileName(getName()), listAllSheetValues, mapAllSheetValues,
styleAllSheetValues, sheetNames, null);
return AbstractListeSheetXml.this;
} catch (Exception e) {
DEFAULT_HANDLER.uncaughtException(null, e);
// rethrow exception so that the unsuspecting caller can use this as the
57,7 → 65,7
 
}
};
return this.runnableQueue.submit(c);
return runnableQueue.submit(c);
}
 
/**
64,4 → 72,24
* To fill listAllSheetValues, styleAllSheetValues, mapAllSheetValues, sheetNames
*/
protected abstract void createListeValues();
 
@Override
public String getStoragePathP() {
return StringUtils.firstUp(elt.getPluralName());
}
 
@Override
public File getGeneratedFile() {
return generatedOpenDocumentFile;
}
 
@Override
public File getDocumentOutputDirectoryP() {
return DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(this.getTemplateId());
}
 
@Override
public File getPDFOutputDirectoryP() {
return DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.getTemplateId());
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DocumentGeneratorManager.java
New file
0,0 → 1,66
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class DocumentGeneratorManager {
private static DocumentGeneratorManager instance = new DocumentGeneratorManager();
private Map<String, DocumentGenerator> generators = new HashMap<String, DocumentGenerator>();
private DocumentGenerator defautGenerator;
 
public static DocumentGeneratorManager getInstance() {
return instance;
}
 
public void add(String templateId, DocumentGenerator generator) {
this.generators.put(templateId, generator);
}
 
public void remove(DocumentGenerator generator) {
final Set<String> keys = generators.keySet();
for (String key : keys) {
if (generators.get(key).equals(generator)) {
generators.remove(key);
}
}
}
 
public void setDefaultGenerator(DocumentGenerator generator) {
this.defautGenerator = generator;
}
 
/**
* Returns the document generator a specific templateId
* */
public DocumentGenerator getGenerator(String templateId) {
DocumentGenerator generator = this.generators.get(templateId);
if (generator == null) {
generator = defautGenerator;
}
return generator;
}
 
public void dump() {
System.out.println(this.getClass().getCanonicalName());
System.out.println("Default generator:" + this.defautGenerator);
Set<String> ids = generators.keySet();
for (String templateId : ids) {
System.out.println("'" + templateId + "' : " + generators.get(templateId));
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractJOOReportsSheet.java
41,7 → 41,6
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
 
public abstract class AbstractJOOReportsSheet {
private static final String defaultLocationTemplate = SpreadSheetGenerator.defaultLocationTemplate;
protected static final DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
49,8 → 48,7
protected static final DateFormat yearFormat = new SimpleDateFormat("yyyy");
private String year;
protected String locationTemplate = TemplateNXProps.getInstance().getStringProperty("LocationTemplate");
private String locationOO, locationPDF;
protected String templateFileName;
protected String templateId;
private String printer;
protected boolean askOverwriting = false;
 
61,11 → 59,9
 
abstract public String getFileName();
 
protected void init(String year, String templateFileName, String attributePrinter, Tuple2<String, String> t) {
protected void init(String year, String templateId, String attributePrinter) {
this.year = year;
this.templateFileName = templateFileName;
this.locationOO = SheetXml.getLocationForTuple(t, false) + File.separator + this.year;
this.locationPDF = SheetXml.getLocationForTuple(t, true) + File.separator + this.year;
this.templateId = templateId;
this.printer = PrinterNXProps.getInstance().getStringProperty(attributePrinter);
}
 
88,27 → 84,23
try {
 
String fileName = getFileName();
final InputStream fileTemplate = getStream(this.templateFileName, this.locationTemplate, defaultLocationTemplate);
 
File fileOutOO = new File(this.locationOO, fileName + ".odt");
// File fileOutPDF = new File(locationPropositionPDF, fileName);
 
final InputStream fileTemplate = TemplateManager.getInstance().getTemplate(this.templateId);
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(this.templateId);
File fileOutOO = getDocumentFile();
if (fileOutOO.exists() && overwrite) {
if (this.askOverwriting) {
int answer = JOptionPane.showConfirmDialog(null, "Voulez vous écraser le document ?", "Remplacement d'un document", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
SheetUtils.getInstance().convertToOldFile(fileName, new File(this.locationOO), fileOutOO, ".odt");
SheetUtils.convertToOldFile(fileName, outputDir, fileOutOO, ".odt");
}
} else {
SheetUtils.getInstance().convertToOldFile(fileName, new File(this.locationOO), fileOutOO, ".odt");
SheetUtils.convertToOldFile(fileName, outputDir, fileOutOO, ".odt");
}
}
 
if (!fileOutOO.exists()) {
fileOutOO.getParentFile().mkdirs();
Template template;
// try {
template = new Template(new BufferedInputStream(fileTemplate));
Template template = new Template(new BufferedInputStream(fileTemplate));
 
// creation du document
final Map createMap = createMap();
116,11 → 108,7
 
model.putAll(createMap);
template.createDocument(model).saveAs(fileOutOO);
// template.createDocument(model, new BufferedOutputStream(new
// FileOutputStream(fileOutOO)));
// } catch (JDOMException e) {
// e.printStackTrace();
// }
 
}
 
// ouverture de OO
133,9 → 121,10
}
final Component doc = ooConnexion.loadDocument(fileOutOO, !show);
 
if (this.savePDF())
doc.saveToPDF(new File(this.locationPDF, fileName + ".pdf"), "writer_pdf_Export");
 
if (this.savePDF()) {
File pdfOutputDir = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(templateId);
doc.saveToPDF(new File(pdfOutputDir, fileName + ".pdf"), "writer_pdf_Export");
}
if (print) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("Name", printer);
164,7 → 153,7
}
 
public void showDocument() {
File fileOutOO = new File(this.locationOO, getFileName() + ".odt");
File fileOutOO = getDocumentFile();
if (fileOutOO.exists()) {
try {
final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
183,8 → 172,13
}
}
 
private File getDocumentFile() {
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(templateId);
return new File(outputDir, getFileName() + ".odt");
}
 
public void printDocument() {
File fileOutOO = new File(this.locationOO, getFileName() + ".odt");
File fileOutOO = getDocumentFile();
if (fileOutOO.exists()) {
 
try {
211,7 → 205,7
 
public void fastPrintDocument() {
 
final File f = new File(this.locationOO, getFileName() + ".odt");
final File f = getDocumentFile();
 
if (!f.exists()) {
generate(true, false, this.printer);
239,13 → 233,6
}
}
 
public boolean exists() {
 
String fileName = getFileName();
File fileOutOO = new File(this.locationOO, fileName + ".odt");
return fileOutOO.exists();
}
 
protected String getInitiales(SQLRow row) {
String init = "";
if (row != null) {
264,9 → 251,10
public void exportToPdf() {
 
// Export vers PDF
String fileName = getFileName();
File fileOutOO = new File(this.locationOO, fileName + ".odt");
File fileOutPDF = new File(this.locationPDF, fileName);
final String fileName = getFileName();
final File fileOutOO = getDocumentFile();
final File outputPDFDirectory = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.templateId);
final File fileOutPDF = new File(outputPDFDirectory, fileName + ".pdf");
 
if (!fileOutOO.exists()) {
generate(false, false, "");
290,7 → 278,7
int result = JOptionPane.showOptionDialog(null, "Ouvrir le pdf ?", "Ouverture du PDF", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
 
if (result == JOptionPane.YES_OPTION) {
Gestion.openPDF(new File(fileOutPDF.getAbsolutePath() + ".pdf"));
Gestion.openPDF(fileOutPDF);
} else {
try {
FileUtils.openFile(fileOutPDF.getParentFile());
317,10 → 305,6
return ville.getName();
}
 
public String getLocationOO() {
return locationOO;
}
 
protected static String getVilleCP(String name) {
Ville ville = Ville.getVilleFromVilleEtCode(name);
if (ville == null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractLocalTemplateProvider.java
New file
0,0 → 1,73
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
 
public abstract class AbstractLocalTemplateProvider implements TemplateProvider {
 
@Override
public InputStream getTemplate(String templateId, String langage, String type) {
try {
final File templateFile = getTemplateFile(templateId, langage, type);
if (templateFile == null || !templateFile.exists()) {
return null;
}
return new FileInputStream(templateFile);
} catch (FileNotFoundException e) {
return null;
}
}
 
@Override
public InputStream getTemplatePrintConfiguration(String templateId, String langage, String type) {
final File t = getTemplateFile(templateId, langage, type);
final String name = t.getName();
if (name.toLowerCase().endsWith(".ods")) {
final File file = new File(t.getParent(), name.substring(0, name.length() - 4) + ".odsp");
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
System.err.println("No print configuration " + file.getAbsolutePath() + " for template id: " + templateId);
e.printStackTrace();
}
}
return null;
}
 
@Override
public InputStream getTemplateConfiguration(String templateId, String langage, String type) {
final File t = getTemplateFile(templateId, langage, type);
final String name = t.getName();
if (name.toLowerCase().endsWith(".ods")) {
final File file = new File(t.getParent(), name.substring(0, name.length() - 4) + ".xml");
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
System.err.println("No template configuration " + file.getAbsolutePath() + " for template id: " + templateId);
e.printStackTrace();
}
}
return null;
}
 
public abstract File getTemplateFile(String templateId, String langage, String type);
 
@Override
public abstract String getTemplatePath(String templateId, String langage, String type);
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DocumentGenerator.java
New file
0,0 → 1,27
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.util.Map;
 
public interface DocumentGenerator {
 
/**
* Define the context for the creation of the document Keys of the context are defined in the
* objects implementing the interface
* */
public void setContext(Map<String, Object> context);
 
public void createDocument();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/TemplateProvider.java
New file
0,0 → 1,38
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc;
 
import java.io.InputStream;
 
public interface TemplateProvider {
/**
* Path: ex ILM/Devis
* */
public String getTemplatePath(String templateId, String language, String type);
 
/**
* Returns the content of template file (ex: the ODS file)
* */
public InputStream getTemplate(String templateId, String language, String type);
 
/**
* Returns the content of template configuration file (ex: the odsp file)
* */
public InputStream getTemplateConfiguration(String templateId, String language, String type);
 
/**
* Returns the content of template print configuration file (ex: the odsp file)
* */
public InputStream getTemplatePrintConfiguration(String templateId, String language, String type);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
17,7 → 17,8
import org.openconcerto.erp.core.common.ui.FastPrintAskFrame;
import org.openconcerto.erp.core.common.ui.PreviewFrame;
import org.openconcerto.erp.generationDoc.element.TypeModeleSQLElement;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.erp.storage.StorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
import org.openconcerto.openoffice.OOUtils;
import org.jopendocument.link.Component;
import org.openconcerto.sql.Configuration;
25,13 → 26,17
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
46,6 → 51,23
 
public abstract class SheetXml {
 
// return null to keep default value
public interface StorageDirs {
public File getDocumentOutputDirectory(SheetXml sheet);
 
public File getPDFOutputDirectory(SheetXml sheet);
 
public String getStoragePath(SheetXml sheet);
}
 
private static StorageDirs STORAGE_DIRS;
 
// allow to redirect all documents
public static void setStorageDirs(StorageDirs d) {
STORAGE_DIRS = d;
}
 
public static final String DEFAULT_PROPERTY_NAME = "Default";
protected SQLElement elt;
 
// nom de l'imprimante à utiliser
57,16 → 79,6
// Language du document
protected SQLRow rowLanguage;
 
// emplacement du fichier OO généré
protected String locationOO;
 
// emplacement du fichier PDF généré
protected String locationPDF;
 
protected File f;
 
public static final Tuple2<String, String> tupleDefault = Tuple2.create("Default", "Autres");
 
protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
 
// single threaded and kill its thread after 3 seconds (to allow the program to exit)
79,62 → 91,98
}
};
 
public void useOO(final File f, final boolean visu, final boolean impression, final String fileName) {
useOO(f, visu, impression, fileName, true);
public final SQLElement getElement() {
return this.elt;
}
 
public void useOO(final File f, final boolean visu, final boolean impression, final String fileName, boolean exportPDF) {
/**
* Show, print and export the document to PDF. This method is asynchronous, but is executed in a
* single threaded queue shared with createDocument
* */
public Future<SheetXml> showPrintAndExportAsynchronous(final boolean showDocument, final boolean printDocument, final boolean exportToPDF) {
final Callable<SheetXml> c = new Callable<SheetXml>() {
@Override
public SheetXml call() throws Exception {
showPrintAndExport(showDocument, printDocument, exportToPDF);
return SheetXml.this;
}
};
return runnableQueue.submit(c);
 
if (f == null || fileName.trim().length() == 0) {
ExceptionHandler.handle("Erreur lors de la génération du fichier " + fileName);
}
 
/**
* Show, print and export the document to PDF. This method is synchronous
* */
public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF) {
 
final File generatedFile = getGeneratedFile();
final File pdfFile = getGeneratedPDFFile();
if (generatedFile == null || !generatedFile.exists()) {
ExceptionHandler.handle("Fichier généré manquant: " + generatedFile);
return;
}
 
try {
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, !visu);
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(generatedFile, !showDocument);
 
if (exportPDF) {
doc.saveToPDF(getFilePDF()).get();
}
 
if (impression) {
if (printDocument) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("Name", this.printer);
doc.printDocument(map);
}
if (exportToPDF) {
doc.saveToPDF(pdfFile).get();
}
doc.close();
} else {
final OpenDocument doc = new OpenDocument(f);
final OpenDocument doc = new OpenDocument(generatedFile);
 
if (exportPDF) {
final Thread t = new Thread("PDF Export: " + fileName) {
if (showDocument) {
showPreviewDocument();
}
if (printDocument) {
// Print !
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
printer.print(doc);
 
}
if (exportToPDF) {
 
try {
SheetUtils.convert2PDF(doc, pdfFile);
 
} catch (Throwable e) {
ExceptionHandler.handle("Impossible de créer le PDF");
}
 
Thread t = new Thread(new Runnable() {
 
@Override
public void run() {
 
List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
for (StorageEngine storageEngine : engines) {
if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
try {
SheetUtils.getInstance().convert2PDF(doc, f, fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
storageEngine.connect();
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(pdfFile));
final String path = getStoragePath();
storageEngine.store(inStream, path, pdfFile.getName(), true);
inStream.close();
storageEngine.disconnect();
} catch (IOException e) {
ExceptionHandler.handle("Impossible de sauvegarder le PDF");
}
}
};
t.setPriority(Thread.MIN_PRIORITY);
t.start();
 
}
if (visu) {
showPreviewDocument();
}
if (impression) {
// Print !
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
printer.print(doc);
 
}
});
t.start();
 
}
}
 
} catch (Exception e) {
e.printStackTrace();
142,19 → 190,61
}
}
 
public abstract String getDefaultModele();
public abstract String getDefaultTemplateId();
 
// nom du modele sans extension
public String getModele() {
if (this.row.getTable().getFieldsName().contains("ID_MODELE")) {
/**
* Path of the directory used for storage. Ex: Devis/2010
* */
public final String getStoragePath() {
final String res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getStoragePath(this);
if (res != null)
return res;
else
return this.getStoragePathP();
}
 
public final File getDocumentOutputDirectory() {
final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getDocumentOutputDirectory(this);
if (res != null)
return res;
else
return this.getDocumentOutputDirectoryP();
}
 
public final File getPDFOutputDirectory() {
final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getPDFOutputDirectory(this);
if (res != null)
return res;
else
return this.getPDFOutputDirectoryP();
}
 
protected abstract String getStoragePathP();
 
protected abstract File getDocumentOutputDirectoryP();
 
protected abstract File getPDFOutputDirectoryP();
 
/**
* Name of the generated document (without extension), do not rely on this name.
*
* Use getGeneratedFile().getName() to get the generated file name.
* */
public abstract String getName();
 
/**
* @return the template id for this template (ex: "sales.quote")
* */
public String getTemplateId() {
if (this.row != null && this.row.getTable().getFieldsName().contains("ID_MODELE")) {
SQLRow rowModele = this.row.getForeignRow("ID_MODELE");
if (rowModele.isUndefined()) {
TypeModeleSQLElement typeModele = Configuration.getInstance().getDirectory().getElement(TypeModeleSQLElement.class);
String modele = typeModele.getTemplateMapping().get(this.row.getTable());
String modele = typeModele.getTemplateMapping().get(this.row.getTable().getName());
if (modele == null) {
System.err.println("No default modele in table TYPE_MODELE for table " + this.row.getTable().getName());
Thread.dumpStack();
return getDefaultModele();
return getDefaultTemplateId();
} else {
return modele;
}
162,23 → 252,24
return rowModele.getString("NOM");
}
}
return getDefaultModele();
return getDefaultTemplateId();
}
 
public abstract Future<File> genere(final boolean visu, final boolean impression);
public abstract Future<SheetXml> createDocumentAsynchronous();
 
public abstract String getFileName();
 
private String getOOName() {
return getValidFileName(getFileName()) + ".ods";
public void createDocument() throws InterruptedException, ExecutionException {
createDocumentAsynchronous().get();
}
 
private String getPDFName() {
return getValidFileName(getFileName()) + ".pdf";
}
/**
* get the File that is, or must be generated.
*
* @return a file (not null)
* */
public abstract File getGeneratedFile();
 
private String getOO1Name() {
return getValidFileName(getFileName()) + ".sxc";
public File getGeneratedPDFFile() {
return SheetUtils.getFileWithExtension(getGeneratedFile(), ".pdf");
}
 
public SQLRow getRowLanguage() {
190,64 → 281,49
}
 
/**
* retourne l'emplacement de destination d'un Tuple<id (ex:LocationDevis), Nom (ex:Devis)>
*/
public static String getLocationForTuple(Tuple2<String, String> t, boolean pdf) {
 
final String stringProperty = TemplateNXProps.getInstance().getStringProperty(t.get0() + (pdf ? "PDF" : "OO"));
if (stringProperty.equalsIgnoreCase(TemplateNXProps.getInstance().getDefaultStringValue())) {
return stringProperty + File.separator + t.get1();
} else {
return stringProperty;
}
}
 
private File getFile() {
if (this.f != null) {
return f;
}
File f = new File(this.locationOO + File.separator + getOOName());
* Creates the document if needed and returns the generated file (OpenDocument)
* */
public File getOrCreateDocumentFile() throws Exception {
File f = getGeneratedFile();
if (!f.exists()) {
File f2 = new File(this.locationOO + File.separator + getOO1Name());
if (f2.exists()) {
return f2;
return createDocumentAsynchronous().get().getGeneratedFile();
} else {
return f;
}
} else {
return f;
}
}
 
public File getFilePDF() {
File f = new File(this.locationPDF + File.separator + getPDFName());
return f;
}
/**
* Open the document with the native application
*
* @param synchronous
* */
public void openDocument(boolean synchronous) {
Runnable r = new Runnable() {
 
public File getFileWithoutExt() {
File f = new File(this.locationPDF + File.separator + getValidFileName(getFileName()));
return f;
}
 
public File getFileODS() {
File f = new File(this.locationOO + File.separator + getOOName());
return f;
}
 
public void showDocument() {
final File f = getFile();
@Override
public void run() {
File f;
try {
f = getOrCreateDocumentFile();
OOUtils.open(f);
} catch (IOException e) {
ExceptionHandler.handle("Impossible d'ouvrir " + f.getAbsolutePath(), e);
} catch (Exception e) {
ExceptionHandler.handle("Impossible d'ouvrir le document.", e);
}
}
};
if (synchronous) {
r.run();
} else {
Thread thread = new Thread(r, "openDocument: " + getGeneratedFile().getAbsolutePath());
thread.setDaemon(true);
thread.start();
}
 
public void showPreviewDocument() {
if (!isFileOOExist()) {
genere(false, false);
}
final File f = getFile();
 
public void showPreviewDocument() throws Exception {
File f = null;
f = getOrCreateDocumentFile();
PreviewFrame.show(f);
}
 
257,9 → 333,10
}
 
public void fastPrintDocument(short copies) {
final File f = getFile();
 
try {
final File f = getOrCreateDocumentFile();
 
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
 
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, true);
295,9 → 372,9
}
 
public void printDocument() {
final File f = getFile();
 
try {
final File f = getOrCreateDocumentFile();
 
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
 
320,20 → 397,10
}
}
 
public boolean isFileOOExist() {
final File f = getFile();
return f.exists();
}
 
public SQLRow getSQLRow() {
return this.row;
}
 
public boolean isFileODSExist() {
final File f = getFileODS();
return f.exists();
}
 
/**
* Remplace tous les caracteres non alphanumeriques (seul le _ est autorisé) par un -. Cela
* permet d'avoir toujours un nom de fichier valide.
341,14 → 408,14
* @param fileName nom du fichier à créer ex:FACTURE_2007/03/001
* @return un nom fichier valide ex:FACTURE_2007-03-001
*/
public static String getValidFileName(String fileName) {
StringBuffer result = new StringBuffer(fileName.length());
static String getValidFileName(String fileName) {
final StringBuffer result = new StringBuffer(fileName.length());
for (int i = 0; i < fileName.length(); i++) {
char c = fileName.charAt(i);
char ch = fileName.charAt(i);
 
// Si c'est un caractere alphanumerique
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_') || (c == ' ')) {
result.append(c);
if (Character.isLetterOrDigit(ch) || (ch == '_') || (ch == ' ')) {
result.append(ch);
} else {
result.append('-');
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetUtils.java
13,6 → 13,8
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileOutputStream;
36,16 → 38,8
 
public class SheetUtils {
 
static SheetUtils instance;
 
public static SheetUtils getInstance() {
if (instance == null) {
instance = new SheetUtils();
}
return instance;
}
 
public File convertToOldFile(String fileName, File pathDest, File fDest) {
public static File convertToOldFile(String fileName, File pathDest, File fDest) {
// FIXME: !!!!!!!!
return convertToOldFile(fileName, pathDest, fDest, ".ods");
}
 
57,7 → 51,7
* @param fDest
* @return
*/
public File convertToOldFile(String fileName, File pathDest, File fDest, String extension) {
public static File convertToOldFile(String fileName, File pathDest, File fDest, String extension) {
if (fDest.exists()) {
int i = 0;
String destName = fileName;
92,7 → 86,7
return fDest;
}
 
public List<File> getHistorique(final String fileName, File pathDest) {
public static List<File> getHistorique(final String fileName, File pathDest) {
File pathOld = new File(pathDest, "Historique");
File[] files = pathOld.listFiles(new FilenameFilter() {
 
118,44 → 112,24
return result;
}
 
public static void main(String[] args) {
final OpenDocument doc = new OpenDocument(new File("E:/Facture_FACT1108-5785.ods"));
try {
SheetUtils.getInstance().convert2PDF(doc, new File("E:/test"), "test");
} catch (Exception exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate) throws Exception {
 
public void convert2PDF(final OpenDocument doc, final File f, final String fileName) throws Exception {
 
SwingUtilities.invokeLater(new Runnable() {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// TODO Raccord de méthode auto-généré
 
// Open the PDF document
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
File outFile = new File(f.getParent(), fileName + ".pdf");
FileOutputStream fileOutputStream;
 
try {
 
fileOutputStream = new FileOutputStream(outFile);
FileOutputStream fileOutputStream = new FileOutputStream(pdfFileToCreate);
 
// Create the writer
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
writer.setPdfVersion(PdfWriter.VERSION_1_6);
writer.setFullCompression();
// writer.setPageEmpty(true);
 
document.open();
// System.out.println(writer.getPageNumber());
// // Create a template and a Graphics2D object
// com.itextpdf.text.Rectangle pageSize = document.getPageSize();
// int w = (int) (pageSize.getWidth() * 0.9);
// int h = (int) (pageSize.getHeight() * 0.95);
 
PdfContentByte cb = writer.getDirectContent();
 
190,11 → 164,27
// writer.close();
fileOutputStream.close();
 
} catch (Exception exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
} catch (Exception originalExn) {
ExceptionHandler.handle("Impossible de créer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn);
}
}
});
}
 
/**
* Get a new file with an other extension
*
* @param the file (ex: Test.ods)
* @param the extension (ex: pdf)
* */
static File getFileWithExtension(File file, String extension) {
if (!extension.startsWith(".")) {
extension = "." + extension;
}
String name = file.getName();
int i = name.lastIndexOf(".");
name = name.substring(0, i) + extension;
final File f = new File(file.getParent(), name);
return f;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetInterface.java
18,11 → 18,12
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.StringUtils;
 
import java.io.File;
import java.util.HashMap;
import java.util.Map;
 
 
public abstract class SheetInterface {
 
// SQLRow de l'élément de la table qui est utilisé pour la génération
46,12 → 47,6
// modele du document
protected String modele;
 
// emplacement du fichier OO généré
protected String locationOO;
 
// emplacement du fichier PDF généré
protected String locationPDF;
 
// nom du futur fichier
protected String fileName;
 
64,14 → 59,6
 
protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
 
public String getLocationOO() {
return this.locationOO;
}
 
public String getLocationPDF() {
return this.locationPDF;
}
 
public int getNbPage() {
return this.nbPage;
}
114,6 → 101,17
return this.mCell;
}
 
protected abstract String getYear();
 
public File getDocumentOutputDirectory() {
return new File(DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(this.getTemplateId()), getYear());
}
 
public File getPDFOutputDirectory() {
return new File(DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.getTemplateId()), getYear());
}
 
protected abstract void createMap();
 
public abstract String getTemplateId();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java
154,7 → 154,7
for (TableModelListener listener : l) {
liste.getListe().getTableModel().addTableModelListener(listener);
if (elementSheet.get(liste.getElement()) != null) {
liste.getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(liste.getListe(), elementSheet.get(liste.getElement())));
liste.getListe().addIListeActions(new MouseSheetXmlListeListener(elementSheet.get(liste.getElement())).getRowActions());
}
}
}
228,7 → 228,7
 
setRenderer(liste);
if (elementSheet.get(liste.getElement()) != null) {
liste.getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(liste.getListe(), elementSheet.get(liste.getElement())));
liste.getListe().addIListeActions(new MouseSheetXmlListeListener(elementSheet.get(liste.getElement())).getRowActions());
}
liste.getListe().setSQLEditable(false);
liste.setOpaque(false);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/action/ListeDesAvoirsFournisseurAction.java
33,7 → 33,7
public JFrame createFrame() {
final IListFrame frame = new IListFrame(new ListeGestCommEltPanel(Configuration.getInstance().getDirectory().getElement("AVOIR_FOURNISSEUR")));
 
frame.getPanel().getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(frame.getPanel().getListe(), AvoirFournisseurXmlSheet.class));
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(AvoirFournisseurXmlSheet.class).getRowActions());
frame.getPanel().getListe().setSQLEditable(false);
return frame;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
35,6 → 35,7
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
79,6 → 80,17
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
// Numero du commande
c.gridx = 0;
c.weightx = 0;
311,7 → 323,6
 
panel.add(totalTTC, c);
 
 
table.getModel().addTableModelListener(new TableModelListener() {
 
public void tableChanged(TableModelEvent e) {
362,15 → 373,16
this.table.createArticle(idCommande, this.getElement());
 
// generation du document
CommandeXmlSheet sheet = new CommandeXmlSheet(getTable().getRow(idCommande));
sheet.genere(this.checkVisu.isSelected(), this.checkImpression.isSelected());
final CommandeXmlSheet sheet = new CommandeXmlSheet(getTable().getRow(idCommande));
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(this.checkVisu.isSelected(), this.checkImpression.isSelected(), true);
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(CommandeSQLElement.class).equalsIgnoreCase(this.numeroUniqueCommande.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(this.tableNum);
int val = this.tableNum.getRow(2).getInt("COMMANDE_CLIENT_START");
int val = this.tableNum.getRow(2).getInt("COMMANDE_START");
val++;
rowVals.put("COMMANDE_CLIENT_START", new Integer(val));
rowVals.put("COMMANDE_START", new Integer(val));
 
try {
rowVals.update(2);
419,8 → 431,10
this.table.createArticle(getSelectedID(), this.getElement());
 
// generation du document
CommandeXmlSheet dSheet = new CommandeXmlSheet(getTable().getRow(getSelectedID()));
dSheet.genere(this.checkVisu.isSelected(), this.checkImpression.isSelected());
final CommandeXmlSheet sheet = new CommandeXmlSheet(getTable().getRow(getSelectedID()));
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(this.checkVisu.isSelected(), this.checkImpression.isSelected(), true);
 
}
 
public void setDefaults() {
454,6 → 468,7
rowVals.put("T_SERVICE", Long.valueOf(0));
rowVals.put("T_TVA", Long.valueOf(0));
rowVals.put("T_TTC", Long.valueOf(0));
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(CommandeSQLElement.class));
 
return rowVals;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/SaisieAchatSQLComponent.java
34,6 → 34,7
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
120,6 → 121,17
this.textIdSource = new JTextField();
this.textSource = new JTextField();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
/*******************************************************************************************
* * RENSEIGNEMENTS
******************************************************************************************/
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesClientAction.java
22,6 → 22,10
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
63,43 → 67,49
frame.getPanel().add(legendePanel, c);
JTable table = frame.getPanel().getListe().getJTable();
for (int i = 0; i < table.getColumnCount(); i++) {
// if (table.getColumnClass(i) == Long.class || table.getColumnClass(i) ==
// if (table.getColumnClass(i) == Long.class ||
// table.getColumnClass(i) ==
// BigInteger.class) {
table.getColumnModel().getColumn(i).setCellRenderer(rend);
// }
}
 
frame.getPanel().getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(frame.getPanel().getListe(), CommandeClientXmlSheet.class) {
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(CommandeClientXmlSheet.class) {
@Override
public List<AbstractAction> addToMenu() {
public List<RowAction> addToMenu() {
// Transfert vers facture
AbstractAction bonAction = (new AbstractAction("Transfert vers BL") {
PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction("Transfert vers BL") {
public void actionPerformed(ActionEvent e) {
transfertBonLivraisonClient(frame.getPanel().getListe().getSelectedRow());
transfertBonLivraisonClient(IListe.get(e).getSelectedRow());
}
});
}, false);
 
// Transfert vers facture
AbstractAction factureAction = (new AbstractAction("Transfert vers facture") {
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction("Transfert vers facture") {
public void actionPerformed(ActionEvent e) {
transfertFactureClient(frame.getPanel().getListe().getSelectedRow());
transfertFactureClient(IListe.get(e).getSelectedRow());
}
});
}, false);
 
// Transfert vers commande
AbstractAction cmdAction = (new AbstractAction("Transfert vers commande fournisseur") {
PredicateRowAction cmdAction = new PredicateRowAction(new AbstractAction("Transfert vers commande fournisseur") {
public void actionPerformed(ActionEvent e) {
CommandeClientSQLElement elt = (CommandeClientSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
elt.transfertCommande(frame.getPanel().getListe().getSelectedRow().getID());
elt.transfertCommande(IListe.get(e).getSelectedId());
}
});
List<AbstractAction> l = new ArrayList<AbstractAction>();
 
}, false);
 
cmdAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
List<RowAction> l = new ArrayList<RowAction>();
l.add(bonAction);
l.add(factureAction);
l.add(cmdAction);
return l;
}
});
}.getRowActions());
 
return frame;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesAction.java
21,6 → 21,10
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
 
import java.awt.event.ActionEvent;
import java.util.ArrayList;
39,29 → 43,33
public JFrame createFrame() {
final IListFrame frame = new IListFrame(new ListeAddPanel(Configuration.getInstance().getDirectory().getElement("COMMANDE")));
 
frame.getPanel().getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(frame.getPanel().getListe(), CommandeXmlSheet.class) {
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(CommandeXmlSheet.class) {
@Override
public List<AbstractAction> addToMenu() {
public List<RowAction> addToMenu() {
// Transfert vers BR
AbstractAction bonAction = (new AbstractAction("Transfert vers BR") {
PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction("Transfert vers BR") {
public void actionPerformed(ActionEvent e) {
transfertBonReceptionClient(frame.getPanel().getListe().getSelectedRow());
transfertBonReceptionClient(IListe.get(e).getSelectedRow());
}
});
}, false);
 
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
// Transfert vers facture
AbstractAction factureAction = (new AbstractAction("Transfert vers facture") {
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction("Transfert vers facture") {
public void actionPerformed(ActionEvent e) {
transfertFactureFournisseur(frame.getPanel().getListe().getSelectedRow());
transfertFactureFournisseur(IListe.get(e).getSelectedRow());
}
});
}, false);
 
List<AbstractAction> l = new ArrayList<AbstractAction>();
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
List<RowAction> l = new ArrayList<RowAction>();
l.add(bonAction);
l.add(factureAction);
return l;
}
});
}.getRowActions());
 
return frame;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
37,6 → 37,7
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.TitledSeparator;
91,6 → 92,17
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
this.textTotalHT.setOpaque(false);
this.textTotalTVA.setOpaque(false);
this.textTotalTTC.setOpaque(false);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
245,7 → 245,7
// final float qteShow = qteNvlle;
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticle));
 
rowValsElt.put("ID_STYLE", 2);
rowValsElt.put("QTE", Math.round(rowArticle.getInt("QTE_MIN") - qteNvlle));
rowValsElt.put("ID_TAXE", rowValsElt.getObject("ID_TAXE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/FicheClientXmlSheet.java
13,38 → 13,31
package org.openconcerto.erp.core.customerrelationship.customer.report;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
 
public class FicheClientXmlSheet extends AbstractSheetXml {
public class FicheClientXmlSheet extends AbstractSheetXMLWithDate {
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
public static final String TEMPLATE_ID = "FicheClient";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
public FicheClientXmlSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("DevisPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("CLIENT");
Calendar cal = Calendar.getInstance();
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true) + File.separator + cal.get(Calendar.YEAR);
}
 
@Override
public String getDefaultModele() {
return "FicheClient";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
return getValidFileName("FicheClient_" + new Date().getTime());
@Override
public String getName() {
return "FicheClient_" + new Date().getTime();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
44,6 → 44,7
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
 
86,8 → 87,11
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
l.add("FORME_JURIDIQUE");
// l.add("FORME_JURIDIQUE");
l.add("NOM");
if (getTable().getFieldsName().contains("LOCALISATION")) {
l.add("LOCALISATION");
}
l.add("RESPONSABLE");
l.add("ID_ADRESSE");
l.add("TEL");
115,9 → 119,13
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("FORME_JURIDIQUE");
// l.add("FORME_JURIDIQUE");
l.add("NOM");
if (getTable().getFieldsName().contains("LOCALISATION")) {
l.add("LOCALISATION");
} else {
l.add("CODE");
}
return l;
}
 
234,7 → 242,20
this.add(boxPays, c);
this.addView(boxPays, "ID_PAYS");
}
 
if (getTable().getFieldsName().contains("LOCALISATION")) {
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel comp2 = new JLabel(getLabelFor("LOCALISATION"));
comp2.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(comp2, c);
JTextField loc = new JTextField();
c.gridx++;
c.weightx = 1;
// DefaultGridBagConstraints.lockMinimumSize(boxPays);
this.add(loc, c);
this.addView(loc, "LOCALISATION");
}
// Numero intracomm
JLabel labelIntraComm = new JLabel("N° TVA");
labelIntraComm.setHorizontalAlignment(SwingConstants.RIGHT);
380,6 → 401,17
// Secteur activité
final boolean customerIsKD;
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
// Adresse
c.gridx = 0;
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ExerciceCommonSQLElement.java
123,6 → 123,9
 
@Override
public synchronized ValidState getValidState() {
if (this.dateDeb.getValue() == null || this.dateFin.getValue() == null) {
return new ValidState(false, "Date de début ou de fin d'exercice non définie");
}
return super.getValidState().and(ValidState.createCached(this.dateDeb.getValue().before(this.dateFin.getValue()), "Date de début après date de fin"));
}
};
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/BalanceAgeeListeSheetXML.java
15,7 → 15,6
 
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
23,7 → 22,6
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.Tuple2;
 
import java.util.ArrayList;
import java.util.Calendar;
34,33 → 32,26
 
public class BalanceAgeeListeSheetXML extends AbstractListeSheetXml {
 
// private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
private Date deb, fin;
public static String TEMPLATE_ID = "Balance agée";
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public BalanceAgeeListeSheetXML(Date deb, Date fin) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.deb = deb;
this.fin = fin;
 
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
}
 
@Override
public String getDefaultModele() {
public String getDefaultTemplateId() {
return "BalanceAgee";
}
 
public String getFileName() {
return getValidFileName("BalanceAgee" + new Date().getTime());
@Override
public String getName() {
return "BalanceAgee" + new Date().getTime();
}
 
protected void createListeValues() {
 
SQLElement ecr = Configuration.getInstance().getDirectory().getElement("ECRITURE");
SQLElement cpt = Configuration.getInstance().getDirectory().getElement("COMPTE_PCE");
SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
106,7 → 97,6
long time = c.getTimeInMillis() - date;
long day = time / 86400000;
if (day < 0) {
// System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
continue;
}
final SQLRow rowCpt = sqlRow.getForeignRow("ID_COMPTE_PCE");
185,7 → 175,7
valuesTab.add(e);
}
}
Map<String, Object> totalMap = new HashMap<String, Object>();
final Map<String, Object> totalMap = new HashMap<String, Object>();
totalMap.put("NOM", "TOTAL");
totalMap.put("30", total30 / 100.0);
totalMap.put("60", total60 / 100.0);
194,29 → 184,7
totalMap.put("TOTAL", totalFull / 100.0);
valuesTab.add(totalMap);
 
// Map<String, Object> values = this.mapAllSheetValues.get(0);
// if (values == null) {
// values = new HashMap<String, Object>();
// }
// valuesHA.put("TOTAL", totalHA);
// valuesE.put("TOTAL_HA", totalHA);
// valuesE.put("TOTAL", totalE);
// valuesE.put("TOTAL_VT", totalTPVTTC);
// values.put("TOTAL", totalVC);
// values.put("TOTAL_MARGE", totalTPVTTC - totalTPA);
//
// valuesE.put("TOTAL_GLOBAL", totalTPVTTC + totalHA);
// values.put("TOTAL_PA", totalTPA);
// values.put("TOTAL_PV_TTC", totalTPVTTC);
//
// String periode = "Période Du " + dateFormat.format(this.du) + " au " +
// dateFormat.format(this.au);
// values.put("DATE", periode);
// valuesHA.put("DATE", periode);
// valuesE.put("DATE", periode);
 
this.listAllSheetValues.put(0, valuesTab);
// this.mapAllSheetValues.put(0, values);
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/JournauxSheet.java
57,6 → 57,9
protected int lettrage;
private String compteDeb, compteEnd;
 
public static String TEMPLATE_ID = "Journaux";
public static String TEMPLATE_PROPERTY_NAME = "LocationJournaux";
 
public static void setSize(int debut, int fin) {
debutFill = debut;
endFill = fin;
66,10 → 69,14
setSize(7, 68);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationJournaux", "Journaux");
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
protected String getYear() {
return "";
}
 
public JournauxSheet(int[] id, Date du, Date au, int lettrage, String compteDeb, String compteEnd) {
78,8 → 85,6
cal.setTime(au);
this.printer = PrinterNXProps.getInstance().getStringProperty("JournauxPrinter");
this.modele = "Journaux.ods";
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
this.dateAu = au;
this.dateDu = du;
this.idS = id;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheet.java
16,7 → 16,6
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.generationDoc.SheetInterface;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.Configuration;
28,10 → 27,8
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
 
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
66,6 → 63,9
private boolean centralFourn = false;
int idJrnlExclude = -1;
 
public static String TEMPLATE_ID = "Grand Livre";
public static String TEMPLATE_PROPERTY_NAME = "LocationGrandLivre";
 
public static void setSize(int debut, int fin) {
debutFill = debut;
endFill = fin;
75,10 → 75,9
setSize(7, 69);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationGrandLivre", "Grand Livre");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
protected String getYear() {
return "";
}
 
public GrandLivreSheet(Date du, Date au, String compteDep, String compteEnd, int lettrage, boolean cumul, boolean excludeCptSolde, boolean centralClient, boolean centralFourn, int idJrnlExclude) {
89,8 → 88,6
this.idJrnlExclude = idJrnlExclude;
this.printer = PrinterNXProps.getInstance().getStringProperty("GrandLivrePrinter");
this.modele = "GrandLivre.ods";
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
this.dateAu = au;
this.dateDu = du;
this.compteDeb = compteDep.trim();
621,4 → 618,10
 
return map;
}
 
@Override
public String getTemplateId() {
// TODO Auto-generated method stub
return TEMPLATE_ID;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/BalanceSheet.java
14,8 → 14,8
package org.openconcerto.erp.core.finance.accounting.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetInterface;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
23,9 → 23,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
42,7 → 40,8
private boolean centralClient, centralFourn;
private final static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
private final static DateFormat dateFormatEcr = DateFormat.getDateInstance(DateFormat.SHORT);
 
public static String TEMPLATE_ID = "Balance";
public static String TEMPLATE_PROPERTY_NAME = "LocationBalance";
private Date dateDu, dateAu;
private String compteDeb, compteEnd;
 
56,10 → 55,14
 
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationBalance", "Balance");
@Override
protected String getYear() {
return "";
}
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
public BalanceSheet(Date du, Date au, String compteDeb, String compteEnd, boolean centralClient, boolean centralFourn) {
72,10 → 75,11
this.nbRowsPerPage = 72;
this.printer = PrinterNXProps.getInstance().getStringProperty("BalancePrinter");
this.modele = "Balance.ods";
final String locationForTuple = SheetXml.getLocationForTuple(tuple, false);
System.err.println("Emplacement balance :::: " + locationForTuple);
this.locationOO = locationForTuple + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
 
final DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
 
// this.locationOO = storage.getDocumentOutputDirectory(TEMPLATE_ID);
// this.locationPDF = storage.getPDFOutputDirectory(TEMPLATE_ID);
this.dateAu = au;
this.dateDu = du;
this.compteDeb = compteDeb;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/BalanceAgeePanel.java
66,19 → 66,10
BalanceAgeeListeSheetXML l = new BalanceAgeeListeSheetXML(dateDeb.getDate(), dateFin.getDate());
 
try {
l.genere(false, false).get();
// FIXME Probleme avec l'odsviewer
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
l.showDocument();
} else {
l.showPreviewDocument();
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
l.createDocument();
l.openDocument(false);
} catch (Exception e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/GenerationPointagePanel.java
13,7 → 13,6
package org.openconcerto.erp.core.finance.accounting.ui;
 
 
import org.openconcerto.erp.generationDoc.gestcomm.PointageXmlSheet;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
69,7 → 68,6
 
this.add(this.spinYear, c);
 
JPanel panelButton = new JPanel();
panelButton.add(this.gen);
panelButton.add(this.close);
100,7 → 98,8
int mois = this.combo.getValue() - 2;
int year = Integer.valueOf(this.spinYear.getValue().toString());
PointageXmlSheet sheet = new PointageXmlSheet(mois, year);
sheet.genere(true, false);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
} else {
if (e.getSource() == this.close) {
((JFrame) SwingUtilities.getRoot(this)).dispose();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/action/ListeDesRelancesAction.java
26,6 → 26,7
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
103,14 → 104,20
// Impression
AbstractAction actionPrintFact = new AbstractAction("Imprimer la facture") {
public void actionPerformed(ActionEvent e) {
final Thread t = new Thread(new Runnable() {
 
VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowRelance.getForeignRow("ID_SAISIE_VENTE_FACTURE"));
if (sheet.getFileODS().exists()) {
sheet.fastPrintDocument();
} else {
sheet.genere(false, true);
@Override
public void run() {
try {
printInvoice(rowRelance);
} catch (Exception e) {
ExceptionHandler.handle("Impression impossible", e);
}
}
});
t.start();
 
}
};
menu.add(actionPrintFact);
 
118,14 → 125,19
 
AbstractAction actionPrintBoth = new AbstractAction("Imprimer la facture et la relance") {
public void actionPerformed(ActionEvent e) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
s.fastPrintDocument();
VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowRelance.getForeignRow("ID_SAISIE_VENTE_FACTURE"));
if (sheet.getFileODS().exists()) {
sheet.fastPrintDocument();
} else {
sheet.genere(false, true);
printInvoice(rowRelance);
} catch (Exception e) {
ExceptionHandler.handle("Impression impossible", e);
}
}
});
t.start();
}
};
menu.add(actionPrintBoth);
 
138,13 → 150,17
}
});
 
// Générer
// Créer la fiche de relance
menu.add(new AbstractAction("Créer la fiche de relance") {
public void actionPerformed(ActionEvent e) {
 
try {
FicheRelanceSheet sheet = new FicheRelanceSheet(rowRelance);
sheet.genere(true, false);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
} catch (Exception ex) {
ExceptionHandler.handle("Impression impossible", ex);
}
}
});
 
menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
159,4 → 175,11
 
public void mouseExited(MouseEvent e) {
}
 
private void printInvoice(final SQLRow rowRelance) throws Exception {
final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowRelance.getForeignRow("ID_SAISIE_VENTE_FACTURE"));
sheet.getOrCreateDocumentFile();
sheet.fastPrintDocument();
sheet.showPrintAndExport(false, false, true);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/FichePayeSheet.java
14,8 → 14,8
package org.openconcerto.erp.core.humanresources.payroll.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetInterface;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.SpreadSheetGeneratorGestComm;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.map.model.Ville;
26,7 → 26,6
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.text.DateFormat;
163,26 → 162,38
 
// Emplacement des fichiers générés
public static String getLocation(int id, int type) {
 
return getLocation(tableFiche.getRow(id), type);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationFichePaye", "Fiche de paye");
public static final String TEMPLATE_ID = "Fiche de paye";
public static final String TEMPLATE_PROPERTY_NAME = "LocationFichePaye";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
@Override
protected String getYear() {
// TODO Auto-generated method stub
return this.row.getString("ANNEE");
}
 
public static String getLocation(SQLRow r, int type) {
DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
String path;
if (type == FichePayeSheet.typeOO) {
path = storage.getDocumentOutputDirectory(TEMPLATE_ID).getAbsolutePath();
} else {
path = storage.getPDFOutputDirectory(TEMPLATE_ID).getAbsolutePath();
}
 
return SheetXml.getLocationForTuple(tuple, !(type == FichePayeSheet.typeOO)) + File.separator + r.getString("ANNEE");
return path + File.separator + r.getString("ANNEE");
}
 
private void init() {
this.modele = "FichePaye.ods";
this.printer = PrinterNXProps.getInstance().getStringProperty("FichePayePrinter");
this.locationOO = getLocation(this.row, typeOO);
this.locationPDF = getLocation(this.row, typePDF);
}
 
protected void createMap() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/LivrePayeSheet.java
60,18 → 60,18
setSize(8, 65, 3);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationLivrePaye", "Livre de paye");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
protected String getYear() {
return "";
}
 
public static final String TEMPLATE_ID = "Livre de paye";
public static final String TEMPLATE_PROPERTY_NAME = "LocationLivrePaye";
 
public LivrePayeSheet(int moisDu, int moisAu, String annee) {
super();
this.printer = PrinterNXProps.getInstance().getStringProperty("LivrePayePrinter");
this.modele = "LivrePaye.ods";
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + annee;
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + annee;
this.moisAu = moisAu;
this.moisDu = moisDu;
this.annee = annee;
96,6 → 96,11
this.mCell.put("A" + row, "Période de " + rowMoisDu.getString("NOM") + " à " + rowMoisAu.getString("NOM") + " " + this.annee);
}
 
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
protected void createMap() {
 
this.mapReplace = new HashMap();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/EtatChargesPayeSheet.java
57,19 → 57,24
setSize(7, 66);
}
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationEtatChargesPaye", "Etat des charges");
public static String TEMPLATE_ID = "Etat des charges";
public static String TEMPLATE_PROPERTY_NAME = "LocationEtatChargesPaye";
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
@Override
protected String getYear() {
return "";
}
 
public EtatChargesPayeSheet(int moisDu, int moisAu, String annee) {
super();
 
this.printer = PrinterNXProps.getInstance().getStringProperty("EtatChargesPayePrinter");
this.modele = "EtatChargesPaye.ods";
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + annee;
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + annee;
this.moisAu = moisAu;
this.moisDu = moisDu;
this.annee = annee;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/report/N4DS.java
New file
0,0 → 1,458
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.humanresources.employe.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
 
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
 
public class N4DS {
 
private static DateFormat format = new SimpleDateFormat("ddMMyyyy");
private ComptaPropsConfiguration conf = ((ComptaPropsConfiguration) Configuration.getInstance());
private long masseSalarialeBrute;
private static final byte[] retour = "'\n".getBytes();
private PrintStream stream = null;
 
// FIXME Salarie renvoye
 
/**
* Déclaration normale (type 51)
* */
public N4DS() {
 
}
 
public void createDocument() {
masseSalarialeBrute = 0;
File f = new File("N4DS_" + format.format(new Date()) + ".txt");
 
try {
 
stream = new PrintStream(f, "ISO-8859-1");
 
SQLElement eltSalarie = this.conf.getDirectory().getElement("SALARIE");
 
// Infos emetteur
SQLRow rowSociete = this.conf.getRowSociete();
 
writeS10(stream, rowSociete);
 
writeS20(stream, rowSociete);
 
SQLSelect sel = new SQLSelect(this.conf.getBase());
sel.addSelect(eltSalarie.getTable().getKey());
 
@SuppressWarnings("unchecked")
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltSalarie.getTable()));
 
for (SQLRow row : l) {
N4DSSalarie s = new N4DSSalarie(this);
s.write(row, rowSociete);
 
}
writeS80(stream, rowSociete);
writeS90(stream);
 
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
stream.close();
}
}
}
 
private void writeS80(PrintStream stream, SQLRow rowSociete) throws IOException {
 
String siren = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(0, 9);
String nic = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(9);
 
// SIREN
write("S80.G01.00.001.001", siren);
 
// NIC
write("S80.G01.00.001.002", nic);
 
SQLRow rowAdr = rowSociete.getForeignRow("ID_ADRESSE_COMMON");
String voie = rowAdr.getString("RUE");
 
Ville ville = Ville.getVilleFromVilleEtCode(rowAdr.getString("VILLE"));
 
// Complement adresse
if (voie.contains("\n")) {
String[] sVoies = voie.split("\n");
if (sVoies.length > 0) {
voie = sVoies[0];
String complement = "";
for (int i = 1; i < sVoies.length; i++) {
complement += sVoies[i].trim() + " ";
}
if (complement.length() > 0) {
complement = complement.substring(0, complement.length() - 1);
}
 
write("S80.G01.00.003.001", complement);
}
}
 
// Voie
write("S80.G01.00.003.006", voie);
 
// TODO Code INSEE, facultatif
// stream.write("S80.G01.00.003.007",voie);
 
// FIXME Service de distribution
// stream.write("S80.G01.00.003.009",ville.getName());
 
// Code postal
write("S80.G01.00.003.010", ville.getCodepostal());
 
// Localité
write("S80.G01.00.003.012", ville.getName().toUpperCase());
 
// Code Pays, ne doit pas être renseigné pour une adresse en France
// TODO support des autres pays
// write("S80.G01.00.003.013", "");
 
// FIXME effectif déclaré
write("S80.G01.00.004.001", String.valueOf(getEffectifDeclare()));
 
// TODO Code établissement sans salarié
// write( "S80.G01.00.004.001", "2");
 
// TODO Code assujettis taxe sur salaires
write("S80.G01.00.005", "01");
 
// Code NAF etablissement
write("S80.G01.00.006", rowSociete.getString("NUM_APE"));
 
// FIXME Code section prud'homale
write("S80.G01.00.007.001", "04");
 
// TODO stecion principale dérogatoire
// write( "S80.G01.00.004.001", "2");
 
// TODO Institution Prevoyance sans salarie
// write( "S80.G01.01.001", "P0012");
// write( "S80.G01.01.002", "0003");
 
// TODO Institution retraite sans salarie
// write( "S80.G01.02.001", "G022");
 
// FIXME Code assujettissement taxe et contribution apprentissage
write("S80.G62.05.001", "01");
long totalApprentissage = Math.round(this.masseSalarialeBrute * 0.0068);
System.err.println(this.masseSalarialeBrute);
write("S80.G62.05.002.001", String.valueOf(totalApprentissage));
 
write("S80.G62.05.003", "02");
 
// FIXME Code assujettissement formation professionnelle continue
write("S80.G62.10.001", "01");
long totalFormation = Math.round(this.masseSalarialeBrute * 0.0055);
write("S80.G62.10.003.001", String.valueOf(totalFormation));
 
}
 
private void writeS90(PrintStream stream) throws IOException {
// Nombre total de rubrique + S90
write("S90.G01.00.001", String.valueOf(this.nbRubrique + 2));
 
// Nombre total de rubrique S20
write("S90.G01.00.002", String.valueOf(1));
}
 
private int nbRubrique = 0;
 
public void write(String rubriqueName, String value) throws IOException {
String tmp = rubriqueName + ",'";
stream.write(tmp.getBytes());
stream.write(value.getBytes());
stream.write(retour);
 
// if (rubriqueName.startsWith("S20")) {
// this.nbRubriqueS20++;
// }
this.nbRubrique++;
}
 
private int getEffectifDeclare() {
// FIXME ne pas inclure les intérimaires
SQLElement eltSalarie = this.conf.getDirectory().getElement("SALARIE");
SQLElement eltInfos = this.conf.getDirectory().getElement("INFOS_SALARIE_PAYE");
SQLSelect sel = new SQLSelect(eltSalarie.getTable().getBase());
sel.addSelect(eltSalarie.getTable().getKey());
Date d2 = new Date(110, 11, 31);
Where w = new Where(eltSalarie.getTable().getField("ID_INFOS_SALARIE_PAYE"), "=", eltInfos.getTable().getKey());
w = w.and(new Where(eltInfos.getTable().getField("DATE_SORTIE"), "=", (Date) null).or(new Where(eltInfos.getTable().getField("DATE_SORTIE"), ">", d2)));
 
sel.setWhere(w);
System.err.println(sel.asString());
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltSalarie.getTable()));
 
return (l == null ? 0 : l.size());
}
 
public static String normalizeString2(String s) {
s = s.toUpperCase();
String temp = Normalizer.normalize(s, Form.NFC);
temp = temp.replaceAll("-", " ");
return temp.replaceAll("[^\\p{ASCII}]", "");
}
 
private void writeS20(PrintStream stream, SQLRow rowSociete) throws IOException {
 
// Siren
 
String siren = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(0, 9);
String nic = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(9);
write("S20.G01.00.001", siren);
 
// Raison sociale
write("S20.G01.00.002", rowSociete.getString("NOM"));
 
// FIXME Debut periode
write("S20.G01.00.003.001", "01012011");
 
// FIXME Fin periode
write("S20.G01.00.003.002", "31122011");
 
// Code nature
write("S20.G01.00.004.001", "01");
 
// FIXME Code type (complement, Rectificatif, ...)
write("S20.G01.00.004.002", "51");
 
// fraction
write("S20.G01.00.005", "11");
 
// TODO debut periode rattachement
// stream.write("S20.G01.00.006.001,'","11");
 
// fin periode rattachement
// stream.write("S20.G01.00.006.002,'","11");
 
// Code devise de la déclaration
write("S20.G01.00.007", "01");
 
// NIC
write("S20.G01.00.008", nic);
 
SQLRow rowAdr = rowSociete.getForeignRow("ID_ADRESSE_COMMON");
String voie = rowAdr.getString("RUE");
 
Ville ville = Ville.getVilleFromVilleEtCode(rowAdr.getString("VILLE"));
 
// Complement adresse
if (voie.contains("\n")) {
String[] sVoies = voie.split("\n");
if (sVoies.length > 0) {
voie = sVoies[0];
String complement = "";
for (int i = 1; i < sVoies.length; i++) {
complement += sVoies[i].trim() + " ";
}
if (complement.length() > 0) {
complement = complement.substring(0, complement.length() - 1);
}
 
write("S20.G01.00.009.001", complement);
}
}
 
// Voie
write("S20.G01.00.009.006", voie);
 
// TODO Code INSEE
// stream.write("S20.G01.00.009.007",voie);
 
// FIXME Service de distribution
// stream.write("S20.G01.00.009.009",ville.getName());
 
// Code postal
write("S20.G01.00.009.010", ville.getCodepostal());
 
// Localité
write("S20.G01.00.009.012", ville.getName().toUpperCase());
 
// TODO Code Pays pour les autres pays que la France
// write("S20.G01.00.009.013","");
// write("S20.G01.00.009.016","");
 
write("S20.G01.00.013.002", "1");
// Code periodicite
// TODO déclaration autre que annuelle
write("S20.G01.00.018", "A00");
 
}
 
/**
* Strucuture S10, N4DS
* */
private void writeS10(PrintStream stream, SQLRow rowSociete) throws IOException {
 
// Siren
 
String siren = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(0, 9);
String nic = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(9);
write("S10.G01.00.001.001", siren);
 
// NIC
write("S10.G01.00.001.002", nic);
 
// Raison sociale
write("S10.G01.00.002", rowSociete.getString("NOM"));
 
SQLRow rowAdr = rowSociete.getForeignRow("ID_ADRESSE_COMMON");
String voie = rowAdr.getString("RUE");
 
Ville ville = Ville.getVilleFromVilleEtCode(rowAdr.getString("VILLE"));
 
// Complement adresse
if (voie.contains("\n")) {
String[] sVoies = voie.split("\n");
if (sVoies.length > 0) {
voie = sVoies[0];
String complement = "";
for (int i = 1; i < sVoies.length; i++) {
complement += sVoies[i] + " ";
}
if (complement.length() > 0) {
complement = complement.substring(0, complement.length() - 1);
}
 
write("S10.G01.00.003.001", complement);
}
}
 
// Voie
write("S10.G01.00.003.006", voie);
 
// TODO Code INSEE, facultatif
// stream.write("S10.G01.00.003.007",voie);
 
// TODO: Service de distribution
write("S10.G01.00.003.009", ville.getName());
 
// Code postal
write("S10.G01.00.003.010", ville.getCodepostal());
 
// Localité
write("S10.G01.00.003.012", ville.getName().toUpperCase());
 
// Code Pays, ne doit pas être renseigné pour une adresse en France
// TODO support des autres pays
// write("S10.G01.00.003.013", "");
 
// FIXME Référence de l'envoi
// Incrémenté le numéro
write("S10.G01.00.004,'", "1");
 
// Nom du logiciel
write("S10.G01.00.005", "OpenConcerto");
 
// Nom de l'éditeur
write("S10.G01.00.006", "ILM Informatique");
 
// Numéro version
// FIXME: utiliser le nuémro de version du logiciel
write("S10.G01.00.007", "1.2");
 
// Code service choisi
write("S10.G01.00.009", "40");
 
// Code envoi du fichier essai ou réel
write("S10.G01.00.010", "02");
 
// Norme utilisée
write("S10.G01.00.011", "V01X06");
 
// Code table char
write("S10.G01.00.012", "01");
 
// TODO Contact pour DADS
// Code civilite
write("S10.G01.01.001.001", "01");
// Nom Contact
// TODO Contact pour DADS
write("S10.G01.01.001.002", "MAILLARD GUILLAUME");
 
// Code domaine
// TODO Contact pour DADS
write("S10.G01.01.002", "03");
 
// Adresse mail
// TODO Contact pour DADS
write("S10.G01.01.005", "contact@ilm-informatique.fr");
 
// Tel
// TODO Contact pour DADS
write("S10.G01.01.006", "0322194472");
// TODO Contact pour DADS
 
// Fax
write("S10.G01.01.007", "0322194408");
}
 
private String getNumeroVoie(String voie) {
String numero = "";
voie = voie.trim();
for (int i = 0; i < voie.trim().length(); i++) {
char c = voie.charAt(i);
if (c >= '0' && c <= '9') {
numero += c;
} else {
break;
}
}
return numero;
}
 
private String getVoieWithoutNumber(String voie) {
voie = voie.trim();
String resultVoie = new String(voie);
 
for (int i = 0; i < voie.trim().length(); i++) {
char c = voie.charAt(i);
if (c >= '0' && c <= '9') {
resultVoie = resultVoie.substring(1);
} else {
break;
}
}
return resultVoie.trim();
}
 
public void addMasseSalarialeBrute(long baseBrute) {
this.masseSalarialeBrute += baseBrute;
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/report/N4DSSalarie.java
New file
0,0 → 1,508
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.humanresources.employe.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
 
import java.io.IOException;
import java.text.DateFormat;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
 
public class N4DSSalarie {
 
private static DateFormat format = new SimpleDateFormat("ddMMyyyy");
private ComptaPropsConfiguration conf = ((ComptaPropsConfiguration) Configuration.getInstance());
private N4DS n4ds;
 
// FIXME Salarie renvoye
 
public N4DSSalarie(N4DS n4ds) {
this.n4ds = n4ds;
}
 
public void write(SQLRow row, SQLRow rowSociete) throws IOException {
writeS30(row);
writeS41(row, rowSociete);
writeS44(row);
}
 
private void writeS44(SQLRow rowSalarie) throws IOException {
// FIXME
n4ds.write("S44.G01.00.001", "07");
n4ds.write("S44.G01.00.002", "1100");
 
}
 
private void writeS41(SQLRow rowSalarie, SQLRow rowSociete) throws IOException {
 
// FIXME Debut periode
n4ds.write("S40.G01.00.001", "01012011");
// FIXME embauche, etc...
n4ds.write("S40.G01.00.002.001", "097");
 
// FIXME Fin periode
n4ds.write("S40.G01.00.003", "31122010");
// FIXME licenciement, etc...
n4ds.write("S40.G01.00.004.001", "098");
 
// Nic de l'établissment du d'affectation du salarié
String siren = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(0, 9);
String nic = rowSociete.getString("NUM_SIRET").replaceAll(" ", "").substring(9);
n4ds.write("S40.G01.00.005", nic);
 
// Nic de l'établissment du lieu de travail du salarié
// FIXME gerer si different
n4ds.write("S40.G05.00.001", nic);
 
// FIXME n4ds.write("S40.G05.00.002", enseigne);
// Numéro, extension, nature et libellé de la voie
// FIXME n4ds.write("S40.G05.00.060.006", voie);
// Code postal
// FIXME n4ds.write("S40.G05.00.060.010", codePostal);
// FIXME n4ds.write("S40.G05.00.060.012", localite);
 
// TODO siren de l'entreprise du lieu de travail
// A remplir si different de S40.G05.00.001 n4ds.write("S40.G05.00.070",siren);
 
/**
* Situation administrative générale du salarié ou de l'agent. S40.G10.00
*/
 
// TODO: ajouter les codes emplois pour le public, etc...
n4ds.write("S40.G10.00.005", "10");
 
// TODO Code Employeur multiple
// Ici forcé en employeur unique
n4ds.write("S40.G10.00.008.001", "01");
 
// TODO Code Emploi multiple
// Ici forcé en emploi unique
n4ds.write("S40.G10.00.008.002", "01");
 
// TODO Code decalage paie
// Ici, sans décalage de paie
n4ds.write("S40.G10.00.009.001", "01");
// Ici, paiement au mois
n4ds.write("S40.G10.00.009.002", "01");
 
SQLRow rowInfos = rowSalarie.getForeignRow("ID_INFOS_SALARIE_PAYE");
SQLRow rowContrat = rowInfos.getForeignRow("ID_CONTRAT_SALARIE");
 
// Nature de l'emploi
n4ds.write("S40.G10.00.010", rowContrat.getString("NATURE"));
 
// Catégorie socio
SQLRow rowCodeEmploi = rowContrat.getForeignRow("ID_CODE_EMPLOI");
n4ds.write("S40.G10.05.011.001", rowCodeEmploi.getString("CODE"));
 
// code contrat
SQLRow rowCodeContrat = rowContrat.getForeignRow("ID_CODE_CONTRAT_TRAVAIL");
n4ds.write("S40.G10.05.012.001", rowCodeContrat.getString("CODE"));
 
// code droit contrat
SQLRow rowCodeDroitContrat = rowContrat.getForeignRow("ID_CODE_DROIT_CONTRAT");
n4ds.write("S40.G10.05.012.002", rowCodeDroitContrat.getString("CODE"));
 
// FIXME code conjoint salarie
// stream.write("S41.G01.00.012.003",rowCodeDroitContrat.getString("CODE"));
 
// code caracteristique travail
// SQLRow rowCaractAct = rowContrat.getForeignRow("ID_CODE_CARACT_ACTIVITE");
// n4ds.write("S41.G01.00.013", rowCaractAct.getString("CODE"));
 
// code statut prof
// SQLRow rowStatutProf = rowContrat.getForeignRow("ID_CODE_STATUT_PROF");
// n4ds.write("S41.G01.00.014", rowStatutProf.getString("CODE"));
 
// FIXME code statut cat convention
SQLRow rowStatutCat = rowContrat.getForeignRow("ID_CODE_STATUT_CATEGORIEL");
// n4ds.write("S41.G01.00.015.001", "01");
 
// Code statut cat agirc arrco
n4ds.write("S40.G10.05.015.002", rowStatutCat.getString("CODE"));
 
// Convention collective IDCC
SQLRow rowIDCC = rowInfos.getForeignRow("ID_IDCC");
n4ds.write("S40.G10.05.016", rowIDCC.getString("CODE"));
 
// FIXME Classement conventionnel
n4ds.write("S40.G10.05.017", "sans classement conventionnel");
 
/**
* Caisse spécifique de congés payés. S40.G10.06
*/
 
//
 
/**
* Complément salarié sous contrat de droit privé dans le secteur public. S40.G10.08
*/
// TODO secteur public
 
/**
* Situation administrative spécifique de l'agent sous statut d'emploi de droit public.
* S40.G10.10
*/
// TODO secteur public
 
/**
* Emploi supérieur antérieur de l'agent sous statut personnel de droit public. S40.G10.15
* */
// TODO secteur public
 
/**
* Départ ou retour de détachement de l'agent sous statut personnel de droit public.
* S40.G10.24
*/
// TODO secteur public
 
// FIXME Code regime de base obligatoire
// n4ds.write("S41.G01.00.018.001", "200");
 
// TODO rubrique conditionnelle
 
// if (prenom.equalsIgnoreCase("guillaume")) {
// // FIXME Durée anuelle du travail
// n4ds.write( "S41.G01.00.023.001", "99");
//
// // FIXME Durée trimestrielle du travail
// n4ds.write( "S41.G01.00.023.002", "12");
//
// // FIXME Durée mensuelle du travail
// n4ds.write( "S41.G01.00.023.003", "98");
// } else {
 
// FIXME Code unité d'expression du temps de travail
n4ds.write("S40.G15.00.001", "10");
 
// FIXME Code unité d'expression du temps de travail
n4ds.write("S40.G15.00.003", "----------------------");
// }
// TODO Code section accident travail
n4ds.write("S41.G01.00.025", "01");
 
// TODO Code risque accident travail
n4ds.write("S41.G01.00.026", "516GB");
 
// TODO Code bureau
// n4ds.write( "S41.G01.00.027", "B");
 
// Taux accident travail
float f = rowInfos.getFloat("TAUX_AT");
String tauxAT = String.valueOf(Math.round(f * 100.0));
n4ds.write("S41.G01.00.028", tauxAT);
 
// Base brute
final long baseBrute = getBaseBrute(rowSalarie);
n4ds.write("S41.G01.00.029.001", String.valueOf(baseBrute));
n4ds.addMasseSalarialeBrute(baseBrute);
 
// Code nature cotisations
n4ds.write("S41.G01.00.029.003", "01");
 
// FIXME Base brute limité plafond
n4ds.write("S41.G01.00.030.001", String.valueOf(baseBrute));
 
// CSG
n4ds.write("S41.G01.00.032.001", String.valueOf(getCSG(rowSalarie)));
 
// CRDS
n4ds.write("S41.G01.00.033.001", String.valueOf(getCSG(rowSalarie)));
 
// FIXME base brute fiscale
n4ds.write("S41.G01.00.035.001", String.valueOf(baseBrute));
 
long fraisPro = getFraisProfessionels(rowSalarie);
 
if (fraisPro > 0) {
// Montant des frais professionnels
n4ds.write("S41.G01.00.044.001", String.valueOf(fraisPro));
 
// remboursement frais pro
n4ds.write("S41.G01.00.046", "R");
}
 
// revenu d'activite net
n4ds.write("S41.G01.00.063.001", String.valueOf(getNetImp(rowSalarie)));
 
// FIXME Régimes complémentaires
// Mederic
n4ds.write("S41.G01.01.001", "G022");
n4ds.write("S41.G01.01.002", "200339139001002");
 
// UGRR
n4ds.write("S41.G01.01.001", "A700");
n4ds.write("S41.G01.01.002", "800943487");
 
// UGRC
n4ds.write("S41.G01.01.001", "C039");
n4ds.write("S41.G01.01.002", "00095913");
 
// Fillon
if (rowSalarie.getString("PRENOM").equalsIgnoreCase("ludovic") || rowSalarie.getString("PRENOM").equalsIgnoreCase("guillaume")) {
// S41.G01.06.001 Code type exonération O X ..6
n4ds.write("S41.G01.06.001", "33");
// X S41.G01.06.002.001 Base brute soumise à exonération O N ..10
n4ds.write("S41.G01.06.002.001", String.valueOf(baseBrute));
}
 
// FIXME Election Prud'homales
n4ds.write("S41.G02.00.008", String.valueOf("01"));
n4ds.write("S41.G02.00.009", String.valueOf("01"));
n4ds.write("S41.G02.00.010", String.valueOf("04"));
}
 
private long getFraisProfessionels(SQLRow rowSalarie) {
 
SQLElement eltFichePaye = this.conf.getDirectory().getElement("FICHE_PAYE");
SQLElement eltFichePayeElement = this.conf.getDirectory().getElement("FICHE_PAYE_ELEMENT");
SQLElement eltRubriqueNet = this.conf.getDirectory().getElement("RUBRIQUE_NET");
SQLSelect sel = new SQLSelect(rowSalarie.getTable().getBase());
sel.addSelect(eltFichePayeElement.getTable().getKey());
Date d = new Date(110, 0, 1);
Date d2 = new Date(110, 11, 31);
Where w = new Where(eltFichePaye.getTable().getField("DU"), d, d2);
w = w.and(new Where(eltFichePaye.getTable().getField("VALIDE"), "=", Boolean.TRUE));
w = w.and(new Where(eltFichePaye.getTable().getField("ID_SALARIE"), "=", rowSalarie.getID()));
w = w.and(new Where(eltFichePayeElement.getTable().getField("ID_FICHE_PAYE"), "=", eltFichePaye.getTable().getKey()));
w = w.and(new Where(eltFichePayeElement.getTable().getField("SOURCE"), "=", "RUBRIQUE_NET"));
 
sel.setWhere(w);
System.err.println(sel.asString());
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltFichePayeElement.getTable()));
 
float fraisPro = 0;
for (SQLRow row : l) {
int id = row.getInt("IDSOURCE");
if (id > 1) {
SQLRow rowRubrique = eltRubriqueNet.getTable().getRow(id);
if (rowRubrique.getBoolean("FRAIS_PERS")) {
fraisPro += row.getFloat("MONTANT_SAL_AJ");
}
}
}
 
return Math.round(fraisPro);
}
 
private long getBaseBrute(SQLRow rowSalarie) {
 
SQLElement eltFichePaye = this.conf.getDirectory().getElement("FICHE_PAYE");
SQLSelect sel = new SQLSelect(rowSalarie.getTable().getBase());
sel.addSelect(eltFichePaye.getTable().getKey());
Date d = new Date(110, 0, 1);
Date d2 = new Date(110, 11, 31);
Where w = new Where(eltFichePaye.getTable().getField("DU"), d, d2);
w = w.and(new Where(eltFichePaye.getTable().getField("VALIDE"), "=", Boolean.TRUE));
w = w.and(new Where(eltFichePaye.getTable().getField("ID_SALARIE"), "=", rowSalarie.getID()));
 
sel.setWhere(w);
System.err.println(sel.asString());
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltFichePaye.getTable()));
 
float brut = 0;
for (SQLRow row : l) {
brut += row.getFloat("SAL_BRUT");
}
 
return Math.round(brut);
}
 
private long getNetImp(SQLRow rowSalarie) {
 
SQLElement eltFichePaye = this.conf.getDirectory().getElement("FICHE_PAYE");
SQLSelect sel = new SQLSelect(rowSalarie.getTable().getBase());
sel.addSelect(eltFichePaye.getTable().getKey());
Date d = new Date(110, 0, 1);
Date d2 = new Date(110, 11, 31);
Where w = new Where(eltFichePaye.getTable().getField("DU"), d, d2);
w = w.and(new Where(eltFichePaye.getTable().getField("VALIDE"), "=", Boolean.TRUE));
w = w.and(new Where(eltFichePaye.getTable().getField("ID_SALARIE"), "=", rowSalarie.getID()));
 
sel.setWhere(w);
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltFichePaye.getTable()));
 
float brut = 0;
for (SQLRow row : l) {
brut += row.getFloat("NET_IMP");
}
 
return Math.round(brut);
}
 
private long getCSG(SQLRow rowSalarie) {
 
SQLElement eltFichePaye = this.conf.getDirectory().getElement("FICHE_PAYE");
SQLSelect sel = new SQLSelect(rowSalarie.getTable().getBase());
sel.addSelect(eltFichePaye.getTable().getKey());
Date d = new Date(110, 0, 1);
Date d2 = new Date(110, 11, 31);
Where w = new Where(eltFichePaye.getTable().getField("DU"), d, d2);
w = w.and(new Where(eltFichePaye.getTable().getField("VALIDE"), "=", Boolean.TRUE));
w = w.and(new Where(eltFichePaye.getTable().getField("ID_SALARIE"), "=", rowSalarie.getID()));
 
sel.setWhere(w);
List<SQLRow> l = (List<SQLRow>) this.conf.getBase().getDataSource().execute(sel.asString(), new SQLRowListRSH(eltFichePaye.getTable()));
 
float brut = 0;
for (SQLRow row : l) {
brut += row.getFloat("CSG");
}
 
return Math.round(brut);
}
 
private void writeS30(SQLRow rowSalarie) throws IOException {
 
SQLRow rowEtatCivil = rowSalarie.getForeignRow("ID_ETAT_CIVIL");
 
// Numero inscription
String nir = rowEtatCivil.getString("NUMERO_SS").replaceAll(" ", "");
 
if (nir.length() >= 13) {
nir = nir.substring(0, 13);
} else {
JOptionPane.showMessageDialog(new JFrame(), "Numéro d'inscription pour le salarié " + rowSalarie.getString("PRENOM") + " " + rowSalarie.getString("NOM") + " incorrect");
 
}
n4ds.write("S30.G01.00.001", nir);
 
// Nom
n4ds.write("S30.G01.00.002", rowSalarie.getString("NOM"));
 
// Prenoms
// FIXME: regarder pour les prénoms pas seulement le 1er
n4ds.write("S30.G01.00.003", rowSalarie.getString("PRENOM"));
 
// Code civilite
final SQLRow rowTitre = rowSalarie.getForeignRow("ID_TITRE_PERSONNEL");
final String civilite = rowTitre.getString("NOM").toLowerCase();
if (civilite.contains("monsieur")) {
n4ds.write("S30.G01.00.007", "01");
} else if (civilite.contains("madame")) {
n4ds.write("S30.G01.00.007", "02");
} else if (civilite.contains("mademoiselle") || civilite.contains("mlle")) {
n4ds.write("S30.G01.00.007", "03");
} else {
JOptionPane.showMessageDialog(new JFrame(), "Civilité incorrecte pour " + rowSalarie.getString("PRENOM") + " " + rowSalarie.getString("NOM") + " (" + civilite + ")");
}
SQLRow rowAdr = rowEtatCivil.getForeignRow("ID_ADRESSE");
String voie = rowAdr.getString("RUE");
 
Ville ville = Ville.getVilleFromVilleEtCode(rowAdr.getString("VILLE"));
 
// Complement adresse
if (voie.contains("\n")) {
String[] sVoies = voie.split("\n");
if (sVoies.length > 0) {
voie = sVoies[0].trim();
String complement = "";
for (int i = 1; i < sVoies.length; i++) {
complement += sVoies[i].trim() + " ";
}
if (complement.length() > 0) {
complement = complement.substring(0, complement.length() - 1);
}
 
n4ds.write("S30.G01.00.008.001", complement);
}
}
 
// Numéro, extension, nature et libellé de la voie
n4ds.write("S30.G01.00.008.006", voie);
 
// Code postal
n4ds.write("S30.G01.00.008.010", ville.getCodepostal());
 
// Commune
String villeFormat = normalizeString2(ville.getName());
n4ds.write("S30.G01.00.008.012", villeFormat);
 
// Date de naissance
Date d = rowEtatCivil.getDate("DATE_NAISSANCE").getTime();
n4ds.write("S30.G01.00.009", format.format(d));
 
// Commune de naissance
String villeFormat2 = normalizeString2(rowEtatCivil.getString("COMMUNE_NAISSANCE"));
n4ds.write("S30.G01.00.010", villeFormat2);
 
SQLRow rowDept = rowEtatCivil.getForeignRow("ID_DEPARTEMENT_NAISSANCE");
 
// Code departement de naissance
n4ds.write("S30.G01.00.011", rowDept.getString("NUMERO"));
 
SQLRow rowPays = rowEtatCivil.getForeignRow("ID_PAYS_NAISSANCE");
 
// Pays naissance
String pays = rowPays.getString("NOM").toUpperCase();
n4ds.write("S30.G01.00.012", pays);
 
// Pays
n4ds.write("S30.G01.00.013", pays);
 
// Matricule Salarie
n4ds.write("S30.G10.05.001", rowSalarie.getString("CODE"));
}
 
public static String normalizeString2(String s) {
s = s.toUpperCase();
String temp = Normalizer.normalize(s, Form.NFC);
temp = temp.replaceAll("-", " ");
return temp.replaceAll("[^\\p{ASCII}]", "");
}
 
private String getNumeroVoie(String voie) {
String numero = "";
voie = voie.trim();
for (int i = 0; i < voie.trim().length(); i++) {
char c = voie.charAt(i);
if (c >= '0' && c <= '9') {
numero += c;
} else {
break;
}
}
return numero;
}
 
private String getVoieWithoutNumber(String voie) {
voie = voie.trim();
String resultVoie = new String(voie);
 
for (int i = 0; i < voie.trim().length(); i++) {
char c = voie.charAt(i);
if (c >= '0' && c <= '9') {
resultVoie = resultVoie.substring(1);
} else {
break;
}
}
return resultVoie.trim();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/action/N4DSAction.java
New file
0,0 → 1,34
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.humanresources.employe.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.humanresources.employe.report.N4DS;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class N4DSAction extends CreateFrameAbstractAction {
 
public N4DSAction() {
super();
this.putValue(Action.NAME, "Déclaration N4DS");
}
 
@Override
public JFrame createFrame() {
new N4DS().createDocument();
return new JFrame();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/action/ListeDesAvoirsClientsAction.java
66,7 → 66,7
c.anchor = GridBagConstraints.CENTER;
frame.getPanel().add(datePanel, c);
 
frame.getPanel().getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(frame.getPanel().getListe(), AvoirClientXmlSheet.class));
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(AvoirClientXmlSheet.class).getRowActions());
 
frame.getPanel().getListe().setSQLEditable(false);
return frame;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/component/AvoirClientSQLComponent.java
47,6 → 47,7
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.utils.ExceptionHandler;
205,6 → 206,17
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
this.textNom = new JTextField();
this.date = new JDate(true);
this.date.addValueListener(new PropertyChangeListener() {
668,8 → 680,7
gen.genereMouvement();
 
// generation du document
AvoirClientXmlSheet bSheet = new AvoirClientXmlSheet(row);
bSheet.genere(this.checkVisu.isSelected(), this.checkImpr.isSelected());
createAvoirClient(row);
 
} else {
ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
682,6 → 693,18
return id;
}
 
private void createAvoirClient(final SQLRow row) {
 
final AvoirClientXmlSheet bSheet = new AvoirClientXmlSheet(row);
try {
bSheet.createDocumentAsynchronous();
bSheet.showPrintAndExportAsynchronous(checkVisu.isSelected(), checkImpr.isSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de créer l'avoir", e);
}
 
}
 
@Override
public void select(SQLRowAccessor r) {
if (r != null) {
691,10 → 714,8
this.comboClient.rmValueListener(changeClientListener);
 
if (r != null) {
System.err.println("Selection Avoir");
this.table.insertFrom("ID_AVOIR_CLIENT", r.getID());
 
System.err.println(r);
// Les contacts sont filtrés en fonction du client (ID_AFFAIRE.ID_CLIENT), donc si
// l'ID_CONTACT est changé avant ID_AFFAIRE le contact ne sera pas présent dans la combo
// => charge en deux fois les valeurs
708,7 → 729,6
vals.setID(rVals.getID());
super.select(vals);
rVals.remove("ID_CLIENT");
System.err.println("Select Other vlues");
super.select(rVals);
} else {
super.select(r);
770,8 → 790,7
GenerationMvtAvoirClient gen = new GenerationMvtAvoirClient(getSelectedID(), idMvt);
gen.genereMouvement();
 
AvoirClientXmlSheet bSheet = new AvoirClientXmlSheet(row);
bSheet.genere(this.checkVisu.isSelected(), this.checkImpr.isSelected());
createAvoirClient(row);
} else {
ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
Object root = SwingUtilities.getRoot(this);
790,18 → 809,6
 
loadItem(this.table, facture, idFacture, factureElt);
 
// if (idFacture > 1) {
// SQLTable factureTable = facture.getTable();
// SQLRow row = factureTable.getRow(idFacture);
//
// int idClient = row.getInt("ID_CLIENT");
// this.selectClient.setValue(String.valueOf(idClient));
//
// Long l = (Long) row.getObject("T_HT");
// this.montantPanel.getMontantHT().setValue(String.valueOf(GestionDevise.currencyToString(l)));
//
// this.textNom.setValue("Avoir annulant Facture " + row.getString("NUMERO"));
// }
}
 
/**
854,7 → 861,7
} catch (SQLException e) {
e.printStackTrace();
}
// }
 
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/report/CommandeClientXmlSheet.java
13,23 → 13,22
package org.openconcerto.erp.core.sales.order.report;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class CommandeClientXmlSheet extends AbstractSheetXMLWithDate {
 
public class CommandeClientXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "CommandeClient";
public static final String TEMPLATE_PROPERTY_NAME = "LocationCmdCli";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationCmdCli", "Commande client");
// FIXME Prefs printer location
public CommandeClientXmlSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("cmdCliPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
47,24 → 46,13
}
}
 
// FIXME Prefs printer location
public CommandeClientXmlSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("cmdCliPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
 
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
@Override
public String getDefaultModele() {
return "CommandeClient";
public String getName() {
return "CommandeClient_" + this.row.getString("NUMERO");
}
 
public String getFileName() {
return getValidFileName("CommandeClient_" + this.row.getString("NUMERO"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/component/CommandeClientSQLComponent.java
37,6 → 37,7
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
81,6 → 82,17
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
this.comboDevis = new ElementComboBox();
 
// Numero du commande
373,8 → 385,7
}
 
public int insert(SQLRow order) {
 
int idCommande = getSelectedID();
final int idCommande;
// on verifie qu'un devis du meme numero n'a pas été inséré entre temps
if (this.numeroUniqueCommande.checkValidation()) {
 
383,10 → 394,15
 
// Création des articles
this.table.createArticle(idCommande, this.getElement());
// generation du document
 
// generation du document
try {
CommandeClientXmlSheet sheet = new CommandeClientXmlSheet(getTable().getRow(idCommande));
sheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(CommandeClientSQLComponent.this.panelOO.isVisualisationSelected(), CommandeClientSQLComponent.this.panelOO.isImpressionSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de créer la commande", e);
}
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(CommandeClientSQLElement.class).equalsIgnoreCase(this.numeroUniqueCommande.getText().trim())) {
402,6 → 418,7
}
}
} else {
idCommande = getSelectedID();
ExceptionHandler.handle("Impossible d'ajouter, numéro de commande client existant.");
Object root = SwingUtilities.getRoot(this);
if (root instanceof EditFrame) {
443,10 → 460,17
this.table.createArticle(getSelectedID(), this.getElement());
 
// generation du document
CommandeClientXmlSheet dSheet = new CommandeClientXmlSheet(getTable().getRow(getSelectedID()));
dSheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
 
try {
CommandeClientXmlSheet sheet = new CommandeClientXmlSheet(getTable().getRow(getSelectedID()));
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(CommandeClientSQLComponent.this.panelOO.isVisualisationSelected(), CommandeClientSQLComponent.this.panelOO.isImpressionSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de créer la commande", e);
}
 
}
 
public void setDefaults() {
this.resetValue();
this.numeroUniqueCommande.setText(NumerotationAutoSQLElement.getNextNumero(CommandeClientSQLElement.class));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientSQLElement.java
172,7 → 172,7
SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
 
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", rowValsElt.getLong("PA_HT") * rowValsElt.getInt("QTE"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureSQLElement.java
50,8 → 50,10
 
public class SaisieVenteFactureSQLElement extends ComptaSQLConfElement {
 
public static final String TABLENAME = "SAISIE_VENTE_FACTURE";
 
public SaisieVenteFactureSQLElement() {
super("SAISIE_VENTE_FACTURE", "une facture", "factures");
super(TABLENAME, "une facture", "factures");
}
 
protected List<String> getListFields() {
244,7 → 246,7
SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
 
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ListeVenteXmlSheet.java
26,6 → 26,7
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
42,31 → 43,33
 
private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
 
public static final String TEMPLATE_ID = "ListeVentes";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private Date du, au;
private List<SQLRow> listeIds;
JProgressBar bar;
private JProgressBar bar;
private SQLElement eltAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
private SQLElement eltEnc = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
private SQLElement eltEncElt = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT_ELEMENT");
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public ListeVenteXmlSheet(List<SQLRow> listeIds, Date du, Date au, JProgressBar bar) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.listeIds = listeIds;
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
this.du = du;
this.au = au;
this.bar = bar;
}
 
public String getDefaultModele() {
return "ListeVentes";
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
};
 
SQLElement eltAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
SQLElement eltEnc = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
SQLElement eltEncElt = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT_ELEMENT");
@Override
public String getName() {
return "JournalVentes";
}
 
protected void createListeValues() {
 
172,7 → 175,4
this.mapAllSheetValues.put(0, values);
}
 
public String getFileName() {
return getValidFileName("JournalVentes");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ListeDebiteursXmlSheet.java
15,7 → 15,6
 
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
24,7 → 23,6
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
37,20 → 35,19
 
private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public ListeDebiteursXmlSheet() {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
}
 
public String getDefaultModele() {
public String getDefaultTemplateId() {
return "ListeDebiteur";
}
 
@Override
public String getName() {
return "ListeDebiteurs";
}
 
SQLElement eltEch = Configuration.getInstance().getDirectory().getElement("ECHEANCE_CLIENT");
SQLElement eltVf = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
SQLElement eltMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT");
124,22 → 121,9
 
}
 
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// ListeDebiteursXmlSheet.this.bar.setMaximum(ListeDebiteursXmlSheet.this.listeIds.size());
// }
// });
 
// final Map<String, Object> values = new HashMap<String, Object>();
// values.put("DATE", "Du " + dateFormat.format(this.du) + " au " +
// dateFormat.format(this.au));
 
this.listAllSheetValues.put(0, listValues);
this.styleAllSheetValues.put(0, styleValues);
// this.mapAllSheetValues.put(0, values);
 
}
 
public String getFileName() {
return getValidFileName("ListeDebiteurs");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ListeFactureXmlSheet.java
23,6 → 23,7
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
33,25 → 34,26
import java.util.Map;
 
public class ListeFactureXmlSheet extends AbstractListeSheetXml {
public static final String TEMPLATE_ID = "ListeFacture";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private List<Map<String, Object>> listValues;
private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
 
private List<Integer> listeIds;
 
public static Tuple2<String, String> getTuple2Location() {
return tupleDefault;
}
 
public ListeFactureXmlSheet(List<Integer> listeIds) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.listeIds = listeIds;
this.locationOO = SheetXml.getLocationForTuple(tupleDefault, false);
this.locationPDF = SheetXml.getLocationForTuple(tupleDefault, true);
}
 
@Override
public String getDefaultModele() {
// TODO Raccord de méthode auto-généré
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
@Override
public String getName() {
return "ListeFacture";
}
 
100,7 → 102,4
this.listAllSheetValues.put(0, this.listValues);
}
 
public String getFileName() {
return getValidFileName("ListeFacture");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/VenteFactureXmlSheet.java
14,8 → 14,7
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
23,20 → 22,13
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
 
public class VenteFactureXmlSheet extends AbstractSheetXml {
public class VenteFactureXmlSheet extends AbstractSheetXMLWithDate {
 
private String startName;
public static final String TEMPLATE_ID = "VenteFacture";
public static final String TEMPLATE_PROPERTY_NAME = "LocationFacture";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationFacture", "Factures");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
public String getReference() {
return this.row.getString("NOM");
43,6 → 35,19
}
 
@Override
public String getName() {
final String startName;
if (row.getBoolean("COMPLEMENT")) {
startName = "FactureComplement_";
} else if (row.getBoolean("ACOMPTE")) {
startName = "FactureAcompte_";
} else {
startName = "Facture_";
}
return startName + this.row.getString("NUMERO");
}
 
@Override
public SQLRow getRowLanguage() {
SQLRow rowClient = this.row.getForeignRow("ID_CLIENT");
if (rowClient.getTable().contains("ID_LANGUE")) {
56,35 → 61,27
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("FacturePrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
getDefaultModele();
getDefaultTemplateId();
}
 
@Override
public String getDefaultModele() {
String modele;
public String getType() {
String type;
if (row.getBoolean("COMPLEMENT")) {
this.startName = "FactureComplement_";
modele = "VenteFactureComplement";
type = "Complement";
} else if (row.getBoolean("ACOMPTE")) {
type = "Acompte";
} else {
if (row.getBoolean("ACOMPTE")) {
this.startName = "FactureAcompte_";
modele = "VenteFactureAcompte";
} else {
this.startName = "Facture_";
modele = "VenteFacture";
type = "null";
 
}
 
return type;
}
 
return modele;
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
 
return getValidFileName(this.startName + this.row.getString("NUMERO"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/VenteComptoirSheet.java
29,11 → 29,12
private static final SQLTable tableComptoir = base.getTable("SAISIE_VENTE_COMPTOIR");
private static final SQLTable tableClient = base.getTable("CLIENT");
private static final SQLTable tableAdresse = base.getTable("ADRESSE");
private final static SQLTable tableAdresseCommon = Configuration.getInstance().getBase().getTable("ADRESSE_COMMON");
private static final SQLTable tableArticle = base.getTable("ARTICLE");
private static final SQLTable tableTaxe = base.getTable("TAXE");
private static final SQLTable tableModeRegl = base.getTable("MODE_REGLEMENT");
private static final SQLTable tableTypeRegl = base.getTable("TYPE_REGLEMENT");
public static final String TEMPLATE_ID = "VenteComptoir";
public static final String TEMPLATE_PROPERTY_NAME = "LocationVenteComptoir";
 
public VenteComptoirSheet(int idFact) {
super(idFact, tableComptoir);
43,6 → 44,16
super(rowSaisie);
}
 
@Override
protected String getYear() {
return "";
}
 
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
protected void createMap() {
// TODO Auto-generated method stub
this.mCell = new HashMap();
89,4 → 100,5
 
this.mCell.put("A35", this.row.getObject("INFOS"));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeDebiteursAction.java
14,8 → 14,10
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.core.sales.invoice.report.ListeDebiteursXmlSheet;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.event.ActionEvent;
import java.util.concurrent.ExecutionException;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
28,8 → 30,17
 
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
final ListeDebiteursXmlSheet sheet = new ListeDebiteursXmlSheet();
try {
sheet.createDocumentAsynchronous().get();
sheet.showPrintAndExport(true, false, false);
} catch (Exception e) {
ExceptionHandler.handle("Impossible d'afficher la liste des débiteurs");
}
 
ListeDebiteursXmlSheet sheet = new ListeDebiteursXmlSheet();
sheet.genere(true, false);
}
}).start();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeSaisieVenteFactureAction.java
25,6 → 25,7
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.invoice.report.ListeFactureXmlSheet;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.invoice.ui.DateEnvoiRenderer;
import org.openconcerto.erp.core.sales.invoice.ui.ListeFactureRenderer;
import org.openconcerto.erp.generationEcritures.GenerationMvtRetourNatexis;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
46,11 → 47,16
import org.openconcerto.sql.view.EditPanelListener;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.IClosure;
 
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
60,7 → 66,9
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
 
import javax.sql.rowset.Predicate;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
69,6 → 77,7
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.table.TableColumn;
 
public class ListeSaisieVenteFactureAction extends CreateFrameAbstractAction {
 
90,12 → 99,37
final SQLTableModelSourceOnline src = eltFacture.getTableSource(true);
 
for (SQLTableModelColumn column : src.getColumns()) {
// if (column.getValueClass() == Long.class || column.getValueClass() ==
// if (column.getValueClass() == Long.class ||
// column.getValueClass() ==
// BigInteger.class || column.getValueClass() == BigDecimal.class)
column.setRenderer(ListeFactureRenderer.UTILS.getRenderer(column.getRenderer()));
if (column.getClass().isAssignableFrom(SQLTableModelColumnPath.class)) {
((SQLTableModelColumnPath) column).setEditable(false);
}
}
final SQLTableModelColumn dateEnvoiCol = src.getColumn(eltFacture.getTable().getField("DATE_ENVOI"));
 
((SQLTableModelColumnPath) dateEnvoiCol).setEditable(true);
 
final SQLTableModelColumn dateReglCol = src.getColumn(eltFacture.getTable().getField("DATE_REGLEMENT"));
((SQLTableModelColumnPath) dateReglCol).setEditable(true);
 
dateEnvoiCol.setColumnInstaller(new IClosure<TableColumn>() {
@Override
public void executeChecked(TableColumn columnDateEnvoi) {
columnDateEnvoi.setCellEditor(new org.openconcerto.ui.table.TimestampTableCellEditor());
columnDateEnvoi.setCellRenderer(new DateEnvoiRenderer());
}
});
 
// Edition des dates de reglement
dateReglCol.setColumnInstaller(new IClosure<TableColumn>() {
@Override
public void executeChecked(TableColumn columnDateReglement) {
columnDateReglement.setCellEditor(new org.openconcerto.ui.table.TimestampTableCellEditor());
columnDateReglement.setCellRenderer(new DateEnvoiRenderer());
}
});
this.listeAddPanel = new ListeGestCommEltPanel(eltFacture, new IListe(src)) {
 
 
146,28 → 180,42
this.frame = new IListFrame(this.listeAddPanel);
 
// FIXME Maybe Stock rowSelection in new List
final MouseSheetXmlListeListener mouseListener = new MouseSheetXmlListeListener(this.listeAddPanel.getListe(), VenteFactureXmlSheet.class) {
final MouseSheetXmlListeListener mouseListener = new MouseSheetXmlListeListener(VenteFactureXmlSheet.class) {
@Override
public List<AbstractAction> addToMenu() {
public List<RowAction> addToMenu() {
 
final SQLRow row = liste.getSelectedRow();
List<AbstractAction> l = new ArrayList<AbstractAction>(5);
if (row != null) {
AbstractAction actionAvoir = new AbstractAction("Transférer en avoir") {
// final SQLRow row = liste.getSelectedRow();
List<RowAction> l = new ArrayList<RowAction>(5);
PredicateRowAction actionBL = new PredicateRowAction(new AbstractAction("Transférer en bon de livraison") {
public void actionPerformed(ActionEvent e) {
SaisieVenteFactureSQLElement elt = (SaisieVenteFactureSQLElement) Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
elt.transfertAvoir(row.getID());
elt.transfertBL(IListe.get(e).getSelectedId());
}
};
l.add(actionAvoir);
AbstractAction actionBL = new AbstractAction("Transférer en bon de livraison") {
}, false);
actionBL.setPredicate(IListeEvent.getSingleSelectionPredicate());
l.add(actionBL);
PredicateRowAction actionClone = new PredicateRowAction(new AbstractAction("Créer à partir de ...") {
public void actionPerformed(ActionEvent e) {
 
SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
EditFrame editFrame = new EditFrame(eltFact, EditPanel.CREATION);
 
((SaisieVenteFactureSQLComponent) editFrame.getSQLComponent()).loadFactureExistante(IListe.get(e).getSelectedId());
editFrame.setVisible(true);
}
}, false);
actionClone.setPredicate(IListeEvent.getSingleSelectionPredicate());
l.add(actionClone);
 
PredicateRowAction actionAvoir = new PredicateRowAction(new AbstractAction("Transférer en avoir") {
public void actionPerformed(ActionEvent e) {
SaisieVenteFactureSQLElement elt = (SaisieVenteFactureSQLElement) Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
elt.transfertBL(row.getID());
elt.transfertAvoir(IListe.get(e).getSelectedId());
}
};
l.add(actionBL);
}
}, false);
actionAvoir.setPredicate(IListeEvent.getSingleSelectionPredicate());
l.add(actionAvoir);
 
return l;
// return super.addToMenu();
 
174,7 → 222,7
}
};
// this.frame.getPanel().getListe().addRowActions(mouseListener.getRowActions());
this.frame.getPanel().getListe().getJTable().addMouseListener(mouseListener);
this.frame.getPanel().getListe().addIListeActions(mouseListener.getRowActions());
 
 
return this.frame;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/GenListeVentePanel.java
24,6 → 24,7
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
30,7 → 31,6
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ExecutionException;
 
import javax.swing.JButton;
import javax.swing.JFrame;
96,6 → 96,7
if (e.getSource() == this.buttonGen) {
final Thread thread = new Thread(new Runnable() {
public void run() {
try {
SQLTable tableFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE").getTable();
SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
110,14 → 111,11
sel2.setDistinct(true);
l.addAll((List<SQLRow>) dataSource.execute(sel2.asString(), SQLRowListRSH.createFromSelect(sel2, tableAvoir)));
ListeVenteXmlSheet sheet = new ListeVenteXmlSheet(l, GenListeVentePanel.this.du.getDate(), GenListeVentePanel.this.au.getDate(), GenListeVentePanel.this.bar);
try {
sheet.genere(true, false).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
 
sheet.createDocumentAsynchronous().get();
sheet.showPrintAndExport(true, false, false);
} catch (Exception e) {
ExceptionHandler.handle("Erreur de traitement", e);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/InvoiceEditGroup.java
New file
0,0 → 1,48
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.invoice.ui;
 
import org.openconcerto.sql.element.Group;
import org.openconcerto.sql.element.LayoutHints;
 
public class InvoiceEditGroup extends Group {
 
public InvoiceEditGroup() {
super("sales.invoice.edit");
final Group g = new Group("sales.invoice.identifier");
g.add("NUMERO");
g.add("DATE");
g.add("NOM", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
g.add("ID_COMMERCIAL");
this.add(g);
 
final Group gCustomer = new Group("sales.invoice.customer");
gCustomer.add("ID_CLIENT", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
add(gCustomer, LayoutHints.DEFAULT_LARGE_GROUP_HINTS);
 
final Group gAddress = new Group("sales.invoice.address");
gAddress.add("ID_ADRESSE");
add(gAddress, LayoutHints.DEFAULT_LARGE_GROUP_HINTS);
 
final Group gElements = new Group("sales.invoice.elements");
gElements.add("(SAISIE_VENTE_FACTURE_ELEMENT)*", LayoutHints.DEFAULT_LIST_HINTS);
add(gElements, LayoutHints.DEFAULT_LIST_HINTS);
 
final Group gInfos = new Group("sales.invoice.info");
gInfos.add("INFOS", new LayoutHints(true, true, true, true));
add(gInfos);
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/ListeDesVentesPanel.java
33,7 → 33,10
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
186,45 → 189,45
panelFacture.add(filterDate, cFacture);
tabbedPane.add("Ventes avec facture", panelFacture);
 
tableFact.addMouseListener(new MouseSheetXmlListeListener(this.listeFact.getListe(), VenteFactureXmlSheet.class) {
this.listeFact.getListe().addIListeActions(new MouseSheetXmlListeListener(VenteFactureXmlSheet.class) {
EditFrame edit;
 
@Override
public List<AbstractAction> addToMenu() {
public List<RowAction> addToMenu() {
 
final SQLRow rowFacture = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("SAISIE_VENTE_FACTURE")
.getRow(ListeDesVentesPanel.this.listeFact.getListe().getSelectedId());
AbstractAction actionAvoir = new AbstractAction("Transférer en avoir") {
PredicateRowAction actionAvoir = new PredicateRowAction(new AbstractAction("Transférer en avoir") {
public void actionPerformed(ActionEvent e) {
SaisieVenteFactureSQLElement elt = (SaisieVenteFactureSQLElement) Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
elt.transfertAvoir(rowFacture.getID());
elt.transfertAvoir(IListe.get(e).getSelectedId());
}
};
}, false);
 
AbstractAction actionCommande = new AbstractAction("Transférer en commande") {
PredicateRowAction actionCommande = new PredicateRowAction(new AbstractAction("Transférer en commande") {
public void actionPerformed(ActionEvent e) {
SaisieVenteFactureSQLElement elt = (SaisieVenteFactureSQLElement) Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
elt.transfertCommande(rowFacture.getID());
elt.transfertCommande(IListe.get(e).getSelectedId());
}
};
}, false);
 
AbstractAction actionClient = new AbstractAction("Détails client") {
PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Détails client") {
public void actionPerformed(ActionEvent e) {
if (edit == null) {
edit = new EditFrame(eltClient, EditMode.READONLY);
}
edit.selectionId(rowFacture.getInt("ID_CLIENT"));
edit.selectionId(IListe.get(e).getSelectedRow().getInt("ID_CLIENT"));
edit.setVisible(true);
}
};
 
List<AbstractAction> l = new ArrayList<AbstractAction>(1);
}, false);
actionAvoir.setPredicate(IListeEvent.getSingleSelectionPredicate());
actionCommande.setPredicate(IListeEvent.getSingleSelectionPredicate());
actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
List<RowAction> l = new ArrayList<RowAction>(3);
l.add(actionAvoir);
l.add(actionCommande);
l.add(actionClient);
return l;
}
});
}.getRowActions());
this.listeFact.getListe().addIListener(new org.openconcerto.sql.view.IListener() {
 
public void selectionId(int id, int field) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/EtatVentesPanel.java
137,19 → 137,11
 
EtatVentesXmlSheet sheet = new EtatVentesXmlSheet(this.du.getDate(), this.au.getDate());
try {
sheet.genere(false, false).get();
// FIXME Probleme avec l'odsviewer
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
sheet.showDocument();
} else {
sheet.showPreviewDocument();
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
// FIXME probleme de rendu avec le viewer
sheet.createDocumentAsynchronous().get();
sheet.openDocument(false);
} catch (Exception e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/component/SaisieVenteFactureSQLComponent.java
56,6 → 56,7
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
183,6 → 184,17
this.textIdSource = new JTextField();
this.textAvoirTTC = new DeviseField();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
/*******************************************************************************************
* * RENSEIGNEMENTS
******************************************************************************************/
927,9 → 939,15
 
 
// generation du document
VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
sheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
 
try {
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(panelOO.isVisualisationSelected(), panelOO.isImpressionSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de générer la facture", e);
}
 
int idMvt = -1;
if (getMode() == Mode.MODIFICATION) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/component/DevisSQLComponent.java
37,6 → 37,7
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.VFlowLayout;
92,6 → 93,16
setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
final JLabel labelNumero = new JLabel(getLabelFor("NUMERO"));
labelNumero.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNumero, c);
530,7 → 541,7
@Override
public int insert(final SQLRow order) {
 
int idDevis = getSelectedID();
final int idDevis;
// on verifie qu'un devis du meme numero n'a pas été inséré entre temps
if (this.numeroUniqueDevis.checkValidation()) {
 
540,9 → 551,13
this.table.createArticle(idDevis, getElement());
 
// generation du document
 
try {
final DevisXmlSheet sheet = new DevisXmlSheet(getTable().getRow(idDevis));
sheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(DevisSQLComponent.this.panelOO.isVisualisationSelected(), DevisSQLComponent.this.panelOO.isImpressionSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de créer le devis", e);
}
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(DevisSQLElement.class).equalsIgnoreCase(this.numeroUniqueDevis.getText().trim())) {
550,7 → 565,6
int val = this.tableNum.getRow(2).getInt("DEVIS_START");
val++;
rowVals.put("DEVIS_START", new Integer(val));
 
try {
rowVals.update(2);
} catch (final SQLException e) {
558,6 → 572,7
}
}
} else {
idDevis = getSelectedID();
ExceptionHandler.handle("Impossible d'ajouter, numéro de devis existant.");
final Object root = SwingUtilities.getRoot(this);
if (root instanceof EditFrame) {
598,10 → 613,17
this.table.createArticle(getSelectedID(), getElement());
 
// generation du document
final DevisXmlSheet dSheet = new DevisXmlSheet(getTable().getRow(getSelectedID()));
dSheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
 
try {
final DevisXmlSheet sheet = new DevisXmlSheet(getTable().getRow(getSelectedID()));
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(DevisSQLComponent.this.panelOO.isVisualisationSelected(), DevisSQLComponent.this.panelOO.isImpressionSelected(), true);
} catch (Exception e) {
ExceptionHandler.handle("Impossible de créer le devis", e);
}
 
}
 
/**
* Création d'un devis à partir d'un devis existant
*
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisSQLElement.java
37,8 → 37,10
 
public class DevisSQLElement extends ComptaSQLConfElement {
 
public static final String TABLENAME = "DEVIS";
 
public DevisSQLElement() {
super("DEVIS", "un devis", "devis");
super(TABLENAME, "un devis", "devis");
}
 
protected List<String> getComboFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/report/DevisXmlSheet.java
13,25 → 13,16
package org.openconcerto.erp.core.sales.quote.report;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class DevisXmlSheet extends AbstractSheetXMLWithDate {
 
public class DevisXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "Devis";
public static final String TEMPLATE_PROPERTY_NAME = "LocationDevis";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationDevis", "Devis");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
public String getReference() {
return this.row.getString("OBJET");
51,19 → 42,16
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("DevisPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("DEVIS");
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
 
}
 
@Override
public String getDefaultModele() {
return "Devis";
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
public String getFileName() {
 
return getValidFileName("Devis_" + this.row.getString("NUMERO"));
@Override
public String getName() {
return "Devis_" + this.row.getString("NUMERO");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/report/DevisTextSheet.java
115,7 → 115,7
this.askOverwriting = true;
Date d = (Date) this.row.getObject("DATE");
String year = yearFormat.format(d);
init(year, "Devis.odt", "DevisPrinter", DevisXmlSheet.getTuple2Location());
init(year, "Devis.odt", "DevisPrinter");
}
 
protected boolean savePDF() {
122,8 → 122,13
return true;
}
 
@Override
public String getFileName() {
String fileName = "Devis_" + AbstractSheetXml.getValidFileName(this.row.getString("NUMERO"));
String fileName = "Devis_" + this.row.getString("NUMERO");
return fileName;
}
 
public String getTemplateId() {
return "sales.quote.text";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/ListeDesDevisAction.java
21,6 → 21,7
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.quote.report.DevisTextSheet;
import org.openconcerto.erp.core.sales.quote.ui.ListeDesDevisPanel;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetUtils;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.Configuration;
91,7 → 92,8
openItem.setFont(openItem.getFont().deriveFont(Font.BOLD));
menu.add(openItem);
 
List<File> files = SheetUtils.getInstance().getHistorique(s.getFileName(), new File(s.getLocationOO()));
final File outpuDirectory = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(s.getTemplateId());
List<File> files = SheetUtils.getHistorique(s.getFileName(), outpuDirectory);
if (files.size() > 0) {
JMenu item = new JMenu("Historique");
int i = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/ui/ListeDesDevisPanel.java
35,11 → 35,14
import org.openconcerto.sql.view.IListener;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
91,16 → 94,18
// Bouton generer
this.buttonGen = new JButton("Générer le document");
this.add(this.buttonGen, c);
// this.buttonGen.setToolTipText("Générer");
// this.buttonGen.setBorder(null);
this.buttonGen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
final ListeAddPanel selectedPanel = ListeDesDevisPanel.this.map.get(ListeDesDevisPanel.this.tabbedPane.getSelectedIndex());
SQLRow row = selectedPanel.getListe().getSelectedRow();
DevisXmlSheet sheet = new DevisXmlSheet(row);
sheet.genere(true, false);
// genereDoc(row);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
} catch (Exception ex) {
ExceptionHandler.handle("Erreur lors de de la génération du document", ex);
}
}
});
 
// Bouton voir le document
111,12 → 116,17
// this.buttonShow.setBorder(null);
this.buttonShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
final ListeAddPanel selectedPanel = ListeDesDevisPanel.this.map.get(ListeDesDevisPanel.this.tabbedPane.getSelectedIndex());
SQLRow row = selectedPanel.getListe().getSelectedRow();
DevisXmlSheet sheet = new DevisXmlSheet(row);
sheet.showDocument();
// showDoc(row);
sheet.getOrCreateDocumentFile();
sheet.openDocument(false);
} catch (Exception ex) {
ExceptionHandler.handle("Erreur lors de de la génération du document", ex);
}
 
}
});
 
// Bouton Impression
212,7 → 222,8
}
Where wAttente = new Where(this.eltDevis.getTable().getField("ID_ETAT_DEVIS"), "=", idFilter);
lAttente.getReq().setWhere(wAttente);
// one config file per idFilter since they haven't the same number of columns
// one config file per idFilter since they haven't the same number of
// columns
final ListeAddPanel pane = new ListeAddPanel(this.eltDevis, new IListe(lAttente), "idFilter" + idFilter);
 
// Renderer
232,36 → 243,62
}
}
 
pane.getListe().getJTable().addMouseListener(new MouseSheetXmlListeListener(pane.getListe(), DevisXmlSheet.class) {
pane.getListe().addIListeActions(new MouseSheetXmlListeListener(DevisXmlSheet.class) {
@Override
public List<AbstractAction> addToMenu() {
List<AbstractAction> list = new ArrayList<AbstractAction>();
final SQLRow row = pane.getListe().getSelectedRow();
public List<RowAction> addToMenu() {
List<RowAction> list = new ArrayList<RowAction>();
// Transfert vers facture
AbstractAction factureAction = (new AbstractAction("Transfert vers facture") {
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction("Transfert vers facture") {
public void actionPerformed(ActionEvent e) {
transfertFacture(row);
transfertFacture(IListe.get(e).getSelectedRow());
}
});
}, false) {
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowAccessor> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
return true;
}
}
return false;
};
};
 
// Voir le document
AbstractAction actionTransfertCmd = new AbstractAction("Transférer en commande") {
PredicateRowAction actionTransfertCmd = new PredicateRowAction(new AbstractAction("Transférer en commande") {
public void actionPerformed(ActionEvent e) {
transfertCommande(row);
transfertCommande(IListe.get(e).getSelectedRow());
}
}, false) {
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowAccessor> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
return true;
}
}
return false;
};
};
 
// Transfert vers commande
AbstractAction commandeAction = (new AbstractAction("Transfert vers commande client") {
PredicateRowAction commandeAction = new PredicateRowAction(new AbstractAction("Transfert vers commande client") {
public void actionPerformed(ActionEvent e) {
transfertCommandeClient(row);
transfertCommandeClient(IListe.get(e).getSelectedRow());
}
});
}, false) {
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowAccessor> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
return true;
}
}
return false;
};
};
 
// Marqué accepté
AbstractAction accepteAction = (new AbstractAction("Marquer comme accepté") {
PredicateRowAction accepteAction = new PredicateRowAction(new AbstractAction("Marquer comme accepté") {
public void actionPerformed(ActionEvent e) {
SQLRowValues rowVals = row.createEmptyUpdateRow();
SQLRowValues rowVals = IListe.get(e).getSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
try {
rowVals.update();
269,22 → 306,34
// TODO Auto-generated catch block
e1.printStackTrace();
}
row.getTable().fireTableModified(row.getID());
IListe.get(e).getSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
});
}, false) {
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowAccessor> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.EN_ATTENTE) {
return true;
}
}
return false;
};
};
 
int type = pane.getListe().getSelectedRow().getInt("ID_ETAT_DEVIS");
factureAction.setEnabled(type == EtatDevisSQLElement.ACCEPTE);
commandeAction.setEnabled(type == EtatDevisSQLElement.ACCEPTE);
if (type == EtatDevisSQLElement.EN_ATTENTE) {
list.add(accepteAction);
}
list.add(factureAction);
list.add(commandeAction);
list.add(actionTransfertCmd);
// int type =
// pane.getListe().getSelectedRow().getInt("ID_ETAT_DEVIS");
// factureAction.setEnabled(type ==
// EtatDevisSQLElement.ACCEPTE);
// commandeAction.setEnabled(type ==
// EtatDevisSQLElement.ACCEPTE);
// if (type == EtatDevisSQLElement.EN_ATTENTE) {
// list.add(accepteAction);
// }
// list.add(factureAction);
// list.add(commandeAction);
// list.add(actionTransfertCmd);
return list;
}
});
}.getRowActions());
 
// activation des boutons
pane.getListe().addIListener(new IListener() {
308,8 → 357,8
this.buttonFacture.setEnabled(etat == EtatDevisSQLElement.ACCEPTE);
this.buttonCmd.setEnabled(etat == EtatDevisSQLElement.ACCEPTE);
 
this.buttonPrint.setEnabled(sheet.isFileOOExist());
this.buttonShow.setEnabled(sheet.isFileOOExist());
this.buttonPrint.setEnabled(sheet.getGeneratedFile().exists());
this.buttonShow.setEnabled(sheet.getGeneratedFile().exists());
this.buttonGen.setEnabled(true);
this.buttonClone.setEnabled(true);
 
363,7 → 412,7
SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
 
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", rowValsElt.getLong("PA_HT") * rowValsElt.getInt("QTE"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/component/ReferenceArticleSQLComponent.java
363,6 → 363,7
// Obsolete
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
this.checkObs.setOpaque(false);
panel.add(this.checkObs, c);
 
this.checkObs.setVisible(false);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/Caisse.java
41,6 → 41,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.DesktopEnvironment;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Pair;
55,6 → 56,7
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.jdom.Document;
107,7 → 109,7
return document;
}
 
private static File getConfigFile() {
public static File getConfigFile() {
return getConfigFile(ComptaPropsConfiguration.APP_NAME, new File("."));
}
 
132,8 → 134,12
}
}
 
public static void commitAll(List<Ticket> tickets) {
public static void commitAll(final List<Ticket> tickets) {
// createConnexion();
try {
SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLUtils.SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
SQLElement elt = Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE");
SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
SQLElement eltEnc = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
204,16 → 210,17
rowValsElt.put("ID_TICKET_CAISSE", rowVals);
}
}
try {
 
SQLRow rowFinal = rowVals.insert();
Thread t = new Thread(new GenerationMvtTicketCaisse(rowFinal));
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
 
// msie à jour du mouvement
rowFinal = rowFinal.getTable().getRow(rowFinal.getID());
List<SQLRow> rowsEnc = rowFinal.getReferentRows(eltEnc.getTable());
223,8 → 230,8
PrixTTC ttc = new PrixTTC(montant);
totalEnc += montant;
new GenerationReglementVenteNG("Règlement " + sqlRow.getForeignRow("ID_MODE_REGLEMENT").getForeignRow("ID_TYPE_REGLEMENT").getString("NOM") + " Ticket "
+ rowFinal.getString("NUMERO"), getClientCaisse(), ttc, sqlRow.getDate("DATE").getTime(), sqlRow.getForeignRow("ID_MODE_REGLEMENT"), rowFinal,
rowFinal.getForeignRow("ID_MOUVEMENT"), false);
+ rowFinal.getString("NUMERO"), getClientCaisse(), ttc, sqlRow.getDate("DATE").getTime(), sqlRow.getForeignRow("ID_MODE_REGLEMENT"), rowFinal, rowFinal
.getForeignRow("ID_MOUVEMENT"), false);
}
if (totalEnc > total) {
final SQLTable table = Configuration.getInstance().getDirectory().getElement("TYPE_REGLEMENT").getTable();
232,19 → 239,33
if (idComptePceCaisse == table.getUndefinedID()) {
idComptePceCaisse = ComptePCESQLElement.getId(ComptePCESQLElement.getComptePceDefault("VenteEspece"));
}
new GenerationMvtVirement(idComptePceCaisse, getClientCaisse().getInt("ID_COMPTE_PCE"), 0, totalEnc - total,
"Rendu sur règlement " + " Ticket " + rowFinal.getString("NUMERO"), new Date(), JournalSQLElement.CAISSES, " Ticket " + rowFinal.getString("NUMERO")).genereMouvement();
new GenerationMvtVirement(idComptePceCaisse, getClientCaisse().getInt("ID_COMPTE_PCE"), 0, totalEnc - total, "Rendu sur règlement " + " Ticket "
+ rowFinal.getString("NUMERO"), new Date(), JournalSQLElement.CAISSES, " Ticket " + rowFinal.getString("NUMERO")).genereMouvement();
}
 
updateStock(rowFinal.getID());
} catch (SQLException e) {
e.printStackTrace();
 
}
}
}
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
// TODO Raccord de méthode auto-généré
 
JOptionPane.showMessageDialog(null, "Clôture de la caisse terminée.");
}
});
return null;
}
});
} catch (Exception exn) {
// TODO Bloc catch auto-généré
ExceptionHandler.handle("Une erreur est survenue pendant la clôture.", exn);
}
 
}
 
private static SQLRow rowClient = null;
 
private static SQLRow getClientCaisse() throws SQLException {
341,7 → 362,7
 
public static int getID() {
final Document d = getDocument();
return Integer.valueOf(d.getRootElement().getAttributeValue("caisseID", "2"));
return Integer.valueOf(d.getRootElement().getAttributeValue("caisseID", "-1"));
}
 
public static void setID(int caisseId) {
364,7 → 385,7
 
public static int getUserID() {
final Document d = getDocument();
return Integer.valueOf(d.getRootElement().getAttributeValue("userID", "2"));
return Integer.valueOf(d.getRootElement().getAttributeValue("userID", "-1"));
}
 
public static void setUserID(int userId) {
374,7 → 395,7
 
public static int getSocieteID() {
final Document d = getDocument();
return Integer.valueOf(d.getRootElement().getAttributeValue("societeID", "42"));
return Integer.valueOf(d.getRootElement().getAttributeValue("societeID", "-1"));
}
 
public static void setSocieteID(int societeId) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSelector.java
107,7 → 107,6
this.add(list, c);
list.addListSelectionListener(this);
 
comp.setModel(model);
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
41,11 → 41,10
 
public class CaissePanel extends JPanel implements CaisseListener {
private CaisseControler controler;
private CaisseFrame caisseFrame;
 
private StatusBar st;
 
public CaissePanel(final CaisseFrame caisseFrame) {
this.caisseFrame = caisseFrame;
this.setLayout(new GridBagLayout());
this.setBackground(Color.WHITE);
this.setOpaque(isOpaque());
152,6 → 151,7
if (s1 != null) {
Article a = new Article(s1, row.getString("NOM"));
a.setBarCode(row.getString("CODE_BARRE"));
a.setCode(row.getString("CODE"));
a.setIdTaxe(row.getInt("ID_TAXE"));
a.setPriceHTInCents((int) row.getLong("PV_HT"));
a.setPriceInCents((int) row.getLong("PV_TTC"));
224,8 → 224,8
Rectangle2D r;
g.setFont(g.getFont().deriveFont(66f));
final int total = this.controler.getTotal();
euros = this.controler.getEuros(total) + ".";
cents = this.controler.getCents(total);
euros = CaisseControler.getEuros(total) + ".";
cents = CaisseControler.getCents(total);
r = g.getFontMetrics().getStringBounds(euros, g);
x = x - (int) r.getWidth();
g.drawString(euros, x, y);
235,8 → 235,8
y += 40;
x = 300;
final int paye = this.controler.getPaidTotal();
euros = this.controler.getEuros(paye) + ".";
cents = this.controler.getCents(paye);
euros = CaisseControler.getEuros(paye) + ".";
cents = CaisseControler.getCents(paye);
 
g.setFont(g.getFont().deriveFont(18f));
Rectangle2D r2 = g.getFontMetrics().getStringBounds("Payé", g);
266,8 → 266,8
aRendre = -aRendre;
}
 
euros = this.controler.getEuros(aRendre) + ".";
cents = this.controler.getCents(aRendre);
euros = CaisseControler.getEuros(aRendre) + ".";
cents = CaisseControler.getCents(aRendre);
 
g.setFont(g.getFont().deriveFont(18f));
Rectangle2D r3 = g.getFontMetrics().getStringBounds(label, g);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CategorieSelector.java
62,8 → 62,6
this.add(this.list, c);
this.list.getSelectionModel().addListSelectionListener(this);
 
this.comp.setModel(this.model);
 
this.comp.addMouseListener(new MouseAdapter() {
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/StatusBar.java
13,7 → 13,6
package org.openconcerto.erp.core.sales.pos.ui;
 
 
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
24,20 → 23,17
 
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.ListModel;
 
public class StatusBar extends JPanel {
private Image bg;
private Image bg_retour;
private String title = "";
// private Categorie previous;
private ListModel model;
 
private boolean previous;
private int offsetX = 110;
 
StatusBar() {
this("toolbar.png", "toolbar_retour.png");
 
}
 
StatusBar(String fileBg, String fileFg) {
93,8 → 89,4
return new Dimension(320, 44);
}
 
public void setModel(ListModel model) {
this.model = model;
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ConfigCaissePanel.java
79,7 → 79,22
setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
c.weighty = 0;
// Fichier
c.weightx = 0;
this.add(new JLabel("Fichier de configuration", SwingConstants.RIGHT), c);
c.gridx++;
c.gridwidth = 3;
c.weightx = 1;
JTextField textConfigurationFile = new JTextField("");
if (Caisse.getConfigFile() != null) {
textConfigurationFile.setText(Caisse.getConfigFile().getAbsolutePath());
}
textConfigurationFile.setEditable(false);
this.add(textConfigurationFile, c);
 
// Connexion
c.gridy++;
c.gridx = 0;
final JLabelBold titleConnexion = new JLabelBold("Connexion");
c.gridwidth = 2;
this.add(titleConnexion, c);
275,7 → 290,7
try {
System.out.println("Reloading POS information from: " + config);
SQLServer server = config.createServer("Common");
DBSystemRoot r = server.getSystemRoot("OpenConcerto");
DBSystemRoot r = server.getSystemRoot(config.getSystemRoot());
DBRoot root = r.getRoot("Common");
// Sociétés
SQLSelect sel = new SQLSelect(root.getBase());
287,18 → 302,19
if (societes.size() > 0) {
final String name = societes.get(0).getString("DATABASE_NAME");
server = config.createServer(name);
r = server.getSystemRoot("OpenConcerto");
r = server.getSystemRoot(config.getSystemRoot());
root = r.getRoot(name);
// Caisses
sel = new SQLSelect(root.getBase());
sel.addSelectStar(root.getTable("CAISSE"));
final List<SQLRow> caisses = SQLRowListRSH.execute(sel);
 
server.destroy();
 
// Stock l'id de la caisse pour que la reslectionne soit correcte
final int idCaisseToSelect = this.caisseId;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ConfigCaissePanel.this.caisseId = idCaisseToSelect;
if (caisses.isEmpty()) {
JOptionPane.showMessageDialog(ConfigCaissePanel.this, "Pas de caisses définies dans la société " + name);
}
314,7 → 330,7
}
for (int i = 0; i < stop; i++) {
final SQLRow r = (SQLRow) model.getElementAt(i);
if (r.getID() == ConfigCaissePanel.this.caisseId) {
if (r.getID() == idCaisseToSelect) {
ConfigCaissePanel.this.comboCaisse.setSelectedItem(r);
break;
}
375,11 → 391,10
JOptionPane.showMessageDialog(ConfigCaissePanel.this, "Impossible de se connecter au serveur");
return;
}
String result = "Erreur de connexion. \n";
try {
 
final SQLServer server = config.createServer("Common");
final DBSystemRoot r = server.getSystemRoot("OpenConcerto");
final DBSystemRoot r = server.getSystemRoot(config.getSystemRoot());
final DBRoot root = r.getRoot("Common");
// Sociétés
SQLSelect sel = new SQLSelect(root.getBase());
402,30 → 417,49
ConfigCaissePanel.this.comboSociete.setEnabled(true);
ConfigCaissePanel.this.comboUtilisateur.setEnabled(true);
 
// Societe
ComboBoxModel model = ConfigCaissePanel.this.comboSociete.getModel();
int stop = model.getSize();
boolean societeFound = false;
for (int i = 0; i < stop; i++) {
final SQLRow r = (SQLRow) model.getElementAt(i);
if (r.getID() == ConfigCaissePanel.this.societeId) {
ConfigCaissePanel.this.comboSociete.setSelectedItem(r);
ConfigCaissePanel.this.societeId = r.getID();
societeFound = true;
break;
}
}
 
if (!societeFound && stop > 0) {
ConfigCaissePanel.this.comboSociete.setSelectedItem(model.getElementAt(0));
ConfigCaissePanel.this.societeId = ((SQLRow) model.getElementAt(0)).getID();
}
// Utilisateur
model = ConfigCaissePanel.this.comboUtilisateur.getModel();
stop = model.getSize();
boolean utilisateurFound = false;
for (int i = 0; i < stop; i++) {
final SQLRow r = (SQLRow) model.getElementAt(i);
if (r.getID() == ConfigCaissePanel.this.userId) {
ConfigCaissePanel.this.comboUtilisateur.setSelectedItem(r);
ConfigCaissePanel.this.userId = r.getID();
utilisateurFound = true;
break;
}
}
 
if (!utilisateurFound && stop > 0) {
ConfigCaissePanel.this.comboUtilisateur.setSelectedItem(model.getElementAt(0));
ConfigCaissePanel.this.userId = ((SQLRow) model.getElementAt(0)).getID();
}
 
reloadCaisses();
}
 
});
 
} catch (final Exception e) {
result += e.getMessage();
e.printStackTrace();
}
 
437,6 → 471,12
});
}
 
public void dumpConfiguration() {
System.out.println("Societe: id:" + this.societeId);
System.out.println("Caisse: id:" + this.caisseId);
System.out.println("Utilisateur: id:" + this.userId);
}
 
public void saveConfiguration() {
Caisse.setPrinterType(this.comboType.getSelectedItem().toString());
if (this.comboType.getSelectedIndex() == 0) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketPanel.java
59,18 → 59,15
@Override
public void addListDataListener(final ListDataListener l) {
TicketPanel.this.listeners.add(l);
 
}
 
@Override
public Object getElementAt(final int index) {
 
return controler.getItems().get(index);
}
 
@Override
public int getSize() {
// TODO Auto-generated method stub
return controler.getItems().size();
}
 
77,7 → 74,6
@Override
public void removeListDataListener(final ListDataListener l) {
TicketPanel.this.listeners.remove(l);
 
}
 
};
133,13 → 129,11
 
@Override
public Dimension getMinimumSize() {
// TODO Auto-generated method stub
return new Dimension(480, 707);
}
 
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(480, 707);
}
 
169,7 → 163,6
return;
}
} catch (final Exception e) {
// TODO: handle exception
e.printStackTrace();
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TouchScrollPane.java
32,8 → 32,6
public class TouchScrollPane extends JScrollPane implements MouseListener, MouseMotionListener {
 
private JComponent child;
int dy = 0;
int olddy = 0;
private int mousePressedY;
private double viewY;
private int lastLocationOnscreen;
42,7 → 40,6
super(l);
this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
 
if (!(l instanceof Scrollable)) {
throw new IllegalArgumentException("Argument is not implementing Scrollable");
}
49,7 → 46,6
this.child = l;
child.addMouseListener(this);
child.addMouseMotionListener(this);
 
}
 
@Override
59,13 → 55,6
super.paint(g);
}
 
/*
* @Override public void paint(Graphics g, int x, int y, int width, int height) { int oldOffsetY
* = g.getOffsetY(); g.setColor(Color.RED); g.fillRect(0, 0, this.getWidth(), this.getHeight());
* g.setOffset(g.getOffsetX(), oldOffsetY + dy); child.paint(g, x, y, width, height);
* g.setOffset(g.getOffsetX(), oldOffsetY); }
*/
 
/**
* @param args
*/
83,92 → 72,54
f.setContentPane(t);
f.setSize(200, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
f.setVisible(true);
}
 
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("TouchScrollPane.mouseClicked()");
}
 
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("TouchScrollPane.mouseEntered()");
}
 
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("TouchScrollPane.mouseExited()");
}
 
@Override
public void mousePressed(MouseEvent e) {
this.mousePressedY = e.getLocationOnScreen().y;
System.out.println("TouchScrollPane.mousePressed():" + e.getY());
 
viewY = this.getViewport().getViewPosition().getY();
e.consume();
 
}
 
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("TouchScrollPane.mouseReleased()");
}
 
@Override
public void mouseDragged(MouseEvent e) {
e.consume();
if (e.getLocationOnScreen().y == lastLocationOnscreen) {
return;
}
 
lastLocationOnscreen = e.getLocationOnScreen().y;
System.out.println("TouchScrollPane.mouseDragged()");
// final int newDy = olddy + (e.getY() - this.mousePressedY);
//
// dy = newDy;
// if (dy >= 0) {
// dy = 0;
// }
// if (dy <= -(child.getHeight() - this.getHeight())) {
// dy = -(child.getHeight() - this.getHeight());
// }
//
// this.getViewport().setViewPosition(new Point(0,dy));
int xDiff = 0;
int yDiff = mousePressedY;
System.out.println("DY:" + yDiff);
JViewport jv = this.getViewport();
Point p = jv.getViewPosition();
int newX = 0;// p.x - (e.getX() - xDiff);
final JViewport jv = this.getViewport();
int newX = 0;
int deplacementY = e.getLocationOnScreen().y - yDiff;
int newY = (int) viewY - deplacementY;
System.out.println("View Position:" + p.y);
System.out.println("Decallage depuis mouse pressed:" + deplacementY + "(" + e.getLocationOnScreen().y + " - " + yDiff + ")");
int maxX = child.getWidth() - jv.getWidth();
int maxY = child.getHeight() - jv.getHeight();
/*
* if (newX < 0) newX = 0; if (newX > maxX) newX = maxX;
*/
if (newY < 0)
newY = 0;/*
* if (newY > maxY) newY = maxY;
*/
 
if (newY < 0) {
newY = 0;
}
jv.setViewPosition(new Point(newX, newY));
System.out.println(newY);
e.consume();
}
 
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("TouchScrollPane.mouseMoved()");
}
 
@Override
public void mouseClicked(MouseEvent e) {
}
 
@Override
public void mouseReleased(MouseEvent e) {
}
 
@Override
public void mouseEntered(MouseEvent e) {
}
 
@Override
public void mouseExited(MouseEvent e) {
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PaiementPanel.java
31,7 → 31,6
import javax.swing.ImageIcon;
import javax.swing.JPanel;
 
 
public class PaiementPanel extends JPanel implements CaisseListener, MouseListener, BarcodeListener {
private static final int OFFSETY = 50;
private static final int LINE_HEIGHT = 64;
90,13 → 89,14
y += LINE_HEIGHT;
}
drawCalculator(g);
// drawGrid(g);
if (Boolean.getBoolean("sales.pos.debug")) {
drawGrid(g);
}
super.paint(g);
}
 
private void drawGrid(Graphics g) {
g.setColor(Color.RED);
Graphics2D g2 = (Graphics2D) g;
for (int x = 0; x < 320; x += 80) {
for (int y = 28; y < 900; y += 72) {
g.drawLine(x, y, x + 2, y + 2);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Article.java
22,7 → 22,8
int priceInCents;
int idTaxe;
int priceHTInCents;
String code = "empty barcode";
String barCode = "empty barcode";
String code = "";
private static Map<String, Article> codes = new HashMap<String, Article>();
 
public Article(Categorie s1, String string) {
48,7 → 49,7
}
 
public void setBarCode(String bar) {
this.code = bar;
this.barCode = bar;
codes.put(bar, this);
}
 
64,8 → 65,16
return this.name;
}
 
public void setCode(String code) {
this.code = code;
}
 
public String getCode() {
return this.code;
};
 
public String getBarCode() {
return this.barCode;
}
 
public Categorie getCategorie() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Ticket.java
107,12 → 107,14
String categorie = element.getAttributeValue("categorie");
String name = element.getValue();
String codebarre = element.getAttributeValue("codebarre");
String codeArt = element.getAttributeValue("code");
Categorie cat = new Categorie(categorie);
Article art = new Article(cat, name);
art.priceInCents = prix_unitaire_cents;
art.setCode(codeArt);
art.setPriceHTInCents(prix_unitaire_cents_ht);
art.setIdTaxe(idTaxe);
art.code = codebarre;
art.barCode = codebarre;
Pair<Article, Integer> line = new Pair<Article, Integer>(art, qte);
t.items.add(line);
 
267,7 → 269,8
e.setAttribute("prixHT", String.valueOf(item.getFirst().getPriceHTInCents()));
e.setAttribute("idTaxe", String.valueOf(item.getFirst().getIdTaxe()));
e.setAttribute("categorie", item.getFirst().getCategorie().getName());
e.setAttribute("codebarre", item.getFirst().getCode());
e.setAttribute("codebarre", item.getFirst().getBarCode());
e.setAttribute("code", item.getFirst().getCode());
e.setText(item.getFirst().getName());
topLevel.addContent(e);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/report/BonLivraisonXmlSheet.java
13,25 → 13,16
package org.openconcerto.erp.core.sales.shipment.report;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.Tuple2;
 
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class BonLivraisonXmlSheet extends AbstractSheetXMLWithDate {
 
public class BonLivraisonXmlSheet extends AbstractSheetXml {
public static final String TEMPLATE_ID = "BonLivraison";
public static final String TEMPLATE_PROPERTY_NAME = "LocationBon";
 
private static final Tuple2<String, String> tuple = Tuple2.create("LocationBon", "Bon de livraison");
 
public static Tuple2<String, String> getTuple2Location() {
return tuple;
}
 
@Override
public String getReference() {
return this.row.getString("NOM");
51,18 → 42,17
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
Calendar cal = Calendar.getInstance();
cal.setTime((Date) row.getObject("DATE"));
this.locationOO = SheetXml.getLocationForTuple(tuple, false) + File.separator + cal.get(Calendar.YEAR);
this.locationPDF = SheetXml.getLocationForTuple(tuple, true) + File.separator + cal.get(Calendar.YEAR);
 
}
 
@Override
public String getDefaultModele() {
return "BonLivraison";
public String getName() {
return "BonLivraison_" + this.row.getString("NUMERO");
}
 
public String getFileName() {
return getValidFileName("BonLivraison_" + this.row.getString("NUMERO"));
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/action/ListeDesBonsDeLivraisonAction.java
22,6 → 22,10
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
68,20 → 72,21
table.getColumnModel().getColumn(i).setCellRenderer(rend);
}
 
table.addMouseListener(new MouseSheetXmlListeListener(edit1.getPanel().getListe(), BonLivraisonXmlSheet.class) {
edit1.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(BonLivraisonXmlSheet.class) {
@Override
public List<AbstractAction> addToMenu() {
AbstractAction actionTransfertFacture = new AbstractAction("Transfert en facture") {
public List<RowAction> addToMenu() {
PredicateRowAction actionTransfertFacture = new PredicateRowAction(new AbstractAction("Transfert en facture") {
public void actionPerformed(ActionEvent ev) {
transfertFactureClient(edit1.getPanel().getListe().getSelectedRow());
transfertFactureClient(IListe.get(ev).getSelectedRow());
}
};
List<AbstractAction> l = new ArrayList<AbstractAction>();
}, false);
actionTransfertFacture.setPredicate(IListeEvent.getSingleSelectionPredicate());
List<RowAction> l = new ArrayList<RowAction>();
l.add(actionTransfertFacture);
 
return l;
}
});
}.getRowActions());
 
return edit1;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/component/BonDeLivraisonSQLComponent.java
36,6 → 36,7
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.TitledSeparator;
104,6 → 105,17
 
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
c.gridy++;
c.gridwidth = 1;
 
// Numero
JLabel labelNum = new JLabel(getLabelFor("NUMERO"));
labelNum.setHorizontalAlignment(SwingConstants.RIGHT);
423,7 → 435,8
 
// generation du document
BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(idBon));
bSheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
bSheet.createDocumentAsynchronous();
bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(BonDeLivraisonSQLElement.class).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
480,7 → 493,9
 
// generation du document
BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(getSelectedID()));
bSheet.genere(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected());
bSheet.createDocumentAsynchronous();
bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
 
}
 
private void updateTotal() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/NumerotationAutoSQLElement.java
39,7 → 39,9
import org.openconcerto.sql.model.SQLTableModifiedListener;
import org.openconcerto.sql.model.Where;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
50,10 → 52,13
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.Icon;
import javax.swing.JLabel;
94,318 → 99,67
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
 
private JTextField textDevisFormat = new JTextField(16);
private JTextField textDevisStart = new JTextField(6);
private JTextField textFactStart = new JTextField(6);
private JTextField textFactFormat = new JTextField(16);
private JTextField textBonFormat = new JTextField(16);
private JTextField textBonStart = new JTextField(6);
private JTextField textBonRFormat = new JTextField(16);
private JTextField textBonRStart = new JTextField(6);
private JTextField textSalarieFormat = new JTextField(16);
private JTextField textSalarieStart = new JTextField(6);
private JTextField textPropositionFormat = new JTextField(16);
private JTextField textPropositionStart = new JTextField(6);
private JTextField textRelanceFormat = new JTextField(16);
private JTextField textRelanceStart = new JTextField(6);
private JTextField textCmdCliFormat = new JTextField(16);
private JTextField textCmdCliStart = new JTextField(6);
private JTextField textCmdFormat = new JTextField(16);
private JTextField textCmdStart = new JTextField(6);
private JTextField textAffaireFormat = new JTextField(16);
private JTextField textAffaireStart = new JTextField(6);
private JTextField textAvoirFormat = new JTextField(16);
private JTextField textAvoirStart = new JTextField(6);
private JTextField textCourrierFormat = new JTextField(16);
private JTextField textCourrierStart = new JTextField(6);
 
private Icon iconWarning = ImageIconWarning.getInstance();
 
private JLabel labelNumDevis, labelNumFact, labelNumBon, labelNumSalarie;
private JLabel labelNumRelance, labelNumProposition, labelNumCmdCli;
private JLabel labelNumCmd, labelNumBonR, labelNumAffaire, labelNumAvoir, labelNumCourrier;
// private JLabel labelNextCodeLettrage;
private DocumentListener listenText = new DocumentListener() {
 
public void insertUpdate(DocumentEvent e) {
updateLabels();
}
 
public void removeUpdate(DocumentEvent e) {
updateLabels();
}
 
public void changedUpdate(DocumentEvent e) {
updateLabels();
}
};
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Avoir
JLabel labelAvoirFormat = new JLabel("Avoir " + getLabelFor("AVOIR_FORMAT"));
this.add(labelAvoirFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textAvoirFormat, c);
Set<Class<? extends SQLElement>> s = map.keySet();
 
JLabel labelAvoirStart = new JLabel(getLabelFor("AVOIR_START"));
c.gridx++;
c.weightx = 0;
this.add(labelAvoirStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textAvoirStart, c);
final ArrayList<Class<? extends SQLElement>> list = new ArrayList<Class<? extends SQLElement>>(s);
Collections.sort(list, new Comparator<Class<? extends SQLElement>>() {
public int compare(Class<? extends SQLElement> o1, Class<? extends SQLElement> o2) {
return o1.toString().compareTo(o2.toString());
};
});
 
this.labelNumAvoir = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumAvoir, c);
 
// Devis
JLabel labelDevisFormat = new JLabel("Devis " + getLabelFor("DEVIS_FORMAT"));
for (Class<? extends SQLElement> class1 : list) {
c.gridy++;
c.gridx = 0;
this.add(labelDevisFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textDevisFormat, c);
 
JLabel labelDevisStart = new JLabel(getLabelFor("DEVIS_START"));
c.gridx++;
c.weightx = 0;
this.add(labelDevisStart, c);
String prefix = map.get(class1);
SQLElement elt = Configuration.getInstance().getDirectory().getElement(class1);
// Avoir
JLabel labelAvoirFormat = new JLabel(StringUtils.firstUp(elt.getPluralName()) + " " + getLabelFor(prefix + FORMAT));
this.add(labelAvoirFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textDevisStart, c);
final JTextField fieldFormat = new JTextField();
this.add(fieldFormat, c);
 
this.labelNumDevis = new JLabel();
final JLabel labelAvoirStart = new JLabel(getLabelFor(prefix + START));
c.gridx++;
c.weightx = 0;
this.add(this.labelNumDevis, c);
 
// Commande Client
JLabel labelCmdCliFormat = new JLabel("Commande client " + getLabelFor("COMMANDE_CLIENT_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelCmdCliFormat, c);
this.add(labelAvoirStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCmdCliFormat, c);
final JTextField fieldStart = new JTextField();
this.add(fieldStart, c);
 
JLabel labelCmdCliStart = new JLabel(getLabelFor("COMMANDE_CLIENT_START"));
final JLabel labelResult = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(labelCmdCliStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCmdCliStart, c);
this.add(labelResult, c);
 
this.labelNumCmdCli = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumCmdCli, c);
// Affichage dynamique du résultat
SimpleDocumentListener listener = new SimpleDocumentListener() {
 
// Commande
JLabel labelCmdFormat = new JLabel("Commande " + getLabelFor("COMMANDE_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelCmdFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCmdFormat, c);
@Override
public void update(DocumentEvent e) {
updateLabel(fieldStart, fieldFormat, labelResult);
 
JLabel labelCmdStart = new JLabel(getLabelFor("COMMANDE_START"));
c.gridx++;
c.weightx = 0;
this.add(labelCmdStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCmdStart, c);
}
};
 
this.labelNumCmd = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumCmd, c);
fieldFormat.getDocument().addDocumentListener(listener);
fieldStart.getDocument().addDocumentListener(listener);
 
// Bon
JLabel labelBonFormat = new JLabel("Bon de livraison" + getLabelFor("BON_L_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelBonFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textBonFormat, c);
this.addRequiredSQLObject(fieldFormat, prefix + FORMAT);
this.addRequiredSQLObject(fieldStart, prefix + START);
 
JLabel labelBonStart = new JLabel(getLabelFor("BON_L_START"));
c.gridx++;
c.weightx = 0;
this.add(labelBonStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textBonStart, c);
}
 
this.labelNumBon = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumBon, c);
 
// Bon Reception
JLabel labelBonRFormat = new JLabel("Bon de réception" + getLabelFor("BON_R_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelBonRFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textBonRFormat, c);
 
JLabel labelBonRStart = new JLabel(getLabelFor("BON_R_START"));
c.gridx++;
c.weightx = 0;
this.add(labelBonRStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textBonRStart, c);
 
this.labelNumBonR = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumBonR, c);
 
// Facture
JLabel labelFactFormat = new JLabel("Facture " + getLabelFor("FACT_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelFactFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textFactFormat, c);
 
JLabel labelFactStart = new JLabel(getLabelFor("FACT_START"));
c.gridx++;
c.weightx = 0;
this.add(labelFactStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textFactStart, c);
 
this.labelNumFact = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumFact, c);
 
// Salarie
JLabel labelSalarieFormat = new JLabel("Salarié " + getLabelFor("SALARIE_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelSalarieFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textSalarieFormat, c);
 
JLabel labelSalarieStart = new JLabel(getLabelFor("SALARIE_START"));
c.gridx++;
c.weightx = 0;
this.add(labelSalarieStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textSalarieStart, c);
 
this.labelNumSalarie = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumSalarie, c);
 
// Affaire
JLabel labelAffaireFormat = new JLabel("Affaire " + getLabelFor("AFFAIRE_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelAffaireFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textAffaireFormat, c);
 
JLabel labelAffaireStart = new JLabel(getLabelFor("AFFAIRE_START"));
c.gridx++;
c.weightx = 0;
this.add(labelAffaireStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textAffaireStart, c);
 
this.labelNumAffaire = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumAffaire, c);
 
// Proposition
JLabel labelPropositionFormat = new JLabel("Proposition " + getLabelFor("PROPOSITION_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelPropositionFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textPropositionFormat, c);
 
JLabel labelPropositionStart = new JLabel(getLabelFor("PROPOSITION_START"));
c.gridx++;
c.weightx = 0;
this.add(labelPropositionStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textPropositionStart, c);
 
this.labelNumProposition = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumProposition, c);
 
// Proposition
JLabel labelCourrierFormat = new JLabel("Courrier " + getLabelFor("COURRIER_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelCourrierFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCourrierFormat, c);
 
JLabel labelCourrierStart = new JLabel(getLabelFor("COURRIER_START"));
c.gridx++;
c.weightx = 0;
this.add(labelCourrierStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textCourrierStart, c);
 
this.labelNumCourrier = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumCourrier, c);
 
// Relance
JLabel labelRelanceFormat = new JLabel("Relance " + getLabelFor("RELANCE_FORMAT"));
c.gridy++;
c.gridx = 0;
this.add(labelRelanceFormat, c);
c.gridx++;
c.weightx = 1;
this.add(this.textRelanceFormat, c);
 
JLabel labelRelanceStart = new JLabel(getLabelFor("RELANCE_START"));
c.gridx++;
c.weightx = 0;
this.add(labelRelanceStart, c);
c.gridx++;
c.weightx = 1;
this.add(this.textRelanceStart, c);
 
this.labelNumRelance = new JLabel();
c.gridx++;
c.weightx = 0;
this.add(this.labelNumRelance, c);
 
// JLabel labelCodeLettrage = new JLabel(getLabelFor("CODE_LETTRAGE"));
// c.gridy++;
// c.gridx = 0;
428,65 → 182,8
c.anchor = GridBagConstraints.NORTHWEST;
this.add(labelExemple, c);
 
this.textBonFormat.getDocument().addDocumentListener(this.listenText);
this.textBonStart.getDocument().addDocumentListener(this.listenText);
this.textDevisFormat.getDocument().addDocumentListener(this.listenText);
this.textDevisStart.getDocument().addDocumentListener(this.listenText);
this.textFactFormat.getDocument().addDocumentListener(this.listenText);
this.textFactStart.getDocument().addDocumentListener(this.listenText);
this.textSalarieFormat.getDocument().addDocumentListener(this.listenText);
this.textSalarieStart.getDocument().addDocumentListener(this.listenText);
this.textPropositionFormat.getDocument().addDocumentListener(this.listenText);
this.textPropositionStart.getDocument().addDocumentListener(this.listenText);
this.textRelanceFormat.getDocument().addDocumentListener(this.listenText);
this.textRelanceStart.getDocument().addDocumentListener(this.listenText);
this.textCmdCliFormat.getDocument().addDocumentListener(this.listenText);
this.textCmdCliStart.getDocument().addDocumentListener(this.listenText);
this.textCmdFormat.getDocument().addDocumentListener(this.listenText);
this.textCmdStart.getDocument().addDocumentListener(this.listenText);
this.textBonRFormat.getDocument().addDocumentListener(this.listenText);
this.textBonRStart.getDocument().addDocumentListener(this.listenText);
this.textAffaireFormat.getDocument().addDocumentListener(this.listenText);
this.textAffaireStart.getDocument().addDocumentListener(this.listenText);
this.textAvoirFormat.getDocument().addDocumentListener(this.listenText);
this.textAvoirStart.getDocument().addDocumentListener(this.listenText);
this.textCourrierFormat.getDocument().addDocumentListener(this.listenText);
this.textCourrierStart.getDocument().addDocumentListener(this.listenText);
// this.textCodeLettrage.getDocument().addDocumentListener(this.listenText);
 
this.addRequiredSQLObject(this.textBonFormat, "BON_L_FORMAT");
this.addRequiredSQLObject(this.textBonStart, "BON_L_START");
this.addRequiredSQLObject(this.textDevisFormat, "DEVIS_FORMAT");
this.addRequiredSQLObject(this.textDevisStart, "DEVIS_START");
this.addRequiredSQLObject(this.textFactFormat, "FACT_FORMAT");
this.addRequiredSQLObject(this.textFactStart, "FACT_START");
this.addRequiredSQLObject(this.textSalarieFormat, "SALARIE_FORMAT");
this.addRequiredSQLObject(this.textSalarieStart, "SALARIE_START");
 
this.addRequiredSQLObject(this.textPropositionFormat, "PROPOSITION_FORMAT");
this.addRequiredSQLObject(this.textPropositionStart, "PROPOSITION_START");
this.addRequiredSQLObject(this.textRelanceFormat, "RELANCE_FORMAT");
this.addRequiredSQLObject(this.textRelanceStart, "RELANCE_START");
 
this.addRequiredSQLObject(this.textCmdCliFormat, "COMMANDE_CLIENT_FORMAT");
this.addRequiredSQLObject(this.textCmdCliStart, "COMMANDE_CLIENT_START");
 
this.addRequiredSQLObject(this.textCmdFormat, "COMMANDE_FORMAT");
this.addRequiredSQLObject(this.textCmdStart, "COMMANDE_START");
 
this.addRequiredSQLObject(this.textBonRFormat, "BON_R_FORMAT");
this.addRequiredSQLObject(this.textBonRStart, "BON_R_START");
 
this.addRequiredSQLObject(this.textAffaireFormat, "AFFAIRE_FORMAT");
this.addRequiredSQLObject(this.textAffaireStart, "AFFAIRE_START");
 
this.addRequiredSQLObject(this.textAvoirFormat, "AVOIR_FORMAT");
this.addRequiredSQLObject(this.textAvoirStart, "AVOIR_START");
 
this.addRequiredSQLObject(this.textCourrierFormat, "COURRIER_FORMAT");
this.addRequiredSQLObject(this.textCourrierStart, "COURRIER_START");
 
updateLabels();
}
 
// private void updateLabelNextCode() {
494,22 → 191,6
// this.labelNextCodeLettrage.setText(donne + " " + s);
// }
 
private void updateLabels() {
updateLabel(this.textDevisStart, this.textDevisFormat, this.labelNumDevis);
updateLabel(this.textBonStart, this.textBonFormat, this.labelNumBon);
updateLabel(this.textBonRStart, this.textBonRFormat, this.labelNumBonR);
updateLabel(this.textFactStart, this.textFactFormat, this.labelNumFact);
updateLabel(this.textSalarieStart, this.textSalarieFormat, this.labelNumSalarie);
updateLabel(this.textPropositionStart, this.textPropositionFormat, this.labelNumProposition);
updateLabel(this.textRelanceStart, this.textRelanceFormat, this.labelNumRelance);
updateLabel(this.textCmdCliStart, this.textCmdCliFormat, this.labelNumCmdCli);
updateLabel(this.textCmdStart, this.textCmdFormat, this.labelNumCmd);
updateLabel(this.textAffaireStart, this.textAffaireFormat, this.labelNumAffaire);
updateLabel(this.textAvoirStart, this.textAvoirFormat, this.labelNumAvoir);
updateLabel(this.textCourrierStart, this.textCourrierFormat, this.labelNumCourrier);
 
}
 
private void updateLabel(JTextField textStart, JTextField textFormat, JLabel label) {
if (textStart.getText().trim().length() > 0) {
String numProposition = getNextNumero(textFormat.getText(), Integer.parseInt(textStart.getText()));
763,6 → 444,17
 
}
 
/**
* Permet d'ajouter la gestion de la numérotation automatique. Attention à bien créer les champs
* name_FORMAT et name_START dans la table NUMEROTATION_AUTO
*
* @param elt
* @param name
*/
public static void addClass(Class<? extends SQLElement> elt, String name) {
map.put(elt, name);
}
 
public static void addListeners() {
for (Class<? extends SQLElement> clazz : map.keySet()) {
final SQLElement elt = Configuration.getInstance().getDirectory().getElement(clazz);
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/ListeFastPrintFrame.java
15,7 → 15,9
 
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
45,7 → 47,7
private static final long serialVersionUID = -1653555706074122489L;
private final Class<? extends AbstractSheetXml> clazz;
private final JPanel panel;
private final List<SQLRow> liste;
private final List<SQLRowAccessor> liste;
private final JLabel operation = new JLabel("");
private final JProgressBar bar = new JProgressBar();
private final JSpinner spin;
54,7 → 56,7
 
private final JButton valid, cancel;
 
public ListeFastPrintFrame(final List<SQLRow> liste, final Class<? extends AbstractSheetXml> clazz) {
public ListeFastPrintFrame(final List<SQLRowAccessor> liste, final Class<? extends AbstractSheetXml> clazz) {
this.panel = new JPanel(new GridBagLayout());
this.liste = liste;
this.clazz = clazz;
61,9 → 63,9
final GridBagConstraints c = new DefaultGridBagConstraints();
// c.gridwidth = GridBagConstraints.REMAINDER;
// FIXME Add Preferences nombre de copies par defaut
final SQLRow row = this.liste.get(0);
final SQLRowAccessor row = this.liste.get(0);
 
final AbstractSheetXml bSheet = this.createAbstractSheet(row);
final AbstractSheetXml bSheet = this.createAbstractSheet(row.asRow());
if (this.liste.size() <= 1) {
this.panel.add(new JLabel("Lancer l'impression document"), c);
} else {
151,30 → 153,27
ListeFastPrintFrame.this.bar.setString("0/" + ListeFastPrintFrame.this.liste.size());
}
});
for (final SQLRow rowAt : ListeFastPrintFrame.this.liste) {
for (final SQLRowAccessor rowAt : ListeFastPrintFrame.this.liste) {
 
final AbstractSheetXml bSheet = ListeFastPrintFrame.this.createAbstractSheet(rowAt);
if (!bSheet.isFileODSExist()) {
final AbstractSheetXml bSheet = ListeFastPrintFrame.this.createAbstractSheet(rowAt.asRow());
if (!bSheet.getGeneratedFile().exists()) {
 
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListeFastPrintFrame.this.operation.setText("Création du document " + bSheet.getFileName());
ListeFastPrintFrame.this.operation.setText("Création du document " + bSheet.getGeneratedFile());
}
});
bSheet.genere(false, false).get();
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bSheet.createDocument();
bSheet.showPrintAndExportAsynchronous(false, false, true);
} catch (Exception e) {
ExceptionHandler.handle("Erreur lors de l'impression du document " + bSheet.getGeneratedFile());
}
}
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListeFastPrintFrame.this.operation.setText("Impression du document " + bSheet.getFileName());
ListeFastPrintFrame.this.operation.setText("Impression du document " + bSheet.getGeneratedFile());
}
});
bSheet.fastPrintDocument(copies);
/trunk/OpenConcerto/src/org/openconcerto/erp/model/GestionChequesModel.java
437,8 → 437,8
Number idMvt = (Number) chqTmp.get("ID_MOUVEMENT");
 
if (mode == MODE_AVOIR) {
GenerationMvtReglementAvoirChequeClient gen = new GenerationMvtReglementAvoirChequeClient(idMvt.intValue(), Long.valueOf(chqTmp.get("MONTANT").toString()), d, id
.intValue());
GenerationMvtReglementAvoirChequeClient gen = new GenerationMvtReglementAvoirChequeClient(idMvt.intValue(), Long.valueOf(chqTmp.get("MONTANT").toString()), d,
id.intValue());
gen.genere();
} else {
if (mode == MODE_ACHAT) {
469,7 → 469,8
} else {
if (mode == MODE_VENTE) {
ReleveChequeSheet sheet = new ReleveChequeSheet(listeCheque, d);
sheet.genere(true, false);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
}
}
}
509,7 → 510,8
} else {
if (mode == MODE_VENTE) {
ReleveChequeSheet sheet = new ReleveChequeSheet(listeCheque, new Date(), true);
sheet.genere(true, false);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/model/MouseSheetXmlListeListener.java
16,7 → 16,6
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.panel.ListeFastPrintFrame;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
30,11 → 29,8
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
42,9 → 38,8
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JPopupMenu;
 
public class MouseSheetXmlListeListener implements MouseListener {
public class MouseSheetXmlListeListener {
 
private Class<? extends AbstractSheetXml> clazz;
protected IListe liste;
62,14 → 57,13
private boolean printIsVisible = true;
private boolean generateIsVisible = true;
 
public MouseSheetXmlListeListener(IListe liste, Class<? extends AbstractSheetXml> clazz) {
this.clazz = clazz;
this.liste = liste;
public MouseSheetXmlListeListener(Class<? extends AbstractSheetXml> clazz) {
this(clazz, true, true, true, true);
 
}
 
public MouseSheetXmlListeListener(IListe liste, Class<? extends AbstractSheetXml> clazz, boolean show, boolean preview, boolean print, boolean generate) {
public MouseSheetXmlListeListener(Class<? extends AbstractSheetXml> clazz, boolean show, boolean preview, boolean print, boolean generate) {
this.clazz = clazz;
this.liste = liste;
this.printIsVisible = print;
this.previewIsVisible = preview;
this.showIsVisible = show;
76,6 → 70,7
this.generateIsVisible = generate;
}
 
// FIXME clear cache if row was updated
private static Map<SQLRow, AbstractSheetXml> cache = new HashMap<SQLRow, AbstractSheetXml>();
 
protected Class<? extends AbstractSheetXml> getSheetClass() {
91,72 → 86,65
AbstractSheetXml sheet = ctor.newInstance(row);
cache.put(row, sheet);
return sheet;
} catch (IllegalArgumentException e) {
} catch (Exception e) {
// FIXME Exception Handler ??
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
}
 
public void mouseClicked(MouseEvent e) {
}
// public void mouseReleased(MouseEvent e) {
// }
//
// public void mouseClicked(MouseEvent e) {
// }
//
// public void mouseEntered(MouseEvent e) {
// }
//
// public void mouseExited(MouseEvent e) {
// }
//
// public void mousePressed(MouseEvent e) {
//
// if (this.liste.getSelectedId() > 1) {
// if (e.getButton() == MouseEvent.BUTTON3) {
// System.err.println("Display Menu");
// JPopupMenu menuDroit = new JPopupMenu();
//
// final AbstractSheetXml bSheet =
// createAbstractSheet(this.liste.getSelectedRow());
// if (bSheet != null) {
//
// for (RowAction action : getRowActions()) {
// menuDroit.add(action.getAction());
// }
//
// menuDroit.pack();
// menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
// menuDroit.setVisible(true);
// }
// } else {
// String sfe =
// DefaultNXProps.getInstance().getStringProperty("ArticleSFE");
// Boolean bSfe = Boolean.valueOf(sfe);
// boolean isSFE = bSfe != null && bSfe.booleanValue();
// if (!isSFE) {
// if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() >= 2) {
// final AbstractSheetXml bSheet =
// createAbstractSheet(this.liste.getSelectedRow());
// if (!bSheet.getGeneratedFile().exists()) {
// bSheet.createDocumentAsynchronous();
// }
// bSheet.showPrintAndExportAsynchronous(true, false, false);
//
// }
// }
// }
// }
// }
 
public void mouseEntered(MouseEvent e) {
}
 
public void mouseExited(MouseEvent e) {
}
 
public void mousePressed(MouseEvent e) {
 
if (this.liste.getSelectedId() > 1) {
if (e.getButton() == MouseEvent.BUTTON3) {
System.err.println("Display Menu");
JPopupMenu menuDroit = new JPopupMenu();
 
final AbstractSheetXml bSheet = createAbstractSheet(this.liste.getSelectedRow());
if (bSheet != null) {
 
for (RowAction action : getRowActions()) {
menuDroit.add(action.getAction());
}
 
menuDroit.pack();
menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
menuDroit.setVisible(true);
}
} else {
String sfe = DefaultNXProps.getInstance().getStringProperty("ArticleSFE");
Boolean bSfe = Boolean.valueOf(sfe);
boolean isSFE = bSfe != null && bSfe.booleanValue();
if (!isSFE) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() >= 2) {
final AbstractSheetXml bSheet = createAbstractSheet(this.liste.getSelectedRow());
if (bSheet.isFileODSExist()) {
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
bSheet.showDocument();
} else {
bSheet.showPreviewDocument();
}
} else {
bSheet.genere(true, false);
}
}
}
}
}
}
 
private void sendMail(final AbstractSheetXml sheet, final boolean readOnly) {
 
SQLRow row = sheet.getSQLRow();
194,18 → 182,12
final Thread t = new Thread() {
@Override
public void run() {
final File f = sheet.getFilePDF();
final File f = sheet.getGeneratedPDFFile();
if (!f.exists()) {
try {
sheet.genere(false, false).get();
// final Component doc =
// ComptaPropsConfiguration.getOOConnexion().loadDocument(sheet.getFileODS(),
// true);
 
// Future<File> pdf = doc.saveToPDF(f);
 
EmailComposer.getInstance().compose(adresseMail, subject + (subject.trim().length() == 0 ? "" : ", ") + sheet.getFilePDF().getName(), "",
sheet.getFilePDF().getAbsoluteFile());
sheet.getOrCreateDocumentFile();
sheet.showPrintAndExport(false, false, true);
EmailComposer.getInstance().compose(adresseMail, subject + (subject.trim().length() == 0 ? "" : ", ") + f.getName(), "", f.getAbsoluteFile());
} catch (Exception e) {
e.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document PDF", e);
224,7 → 206,8
t.start();
} else {
try {
EmailComposer.getInstance().compose(adresseMail, subject + (subject.trim().length() == 0 ? "" : ", ") + sheet.getFileODS().getName(), "", sheet.getFileODS().getAbsoluteFile());
EmailComposer.getInstance().compose(adresseMail, subject + (subject.trim().length() == 0 ? "" : ", ") + sheet.getGeneratedFile().getName(), "",
sheet.getGeneratedFile().getAbsoluteFile());
} catch (Exception exn) {
ExceptionHandler.handle(null, "Impossible de créer le courriel", exn);
}
232,10 → 215,7
 
}
 
public void mouseReleased(MouseEvent e) {
}
 
public List<AbstractAction> addToMenu() {
public List<RowAction> addToMenu() {
return null;
}
 
266,46 → 246,44
if (this.showIsVisible) {
l.add(new RowAction(new AbstractAction(this.showString) {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(IListe.get(ev).getSelectedRow()).showDocument();
createAbstractSheet(IListe.get(ev).getSelectedRow()).openDocument(false);
}
 
}, false) {
@Override
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).isFileODSExist();
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
 
// if (bSheet.isFileOOExist()) {
// item.setFont(item.getFont().deriveFont(Font.BOLD));
// }
}
} else {
if (this.previewIsVisible) {
l.add(new RowAction(new AbstractAction(this.previewString) {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(liste.getSelectedRow()).showPreviewDocument();
try {
createAbstractSheet(IListe.get(ev).getSelectedRow()).showPreviewDocument();
} catch (Exception e) {
ExceptionHandler.handle("Impossilbe d'ouvrir le fichier", e);
}
}
 
}, false) {
 
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
// if (bSheet.isFileOOExist()) {
// item.setFont(item.getFont().deriveFont(Font.BOLD));
// }
 
}
}
 
// action supplémentaire
List<AbstractAction> list = addToMenu();
List<RowAction> list = addToMenu();
if (list != null) {
for (AbstractAction abstractAction : list) {
// JMenuItem itemItalic = new JMenuItem(abstractAction);
// itemItalic.setFont(itemItalic.getFont().deriveFont(Font.ITALIC));
l.add(new PredicateRowAction(abstractAction, false).setPredicate(IListeEvent.getNonEmptySelectionPredicate()));
for (RowAction rowAction : list) {
l.add(rowAction);
}
}
 
314,12 → 292,12
if (this.showIsVisible) {
l.add(new RowAction(new AbstractAction(this.showString) {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(liste.getSelectedRow()).showDocument();
createAbstractSheet(IListe.get(ev).getSelectedRow()).openDocument(false);
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
}
329,63 → 307,55
 
l.add(new RowAction(new AbstractAction(this.fastPrintString) {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(liste.getSelectedRow()).fastPrintDocument();
createAbstractSheet(IListe.get(ev).getSelectedRow()).fastPrintDocument();
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
 
l.add(new RowAction(new AbstractAction(this.printString) {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(liste.getSelectedRow()).printDocument();
createAbstractSheet(IListe.get(ev).getSelectedRow()).printDocument();
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
 
if (this.liste.getSelection().getSelectedIDs().size() > 1) {
l.add(new RowAction(new AbstractAction(this.printAllString) {
PredicateRowAction rowAction = new PredicateRowAction(new AbstractAction(this.printAllString) {
@Override
public void actionPerformed(ActionEvent e) {
 
final int[] l = liste.getJTable().getSelectedRows();
final List<SQLRow> list = new ArrayList<SQLRow>();
 
for (int i = 0; i < l.length; i++) {
list.add(liste.getModel().getTable().getRow(liste.getLine(l[i]).getRow().getID()));
}
 
// final int[] l = liste.getJTable().getSelectedRows();
// final List<SQLRow> list = new ArrayList<SQLRow>();
List<SQLRowAccessor> list = IListe.get(e).getSelectedRows();
ListeFastPrintFrame frame = new ListeFastPrintFrame(list, clazz);
frame.setVisible(true);
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
}
});
}, false);
rowAction.setPredicate(IListeEvent.createSelectionCountPredicate(2, Integer.MAX_VALUE));
 
}
l.add(rowAction);
 
}
 
if (this.showIsVisible) {
 
// if (createAbstractSheet(liste.getSelectedRow()).getSQLRow() != null) {
// if (createAbstractSheet(liste.getSelectedRow()).getSQLRow() !=
// null) {
l.add(new RowAction(new AbstractAction(this.mailPDFString) {
public void actionPerformed(ActionEvent ev) {
sendMail(createAbstractSheet(liste.getSelectedRow()), true);
sendMail(createAbstractSheet(IListe.get(ev).getSelectedRow()), true);
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
 
392,12 → 362,12
// }
l.add(new RowAction(new AbstractAction(this.mailString) {
public void actionPerformed(ActionEvent ev) {
sendMail(createAbstractSheet(liste.getSelectedRow()), false);
sendMail(createAbstractSheet(IListe.get(ev).getSelectedRow()), false);
}
}, false) {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return createAbstractSheet(liste.getSelectedRow()).isFileODSExist();
public boolean enabledFor(IListeEvent evt) {
return createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
}
});
 
406,7 → 376,9
l.add(new RowAction(new AbstractAction(this.generateString) {
public void actionPerformed(ActionEvent ev) {
 
createAbstractSheet(liste.getSelectedRow()).genere(true, false);
final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).getSelectedRow());
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
}
}, false) {
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/utils/NXDatabaseAccessor.java
21,12 → 21,13
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
 
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
 
// TODO use the one from Nego
public class NXDatabaseAccessor implements DatabaseAccessor {
@SuppressWarnings("unchecked")
public List<Ville> read() {
63,6 → 64,12
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
@Override
public void delete(Ville v) {
SQLTable villeT = Configuration.getInstance().getBase().getTable("VILLE");
final Where w = new Where(villeT.getField("NOM"), "=", v.getName()).and(new Where(villeT.getField("CODE_POSTAL"), "=", v.getCodepostal()));
villeT.getDBSystemRoot().getDataSource().execute("DELETE FROM " + villeT.getSQLName().quote() + " WHERE " + w);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/importer/CentsValueConverter.java
14,6 → 14,7
package org.openconcerto.erp.importer;
 
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.utils.GestionDevise;
 
public class CentsValueConverter extends ValueConverter {
public CentsValueConverter(SQLField f) {
24,18 → 25,7
long result = 0;
if (obj != null) {
try {
 
String string = obj.toString();
int index = string.indexOf(".");
if (index >= 0) {
string = string.substring(0, index) + string.substring(index + 1, string.length());
} else {
index = string.indexOf(",");
if (index >= 0) {
string = string.substring(0, index) + string.substring(index + 1, string.length());
}
}
result = Integer.parseInt(string);
return GestionDevise.parseLongCurrency(obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/AbstractGenerationDocumentPreferencePanel.java
13,6 → 13,7
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.utils.FileUtility;
import org.openconcerto.ui.DefaultGridBagConstraints;
238,7 → 239,7
final Color foregroundColor = UIManager.getColor("TextField.foreground");
 
for (final Entry<String, JTextField> entry : this.mapKeyTextOO.entrySet()) {
final File f = new File(SheetXml.getLocationForTuple(Tuple2.create("GetDefault", this.mapKeyLabel.get(entry.getKey())), false));
final File f = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory("Default");
final JTextField textField = entry.getValue();
if (f.exists()) {
textField.setForeground(foregroundColor);
254,7 → 255,7
}
 
for (final Entry<String, JTextField> entry : this.mapKeyTextPDF.entrySet()) {
final File f = new File(SheetXml.getLocationForTuple(Tuple2.create("GetDefault", this.mapKeyLabel.get(entry.getKey())), true));
final File f = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory("Default");
final JTextField textField = entry.getValue();
if (f.exists()) {
textField.setForeground(foregroundColor);
264,7 → 265,6
try {
textField.setText(f.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
281,8 → 281,14
 
private void updateTextFields(final Map<String, JTextField> map, final String format) throws IOException {
final Color foregroundColor = UIManager.getColor("TextField.foreground");
final DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
for (final Entry<String, JTextField> entry : map.entrySet()) {
final File f = new File(SheetXml.getLocationForTuple(Tuple2.create(entry.getKey(), this.mapKeyLabel.get(entry.getKey())), format.equalsIgnoreCase("PDF")));
final File f;
if (format.equalsIgnoreCase("PDF")) {
f = storage.getPDFOutputDirectory(entry.getKey());
} else {
f = storage.getDocumentOutputDirectory(entry.getKey());
}
final JTextField textField = entry.getValue();
if (f.exists()) {
textField.setForeground(foregroundColor);
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/TemplateNXProps.java
14,6 → 14,35
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.customer.report.FicheClientXmlSheet;
import org.openconcerto.erp.core.finance.accounting.report.BalanceSheet;
import org.openconcerto.erp.core.finance.accounting.report.GrandLivreSheet;
import org.openconcerto.erp.core.finance.accounting.report.JournauxSheet;
import org.openconcerto.erp.core.humanresources.payroll.report.EtatChargesPayeSheet;
import org.openconcerto.erp.core.humanresources.payroll.report.FichePayeSheet;
import org.openconcerto.erp.core.humanresources.payroll.report.LivrePayeSheet;
import org.openconcerto.erp.core.sales.invoice.report.ListeFactureXmlSheet;
import org.openconcerto.erp.core.sales.invoice.report.ListeVenteXmlSheet;
import org.openconcerto.erp.core.sales.invoice.report.VenteComptoirSheet;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
import org.openconcerto.erp.generationDoc.DefaultLocalTemplateProvider;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.TemplateManager;
import org.openconcerto.erp.generationDoc.TemplateProvider;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirFournisseurXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.CommandeXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.CourrierClientSheet;
import org.openconcerto.erp.generationDoc.gestcomm.EtatVentesXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.FicheRelanceSheet;
import org.openconcerto.erp.generationDoc.gestcomm.PointageXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.RelanceSheet;
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeEmisSheet;
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeSheet;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
79,10 → 108,87
return conf.getWD().getAbsolutePath() + File.separator + rowSociete.getString("NOM") + "-" + rowSociete.getID();
}
 
public void initDocumentLocalStorage() {
final DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
String propertyDefaultDirectory = getProperty(SheetXml.DEFAULT_PROPERTY_NAME + "OO");
if (propertyDefaultDirectory == null) {
System.out.println("Warning: no default directory stored for document output");
propertyDefaultDirectory = getDefaultStringValue();
}
storage.setDocumentDefaultDirectory(new File(propertyDefaultDirectory));
String propertyDefaultPDFDirectory = getProperty(SheetXml.DEFAULT_PROPERTY_NAME + "PDF");
if (propertyDefaultPDFDirectory == null) {
System.out.println("Warning: no default directory stored for PFD output");
propertyDefaultPDFDirectory = propertyDefaultDirectory;
}
 
storage.setPDFDefaultDirectory(new File(propertyDefaultPDFDirectory));
register(DevisXmlSheet.TEMPLATE_ID, DevisXmlSheet.TEMPLATE_PROPERTY_NAME);
register(VenteFactureXmlSheet.TEMPLATE_ID, VenteFactureXmlSheet.TEMPLATE_PROPERTY_NAME);
register(CommandeClientXmlSheet.TEMPLATE_ID, CommandeClientXmlSheet.TEMPLATE_PROPERTY_NAME);
register(BonLivraisonXmlSheet.TEMPLATE_ID, BonLivraisonXmlSheet.TEMPLATE_PROPERTY_NAME);
register(AvoirClientXmlSheet.TEMPLATE_ID, AvoirClientXmlSheet.TEMPLATE_PROPERTY_NAME);
register(AvoirFournisseurXmlSheet.TEMPLATE_ID, AvoirFournisseurXmlSheet.TEMPLATE_PROPERTY_NAME);
register(CommandeXmlSheet.TEMPLATE_ID, CommandeXmlSheet.TEMPLATE_PROPERTY_NAME);
register(EtatVentesXmlSheet.TEMPLATE_ID, EtatVentesXmlSheet.TEMPLATE_PROPERTY_NAME);
register(FicheClientXmlSheet.TEMPLATE_ID, FicheClientXmlSheet.TEMPLATE_PROPERTY_NAME);
register(FicheRelanceSheet.TEMPLATE_ID, FicheRelanceSheet.TEMPLATE_PROPERTY_NAME);
register(ReleveChequeSheet.TEMPLATE_ID, ReleveChequeSheet.TEMPLATE_PROPERTY_NAME);
register(ListeFactureXmlSheet.TEMPLATE_ID, ListeFactureXmlSheet.TEMPLATE_PROPERTY_NAME);
register(ListeVenteXmlSheet.TEMPLATE_ID, ListeVenteXmlSheet.TEMPLATE_PROPERTY_NAME);
register(BalanceSheet.TEMPLATE_ID, BalanceSheet.TEMPLATE_PROPERTY_NAME);
register(GrandLivreSheet.TEMPLATE_ID, GrandLivreSheet.TEMPLATE_PROPERTY_NAME);
register(JournauxSheet.TEMPLATE_ID, JournauxSheet.TEMPLATE_PROPERTY_NAME);
register(EtatChargesPayeSheet.TEMPLATE_ID, EtatChargesPayeSheet.TEMPLATE_PROPERTY_NAME);
register(FichePayeSheet.TEMPLATE_ID, FichePayeSheet.TEMPLATE_PROPERTY_NAME);
register(LivrePayeSheet.TEMPLATE_ID, LivrePayeSheet.TEMPLATE_PROPERTY_NAME);
register(CourrierClientSheet.TEMPLATE_ID, CourrierClientSheet.TEMPLATE_PROPERTY_NAME);
register(PointageXmlSheet.TEMPLATE_ID, PointageXmlSheet.TEMPLATE_PROPERTY_NAME);
register(RelanceSheet.TEMPLATE_ID, RelanceSheet.TEMPLATE_PROPERTY_NAME);
register(VenteComptoirSheet.TEMPLATE_ID, VenteComptoirSheet.TEMPLATE_PROPERTY_NAME);
register(ReleveChequeEmisSheet.TEMPLATE_ID, ReleveChequeEmisSheet.TEMPLATE_PROPERTY_NAME);
storage.dump();
 
}
 
private void register(String templateId, String propertyBaseName) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
if (propertyBaseName == null) {
throw new IllegalArgumentException("null propertyBaseName");
}
if (TemplateManager.getInstance().isKnwonTemplate(templateId)) {
System.err.println("Warning: registering known template id : " + templateId + " with property base name: " + propertyBaseName);
}
final DocumentLocalStorageManager storage = DocumentLocalStorageManager.getInstance();
final String propertyOO = getProperty(propertyBaseName + "OO");
if (propertyOO != null) {
 
storage.addDocumentDirectory(templateId, new File(propertyOO));
}
final String propertyPDF = getProperty(propertyBaseName + "PDF");
if (propertyPDF != null) {
storage.addPDFDirectory(templateId, new File(propertyPDF));
}
}
 
synchronized public static TemplateProps getInstance() {
if (instance == null) {
instance = new TemplateNXProps();
((TemplateNXProps) instance).initDocumentLocalStorage();
((TemplateNXProps) instance).initDefaulTemplateProvider();
}
return instance;
}
 
private void initDefaulTemplateProvider() {
final String property = getProperty("LocationTemplate");
final DefaultLocalTemplateProvider provider = new DefaultLocalTemplateProvider();
if (property != null) {
provider.setBaseDirectory(new File(property));
}
TemplateManager.getInstance().setDefaultProvider(provider);
TemplateManager.getInstance().dump();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDocumentGestCommPreferencePanel.java
17,7 → 17,6
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirFournisseurXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.CommandeXmlSheet;
25,27 → 24,35
import org.openconcerto.erp.generationDoc.gestcomm.RelanceSheet;
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeEmisSheet;
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeSheet;
import org.openconcerto.sql.Configuration;
import org.openconcerto.utils.StringUtils;
 
public class GenerationDocumentGestCommPreferencePanel extends AbstractGenerationDocumentPreferencePanel {
 
public GenerationDocumentGestCommPreferencePanel() {
super();
this.mapKeyLabel.put(DevisXmlSheet.getTuple2Location().get0(), DevisXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(AvoirClientXmlSheet.getTuple2Location().get0(), AvoirClientXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(DevisXmlSheet.getTuple2Location().get0(), DevisXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(BonLivraisonXmlSheet.getTuple2Location().get0(), BonLivraisonXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(VenteFactureXmlSheet.getTuple2Location().get0(), VenteFactureXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(RelanceSheet.getTuple2Location().get0(), RelanceSheet.getTuple2Location().get1());
this.mapKeyLabel.put(CommandeXmlSheet.getTuple2Location().get0(), CommandeXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(CommandeClientXmlSheet.getTuple2Location().get0(), CommandeClientXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(AvoirFournisseurXmlSheet.getTuple2Location().get0(), AvoirFournisseurXmlSheet.getTuple2Location().get1());
this.mapKeyLabel.put(CourrierClientSheet.getTuple2Location().get0(), CourrierClientSheet.getTuple2Location().get1());
this.mapKeyLabel.put(ReleveChequeEmisSheet.getTuple2Location().get0(), ReleveChequeEmisSheet.getTuple2Location().get1());
this.mapKeyLabel.put(ReleveChequeSheet.getTuple2Location().get0(), ReleveChequeSheet.getTuple2Location().get1());
this.mapKeyLabel.put(SheetXml.tupleDefault.get0(), SheetXml.tupleDefault.get1());
this.mapKeyLabel.put(DevisXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("DEVIS"));
this.mapKeyLabel.put(AvoirClientXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("AVOIR_CLIENT"));
 
this.mapKeyLabel.put(BonLivraisonXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("BON_DE_LIVRAISON"));
this.mapKeyLabel.put(VenteFactureXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("SAISIE_VENTE_FACTURE"));
this.mapKeyLabel.put(RelanceSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("RELANCE"));
this.mapKeyLabel.put(CommandeXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("COMMANDE"));
this.mapKeyLabel.put(CommandeClientXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("COMMANDE_CLIENT"));
this.mapKeyLabel.put(AvoirFournisseurXmlSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("AVOIR_FOURNISSEUR"));
this.mapKeyLabel.put(CourrierClientSheet.TEMPLATE_PROPERTY_NAME, getLabelFromTable("COURRIER_CLIENT"));
this.mapKeyLabel.put(ReleveChequeEmisSheet.TEMPLATE_PROPERTY_NAME, "Relevé chèque émis");
this.mapKeyLabel.put(ReleveChequeSheet.TEMPLATE_PROPERTY_NAME, "Relevé chèque");
// this.mapKeyLabel.put(SheetXml.tupleDefault.get0(), SheetXml.tupleDefault.get1());
// uiInit();
}
 
private String getLabelFromTable(String tableName) {
String pluralName = Configuration.getInstance().getDirectory().getElement(tableName).getPluralName();
pluralName = StringUtils.firstUp(pluralName);
return pluralName;
}
 
public String getTitleName() {
return "Destination des documents générés";
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDocumentComptaPreferencePanel.java
21,9 → 21,9
 
public GenerationDocumentComptaPreferencePanel() {
super();
this.mapKeyLabel.put(GrandLivreSheet.getTuple2Location().get0(), GrandLivreSheet.getTuple2Location().get1());
this.mapKeyLabel.put(JournauxSheet.getTuple2Location().get0(), JournauxSheet.getTuple2Location().get1());
this.mapKeyLabel.put(BalanceSheet.getTuple2Location().get0(), BalanceSheet.getTuple2Location().get1());
this.mapKeyLabel.put(GrandLivreSheet.TEMPLATE_PROPERTY_NAME, GrandLivreSheet.TEMPLATE_ID);
this.mapKeyLabel.put(JournauxSheet.TEMPLATE_PROPERTY_NAME, JournauxSheet.TEMPLATE_ID);
this.mapKeyLabel.put(BalanceSheet.TEMPLATE_PROPERTY_NAME, BalanceSheet.TEMPLATE_ID);
// uiInit();
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/DefaultLocalPreferencePanel.java
22,6 → 22,7
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
 
public class DefaultLocalPreferencePanel extends DefaultPreferencePanel {
71,4 → 72,14
public static File getPrefFile(String fileName) {
return new File(Configuration.getInstance().getConfDir(), "/Configuration/" + fileName);
}
 
public static Properties getPropertiesFromFile(String fileName) throws IOException {
final Properties properties = new Properties();
if (getPrefFile(fileName).exists()) {
FileInputStream fIp = new FileInputStream(getPrefFile(fileName));
properties.load(new BufferedInputStream(fIp));
fIp.close();
}
return properties;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/storage/StorageEngine.java
New file
0,0 → 1,30
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.storage;
 
import java.io.IOException;
import java.io.InputStream;
 
public interface StorageEngine {
public boolean isConfigured();
 
public boolean allowAutoStorage();
 
public void connect() throws IOException;
 
public void disconnect() throws IOException;
 
public void store(final InputStream inStream, String remotePath, String title, boolean synchronous) throws IOException;
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/storage/StorageEngines.java
New file
0,0 → 1,40
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.storage;
 
import java.util.ArrayList;
import java.util.List;
 
public class StorageEngines {
private static final StorageEngines instance = new StorageEngines();
 
public static StorageEngines getInstance() {
return instance;
}
 
private List<StorageEngine> engines = new ArrayList<StorageEngine>();
 
public List<StorageEngine> getActiveEngines() {
// TODO use a map to store active engines;
return engines;
}
 
public void addEngine(StorageEngine e) {
engines.add(e);
}
 
public void removeEngine(StorageEngine e) {
engines.remove(e);
}
}
/trunk/OpenConcerto/src/org/openconcerto/map/ui/StatusPanel.java
16,7 → 16,8
import org.openconcerto.map.model.Ville;
import org.openconcerto.ui.component.ComboLockedMode;
import org.openconcerto.ui.component.ITextComboCache;
import org.openconcerto.ui.component.ITextSelector;
import org.openconcerto.ui.component.combo.ISearchableTextCombo;
import org.openconcerto.utils.model.DefaultIListModel;
 
import java.awt.Dimension;
import java.awt.GridBagConstraints;
37,7 → 38,6
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
 
 
public class StatusPanel extends JPanel implements VilleRendererListener, ZoomListener {
 
/**
81,7 → 81,7
 
}
/* final JButton button = new JButton("Centrer"); */
ITextSelector txt = new ITextSelector("", ComboLockedMode.ITEMS_LOCKED, 40);
ISearchableTextCombo txt = new ISearchableTextCombo(ComboLockedMode.ITEMS_LOCKED, 1, 40);
txt.addValueListener(new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
100,8 → 100,7
txt.setMinimumSearch(0);
txt.setMaximumResult(200);
 
ITextComboCache cache = new ITextComboCacheVille();
txt.initCache(cache);
txt.initCache(new DefaultIListModel<String>(new ITextComboCacheVille().getCache()));
c.weightx = 1;
c.gridx++;
this.add(txt, c);
/trunk/OpenConcerto/src/org/openconcerto/map/ui/ITextComboVilleViewer.java
14,9 → 14,9
package org.openconcerto.map.ui;
 
import org.openconcerto.map.model.Ville;
import org.openconcerto.ui.PopupMouseListener;
import org.openconcerto.ui.component.ComboLockedMode;
import org.openconcerto.ui.component.ITextSelector;
import org.openconcerto.ui.component.IComboCacheListModel;
import org.openconcerto.ui.component.combo.ISearchableTextCombo;
import org.openconcerto.ui.component.text.DocumentComponent;
import org.openconcerto.ui.component.text.TextComponent;
import org.openconcerto.ui.state.WindowStateManager;
27,6 → 27,7
import org.openconcerto.utils.checks.EmptyObjectHelper;
import org.openconcerto.utils.checks.ValidListener;
import org.openconcerto.utils.checks.ValidState;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
39,12 → 40,9
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
 
55,7 → 53,7
* Selecteur de Ville
*/
private static final long serialVersionUID = 3397210337907076649L;
private final ITextSelector text = new ITextSelector(ComboLockedMode.ITEMS_LOCKED);
private final ISearchableTextCombo text = new ISearchableTextCombo(ComboLockedMode.UNLOCKED);
private final JButton button = new JButton("Afficher sur la carte");
private Ville currentVille = null;
private final EmptyObjectHelper emptyHelper;
81,7 → 79,7
});
 
this.cache = new ITextComboCacheVille();
this.text.initCache(this.cache);
new IComboCacheListModel(this.cache).initCacheLater(this.text);
this.add(this.text, BorderLayout.CENTER);
 
this.add(this.button, BorderLayout.EAST);
108,44 → 106,16
}
}
});
this.text.getDocument().addDocumentListener(new DocumentListener() {
 
public void changedUpdate(final DocumentEvent e) {
ITextComboVilleViewer.this.currentVille = Ville.getVilleFromVilleEtCode(ITextComboVilleViewer.this.text.getValue());
this.text.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update(DocumentEvent e) {
ITextComboVilleViewer.this.currentVille = Ville.getVilleFromVilleEtCode(getText(e.getDocument()));
ITextComboVilleViewer.this.button.setEnabled(ITextComboVilleViewer.this.currentVille != null && ITextComboVilleViewer.this.isEnabled());
 
}
 
public void insertUpdate(final DocumentEvent e) {
this.changedUpdate(e);
}
 
public void removeUpdate(final DocumentEvent e) {
this.changedUpdate(e);
}
});
final JPopupMenu popupMenu = new JPopupMenu();
// FIXME ajouter la possibilité de supprimer une ville précédemment enregistrée
final JMenuItem menuItem = new JMenuItem("Enregistrer cette ville");
menuItem.addActionListener(new ActionListener() {
 
public void actionPerformed(final ActionEvent e) {
final String t = ITextComboVilleViewer.this.text.getTextComp().getText();
ITextComboVilleViewer.this.cache.addToCache(t);
final Ville createVilleFrom = ITextComboVilleViewer.this.cache.createVilleFrom(t);
if (createVilleFrom != null) {
final String villeEtCode = createVilleFrom.getVilleEtCode();
ITextComboVilleViewer.this.setValue(villeEtCode);
ITextComboVilleViewer.this.firePropertyChange("value", null, villeEtCode);
}
}
});
popupMenu.add(menuItem);
 
this.text.getTextComp().addMouseListener(new PopupMouseListener(popupMenu));
 
}
 
@Override
public void addEmptyListener(final EmptyListener l) {
this.emptyHelper.addListener(l);
198,6 → 168,9
 
@Override
public ValidState getValidState() {
// TODO listen to Ville list, otherwise if we type a city that doesn't exist, the value
// change and we're invalid, then we add the city but this does not change the value of the
// combo and thus we're still invalid even though the city is now in the list
final Ville villeFromVilleEtCode = Ville.getVilleFromVilleEtCode(this.getValue());
final boolean b = villeFromVilleEtCode != null;
if (b) {
224,7 → 197,6
public void setEnabled(final boolean enabled) {
super.setEnabled(enabled);
this.text.setEnabled(enabled);
this.text.setEditable(enabled);
this.button.setEnabled(enabled);
}
 
/trunk/OpenConcerto/src/org/openconcerto/map/ui/ITextComboCacheVille.java
21,7 → 21,6
 
import javax.swing.JOptionPane;
 
 
public class ITextComboCacheVille implements ITextComboCache {
final ArrayList<String> villesNames = Ville.getVillesNames();
private Ville lastGood;
44,6 → 43,11
return v;
}
 
@Override
public boolean isValid() {
return this.villesNames.size() > 0;
}
 
public void addToCache(String string) {
Ville v = this.createVilleFrom(string);
if (v != null) {
55,6 → 59,9
}
 
public void deleteFromCache(String string) {
final Ville v = Ville.getVilleFromVilleEtCode(string);
if (v != null)
Ville.removeVille(v);
}
 
public List<String> getCache() {
64,7 → 71,8
return villesNames;
}
 
public List<String> loadCache() {
@Override
public List<String> loadCache(final boolean readCache) {
return villesNames;
}
 
/trunk/OpenConcerto/src/org/openconcerto/map/model/DatabaseAccessor.java
18,6 → 18,7
public interface DatabaseAccessor {
 
public void store(Ville v);
public void delete(Ville v);
 
public List<Ville> read();
}
/trunk/OpenConcerto/src/org/openconcerto/map/model/Ville.java
32,7 → 32,6
import javax.swing.JFrame;
import javax.swing.UIManager;
 
 
public class Ville {
 
private static Map<String, Ville> map = new HashMap<String, Ville>();
130,6 → 129,16
// FIXME: fire missing
}
 
public static synchronized void removeVille(final Ville v) {
villes.remove(v);
final String villeEtCode = v.getVilleEtCode();
villesNames.remove(villeEtCode);
map.remove(villeEtCode);
 
accessor.delete(v);
// FIXME: fire missing
}
 
// ** getter
 
private static final synchronized void await() {
/trunk/OpenConcerto/src/org/openconcerto/openoffice/LengthUnit.java
25,7 → 25,7
* Units of length.
*
* @author Sylvain CUAZ
* @see http://www.w3.org/TR/xsl/#d0e5752
* @see <a href="http://www.w3.org/TR/xsl/#d0e5752">W3C Definitions</a>
*/
public enum LengthUnit {
/**
/trunk/OpenConcerto/src/org/openconcerto/openoffice/ODEpoch.java
New file
0,0 → 1,154
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.openoffice;
 
import org.openconcerto.utils.TimeUtils;
 
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TimeZone;
 
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
 
/**
* The null date of an OpenDocument.
*/
public final class ODEpoch {
 
static private final BigDecimal MS_PER_DAY = BigDecimal.valueOf(24l * 60l * 60l * 1000l);
static private final DateFormat DATE_FORMAT;
static private final ODEpoch DEFAULT_EPOCH;
static private final Map<String, ODEpoch> cache = new LinkedHashMap<String, ODEpoch>(4, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, ODEpoch> eldest) {
return this.size() > 16;
}
};
 
static {
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
DATE_FORMAT.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
try {
DEFAULT_EPOCH = new ODEpoch("1899-12-30");
} catch (ParseException e) {
// shouldn't happen since string are constants
throw new IllegalStateException(e);
}
}
 
static public final ODEpoch getDefaultEpoch() {
return DEFAULT_EPOCH;
}
 
static public final ODEpoch getInstance(String date) throws ParseException {
if (date == null || date.equals(DEFAULT_EPOCH.getDateString())) {
return DEFAULT_EPOCH;
} else {
ODEpoch res = cache.get(date);
if (res == null) {
res = new ODEpoch(date);
cache.put(date, res);
}
return res;
}
}
 
static private final Calendar parse(final String date) throws ParseException {
final Calendar cal = (Calendar) DATE_FORMAT.getCalendar().clone();
cal.setTime(DATE_FORMAT.parse(date));
return cal;
}
 
private final String dateString;
private final Calendar epochUTC;
 
private ODEpoch(final String date) throws ParseException {
this.dateString = date;
this.epochUTC = parse(date);
assert this.epochUTC.getTimeZone().equals(DATE_FORMAT.getTimeZone());
}
 
public final String getDateString() {
return this.dateString;
}
 
public final Calendar getCalendar() {
return (Calendar) this.epochUTC.clone();
}
 
private final Calendar getDate(final Duration duration) {
// If we don't use the UTC calendar, we go from 0:00 (the epoch), we add n days, we get
// to the last Sunday of March at 0:00, so far so good, but then we add say 10 hours, thus
// going through the change of offset, and arriving at 11:00.
final Calendar res = getCalendar();
duration.addTo(res);
return res;
}
 
public final Duration normalizeToDays(final Duration dur) {
final Duration res = dur.getYears() == 0 && dur.getMonths() == 0 ? dur : getDuration(getDays(dur));
assert res.getYears() == 0 && res.getMonths() == 0;
return res;
}
 
public final Duration normalizeToHours(final Duration dur) {
final Duration durationInDays = normalizeToDays(dur);
final BigInteger days = (BigInteger) durationInDays.getField(DatatypeConstants.DAYS);
final BigInteger hours = ((BigInteger) durationInDays.getField(DatatypeConstants.HOURS)).add(days.multiply(BigInteger.valueOf(24)));
return TimeUtils.getTypeFactory().newDuration(days.signum() >= 0, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ZERO, hours, (BigInteger) durationInDays.getField(DatatypeConstants.MINUTES),
(BigDecimal) durationInDays.getField(DatatypeConstants.SECONDS));
}
 
public final BigDecimal getDays(final Duration duration) {
return getDays(getDate(duration));
}
 
public final BigDecimal getDays(final Calendar cal) {
// can't use Duration.normalizeWith() since it doesn't handle DST, i.e. going from winter to
// summer at midnight will miss a day
final long diff = TimeUtils.normalizeLocalTime(cal) - this.epochUTC.getTimeInMillis();
return BigDecimal.valueOf(diff).divide(MS_PER_DAY, MathContext.DECIMAL128);
}
 
public final Calendar getDate(final BigDecimal days) {
return getDate(days, Calendar.getInstance());
}
 
public final Calendar getDate(final BigDecimal days, final Calendar res) {
final Calendar utcCal = getDate(getDuration(days));
// can't use getTimeZone().getOffset() since we have no idea for the UTC time
return TimeUtils.copyLocalTime(utcCal, res);
}
 
private final static Duration getDuration(final BigDecimal days) {
final BigDecimal posDays = days.abs();
final BigInteger wholeDays = posDays.toBigInteger().abs();
final BigDecimal hours = posDays.subtract(new BigDecimal(wholeDays)).multiply(BigDecimal.valueOf(24));
final BigInteger wholeHours = hours.toBigInteger();
final BigDecimal minutes = hours.subtract(new BigDecimal(wholeHours)).multiply(BigDecimal.valueOf(60));
final BigInteger wholeMinutes = minutes.toBigInteger();
// round to 16 digits, i.e. 10^-14 seconds is more than enough
// it is required since the number coming from getDays() might have been rounded
final BigDecimal seconds = minutes.subtract(new BigDecimal(wholeMinutes)).multiply(BigDecimal.valueOf(60)).round(MathContext.DECIMAL64);
return TimeUtils.getTypeFactory().newDuration(days.signum() >= 0, BigInteger.ZERO, BigInteger.ZERO, wholeDays, wholeHours, wholeMinutes, seconds);
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/CellStyle.java
13,23 → 13,44
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.Log;
import org.openconcerto.openoffice.ODPackage;
import org.openconcerto.openoffice.ODValueType;
import org.openconcerto.openoffice.Style;
import org.openconcerto.openoffice.StyleStyle;
import org.openconcerto.openoffice.StyleStyleDesc;
import org.openconcerto.openoffice.StyledNode;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.openoffice.style.RelationalOperator;
import org.openconcerto.openoffice.style.SideStyleProperties;
import org.openconcerto.openoffice.style.data.BooleanStyle;
import org.openconcerto.openoffice.style.data.DataStyle;
import org.openconcerto.openoffice.style.data.NumberStyle;
import org.openconcerto.openoffice.text.ParagraphStyle.StyleParagraphProperties;
import org.openconcerto.openoffice.text.TextStyle.StyleTextProperties;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.Tuple3;
import org.openconcerto.xml.JDOMUtils;
 
import java.awt.Color;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.jdom.Attribute;
import org.jdom.Element;
 
public class CellStyle extends StyleStyle {
 
private static final Pattern numberPatrn = Pattern.compile("-?\\d+(?:\\.\\d+)?");
private static final Pattern escapedQuotePatrn = Pattern.compile("\"\"", Pattern.LITERAL);
private static final Pattern stringPatrn = Pattern.compile("\"(?:[^\\p{Cntrl}\"]|\\p{Space}|" + escapedQuotePatrn.pattern() + ")*\"");
private static final String valuePatrn = "(" + numberPatrn.pattern() + "|" + stringPatrn.pattern() + ")";
private static final Pattern cellContentPatrn = Pattern.compile("cell-content\\(\\) *(" + RelationalOperator.OR_PATTERN + ") *" + valuePatrn + "");
private static final Pattern cellContentBetweenPatrn = Pattern.compile("cell-content-is(?:-not)?-between\\(" + valuePatrn + ", *" + valuePatrn + "\\)");
 
// from section 18.728 in v1.2-part1
public static final StyleStyleDesc<CellStyle> DESC = new StyleStyleDesc<CellStyle>(CellStyle.class, XMLVersion.OD, "table-cell", "ce", "table", Arrays.asList("table:body",
"table:covered-table-cell", "table:even-rows", "table:first-column", "table:first-row", "table:last-column", "table:last-row", "table:odd-columns", "table:odd-rows", "table:table-cell")) {
42,8 → 63,54
public CellStyle create(ODPackage pkg, Element e) {
return new CellStyle(pkg, e);
}
 
@Override
protected boolean supportConditions() {
return true;
}
 
@Override
protected Element evaluateConditions(final StyledNode<CellStyle, ?> styledNode, final List<Element> styleMaps) {
final Cell<?> cell = (Cell<?>) styledNode;
final Object cellValue = cell.getValue();
for (final Element styleMap : styleMaps) {
final String condition = styleMap.getAttributeValue("condition", getVersion().getSTYLE()).trim();
Matcher matcher = cellContentPatrn.matcher(condition);
if (matcher.matches()) {
if (RelationalOperator.getInstance(matcher.group(1)).compare(cellValue, parse(matcher.group(2))))
return styleMap;
} else if ((matcher = cellContentBetweenPatrn.matcher(condition)).matches()) {
final boolean wantBetween = condition.startsWith("cell-content-is-between");
assert wantBetween ^ condition.startsWith("cell-content-is-not-between");
final Object o1 = parse(matcher.group(1));
final Object o2 = parse(matcher.group(2));
final boolean isBetween = CompareUtils.compare(cellValue, o1) >= 0 && CompareUtils.compare(cellValue, o2) <= 0;
if (isBetween == wantBetween)
return styleMap;
} else {
// If a consumer does not recognize a condition, it shall ignore the <style:map>
// element containing the condition.
Log.get().fine("Ignoring " + JDOMUtils.output(styleMap));
}
}
return null;
}
};
 
private static final Pattern conditionPatrn = Pattern.compile("value\\(\\) *(" + RelationalOperator.OR_PATTERN + ") *(true|false|" + numberPatrn.pattern() + ")");
 
// from style:condition :
// "n is a number for non-Boolean data styles and true or false for Boolean data styles"
private static final Object convertForCondition(final Object value, final DataStyle style) {
final Object castedValue;
if (style instanceof BooleanStyle) {
castedValue = BooleanStyle.toBoolean(value);
} else {
castedValue = NumberStyle.toNumber(value, style.getEpoch());
}
return castedValue;
}
 
private StyleTableCellProperties cellProps;
private StyleTextProperties textProps;
private StyleParagraphProperties pProps;
52,10 → 119,67
super(pkg, tableColElem);
}
 
public final DataStyle getDataStyle() {
return (DataStyle) Style.getReferencedStyle(getPackage(), getElement().getAttribute("data-style-name", getSTYLE()));
private final DataStyle getDataStyle(final Attribute name) {
return (DataStyle) Style.getReferencedStyle(getPackage(), name);
}
 
// return value since it can be changed depending on the data style.
// e.g. in OO if we input 12:30 in an empty cell, it will have value-type="time"
// but if we had previously set a number style (like 0,00) it would have been converted to 0,52
// value-type="float"
final Tuple3<DataStyle, ODValueType, Object> getDataStyle(final Object cellValue, final ODValueType valueType, final boolean onlyCast) {
DataStyle res = getDataStyle(this.getElement().getAttribute("data-style-name", this.getSTYLE()));
ODValueType returnValueType = valueType;
Object returnCellValue = cellValue;
// if the type is null, then the cell is empty so don't try to convert the cell value or
// evaluate conditions
if (res != null && valueType != null) {
if (!onlyCast) {
final Object convertedForStyle = res.convert(cellValue);
// if conversion is successful
if (convertedForStyle != null) {
returnCellValue = convertedForStyle;
returnValueType = res.getDataType();
}
}
 
final List<?> styleMaps = res.getElement().getChildren("map", getSTYLE());
if (styleMaps.size() > 0) {
final Object converted = convertForCondition(returnCellValue, res);
// we can't compare() so don't try
if (converted != null) {
for (Object child : styleMaps) {
final Element styleMap = (Element) child;
final Matcher matcher = conditionPatrn.matcher(styleMap.getAttributeValue("condition", getSTYLE()).trim());
if (!matcher.matches())
throw new IllegalStateException("Cannot parse " + JDOMUtils.output(styleMap));
if (RelationalOperator.getInstance(matcher.group(1)).compare(converted, parse(matcher.group(2)))) {
res = getDataStyle(styleMap.getAttribute("apply-style-name", getSTYLE()));
break;
}
}
}
}
}
// if the type is null, then the cell is empty, we cannot make up some value, otherwise
// don't change it to null
assert (valueType == null) == (returnValueType == null) : "don't change type to null";
assert !onlyCast || (returnValueType == valueType && returnCellValue == cellValue) : "Requested to only cast, but different object";
// if res is null, the document is incoherent (non existing style name)
return res == null ? null : Tuple3.create(res, returnValueType, returnCellValue);
}
 
static private Object parse(String val) {
if (val.equalsIgnoreCase("true"))
return Boolean.TRUE;
else if (val.equalsIgnoreCase("false"))
return Boolean.FALSE;
else if (val.charAt(0) == '"')
return escapedQuotePatrn.matcher(val.substring(1, val.length() - 1)).replaceAll("\"");
else
return new BigDecimal(val);
}
 
public final Color getBackgroundColor() {
return getTableCellProperties().getBackgroundColor();
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/SheetTableModel.java
14,6 → 14,7
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.utils.CompareUtils;
 
import javax.swing.table.AbstractTableModel;
 
76,6 → 77,50
throw new IndexOutOfBoundsException("column: " + columnIndex + " not between 0 and " + (this.getColumnCount() - 1));
}
 
@Override
public int hashCode() {
final int rowCount = getRowCount();
final int columnCount = getColumnCount();
final int prime = 17;
int result = 1;
result = prime * result + rowCount;
result = prime * result + columnCount;
// use some of the values
final int maxX = Math.min(4, columnCount);
final int maxY = Math.min(8, rowCount);
for (int y = 0; y < maxY; y++) {
for (int x = 0; x < maxX; x++) {
final Object v = this.getValueAt(x, y);
result = prime * result + (v == null ? 0 : v.hashCode());
}
}
return result;
}
 
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof SheetTableModel))
return false;
final SheetTableModel<?> other = (SheetTableModel<?>) obj;
 
final int rowCount = this.getRowCount();
final int columnCount = this.getColumnCount();
if (other.getRowCount() != rowCount || other.getColumnCount() != columnCount)
return false;
 
for (int y = 0; y < rowCount; y++) {
for (int x = 0; x < columnCount; x++) {
if (!CompareUtils.equals(this.getValueAt(x, y), other.getValueAt(x, y)))
return false;
}
}
return true;
}
 
static public final class MutableTableModel<D extends ODDocument> extends SheetTableModel<D> {
 
MutableTableModel(final Table<D> table, final int row, final int column) {
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/Axis.java
New file
0,0 → 1,79
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.StyleProperties;
 
import org.jdom.Attribute;
import org.jdom.Element;
 
public enum Axis {
ROW("row"), COLUMN("column");
 
private final String shortName, elemName, headerName, groupName, pluralName, repeatedAttrName;
 
private Axis(final String shortName) {
this.shortName = shortName;
 
this.elemName = "table-" + shortName;
this.headerName = "table-header-" + shortName + "s";
this.groupName = this.elemName + "-group";
this.pluralName = this.elemName + "s";
this.repeatedAttrName = "number-" + shortName + "s-repeated";
}
 
public final String getShortName() {
return this.shortName;
}
 
public final String getElemName() {
return this.elemName;
}
 
public final String getHeaderName() {
return this.headerName;
}
 
public final String getGroupName() {
return this.groupName;
}
 
public final String getPluralName() {
return this.pluralName;
}
 
public final String getRepeatedAttrName() {
return this.repeatedAttrName;
}
 
final Attribute getRepeatedAttr(final Element elem) {
assert elem.getName().equals(this.getElemName());
return elem.getAttribute(getRepeatedAttrName(), elem.getNamespace());
}
 
final int getRepeated(final Element elem) {
assert elem.getName().equals(this.getElemName());
return StyleProperties.parseInt(elem.getAttributeValue(getRepeatedAttrName(), elem.getNamespace()), 1);
}
 
final void setRepeated(final Element elem, final int i) {
assert elem.getName().equals(this.getElemName());
if (i < 1)
throw new IllegalArgumentException("repeated <1 : " + i);
if (i == 1)
elem.removeAttribute(getRepeatedAttrName(), elem.getNamespace());
else
elem.setAttribute(getRepeatedAttrName(), String.valueOf(i), elem.getNamespace());
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/TableGroup.java
New file
0,0 → 1,174
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.ODNode;
import org.openconcerto.openoffice.StyleProperties;
import org.openconcerto.utils.Tuple2;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
import org.jdom.Element;
 
/**
* A group of columns/rows that can be hidden.
*
* @author Sylvain CUAZ
*/
public class TableGroup extends ODNode {
 
static Tuple2<TableGroup, List<Element>> createRoot(final Table<?> table, final Axis col) {
final TableGroup group = new TableGroup(table, col);
return Tuple2.create(group, group.flatten());
}
 
private final Table<?> table;
private final Axis axis;
private final TableGroup parent;
private final List<TableGroup> children;
 
private int headerCount;
private int first;
private int size;
 
// root group
private TableGroup(final Table<?> table, final Axis col) {
this(table, col, null, table.getElement(), 0);
}
 
private TableGroup(Table<?> table, TableGroup parent, Element elem, final int first) {
this(table, parent.axis, parent, elem, first);
}
 
private TableGroup(Table<?> table, final Axis col, TableGroup parent, Element elem, final int first) {
super(elem);
if (table == null)
throw new NullPointerException("null table");
this.table = table;
this.axis = col;
this.parent = parent;
this.first = first;
this.children = new ArrayList<TableGroup>();
}
 
private List<Element> flatten() {
// max() since a group can have only group children
final List<Element> res = new ArrayList<Element>(Math.max(128, getElement().getContentSize()));
final String fullName = this.axis.getElemName();
final String groupName = this.axis.getGroupName();
final String pluralName = this.axis.getPluralName();
 
// A table shall not contain more than one <table:table-header-rows> element.
final Element header = this.getElement().getChild(this.axis.getHeaderName(), getElement().getNamespace());
if (header != null)
this.headerCount = Table.flattenChildren(res, header, this.axis);
else
this.headerCount = 0;
int size = this.headerCount;
 
this.children.clear();
@SuppressWarnings("unchecked")
final List<Element> content = new ArrayList<Element>(getElement().getChildren());
for (final Element child : content) {
if (child.getName().equals(fullName)) {
size += Table.flatten1(res, child, this.axis);
} else if (child.getName().equals(pluralName)) {
// ignore table-rows element (but add its children)
size += Table.flattenChildren(res, child, this.axis);
} else if (child.getName().equals(groupName)) {
final TableGroup g = new TableGroup(getTable(), this, child, this.first + size);
this.children.add(g);
res.addAll(g.flatten());
size += g.getSize();
}
// else nothing to do (header or soft-page-break)
}
 
this.size = size;
 
return res;
}
 
public final Table<?> getTable() {
return this.table;
}
 
/**
* The parent of this group.
*
* @return the parent, <code>null</code> if this is the root group.
*/
public final TableGroup getParent() {
return this.parent;
}
 
public final List<TableGroup> getChildren() {
return Collections.unmodifiableList(this.children);
}
 
final TableGroup getDescendentOrSelfContaining(final int y) {
if (!this.contains(y))
return null;
for (final TableGroup g : this.getChildren()) {
final TableGroup res = g.getDescendentOrSelfContaining(y);
if (res != null)
return res;
}
return this;
}
 
public final boolean isDisplayed() {
if (this.getParent() == null)
return true;
else
// from table:display : the default value for this attribute is true
return StyleProperties.parseBoolean(getElement().getAttributeValue("display", getElement().getNamespace()), true);
}
 
/**
* The index of the first row/column in this group.
*
* @return index of the first element.
*/
public final int getFirst() {
return this.first;
}
 
public final int getHeaderCount() {
return this.headerCount;
}
 
public final int getSize() {
return this.size;
}
 
public final boolean contains(final int i) {
return i >= this.getFirst() && i < this.getFirst() + this.getSize();
}
 
final int getFollowingHeaderCount() {
int res = this.getHeaderCount();
// the table and each distinct group may contain one <table:table-header-rows> element, if
// and only if the table rows contained in the <table:table-header-rows> elements are
// adjacent.
for (final TableGroup g : this.getChildren()) {
if (g.getFirst() != this.getFirst() + res)
break;
res += g.getFollowingHeaderCount();
}
return res;
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/Row.java
16,10 → 16,13
*/
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.openoffice.StyleDesc;
import org.openconcerto.openoffice.StyleProperties;
import org.openconcerto.openoffice.StyleStyleDesc;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.openoffice.ODDocument;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import org.jdom.Element;
39,46 → 42,79
 
private final Table<D> parent;
private final int index;
private int repeated;
// the same immutable cell instance is repeated, but each MutableCell is only once
// ATTN MutableCell have their index as attribute
private final List<Cell<D>> cells;
// array is faster than List
private Cell<D>[] cells;
private int cellCount;
 
Row(Table<D> parent, Element tableRowElem, int index) {
super(parent.getODDocument(), tableRowElem, RowStyle.class);
Row(Table<D> parent, Element tableRowElem, int index, StyleDesc<RowStyle> styleDesc, StyleDesc<CellStyle> cellStyleDesc) {
super(parent.getODDocument(), tableRowElem, styleDesc);
this.parent = parent;
this.index = index;
this.cells = new ArrayList<Cell<D>>();
this.repeated = Axis.ROW.getRepeated(getElement());
@SuppressWarnings("unchecked")
final Cell<D>[] unsafe = new Cell[parent.getColumnCount()];
this.cells = unsafe;
this.cellCount = 0;
for (final Element cellElem : this.getCellElements()) {
addCellElem(cellElem);
addCellElem(cellElem, cellStyleDesc);
}
}
 
private final void ensureRoom(int additionalItems) {
final int requiredSize = this.getCellCount() + additionalItems;
if (requiredSize > this.cells.length) {
this.cells = Arrays.copyOf(this.cells, requiredSize);
}
}
 
protected final Table<D> getSheet() {
return this.parent;
}
 
// ATTN index of the first row
final int getY() {
return this.index;
}
 
// plain Cell instances have multiple indexes (if repeated) but MutableCell are unique
final int getX(MutableCell<D> c) {
return this.cells.indexOf(c);
// inclusive
final int getLastY() {
return this.getY() + this.getRepeated() - 1;
}
 
private void addCellElem(final Element cellElem) {
final Cell<D> cell = new Cell<D>(this, cellElem);
this.cells.add(cell);
final int getRepeated() {
return this.repeated;
}
 
final String repeatedS = cellElem.getAttributeValue("number-columns-repeated", this.getSheet().getTABLE());
if (repeatedS != null) {
final int toRepeat = Integer.parseInt(repeatedS) - 1;
for (int i = 0; i < toRepeat; i++) {
this.cells.add(cell);
final void setRepeated(int newRepeated) {
Axis.ROW.setRepeated(getElement(), newRepeated);
this.repeated = newRepeated;
}
 
// plain Cell instances have multiple indexes (if repeated) but MutableCell are unique
final int getX(MutableCell<D> c) {
final int stop = this.getCellCount();
for (int i = 0; i < stop; i++) {
final Cell<D> item = this.cells[i];
if (c.equals(item))
return i;
}
return -1;
}
 
private void addCellElem(final Element cellElem, StyleDesc<CellStyle> cellStyleDesc) {
final Cell<D> cell = new Cell<D>(this, cellElem, cellStyleDesc);
final String repeatedS = cellElem.getAttributeValue("number-columns-repeated", this.getTABLE());
final int toRepeat = StyleProperties.parseInt(repeatedS, 1);
final int stop = this.cellCount + toRepeat;
for (int i = this.cellCount; i < stop; i++) {
this.cells[i] = cell;
}
this.cellCount = stop;
}
 
/**
* All cells of this row.
*
90,8 → 126,16
return this.getElement().getChildren();
}
 
protected final int getCellCount() {
return this.cellCount;
}
 
private final List<Cell<D>> getCellsAsList() {
return Arrays.asList(this.cells);
}
 
protected final Cell<D> getCellAt(int col) {
return this.cells.get(col);
return this.cells[col];
}
 
protected final Cell<D> getValidCellAt(int col) {
102,68 → 146,41
}
 
public final MutableCell<D> getMutableCellAt(final int col) {
final Cell c = this.getValidCellAt(col);
final Cell<D> c = this.getValidCellAt(col);
if (!(c instanceof MutableCell)) {
final Element element = c.getElement();
final String repeatedS = element.getAttributeValue("number-columns-repeated", this.getSheet().getTABLE());
if (repeatedS != null) {
final int repeated = Integer.parseInt(repeatedS);
final int firstIndex = this.cells.indexOf(c);
final int lastIndex = firstIndex + repeated - 1;
 
final int preRepeated = col - firstIndex;
final int postRepeated = lastIndex - col;
 
casse(element, firstIndex, preRepeated, true);
element.removeAttribute("number-columns-repeated", this.getSheet().getTABLE());
casse(element, col + 1, postRepeated, false);
RepeatedBreaker.<D> getCellBreaker().breakRepeated(this, getCellsAsList(), col);
}
this.cells.set(col, new MutableCell<D>(this, element));
}
return (MutableCell<D>) this.getValidCellAt(col);
}
 
private final void casse(Element element, int firstIndex, int repeat, boolean before) {
if (repeat > 0) {
final Element newElem = (Element) element.clone();
element.getParentElement().addContent(element.getParent().indexOf(element) + (before ? 0 : 1), newElem);
newElem.setAttribute("number-columns-repeated", repeat + "", this.getSheet().getTABLE());
final Cell<D> preCell = new Cell<D>(this, newElem);
for (int i = 0; i < repeat; i++) {
this.cells.set(firstIndex + i, preCell);
}
}
}
 
// rempli cette ligne avec autant de cellules vides qu'il faut
void columnCountChanged() {
final int diff = this.getSheet().getColumnCount() - this.cells.size();
void columnCountChanged(StyleStyleDesc<CellStyle> cellStyleDesc) {
final int diff = this.getSheet().getColumnCount() - getCellCount();
if (diff < 0) {
throw new IllegalStateException("should have used Table.removeColumn()");
} else if (diff > 0) {
final Element e = Cell.createEmpty(this.getSheet().getODDocument().getVersion(), diff);
this.getElement().addContent(e);
addCellElem(e);
this.ensureRoom(diff);
addCellElem(e, cellStyleDesc);
}
if (this.cells.size() != this.getSheet().getColumnCount())
throw new IllegalStateException();
assert this.getCellCount() == this.getSheet().getColumnCount();
}
 
void checkRemove(int firstIndex, int lastIndexExcl) {
if (lastIndexExcl > this.cells.size()) {
throw new IndexOutOfBoundsException(lastIndexExcl + " > " + this.cells.size());
if (lastIndexExcl > getCellCount()) {
throw new IndexOutOfBoundsException(lastIndexExcl + " > " + getCellCount());
}
if (!this.getCellAt(firstIndex).isValid())
throw new IllegalArgumentException("unable to remove covered cell at " + firstIndex);
}
 
// ATTN unsafe, must call checkRemove() first
void removeCells(int firstIndex, int lastIndexExcl) {
checkRemove(firstIndex, lastIndexExcl);
 
this.getMutableCellAt(firstIndex).unmerge();
 
// if lastIndex == size, nothing to do
if (lastIndexExcl < this.cells.size()) {
if (lastIndexExcl < getCellCount()) {
if (!this.getCellAt(lastIndexExcl - 1).isValid()) {
int currentCol = lastIndexExcl - 2;
// the covering cell is on this row since last cells of previous rows have been
182,8 → 199,13
for (int i = firstIndex; i < lastIndexExcl; i++) {
// ok to detach multiple times the same element (since repeated cells share the same XML
// element)
this.cells.remove(firstIndex).getElement().detach();
this.cells[firstIndex].getElement().detach();
}
final int movedCount = getCellCount() - lastIndexExcl;
System.arraycopy(this.cells, lastIndexExcl, this.cells, firstIndex, movedCount);
this.cells = Arrays.copyOfRange(this.cells, 0, firstIndex + movedCount);
this.cellCount = this.cells.length;
assert this.getCellCount() == this.getSheet().getColumnCount();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/SpreadSheet.java
13,8 → 13,6
package org.openconcerto.openoffice.spreadsheet;
 
import static org.openconcerto.openoffice.ODPackage.RootElement.CONTENT;
import static org.openconcerto.openoffice.ODPackage.RootElement.STYLES;
import org.openconcerto.openoffice.ContentType;
import org.openconcerto.openoffice.ContentTypeVersioned;
import org.openconcerto.openoffice.ODDocument;
21,13 → 19,11
import org.openconcerto.openoffice.ODPackage;
import org.openconcerto.openoffice.OOUtils;
import org.openconcerto.openoffice.XMLFormatVersion;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.openoffice.spreadsheet.SheetTableModel.MutableTableModel;
import org.openconcerto.utils.Tuple2;
 
import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
39,7 → 35,6
 
import javax.swing.table.TableModel;
 
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
49,14 → 44,20
*
* @author Sylvain
*/
public class SpreadSheet implements ODDocument {
public class SpreadSheet extends ODDocument {
 
public static SpreadSheet createFromFile(File f) throws IOException {
return create(new ODPackage(f));
return new ODPackage(f).getSpreadSheet();
}
 
public static SpreadSheet create(final ODPackage fd) {
return new SpreadSheet(fd.getDocument(CONTENT.getZipEntry()), fd.getDocument(STYLES.getZipEntry()), fd);
/**
* This method should be avoided, use {@link ODPackage#getSpreadSheet()}.
*
* @param fd a package.
* @return the spreadsheet.
*/
public static SpreadSheet get(final ODPackage fd) {
return fd.hasODDocument() ? fd.getSpreadSheet() : new SpreadSheet(fd);
}
 
public static SpreadSheet createEmpty(TableModel t) throws IOException {
65,7 → 66,7
 
public static SpreadSheet createEmpty(TableModel t, XMLFormatVersion ns) throws IOException {
final ContentTypeVersioned ct = ContentType.SPREADSHEET.getVersioned(ns.getXMLVersion());
final SpreadSheet spreadSheet = create(ct.createPackage(ns));
final SpreadSheet spreadSheet = ct.createPackage(ns).getSpreadSheet();
spreadSheet.getBody().addContent(Sheet.createEmpty(ns.getXMLVersion()));
spreadSheet.getSheet(0).merge(t, 0, 0, true);
return spreadSheet;
85,46 → 86,14
return SpreadSheet.createEmpty(t, ns).saveAs(f);
}
 
private final ODPackage originalFile;
private final Map<Element, Sheet> sheets;
 
public SpreadSheet(Document doc, Document styles) {
this(doc, styles, null);
}
 
private SpreadSheet(final Document doc, final Document styles, final ODPackage orig) {
if (orig != null) {
// ATTN OK because this is our private instance (see createFromFile())
this.originalFile = orig;
} else {
this.originalFile = new ODPackage();
}
this.originalFile.putFile("content.xml", doc);
if (styles != null)
this.originalFile.putFile("styles.xml", styles);
 
private SpreadSheet(final ODPackage orig) {
super(orig);
// map Sheet by XML elements so has not to depend on ordering or name
this.sheets = new HashMap<Element, Sheet>();
}
 
final Document getContent() {
return this.getPackage().getContent().getDocument();
}
 
@Override
public final XMLVersion getVersion() {
return this.getPackage().getVersion();
}
 
@Override
public XMLFormatVersion getFormatVersion() {
return this.getPackage().getFormatVersion();
}
 
private Element getBody() {
return ContentType.SPREADSHEET.getVersioned(getVersion()).getBody(getContent());
}
 
// ** from 8.3.1 Referencing Table Cells (just double the backslash for . and escape the $)
private static final String minCell = "\\$?([A-Z]+)\\$?([0-9]+)";
// added parens to capture cell address
334,17 → 303,4
parentElement.addContent(getContentIndex(toIndex), sheet.getElement());
// no need to update this.sheets since it doesn't depend on order
}
 
// *** Files
 
public File saveAs(File file) throws FileNotFoundException, IOException {
this.getPackage().setFile(file);
return this.getPackage().save();
}
 
@Override
public final ODPackage getPackage() {
return this.originalFile;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/ColumnStyle.java
14,7 → 14,6
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.LengthUnit;
import org.openconcerto.openoffice.ODFrame;
import org.openconcerto.openoffice.ODPackage;
import org.openconcerto.openoffice.StyleProperties;
import org.openconcerto.openoffice.StyleStyle;
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/Cell.java
19,6 → 19,7
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.openoffice.ODValueType;
import org.openconcerto.openoffice.OOXML;
import org.openconcerto.openoffice.StyleDesc;
import org.openconcerto.openoffice.XMLFormatVersion;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.utils.CollectionUtils;
80,8 → 81,8
 
private final Row<D> row;
 
Cell(Row<D> parent, Element elem) {
super(parent.getODDocument(), elem, CellStyle.class);
Cell(Row<D> parent, Element elem, StyleDesc<CellStyle> styleDesc) {
super(parent.getODDocument(), elem, styleDesc);
this.row = parent;
}
 
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/TableCalcNode.java
15,6 → 15,7
 
import org.openconcerto.openoffice.ImmutableDocStyledNode;
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.openoffice.StyleDesc;
import org.openconcerto.openoffice.StyleStyle;
 
import org.jdom.Element;
34,7 → 35,12
super(parent, local, styleClass);
}
 
protected TableCalcNode(D parent, Element local, StyleDesc<S> styleDesc) {
super(parent, local, styleDesc);
}
 
protected final Namespace getTABLE() {
return this.getODDocument().getVersion().getTABLE();
// a lot faster than asking to the version of our document
return this.getElement().getNamespace();
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/RepeatedBreaker.java
New file
0,0 → 1,97
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.openoffice.spreadsheet;
 
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.openoffice.ODNode;
 
import java.util.List;
 
import org.jdom.Element;
 
abstract class RepeatedBreaker<P, C extends ODNode> {
 
@SuppressWarnings("rawtypes")
static private final RepeatedBreaker CELL_BREAKER = new RepeatedBreaker<Row<?>, Cell<?>>("number-columns-repeated") {
@Override
Cell<?> create(Element elem, Row<?> parent, int index, boolean single) {
return createD(elem, parent, index, single);
}
 
<D extends ODDocument> Cell<D> createD(Element elem, Row<D> parent, int index, boolean single) {
return single ? new MutableCell<D>(parent, elem, parent.getSheet().getCellStyleDesc()) : new Cell<D>(parent, elem, parent.getSheet().getCellStyleDesc());
}
};
 
@SuppressWarnings("rawtypes")
static private final RepeatedBreaker ROW_BREAKER = new RepeatedBreaker<Table<?>, Row<?>>(Axis.ROW.getRepeatedAttrName()) {
@Override
Row<?> create(Element elem, Table<?> parent, int index, boolean single) {
return createD(elem, parent, index, single);
}
 
<D extends ODDocument> Row<D> createD(Element elem, Table<D> parent, int index, boolean single) {
return new Row<D>(parent, elem, index, parent.getRowStyleDesc(), parent.getCellStyleDesc());
}
};
 
@SuppressWarnings("unchecked")
static final <D extends ODDocument> RepeatedBreaker<Row<D>, Cell<D>> getCellBreaker() {
return (RepeatedBreaker<Row<D>, Cell<D>>) CELL_BREAKER;
}
 
@SuppressWarnings("unchecked")
static final <D extends ODDocument> RepeatedBreaker<Table<D>, Row<D>> getRowBreaker() {
return (RepeatedBreaker<Table<D>, Row<D>>) ROW_BREAKER;
}
 
private final String attrName;
 
public RepeatedBreaker(final String attrName) {
this.attrName = attrName;
}
 
abstract C create(final Element elem, final P parent, final int index, final boolean single);
 
public final void breakRepeated(final P parent, final List<C> children, final int col) {
final C c = children.get(col);
final Element element = c.getElement();
final String repeatedS = element.getAttributeValue(this.attrName, element.getNamespace());
if (repeatedS != null) {
final int repeated = Integer.parseInt(repeatedS);
final int firstIndex = children.indexOf(c);
final int lastIndex = firstIndex + repeated - 1;
 
final int preRepeated = col - firstIndex;
final int postRepeated = lastIndex - col;
 
breakRepeated(parent, children, element, firstIndex, preRepeated, true);
element.removeAttribute(this.attrName, element.getNamespace());
breakRepeated(parent, children, element, col + 1, postRepeated, false);
}
children.set(col, this.create(element, parent, col, true));
}
 
private final void breakRepeated(final P parent, final List<C> children, Element element, int firstIndex, int repeat, boolean before) {
if (repeat > 0) {
final Element newElem = (Element) element.clone();
element.getParentElement().addContent(element.getParent().indexOf(element) + (before ? 0 : 1), newElem);
newElem.setAttribute(this.attrName, repeat + "", element.getNamespace());
final C preCell = this.create(newElem, parent, firstIndex, false);
for (int i = 0; i < repeat; i++) {
children.set(firstIndex + i, preCell);
}
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/Table.java
16,6 → 16,7
import org.openconcerto.openoffice.LengthUnit;
import org.openconcerto.openoffice.ODDocument;
import org.openconcerto.openoffice.Style;
import org.openconcerto.openoffice.StyleDesc;
import org.openconcerto.openoffice.StyleStyleDesc;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.openoffice.spreadsheet.SheetTableModel.MutableTableModel;
30,7 → 31,6
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
60,92 → 60,105
}
 
// ATTN Row have their index as attribute
private final List<Row<D>> rows;
private int headerRowCount;
private final List<Column<D>> cols;
private int headerColumnCount;
private final ArrayList<Row<D>> rows;
private TableGroup rowGroup;
private final ArrayList<Column<D>> cols;
private TableGroup columnGroup;
 
public Table(D parent, Element local) {
super(parent, local, TableStyle.class);
 
this.rows = new ArrayList<Row<D>>();
this.cols = new ArrayList<Column<D>>();
this.rows = new ArrayList<Row<D>>(64);
this.cols = new ArrayList<Column<D>>(32);
 
// read columns first since Row constructor needs it
this.readColumns();
this.readRows();
}
 
private void readColumns() {
this.read(true);
this.read(Axis.COLUMN);
}
 
private final void readRows() {
this.read(false);
this.read(Axis.ROW);
}
 
private final void read(final boolean col) {
final Tuple2<List<Element>, Integer> r = flatten(col);
(col ? this.cols : this.rows).clear();
for (final Element clone : r.get0()) {
if (col)
this.addCol(clone);
else
this.addRow(clone);
private final void read(final Axis axis) {
final boolean col = axis == Axis.COLUMN;
final Tuple2<TableGroup, List<Element>> r = TableGroup.createRoot(this, axis);
final ArrayList<?> l = col ? this.cols : this.rows;
final int oldSize = l.size();
l.clear();
final int newSize = r.get0().getSize();
l.ensureCapacity(newSize);
if (col) {
final StyleStyleDesc<ColumnStyle> colStyleDesc = getColumnStyleDesc();
for (final Element clone : r.get1())
this.addCol(clone, colStyleDesc);
this.columnGroup = r.get0();
} else {
final StyleStyleDesc<RowStyle> rowStyleDesc = getRowStyleDesc();
final StyleStyleDesc<CellStyle> cellStyleDesc = getCellStyleDesc();
for (final Element clone : r.get1())
this.addRow(clone, rowStyleDesc, cellStyleDesc);
this.rowGroup = r.get0();
}
if (col)
this.headerColumnCount = r.get1();
else
this.headerRowCount = r.get1();
// this always copy the array, so make sure we reclaim enough memory (~ 64k)
if (oldSize - newSize > 8192) {
l.trimToSize();
}
assert newSize == (col ? this.getColumnCount() : this.getRowCount());
}
 
private final void addCol(Element clone) {
this.cols.add(new Column<D>(this, clone));
private final void addCol(Element clone, StyleStyleDesc<ColumnStyle> colStyleDesc) {
this.cols.add(new Column<D>(this, clone, colStyleDesc));
}
 
private Tuple2<List<Element>, Integer> flatten(boolean col) {
final List<Element> res = new ArrayList<Element>();
final Element header = this.getElement().getChild("table-header-" + getName(col) + "s", getTABLE());
if (header != null)
res.addAll(flatten(header, col));
final int headerCount = res.size();
static final int flattenChildren(final List<Element> res, final Element elem, final Axis axis) {
int count = 0;
// array so that flatten1() can modify an int
int[] index = new int[] { 0 };
// copy since we will change our children (don't use List.listIterator(int) since it
// re-filters all content)
@SuppressWarnings("unchecked")
final List<Element> children = new ArrayList<Element>(elem.getChildren(axis.getElemName(), elem.getNamespace()));
final int stop = children.size();
for (int i = 0; i < stop; i++) {
final Element row = children.get(i);
count += flatten1(res, row, axis, index);
}
return count;
}
 
res.addAll(flatten(getElement(), col));
 
return Tuple2.create(res, headerCount);
static int flatten1(final List<Element> res, final Element row, final Axis axis) {
return flatten1(res, row, axis, null);
}
 
@SuppressWarnings("unchecked")
private List<Element> flatten(final Element elem, boolean col) {
final String childName = getName(col);
final List<Element> children = elem.getChildren("table-" + childName, getTABLE());
// not final, since iter.add() does not work consistently, and
// thus we must recreate an iterator each time
ListIterator<Element> iter = children.listIterator();
while (iter.hasNext()) {
final Element row = iter.next();
final Attribute repeatedAttr = row.getAttribute("number-" + childName + "s-repeated", getTABLE());
if (repeatedAttr != null) {
// add XML elements to res and return the logical count
private static int flatten1(final List<Element> res, final Element row, final Axis axis, final int[] parentIndex) {
final int resSize = res.size();
final Attribute repeatedAttr = axis.getRepeatedAttr(row);
final int repeated = repeatedAttr == null ? 1 : Integer.parseInt(repeatedAttr.getValue());
if (axis == Axis.COLUMN && repeated > 1) {
row.removeAttribute(repeatedAttr);
final int index = iter.previousIndex();
int repeated = Integer.parseInt(repeatedAttr.getValue());
if (repeated > 60000) {
repeated = 10;
}
final Element parent = row.getParentElement();
final int index = (parentIndex == null ? parent.indexOf(row) : parentIndex[0]) + 1;
res.add(row);
// -1 : we keep the original row
for (int i = 0; i < repeated - 1; i++) {
final Element clone = (Element) row.clone();
// cannot use iter.add() since on JDOM 1.1 if row is the last table-column
// before table-row the clone is added at the very end
children.add(index, clone);
res.add(clone);
parent.addContent(index + i, clone);
}
// restart after the added rows
iter = children.listIterator(index + repeated);
} else {
res.add(row);
}
if (parentIndex != null)
parentIndex[0] += res.size() - resSize;
return repeated;
}
 
return children;
}
 
public final String getName() {
return getName(this.getElement());
}
158,10 → 171,6
this.getElement().detach();
}
 
private final String getName(boolean col) {
return col ? "column" : "row";
}
 
public final Object getPrintRanges() {
return this.getElement().getAttributeValue("print-ranges", this.getTABLE());
}
235,14 → 244,38
 
// clone xml elements and add them to our tree
final List<Element> clones = new ArrayList<Element>(count * copies);
for (int i = 0; i < copies; i++) {
for (int l = start; l < stop; l++) {
final Element r = this.rows.get(l).getElement();
clones.add((Element) r.clone());
for (int l = start; l < stop;) {
final Row<D> immutableRow = this.getRow(l);
final Row<D> toClone;
// MAYBE use something else than getMutableRow() since we don't need a single row.
// the repeated row starts before the copied range, split it at the beginning
if (immutableRow.getY() < l) {
toClone = this.getMutableRow(l);
} else {
assert immutableRow.getY() == l;
if (immutableRow.getLastY() >= stop) {
// the repeated row goes beyond the copied range, split it at the end
assert this.getRow(stop) == immutableRow;
this.getMutableRow(stop);
toClone = this.getRow(l);
} else {
toClone = immutableRow;
}
}
assert toClone.getY() == l;
assert toClone.getLastY() < stop : "Row goes to far";
l += toClone.getRepeated();
clones.add((Element) toClone.getElement().clone());
}
final int clonesSize = clones.size();
for (int i = 1; i < copies; i++) {
for (int j = 0; j < clonesSize; j++) {
clones.add((Element) clones.get(j).clone());
}
}
// works anywhere its XML element is
JDOMUtils.insertAfter(this.rows.get(stop - 1).getElement(), clones);
assert this.getRow(stop - 1).getLastY() == stop - 1 : "Adding XML element too far";
JDOMUtils.insertAfter(this.getRow(stop - 1).getElement(), clones);
 
for (final Point coverOrigin : coverOriginsToUpdate) {
final MutableCell<D> coveringCell = getCellAt(coverOrigin);
249,7 → 282,7
coveringCell.setRowsSpanned(coveringCell.getRowsSpanned() + count * copies);
}
 
// synchronize our rows with our new tree
// synchronize our rows with our new tree (rows' index have changed)
this.readRows();
 
// 19.627 in OpenDocument-v1.2-cs01-part1 : The table:end-cell-address attribute specifies
323,9 → 356,13
}
}
 
private synchronized void addRow(Element child) {
this.rows.add(new Row<D>(this, child, this.rows.size()));
private synchronized void addRow(Element child, StyleDesc<RowStyle> styleDesc, StyleDesc<CellStyle> cellStyleDesc) {
final Row<D> row = new Row<D>(this, child, this.rows.size(), styleDesc, cellStyleDesc);
final int toRepeat = row.getRepeated();
for (int i = 0; i < toRepeat; i++) {
this.rows.add(row);
}
}
 
public final Point resolveHint(String ref) {
final Point res = resolve(ref);
346,8 → 383,18
return this.getImmutableCellAt(x, y).isValid();
}
 
/**
* Return a modifiable cell at the passed coordinates. This is slower than
* {@link #getImmutableCellAt(int, int)} since this method may modify the underlying XML (e.g.
* break up repeated cells to allow for modification of only the returned cell).
*
* @param x the column.
* @param y the row.
* @return the cell.
* @see #getImmutableCellAt(int, int)
*/
public final MutableCell<D> getCellAt(int x, int y) {
return this.getRow(y).getMutableCellAt(x);
return this.getMutableRow(y).getMutableCellAt(x);
}
 
public final MutableCell<D> getCellAt(String ref) {
375,11 → 422,20
 
// *** get cell
 
protected final Cell<D> getImmutableCellAt(int x, int y) {
/**
* Return a non modifiable cell at the passed coordinates. This is faster than
* {@link #getCellAt(int, int)} since this method never modifies the underlying XML.
*
* @param x the column.
* @param y the row.
* @return the cell.
* @see #getCellAt(int, int)
*/
public final Cell<D> getImmutableCellAt(int x, int y) {
return this.getRow(y).getCellAt(x);
}
 
protected final Cell<D> getImmutableCellAt(String ref) {
public final Cell<D> getImmutableCellAt(String ref) {
final Point p = resolveHint(ref);
return this.getImmutableCellAt(p.x, p.y);
}
457,7 → 513,7
}
 
public final CellStyle getStyleAt(int column, int row) {
return getCellStyleDesc().findStyle(this.getODDocument().getPackage(), this.getElement().getDocument(), this.getStyleNameAt(column, row));
return getCellStyleDesc().findStyleForNode(this.getImmutableCellAt(column, row), this.getStyleNameAt(column, row));
}
 
protected StyleStyleDesc<CellStyle> getCellStyleDesc() {
506,6 → 562,14
return res;
}
 
protected final StyleStyleDesc<ColumnStyle> getColumnStyleDesc() {
return Style.getStyleStyleDesc(ColumnStyle.class, XMLVersion.getVersion(getElement()));
}
 
protected final StyleStyleDesc<RowStyle> getRowStyleDesc() {
return Style.getStyleStyleDesc(RowStyle.class, XMLVersion.getVersion(getElement()));
}
 
/**
* Retourne la valeur de la cellule spécifiée.
*
518,10 → 582,20
 
// *** get count
 
private Row<D> getRow(int index) {
final Row<D> getRow(int index) {
return this.rows.get(index);
}
 
final Row<D> getMutableRow(int y) {
final Row<D> c = this.getRow(y);
if (c.getRepeated() > 1) {
RepeatedBreaker.<D> getRowBreaker().breakRepeated(this, this.rows, y);
return this.getRow(y);
} else {
return c;
}
}
 
public final Column<D> getColumn(int i) {
return this.cols.get(i);
}
530,8 → 604,22
return this.rows.size();
}
 
public final TableGroup getRowGroup() {
return this.rowGroup;
}
 
/**
* Return the deepest group at the passed row.
*
* @param y a row index.
* @return the group at the index, never <code>null</code>.
*/
public final TableGroup getRowGroupAt(final int y) {
return this.getRowGroup().getDescendentOrSelfContaining(y);
}
 
public final int getHeaderRowCount() {
return this.headerRowCount;
return this.getRowGroup().getFollowingHeaderCount();
}
 
public final int getColumnCount() {
538,8 → 626,22
return this.cols.size();
}
 
public final TableGroup getColumnGroup() {
return this.columnGroup;
}
 
/**
* Return the deepest group at the passed column.
*
* @param x a column index.
* @return the group at the index, never <code>null</code>.
*/
public final TableGroup getColumnGroupAt(final int x) {
return this.getColumnGroup().getDescendentOrSelfContaining(x);
}
 
public final int getHeaderColumnCount() {
return this.headerColumnCount;
return this.getColumnGroup().getFollowingHeaderCount();
}
 
// *** set count
595,17 → 697,22
} else {
elemToClone = getColumn(colIndex).getElement();
}
final StyleStyleDesc<ColumnStyle> columnStyleDesc = getColumnStyleDesc();
for (int i = 0; i < toGrow; i++) {
final Element newElem = (Element) elemToClone.clone();
this.getElement().addContent(indexOfLastCol + 1 + i, newElem);
this.cols.add(new Column<D>(this, newElem));
this.cols.add(new Column<D>(this, newElem, columnStyleDesc));
}
// now update widths
updateWidth(keepTableWidth);
 
// add needed cells
for (final Row r : this.rows) {
r.columnCountChanged();
final StyleStyleDesc<CellStyle> cellStyleDesc = this.getCellStyleDesc();
final int rowCount = this.getRowCount();
for (int i = 0; i < rowCount;) {
final Row<D> r = this.getRow(i);
r.columnCountChanged(cellStyleDesc);
i += r.getRepeated();
}
}
}
629,16 → 736,21
*/
public final void removeColumn(int firstIndex, int lastIndex, final boolean keepTableWidth) {
// first check that removeCells() will succeed, so that we avoid an incoherent XML state
for (final Row r : this.rows) {
final int rowCount = this.getRowCount();
for (int i = 0; i < rowCount;) {
final Row<D> r = this.getRow(i);
r.checkRemove(firstIndex, lastIndex);
i += r.getRepeated();
}
// rm column element
remove(true, firstIndex, lastIndex - 1);
remove(Axis.COLUMN, firstIndex, lastIndex - 1);
// update widths
updateWidth(keepTableWidth);
// rm cells
for (final Row r : this.rows) {
for (int i = 0; i < rowCount;) {
final Row<D> r = this.getRow(i);
r.removeCells(firstIndex, lastIndex);
i += r.getRepeated();
}
}
 
709,20 → 821,41
return colStyle;
}
 
private final void setCount(final boolean col, final int newSize) {
private final void setCount(final Axis col, final int newSize) {
this.remove(col, newSize, -1);
}
 
// both inclusive
private final void remove(final boolean col, final int fromIndex, final int toIndexIncl) {
// ok since rows and cols are flattened in ctor
final List<? extends TableCalcNode> l = col ? this.cols : this.rows;
private final void remove(final Axis col, final int fromIndex, final int toIndexIncl) {
assert col == Axis.COLUMN || toIndexIncl < 0 : "Row index will be wrong";
final List<? extends TableCalcNode<?, ?>> l = col == Axis.COLUMN ? this.cols : this.rows;
final int toIndexValid = CollectionUtils.getValidIndex(l, toIndexIncl);
for (int i = toIndexValid; i >= fromIndex; i--) {
// works anywhere its XML element is
l.remove(i).getElement().detach();
final int toRemoveCount = toIndexValid - fromIndex + 1;
int removedCount = 0;
while (removedCount < toRemoveCount) {
// works backwards to keep y OK
final int i = toIndexValid - removedCount;
final TableCalcNode<?, ?> removed = l.get(i);
if (removed instanceof Row) {
final Row<?> r = (Row<?>) removed;
final int removeFromRepeated = i - Math.max(fromIndex, r.getY()) + 1;
// removedCount grows each iteration
assert removeFromRepeated > 0;
final int newRepeated = r.getRepeated() - removeFromRepeated;
if (newRepeated == 0)
removed.getElement().detach();
else
r.setRepeated(newRepeated);
removedCount += removeFromRepeated;
} else {
// Columns are always flattened
removed.getElement().detach();
removedCount++;
}
}
// one remove to be efficient
l.subList(fromIndex, toIndexValid + 1).clear();
}
 
public final void ensureRowCount(int newSize) {
if (newSize > this.getRowCount())
741,25 → 874,24
* @param rowIndex the index of the row to be copied, -1 for empty row (i.e. default style).
*/
public final void setRowCount(int newSize, int rowIndex) {
final int toGrow = newSize - this.getRowCount();
if (toGrow < 0) {
setCount(Axis.ROW, newSize);
} else if (toGrow > 0) {
final Element elemToClone;
if (rowIndex < 0) {
elemToClone = Row.createEmpty(this.getODDocument().getVersion());
// each row MUST have the same number of columns
elemToClone.addContent(Cell.createEmpty(this.getODDocument().getVersion(), this.getColumnCount()));
} else
elemToClone = getRow(rowIndex).getElement();
final int toGrow = newSize - this.getRowCount();
if (toGrow < 0) {
setCount(false, newSize);
} else {
for (int i = 0; i < toGrow; i++) {
final Element newElem = (Element) elemToClone.clone();
elemToClone = (Element) getRow(rowIndex).getElement().clone();
}
Axis.ROW.setRepeated(elemToClone, toGrow);
// as per section 8.1.1 rows are the last elements inside a table
this.getElement().addContent(newElem);
addRow(newElem);
this.getElement().addContent(elemToClone);
addRow(elemToClone, getRowStyleDesc(), getCellStyleDesc());
}
}
}
 
// *** table models
 
948,7 → 1080,7
public final Range getCurrentRegion() {
while (this.checkFrame())
;// bounded by table size
return new Range(getName(), new Point(minX, minY), new Point(maxX, maxY));
return new Range(getName(), new Point(this.minX, this.minY), new Point(this.maxX, this.maxY));
}
}
 
968,7 → 1100,8
* @param startX x coordinate.
* @param startY y coordinate.
* @return the smallest range containing the passed cell.
* @see http://msdn.microsoft.com/library/aa214248(v=office.11).aspx
* @see <a href="http://msdn.microsoft.com/library/aa214248(v=office.11).aspx">CurrentRegion
* Property</a>
*/
public final Range getCurrentRegion(final int startX, final int startY) {
return this.getCurrentRegion(startX, startY, false);
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/MutableCell.java
18,11 → 18,13
import org.openconcerto.openoffice.ODFrame;
import org.openconcerto.openoffice.ODValueType;
import org.openconcerto.openoffice.OOXML;
import org.openconcerto.openoffice.StyleDesc;
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ByteArrayProducer;
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ImageProducer;
import org.openconcerto.openoffice.style.data.DataStyle;
import org.openconcerto.utils.ExceptionUtils;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.Tuple3;
 
import java.awt.Color;
import java.awt.Image;
36,6 → 38,9
import java.util.Date;
import java.util.List;
 
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
 
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.Namespace;
51,6 → 56,7
 
static private final DateFormat TextPDateFormat = DateFormat.getDateInstance();
static private final DateFormat TextPTimeFormat = DateFormat.getTimeInstance();
static private final NumberFormat TextPMinuteSecondFormat = new DecimalFormat("00.###");
static private final NumberFormat TextPFloatFormat = DecimalFormat.getNumberInstance();
static private final NumberFormat TextPPercentFormat = DecimalFormat.getPercentInstance();
static private final NumberFormat TextPCurrencyFormat = DecimalFormat.getCurrencyInstance();
76,8 → 82,8
}
}
 
MutableCell(Row<D> parent, Element elem) {
super(parent, elem);
MutableCell(Row<D> parent, Element elem, StyleDesc<CellStyle> styleDesc) {
super(parent, elem, styleDesc);
}
 
// ask our column to our row so we don't have to update anything when columns are removed/added
142,6 → 148,10
}
 
public void setValue(Object obj) {
this.setValue(obj, true);
}
 
public void setValue(Object obj, final boolean allowTypeChange) throws UnsupportedOperationException {
final ODValueType type;
final ODValueType currentType = getValueType();
// try to keep current type, since for example a Number can work with FLOAT, PERCENTAGE
148,18 → 158,13
// and CURRENCY
if (currentType != null && currentType.canFormat(obj.getClass())) {
type = currentType;
} else if (obj instanceof Number) {
type = ODValueType.FLOAT;
} else if (obj instanceof Date || obj instanceof Calendar) {
type = ODValueType.DATE;
} else if (obj instanceof Boolean) {
type = ODValueType.BOOLEAN;
} else if (obj instanceof String) {
type = ODValueType.STRING;
} else {
type = ODValueType.forObject(obj);
}
if (type == null) {
throw new IllegalArgumentException("Couldn't infer type of " + obj);
}
this.setValue(obj, type, true);
this.setValue(obj, type, allowTypeChange, true);
}
 
/**
167,16 → 172,20
*
* @param obj the new cell value.
* @param vt the value type.
* @param allowTypeChange if <code>true</code> <code>obj</code> and <code>vt</code> might be
* changed to allow the data style to format, e.g. from Boolean.FALSE to 0.
* @param lenient <code>false</code> to throw an exception if we can't format according to the
* ODF, <code>true</code> to try best-effort.
* @throws UnsupportedOperationException if <code>obj</code> couldn't be formatted.
*/
public void setValue(final Object obj, final ODValueType vt, final boolean lenient) throws UnsupportedOperationException {
public void setValue(Object obj, ODValueType vt, final boolean allowTypeChange, final boolean lenient) throws UnsupportedOperationException {
final String text;
final String formatted = format(obj, lenient);
final Tuple3<String, ODValueType, Object> formatted = format(obj, vt, !allowTypeChange, lenient);
vt = formatted.get1();
obj = formatted.get2();
 
if (formatted != null) {
text = formatted;
if (formatted.get0() != null) {
text = formatted.get0();
} else {
// either there were no format or formatting failed
if (vt == ODValueType.FLOAT) {
186,9 → 195,21
} else if (vt == ODValueType.CURRENCY) {
text = formatCurrency((Number) obj, getDefaultStyle());
} else if (vt == ODValueType.DATE) {
text = TextPDateFormat.format(obj);
final Date d;
if (obj instanceof Calendar) {
d = ((Calendar) obj).getTime();
} else {
d = (Date) obj;
}
text = TextPDateFormat.format(d);
} else if (vt == ODValueType.TIME) {
text = TextPTimeFormat.format(obj);
if (obj instanceof Duration) {
final Duration normalized = getODDocument().getEpoch().normalizeToHours((Duration) obj);
text = "" + normalized.getHours() + ':' + TextPMinuteSecondFormat.format(normalized.getMinutes()) + ':'
+ TextPMinuteSecondFormat.format(normalized.getField(DatatypeConstants.SECONDS));
} else {
text = TextPTimeFormat.format(((Calendar) obj).getTime());
}
} else if (vt == ODValueType.BOOLEAN) {
if (lenient)
text = obj.toString();
203,14 → 224,19
this.setValue(vt, obj, text);
}
 
// return null if no data style exists, or if one exists but we couldn't use it
private String format(Object obj, boolean lenient) {
// return null String if no data style exists, or if one exists but we couldn't use it
private Tuple3<String, ODValueType, Object> format(Object obj, ODValueType valueType, boolean onlyCast, boolean lenient) {
String res = null;
try {
final DataStyle ds = getDataStyle();
final Tuple3<DataStyle, ODValueType, Object> ds = getDataStyleAndValue(obj, valueType, onlyCast);
if (ds != null) {
obj = ds.get2();
valueType = ds.get1();
// act like OO, that is if we set a String to a Date cell, change the value and
// value-type but leave the data-style untouched
if (ds != null && ds.canFormat(obj.getClass()))
return ds.format(obj, getDefaultStyle(), lenient);
if (ds.get0().canFormat(obj.getClass()))
res = ds.get0().format(obj, getDefaultStyle(), lenient);
}
} catch (UnsupportedOperationException e) {
if (lenient)
Log.get().warning(ExceptionUtils.getStackTrace(e));
217,12 → 243,17
else
throw e;
}
return null;
return Tuple3.create(res, valueType, obj);
}
 
public final DataStyle getDataStyle() {
final Tuple3<DataStyle, ODValueType, Object> s = this.getDataStyleAndValue(this.getValue(), this.getValueType(), true);
return s != null ? s.get0() : null;
}
 
private final Tuple3<DataStyle, ODValueType, Object> getDataStyleAndValue(Object obj, ODValueType valueType, boolean onlyCast) {