OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 60 → Rev 61

/trunk/OpenConcerto/src/koala/dynamicjava/interpreter/NameVisitor.java
687,7 → 687,8
 
while (l.size() > 0) {
final String s = TreeUtilities.listToName(l);
if (b = this.context.classExists(s)) {
boolean check = b = this.context.classExists(s);
if (check) {
break;
}
l.remove(l.size() - 1);
/trunk/OpenConcerto/src/org/jopendocument/link/OOInstallation.java
14,13 → 14,12
package org.jopendocument.link;
 
import org.openconcerto.utils.DesktopEnvironment;
import org.openconcerto.utils.DesktopEnvironment.Mac;
 
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
98,11 → 97,11
return null;
}
 
private static String findBundleURL() throws IOException {
private static File findBundleDir() throws IOException {
final Mac de = (Mac) DesktopEnvironment.getDE();
for (final String bundleID : new String[] { LOBundleID, OOBundleID }) {
// if not found prints nothing to out and a cryptic error to the standard error stream
final String url = cmdSubstitution("osascript", "-e", "tell application id \"com.apple.Finder\" to URL of application file id \"" + bundleID + "\"").trim();
if (url.length() > 0)
final File url = de.getAppDir(bundleID);
if (url != null)
return url;
}
return null;
140,13 → 139,16
 
private static final void addUnixPaths(final List<File> cp, final File progDir) throws IOException {
final File baseDir = progDir.getParentFile();
final String basisDir = baseDir.getPath() + File.separator + "basis-link";
final String ureDir = basisDir + File.separator + "ure-link";
addPaths(cp, progDir, basisDir, ureDir);
final File basisDir = new File(baseDir, "basis-link");
// basis-link was dropped from LO 3.5
final String basisPath = (basisDir.exists() ? basisDir : baseDir).getPath();
final String ureDir = basisPath + File.separator + "ure-link";
addPaths(cp, progDir, basisPath, ureDir);
}
 
private static void add(final List<File> res, final File f) {
if (f != null && f.isDirectory()) {
// e.g. on LO 3.5 BASIS is no longer 'Basis/' but './'
if (f != null && f.isDirectory() && !res.contains(f)) {
res.add(f);
}
}
178,21 → 180,28
throw new IOException(unoPath + " is not a directory");
exe = new File(unoPath, "soffice.exe");
 
// Perhaps check out parallel install but in Windows it's really cumbersome :
// http://wiki.documentfoundation.org/Installing_in_parallel
 
final String layerPath;
if (!libreOffice) {
layerPath = "\\Layers\\OpenOffice.org";
} else if (DesktopEnvironment.test("reg", "query", rootPath + "\\Layers")) {
layerPath = "\\Layers\\LibreOffice";
} else {
// LO 3.4
layerPath = "\\Layers_\\LibreOffice";
}
// '/s' since variables are one level (the version) deeper
final Map<String, String> layersValues = getStringValues(rootPath + (libreOffice ? "\\Layers_\\LibreOffice" : "\\Layers\\OpenOffice.org"), "/s");
final Map<String, String> layersValues = getStringValues(rootPath + layerPath, "/s");
addPaths(cp, unoPath, layersValues.get("BASISINSTALLLOCATION"), layersValues.get("UREINSTALLLOCATION"));
} else if (os.startsWith("Mac OS")) {
final String url = findBundleURL();
if (url == null)
final File appPkg = findBundleDir();
if (appPkg == null)
return null;
try {
final File appPkg = new File(new URI(url).getPath());
// need to call soffice from the MacOS directory otherwise it fails
exe = new File(appPkg, "Contents/MacOS/soffice");
addUnixPaths(cp, new File(appPkg, "Contents/program"));
} catch (URISyntaxException e) {
throw new IOException(e);
}
} else if (os.startsWith("Linux")) {
// soffice is usually a symlink in /usr/bin
// if not found prints nothing at all
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
17,6 → 17,7
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.storage.CloudStorageEngine;
import org.openconcerto.erp.storage.StorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
import org.openconcerto.openoffice.OOUtils;
111,10 → 112,14
 
}
 
public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF) {
showPrintAndExport(showDocument, printDocument, exportToPDF, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"));
}
 
/**
* Show, print and export the document to PDF. This method is synchronous
* */
public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF) {
public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF, boolean useODSViewer) {
 
final File generatedFile = getGeneratedFile();
final File pdfFile = getGeneratedPDFFile();
124,7 → 129,7
}
 
try {
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
if (!useODSViewer) {
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(generatedFile, !showDocument);
 
if (printDocument) {
147,6 → 152,10
DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
printer.print(doc);
}
 
// FIXME Profiler pour utiliser moins de ram --> ex : demande trop de mémoire pour
// faire
// un grand livre KD
if (exportToPDF) {
 
try {
153,7 → 162,7
SheetUtils.convert2PDF(doc, pdfFile);
 
} catch (Throwable e) {
ExceptionHandler.handle("Impossible de créer le PDF");
ExceptionHandler.handle("Impossible de créer le PDF.", e);
}
 
Thread t = new Thread(new Runnable() {
173,8 → 182,20
} catch (IOException e) {
ExceptionHandler.handle("Impossible de sauvegarder le PDF");
}
if (storageEngine instanceof CloudStorageEngine) {
try {
storageEngine.connect();
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(generatedFile));
final String path = getStoragePath();
storageEngine.store(inStream, path, generatedFile.getName(), true);
inStream.close();
storageEngine.disconnect();
} catch (IOException e) {
ExceptionHandler.handle("Impossible de sauvegarder le fichier généré");
}
}
}
}
 
}
});
300,15 → 321,19
*
* */
public File getOrCreatePDFDocumentFile(boolean createRecent) throws Exception {
return getOrCreatePDFDocumentFile(createRecent, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"));
}
 
public File getOrCreatePDFDocumentFile(boolean createRecent, boolean useODSViewer) throws Exception {
File f = getGeneratedPDFFile();
if (!f.exists()) {
getOrCreateDocumentFile();
showPrintAndExport(false, false, true);
showPrintAndExport(false, false, true, useODSViewer);
return f;
} else {
File fODS = getOrCreateDocumentFile();
if (fODS.lastModified() > f.lastModified()) {
showPrintAndExport(false, false, true);
showPrintAndExport(false, false, true, useODSViewer);
}
return f;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLField.java
345,7 → 345,7
// Retourne la date d'échéance
int idModeReglement = this.row.getInt("ID_MODE_REGLEMENT");
Date d = (Date) this.row.getObject("DATE");
return getDateEcheance(idModeReglement, d);
return getDateEcheance(idModeReglement, d, this.elt.getAttributeValue("DatePattern"));
} else if (typeComp.equalsIgnoreCase("Jour")) {
int day = this.row.getInt(field);
stringValue = "le " + String.valueOf(day);
413,6 → 413,20
 
long cumul = 0;
 
SQLRowAccessor rowAff = rowFact.getForeign("ID_AFFAIRE");
Calendar date = rowFact.getDate("DATE");
if (rowAff != null && !rowAff.isUndefined()) {
if (rowAff.getBoolean("CCI")) {
 
List<SQLRow> rows = rowAff.asRow().getReferentRows(rowFact.getTable());
for (SQLRow sqlRow : rows) {
if (sqlRow.getID() != rowFact.getID() && sqlRow.getDate("DATE").before(date)) {
cumul += sqlRow.getLong("T_HT");
}
}
}
} else {
 
// On recupere les missions associées
SQLTable tableElt = Configuration.getInstance().getRoot().findTable("SAISIE_VENTE_FACTURE_ELEMENT");
Collection<? extends SQLRowAccessor> factElts = rowFact.getReferentRows(tableElt);
424,12 → 438,13
Collection<? extends SQLRowAccessor> rowsElt = foreign.getReferentRows(tableElt);
for (SQLRowAccessor row2 : rowsElt) {
SQLRowAccessor rowFacture = row2.getForeign("ID_SAISIE_VENTE_FACTURE");
if (rowFacture.getDate("DATE").before(rowFact.getDate("DATE"))) {
if (rowFacture.getDate("DATE").before(date)) {
cumul += row2.getLong("T_PV_HT");
}
}
}
}
}
 
return cumul;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLTableField.java
67,7 → 67,7
} else if (this.type.equalsIgnoreCase("DescriptifArticle")) {
value = getDescriptifArticle(this.row);
} else if (this.type.equalsIgnoreCase("DateEcheance")) {
value = getDateEcheance(this.row.getInt("ID_MODE_REGLEMENT"), (Date) this.row.getObject("DATE"));
value = getDateEcheance(this.row.getInt("ID_MODE_REGLEMENT"), (Date) this.row.getObject("DATE"), this.elt.getAttributeValue("DatePattern"));
} else if (this.type.equalsIgnoreCase("MontantRevise")) {
value = getMontantRevise(this.row);
} else if (this.type.equalsIgnoreCase("Localisation")) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractSheetXml.java
13,10 → 13,15
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.sync.SyncClient;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
81,8 → 86,43
 
@Override
public File getGeneratedFile() {
ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
 
final File outputDirectory = getDocumentOutputDirectory();
try {
FileUtils.mkdir_p(outputDirectory);
} catch (IOException e1) {
ExceptionHandler.handle("Impossible de créer le dossier " + outputDirectory.getAbsolutePath(), e1);
}
 
if (this.generatedOpenDocumentFile == null)
this.generatedOpenDocumentFile = new File(getDocumentOutputDirectory(), getValidFileName(getName()) + ".ods");
this.generatedOpenDocumentFile = new File(outputDirectory, getValidFileName(getName()) + ".ods");
if (config.isOnCloud()) {
if (generatedOpenDocumentFile.exists()) {
long t = generatedOpenDocumentFile.lastModified();
if (System.currentTimeMillis() - t < 1000 * 10) {
return generatedOpenDocumentFile;
}
 
}
 
String remotePath = config.getSocieteID() + "/" + getStoragePath();
remotePath = remotePath.replace('\\', '/');
final SyncClient client = new SyncClient("https://" + config.getStorageServer());
 
client.setVerifyHost(false);
 
try {
 
System.out.println("AbstractSheet: getFromCloud: " + remotePath + " " + generatedOpenDocumentFile.getName() + " to " + outputDirectory.getAbsolutePath());
client.retrieveFile(outputDirectory, remotePath, generatedOpenDocumentFile.getName(), config.getToken());
generatedOpenDocumentFile.setLastModified(System.currentTimeMillis());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
return generatedOpenDocumentFile;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DefaultCloudTemplateProvider.java
New file
0,0 → 1,200
/*
* 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.erp.config.ComptaPropsConfiguration;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.sync.FileProperty;
import org.openconcerto.utils.sync.SyncClient;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
 
public class DefaultCloudTemplateProvider extends AbstractLocalTemplateProvider {
private int idSociete;
private static final String[] EXTS = new String[] { ".ods", ".odsp", ".xml" };
 
// Documents/OpenConcerto/OnCloud/Template/idSosiete/fr/templateIdType.(ods|odsp|xml)
public DefaultCloudTemplateProvider(int idSociete) {
ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
this.idSociete = idSociete;
if (!getCloudDir().exists()) {
getCloudDir().mkdirs();
}
if (!getLocalDir().exists()) {
getLocalDir().mkdirs();
}
final SyncClient client = createSyncClient(config);
final String remotePath = "Template/" + idSociete;
boolean remoteTemplateDirExists = false;
try {
System.out.println("DefaultCloudTemplateProvider: update template:" + getCloudDir().getCanonicalPath() + " from " + remotePath);
ArrayList<FileProperty> list = client.getList(remotePath, config.getToken());
System.out.println("DefaultCloudTemplateProvider: " + list.size() + " remote templates found in path: " + remotePath);
remoteTemplateDirExists = true;
} catch (Exception e) {
// Ok
}
if (!remoteTemplateDirExists) {
System.err.println("DefaultCloudTemplateProvider: No remote templates in path: " + remotePath);
File defaultTemplateDir = new File("Configuration/Template/Default");
try {
if (getCloudDir().list().length <= 0) {
FileUtils.copyDirectory(defaultTemplateDir, getCloudDir());
FileUtils.copyDirectory(defaultTemplateDir, getLocalDir());
}
} catch (IOException e) {
ExceptionHandler.handle("Impossible d'initialiser les modèles", e);
}
} else {
try {
client.retrieveDirectory(getCloudDir(), remotePath, config.getToken());
} catch (Exception e) {
// Set unsync'ed local templates
ExceptionHandler.handle("Impossible de synchroniser les modèles", e);
}
}
}
 
private SyncClient createSyncClient(ComptaPropsConfiguration config) {
final SyncClient client = new SyncClient("https://" + config.getStorageServer());
client.setVerifyHost(false);
return client;
}
 
@Override
public boolean isSynced(String templateId, String language, String type) {
return !getLocalFile(templateId + ".ods", language, type).exists();
}
 
@Override
public File getTemplateFromLocalFile(String templateIdWithExtension, String language, String type) {
File f = getLocalFile(templateIdWithExtension, language, type);
if (!f.exists()) {
f = getCloudFile(templateIdWithExtension, language, type);
}
return f;
}
 
private File getLocalFile(String templateIdWithExtension, String language, String type) {
String path = templateIdWithExtension;
 
if (type != null) {
path = insertBeforeExtenstion(path, type);
}
if (language != null && language.trim().length() > 0) {
path = language + "/" + path;
}
 
File dir = getLocalDir();
File out = new File(dir, path);
 
return out;
}
 
private File getCloudFile(String templateIdWithExtension, String language, String type) {
String path = templateIdWithExtension;
 
if (type != null) {
path = insertBeforeExtenstion(path, type);
}
if (language != null && language.trim().length() > 0) {
path = language + "/" + path;
}
 
File dir = getCloudDir();
File out = new File(dir, path);
 
return out;
}
 
private File getCloudDir() {
return new File(ComptaPropsConfiguration.getInstance().getWD(), "OnCloud/Template/" + idSociete);
}
 
private File getLocalDir() {
return new File(ComptaPropsConfiguration.getInstance().getWD(), "OnCloud/LocalTemplate/" + idSociete);
}
 
@Override
public String getTemplatePath(String templateId, String language, String type) {
String path = templateId;
 
if (type != null) {
path = insertBeforeExtenstion(path, type);
}
if (language != null && language.trim().length() > 0) {
path = language + "/" + path;
}
path = idSociete + "/" + path;
return path;
}
 
@Override
public void unSync(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File from = getCloudFile(templateId + ext, language, type);
final File to = getLocalFile(templateId + ext, language, type);
try {
if (from.exists() && !to.exists()) {
FileUtils.copyFile(from, to);
}
} catch (IOException e) {
throw new IllegalStateException("Copie impossible", e);
}
}
}
 
@Override
public void sync(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File from = getLocalFile(templateId + ext, language, type);
final File to = getCloudFile(templateId + ext, language, type);
try {
if (from.exists()) {
ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
SyncClient c = createSyncClient(config);
String remotePath = "Template/";
if (language != null && language.trim().length() > 0) {
remotePath += language + "/";
}
remotePath += idSociete;
System.out.println("Sending on cloud:" + from.getCanonicalPath() + " to " + remotePath + " " + from.getName());
c.sendFile(from, remotePath, from.getName(), config.getToken());
 
FileUtils.copyFile(from, to);
ensureDelete(from);
}
} catch (Exception e) {
throw new IllegalStateException("Synchronisation impossible", e);
}
}
}
 
@Override
public void restore(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File local = getLocalFile(templateId + ext, language, type);
if (local.exists()) {
ensureDelete(local);
}
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractJOOReportsSheet.java
106,7 → 106,7
OGNLDataModel model = new OGNLDataModel(createMap);
 
model.putAll(createMap);
template.createDocument(model).saveAs(fileOutOO);
template.createDocument(model).saveToPackageAs(fileOutOO);
 
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractLocalTemplateProvider.java
18,56 → 18,91
import java.io.FileNotFoundException;
import java.io.InputStream;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
 
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;
public InputStream getTemplate(String templateId, String language, String type) {
final File file = getFileTemplate(templateId, language, type);
return (file == null ? null : getInputStream(file));
}
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");
private FileInputStream getInputStream(File f) {
try {
return new FileInputStream(file);
return new FileInputStream(f);
} catch (FileNotFoundException e) {
System.err.println("No print configuration " + file.getAbsolutePath() + " for template id: " + templateId);
System.err.println("Error: no file:" + f.getAbsolutePath());
e.printStackTrace();
}
return null;
}
 
public File getFileTemplate(String templateId, String language, String type) {
File templateFile = getTemplateFromLocalFile(templateId, language, type);
if (templateFile != null && templateFile.exists()) {
return templateFile;
}
templateFile = getTemplateFromLocalFile(templateId + ".ods", language, type);
if (templateFile != null && templateFile.exists()) {
return templateFile;
}
templateFile = getTemplateFromLocalFile(templateId + ".odt", language, type);
if (templateFile != null && templateFile.exists()) {
return templateFile;
}
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();
public InputStream getTemplatePrintConfiguration(String templateId, String language, String type) {
final File file = getFileTemplatePrintConfiguration(templateId, language, type);
return getInputStream(file);
}
 
public File getFileTemplatePrintConfiguration(String templateId, String language, String type) {
final File file = getTemplateFromLocalFile(templateId + ".odsp", language, type);
return file;
}
return null;
 
@Override
public InputStream getTemplateConfiguration(String templateId, String language, String type) {
final File file = getFileTemplateConfiguration(templateId, language, type);
return getInputStream(file);
}
 
public abstract File getTemplateFile(String templateId, String langage, String type);
public File getFileTemplateConfiguration(String templateId, String language, String type) {
final File file = getTemplateFromLocalFile(templateId + ".xml", language, type);
return file;
}
 
protected abstract File getTemplateFromLocalFile(String templateIdWithExtension, String language, String type);
 
@Override
public abstract String getTemplatePath(String templateId, String langage, String type);
public abstract String getTemplatePath(String templateId, String language, String type);
 
public static String insertBeforeExtenstion(String fileName, String text) {
final int index = fileName.lastIndexOf('.');
if (index < 0) {
throw new IllegalArgumentException("No extension found in fileName '" + fileName + "'");
}
if (index == 0) {
return fileName + text;
}
final String name = fileName.substring(0, index);
final String ext = fileName.substring(index);
return name + text + ext;
}
 
void ensureDelete(File f) {
for (int i = 0; i < 2; i++) {
if (f.delete()) {
return;
}
JOptionPane.showMessageDialog(new JFrame(), "Fichier " + f.getAbsolutePath() + " vérrouillé.\nMerci de fermer tout programme pouvant y accéder (OpenOffice).");
}
f.deleteOnExit();
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/TemplateProvider.java
35,4 → 35,15
* Returns the content of template print configuration file (ex: the odsp file)
* */
public InputStream getTemplatePrintConfiguration(String templateId, String language, String type);
 
/**
* Returns true if the template is synchronized with other computers
*/
public boolean isSynced(String templateId, String language, String type);
 
public void unSync(String templateId, String language, String type);
 
public void sync(String templateId, String language, String type);
 
public void restore(String templateId, String language, String type);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/TemplateManager.java
47,7 → 47,7
 
public void setDefaultProvider(String templateId, TemplateProvider provider) {
defaultMap.put(templateId, provider);
knownTemplateIds.add(templateId);
register(templateId);
}
 
public void setDefaultProvider(TemplateProvider provider) {
128,8 → 128,10
}
 
public void register(String templateId) {
if (!knownTemplateIds.contains(templateId)) {
knownTemplateIds.add(templateId);
}
}
 
public void dump() {
System.out.println(this.getClass().getCanonicalName());
162,4 → 164,21
public boolean isKnwonTemplate(String templateId) {
return this.knownTemplateIds.contains(templateId);
}
 
public List<String> getKnownTemplateIds() {
return knownTemplateIds;
}
 
/**
* Get the template provider
*
* @return the TemplateProvider file, IllegalStateException if no template is found
* */
public TemplateProvider getProvider(String templateId) {
final TemplateProvider provider = defaultMap.get(templateId);
if (provider == null) {
return defautProvider;
}
return provider;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DefaultLocalTemplateProvider.java
13,10 → 13,14
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.utils.FileUtils;
 
import java.io.File;
import java.io.IOException;
 
public class DefaultLocalTemplateProvider extends AbstractLocalTemplateProvider {
 
private static final String[] EXTS = new String[] { ".ods", ".odsp", ".xml" };
private static final String LOCAL = "local_";
private File baseDirectory;
 
public DefaultLocalTemplateProvider() {
28,22 → 32,43
}
 
@Override
public File getTemplateFile(String templateId, String langage, String type) {
File file = getFile(templateId, langage, type);
public File getTemplateFromLocalFile(String templateIdWithExtension, String language, String type) {
File file = getLocalFile(templateIdWithExtension, language, type);
if (!file.exists()) {
file = getFile(templateId + ".ods", langage, type);
file = getFile(templateIdWithExtension, language, type);
}
return file;
}
 
private File getFile(String templateId, String langage, String type) {
String path = templateId;
private File getLocalFile(String templateIdWithExtension, String language, String type) {
// Looking first for baseDirectory/language/local_templateId + type
String localPath = templateIdWithExtension;
 
if (type != null) {
path += type;
localPath = insertBeforeExtenstion(localPath, type);
}
if (langage != null && langage.trim().length() > 0) {
path = langage + File.separatorChar + path;
 
if (language != null && language.trim().length() > 0) {
localPath = language + File.separatorChar + LOCAL + localPath;
} else {
localPath = LOCAL + localPath;
}
final File file = new File(baseDirectory, localPath);
return file;
}
 
private File getFile(String templateIdWithExtension, String language, String type) {
// baseDirectory/language/templateId + type
String path = templateIdWithExtension;
 
if (type != null) {
path = insertBeforeExtenstion(path, type);
}
 
if (language != null && language.trim().length() > 0) {
path = language + File.separatorChar + path;
}
 
File file = new File(baseDirectory, path);
if (!file.exists()) {
file = new File("Configuration/Template/Default", path);
52,15 → 77,64
}
 
@Override
public String getTemplatePath(String templateId, String langage, String type) {
public String getTemplatePath(String templateId, String language, String type) {
String path = "Configuration/Template/Default";
if (type != null) {
path += type;
path = insertBeforeExtenstion(path, type);
}
if (langage != null) {
path = langage + '/' + path;
if (language != null) {
path = language + '/' + path;
}
return path;
}
 
@Override
public boolean isSynced(String templateId, String language, String type) {
return !getLocalFile(templateId + ".ods", language, type).exists();
}
 
@Override
public void unSync(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File from = getFile(templateId + ext, language, type);
final File to = getLocalFile(templateId + ext, language, type);
try {
if (from.exists() && !to.exists()) {
FileUtils.copyFile(from, to);
}
} catch (IOException e) {
throw new IllegalStateException("Copie impossible", e);
}
}
}
 
@Override
public void sync(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File from = getLocalFile(templateId + ext, language, type);
final File to = getFile(templateId + ext, language, type);
try {
if (from.exists()) {
FileUtils.copyFile(from, to);
ensureDelete(from);
}
} catch (IOException e) {
throw new IllegalStateException("Synchronisation impossible", e);
}
}
}
 
@Override
public void restore(String templateId, String language, String type) {
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File local = getLocalFile(templateId + ext, language, type);
if (local.exists()) {
local.delete();
ensureDelete(local);
}
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLElement.java
77,7 → 77,7
if (attributeValue.equalsIgnoreCase("DateEcheance")) {
int idModeReglement = row.getInt("ID_MODE_REGLEMENT");
Date d = (Date) row.getObject("DATE");
return getDateEcheance(idModeReglement, d);
return getDateEcheance(idModeReglement, d, this.elt.getAttributeValue("DatePattern"));
}
 
final List<Element> eltFields = this.elt.getChildren("field");
177,10 → 177,9
*
* @param idModeRegl
* @param currentDate
* @return la date d'échéance au format dd/MM/yy
* @return la date d'échéance au format dd/MM/yy si datePattern !=null sinon une Date
*/
protected String getDateEcheance(int idModeRegl, Date currentDate) {
final DateFormat format2 = new SimpleDateFormat("dd/MM/yyyy");
protected Object getDateEcheance(int idModeRegl, Date currentDate, String datePattern) {
SQLElement eltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
SQLRow row = eltModeRegl.getTable().getRow(idModeRegl);
int aJ = row.getInt("AJOURS");
192,11 → 191,14
return " ";
}
}
String s = format2.format(ModeDeReglementSQLElement.calculDate(aJ, nJ, currentDate));
System.err.println(s);
return s;
// return format2.format(ModeDeReglementSQLElement.calculDate(aJ, nJ, currentDate));
Date calculDate = ModeDeReglementSQLElement.calculDate(aJ, nJ, currentDate);
if (datePattern != null && datePattern.trim().length() > 0) {
final DateFormat format2 = new SimpleDateFormat(datePattern);
return format2.format(calculDate);
} else {
return calculDate;
}
}
 
public boolean isTypeReplace() {
// remplacement d'un pattern contenu dans la cellule
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
180,6 → 180,15
if (nbPage > 2) {
sheet.duplicateFirstRows(endPageLine, nbPage - 2);
}
String pageRef = tableau.getAttributeValue("pageRef");
if (pageRef != null && pageRef.trim().length() > 0) {
MutableCell<SpreadSheet> cell = sheet.getCellAt(pageRef);
cell.setValue("Page 1/" + nbPage);
for (int i = 1; i < nbPage; i++) {
MutableCell<SpreadSheet> cell2 = sheet.getCellAt(cell.getX(), cell.getY() + (endPageLine * i));
cell2.setValue("Page " + (i + 1) + "/" + nbPage);
}
}
fillTable(tableau, liste, sheet, mapStyle, false, style);
}
}
288,7 → 297,7
 
Object oTmp = mTmp.get(new Integer(sheet.resolveHint(loc).x));
styleOO = oTmp == null ? null : oTmp.toString();
System.err.println("Set style " + styleOO);
// System.err.println("Set style " + styleOO);
}
 
int tmpCelluleAffect = fill(test ? "A1" : loc, value, sheet, replace, null, styleOO, test, controlLine);
400,12 → 409,12
int nbCellule = 1;
// est ce que la cellule est valide
if (test || sheet.isCellValid(sheet.resolveHint(location).x, sheet.resolveHint(location).y)) {
MutableCell cell = sheet.getCellAt(location);
 
// on divise en 2 cellules si il y a des retours à la ligne
if (controlLine && (value != null && value.toString().indexOf('\n') >= 0)) {
 
if (!test) {
MutableCell cell = sheet.getCellAt(location);
String firstPart = value.toString().substring(0, value.toString().indexOf('\n'));
String secondPart = value.toString().substring(value.toString().indexOf('\n') + 1, value.toString().length());
secondPart = secondPart.replace('\n', ',');
425,6 → 434,7
nbCellule = 2;
} else {
if (!test) {
MutableCell cell = sheet.getCellAt(location);
// application de la valeur
setCellValue(cell, value, replace, replacePattern);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractListeSheetXml.java
13,7 → 13,7
package org.openconcerto.erp.generationDoc;
 
import static org.openconcerto.erp.generationDoc.SheetXml.getValidFileName;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.StringUtils;
 
import java.io.File;
40,6 → 40,11
 
private File generatedOpenDocumentFile;
 
public AbstractListeSheetXml(SQLRow row) {
this.row = row;
generatedOpenDocumentFile = new File(getDocumentOutputDirectory(), getValidFileName(getName()) + ".ods");
}
 
public AbstractListeSheetXml() {
generatedOpenDocumentFile = new File(getDocumentOutputDirectory(), getValidFileName(getName()) + ".ods");
}
52,6 → 57,17
createListeValues();
generatedOpenDocumentFile = OOgenerationListeXML.genere(getTemplateId(), getDocumentOutputDirectory(), getValidFileName(getName()), listAllSheetValues, mapAllSheetValues,
styleAllSheetValues, sheetNames, null);
// Flush values after creation
if (listAllSheetValues != null) {
listAllSheetValues.clear();
}
if (mapAllSheetValues != null) {
mapAllSheetValues.clear();
}
if (styleAllSheetValues != null) {
styleAllSheetValues.clear();
}
 
return AbstractListeSheetXml.this;
} catch (Exception e) {
DEFAULT_HANDLER.uncaughtException(null, e);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtTicketCaisse.java
18,18 → 18,16
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
 
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.Callable;
 
public class GenerationMvtTicketCaisse extends GenerationEcritures implements Runnable {
public class GenerationMvtTicketCaisse extends GenerationEcritures {
 
private static final String source = "TICKET_CAISSE";
public static final Integer journal = Integer.valueOf(JournalSQLElement.VENTES);
private SQLRow rowTicket;
private final SQLRow rowTicket;
private static final SQLTable ticketTable = base.getTable("TICKET_CAISSE");
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
45,7 → 43,7
System.err.println("********* init GeneRation");
this.idMvt = idMvt;
this.rowTicket = ticket;
new Thread(GenerationMvtTicketCaisse.this).start();
 
}
 
/**
60,28 → 58,30
this.rowTicket = ticket;
}
 
private void genereMouvement() throws IllegalArgumentException {
public Callable<Integer> genereMouvement() {
final Callable<Integer> c = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
SQLRow clientRow = GenerationMvtTicketCaisse.this.rowTicket.getForeignRow("ID_CLIENT");
 
SQLRow clientRow = this.rowTicket.getForeignRow("ID_CLIENT");
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(((Long) this.rowTicket.getObject("TOTAL_TTC")).longValue());
PrixHT prixTVA = new PrixHT(((Long) this.rowTicket.getObject("TOTAL_TVA")).longValue());
PrixHT prixHT = new PrixHT(((Long) this.rowTicket.getObject("TOTAL_HT")).longValue());
PrixTTC prixTTC = new PrixTTC(((Long) GenerationMvtTicketCaisse.this.rowTicket.getObject("TOTAL_TTC")).longValue());
PrixHT prixTVA = new PrixHT(((Long) GenerationMvtTicketCaisse.this.rowTicket.getObject("TOTAL_TVA")).longValue());
PrixHT prixHT = new PrixHT(((Long) GenerationMvtTicketCaisse.this.rowTicket.getObject("TOTAL_HT")).longValue());
 
// iniatilisation des valeurs de la map
this.date = this.rowTicket.getDate("DATE").getTime();
this.nom = "Ticket " + this.rowTicket.getString("NUMERO");
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
GenerationMvtTicketCaisse.this.date = GenerationMvtTicketCaisse.this.rowTicket.getDate("DATE").getTime();
GenerationMvtTicketCaisse.this.nom = "Ticket " + GenerationMvtTicketCaisse.this.rowTicket.getString("NUMERO");
GenerationMvtTicketCaisse.this.mEcritures.put("DATE", GenerationMvtTicketCaisse.this.date);
GenerationMvtTicketCaisse.this.mEcritures.put("NOM", GenerationMvtTicketCaisse.this.nom);
GenerationMvtTicketCaisse.this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
GenerationMvtTicketCaisse.this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
 
// on calcule le nouveau numero de mouvement
if (this.idMvt == 1) {
getNewMouvement(GenerationMvtTicketCaisse.source, this.rowTicket.getID(), 1, this.nom);
if (GenerationMvtTicketCaisse.this.idMvt == 1) {
getNewMouvement(GenerationMvtTicketCaisse.source, GenerationMvtTicketCaisse.this.rowTicket.getID(), 1, GenerationMvtTicketCaisse.this.nom);
} else {
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
GenerationMvtTicketCaisse.this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(GenerationMvtTicketCaisse.this.idMvt));
}
 
// compte Vente Produits
102,9 → 102,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteProduit));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(produitHT));
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteProduit));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(produitHT));
ajoutEcriture();
}
 
121,7 → 121,8
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(this.rowTicket, this.rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
Map<Integer, Long> m = getMultiTVAFromRow(GenerationMvtTicketCaisse.this.rowTicket, GenerationMvtTicketCaisse.this.rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"),
true);
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
131,17 → 132,17
if (idCpt <= 1) {
idCpt = idCompteTVA;
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(l));
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(l));
ajoutEcriture();
allTaxe += l;
}
}
if (allTaxe < prixTVA.getLongValue()) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
ajoutEcriture();
}
 
158,35 → 159,30
}
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
return GenerationMvtTicketCaisse.this.idMvt;
}
};
return c;
 
// Mise à jour de mouvement associé à la facture
 
SQLRowValues valTicket = new SQLRowValues(GenerationMvtTicketCaisse.ticketTable);
valTicket.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
try {
if (valTicket.getInvalid() == null) {
 
valTicket.update(this.rowTicket.getID());
// // Mise à jour de mouvement associé à la facture
//
// SQLRowValues valTicket = new SQLRowValues(GenerationMvtTicketCaisse.ticketTable);
// valTicket.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
//
// try {
// if (valTicket.getInvalid() == null) {
//
// valTicket.update(this.rowTicket.getID());
// }
// } catch (SQLException e) {
// System.err.println("Erreur à l'insertion dans la table " + valTicket.getTable().getName()
// + " : " + e);
// e.printStackTrace();
// }
}
} catch (SQLException e) {
System.err.println("Erreur à l'insertion dans la table " + valTicket.getTable().getName() + " : " + e);
e.printStackTrace();
}
}
 
public void run() {
try {
System.err.println("****Start genere Mouvement");
genereMouvement();
System.err.println("****End genere Mouvement");
} catch (IllegalArgumentException e) {
ExceptionHandler.handle("Erreur pendant la générations des écritures comptables", e);
e.printStackTrace();
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationEcritures.java
23,6 → 23,8
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
320,20 → 322,35
return 1;
}
 
protected Map<Integer, Long> getMultiTVAFromRow(SQLRow row, SQLTable foreign) {
protected Map<Integer, Long> getMultiTVAFromRow(SQLRow row, SQLTable foreign, boolean vente) {
List<SQLRow> rows = row.getReferentRows(foreign);
 
Map<Integer, Long> map = new HashMap<Integer, Long>();
// Total HT par TVA
Map<SQLRow, Long> mapTaxeHT = new HashMap<SQLRow, Long>();
for (SQLRow sqlRow : rows) {
SQLRow taxe = sqlRow.getForeignRow("ID_TAXE");
long val = sqlRow.getLong("T_PV_TTC") - sqlRow.getLong("T_PV_HT");
Long l = map.get(taxe.getInt("ID_COMPTE_PCE_COLLECTE"));
long val = sqlRow.getLong("T_PV_HT");
Long l = mapTaxeHT.get(taxe);
if (l == null) {
map.put(taxe.getInt("ID_COMPTE_PCE_COLLECTE"), Long.valueOf(val));
mapTaxeHT.put(taxe, Long.valueOf(val));
} else {
map.put(taxe.getInt("ID_COMPTE_PCE_COLLECTE"), Long.valueOf(val + l));
mapTaxeHT.put(taxe, Long.valueOf(val + l));
}
}
 
Map<Integer, Long> map = new HashMap<Integer, Long>();
for (SQLRow sqlRow : mapTaxeHT.keySet()) {
BigDecimal d = new BigDecimal(sqlRow.getFloat("TAUX"));
BigDecimal result = d.multiply(new BigDecimal(mapTaxeHT.get(sqlRow)), MathContext.DECIMAL128).movePointLeft(2);
int compte;
if (vente) {
compte = sqlRow.getInt("ID_COMPTE_PCE_COLLECTE");
} else {
compte = sqlRow.getInt("ID_COMPTE_PCE_DED");
}
map.put(compte, result.setScale(0, BigDecimal.ROUND_HALF_UP).longValue());
}
 
return map;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirClient.java
26,6 → 26,7
 
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
 
public class GenerationMvtAvoirClient extends GenerationEcritures {
 
142,20 → 143,57
}
 
// compte TVA
if (prixTVA.getLongValue() > 0) {
int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
if (idCompteTVA <= 1) {
try {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
} catch (Exception e) {
 
e.printStackTrace();
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(avoirRow, avoirClientTable.getTable("AVOIR_CLIENT_ELEMENT"), true);
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
if (l != null && l > 0) {
// FIXME
int idCpt = i;
if (idCpt <= 1) {
idCpt = idCompteTVA;
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(l));
ajoutEcriture();
allTaxe += l;
}
}
if (allTaxe < prixTVA.getLongValue()) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.mEcritures.put("DEBIT", Long.valueOf(prixTVA.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
ajoutEcriture();
}
 
}
//
// // compte TVA
// int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
// if (idCompteTVA <= 1) {
// try {
// idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
// } catch (Exception e) {
//
// e.printStackTrace();
// }
// }
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
// this.mEcritures.put("DEBIT", Long.valueOf(prixTVA.getLongValue()));
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// ajoutEcriture();
 
// compte Clients
int idCompteClient = avoirRow.getForeignRow("ID_CLIENT").getInt("ID_COMPTE_PCE");
if (idCompteClient <= 1) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteFacture.java
162,7 → 162,7
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
Map<Integer, Long> m = getMultiTVAFromRow(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), true);
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/component/ReferenceArticleSQLComponent.java
18,11 → 18,13
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ArticleDesignationTable;
import org.openconcerto.erp.core.sales.product.ui.ArticleTarifTable;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLElement;
33,6 → 35,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
289,6 → 292,18
this.add(fieldCodeBarre, c);
this.addView(fieldCodeBarre, "CODE_BARRE");
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
if (gestionUV) {
c.gridy++;
c.gridx = 0;
this.add(new JLabel(getLabelFor("ID_UNITE_VENTE")), c);
c.gridx++;
ElementComboBox boxUnite = new ElementComboBox();
this.add(boxUnite, c);
this.addView(boxUnite, "ID_UNITE_VENTE");
}
DefaultProps props = DefaultNXProps.getInstance();
 
// Article détaillé
1057,6 → 1072,7
SQLRow row = getTable().getRow(getTable().getUndefinedID());
 
rowVals.put("ID_TAXE", row.getInt("ID_TAXE"));
rowVals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
rowVals.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
selectModeVente(ReferenceArticleSQLElement.A_LA_PIECE);
rowVals.put("VALEUR_METRIQUE_1", Float.valueOf("1.0"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ModeVenteArticleSQLElement.java
16,6 → 16,7
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
54,18 → 55,10
public void addViews() {
 
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 1;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.WEST;
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Nom
JLabel labelNom = new JLabel("Nom");
JLabel labelNom = new JLabel(getLabelFor("NOM"));
JTextField textNom = new JTextField();
 
this.add(labelNom, c);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/UniteVenteArticleSQLElement.java
New file
0,0 → 1,93
/*
* 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.product.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class UniteVenteArticleSQLElement extends ComptaSQLConfElement {
 
public static final int A_LA_PIECE = 2;
 
public UniteVenteArticleSQLElement() {
super("UNITE_VENTE", "une unité de vente", "unité de vente");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
l.add("NOM");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
return l;
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
 
public void addViews() {
 
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Nom
JLabel labelCode = new JLabel(getLabelFor("CODE"));
JTextField textCode = new JTextField(25);
 
this.add(labelCode, c);
c.gridx++;
DefaultGridBagConstraints.lockMinimumSize(textCode);
this.add(textCode, c);
 
// Nom
c.gridy++;
c.gridx = 0;
JLabel labelNom = new JLabel(getLabelFor("NOM"));
JTextField textNom = new JTextField(50);
 
this.add(labelNom, c);
c.gridx++;
DefaultGridBagConstraints.lockMinimumSize(textNom);
this.add(textNom, c);
 
this.addRequiredSQLObject(textCode, "CODE");
this.addRequiredSQLObject(textNom, "NOM");
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".unit";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/ArticleRowValuesRenderer.java
63,9 → 63,10
if (mode != null && this.listColorModeVente != null && this.listColorModeVente.contains(Integer.valueOf(mode.intValue()))) {
if (!isSelected) {
comp.setBackground(light);
} else {
comp.setBackground(darker);
}
// else {
// comp.setBackground(darker);
// }
return comp;
}
 
72,9 → 73,10
if (!model.isCellEditable(row, column)) {
if (!isSelected) {
comp.setBackground(lightBlack);
} else {
comp.setBackground(lightBlackDarker);
}
// else {
// comp.setBackground(lightBlackDarker);
// }
return comp;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/QteUnitRowValuesRenderer.java
New file
0,0 → 1,53
/*
* 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.product.ui;
 
import org.openconcerto.erp.core.common.ui.DeviseNiceTableCellRenderer;
 
import java.awt.Color;
import java.awt.Component;
import java.text.DecimalFormat;
 
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
 
public class QteUnitRowValuesRenderer extends DeviseNiceTableCellRenderer {
 
// Black
private final static Color lightBlack = new Color(215, 215, 215);
DecimalFormat decimalFormat = new DecimalFormat("##,##0.######");
 
public QteUnitRowValuesRenderer() {
// AlternateTableCellRenderer.setBGColorMap(this, CollectionUtils.createMap(light,
// lightGrey, lightBlack, lightBlackGrey));
}
 
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
((JLabel) comp).setHorizontalAlignment(SwingConstants.RIGHT);
if (!table.getModel().isCellEditable(row, column) && !isSelected) {
 
comp.setBackground(lightBlack);
}
if (value == null) {
((JLabel) comp).setText("");
} else {
((JLabel) comp).setText(this.decimalFormat.format(((Number) value).doubleValue()));
}
return comp;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/Caisse.java
24,8 → 24,8
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.TicketLine;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.generationEcritures.GenerationMvtTicketCaisse;
import org.openconcerto.erp.generationEcritures.GenerationMvtVirement;
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
33,7 → 33,6
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
50,7 → 49,6
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
 
58,7 → 56,6
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
115,7 → 112,7
 
public static void createConnexion() {
final ComptaPropsConfiguration conf = ComptaPropsConfiguration.create();
conf.setupLogging("Logs");
conf.setupLogging("logs");
Configuration.setInstance(conf);
try {
conf.getBase();
131,6 → 128,7
} catch (Exception e) {
JOptionPane.showMessageDialog(new JFrame(), "Impossible de configurer la connexion à la base de donnée.\n ID société: " + getSocieteID() + " \n ID utilisateur: " + getUserID());
e.printStackTrace();
System.exit(2);
}
}
 
161,19 → 159,21
// Articles
for (Pair<Article, Integer> item : ticket.getArticles()) {
SQLRowValues rowValsElt = new SQLRowValues(eltFact.getTable());
 
rowValsElt.put("QTE", item.getSecond());
rowValsElt.put("PV_HT", Long.valueOf(item.getFirst().getPriceInCents()));
final long value = Long.valueOf(item.getFirst().getPriceInCents()) * item.getSecond();
final long valueHT = Long.valueOf(item.getFirst().getPriceHTInCents()) * item.getSecond();
final Article article = item.getFirst();
final Integer nb = item.getSecond();
rowValsElt.put("QTE", nb);
rowValsElt.put("PV_HT", Long.valueOf(article.getPriceHTInCents()));
final long value = Long.valueOf(article.getPriceInCents()) * nb;
final long valueHT = Long.valueOf(article.getPriceHTInCents()) * nb;
total += value;
totalHT += valueHT;
rowValsElt.put("T_PV_HT", valueHT);
rowValsElt.put("T_PV_TTC", value);
rowValsElt.put("ID_TAXE", item.getFirst().getIdTaxe());
rowValsElt.put("CODE", item.getFirst().getCode());
rowValsElt.put("NOM", item.getFirst().getName());
rowValsElt.put("ID_TAXE", article.getIdTaxe());
rowValsElt.put("CODE", article.getCode());
rowValsElt.put("NOM", article.getName());
rowValsElt.put("ID_TICKET_CAISSE", rowVals);
rowValsElt.put("ID_ARTICLE", article.getId());
}
rowVals.put("TOTAL_HT", totalHT);
 
197,7 → 197,6
try {
rowValsElt.put("ID_CLIENT", getClientCaisse().getID());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long montant = Long.valueOf(paiement.getMontantInCents());
212,17 → 211,20
}
 
SQLRow rowFinal = rowVals.insert();
Thread t = new Thread(new GenerationMvtTicketCaisse(rowFinal));
t.start();
GenerationMvtTicketCaisse mvt = new GenerationMvtTicketCaisse(rowFinal);
final Integer idMvt;
try {
t.join();
} catch (InterruptedException exn) {
// TODO Bloc catch auto-généré
idMvt = mvt.genereMouvement().call();
} catch (Exception exn) {
exn.printStackTrace();
throw new SQLException(exn);
}
 
SQLRowValues valTicket = rowFinal.asRowValues();
valTicket.put("ID_MOUVEMENT", Integer.valueOf(idMvt));
rowFinal = valTicket.update();
 
// msie à jour du mouvement
rowFinal = rowFinal.getTable().getRow(rowFinal.getID());
List<SQLRow> rowsEnc = rowFinal.getReferentRows(eltEnc.getTable());
long totalEnc = 0;
for (SQLRow sqlRow : rowsEnc) {
251,8 → 253,6
 
@Override
public void run() {
// TODO Raccord de méthode auto-généré
 
JOptionPane.showMessageDialog(null, "Clôture de la caisse terminée.");
}
});
260,7 → 260,6
}
});
} catch (Exception exn) {
// TODO Bloc catch auto-généré
ExceptionHandler.handle("Une erreur est survenue pendant la clôture.", exn);
}
 
308,58 → 307,17
 
private static void updateStock(int id) {
 
final SQLElement elt = Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE");
final SQLElement eltArticleFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
final SQLElement elt = Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE");
final SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
final SQLRow rowFacture = elt.getTable().getRow(id);
 
// On récupére les articles qui composent la facture
final SQLSelect selEltfact = new SQLSelect(eltArticleFact.getTable().getBase());
selEltfact.addSelect(eltArticleFact.getTable().getField("ID"));
selEltfact.setWhere(new Where(eltArticleFact.getTable().getField("ID_TICKET_CAISSE"), "=", id));
 
final List lEltFact = (List) eltArticleFact.getTable().getBase().getDataSource().execute(selEltfact.asString(), new ArrayListHandler());
 
if (lEltFact != null) {
for (int i = 0; i < lEltFact.size(); i++) {
 
// Elt qui compose facture
final Object[] tmp = (Object[]) lEltFact.get(i);
final int idEltFact = ((Number) tmp[0]).intValue();
final SQLRow rowEltFact = eltArticleFact.getTable().getRow(idEltFact);
 
// on récupére l'article qui lui correspond
final SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (SQLField field : eltArticle.getTable().getFields()) {
if (rowEltFact.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), rowEltFact.getObject(field.getName()));
MouvementStockSQLElement mvtStock = (MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
mvtStock.createMouvement(elt.getTable().getRow(id), eltArticleFact.getTable(), new StockLabel() {
@Override
public String getLabel(SQLRow rowOrigin, SQLRow rowElt) {
return "Ticket N°" + rowOrigin.getString("NUMERO");
}
}, false);
}
// rowArticle.loadAllSafe(rowEltFact);
final int idArticle = ReferenceArticleSQLElement.getIdForCN(rowArticle, true);
 
// on crée un mouvement de stock pour chacun des articles
final SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
final SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
rowVals.put("QTE", -(rowEltFact.getInt("QTE")));
rowVals.put("NOM", "Ticket N°" + rowFacture.getString("NUMERO"));
rowVals.put("IDSOURCE", id);
rowVals.put("SOURCE", elt.getTable().getName());
rowVals.put("ID_ARTICLE", idArticle);
rowVals.put("DATE", rowFacture.getObject("DATE"));
try {
final SQLRow row = rowVals.insert();
// MAYBE Show warning if qte min
MouvementStockSQLElement.updateStock(Arrays.asList(row.getID()));
} catch (SQLException e) {
e.printStackTrace();
}
 
}
}
}
 
public static int getID() {
final Document d = getDocument();
return Integer.valueOf(d.getRootElement().getAttributeValue("caisseID", "-1"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/ESCSerialPrinter.java
24,8 → 24,6
import java.util.List;
 
public class ESCSerialPrinter extends DefaultTicketPrinter {
protected List<String> strings = new ArrayList<String>();
protected List<Integer> modes = new ArrayList<Integer>();
private String port;
 
public ESCSerialPrinter(String port) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/SaisieVenteComptoirSQLElement.java
734,7 → 734,8
rowVals.put("DATE", rowVC.getObject("DATE"));
try {
SQLRow row = rowVals.insert();
CollectionMap<SQLRow, List<SQLRowValues>> map = MouvementStockSQLElement.updateStock(Arrays.asList(row.getID()));
CollectionMap<SQLRow, List<SQLRowValues>> map = ((MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK")).updateStock(
Arrays.asList(row.getID()), false);
MouvementStockSQLElement.createCommandeF(map, null);
} catch (SQLException e) {
e.printStackTrace();
875,7 → 876,8
rowVals.put("DATE", row.getObject("DATE"));
try {
SQLRow rowNew = rowVals.insert();
CollectionMap<SQLRow, List<SQLRowValues>> map = MouvementStockSQLElement.updateStock(Arrays.asList(rowNew.getID()));
CollectionMap<SQLRow, List<SQLRowValues>> map = ((MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK")).updateStock(
Arrays.asList(rowNew.getID()), false);
MouvementStockSQLElement.createCommandeF(map, null);
} catch (SQLException e) {
e.printStackTrace();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseFrame.java
15,10 → 15,13
 
import org.openconcerto.erp.core.sales.pos.Caisse;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.State;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.utils.ClassPathLoader;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ProductInfo;
 
import java.io.File;
import java.net.MalformedURLException;
45,10 → 48,18
if (System.getProperty(State.DEAF) == null) {
System.setProperty(State.DEAF, "true");
}
 
System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
System.setProperty(SQLBase.ALLOW_OBJECT_REMOVAL, "true");
 
ExceptionHandler.setForceUI(true);
ExceptionHandler.setForumURL("http://www.openconcerto.org/forum");
ProductInfo.setInstance(new ProductInfo("OpenConcerto"));
 
// SpeedUp Linux
System.setProperty("sun.java2d.pmoffscreen", "false");
System.setProperty("org.openconcerto.sql.structure.useXML", "true");
 
System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
if (Caisse.isUsingJPos()) {
ClassPathLoader c = ClassPathLoader.getInstance();
try {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
149,7 → 149,7
 
final Categorie s1 = m.get(row.getInt("ID_FAMILLE_ARTICLE"));
if (s1 != null) {
Article a = new Article(s1, row.getString("NOM"));
Article a = new Article(s1, row.getString("NOM"), row.getID());
a.setBarCode(row.getString("CODE_BARRE"));
a.setCode(row.getString("CODE"));
a.setIdTaxe(row.getInt("ID_TAXE"));
177,22 → 177,22
c2.add(s2_2);
 
for (int i = 0; i < 100; i++) {
final Article al = new Article(s2_2, "ILM" + i);
final Article al = new Article(s2_2, "ILM" + i, 1);
al.setPriceInCents(5000);
al.setBarCode("INFORMATIQUE " + i);
}
final Article a = new Article(s1, "012345678901234567890123456789");
final Article a = new Article(s1, "012345678901234567890123456789", 1);
a.setPriceInCents(106);
final Article b = new Article(s1, "St Valery");
final Article b = new Article(s1, "St Valery", 1);
b.setBarCode("ST VALERY");
b.setPriceInCents(300);
final Article cc = new Article(s1, "Cayeux");
final Article cc = new Article(s1, "Cayeux", 1);
cc.setPriceInCents(300);
final Article v1 = new Article(s2, "Abbeville");
final Article v1 = new Article(s2, "Abbeville", 1);
v1.setPriceInCents(106);
final Article v2 = new Article(s2, "Amiens");
final Article v2 = new Article(s2, "Amiens", 1);
v2.setPriceInCents(300);
final Article v3 = new Article(s2, "Rue");
final Article v3 = new Article(s2, "Rue", 1);
v3.setPriceInCents(300);
this.controler.addArticle(a);
this.controler.addArticle(a);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TextAreaTicketPanel.java
14,6 → 14,7
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.pos.Caisse;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Categorie;
103,8 → 104,11
List<SQLRow> l2 = row.getReferentRows(eltArticle.getTable());
Categorie c = new Categorie("");
for (SQLRow row2 : l2) {
Article a = new Article(c, row2.getString("NOM"));
a.setPriceInCents((int) row2.getLong("PV_HT"));
Article a = new Article(c, row2.getString("NOM"), row2.getInt("ID_ARTICLE"));
int ht = (int) row2.getLong("PV_HT");
a.setPriceHTInCents(ht);
float tva = TaxeCache.getCache().getTauxFromId(row2.getInt("ID_TAXE"));
a.setPriceInCents((int) Math.round(ht * (1.0 + (tva / 100.0D))));
t.addArticle(a);
t.setArticleCount(a, row2.getInt("QTE"));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Article.java
24,14 → 24,20
int priceHTInCents;
String barCode = "empty barcode";
String code = "";
private final int id;
private static Map<String, Article> codes = new HashMap<String, Article>();
 
public Article(Categorie s1, String string) {
public Article(Categorie s1, String string, int id) {
this.s = s1;
this.id = id;
this.name = string;
s1.addArticle(this);
}
 
public int getId() {
return this.id;
}
 
public int getPriceHTInCents() {
return this.priceHTInCents;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Ticket.java
18,6 → 18,8
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.ui.TicketCellRenderer;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Pair;
 
30,6 → 32,7
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
 
import org.jdom.Attribute;
import org.jdom.Document;
49,6 → 52,8
// Propre à la caisse
private int caisseNumber;
 
private static final SQLTable tableArticle = Configuration.getInstance().getRoot().findTable("ARTICLE");
 
public static Ticket getTicketFromCode(String code) {
// Code: 01_05042011_00002
// filtre les chiffres
109,7 → 114,11
String codebarre = element.getAttributeValue("codebarre");
String codeArt = element.getAttributeValue("code");
Categorie cat = new Categorie(categorie);
Article art = new Article(cat, name);
 
String valueID = element.getAttributeValue("id");
 
int id = valueID == null || valueID.trim().length() == 0 ? tableArticle.getUndefinedID() : Integer.parseInt(valueID);
Article art = new Article(cat, name, id);
art.priceInCents = prix_unitaire_cents;
art.setCode(codeArt);
art.setPriceHTInCents(prix_unitaire_cents_ht);
197,10 → 206,8
// final String codeStart = code;
final String codeStart = getPrefixCode();
String[] files = dir.list(new FilenameFilter() {
 
@Override
public boolean accept(File dir, String name) {
 
return name.startsWith(codeStart) && name.endsWith(".xml");
}
});
271,6 → 278,7
e.setAttribute("categorie", item.getFirst().getCategorie().getName());
e.setAttribute("codebarre", item.getFirst().getBarCode());
e.setAttribute("code", item.getFirst().getCode());
e.setAttribute("id", String.valueOf(item.getFirst().getId()));
e.setText(item.getFirst().getName());
topLevel.addContent(e);
}
314,14 → 322,16
 
// Date
prt.addToBuffer("");
SimpleDateFormat df = new SimpleDateFormat("EEEE d MMMM yyyy à HH:mm");
SimpleDateFormat df = new SimpleDateFormat("EEEE d MMMM yyyy à HH:mm", Locale.FRENCH);
prt.addToBuffer(DefaultTicketPrinter.formatRight(maxWidth, "Le " + df.format(getCreationDate())));
prt.addToBuffer("");
 
for (Pair<Article, Integer> item : this.items) {
prt.addToBuffer(DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, String.valueOf(item.getSecond())) + " "
+ DefaultTicketPrinter.formatLeft(maxWidth - 2 - MAX_PRICE_WIDTH - MAX_QTE_WIDTH, item.getFirst().getName()) + " "
+ DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, TicketCellRenderer.centsToString(item.getFirst().getPriceInCents())));
final Article article = item.getFirst();
final Integer nb = item.getSecond();
prt.addToBuffer(DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, String.valueOf(nb)) + " "
+ DefaultTicketPrinter.formatLeft(maxWidth - 2 - MAX_PRICE_WIDTH - MAX_QTE_WIDTH, article.getName()) + " "
+ DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, TicketCellRenderer.centsToString(nb * article.getPriceInCents())));
}
 
StringBuilder spacer = new StringBuilder();
429,9 → 439,7
if (string.length() > l) {
string = string.substring(0, l);
}
 
StringBuffer str = new StringBuffer(l);
 
final StringBuffer str = new StringBuffer(l);
final int stop = l - string.length();
for (int i = 0; i < stop; i++) {
str.append('0');
477,7 → 485,6
}
 
public List<Paiement> getPaiements() {
 
return this.paiements;
}
 
493,7 → 500,6
}
 
public List<Pair<Article, Integer>> getArticles() {
 
return this.items;
}
 
528,6 → 534,7
}
}
if (toModify != null) {
System.out.println("Ticket.setArticleCount():" + article + " " + count);
toModify.setSecond(count);
}
 
554,7 → 561,6
Pair<Article, Integer> lineToDelete = null;
for (Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(a)) {
 
final int count = line.getSecond() + 1;
if (count <= 0) {
lineToDelete = line;
571,7 → 577,6
 
@Override
public String toString() {
 
return "Ticket " + getCode();
}
 
592,7 → 597,6
}
 
public void deleteTicket() {
 
File dir = this.getOutputDir();
String name = this.getCode().replace(' ', '_') + ".xml";
File f = new File(dir, name);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/component/BonDeLivraisonSQLComponent.java
22,8 → 22,11
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement;
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
import org.openconcerto.erp.core.sales.shipment.ui.BonDeLivraisonItemTable;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.panel.PanelOOSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLInjector;
32,6 → 35,8
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 org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
168,11 → 173,11
this.addView(dateLivraison, "DATE_LIVRAISON");
}
// Client
JLabel labelClient = new JLabel(getLabelFor("ID_CLIENT"));
labelClient.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel labelClient = new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
this.add(labelClient, c);
 
496,6 → 501,12
}
}
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
 
if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
 
updateStock(idBon);
}
// updateQte(idBon);
} else {
ExceptionHandler.handle("Impossible d'ajouter, numéro de bon de livraison existant.");
553,8 → 564,32
bSheet.createDocumentAsynchronous();
bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
// On efface les anciens mouvements de stocks
SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
sel.addSelect(eltMvtStock.getTable().getField("ID"));
Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", getSelectedID());
Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
sel.setWhere(w.and(w2));
 
List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
if (l != null) {
for (int i = 0; i < l.size(); i++) {
Object[] tmp = (Object[]) l.get(i);
try {
eltMvtStock.archive(((Number) tmp[0]).intValue());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
updateStock(getSelectedID());
}
 
}
 
private void updateTotal() {
RowValuesTableModel model = this.tableBonItem.getModel();
 
706,4 → 741,26
 
}
 
protected String getLibelleStock(SQLRow row, SQLRow rowElt) {
return "BL N°" + row.getString("NUMERO");
}
 
/**
* Mise à jour des stocks pour chaque article composant la facture
*/
private void updateStock(int id) {
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
 
MouvementStockSQLElement mvtStock = (MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
mvtStock.createMouvement(getTable().getRow(id), getTable().getTable("BON_DE_LIVRAISON_ELEMENT"), new StockLabel() {
@Override
public String getLabel(SQLRow rowOrigin, SQLRow rowElt) {
return getLibelleStock(rowOrigin, rowElt);
}
}, false);
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/element/BonDeLivraisonSQLElement.java
18,14 → 18,20
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.preferences.DefaultProps;
 
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
34,6 → 40,8
import javax.swing.ImageIcon;
import javax.swing.JFrame;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
public class BonDeLivraisonSQLElement extends ComptaSQLConfElement {
 
// TODO bug rafraichissement on resize frame
112,4 → 120,30
editFactureFrame.setState(JFrame.NORMAL);
editFactureFrame.setVisible(true);
}
 
@Override
protected void archive(SQLRow row, boolean cutLinks) throws SQLException {
// TODO Raccord de méthode auto-généré
super.archive(row, cutLinks);
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
 
// Mise à jour des stocks
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
sel.addSelect(eltMvtStock.getTable().getField("ID"));
Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
sel.setWhere(w.and(w2));
 
List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
if (l != null) {
for (int i = 0; i < l.size(); i++) {
Object[] tmp = (Object[]) l.get(i);
eltMvtStock.archive(((Number) tmp[0]).intValue());
}
}
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/ui/BonDeLivraisonItemTable.java
20,11 → 20,18
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ArticleRowValuesRenderer;
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.CellDynamicModifier;
import org.openconcerto.sql.view.list.RowValuesTable;
32,6 → 39,8
import org.openconcerto.sql.view.list.SQLTableElement;
import org.openconcerto.ui.table.XTableColumnModel;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
45,6 → 54,7
// private final Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
 
private SQLTableElement tableElementPoidsTotalLivree;
private SQLTable tableArticle = Configuration.getInstance().getBase().getTable("ARTICLE");
 
public BonDeLivraisonItemTable(List<JButton> l) {
super(l);
54,8 → 64,17
protected void init() {
final SQLElement e = getSQLElement();
 
SQLPreferences prefs = new SQLPreferences(getSQLElement().getTable().getDBRoot());
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
// Article
final SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true);
list.add(tableElementArticle);
 
// Code article
final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"));
list.add(tableElementCode);
156,9 → 175,31
// DeviseCellEditor());
// list.add(tableElement_PrixMetrique3_AchatHT);
 
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
@Override
public boolean isCellEditable(SQLRowValues vals) {
 
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
return false;
} else {
return super.isCellEditable(vals);
}
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
}
};
list.add(qteU);
 
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
// Quantité
final SQLTableElement tableElement_Quantite = new SQLTableElement(e.getTable().getField("QTE"), Integer.class);
list.add(tableElement_Quantite);
this.qte = new SQLTableElement(e.getTable().getField("QTE"), Integer.class);
list.add(this.qte);
 
// Mode de vente
final SQLTableElement tableElement_ModeVente = new SQLTableElement(e.getTable().getField("ID_MODE_VENTE_ARTICLE"));
180,8 → 221,8
list.add(tableElement_PrixVente_HT);
 
// TVA
final SQLTableElement tableElement_Taxe = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(tableElement_Taxe);
this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(this.tableElementTVA);
 
// Quantité Livrée
final SQLTableElement tableElement_QuantiteLivree = new SQLTableElement(e.getTable().getField("QTE_LIVREE"), Integer.class);
217,44 → 258,77
ToolTipManager.sharedInstance().unregisterComponent(this.table);
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
 
List<String> completionField = new ArrayList<String>();
SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
 
completionField.add("CODE_DOUANIER");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("ID_PAYS");
}
completionField.add("ID_UNITE_VENTE");
completionField.add("PA_HT");
completionField.add("PV_HT");
completionField.add("ID_TAXE");
completionField.add("POIDS");
completionField.add("PRIX_METRIQUE_HA_1");
completionField.add("PRIX_METRIQUE_HA_2");
completionField.add("PRIX_METRIQUE_HA_3");
completionField.add("VALEUR_METRIQUE_1");
completionField.add("VALEUR_METRIQUE_2");
completionField.add("VALEUR_METRIQUE_3");
completionField.add("ID_MODE_VENTE_ARTICLE");
completionField.add("PRIX_METRIQUE_VT_1");
completionField.add("PRIX_METRIQUE_VT_2");
completionField.add("PRIX_METRIQUE_VT_3");
completionField.add("SERVICE");
if (getSQLElement().getTable().getFieldsName().contains("DESCRIPTIF")) {
completionField.add("DESCRIPTIF");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("ID_DEVISE");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("PV_U_DEVISE");
}
if (getSQLElement().getTable().getFieldsName().contains("QTE_ACHAT") && sqlTableArticle.getTable().getFieldsName().contains("QTE_ACHAT")) {
completionField.add("QTE_ACHAT");
}
 
// Autocompletion
final AutoCompletionManager m = new AutoCompletionManager(tableElementCode, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.CODE"), this.table,
this.table.getRowValuesTableModel());
m.fill("NOM", "NOM");
m.fill("PA_HT", "PA_HT");
m.fill("PV_HT", "PV_HT");
m.fill("ID_MODE_VENTE_ARTICLE", "ID_MODE_VENTE_ARTICLE");
m.fill("POIDS", "POIDS");
m.fill("PRIX_METRIQUE_HA_1", "PRIX_METRIQUE_HA_1");
m.fill("PRIX_METRIQUE_HA_2", "PRIX_METRIQUE_HA_2");
m.fill("PRIX_METRIQUE_HA_3", "PRIX_METRIQUE_HA_3");
m.fill("VALEUR_METRIQUE_1", "VALEUR_METRIQUE_1");
m.fill("VALEUR_METRIQUE_2", "VALEUR_METRIQUE_2");
m.fill("VALEUR_METRIQUE_3", "VALEUR_METRIQUE_3");
m.fill("PRIX_METRIQUE_VT_1", "PRIX_METRIQUE_VT_1");
m.fill("PRIX_METRIQUE_VT_2", "PRIX_METRIQUE_VT_2");
m.fill("PRIX_METRIQUE_VT_3", "PRIX_METRIQUE_VT_3");
m.fill("SERVICE", "SERVICE");
m.fill("ID", "ID_ARTICLE");
for (String string : completionField) {
m.fill(string, string);
}
m.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
 
final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNom, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
this.table.getRowValuesTableModel());
m2.fill("CODE", "CODE");
m2.fill("PA_HT", "PA_HT");
m2.fill("PV_HT", "PV_HT");
m2.fill("POIDS", "POIDS");
m2.fill("ID_MODE_VENTE_ARTICLE", "ID_MODE_VENTE_ARTICLE");
m2.fill("PRIX_METRIQUE_HA_1", "PRIX_METRIQUE_HA_1");
m2.fill("PRIX_METRIQUE_HA_2", "PRIX_METRIQUE_HA_2");
m2.fill("PRIX_METRIQUE_HA_3", "PRIX_METRIQUE_HA_3");
m2.fill("VALEUR_METRIQUE_1", "VALEUR_METRIQUE_1");
m2.fill("VALEUR_METRIQUE_2", "VALEUR_METRIQUE_2");
m2.fill("VALEUR_METRIQUE_3", "VALEUR_METRIQUE_3");
m2.fill("PRIX_METRIQUE_VT_1", "PRIX_METRIQUE_VT_1");
m2.fill("PRIX_METRIQUE_VT_2", "PRIX_METRIQUE_VT_2");
m2.fill("PRIX_METRIQUE_VT_3", "PRIX_METRIQUE_VT_3");
m2.fill("SERVICE", "SERVICE");
m2.fill("ID", "ID_ARTICLE");
for (String string : completionField) {
m2.fill(string, string);
}
 
m2.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
 
final AutoCompletionManager m3 = new AutoCompletionManager(tableElementArticle, sqlTableArticle.getField("NOM"), this.table, this.table.getRowValuesTableModel(),
ITextWithCompletion.MODE_CONTAINS, true, true);
m3.fill("CODE", "CODE");
m3.fill("NOM", "NOM");
for (String string : completionField) {
m3.fill(string, string);
}
 
m3.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
 
// Calcul automatique du total HT
tableElement_Quantite.addModificationListener(totalHT);
this.qte.addModificationListener(totalHT);
qteU.addModificationListener(totalHT);
tableElement_PrixVente_HT.addModificationListener(totalHT);
this.totalHT.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row) {
262,25 → 336,27
int qte = Integer.parseInt(row.getObject("QTE").toString());
Number f = (Number) row.getObject("PV_HT");
System.out.println("Qte:" + qte + " et PV_HT:" + f);
long r = f.longValue() * qte;
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
return new Long(r);
}
 
});
// Calcul automatique du total TTC
tableElement_Quantite.addModificationListener(tableElementTotalTTC);
this.qte.addModificationListener(tableElementTotalTTC);
qteU.addModificationListener(tableElementTotalTTC);
tableElement_PrixVente_HT.addModificationListener(tableElementTotalTTC);
tableElement_Taxe.addModificationListener(tableElementTotalTTC);
this.tableElementTVA.addModificationListener(tableElementTotalTTC);
this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
int qte = Integer.parseInt(row.getObject("QTE").toString());
Number f = (Number) row.getObject("PV_HT");
 
Number f = (Number) row.getObject("T_PV_HT");
int idTaux = Integer.parseInt(row.getObject("ID_TAXE").toString());
 
Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
 
PrixHT pHT = new PrixHT(f.longValue() * qte);
PrixHT pHT = new PrixHT(f.longValue());
float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
Long r = new Long(pHT.calculLongTTC(taux / 100f));
return r;
299,12 → 375,16
});
// Calcul automatique du poids total
tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
tableElement_Quantite.addModificationListener(this.tableElementPoidsTotal);
this.qte.addModificationListener(this.tableElementPoidsTotal);
qteU.addModificationListener(this.tableElementPoidsTotal);
this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row) {
Number f = (Number) row.getObject("POIDS");
int qte = Integer.parseInt(row.getObject("QTE").toString());
return new Float(f.floatValue() * qte);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
// FIXME convertir en float autrement pour éviter une valeur non valeur transposable
// avec floatValue ou passer POIDS en bigDecimal
return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
}
 
});
321,7 → 401,10
int qte = (qteOb == null) ? 0 : Integer.parseInt(qteOb.toString());
 
float fValue = (f == null) ? 0.0F : f.floatValue();
return new Float(fValue * qte);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
// FIXME convertir en float autrement pour éviter une valeur non transposable
// avec floatValue ou passer POIDS en bigDecimal
return b.multiply(new BigDecimal(fValue * qte)).floatValue();
}
});
 
346,6 → 429,19
 
this.table.readState();
 
tableElementCode.addModificationListener(tableElementArticle);
tableElementArticle.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
return foreign.getID();
} else {
return tableArticle.getUndefinedID();
}
}
});
 
// Mode Gestion article avancé
String valModeAvanceVt = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
Boolean bModeAvance = Boolean.valueOf(valModeAvanceVt);
356,6 → 452,16
hideColumn(model.getColumnForField("PV_HT"));
hideColumn(model.getColumnForField("ID_MODE_VENTE_ARTICLE"));
}
 
setColumnVisible(this.model.getColumnForField("ID_ARTICLE"), selectArticle);
setColumnVisible(this.model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
setColumnVisible(this.model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
 
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
setColumnVisible(this.model.getColumnForField("QTE_UNITAIRE"), gestionUV);
setColumnVisible(this.model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
 
// On réécrit la configuration au cas ou les preferences aurait changé
this.table.writeState();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/element/AvoirClientSQLElement.java
38,6 → 38,7
public List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("NUMERO");
l.add("ID_COMMERCIAL");
l.add("ID_CLIENT");
 
l.add("NOM");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/action/ListeDesAvoirsClientsAction.java
41,12 → 41,14
 
public JFrame createFrame() {
final SQLElement element = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
final IListFrame frame = new IListFrame(new ListeGestCommEltPanel(element));
ListeGestCommEltPanel panel = new ListeGestCommEltPanel(element);
panel.setAddVisible(true);
final IListFrame frame = new IListFrame(panel);
 
List<SQLField> fields = new ArrayList<SQLField>(2);
fields.add(element.getTable().getField("MONTANT_HT"));
fields.add(element.getTable().getField("MONTANT_TTC"));
IListTotalPanel totalPanel = new IListTotalPanel(frame.getPanel().getListe(), fields, null, "Total Global");
IListTotalPanel totalPanel = new IListTotalPanel(frame.getPanel().getListe(), fields, "Total Global");
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/component/AvoirClientSQLComponent.java
27,8 → 27,8
import org.openconcerto.erp.core.sales.credit.element.AvoirClientSQLElement;
import org.openconcerto.erp.core.sales.credit.ui.AvoirItemTable;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
import org.openconcerto.erp.generationEcritures.GenerationMvtAvoirClient;
import org.openconcerto.erp.model.ISQLCompteSelector;
36,7 → 36,6
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.ElementSQLObject;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
61,7 → 60,6
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
 
379,7 → 377,7
c.weightx = 0;
c.weighty = 0;
c.gridwidth = 1;
this.add(new JLabel("Tarif à appliquer"), c);
this.add(new JLabel("Tarif à appliquer", SwingConstants.RIGHT), c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
 
547,9 → 545,7
JTextField poids = new JTextField();
if (getTable().getFieldsName().contains("T_POIDS"))
addSQLObject(poids, "T_POIDS");
final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
this.table.getQteElement(), fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, this.table.getPrixServiceElement(), fieldDevise,
this.table.getTableElementTotalDevise(), poids, this.table.getPoidsTotalElement());
final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, poids, null);
totalTTC.setOpaque(false);
c.gridx++;
c.gridy = 0;
650,9 → 646,10
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(AvoirClientSQLElement.class, row.getDate("DATE").getTime()).equalsIgnoreCase(this.textNumero.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(tableNum);
int val = tableNum.getRow(2).getInt("AVOIR_START");
String label = NumerotationAutoSQLElement.getLabelNumberFor(AvoirClientSQLElement.class);
int val = tableNum.getRow(2).getInt(label);
val++;
rowVals.put("AVOIR_START", Integer.valueOf(val));
rowVals.put(label, Integer.valueOf(val));
 
try {
rowVals.update(2);
812,61 → 809,25
 
}
 
protected String getLibelleStock(SQLRow row, SQLRow rowElt) {
return "Avoir client N°" + row.getString("NUMERO");
}
 
/**
* Mise à jour des stocks pour chaque article composant la facture d'avoir
*/
private void updateStock(int id) {
 
SQLElement eltArticleAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT_ELEMENT");
SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
SQLRow rowAvoir = getTable().getRow(id);
 
// On récupére les articles qui composent la facture
SQLSelect selEltAvoir = new SQLSelect(eltArticleAvoir.getTable().getBase());
selEltAvoir.addSelect(eltArticleAvoir.getTable().getField("ID"));
selEltAvoir.setWhere(new Where(eltArticleAvoir.getTable().getField("ID_AVOIR_CLIENT"), "=", id));
 
List lEltAvoir = (List) eltArticleAvoir.getTable().getBase().getDataSource().execute(selEltAvoir.asString(), new ArrayListHandler());
 
if (lEltAvoir != null) {
for (int i = 0; i < lEltAvoir.size(); i++) {
 
// Elt qui compose facture
Object[] tmp = (Object[]) lEltAvoir.get(i);
int idEltFact = ((Number) tmp[0]).intValue();
SQLRow rowEltAvoir = eltArticleAvoir.getTable().getRow(idEltFact);
 
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (SQLField field : eltArticle.getTable().getFields()) {
if (rowEltAvoir.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), rowEltAvoir.getObject(field.getName()));
MouvementStockSQLElement mvtStock = (MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
mvtStock.createMouvement(getTable().getRow(id), getTable().getTable("AVOIR_CLIENT_ELEMENT"), new StockLabel() {
@Override
public String getLabel(SQLRow rowOrigin, SQLRow rowElt) {
return getLibelleStock(rowOrigin, rowElt);
}
}
// rowArticle.loadAllSafe(rowEltFact);
int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
}, true);
 
// on crée un mouvement de stock pour chacun des articles
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
rowVals.put("QTE", rowEltAvoir.getInt("QTE"));
rowVals.put("NOM", "Avoir client N°" + rowAvoir.getString("NUMERO"));
rowVals.put("IDSOURCE", id);
rowVals.put("SOURCE", getTable().getName());
rowVals.put("ID_ARTICLE", idArticle);
rowVals.put("DATE", rowAvoir.getObject("DATE"));
try {
SQLRow row = rowVals.insert();
MouvementStockSQLElement.updateStock(Arrays.asList(row.getID()));
} catch (SQLException e) {
e.printStackTrace();
}
 
}
}
}
 
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.boxAdeduire) {
if (this.eltModeRegl != null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/component/CommandeClientSQLComponent.java
117,6 → 117,7
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
 
 
this.setAdditionalFieldsPanel(new FormLayouter(addP, 2));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
304,7 → 305,9
DeviseField fieldTTC = new DeviseField();
DeviseField fieldDevise = new DeviseField();
DeviseField fieldService = new DeviseField();
DeviseField fieldHA = new DeviseField();
fieldHT.setOpaque(false);
fieldHA.setOpaque(false);
fieldTVA.setOpaque(false);
fieldTTC.setOpaque(false);
fieldService.setOpaque(false);
313,11 → 316,15
addRequiredSQLObject(fieldTVA, "T_TVA");
addRequiredSQLObject(fieldTTC, "T_TTC");
addRequiredSQLObject(fieldService, "T_SERVICE");
if (getTable().contains("PREBILAN")) {
addSQLObject(fieldHA, "PREBILAN");
} else if (getTable().contains("T_HA")) {
addSQLObject(fieldHA, "T_HA");
}
 
JTextField poids = new JTextField();
// addSQLObject(poids, "T_POIDS");
final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
this.table.getQteElement(), fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, this.table.getPrixServiceElement(), fieldDevise,
this.table.getTableElementTotalDevise(), poids, this.table.getPoidsTotalElement());
final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, fieldHA, fieldDevise, poids, null);
 
c.gridx = GridBagConstraints.RELATIVE;
c.gridy--;
331,7 → 338,7
 
this.panelOO = new PanelOOSQLComponent(this);
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.gridx = 0;
c.gridy += 3;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeSaisieVenteFactureAction.java
85,10 → 85,16
private SQLElement eltEcheance = Configuration.getInstance().getDirectory().getElement("ECHEANCE_CLIENT");
private SQLElement eltMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT");
private boolean affact = UserManager.getInstance().getCurrentUser().getRights().haveRight(NXRights.ACCES_RETOUR_AFFACTURAGE.getCode());
private boolean filterOnCurrentYear = false;
 
public ListeSaisieVenteFactureAction() {
this(false);
}
 
public ListeSaisieVenteFactureAction(boolean filterOnCurrentYear) {
super();
this.putValue(Action.NAME, "Liste des factures");
this.filterOnCurrentYear = filterOnCurrentYear;
}
 
public JFrame createFrame() {
139,7 → 145,7
return c;
}
};
 
this.listeAddPanel.setAddVisible(true);
this.listeAddPanel.getListe().getModel().setEditable(true);
GridBagConstraints c = new DefaultGridBagConstraints();
// Total panel
161,7 → 167,7
 
fields.add(eltFacture.getTable().getField("T_HT"));
fields.add(eltFacture.getTable().getField("T_TTC"));
IListTotalPanel totalPanel = new IListTotalPanel(this.listeAddPanel.getListe(), fields, null, "Total Global");
IListTotalPanel totalPanel = new IListTotalPanel(this.listeAddPanel.getListe(), IListTotalPanel.initListe(this.listeAddPanel.getListe(), fields), null, "Total Global");
 
panelTotal.add(totalPanel);
 
172,6 → 178,9
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
this.listeAddPanel.add(datePanel, c);
if (this.filterOnCurrentYear) {
datePanel.setFilterOnDefault();
}
 
this.frame = new IListFrame(this.listeAddPanel);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/ListeDesVentesPanel.java
72,7 → 72,7
 
private ListeGestCommEltPanel listeFact;
private JButton buttonEnvoye, buttonRegle, buttonDupliquer;
private static SQLElement eltClient = Configuration.getInstance().getDirectory().getElement("CLIENT");
private static SQLElement eltClient = Configuration.getInstance().getDirectory().getElement(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT"));
JLabelBold textField = new JLabelBold("0");
JLabelBold textField2 = new JLabelBold("0");
 
112,6 → 112,7
final SQLTableModelColumn dateEnvoiCol = src.getColumn(eltFacture.getTable().getField("DATE_ENVOI"));
((SQLTableModelColumnPath) dateEnvoiCol).setEditable(true);
final SQLTableModelColumn dateReglCol = src.getColumn(eltFacture.getTable().getField("DATE_REGLEMENT"));
if (dateReglCol != null)
((SQLTableModelColumnPath) dateReglCol).setEditable(true);
 
// Edition des dates d'envois
124,6 → 125,7
});
 
// Edition des dates de reglement
if (dateReglCol != null) {
dateReglCol.setColumnInstaller(new IClosure<TableColumn>() {
@Override
public void executeChecked(TableColumn columnDateReglement) {
131,6 → 133,7
columnDateReglement.setCellRenderer(new DateEnvoiRenderer());
}
});
}
 
this.listeFact = new ListeGestCommEltPanel(eltFacture, new IListe(src), true);
this.listeFact.setOpaque(false);
172,7 → 175,7
List<SQLField> l = new ArrayList<SQLField>();
l.add(eltFacture.getTable().getField("T_HT"));
l.add(eltFacture.getTable().getField("T_TTC"));
final IListTotalPanel total = new IListTotalPanel(this.listeFact.getListe(), l, null, null);
final IListTotalPanel total = new IListTotalPanel(this.listeFact.getListe(), l);
cFacture.weighty = 0;
cFacture.fill = GridBagConstraints.NONE;
cFacture.gridy++;
261,7 → 264,7
final List<SQLField> l2 = new ArrayList<SQLField>();
l2.add(panelTicket.getElement().getTable().getField("TOTAL_HT"));
l2.add(panelTicket.getElement().getTable().getField("TOTAL_TTC"));
final IListTotalPanel total2 = new IListTotalPanel(panelTicket.getListe(), l2, null, null);
final IListTotalPanel total2 = new IListTotalPanel(panelTicket.getListe(), l2);
cc.weighty = 0;
cc.fill = GridBagConstraints.NONE;
cc.gridy++;
302,7 → 305,7
final List<SQLField> l2 = new ArrayList<SQLField>();
l2.add(listeVC.getElement().getTable().getField("MONTANT_HT"));
l2.add(listeVC.getElement().getTable().getField("MONTANT_TTC"));
final IListTotalPanel total2 = new IListTotalPanel(listeVC.getListe(), l2, null, null);
final IListTotalPanel total2 = new IListTotalPanel(listeVC.getListe(), l2);
cc.weighty = 0;
cc.fill = GridBagConstraints.NONE;
cc.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/component/SaisieVenteFactureSQLComponent.java
26,13 → 26,14
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.erp.model.BanqueModifiedListener;
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.erp.panel.PanelOOSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.ElementSQLObject;
39,7 → 40,6
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
48,6 → 48,8
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.UndefinedRowValuesCache;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.ISQLElementWithCodeSelector;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
61,7 → 63,6
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.text.SimpleDocumentListener;
84,6 → 85,7
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
224,10 → 226,8
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
final JDate dateSaisie = new JDate(true);
 
this.add(dateSaisie, c);
 
 
// Ligne 2 : reference
c.gridx = 0;
c.gridwidth = 1;
275,12 → 275,49
 
this.add(this.comboClient, c);
 
if (getTable().contains("ID_ECHEANCIER_CCI")) {
// Echeancier
c.gridx++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel(getLabelFor("ID_ECHEANCIER_CCI"), SwingConstants.RIGHT), c);
 
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
final ElementComboBox echeancier = new ElementComboBox();
final SQLElement contactElement = Configuration.getInstance().getDirectory().getElement("ECHEANCIER_CCI");
echeancier.init(contactElement, new ComboSQLRequest(contactElement.getComboRequest()));
DefaultGridBagConstraints.lockMinimumSize(echeancier);
this.addView(echeancier, "ID_ECHEANCIER_CCI");
 
selAffaire.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent arg0) {
// TODO Raccord de méthode auto-généré
if (selAffaire.getSelectedRow() != null) {
echeancier.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_AFFAIRE"), "=", selAffaire.getSelectedRow().getID()));
 
if (!isFilling()) {
SQLRow rowPole = selAffaire.getSelectedRow().getForeignRow("ID_POLE_PRODUIT");
comboCommercial.setValue(rowPole);
}
} else {
echeancier.getRequest().setWhere(null);
}
}
});
this.add(echeancier, c);
 
}
 
this.comboClient.addValueListener(this.changeClientListener);
 
this.comboAdresse = new ElementComboBox();
this.comboAdresse.setAddIconVisible(false);
this.comboAdresse.setListIconVisible(false);
JLabel labelAdresse = new JLabel(getLabelFor("ID_ADRESSE"));
JLabel labelAdresse = new JLabel(getLabelFor("ID_ADRESSE"), SwingConstants.RIGHT);
c.gridy++;
c.gridx = 0;
c.gridwidth = 1;
293,6 → 330,14
c.weightx = 1;
this.add(this.comboAdresse, c);
 
// Acompte
this.checkAcompte = new JCheckBox(getLabelFor("ACOMPTE"));
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
// this.add(this.checkAcompte, c);
c.gridwidth = 1;
this.addView(this.checkAcompte, "ACOMPTE");
 
Boolean bCompteCli = Boolean.valueOf(DefaultNXProps.getInstance().getStringProperty("HideCompteFacture"));
if (!bCompteCli) {
// Ligne 5: Compte Client
345,10 → 390,6
setCompteServiceVisible(!(bServ != null && !bServ.booleanValue()));
 
 
// Acompte
this.checkAcompte = new JCheckBox(getLabelFor("ACOMPTE"));
this.addView(this.checkAcompte, "ACOMPTE");
 
final JPanel pAcompte = new JPanel();
final DeviseField textAcompteHT = new DeviseField();
pAcompte.add(new JLabel("Acompte HT"));
381,7 → 422,7
c.weightx = 0;
c.weighty = 0;
c.gridwidth = 1;
this.add(new JLabel("Tarif à appliquer"), c);
this.add(new JLabel("Tarif à appliquer", SwingConstants.RIGHT), c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
 
401,14 → 442,14
c.weightx = 1;
c.weighty = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
 
c.fill = GridBagConstraints.BOTH;
ITextArea infos = new ITextArea(4, 4);
this.add(this.tableFacture, c);
 
// FIXME
this.addView(this.tableFacture.getRowValuesTable(), "");
 
 
/*******************************************************************************************
* * MODE DE REGLEMENT
******************************************************************************************/
484,9 → 525,7
addRequiredSQLObject(fieldService, "T_SERVICE");
JTextField poids = new JTextField();
addSQLObject(poids, "T_POIDS");
totalTTC = new TotalPanel(this.tableFacture.getRowValuesTable(), this.tableFacture.getPrixTotalHTElement(), this.tableFacture.getPrixTotalTTCElement(), this.tableFacture.getHaElement(),
this.tableFacture.getQteElement(), fieldHT, fieldTVA, this.fieldTTC, this.textPortHT, this.textRemiseHT, fieldService, this.tableFacture.getPrixServiceElement(), null, fieldTHA,
fieldDevise, this.tableFacture.getTableElementTotalDevise(), poids, this.tableFacture.getPoidsTotalElement());
totalTTC = new TotalPanel(this.tableFacture, fieldHT, fieldTVA, this.fieldTTC, this.textPortHT, this.textRemiseHT, fieldService, fieldTHA, fieldDevise, poids, null);
DefaultGridBagConstraints.lockMinimumSize(totalTTC);
cBottom.gridx++;
cBottom.weightx = 1;
519,7 → 558,6
c.fill = GridBagConstraints.BOTH;
this.add(new TitledSeparator(getLabelFor("INFOS")), c);
 
ITextArea infos = new ITextArea(4, 4);
c.gridy++;
 
final JScrollPane comp = new JScrollPane(infos);
842,6 → 880,7
if (compteSel != null) {
this.compteSel.rmValueListener(this.changeCompteListener);
}
if (this.comboClient != null)
this.comboClient.rmValueListener(this.listenerModeReglDefaut);
this.rowSelected = r;
if (r != null) {
860,8 → 899,10
setAcompte(false);
}
}
if (this.comboClient != null) {
this.comboClient.addValueListener(this.listenerModeReglDefaut);
this.comboClient.addValueListener(this.changeClientListener);
}
if (this.compteSel != null) {
this.compteSel.addValueListener(this.changeCompteListener);
} // nomClient.addValueListener(changeClientListener);
899,9 → 940,11
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, rowFacture.getDate("DATE").getTime()).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(this.tableNum);
int val = this.tableNum.getRow(2).getInt("FACT_START");
 
String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(SaisieVenteFactureSQLElement.class);
int val = this.tableNum.getRow(2).getInt(labelNumberFor);
val++;
rowVals.put("FACT_START", Integer.valueOf(val));
rowVals.put(labelNumberFor, Integer.valueOf(val));
 
try {
rowVals.update(2);
912,7 → 955,8
} else {
if (JOptionPane.showConfirmDialog(this, "Attention en modifiant cette facture, vous supprimerez les chéques et les échéances associés. Continuer?", "Modification de facture",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
// On efface les anciens mouvements de stocks
SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
sel.addSelect(eltMvtStock.getTable().getField("ID"));
931,7 → 975,7
}
}
}
 
}
// On recupere l'ancien total HT
rowFactureOld = this.getTable().getRow(getSelectedID());
lFactureOld = ((Number) rowFactureOld.getObject("T_HT")).longValue();
983,6 → 1027,7
System.err.println("Fin regeneration");
 
// Mise à jour des stocks
 
updateStock(idSaisieVF);
 
// On retire l'avoir
1381,70 → 1426,27
this.refClient.setText(text);
}
 
protected String getLibelleStock(SQLRow row, SQLRow rowElt) {
return "Saisie vente facture N°" + row.getString("NUMERO");
}
 
/**
* Mise à jour des stocks pour chaque article composant la facture
*/
private void updateStock(int id) {
 
SQLElement eltArticleFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
SQLRow rowFacture = getTable().getRow(id);
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
 
// FIXME Si la facture vient d'un bon de livraison le stock a deja été mis à jour
// if (rowFacture.getString("SOURCE").equalsIgnoreCase("BON_DE_LIVRAISON")) {
// return;
// }
MouvementStockSQLElement mvtStock = (MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
mvtStock.createMouvement(getTable().getRow(id), getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"), new StockLabel() {
 
// On récupére les articles qui composent la facture
SQLSelect selEltfact = new SQLSelect(eltArticleFact.getTable().getBase());
selEltfact.addSelect(eltArticleFact.getTable().getField("ID"));
selEltfact.setWhere(new Where(eltArticleFact.getTable().getField("ID_SAISIE_VENTE_FACTURE"), "=", id));
 
List lEltFact = (List) eltArticleFact.getTable().getBase().getDataSource().execute(selEltfact.asString(), new ArrayListHandler());
 
if (lEltFact != null) {
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < lEltFact.size(); i++) {
 
// Elt qui compose facture
Object[] tmp = (Object[]) lEltFact.get(i);
int idEltFact = ((Number) tmp[0]).intValue();
SQLRow rowEltFact = eltArticleFact.getTable().getRow(idEltFact);
 
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (SQLField field : eltArticle.getTable().getFields()) {
if (rowEltFact.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), rowEltFact.getObject(field.getName()));
@Override
public String getLabel(SQLRow rowOrigin, SQLRow rowElt) {
return getLibelleStock(rowOrigin, rowElt);
}
}
// rowArticle.loadAllSafe(rowEltFact);
int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
}, false);
 
// on crée un mouvement de stock pour chacun des articles
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
rowVals.put("QTE", -(rowEltFact.getInt("QTE")));
rowVals.put("NOM", "Saisie vente facture N°" + rowFacture.getString("NUMERO"));
rowVals.put("IDSOURCE", id);
rowVals.put("SOURCE", getTable().getName());
rowVals.put("ID_ARTICLE", idArticle);
rowVals.put("DATE", rowFacture.getObject("DATE"));
try {
SQLRow row = rowVals.insert();
l.add(row.getID());
} catch (SQLException e) {
e.printStackTrace();
}
// }
}
CollectionMap<SQLRow, List<SQLRowValues>> map = MouvementStockSQLElement.updateStock(l);
if (map.keySet().size() > 0) {
if (JOptionPane.showConfirmDialog(null, "Certains articles sont en dessous du stock minimum.\n Voulez créer une commande?") == JOptionPane.YES_OPTION) {
MouvementStockSQLElement.createCommandeF(map, rowFacture.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"));
}
}
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureSQLElement.java
21,6 → 21,7
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
31,6 → 32,7
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.utils.CollectionMap;
158,6 → 160,8
 
super.archive(row, cutLinks);
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
 
// Mise à jour des stocks
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
175,6 → 179,7
}
}
}
}
 
public void transfertBL(int idFacture) {
final SQLElement elt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/ui/ListeDesDevisPanel.java
13,6 → 13,8
package org.openconcerto.erp.core.sales.quote.ui;
 
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.sales.invoice.ui.DateEnvoiRenderer;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.quote.component.DevisSQLComponent;
19,14 → 21,14
import org.openconcerto.erp.core.sales.quote.element.DevisItemSQLElement;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
33,6 → 35,7
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
40,6 → 43,7
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.Tuple2;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
46,9 → 50,12
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
62,8 → 69,9
private JTabbedPane tabbedPane = new JTabbedPane();
private Map<Integer, ListeAddPanel> map = new HashMap<Integer, ListeAddPanel>();
private SQLElement eltDevis = Configuration.getInstance().getDirectory().getElement("DEVIS");
private SQLElement eltEtatDevis = Configuration.getInstance().getDirectory().getElement("ETAT_DEVIS");
private JButton buttonShow, buttonGen, buttonPrint, buttonFacture, buttonCmd, buttonClone;
private EditFrame editFrame;
protected EditFrame editFrame;
 
public ListeDesDevisPanel() {
this.setLayout(new GridBagLayout());
70,21 → 78,34
final GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.NONE;
 
// Tous
ListeAddPanel panelAll = createPanel(-1);
this.map.put(this.tabbedPane.getTabCount(), panelAll);
this.tabbedPane.add("Tous", panelAll);
 
// Attente
ListeAddPanel panelCours = createPanel(EtatDevisSQLElement.EN_COURS);
this.map.put(this.tabbedPane.getTabCount(), panelCours);
 
this.tabbedPane.add(eltEtatDevis.getTable().getRow(EtatDevisSQLElement.EN_COURS).getString("NOM"), panelCours);
 
// Attente
ListeAddPanel panelAttente = createPanel(EtatDevisSQLElement.EN_ATTENTE);
this.map.put(this.tabbedPane.getTabCount(), panelAttente);
this.tabbedPane.add("En attente", panelAttente);
this.tabbedPane.add(eltEtatDevis.getTable().getRow(EtatDevisSQLElement.EN_ATTENTE).getString("NOM"), panelAttente);
 
// Accepte
ListeAddPanel panelAccepte = createPanel(EtatDevisSQLElement.ACCEPTE);
this.map.put(this.tabbedPane.getTabCount(), panelAccepte);
this.tabbedPane.add("Accepté", panelAccepte);
this.tabbedPane.add(eltEtatDevis.getTable().getRow(EtatDevisSQLElement.ACCEPTE).getString("NOM"), panelAccepte);
 
// Refuse
ListeAddPanel panelRefuse = createPanel(EtatDevisSQLElement.REFUSE);
this.map.put(this.tabbedPane.getTabCount(), panelRefuse);
this.tabbedPane.add("Refusé", panelRefuse);
this.tabbedPane.add(eltEtatDevis.getTable().getRow(EtatDevisSQLElement.REFUSE).getString("NOM"), panelRefuse);
 
this.tabbedPane.setSelectedIndex(1);
 
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
93,8 → 114,27
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(this.tabbedPane, c);
 
// Date panel
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(panelAttente.getListe(), eltDevis.getTable().getField("DATE"));
map.put(panelAccepte.getListe(), eltDevis.getTable().getField("DATE"));
map.put(panelRefuse.getListe(), eltDevis.getTable().getField("DATE"));
map.put(panelCours.getListe(), eltDevis.getTable().getField("DATE"));
map.put(panelAll.getListe(), eltDevis.getTable().getField("DATE"));
 
IListFilterDatePanel datePanel = new IListFilterDatePanel(map, IListFilterDatePanel.getDefaultMap());
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
c.weighty = 0;
datePanel.setFilterOnDefault();
this.add(datePanel, c);
 
}
 
protected void setRenderer(SQLTableModelSourceOnline source) {
 
}
 
private ListeAddPanel createPanel(int idFilter) {
// Filter
final SQLTableModelSourceOnline lAttente = this.eltDevis.getTableSource(true);
107,12 → 147,69
} else {
dateEnvoiCol = null;
}
if (idFilter > 1) {
Where wAttente = new Where(this.eltDevis.getTable().getField("ID_ETAT_DEVIS"), "=", idFilter);
lAttente.getReq().setWhere(wAttente);
} else {
lAttente.getColumns().add(new BaseSQLTableModelColumn("Etat", String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
// TODO Raccord de méthode auto-généré
return r.getForeign("ID_ETAT_DEVIS").getString("NOM");
}
 
@Override
public Set<FieldPath> getPaths() {
// TODO Raccord de méthode auto-généré
Set<FieldPath> s = new HashSet<FieldPath>();
s.add(eltDevis.getTable().getField("ID_ETAT_DEVIS").getFieldPath());
return s;
}
});
}
 
setRenderer(lAttente);
// 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);
 
IListTotalPanel total;
if (this.eltDevis.getTable().contains("PREBILAN")) {
// asList = Arrays.asList(this.eltDevis.getTable().getField("PREBILAN"),
// this.eltDevis.getTable().getField("T_HT"));
List<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>> fields = new ArrayList<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>>(2);
fields.add(Tuple2.create(pane.getListe().getSource().getColumn(this.eltDevis.getTable().getField("T_HT")), IListTotalPanel.Type.SOMME));
fields.add(Tuple2.create(pane.getListe().getSource().getColumn(this.eltDevis.getTable().getField("PREBILAN")), IListTotalPanel.Type.SOMME));
fields.add(Tuple2.create(new BaseSQLTableModelColumn("%MB", String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
// TODO Raccord de méthode auto-généré
return null;
}
 
@Override
public Set<FieldPath> getPaths() {
// TODO Raccord de méthode auto-généré
return null;
}
}, IListTotalPanel.Type.MOYENNE_MARGE));
total = new IListTotalPanel(pane.getListe(), fields, null, "Total Global");
} else if (this.eltDevis.getTable().contains("T_HA")) {
 
total = new IListTotalPanel(pane.getListe(), Arrays.asList(this.eltDevis.getTable().getField("T_HA"), this.eltDevis.getTable().getField("T_HT")));
} else {
total = new IListTotalPanel(pane.getListe(), Arrays.asList(this.eltDevis.getTable().getField("T_HT")));
}
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridy = 4;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
pane.add(total, c);
 
// Renderer
JTable table = pane.getListe().getJTable();
 
130,10 → 227,45
}
}
 
MouseSheetXmlListeListener mouseSheetXmlListeListener = new MouseSheetXmlListeListener(DevisXmlSheet.class) {
@Override
public List<RowAction> addToMenu() {
List<RowAction> list = new ArrayList<RowAction>();
// MouseSheetXmlListeListener mouseSheetXmlListeListener = new
// MouseSheetXmlListeListener(DevisXmlSheet.class) {
// @Override
// public List<RowAction> addToMenu() {
//
// // 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);
// }
// };
// mouseSheetXmlListeListener.setGenerateHeader(true);
// mouseSheetXmlListeListener.setShowHeader(true);
// pane.getListe().addIListeActions(mouseSheetXmlListeListener.getRowActions());
 
// activation des boutons
// pane.getListe().addIListener(new IListener() {
// public void selectionId(int id, int field) {
// checkButton(id);
// }
// });
addRowActions(pane.getListe(), idFilter);
 
pane.getListe().setOpaque(false);
 
pane.setOpaque(false);
return pane;
}
 
protected void addRowActions(IListe liste, int etat) {
// List<RowAction> list = new ArrayList<RowAction>();
// Transfert vers facture
RowAction factureAction = new RowAction(new AbstractAction("Transfert vers facture") {
public void actionPerformed(ActionEvent e) {
150,7 → 282,7
};
};
 
list.add(factureAction);
liste.addIListeAction(factureAction);
 
// Voir le document
RowAction actionTransfertCmd = new RowAction(new AbstractAction("Transférer en commande") {
167,7 → 299,7
return false;
};
};
list.add(actionTransfertCmd);
liste.addIListeAction(actionTransfertCmd);
 
// Transfert vers commande
RowAction commandeAction = new RowAction(new AbstractAction("Transfert vers commande client") {
185,8 → 317,34
};
};
 
list.add(commandeAction);
liste.addIListeAction(commandeAction);
 
RowAction accepteEtCmdAction = new RowAction(new AbstractAction("Marquer comme accepté et Transfert en commande client") {
public void actionPerformed(ActionEvent e) {
SQLRow selectedRow = IListe.get(e).getSelectedRow();
SQLRowValues rowVals = selectedRow.createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
selectedRow.getTable().fireTableModified(IListe.get(e).getSelectedId());
transfertCommandeClient(selectedRow);
}
}, 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;
};
};
liste.addIListeAction(accepteEtCmdAction);
 
// Marqué accepté
RowAction accepteAction = new RowAction(new AbstractAction("Marquer comme accepté") {
public void actionPerformed(ActionEvent e) {
211,13 → 369,13
};
};
 
list.add(accepteAction);
liste.addIListeAction(accepteAction);
 
RowAction accepteEtCmdAction = new RowAction(new AbstractAction("Marquer comme accepté et Transfert en commande client") {
// Marqué accepté
RowAction refuseAction = new RowAction(new AbstractAction("Marquer comme refusé") {
public void actionPerformed(ActionEvent e) {
SQLRow selectedRow = IListe.get(e).getSelectedRow();
SQLRowValues rowVals = selectedRow.createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
SQLRowValues rowVals = IListe.get(e).getSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.REFUSE);
try {
rowVals.update();
} catch (SQLException e1) {
224,8 → 382,7
// TODO Auto-generated catch block
e1.printStackTrace();
}
selectedRow.getTable().fireTableModified(IListe.get(e).getSelectedId());
transfertCommandeClient(selectedRow);
IListe.get(e).getSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
}, false) {
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowAccessor> selection) {
237,8 → 394,9
return false;
};
};
list.add(accepteEtCmdAction);
 
liste.addIListeAction(refuseAction);
 
// // Dupliquer
RowAction cloneAction = new RowAction(new AbstractAction("Créer à partir de") {
public void actionPerformed(ActionEvent e) {
258,39 → 416,9
};
};
 
list.add(cloneAction);
 
// 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;
liste.addIListeAction(cloneAction);
}
};
mouseSheetXmlListeListener.setGenerateHeader(true);
mouseSheetXmlListeListener.setShowHeader(true);
pane.getListe().addIListeActions(mouseSheetXmlListeListener.getRowActions());
 
// activation des boutons
// pane.getListe().addIListener(new IListener() {
// public void selectionId(int id, int field) {
// checkButton(id);
// }
// });
pane.getListe().setOpaque(false);
 
pane.setOpaque(false);
return pane;
}
 
/**
* Transfert en facture
*
342,4 → 470,8
}
MouvementStockSQLElement.createCommandeF(map, row.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"));
}
 
public Map<Integer, ListeAddPanel> getListePanel() {
return this.map;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/ui/DevisItemTable.java
13,6 → 13,9
package org.openconcerto.erp.core.sales.quote.ui;
 
import java.util.HashMap;
import java.util.Map;
 
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
30,4 → 33,10
return Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
 
}
 
public static Map<String, Boolean> map = new HashMap<String, Boolean>();
 
protected Map<String, Boolean> getCustomVisibilityMap() {
return map;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/component/DevisSQLComponent.java
89,6 → 89,10
super(elt);
}
 
public DevisItemTable getRowValuesTable() {
return this.table;
}
 
@Override
public void addViews() {
setLayout(new GridBagLayout());
140,7 → 144,7
this.radioEtat.setLayout(new VFlowLayout());
this.radioEtat.setBorder(BorderFactory.createTitledBorder(getLabelFor("ID_ETAT_DEVIS")));
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 3;
c.gridheight = 5;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
265,7 → 269,8
c.weightx = 0;
c.weighty = 0;
c.gridwidth = 1;
this.add(new JLabel("Tarif à appliquer"), c);
JLabel comp = new JLabel("Tarif à appliquer", SwingConstants.RIGHT);
this.add(comp, c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
 
286,7 → 291,7
this.table = new DevisItemTable();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy++;
c.gridy += 2;
c.weighty = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(this.table, c);
402,14 → 407,15
 
// FIXME Field add field T_HA dans installation avec recalcul des devis deja saisis
final DeviseField fieldHA = new DeviseField();
if (getTable().contains("T_HA")) {
 
if (getTable().contains("PREBILAN")) {
addSQLObject(fieldHA, "PREBILAN");
} else if (getTable().contains("T_HA")) {
 
addSQLObject(fieldHA, "T_HA");
}
 
final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
this.table.getQteElement(), this.fieldHT, fieldTVA, fieldTTC, textPortHT, this.textRemiseHT, fieldService, this.table.getPrixServiceElement(), null, fieldHA, fieldDevise,
this.table.getTableElementTotalDevise(), poids, this.table.getPoidsTotalElement());
final TotalPanel totalTTC = new TotalPanel(this.table, this.fieldHT, fieldTVA, fieldTTC, textPortHT, this.textRemiseHT, fieldService, fieldHA, fieldDevise, poids, null);
 
cBottom.gridy = 0;
cBottom.gridx += 2;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/EtatDevisSQLElement.java
28,6 → 28,7
public static final int REFUSE = 3;
public static final int ACCEPTE = 4;
public static final int EN_ATTENTE = 2;
public static final int EN_COURS = 5;
 
public EtatDevisSQLElement() {
super("ETAT_DEVIS", "un état de devis", "états de devis");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisSQLElement.java
19,6 → 19,8
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.core.sales.order.component.CommandeClientSQLComponent;
import org.openconcerto.erp.core.sales.quote.component.DevisSQLComponent;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
41,6 → 43,9
 
public DevisSQLElement() {
super(TABLENAME, "un devis", "devis");
 
MouseSheetXmlListeListener l = new MouseSheetXmlListeListener(DevisXmlSheet.class);
getRowActions().addAll(l.getRowActions());
}
 
protected List<String> getComboFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/NumerotationAutoSQLElement.java
23,6 → 23,7
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement;
import org.openconcerto.erp.core.supplychain.credit.element.AvoirFournisseurSQLElement;
import org.openconcerto.erp.core.supplychain.order.element.CommandeSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionSQLElement;
import org.openconcerto.sql.Configuration;
64,8 → 65,8
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
 
// FIXME bug JTextField for input bigInt
 
125,7 → 126,7
added.add(prefix);
SQLElement elt = Configuration.getInstance().getDirectory().getElement(class1);
// Avoir
JLabel labelAvoirFormat = new JLabel(StringUtils.firstUp(elt.getPluralName()) + " " + getLabelFor(prefix + FORMAT));
JLabel labelAvoirFormat = new JLabel(StringUtils.firstUp(elt.getPluralName()) + " " + getLabelFor(prefix + FORMAT), SwingConstants.RIGHT);
this.add(labelAvoirFormat, c);
c.gridx++;
c.weightx = 1;
465,6 → 466,7
map.put(AvoirClientSQLElement.class, "AVOIR");
map.put(SaisieVenteFactureSQLElement.class, "FACT");
map.put(AvoirClientSQLElement.class, "AVOIR");
map.put(AvoirFournisseurSQLElement.class, "AVOIR_F");
map.put(DevisSQLElement.class, "DEVIS");
map.put(BonDeLivraisonSQLElement.class, "BON_L");
map.put(BonReceptionSQLElement.class, "BON_R");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/DeviseField.java
60,7 → 60,6
 
private SQLField field;
private String sqlName;
private String label;
 
private List<String> items;
 
221,15 → 220,6
});
}
 
public String getDescription() {
return this.label;
}
 
@Override
public void setDescription(String s) {
this.label = s;
}
 
public final void resetValue() {
this.setValue("");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/DeviseCellEditor.java
48,6 → 48,7
public DeviseCellEditor() {
// Mimic JTable.GenericEditor behavior
this.textField.setBorder(new LineBorder(Color.black));
this.textField.setHorizontalAlignment(JTextField.RIGHT);
// On ne peut saisir qu'un chiffre à 2 décimales
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent keyEvent) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractArticleItemTable.java
15,6 → 15,8
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
22,6 → 24,7
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableControlPanel;
import org.openconcerto.sql.view.list.RowValuesTableModel;
44,10 → 47,12
public abstract class AbstractArticleItemTable extends JPanel {
protected RowValuesTable table;
protected SQLTableElement totalHT;
protected SQLTableElement tableElementTVA;
protected SQLTableElement tableElementTotalTTC;
protected SQLTableElement tableElementTotalDevise;
protected SQLTableElement service, qte, ha;
protected SQLTableElement tableElementPoidsTotal;
protected SQLTableElement prebilan;
protected RowValuesTableModel model;
protected SQLRowValues defaultRowVals;
private List<JButton> buttons = null;
80,12 → 85,13
protected void uiInit() {
// Ui init
setLayout(new GridBagLayout());
this.setOpaque(false);
final GridBagConstraints c = new DefaultGridBagConstraints();
 
c.weightx = 1;
 
control = new RowValuesTableControlPanel(this.table, this.buttons);
 
control.setOpaque(false);
this.add(control, c);
 
c.gridy++;
121,6 → 127,10
return this.table.getRowValuesTableModel();
}
 
public SQLTableElement getPrebilanElement() {
return this.prebilan;
}
 
public SQLTableElement getPrixTotalHTElement() {
return this.totalHT;
}
145,6 → 155,10
return this.ha;
}
 
public SQLTableElement getTVAElement() {
return this.tableElementTVA;
}
 
public SQLTableElement getTableElementTotalDevise() {
return this.tableElementTotalDevise;
}
184,6 → 198,10
 
final SQLTable tableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
 
final boolean modeAvance = DefaultNXProps.getInstance().getBooleanValue("ArticleModeVenteAvance", false);
SQLPreferences prefs = new SQLPreferences(tableArticle.getDBRoot());
final boolean createArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
// On récupére les articles qui composent la table
final List<SQLRow> listElts = eltSource.getTable().getRow(id).getReferentRows(eltArticleTable.getTable());
final SQLRowValues rowArticle = new SQLRowValues(tableArticle);
203,8 → 221,14
}
}
// crée les articles si il n'existe pas
ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
 
if (modeAvance)
ReferenceArticleSQLElement.getIdForCNM(rowArticle, createArticle);
else {
ReferenceArticleSQLElement.getIdForCN(rowArticle, createArticle);
}
// ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
}
// }
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractAchatArticleItemTable.java
16,8 → 16,10
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
25,6 → 27,8
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.CellDynamicModifier;
import org.openconcerto.sql.view.list.RowValuesTable;
31,6 → 35,8
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.SQLTableElement;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
38,6 → 44,7
import java.util.Vector;
 
import javax.swing.ToolTipManager;
import javax.swing.table.TableCellRenderer;
 
public abstract class AbstractAchatArticleItemTable extends AbstractArticleItemTable {
 
46,7 → 53,8
}
 
AutoCompletionManager m;
AutoCompletionManager m2;
AutoCompletionManager m2, m3;
private final SQLTable tableArticle = getSQLElement().getTable().getTable("ARTICLE");
 
/**
*
55,11 → 63,15
 
final SQLElement e = getSQLElement();
 
SQLPreferences prefs = new SQLPreferences(getSQLElement().getTable().getDBRoot());
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
// final SQLTableElement tableElementArticle = new SQLTableElement("ID_ARTICLE");
// list.add(tableElementArticle);
final SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true);
list.add(tableElementArticle);
 
if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
113,6 → 125,28
this.ha.setRenderer(new DeviseNiceTableCellRenderer());
list.add(this.ha);
 
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
@Override
public boolean isCellEditable(SQLRowValues vals) {
 
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
return false;
} else {
return super.isCellEditable(vals);
}
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
}
};
list.add(qteU);
 
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
// Quantité
final SQLTableElement qteElement = new SQLTableElement(e.getTable().getField("QTE"), Integer.class) {
protected Object getDefaultNullValue() {
121,8 → 155,8
};
list.add(qteElement);
// TVA
final SQLTableElement tableElement_Taxe = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(tableElement_Taxe);
this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(this.tableElementTVA);
// Poids piece
SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class);
list.add(tableElementPoids);
162,7 → 196,7
 
// Autocompletion
List<String> completionFields = new ArrayList<String>();
 
completionFields.add("ID_UNITE_VENTE");
completionFields.add("PA_HT");
completionFields.add("PV_HT");
completionFields.add("POIDS");
200,7 → 234,7
}
};
m.fill("NOM", "NOM");
// m.fill("ID", "ID_ARTICLE");
m.fill("ID", "ID_ARTICLE");
for (String string : completionFields) {
m.fill(string, string);
}
217,34 → 251,32
}
};
m2.fill("CODE", "CODE");
// m2.fill("ID", "ID_ARTICLE");
m2.fill("ID", "ID_ARTICLE");
for (String string : completionFields) {
m2.fill(string, string);
}
 
// final AutoCompletionManager m3 = new AutoCompletionManager(tableElementArticle,
// ((ComptaPropsConfiguration)
// Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"),
// this.table, this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true,
// true) {
// @Override
// protected Object getValueFrom(SQLRow row, String field) {
// Object res = tarifCompletion(row, field);
// if (res == null) {
// return super.getValueFrom(row, field);
// } else {
// return res;
// }
// }
// };
// m3.fill("CODE", "CODE");
// m3.fill("NOM", "NOM");
// for (String string : completionFields) {
// m3.fill(string, string);
// }
this.m3 = new AutoCompletionManager(tableElementArticle, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true) {
@Override
protected Object getValueFrom(SQLRow row, String field) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field);
} else {
return res;
}
}
};
m3.fill("CODE", "CODE");
m3.fill("NOM", "NOM");
for (String string : completionFields) {
m3.fill(string, string);
}
 
// Calcul automatique du total HT
qteElement.addModificationListener(this.totalHT);
qteU.addModificationListener(this.totalHT);
this.ha.addModificationListener(this.totalHT);
this.totalHT.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row) {
255,7 → 287,8
Number f = (Number) row.getObject("PA_HT");
System.err.println("Qte:" + qte + " et PA_HT:" + f);
// long longValue = (f == null) ? 0 : f.longValue();
long r = f.longValue() * qte;
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
return new Long(r);
}
 
262,6 → 295,7
});
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
qteElement.addModificationListener(this.tableElementTotalDevise);
qteU.addModificationListener(this.tableElementTotalDevise);
tableElement_PA_Devise.addModificationListener(this.tableElementTotalDevise);
this.tableElementTotalDevise.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row) {
271,8 → 305,9
int qte = Integer.parseInt(row.getObject("QTE").toString());
Number f = (Number) row.getObject("PA_DEVISE");
// long longValue = (f == null) ? 0 : f.longValue();
long r = f.longValue() * qte;
return new Long(r);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
return r;
}
 
});
279,8 → 314,9
}
// Calcul automatique du total TTC
qteElement.addModificationListener(this.tableElementTotalTTC);
qteU.addModificationListener(this.tableElementTotalTTC);
this.ha.addModificationListener(this.tableElementTotalTTC);
tableElement_Taxe.addModificationListener(this.tableElementTotalTTC);
this.tableElementTVA.addModificationListener(this.tableElementTotalTTC);
this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
294,12 → 330,14
}
Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
 
PrixHT pHT = new PrixHT(f.longValue() * qte);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
PrixHT pHT = new PrixHT(r);
// System.err.println("Calcul du total TTC : taux " + resultTaux + " : HT " + pHT);
float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
// float taux = resultTaux.floatValue();
Long r = new Long(pHT.calculLongTTC(taux / 100f));
return r;
Long total = new Long(pHT.calculLongTTC(taux / 100f));
return total;
}
 
});
306,6 → 344,19
 
this.table.readState();
 
tableElementCode.addModificationListener(tableElementArticle);
tableElementArticle.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
return foreign.getID();
} else {
return tableArticle.getUndefinedID();
}
}
});
 
// Mode Gestion article avancé
String valModeAvanceVt = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
Boolean bModeAvance = Boolean.valueOf(valModeAvanceVt);
317,6 → 368,17
setColumnVisible(this.model.getColumnForField("ID_MODE_VENTE_ARTICLE"), view);
setColumnVisible(this.model.getColumnForField("PA_HT"), view);
 
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
setColumnVisible(this.model.getColumnForField("QTE_UNITAIRE"), gestionUV);
setColumnVisible(this.model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
 
setColumnVisible(this.model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", true));
 
setColumnVisible(this.model.getColumnForField("ID_ARTICLE"), selectArticle);
setColumnVisible(this.model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
setColumnVisible(this.model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
 
// Calcul automatique du poids unitaire
tableElement_ValeurMetrique1.addModificationListener(tableElementPoids);
tableElement_ValeurMetrique2.addModificationListener(tableElementPoids);
330,12 → 392,19
// Calcul automatique du poids total
tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
qteElement.addModificationListener(this.tableElementPoidsTotal);
qteU.addModificationListener(this.tableElementPoidsTotal);
this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row) {
System.err.println("Calcul du poids total ");
Number f = (Number) row.getObject("POIDS");
int qte = Integer.parseInt(row.getObject("QTE").toString());
return new Float(f.floatValue() * qte);
 
// return new Float(f.floatValue() * qte);
//
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
// FIXME convertir en float autrement pour éviter une valeur non transposable
// avec floatValue ou passer POIDS en bigDecimal
return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
}
 
});
360,6 → 429,19
 
});
 
uniteVente.addModificationListener(qteU);
qteU.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row) {
SQLRowAccessor rowUnite = row.getForeign("ID_UNITE_VENTE");
if (rowUnite != null && !rowUnite.isUndefined() && rowUnite.getBoolean("A_LA_PIECE")) {
return BigDecimal.ONE;
} else {
return row.getObject("QTE_UNITAIRE");
}
}
 
});
 
for (String string : visibilityMap.keySet()) {
setColumnVisible(this.model.getColumnForField(string), visibilityMap.get(string));
}
405,15 → 487,17
 
public void setFournisseurFilterOnCompletion(SQLRow row) {
if (row != null && !row.isUndefined()) {
SQLTable tableArticle = getSQLElement().getTable().getTable("ARTICLE");
 
Where w = new Where(tableArticle.getField("ID_FOURNISSEUR"), "=", row.getID());
w = w.or(new Where(tableArticle.getField("ID_FOURNISSEUR"), "IS", (Object) null));
w = w.or(new Where(tableArticle.getField("ID_FOURNISSEUR"), "=", getSQLElement().getTable().getTable("FOURNISSEUR").getUndefinedID()));
this.m.setWhere(w);
this.m2.setWhere(w);
this.m3.setWhere(w);
} else {
this.m.setWhere(null);
this.m2.setWhere(null);
this.m3.setWhere(null);
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractVenteArticleItemTable.java
18,8 → 18,10
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ArticleRowValuesRenderer;
import org.openconcerto.erp.core.sales.product.ui.QteMultipleRowValuesRenderer;
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
28,6 → 30,8
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.CellDynamicModifier;
import org.openconcerto.sql.view.list.RowValuesTable;
36,6 → 40,7
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
68,6 → 73,7
}
 
private SQLTable tableArticleTarif = Configuration.getInstance().getBase().getTable("ARTICLE_TARIF");
private SQLTable tableArticle = Configuration.getInstance().getBase().getTable("ARTICLE");
private SQLTable tableTarif = Configuration.getInstance().getBase().getTable("TARIF");
 
/**
75,15 → 81,18
*/
protected void init() {
 
SQLPreferences prefs = new SQLPreferences(getSQLElement().getTable().getDBRoot());
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
final SQLElement e = getSQLElement();
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
// Code article
// final SQLTableElement tableElementArticle = new
// SQLTableElement(e.getTable().getField("ID_ARTICLE"));
// list.add(tableElementArticle);
// Article
final SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true);
list.add(tableElementArticle);
 
// Code article
final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"));
174,14 → 183,21
list.add(tableElement_ValeurMetrique1);
 
// Prébilan
 
if (e.getTable().getFieldsName().contains("PREBILAN")) {
SQLTableElement prebilan = new SQLTableElement(e.getTable().getField("PREBILAN"), Long.class, new DeviseCellEditor());
prebilan = new SQLTableElement(e.getTable().getField("PREBILAN"), Long.class, new DeviseCellEditor());
prebilan.setRenderer(new DeviseNiceTableCellRenderer());
list.add(prebilan);
}
 
// Prix d'achat HT de la métrique 1
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), Long.class, new DeviseCellEditor());
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), Long.class, new DeviseCellEditor()) {
@Override
public boolean isCellEditable(SQLRowValues vals) {
// TODO Raccord de méthode auto-généré
return !(selectArticle && !createAuto);
}
};
tableElement_PrixMetrique1_AchatHT.setRenderer(new DeviseNiceTableCellRenderer());
list.add(tableElement_PrixMetrique1_AchatHT);
 
219,6 → 235,29
// SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), Long.class, new
// DeviseCellEditor());
// list.add(tableElement_PrixMetrique1_AchatHT);
 
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
@Override
public boolean isCellEditable(SQLRowValues vals) {
 
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
return false;
} else {
return super.isCellEditable(vals);
}
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
}
};
list.add(qteU);
 
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
// Quantité
this.qte = new SQLTableElement(e.getTable().getField("QTE"), Integer.class, new QteCellEditor()) {
protected Object getDefaultNullValue() {
251,9 → 290,9
list.add(tableElement_PrixVente_HT);
 
// TVA
final SQLTableElement tableElement_Taxe = new SQLTableElement(e.getTable().getField("ID_TAXE"));
tableElement_Taxe.setPreferredSize(20);
list.add(tableElement_Taxe);
this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
this.tableElementTVA.setPreferredSize(20);
list.add(this.tableElementTVA);
// Poids piece
SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class);
tableElementPoids.setPreferredSize(20);
270,6 → 309,7
}
 
this.totalHT = new SQLTableElement(e.getTable().getField("T_PV_HT"), Long.class, new DeviseCellEditor());
this.totalHT.setEditable(false);
if (e.getTable().getFieldsName().contains("POURCENT_ACOMPTE")) {
SQLTableElement tableElementAcompte = new SQLTableElement(e.getTable().getField("POURCENT_ACOMPTE"));
list.add(tableElementAcompte);
297,7 → 337,6
}
 
// Marge HT
 
if (e.getTable().getFieldsName().contains("MARGE_HT")) {
 
SQLTableElement marge = new SQLTableElement(e.getTable().getField("MARGE_HT"), Long.class, new DeviseCellEditor());
329,6 → 368,37
 
}
 
if (e.getTable().getFieldsName().contains("MARGE_PREBILAN_HT")) {
 
SQLTableElement marge = new SQLTableElement(e.getTable().getField("MARGE_PREBILAN_HT"), Long.class, new DeviseCellEditor());
marge.setRenderer(new MargeTableCellRenderer());
marge.setEditable(false);
list.add(marge);
this.totalHT.addModificationListener(marge);
prebilan.addModificationListener(marge);
marge.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
 
Long vt = row.getLong("T_PV_HT");
 
Long ha = (row.getObject("PREBILAN") == null ? 0 : row.getLong("PREBILAN"));
 
final Object o = row.getObject("POURCENT_ACOMPTE");
double lA = (o == null) ? 100 : ((BigDecimal) o).doubleValue();
if (lA >= 0 && lA != 100) {
ha = Math.round(ha * (lA / 100.0));
vt = Math.round(vt * (lA / 100.0));
}
 
Long r = Long.valueOf(vt - ha);
return r;
}
 
});
 
}
 
// Total HT
this.totalHT.setRenderer(new DeviseNiceTableCellRenderer());
list.add(this.totalHT);
354,6 → 424,7
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("ID_PAYS");
}
completionField.add("ID_UNITE_VENTE");
completionField.add("PA_HT");
completionField.add("PV_HT");
completionField.add("ID_TAXE");
394,7 → 465,7
}
};
m.fill("NOM", "NOM");
// m.fill("ID", "ID_ARTICLE");
m.fill("ID", "ID_ARTICLE");
for (String string : completionField) {
m.fill(string, string);
}
413,7 → 484,7
 
};
m2.fill("CODE", "CODE");
// m2.fill("ID", "ID_ARTICLE");
m2.fill("ID", "ID_ARTICLE");
for (String string : completionField) {
m2.fill(string, string);
}
420,31 → 491,45
 
m2.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
 
// final AutoCompletionManager m3 = new AutoCompletionManager(tableElementArticle,
// sqlTableArticle.getField("NOM"), this.table, this.table.getRowValuesTableModel(),
// ITextWithCompletion.MODE_CONTAINS, true, true) {
// @Override
// protected Object getValueFrom(SQLRow row, String field) {
// Object res = tarifCompletion(row, field);
// if (res == null) {
// return super.getValueFrom(row, field);
// } else {
// return res;
// }
// }
//
// };
// m3.fill("CODE", "CODE");
// m3.fill("NOM", "NOM");
// for (String string : completionField) {
// m3.fill(string, string);
// }
final AutoCompletionManager m3 = new AutoCompletionManager(tableElementArticle, sqlTableArticle.getField("NOM"), this.table, this.table.getRowValuesTableModel(),
ITextWithCompletion.MODE_CONTAINS, true, true) {
@Override
protected Object getValueFrom(SQLRow row, String field) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field);
} else {
return res;
}
}
 
// m3.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
};
m3.fill("CODE", "CODE");
m3.fill("NOM", "NOM");
for (String string : completionField) {
m3.fill(string, string);
}
 
m3.setWhere(new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
 
tableElementCode.addModificationListener(tableElementArticle);
tableElementArticle.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
return foreign.getID();
} else {
return tableArticle.getUndefinedID();
}
}
});
 
// Calcul automatique du total HT
this.qte.addModificationListener(this.totalHT);
this.qte.addModificationListener(totalHA);
qteU.addModificationListener(this.totalHT);
qteU.addModificationListener(totalHA);
if (tableElementRG != null) {
tableElementRG.addModificationListener(this.totalHT);
}
466,8 → 551,9
}
 
int qte = (row.getObject("QTE") == null) ? 0 : Integer.parseInt(row.getObject("QTE").toString());
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
Number f = (Number) row.getObject("PV_HT");
long r = f.longValue() * qte;
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
if (row.getTable().getFieldsName().contains("POURCENT_ACOMPTE")) {
final Object o = row.getObject("POURCENT_ACOMPTE");
double lA = (o == null) ? 0 : ((BigDecimal) o).doubleValue();
485,8 → 571,9
@Override
public Object computeValueFrom(SQLRowValues row) {
int qte = Integer.parseInt(row.getObject("QTE").toString());
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
Number f = (Number) row.getObject("PA_HT");
long r = f.longValue() * qte;
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
return Long.valueOf(r);
}
});
493,6 → 580,7
 
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
this.qte.addModificationListener(tableElementTotalDevise);
qteU.addModificationListener(tableElementTotalDevise);
eltUnitDevise.addModificationListener(tableElementTotalDevise);
tableElementRemise.addModificationListener(this.tableElementTotalDevise);
tableElementTotalDevise.setModifier(new CellDynamicModifier() {
502,7 → 590,9
double lremise = (o2 == null) ? 0 : ((BigDecimal) o2).doubleValue();
int qte = Integer.parseInt(row.getObject("QTE").toString());
Number f = (Number) row.getObject("PV_U_DEVISE");
long r = f.longValue() * qte;
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
;
if (lremise > 0 && lremise != 100) {
r = Math.round(r * (100.0 - lremise) / 100.0);
}
514,7 → 604,7
// tableElement_Quantite.addModificationListener(tableElement_TotalTTC);
// tableElement_PrixVente_HT.addModificationListener(tableElement_TotalTTC);
this.totalHT.addModificationListener(this.tableElementTotalTTC);
tableElement_Taxe.addModificationListener(this.tableElementTotalTTC);
this.tableElementTVA.addModificationListener(this.tableElementTotalTTC);
this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row) {
557,15 → 647,31
});
// Calcul automatique du poids total
tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
qteU.addModificationListener(tableElementPoidsTotal);
this.qte.addModificationListener(this.tableElementPoidsTotal);
this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row) {
Number f = (Number) row.getObject("POIDS");
int qte = Integer.parseInt(row.getObject("QTE").toString());
return new Float(f.floatValue() * qte);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
// FIXME convertir en float autrement pour éviter une valeur non valeur transposable
// avec floatValue ou passer POIDS en bigDecimal
return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
}
 
});
uniteVente.addModificationListener(qteU);
qteU.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row) {
SQLRowAccessor rowUnite = row.getForeign("ID_UNITE_VENTE");
if (rowUnite != null && !rowUnite.isUndefined() && rowUnite.getBoolean("A_LA_PIECE")) {
return BigDecimal.ONE;
} else {
return row.getObject("QTE_UNITAIRE");
}
}
 
});
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
eltUnitDevise.addModificationListener(tableElement_PrixMetrique1_VenteHT);
tableElement_PrixMetrique1_VenteHT.setModifier(new CellDynamicModifier() {
634,6 → 740,15
setColumnVisible(this.model.getColumnForField("PA_HT"), modeAvance);
setColumnVisible(this.model.getColumnForField("ID_MODE_VENTE_ARTICLE"), modeAvance);
 
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
setColumnVisible(this.model.getColumnForField("QTE_UNITAIRE"), gestionUV);
setColumnVisible(this.model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
 
setColumnVisible(this.model.getColumnForField("ID_ARTICLE"), selectArticle);
setColumnVisible(this.model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
setColumnVisible(this.model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
 
// Voir le poids
final boolean showPoids = DefaultNXProps.getInstance().getBooleanValue("ArticleShowPoids", false);
setColumnVisible(this.model.getColumnForField("POIDS"), showPoids);
640,7 → 755,7
setColumnVisible(this.model.getColumnForField("T_POIDS"), showPoids);
 
// Voir le style
setColumnVisible(this.model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", false));
setColumnVisible(this.model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", true));
setColumnVisible(this.model.getColumnForField("POURCENT_ACOMPTE"), false);
 
 
717,8 → 832,6
return null;
}
 
SQLTable tableArticle = Configuration.getInstance().getBase().getTable("ARTICLE");
 
@Override
public void setTarif(SQLRowAccessor rowValuesTarif, boolean ask) {
// TODO Raccord de méthode auto-généré
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/TotalPanel.java
18,6 → 18,7
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.SQLTableElement;
31,6 → 32,10
import java.awt.GridBagLayout;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.JLabel;
import javax.swing.JPanel;
45,7 → 50,7
public class TotalPanel extends JPanel implements TableModelListener {
public static String MARGE_MARQUE = "MargeMarque";
private RowValuesTable table;
private int columnIndexHT, columnIndexTTC, columnIndexService, columnIndexHA, columnIndexQte, columnIndexDevise, columnIndexPoids;
private int columnIndexHT, columnIndexTVA, columnIndexService, columnIndexHA, columnIndexQte, columnIndexDevise, columnIndexPoids;
private DeviseField textTotalHT, textTotalHTSel;
private DeviseField textTotalTVA, textTotalTVASel;
private DeviseField textTotalTTC, textTotalTTCSel;
60,32 → 65,28
private PropertyChangeSupport supp;
private int columnIndexEchHT = -1;
private int columnIndexEchTTC = -1;
SQLTableElement ha;
 
public TotalPanel(RowValuesTable table, SQLTableElement ht, SQLTableElement ttc, SQLTableElement ha, SQLTableElement qte, DeviseField textTotalHT, DeviseField textTotalTVA,
DeviseField textTotalTTC, DeviseField textPortHT, DeviseField textRemiseHT, DeviseField textService, SQLTableElement serv, DeviseField textTotalDevise, SQLTableElement devise,
JTextField textTotalPoids, SQLTableElement poids) {
this(table, ht, ttc, ha, qte, textTotalHT, textTotalTVA, textTotalTTC, textPortHT, textRemiseHT, textService, serv, null, null, textTotalDevise, devise, textTotalPoids, poids);
}
public TotalPanel(AbstractArticleItemTable articleItemTable, DeviseField textTotalHT, DeviseField textTotalTVA, DeviseField textTotalTTC, DeviseField textPortHT, DeviseField textRemiseHT,
DeviseField textService, DeviseField textTotalHA, DeviseField textTotalDevise, JTextField textTotalPoids, JPanel tableEchantillon) {
 
public TotalPanel(RowValuesTable table, SQLTableElement ht, SQLTableElement ttc, SQLTableElement ha, SQLTableElement qte, DeviseField textTotalHT, DeviseField textTotalTVA,
DeviseField textTotalTTC, DeviseField textPortHT, DeviseField textRemiseHT, DeviseField textService, SQLTableElement serv, JPanel tableEchantillon, DeviseField textTotalHA,
DeviseField textTotalDevise, SQLTableElement devise, JTextField textTotalPoids, SQLTableElement poids) {
 
super();
this.ha = (articleItemTable.getPrebilanElement() == null) ? articleItemTable.getHaElement() : articleItemTable.getPrebilanElement();
this.supp = new PropertyChangeSupport(this);
this.table = table;
this.columnIndexHT = this.table.getRowValuesTableModel().getColumnIndexForElement(ht);
this.columnIndexTTC = this.table.getRowValuesTableModel().getColumnIndexForElement(ttc);
this.columnIndexDevise = (devise == null ? -1 : this.table.getRowValuesTableModel().getColumnIndexForElement(devise));
this.columnIndexService = this.table.getRowValuesTableModel().getColumnIndexForElement(serv);
this.columnIndexPoids = this.table.getRowValuesTableModel().getColumnIndexForElement(poids);
this.gestionHA = ha != null && qte != null;
this.table = articleItemTable.getRowValuesTable();
this.columnIndexHT = this.table.getRowValuesTableModel().getColumnIndexForElement(articleItemTable.getPrixTotalHTElement());
this.columnIndexTVA = this.table.getRowValuesTableModel().getColumnIndexForElement(articleItemTable.getTVAElement());
this.columnIndexDevise = (articleItemTable.getTableElementTotalDevise() == null ? -1 : this.table.getRowValuesTableModel().getColumnIndexForElement(
articleItemTable.getTableElementTotalDevise()));
this.columnIndexService = this.table.getRowValuesTableModel().getColumnIndexForElement(articleItemTable.getPrixServiceElement());
this.columnIndexPoids = this.table.getRowValuesTableModel().getColumnIndexForElement(articleItemTable.getPoidsTotalElement());
this.gestionHA = ha != null && articleItemTable.getQteElement() != null;
 
if (this.gestionHA) {
this.columnIndexHA = this.table.getRowValuesTableModel().getColumnIndexForElement(ha);
this.columnIndexQte = this.table.getRowValuesTableModel().getColumnIndexForElement(qte);
this.columnIndexQte = this.table.getRowValuesTableModel().getColumnIndexForElement(articleItemTable.getQteElement());
}
this.textPoids = textTotalPoids;
this.textPoids = (textTotalPoids == null ? new JTextField() : textTotalPoids);
this.textTotalHT = textTotalHT;
this.textTotalHT.setBold();
this.textTotalTVA = textTotalTVA;
101,7 → 102,7
this.textTotalTVASel = new DeviseField();
this.marge = new JTextField();
this.margeSel = new JTextField();
if (devise != null) {
if (articleItemTable.getTableElementTotalDevise() != null) {
this.textTotalDevise = textTotalDevise;
this.textTotalDeviseSel = new DeviseField();
reconfigure(this.textTotalDevise);
123,8 → 124,9
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean b = Boolean.valueOf(val);
 
if (this.columnIndexHT < 0 || this.columnIndexTTC < 0 || (b != null && b.booleanValue() && this.columnIndexService < 0)) {
throw new IllegalArgumentException("Impossible de trouver la colonne de " + ht + " / " + ttc + " / " + serv);
if (this.columnIndexHT < 0 || this.columnIndexTVA < 0 || (b != null && b.booleanValue() && this.columnIndexService < 0)) {
throw new IllegalArgumentException("Impossible de trouver la colonne de " + articleItemTable.getPrixTotalHTElement() + " / " + articleItemTable.getTVAElement() + " / "
+ articleItemTable.getPrixServiceElement());
}
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
150,7 → 152,7
 
// Total HA HT
c.gridy++;
this.add(new JLabel("Total HA HT"), c);
this.add(new JLabel("Total achat HT"), c);
 
c.gridx++;
c.weightx = 1;
215,7 → 217,7
c.fill = GridBagConstraints.BOTH;
this.add(createSeparator(), c);
 
if (devise != null) {
if (articleItemTable.getTableElementTotalDevise() != null) {
// Devise
c.gridwidth = 1;
c.gridx = 1;
264,7 → 266,7
 
// Total HA HT
c.gridy++;
this.add(new JLabel("Total HA HT"), c);
this.add(new JLabel("Total achat HT"), c);
 
c.gridx++;
c.weightx = 1;
327,7 → 329,7
c.fill = GridBagConstraints.BOTH;
this.add(createSeparator(), c);
 
if (devise != null) {
if (articleItemTable.getTableElementTotalDevise() != null) {
// devise
c.gridwidth = 1;
c.gridx = 4;
377,7 → 379,7
}
 
public void tableChanged(TableModelEvent e) {
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == this.columnIndexHT || e.getColumn() == this.columnIndexTTC || e.getColumn() == this.columnIndexEchHT
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == this.columnIndexHT || e.getColumn() == this.columnIndexTVA || e.getColumn() == this.columnIndexEchHT
|| e.getColumn() == this.columnIndexEchTTC || e.getColumn() == this.columnIndexDevise) {
// System.out.println(e);
updateTotal();
388,21 → 390,23
*
*/
public void updateTotal() {
long valPortHT, valRemiseHT, realTotalHT, realTotalTTC;
long valPortHT, valRemiseHT, realTotalHT;
 
try {
long totalHT = 0;
long totalHA = 0;
long totalTTC = 0;
 
long totalService = 0;
long totalHTSel = 0;
long totalHASel = 0;
long totalTTCSel = 0;
 
long totalServiceSel = 0;
long totalDeviseSel = 0;
long totalDevise = 0;
double totalPoids = 0;
int[] selectedRows = this.table.getSelectedRows();
Map<SQLRowAccessor, Long> mapHtTVA = new HashMap<SQLRowAccessor, Long>();
Map<SQLRowAccessor, Long> mapHtTVASel = new HashMap<SQLRowAccessor, Long>();
 
for (int i = 0; i < this.table.getRowValuesTableModel().getRowCount(); i++) {
 
412,8 → 416,12
if (this.gestionHA) {
Number nHA = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexHA);
Number nQte = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexQte);
if (this.ha != null && this.ha.getField().getName().equalsIgnoreCase("PREBILAN")) {
totalHA += (nHA.longValue());
} else {
totalHA += (nHA.longValue() * nQte.intValue());
}
}
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean bServiceActive = Boolean.valueOf(val);
if (bServiceActive != null && bServiceActive) {
427,11 → 435,18
nDevise = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexDevise);
totalDevise += nDevise.longValue();
}
Number nTTC = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexTTC);
totalTTC += nTTC.longValue();
// Number nTTC = (Number) this.table.getRowValuesTableModel().getValueAt(i,
// this.columnIndexTTC);
// totalTTC += nTTC.longValue();
if (mapHtTVA.get(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE")) == null) {
mapHtTVA.put(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"), nHT.longValue());
} else {
Long l = mapHtTVA.get(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"));
mapHtTVA.put(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"), l + nHT.longValue());
}
 
Number nPoids = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexPoids);
totalPoids += nPoids.doubleValue();
totalPoids += nPoids == null ? 0 : nPoids.doubleValue();
 
if (containsInt(selectedRows, i)) {
 
440,8 → 455,12
if (this.gestionHA) {
Number nHA = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexHA);
Number nQte = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexQte);
if (this.ha != null && this.ha.getField().getName().equalsIgnoreCase("PREBILAN")) {
totalHASel += (nHA.longValue());
} else {
totalHASel += (nHA.longValue() * nQte.intValue());
}
}
 
if (bServiceActive != null && bServiceActive) {
Boolean b = (Boolean) this.table.getRowValuesTableModel().getValueAt(i, this.columnIndexService);
450,7 → 469,13
}
}
 
totalTTCSel += nTTC.longValue();
if (mapHtTVASel.get(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE")) == null) {
mapHtTVASel.put(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"), nHT.longValue());
} else {
Long l = mapHtTVASel.get(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"));
mapHtTVASel.put(this.table.getRowValuesTableModel().getRowValuesAt(i).getForeign("ID_TAXE"), l + nHT.longValue());
}
// totalTTCSel += nTTC.longValue();
if (this.textTotalDevise != null) {
totalDeviseSel += nDevise.longValue();
}
480,8 → 505,16
realTotalHT = totalHT + valPortHT - valRemiseHT;
long portTTC = new PrixHT(valPortHT).calculLongTTC(0.196F);
long remiseTTC = new PrixHT(valRemiseHT).calculLongTTC(0.196F);
realTotalTTC = totalTTC + portTTC - remiseTTC;
 
long realTotalTVA = 0;
for (SQLRowAccessor row : mapHtTVA.keySet()) {
BigDecimal d = new BigDecimal(row.getFloat("TAUX"));
BigDecimal result = d.multiply(new BigDecimal(mapHtTVA.get(row)), MathContext.DECIMAL128).movePointLeft(2);
realTotalTVA += result.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
}
 
long realTotalTTC = totalHT + realTotalTVA + portTTC - remiseTTC;
 
if (this.textTotalDevise != null) {
this.textTotalDevise.setText(GestionDevise.currencyToString(totalDevise));
this.textTotalDeviseSel.setText(GestionDevise.currencyToString(totalDeviseSel));
489,12 → 522,20
this.textPoids.setText(String.valueOf(totalPoids));
this.textTotalHT.setText(GestionDevise.currencyToString(realTotalHT));
this.textService.setText(GestionDevise.currencyToString(totalService));
this.textTotalTVA.setText(GestionDevise.currencyToString(realTotalTTC - realTotalHT));
this.textTotalTVA.setText(GestionDevise.currencyToString(realTotalTVA));
this.textTotalTTC.setText(GestionDevise.currencyToString(realTotalTTC));
this.textTotalHTSel.setText(GestionDevise.currencyToString(totalHTSel));
this.textServiceSel.setText(GestionDevise.currencyToString(totalServiceSel));
this.textTotalTVASel.setText(GestionDevise.currencyToString(totalTTCSel - totalHTSel));
this.textTotalTTCSel.setText(GestionDevise.currencyToString(totalTTCSel));
 
long realTotalTVASel = 0;
for (SQLRowAccessor row : mapHtTVASel.keySet()) {
BigDecimal d = new BigDecimal(row.getFloat("TAUX"));
BigDecimal result = d.multiply(new BigDecimal(mapHtTVASel.get(row)), MathContext.DECIMAL128).movePointLeft(2);
realTotalTVASel += result.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
}
 
this.textTotalTVASel.setText(GestionDevise.currencyToString(realTotalTVASel));
this.textTotalTTCSel.setText(GestionDevise.currencyToString(realTotalTVASel + totalHTSel));
if (this.gestionHA) {
this.textHA.setText(GestionDevise.currencyToString(totalHA));
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/IListTotalPanel.java
13,20 → 13,23
package org.openconcerto.erp.core.common.ui;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
33,6 → 36,7
 
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.EventListenerList;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
39,14 → 43,41
 
public class IListTotalPanel extends JPanel {
 
public enum Type {
// Pourcentage moyen d'une colonne
MOYENNE_POURCENT,
// Moyenne d'une colonne
MOYENNE_DEVISE,
// Somme total d'une colonne
SOMME,
// Marge en pourcentage requiert dans la liste la colonne achat en premier et vente en
// deuxieme
MOYENNE_MARGE;
};
 
DecimalFormat decimalFormat = new DecimalFormat("##,##0.00");
 
EventListenerList loadingListener = new EventListenerList();
private final IListe list;
private final Map<SQLField, JLabel> map = new HashMap<SQLField, JLabel>();
private final Map<SQLTableModelColumn, JLabel> map = new HashMap<SQLTableModelColumn, JLabel>();
 
public IListTotalPanel(IListe l, final List<SQLField> listField) {
this(l, listField, null, null);
this(l, initListe(l, listField), null, null);
}
 
public IListTotalPanel(IListe l, final List<SQLField> listField, String title) {
this(l, initListe(l, listField), null, title);
}
 
public static List<Tuple2<? extends SQLTableModelColumn, Type>> initListe(IListe iL, List<SQLField> l) {
List<Tuple2<? extends SQLTableModelColumn, Type>> lFinal = new ArrayList<Tuple2<? extends SQLTableModelColumn, Type>>();
 
for (SQLField field : l) {
lFinal.add(Tuple2.create(iL.getSource().getColumn(field), Type.SOMME));
}
return lFinal;
}
 
/**
*
* @param l
53,9 → 84,10
* @param listField Liste des fields à totaliser
* @param filters filtre ex : Tuple((SQLField)NATEXIER,(Boolean)FALSE)
*/
public IListTotalPanel(IListe l, final List<SQLField> listField, final List<Tuple2<SQLField, ?>> filters, String title) {
public IListTotalPanel(IListe l, final List<Tuple2<? extends SQLTableModelColumn, Type>> listField, final List<Tuple2<SQLField, ?>> filters, String title) {
super(new GridBagLayout());
this.list = l;
this.setOpaque(false);
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
69,14 → 101,21
c.gridwidth = 1;
}
// Filtre
for (SQLField field2 : listField) {
for (Tuple2<? extends SQLTableModelColumn, Type> field2 : listField) {
c.weightx = 0;
this.add(new JLabelBold(Configuration.getTranslator(field2.getTable()).getDescFor(field2.getTable(), field2.getName()).getLabel()), c);
JLabelBold comp = new JLabelBold(field2.get0().getName());
comp.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(comp, c);
JLabelBold textField = new JLabelBold("0");
this.map.put(field2, textField);
textField.setHorizontalAlignment(SwingConstants.RIGHT);
this.map.put(field2.get0(), textField);
c.weightx = 1;
this.add(textField, c);
if (field2.get1() == Type.SOMME || field2.get1() == Type.MOYENNE_DEVISE) {
this.add(new JLabelBold("€"), c);
} else if (field2.get1() == Type.MOYENNE_POURCENT || field2.get1() == Type.MOYENNE_MARGE) {
this.add(new JLabelBold("%"), c);
}
c.gridy++;
}
 
83,22 → 122,58
this.list.addListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
Map<SQLField, Long> mapTotal = new HashMap<SQLField, Long>();
Map<SQLTableModelColumn, BigDecimal> mapTotal = new HashMap<SQLTableModelColumn, BigDecimal>();
Map<SQLTableModelColumn, Double> mapPourcent = new HashMap<SQLTableModelColumn, Double>();
Map<SQLTableModelColumn, Integer> mapPourcentSize = new HashMap<SQLTableModelColumn, Integer>();
 
for (int i = 0; i < list.getRowCount(); i++) {
 
final SQLRowValues rowAt = ITableModel.getLine(list.getModel(), i).getRow();
 
for (SQLField field : listField) {
Long n = mapTotal.get(field);
for (Tuple2<? extends SQLTableModelColumn, Type> field : listField) {
 
Long n2;
if (field.getTable().getName().equalsIgnoreCase(rowAt.getTable().getName())) {
n2 = (Long) rowAt.getObject(field.getName());
if (field.get1() == Type.MOYENNE_POURCENT) {
 
Double n2 = (Double) list.getModel().getValueAt(i, list.getSource().getColumns().indexOf(field.get0()));
 
boolean in = true;
 
if (filters != null) {
for (Tuple2<SQLField, ?> tuple2 : filters) {
in = in && rowAt.getObject(tuple2.get0().getName()).equals(tuple2.get1());
}
}
 
if (in) {
 
if (mapPourcent.get(field.get0()) == null) {
mapPourcent.put(field.get0(), n2);
} else {
SQLField fk = (SQLField) rowAt.getTable().getForeignKeys(field.getTable()).toArray()[0];
n2 = (Long) rowAt.getForeign(fk.getName()).getObject(field.getName());
mapPourcent.put(field.get0(), n2 + mapPourcent.get(field.get0()));
}
 
if (mapPourcentSize.get(field.get0()) == null) {
mapPourcentSize.put(field.get0(), 1);
} else {
mapPourcentSize.put(field.get0(), mapPourcentSize.get(field.get0()).intValue() + 1);
}
 
}
} else if (field.get1() != Type.MOYENNE_MARGE) {
BigDecimal n = mapTotal.get(field.get0());
 
BigDecimal n2 = BigDecimal.valueOf(((Number) list.getModel().getValueAt(i, list.getSource().getColumns().indexOf(field.get0()))).doubleValue());
// if
// (list.getSource().getPrimaryTable().getName().equalsIgnoreCase(field.get0().getFields()))
// {
// n2 = (Long) rowAt.getObject(field.getName());
// } else {
// SQLField fk = (SQLField)
// rowAt.getTable().getForeignKeys(field.getTable()).toArray()[0];
// n2 = (Long)
// rowAt.getForeign(fk.getName()).getObject(field.getName());
// }
 
boolean in = true;
 
if (filters != null) {
109,22 → 184,42
 
if (in) {
if (n == null) {
mapTotal.put(field, n2);
mapTotal.put(field.get0(), n2);
} else {
mapTotal.put(field, n + n2);
mapTotal.put(field.get0(), n.add(n2));
}
}
}
}
}
 
for (SQLField field : listField) {
Long l = mapTotal.get(field);
for (Tuple2<? extends SQLTableModelColumn, Type> field : listField) {
if (field.get1() == Type.MOYENNE_MARGE) {
 
BigDecimal totalVT = mapTotal.get(listField.get(0).get0());
BigDecimal totalHA = mapTotal.get(listField.get(1).get0());
if (totalHA != null && totalVT != null && totalVT.longValue() != 0) {
map.get(field.get0()).setText(decimalFormat.format(totalVT.subtract(totalHA).divide(totalVT, MathContext.DECIMAL32).doubleValue() * 100.0D));
} else {
map.get(field.get0()).setText(decimalFormat.format(0));
}
} else if (field.get1() == Type.MOYENNE_POURCENT) {
Double l = mapPourcent.get(field.get0());
Integer d = mapPourcentSize.get(field.get0());
if (l != null && d != null && d != 0) {
map.get(field.get0()).setText(decimalFormat.format(l / (double) d));
} else {
map.get(field.get0()).setText(decimalFormat.format(0));
}
} else {
BigDecimal l = mapTotal.get(field.get0());
if (l != null) {
map.get(field).setText(GestionDevise.currencyToString(l));
map.get(field.get0()).setText(decimalFormat.format(l.doubleValue()));
} else {
map.get(field).setText(GestionDevise.currencyToString(0));
map.get(field.get0()).setText(decimalFormat.format(0));
}
}
}
fireUpdated();
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/IListFilterDatePanel.java
13,6 → 13,7
package org.openconcerto.erp.core.common.ui;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
49,7 → 50,10
private Map<IListe, ITransformer<SQLSelect, SQLSelect>> mapListTransformer;
// Liste des filtres
private Map<String, Tuple2<Date, Date>> map;
private static LinkedHashMap<String, Tuple2<Date, Date>> mapDefault;
 
private JComboBox combo;
 
private final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
62,12 → 66,26
 
public IListFilterDatePanel(IListe l, SQLField fieldDate) {
this(l, fieldDate, null);
if (l.getRequest() == Configuration.getInstance().getDirectory().getElement(l.getSource().getPrimaryTable()).getListRequest()) {
System.err.println("Attention il ne faut pas utiliser la listrequest par défaut sinon les filtres restes !!!");
Thread.dumpStack();
}
}
 
public static Map<String, Tuple2<Date, Date>> getDefaultMap() {
Calendar c = Calendar.getInstance();
 
if (mapDefault == null) {
initDefaultMap();
}
Map<String, Tuple2<Date, Date>> m = new LinkedHashMap<String, Tuple2<Date, Date>>();
m.putAll(mapDefault);
return m;
}
 
private static void initDefaultMap() {
mapDefault = new LinkedHashMap<String, Tuple2<Date, Date>>();
Calendar c = Calendar.getInstance();
 
// Année courante
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
75,7 → 93,7
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d2 = c.getTime();
m.put("Année courante", Tuple2.create(d1, d2));
mapDefault.put("Année courante", Tuple2.create(d1, d2));
 
// Année précedente
c.set(Calendar.DATE, 1);
85,7 → 103,7
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d4 = c.getTime();
m.put("Année précédente", Tuple2.create(d3, d4));
mapDefault.put("Année précédente", Tuple2.create(d3, d4));
 
// Mois courant
c = Calendar.getInstance();
93,7 → 111,7
Date d5 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
Date d6 = c.getTime();
m.put("Mois courant", Tuple2.create(d5, d6));
mapDefault.put("Mois courant", Tuple2.create(d5, d6));
 
// Mois précédent
c = Calendar.getInstance();
102,7 → 120,7
Date d7 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
Date d8 = c.getTime();
m.put("Mois précédent", Tuple2.create(d7, d8));
mapDefault.put("Mois précédent", Tuple2.create(d7, d8));
 
// semaine courante
c = Calendar.getInstance();
110,7 → 128,7
Date d9 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date d10 = c.getTime();
m.put("Semaine courante", Tuple2.create(d9, d10));
mapDefault.put("Semaine courante", Tuple2.create(d9, d10));
 
// semaine précédente
c = Calendar.getInstance();
119,13 → 137,18
Date d11 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date d12 = c.getTime();
m.put("Semaine précédente", Tuple2.create(d11, d12));
mapDefault.put("Semaine précédente", Tuple2.create(d11, d12));
}
 
return m;
public static void addDefaultValue(String label, Tuple2<Date, Date> period) {
if (mapDefault == null)
initDefaultMap();
mapDefault.put(label, period);
}
 
public IListFilterDatePanel(IListe l, SQLField fieldDate, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
setOpaque(false);
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(l, fieldDate);
 
165,7 → 188,8
model.addElement(s);
}
 
final JComboBox combo = new JComboBox(model);
this.combo = new JComboBox(model);
 
c.weightx = 0;
this.add(combo, c);
 
194,17 → 218,24
this.dateAu.setValue(d);
}
 
public void setFilterOnCurrentYear() {
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH, 1);
Date d = c.getTime();
c.set(Calendar.MONTH, 11);
c.set(Calendar.DAY_OF_MONTH, c.getMaximum(Calendar.DAY_OF_MONTH));
Date d2 = c.getTime();
setPeriode(d, d2);
private static Tuple2<String, Tuple2<Date, Date>> DEFAULT_FILTER = null;
 
public static void setDefaultFilter(Tuple2<String, Tuple2<Date, Date>> t) {
DEFAULT_FILTER = t;
}
 
public void setFilterOnDefault() {
 
if (DEFAULT_FILTER != null) {
 
if (this.combo != null) {
this.combo.setSelectedItem(DEFAULT_FILTER.get0());
} else {
setPeriode(DEFAULT_FILTER.get1().get0(), DEFAULT_FILTER.get1().get1());
}
}
}
 
public void setPeriode(Tuple2<Date, Date> t) {
if (t == null) {
setPeriode(null, null);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/component/AdresseSQLComponent.java
22,10 → 22,7
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
70,23 → 67,26
c.gridx = 0;
c.weightx = 0;
c.gridwidth = 1;
 
this.add(labelVille, c);
c.gridwidth = 1;
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
DefaultGridBagConstraints.lockMinimumSize(textVille);
this.add(textVille, c);
 
// Cedex
final JCheckBox checkCedex = new JCheckBox(getLabelFor("CEDEX"), false);
checkCedex.setOpaque(false);
c.gridx++;
final JLabel labelCedex = new JLabel(getLabelFor("CEDEX"), SwingConstants.RIGHT);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
this.add(checkCedex, c);
c.fill = GridBagConstraints.HORIZONTAL;
this.add(labelCedex, c);
final JTextField cedex = new JTextField(6);
c.gridx++;
cedex.setEditable(false);
c.fill = GridBagConstraints.NONE;
this.add(cedex, c);
 
// Pays
94,10 → 94,12
c.gridx = 0;
c.weightx = 0;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
final JLabel labelPays = new JLabel(getLabelFor("PAYS"), SwingConstants.RIGHT);
this.add(labelPays, c);
final JTextField pays = new JTextField();
final JTextField pays = new JTextField(16);
c.gridx++;
c.fill = GridBagConstraints.NONE;
this.add(pays, c);
 
this.addSQLObject(textRue, "RUE");
104,15 → 106,10
this.addView(textVille, "VILLE", REQ);
this.addView(cedex, "CEDEX");
this.addView(destinataire, "DEST");
this.addView(checkCedex, "HAS_CEDEX");
 
this.addRequiredSQLObject(pays, "PAYS");
 
checkCedex.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cedex.setEditable(checkCedex.isSelected());
}
});
}
 
protected SQLRowValues createDefaults() {
final SQLRowValues rowVals = new SQLRowValues(getTable());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/component/SocieteCommonSQLElement.java
320,23 → 320,22
c.gridy++;
c.insets = new Insets(10, 2, 1, 2);
this.add(this.sepPlan, c);
JPanel panelPlan = new JPanel();
this.labelPlan = new JLabel("Choix du plan comptable", SwingConstants.RIGHT);
this.combo = new JComboBox();
this.combo.addItem("Base");
this.combo.addItem("Abrégé");
this.combo.addItem("Développé");
panelPlan.add(this.labelPlan);
panelPlan.add(this.combo);
 
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.gridwidth = GridBagConstraints.REMAINDER;
c.insets = new Insets(2, 2, 1, 2);
this.labelPlan = new JLabel("Choix du plan comptable");
this.add(this.labelPlan, c);
c.fill = GridBagConstraints.NONE;
this.add(panelPlan, c);
 
this.combo = new JComboBox();
 
this.combo.addItem("Base");
this.combo.addItem("Abrégé");
this.combo.addItem("Développé");
c.gridx++;
c.gridx = GridBagConstraints.RELATIVE;
this.add(this.combo, c);
 
this.addRequiredSQLObject(this.textNom, "NOM");
// this.addSQLObject(this.textAdresse, "ADRESSE");
this.addRequiredSQLObject(this.textNumAPE, "NUM_APE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java
88,6 → 88,7
private Map<SQLTable, SQLField> listFieldMap = new HashMap<SQLTable, SQLField>();
private Map<String, Where> whereList = new HashMap<String, Where>();
private static Map<SQLElement, Class<? extends AbstractSheetXml>> elementSheet = new HashMap<SQLElement, Class<? extends AbstractSheetXml>>();
private String undefinedLabel;
 
static {
SQLElementDirectory dir = Configuration.getInstance().getDirectory();
103,6 → 104,11
int selectIndex = ListeHistoriquePanel.this.jListePanel.getSelectedIndex();
 
SQLRowAccessor row = ListeHistoriquePanel.this.jListePanel.getModel().getRowAt(selectIndex);
 
if ((row == null || row.isUndefined()) && undefinedLabel == null) {
return;
}
 
int id = SQLRow.NONEXISTANT_ID;
if (row != null) {
id = row.getID();
167,6 → 173,10
}
};
 
public ListeHistoriquePanel(final String title, final SQLTable tableList, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap) {
this(title, tableList, listTableOnglet, panelBottom, listFieldMap, "Tous");
}
 
// TODO verifier que les tables contiennent bien la clef etrangere
/**
* @param title titre de la JList
175,8 → 185,10
* @param panelBottom panel à afficher en bas de la frame
* @param listFieldMap jointure d'une table pour utiliser le filtre si la table ne contient pas
* de foreignKey pointant sur tableList
* @param undefinedLabel label pour l'indéfini permettant de tout sélectionner, null si
* l'undefined n'est pas à inclure.
*/
public ListeHistoriquePanel(final String title, final SQLTable tableList, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap) {
public ListeHistoriquePanel(final String title, final SQLTable tableList, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap, String undefinedLabel) {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
297,7 → 309,7
SQLElement e = Configuration.getInstance().getDirectory().getElement(tableList);
 
List<String> fields = getListSQLField(e.getComboRequest().getFields());
this.jListePanel = new JListSQLTablePanel(tableList, fields, "Tous");
this.jListePanel = new JListSQLTablePanel(tableList, fields, undefinedLabel);
 
// Right panel
JPanel rightPanel = new JPanel();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockLabel.java
New file
0,0 → 1,25
/*
* 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.
*/
/*
* Créé le 13 avr. 2012
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.sql.model.SQLRow;
 
public abstract class StockLabel {
 
abstract public String getLabel(SQLRow rowOrigin, SQLRow rowElt);
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
19,11 → 19,13
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
import org.openconcerto.erp.core.supplychain.supplier.component.MouvementStockSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
31,6 → 33,7
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
45,8 → 48,11
import java.util.Arrays;
import java.util.List;
 
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
public class MouvementStockSQLElement extends ComptaSQLConfElement {
 
public MouvementStockSQLElement() {
84,10 → 90,110
updateStock(Arrays.asList(row.getID()), true);
}
 
public static CollectionMap<SQLRow, List<SQLRowValues>> updateStock(List<Integer> ids) {
return updateStock(ids, false);
// public CollectionMap<SQLRow, List<SQLRowValues>> updateStock(List<Integer> ids) {
// return updateStock(ids, false);
// }
 
private final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
 
/**
* Ajout des mouvements de Stock
*
* @param rowOrigin SQLRow de la piece d'origine (ex : BL)
* @param eltTable SQLTable des éléments de la pièce (ex : element du BL)
* @param label label pour les mouvements de stocks
* @param entry true si c'est une entrée de stock
*
*/
public void createMouvement(SQLRow rowOrigin, SQLTable eltTable, StockLabel label, boolean entry) {
 
// On récupére les articles qui composent la piéce
SQLSelect selEltfact = new SQLSelect(rowOrigin.getTable().getBase());
selEltfact.addSelectStar(eltTable);
selEltfact.setWhere(new Where((SQLField) eltTable.getForeignKeys(rowOrigin.getTable()).toArray()[0], "=", rowOrigin.getID()));
 
List<SQLRow> lElt = SQLRowListRSH.execute(selEltfact);
 
final boolean modeAvance = DefaultNXProps.getInstance().getBooleanValue("ArticleModeVenteAvance", false);
SQLPreferences prefs = new SQLPreferences(eltTable.getDBRoot());
final boolean createArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
if (lElt != null) {
List<Integer> l = new ArrayList<Integer>();
for (SQLRow rowElt : lElt) {
SQLRow rowArticleAssocie = (rowElt.getTable().contains("ID_ARTICLE") ? rowElt.getForeign("ID_ARTICLE") : null);
 
int idArticle;
 
// Si on a bien sélectionné un article ou qu'il y a un code de saisi
if ((rowArticleAssocie != null && !rowArticleAssocie.isUndefined()) || rowElt.getString("CODE").trim().length() > 0) {
 
// Si l'article est à créer ou le lien est à refaire (ancienne version saisie
// sans ID_ARTICLE en BD)
if (rowArticleAssocie == null || rowArticleAssocie.isUndefined()) {
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(sqlTableArticle);
for (SQLField field : sqlTableArticle.getFields()) {
if (rowElt.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), rowElt.getObject(field.getName()));
}
}
// rowArticle.loadAllSafe(rowEltFact);
if (modeAvance)
idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, createArticle);
else {
idArticle = ReferenceArticleSQLElement.getIdForCN(rowArticle, createArticle);
}
if (idArticle > 0 && idArticle != sqlTableArticle.getUndefinedID()) {
SQLRowValues rowVals = rowElt.asRowValues();
rowVals.put("ID_ARTICLE", idArticle);
try {
rowVals.update();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
} else {
idArticle = rowArticleAssocie.getID();
}
 
// on crée un mouvement de stock pour chacun des articles
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
if (entry) {
rowVals.put("QTE", (rowElt.getInt("QTE")));
} else {
rowVals.put("QTE", -(rowElt.getInt("QTE")));
}
rowVals.put("NOM", label.getLabel(rowOrigin, rowElt));
rowVals.put("IDSOURCE", rowOrigin.getID());
rowVals.put("SOURCE", rowOrigin.getTable().getName());
rowVals.put("ID_ARTICLE", idArticle);
rowVals.put("DATE", rowOrigin.getObject("DATE"));
try {
SQLRow row = rowVals.insert();
l.add(row.getID());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
CollectionMap<SQLRow, List<SQLRowValues>> map = updateStock(l, false);
if (map.keySet().size() > 0) {
if (!rowOrigin.getTable().contains("ID_TARIF")) {
System.err.println("Attention la table " + rowOrigin.getTable().getName()
+ " ne contient pas le champ ID_TARIF. La création automatique d'une commande fournisseur est donc impossible!");
Thread.dumpStack();
} else {
if (JOptionPane.showConfirmDialog(null, "Certains articles sont en dessous du stock minimum.\n Voulez créer une commande?") == JOptionPane.YES_OPTION) {
MouvementStockSQLElement.createCommandeF(map, rowOrigin.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"));
}
}
}
}
}
 
/**
* Mise à jour des stocks ajoute la quantité si archive est à false
*
94,7 → 200,7
* @param id mouvement stock
* @param archive
*/
public static CollectionMap<SQLRow, List<SQLRowValues>> updateStock(List<Integer> ids, boolean archive) {
public CollectionMap<SQLRow, List<SQLRowValues>> updateStock(List<Integer> ids, boolean archive) {
CollectionMap<SQLRow, List<SQLRowValues>> map = new CollectionMap<SQLRow, List<SQLRowValues>>();
SQLTable tableCmdElt = Configuration.getInstance().getBase().getTable("COMMANDE_ELEMENT");
for (Integer id : ids) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/component/MouvementStockSQLComponent.java
108,7 → 108,7
@Override
public int insert(SQLRow order) {
int id = super.insert(order);
MouvementStockSQLElement.updateStock(Arrays.asList(id));
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(id), false);
return id;
}
 
115,9 → 115,9
@Override
public void update() {
int id = getSelectedID();
MouvementStockSQLElement.updateStock(Arrays.asList(id), true);
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(id), true);
super.update();
MouvementStockSQLElement.updateStock(Arrays.asList(id));
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(id), false);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/component/FournisseurSQLComponent.java
25,6 → 25,7
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.ElementSQLObject;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
309,6 → 310,34
c.anchor = GridBagConstraints.NORTHWEST;
this.add(panel, c);
 
// Compte charge par défaut
 
c.gridx = 0;
c.gridy++;
c.weightx = 1;
c.weighty = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
TitledSeparator sepCompteCharge = new TitledSeparator("Compte de charge par défaut");
this.add(sepCompteCharge, c);
 
JPanel panel2 = new JPanel(new GridBagLayout());
GridBagConstraints c3 = new DefaultGridBagConstraints();
 
panel2.add(new JLabel(getLabelFor("ID_COMPTE_PCE_CHARGE")), c3);
ISQLCompteSelector compteSelCharge = new ISQLCompteSelector(true);
c3.gridx++;
c3.weightx = 1;
panel2.add(compteSelCharge, c3);
addView(compteSelCharge, "ID_COMPTE_PCE_CHARGE");
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridy++;
c.gridx = 0;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.NORTHWEST;
this.add(panel2, c);
 
// INfos
c.gridx = 0;
c.gridy++;
416,6 → 445,20
System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
e.printStackTrace();
}
 
// Select Compte charge par defaut
final SQLTable tablePrefCompte = getTable().getTable("PREFS_COMPTE");
final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
// compte Achat
int idCompteAchat = rowPrefsCompte.getInt("ID_COMPTE_PCE_ACHAT");
if (idCompteAchat <= 1) {
try {
idCompteAchat = ComptePCESQLElement.getIdComptePceDefault("Achats");
} catch (Exception e) {
e.printStackTrace();
}
}
vals.put("ID_COMPTE_PCE_CHARGE", idCompteAchat);
return vals;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/action/ListeDesAvoirsFournisseurAction.java
13,12 → 13,21
package org.openconcerto.erp.core.supplychain.credit.action;
 
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.List;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.finance.accounting.ui.ListeGestCommEltPanel;
import org.openconcerto.erp.generationDoc.gestcomm.AvoirFournisseurXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import javax.swing.Action;
import javax.swing.JFrame;
31,10 → 40,37
}
 
public JFrame createFrame() {
final IListFrame frame = new IListFrame(new ListeGestCommEltPanel(Configuration.getInstance().getDirectory().getElement("AVOIR_FOURNISSEUR")));
SQLElement element = Configuration.getInstance().getDirectory().getElement("AVOIR_FOURNISSEUR");
ListeGestCommEltPanel panel = new ListeGestCommEltPanel(element);
 
List<SQLField> fields = new ArrayList<SQLField>(2);
fields.add(element.getTable().getField("MONTANT_HT"));
fields.add(element.getTable().getField("MONTANT_TTC"));
IListTotalPanel totalPanel = new IListTotalPanel(panel.getListe(), fields, "Total Global");
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.weightx = 0;
 
// Total panel
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
c.gridy = 4;
panel.add(totalPanel, c);
 
// Date panel
IListFilterDatePanel datePanel = new IListFilterDatePanel(panel.getListe(), element.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
panel.add(datePanel, c);
 
final IListFrame frame = new IListFrame(panel);
frame.getPanel().setAddVisible(true);
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(AvoirFournisseurXmlSheet.class).getRowActions());
frame.getPanel().getListe().setSQLEditable(false);
 
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/component/AvoirFournisseurSQLComponent.java
15,9 → 15,11
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.common.ui.MontantPanel;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.supplychain.credit.element.AvoirFournisseurSQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtAvoirFournisseur;
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.sql.Configuration;
40,6 → 42,8
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.util.Date;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
61,13 → 65,12
 
public void propertyChange(PropertyChangeEvent evt) {
 
int idSeleted = AvoirFournisseurSQLComponent.this.selectFournisseur.getValue().intValue();
SQLRow rowSelected = AvoirFournisseurSQLComponent.this.selectFournisseur.getSelectedRow();
 
if (idSeleted > 1) {
SQLElement fournisseur = Configuration.getInstance().getDirectory().getElement("FOURNISSEUR");
SQLRow rowFourn = fournisseur.getTable().getRow(idSeleted);
AvoirFournisseurSQLComponent.this.montantPanel.setUE(rowFourn.getBoolean("UE"));
int idModeRegl = rowFourn.getInt("ID_MODE_REGLEMENT");
if (rowSelected != null && !rowSelected.isUndefined()) {
rowSelected = rowSelected.asRow();
AvoirFournisseurSQLComponent.this.montantPanel.setUE(rowSelected.getBoolean("UE"));
int idModeRegl = rowSelected.getInt("ID_MODE_REGLEMENT");
 
if (idModeRegl > 1 && AvoirFournisseurSQLComponent.this.eltModeRegl != null) {
SQLElement sqlEltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
104,6 → 107,7
}
vals.put("ID_COMPTE_PCE", idCompteAchat);
vals.put("ID_TAXE", 2);
vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(AvoirFournisseurSQLElement.class, new Date()));
return vals;
}
 
278,6 → 282,24
 
id = super.insert(order);
 
final SQLTable tableNum = this.getTable().getBase().getTable("NUMEROTATION_AUTO");
final SQLRow row = getTable().getRow(id);
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(AvoirFournisseurSQLElement.class, row.getDate("DATE").getTime()).equalsIgnoreCase(this.textNumero.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(tableNum);
int val = tableNum.getRow(2).getInt("AVOIR_F_START");
val++;
rowVals.put("AVOIR_F_START", Integer.valueOf(val));
 
try {
rowVals.update(2);
} catch (SQLException e) {
 
e.printStackTrace();
}
}
 
GenerationMvtAvoirFournisseur gen = new GenerationMvtAvoirFournisseur(id);
gen.genereMouvement();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
36,6 → 36,7
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.DefaultGridBagConstraints;
77,6 → 78,9
private final JCheckBox checkVisu = new JCheckBox("Visualiser");
private final ITextArea infos = new ITextArea(3, 3);
private ElementComboBox fourn = new ElementComboBox();
final JCheckBox boxLivrClient = new JCheckBox("Livrer directement le client");
private DefaultElementSQLObject compAdr;
final JPanel panelAdrSpec = new JPanel(new GridBagLayout());
 
public CommandeSQLComponent() {
super(Configuration.getInstance().getDirectory().getElement("COMMANDE"));
135,7 → 139,9
c.gridx = 2;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(boxEnCours, c);
c.gridwidth = 1;
this.addRequiredSQLObject(boxEnCours, "EN_COURS");
}
 
173,6 → 179,7
}
// Adresse de livraison
if (getTable().getFieldsName().contains("ID_ADRESSE")) {
if (getTable().getFieldsName().contains("LIVRAISON_F")) {
c.gridx = 0;
c.gridy++;
c.weightx = 0;
180,7 → 187,7
this.add(new JLabel(getLabelFor("ID_ADRESSE")), c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridy++;
// c.gridy++;
this.addView("ID_ADRESSE");
final DefaultElementSQLObject comp = (DefaultElementSQLObject) this.getView("ID_ADRESSE").getComp();
 
213,9 → 220,104
c.gridy++;
this.add(comp, c);
this.add(this.getView("ID_ADRESSE").getComp(), c);
} else {
 
c.gridy++;
c.gridx = 0;
this.add(new JLabel("Livraison"), c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(boxLivrClient, c);
c.gridwidth = 1;
 
final GridBagConstraints cAdr = new DefaultGridBagConstraints();
 
panelAdrSpec.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), cAdr);
final ElementComboBox boxClient = new ElementComboBox(true);
cAdr.weightx = 1;
cAdr.gridx++;
panelAdrSpec.add(boxClient, cAdr);
this.addView(boxClient, "ID_CLIENT");
 
cAdr.gridy++;
cAdr.weightx = 0;
cAdr.gridx = 0;
panelAdrSpec.add(new JLabel("Adresse", SwingConstants.RIGHT), cAdr);
final SQLRequestComboBox boxAdr = new SQLRequestComboBox(true);
boxAdr.uiInit(Configuration.getInstance().getDirectory().getElement(getTable().getTable("ADRESSE")).getComboRequest(true));
boxClient.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (boxClient.getSelectedRow() != null && !boxClient.getSelectedRow().isUndefined()) {
Where w = new Where(boxAdr.getRequest().getPrimaryTable().getField("ID_CLIENT"), "=", boxClient.getSelectedRow().getID());
w = w.or(new Where(boxAdr.getRequest().getPrimaryTable().getKey(), "=", boxClient.getSelectedRow().getInt("ID_ADRESSE")));
w = w.or(new Where(boxAdr.getRequest().getPrimaryTable().getKey(), "=", boxClient.getSelectedRow().getInt("ID_ADRESSE_F")));
w = w.or(new Where(boxAdr.getRequest().getPrimaryTable().getKey(), "=", boxClient.getSelectedRow().getInt("ID_ADRESSE_L")));
boxAdr.getRequest().setWhere(w);
} else {
boxAdr.getRequest().setWhere(null);
}
}
});
cAdr.weightx = 1;
cAdr.gridx++;
panelAdrSpec.add(boxAdr, cAdr);
 
cAdr.gridx = 0;
cAdr.gridy++;
cAdr.weightx = 0;
if (getMode() == Mode.MODIFICATION) {
panelAdrSpec.add(new JLabel(getLabelFor("ID_ADRESSE")), cAdr);
}
cAdr.gridx++;
cAdr.gridwidth = GridBagConstraints.REMAINDER;
this.addView("ID_ADRESSE");
compAdr = (DefaultElementSQLObject) this.getView("ID_ADRESSE").getComp();
 
cAdr.gridy++;
if (getMode() == Mode.MODIFICATION) {
panelAdrSpec.add(compAdr, cAdr);
}
boxAdr.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
SQLRow row = boxAdr.getSelectedRow();
if (row != null && !row.isUndefined()) {
compAdr.setCreated(true);
SQLRowValues asRowValues = new SQLRowValues(row.asRowValues());
compAdr.setValue(asRowValues);
}
}
});
 
c.gridy++;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1;
this.add(panelAdrSpec, c);
c.gridwidth = 1;
c.weightx = 0;
 
boxLivrClient.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
panelAdrSpec.setVisible(boxLivrClient.isSelected());
 
if (!boxLivrClient.isSelected()) {
boxClient.setValue((Integer) null);
boxAdr.setValue((Integer) null);
compAdr.setCreated(false);
}
}
});
panelAdrSpec.setVisible(false);
}
}
c.gridwidth = 1;
 
// Champ Module
c.gridx = 0;
c.gridy++;
443,9 → 545,7
 
addRequiredSQLObject(fieldTTC, "T_TTC");
addRequiredSQLObject(fieldService, "T_SERVICE");
final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
this.table.getQteElement(), fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, this.table.getPrixServiceElement(), fieldDevise,
this.table.getTableElementTotalDevise(), poids, this.table.getPoidsTotalElement());
final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, null, null);
 
c.gridx++;
c.gridy--;
542,7 → 642,17
if (r != null) {
this.numeroUniqueCommande.setIdSelected(r.getID());
}
if (!getTable().contains("LIVRAISON_F") && r != null && !r.isUndefined()) {
 
SQLRowAccessor adr = r.getForeign("ID_ADRESSE");
boxLivrClient.setSelected(adr != null && !adr.isUndefined());
panelAdrSpec.setVisible(boxLivrClient.isSelected());
 
if (!boxLivrClient.isSelected()) {
compAdr.setCreated(false);
}
}
 
super.select(r);
if (r != null) {
this.table.insertFrom("ID_COMMANDE", r.getID());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/SaisieAchatSQLComponent.java
45,8 → 45,6
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
56,7 → 54,6
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
73,6 → 70,7
private JTextField textSource, textIdSource;
 
private DeviseField fieldMontantRegle = new DeviseField();
final ISQLCompteSelector compteSel = new ISQLCompteSelector();
 
private JCheckBox checkImmo;
// private JRadioButton radioButtonNumeroFacture;
81,22 → 79,25
private MontantPanel montant;
private ElementComboBox nomFournisseur;
private ElementComboBox comboAvoir;
private ElementSQLObject eltModeRegl;
protected ElementSQLObject eltModeRegl;
private int idFournSelect = 1;
private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
 
Integer idSeleted = SaisieAchatSQLComponent.this.nomFournisseur.getValue();
SQLRow rowFourn = SaisieAchatSQLComponent.this.nomFournisseur.getSelectedRow();
 
// System.err.println("Select Fournisseur " + idSeleted);
 
if (idSeleted != null && idSeleted > 1) {
SQLElement fournisseur = Configuration.getInstance().getDirectory().getElement("FOURNISSEUR");
SQLRow rowFourn = fournisseur.getTable().getRow(idSeleted);
if (!isFilling() && rowFourn != null && !rowFourn.isUndefined()) {
SaisieAchatSQLComponent.this.montant.setUE(rowFourn.getBoolean("UE"));
 
if (getSelectedID() <= 1 || SaisieAchatSQLComponent.this.idFournSelect != idSeleted) {
SQLRow rowCharge = rowFourn.getForeign("ID_COMPTE_PCE_CHARGE");
if (rowCharge != null && !rowCharge.isUndefined()) {
compteSel.setValue(rowCharge);
}
// if (getSelectedID() <= 1 || SaisieAchatSQLComponent.this.idFournSelect !=
// idSeleted) {
int idModeRegl = rowFourn.getInt("ID_MODE_REGLEMENT");
if (idModeRegl > 1 && SaisieAchatSQLComponent.this.eltModeRegl != null && getMode() == Mode.INSERTION) {
SQLElement sqlEltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
106,10 → 107,10
SaisieAchatSQLComponent.this.eltModeRegl.setValue(rowVals);
System.err.println("Select Mode regl " + idModeRegl);
}
// }
}
// / SaisieAchatSQLComponent.this.idFournSelect = (idSeleted == null) ? 1 : idSeleted;
}
SaisieAchatSQLComponent.this.idFournSelect = (idSeleted == null) ? 1 : idSeleted;
}
 
};
 
178,8 → 179,8
c.weightx = 0;
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
final ISQLCompteSelector compteSel = new ISQLCompteSelector();
this.add(new JLabel(getLabelFor("ID_COMPTE_PCE")), c);
c.gridwidth = 1;
this.add(new JLabel(getLabelFor("ID_COMPTE_PCE"), SwingConstants.RIGHT), c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx++;
c.weightx = 1;
195,13 → 196,13
// SaisieAchatSQLComponent.this.textNumeroCmd.setEnabled(false);
// }
// });
c.fill = GridBagConstraints.NONE;
 
c.weightx = 0;
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
// this.add(this.radioButtonNumeroFacture, c);
this.add(new JLabel(getLabelFor("NUMERO_FACTURE")), c);
this.add(new JLabel(getLabelFor("NUMERO_FACTURE"), SwingConstants.RIGHT), c);
 
this.textNumeroFacture = new JTextField(16);
DefaultGridBagConstraints.lockMinimumSize(textNumeroFacture);
234,9 → 235,10
// });
c.gridx = 0;
c.gridy++;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
// this.add(this.radioButtonNumeroCmd, c);
this.add(new JLabel(getLabelFor("NUMERO_COMMANDE")), c);
this.add(new JLabel(getLabelFor("NUMERO_COMMANDE"), SwingConstants.RIGHT), c);
 
this.textNumeroCmd = new JTextField(16);
c.gridx = 1;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesClientAction.java
14,11 → 14,14
package org.openconcerto.erp.core.supplychain.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.order.ui.CommandeClientRenderer;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
35,10 → 38,7
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
 
public class ListeDesCommandesClientAction extends CreateFrameAbstractAction {
 
48,7 → 48,8
}
 
public JFrame createFrame() {
final IListFrame frame = new IListFrame(new ListeAddPanel(Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT")) {
SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
ListeAddPanel listeAddPanel = new ListeAddPanel(eltCmd, new IListe(eltCmd.getTableSource(true))) {
@Override
protected GridBagConstraints createConstraints() {
// TODO Auto-generated method stub
56,23 → 57,46
c.gridy++;
return c;
}
});
};
 
final CommandeClientRenderer rend = CommandeClientRenderer.getInstance();
List<SQLField> fields = new ArrayList<SQLField>(2);
fields.add(eltCmd.getTable().getField("T_HT"));
// fields.add(eltCmd.getTable().getField("T_TTC"));
IListTotalPanel totalPanel = new IListTotalPanel(listeAddPanel.getListe(), fields, "Total Global");
 
GridBagConstraints c = new DefaultGridBagConstraints();
final JPanel legendePanel = rend.getLegendePanel();
legendePanel.setBorder(BorderFactory.createTitledBorder("Légende"));
legendePanel.setOpaque(true);
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
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) ==
// BigInteger.class) {
table.getColumnModel().getColumn(i).setCellRenderer(rend);
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
c.gridy = 4;
 
listeAddPanel.add(totalPanel, c);
 
// Date panel
IListFilterDatePanel datePanel = new IListFilterDatePanel(listeAddPanel.getListe(), eltCmd.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
listeAddPanel.add(datePanel, c);
 
final IListFrame frame = new IListFrame(listeAddPanel);
 
// FIXME Probleme avec le renderer
// final CommandeClientRenderer rend = CommandeClientRenderer.getInstance();
// c = new DefaultGridBagConstraints();
// final JPanel legendePanel = rend.getLegendePanel();
// legendePanel.setBorder(BorderFactory.createTitledBorder("Légende"));
// legendePanel.setOpaque(true);
// c.fill = GridBagConstraints.NONE;
// 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) ==
// // BigInteger.class) {
// table.getColumnModel().getColumn(i).setCellRenderer(rend);
// // }
// }
}
 
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(CommandeClientXmlSheet.class) {
@Override
111,6 → 135,8
}
}.getRowActions());
 
datePanel.setFilterOnDefault();
 
return frame;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesAction.java
55,18 → 55,8
 
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
// Transfert vers facture
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction("Transfert vers facture") {
public void actionPerformed(ActionEvent e) {
transfertFactureFournisseur(IListe.get(e).getSelectedRow());
}
}, false);
 
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
List<RowAction> l = new ArrayList<RowAction>();
l.add(bonAction);
l.add(factureAction);
return l;
}
}.getRowActions());
84,14 → 74,4
elt.transfertBR(row.getID());
}
 
/**
* Transfert en Facture
*
* @param row
*/
private void transfertFactureFournisseur(SQLRow row) {
CommandeSQLElement elt = (CommandeSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE");
elt.transfertFacture(row.getID());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeSaisieAchatAction.java
14,10 → 14,21
package org.openconcerto.erp.core.supplychain.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.finance.accounting.ui.ListeGestCommEltPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
29,10 → 40,28
}
 
public JFrame createFrame() {
ListeGestCommEltPanel panel = new ListeGestCommEltPanel(Configuration.getInstance().getDirectory().getElement("SAISIE_ACHAT"));
SQLElement element = Configuration.getInstance().getDirectory().getElement("SAISIE_ACHAT");
ListeGestCommEltPanel panel = new ListeGestCommEltPanel(element);
panel.setAddVisible(true);
IListFrame frame = new IListFrame(panel);
IListTotalPanel total = new IListTotalPanel(frame.getPanel().getListe(), Arrays.asList(element.getTable().getField("MONTANT_HT"), element.getTable().getField("MONTANT_TTC")));
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridy = 3;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
frame.getPanel().add(total, c);
 
// Date panel
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(frame.getPanel().getListe(), element.getTable().getField("DATE"));
 
IListFilterDatePanel datePanel = new IListFilterDatePanel(map, IListFilterDatePanel.getDefaultMap());
c.gridy = 4;
c.anchor = GridBagConstraints.CENTER;
c.weighty = 0;
datePanel.setFilterOnDefault();
frame.getPanel().add(datePanel, c);
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
21,10 → 21,10
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.ui.BonReceptionItemTable;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
51,7 → 51,6
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
 
import javax.swing.JLabel;
85,6 → 84,7
@Override
protected SQLRowValues createDefaults() {
this.tableBonItem.getModel().clearRows();
this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(BonReceptionSQLElement.class));
return super.createDefaults();
}
 
307,7 → 307,6
c.fill = GridBagConstraints.BOTH;
final ITextArea textInfos = new ITextArea(4, 4);
JScrollPane scrollPane = new JScrollPane(textInfos);
textInfos.setBorder(null);
DefaultGridBagConstraints.lockMinimumSize(scrollPane);
 
this.add(textInfos, c);
534,48 → 533,22
}
}
 
protected String getLibelleStock(SQLRow row, SQLRow rowElt) {
return "Bon de réception N°" + row.getString("NUMERO");
}
 
/**
* Mise à jour des stocks pour chaque article composant du bon
*/
private void updateStock(int id) {
MouvementStockSQLElement mvtStock = (MouvementStockSQLElement) Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
mvtStock.createMouvement(getTable().getRow(id), getTable().getTable("BON_RECEPTION_ELEMENT"), new StockLabel() {
@Override
public String getLabel(SQLRow rowOrigin, SQLRow rowElt) {
 
SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
SQLTable sqlTableBonElt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("BON_RECEPTION_ELEMENT");
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
SQLRow row = getTable().getRow(id);
 
// On récupére les articles qui composent la facture
List<SQLRow> elts = row.getReferentRows(sqlTableBonElt);
 
for (SQLRow rowElt : elts) {
 
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (SQLField field : eltArticle.getTable().getFields()) {
if (rowElt.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), rowElt.getObject(field.getName()));
return getLibelleStock(rowOrigin, rowElt);
}
}
// rowArticle.loadAllSafe(rowEltFact);
int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
}, true);
 
// on crée un mouvement de stock pour chacun des articles
SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
rowVals.put("QTE", rowElt.getInt("QTE"));
rowVals.put("NOM", "Bon de réception N°" + row.getString("NUMERO"));
rowVals.put("IDSOURCE", id);
rowVals.put("SOURCE", getTable().getName());
rowVals.put("ID_ARTICLE", idArticle);
rowVals.put("DATE", row.getObject("DATE"));
try {
SQLRow rowInsert = rowVals.insert();
MouvementStockSQLElement.updateStock(Arrays.asList(rowInsert.getID()));
} catch (SQLException e) {
e.printStackTrace();
}
 
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheetXML.java
New file
0,0 → 1,668
/*
* 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.finance.accounting.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.cc.ITransformer;
 
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
public class GrandLivreSheetXML extends AbstractListeSheetXml {
 
private static int debutFill, endFill;
public static int MODEALL = 1;
public static int MODELETTREE = 2;
public static int MODENONLETTREE = 3;
private final static SQLTable tableEcriture = base.getTable("ECRITURE");
private final static SQLTable tableJournal = base.getTable("JOURNAL");
private final static SQLTable tableMvt = base.getTable("MOUVEMENT");
private final static SQLTable tableCompte = base.getTable("COMPTE_PCE");
 
private final static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
private final static DateFormat dateFormatEcr = DateFormat.getDateInstance(DateFormat.SHORT);
private SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
 
private Date dateDu, dateAu;
private String compteDeb, compteEnd;
private int lettrage;
private boolean cumul = false;
private boolean excludeCompteSolde = true;
private boolean centralClient = false;
private boolean centralFourn = false;
int idJrnlExclude = -1;
 
public static String TEMPLATE_ID = "GrandLivre";
public static String TEMPLATE_PROPERTY_NAME = "LocationGrandLivre";
 
public static void setSize(int debut, int fin) {
debutFill = debut;
endFill = fin;
}
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
Date date;
 
@Override
public String getName() {
if (this.date == null) {
this.date = new Date();
}
return "GrandLivre" + date.getTime();
}
 
public GrandLivreSheetXML(Date du, Date au, String compteDep, String compteEnd, int lettrage, boolean cumul, boolean excludeCptSolde, boolean centralClient, boolean centralFourn, int idJrnlExclude) {
super();
Calendar cal = Calendar.getInstance();
cal.setTime(au);
this.idJrnlExclude = idJrnlExclude;
this.printer = PrinterNXProps.getInstance().getStringProperty("GrandLivrePrinter");
this.dateAu = au;
this.dateDu = du;
this.compteDeb = compteDep.trim();
this.compteEnd = compteEnd.trim();
this.lettrage = lettrage;
this.cumul = cumul;
this.excludeCompteSolde = excludeCptSolde;
this.centralClient = centralClient;
this.centralFourn = centralFourn;
 
// createMap();
}
 
private String toDay = dateFormat.format(new Date());
private int size;
 
// private void makeEntete(int rowDeb) {
//
// this.mCell.put("A" + rowDeb, this.rowSociete.getObject("NOM"));
// this.mCell.put("G" + rowDeb, "Edition du " + this.toDay);
// // this.mCell.put("D" + (rowDeb + 2), "Grand livre");
// // System.err.println("MAKE ENTETE");
// }
//
// private void makePiedPage(int row, String comptes) {
// this.mCell.put("A" + row, "Compte : " + comptes);
// this.mCell.put("E" + row, "Période du " + dateFormatEcr.format(this.dateDu) + " au " +
// dateFormatEcr.format(this.dateAu));
// }
 
private void makeSousTotal(Map<String, Object> line, Map<Integer, String> style, int pos, long debit, long credit) {
style.put(pos, "Titre 1");
 
line.put("DATE", "");
line.put("JOURNAL", "");
line.put("MOUVEMENT", "");
line.put("LIBELLE", "Sous total");
line.put("DEBIT", Double.valueOf(GestionDevise.currencyToString(debit, false)));
line.put("CREDIT", Double.valueOf(GestionDevise.currencyToString(credit, false)));
line.put("SOLDE", Double.valueOf(GestionDevise.currencyToString(debit - credit, false)));
}
 
protected void createListeValues() {
Date d = new Date();
 
final SQLRowValues vals = new SQLRowValues(tableEcriture);
vals.put("ID_COMPTE_PCE", null);
vals.put("COMPTE_NUMERO", null);
vals.put("COMPTE_NOM", null);
vals.put("ID_JOURNAL", null);
vals.put("JOURNAL_CODE", null);
vals.putRowValues("ID_MOUVEMENT").put("NUMERO", null);
vals.put("CREDIT", null);
vals.put("DEBIT", null);
vals.put("DATE", null);
vals.put("NOM", null);
 
final List<Integer> lCompteSolde;
if (GrandLivreSheetXML.this.excludeCompteSolde) {
lCompteSolde = getListeCompteSolde();
} else {
lCompteSolde = null;
}
Map<Integer, Long> mapCumul = getCumulsAnterieur(GrandLivreSheetXML.this.dateDu, lCompteSolde);
 
final SQLRowValuesListFetcher fetcher = new SQLRowValuesListFetcher(vals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect sel) {
 
Where w = (new Where(tableEcriture.getField("DATE"), GrandLivreSheetXML.this.dateDu, GrandLivreSheetXML.this.dateAu));
 
if (GrandLivreSheetXML.this.compteDeb.equals(GrandLivreSheetXML.this.compteEnd)) {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "=", GrandLivreSheetXML.this.compteDeb));
} else {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), (Object) GrandLivreSheetXML.this.compteDeb, (Object) GrandLivreSheetXML.this.compteEnd));
}
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
w = w.and(new Where(tableEcriture.getField("ID_MOUVEMENT"), "=", tableMvt.getField("ID")));
 
if (GrandLivreSheetXML.this.lettrage == MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
} else {
if (GrandLivreSheetXML.this.lettrage == MODENONLETTREE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
}
}
 
if (GrandLivreSheetXML.this.excludeCompteSolde) {
System.err.println("Exclude compte");
 
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), lCompteSolde).not());
}
 
if (!UserManager.getInstance().getCurrentUser().getRights().haveRight(ComptaUserRight.ACCES_NOT_RESCTRICTED_TO_411)) {
// TODO Show Restricted acces in UI
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "LIKE", "411%"));
}
 
sel.setWhere(w);
sel.addRawOrder("\"ECRITURE\".\"COMPTE_NUMERO\"");
sel.addRawOrder("\"ECRITURE\".\"DATE\"");
sel.addRawOrder("\"MOUVEMENT\".\"NUMERO\"");
System.err.println(sel.asString());
return sel;
}
});
 
List<SQLRowValues> list = fetcher.fetch();
size = list.size();
System.err.println("START CREATE Grand livre, NB ecritures " + size);
 
long totalDebit, totalCredit, sousTotalDebit, sousTotalCredit, totalCreditAntC, totalDebitAntC, totalCreditAntF, totalDebitAntF;
 
totalDebit = 0;
totalCredit = 0;
sousTotalCredit = 0;
sousTotalDebit = 0;
totalCreditAntC = 0;
totalDebitAntC = 0;
totalCreditAntF = 0;
totalDebitAntF = 0;
SQLRowValues rowFirstEcr = null;
int idCptFirstEcr = 1;
 
boolean setTitle = true;
boolean setLine = false;
boolean setCumuls = true;
boolean firstEcrCentC = true;
boolean firstEcrCentF = true;
String numCptFirstEcr = "411";
String numCptClient = "411";
String nomCptClient = "Clients";
String numCptFourn = "401";
String nomCptFourn = "Fournisseurs";
int idCptClient = ComptePCESQLElement.getId(numCptClient, nomCptClient);
int idCptFourn = ComptePCESQLElement.getId(numCptFourn, nomCptFourn);
 
final String titre3 = "Titre 3";
final String cumulAntString = "Cumuls antérieurs";
// int j = 0;
 
// Valeur de la liste
// listAllSheetValues ;
 
// Style des lignes
// styleAllSheetValues;
 
// Valeur à l'extérieur de la liste
// mapAllSheetValues
 
List<Map<String, Object>> tableauVals = new ArrayList<Map<String, Object>>();
this.listAllSheetValues.put(0, tableauVals);
 
Map<Integer, String> style = new HashMap<Integer, String>();
this.styleAllSheetValues.put(0, style);
 
// Affiche le nom du compte
setTitle = true;
// ligne vide avant de mettre le setTitle
setLine = false;
for (int i = 0; i < size;) {
// System.err.println(i);
// // System.err.println("START NEW PAGE; POS : " + posLine);
//
// /***************************************************************************************
// * ENTETE
// **************************************************************************************/
// // makeEntete(posLine);
// // posLine += debutFill - 1;
 
/***************************************************************************************
* CONTENU
**************************************************************************************/
final Double doubleZero = Double.valueOf("0");
 
SQLRowValues rowEcr = list.get(i);
 
int idCpt = rowEcr.getInt("ID_COMPTE_PCE");
String nomCpt = rowEcr.getString("COMPTE_NOM");
String numCpt = rowEcr.getString("COMPTE_NUMERO");
 
Map<String, Object> ooLine = new HashMap<String, Object>();
tableauVals.add(ooLine);
// Cumuls antérieurs
if (setCumuls && this.cumul && !setTitle) {
 
style.put(tableauVals.size(), titre3);
ooLine.put("DATE", "");
ooLine.put("JOURNAL", "");
ooLine.put("MOUVEMENT", "");
 
ooLine.put("LIBELLE", cumulAntString);
Long longSolde = mapCumul.get(idCpt);
 
if (longSolde == null) {
longSolde = Long.valueOf(0);
}
long debitCumulAnt = 0;
long creditCumulAnt = 0;
 
if (longSolde > 0) {
debitCumulAnt = longSolde;
} else {
creditCumulAnt = -longSolde;
}
ooLine.put("DEBIT", (debitCumulAnt == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(debitCumulAnt, false)));
ooLine.put("CREDIT", (creditCumulAnt == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(creditCumulAnt, false)));
ooLine.put("SOLDE", (longSolde == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(longSolde, false)));
 
totalCredit += creditCumulAnt;
totalDebit += debitCumulAnt;
 
sousTotalCredit += creditCumulAnt;
sousTotalDebit += debitCumulAnt;
setCumuls = false;
} else {
// Titre
if (setTitle) {
if (!setLine) {
style.put(tableauVals.size() - 1, "Titre 1");
 
// Si on centralise les comptes clients ou fournisseurs on affiche le
// compte 401 ou 411
if (this.centralClient && nomCpt.startsWith("411")) {
nomCpt = nomCptClient;
numCpt = numCptClient;
idCpt = idCptClient;
}
if (this.centralFourn && nomCpt.startsWith("401")) {
nomCpt = nomCptFourn;
numCpt = numCptFourn;
idCpt = idCptFourn;
}
ooLine.put("DATE", numCpt);
ooLine.put("JOURNAL", nomCpt);
ooLine.put("MOUVEMENT", "");
ooLine.put("LIBELLE", "");
ooLine.put("DEBIT", "");
ooLine.put("CREDIT", "");
ooLine.put("SOLDE", "");
setTitle = false;
setLine = true;
 
if (rowFirstEcr == null) {
rowFirstEcr = rowEcr;
idCptFirstEcr = rowEcr.getInt("ID_COMPTE_PCE");
numCptFirstEcr = rowEcr.getString("COMPTE_NUMERO");
}
 
} else {
style.put(tableauVals.size() - 1, "Normal");
setLine = false;
}
} else {
 
// si on change de compte alors on applique le style Titre 1
if (rowFirstEcr != null && idCptFirstEcr != idCpt && (!this.centralFourn || (!(numCptFirstEcr.startsWith("401") && numCpt.startsWith("401"))))
&& (!this.centralClient || (!(numCptFirstEcr.startsWith("411") && numCpt.startsWith("411"))))) {
 
rowFirstEcr = rowEcr;
idCptFirstEcr = rowFirstEcr.getInt("ID_COMPTE_PCE");
numCptFirstEcr = rowEcr.getString("COMPTE_NUMERO");
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sousTotalCredit = 0;
sousTotalDebit = 0;
setTitle = true;
setCumuls = true;
} else {
long cred = rowEcr.getLong("CREDIT");
long deb = rowEcr.getLong("DEBIT");
// Centralisation fournisseur
if (this.centralFourn && numCpt.startsWith("401")) {
i++;
 
if (firstEcrCentF) {
// posLine++;
ooLine.put("LIBELLE", "Centralisation des comptes fournisseurs");
style.put(tableauVals.size() - 1, "Normal");
firstEcrCentF = false;
}
 
totalCreditAntF += cred;
totalDebitAntF += deb;
sousTotalCredit += cred;
sousTotalDebit += deb;
long solde = totalDebitAntF - totalCreditAntF;
ooLine.put("DEBIT", (totalDebitAntF == 0) ? doubleZero : new Double(GestionDevise.currencyToString(totalDebitAntF, false)));
ooLine.put("CREDIT", (totalCreditAntF == 0) ? doubleZero : new Double(GestionDevise.currencyToString(totalCreditAntF, false)));
ooLine.put("SOLDE", (solde == 0) ? doubleZero : new Double(GestionDevise.currencyToString(solde, false)));
 
continue;
}
// Centralisation client
if (this.centralClient && numCpt.startsWith("411")) {
i++;
if (firstEcrCentC) {
// posLine++;
ooLine.put("LIBELLE", "Centralisation des comptes clients");
style.put(tableauVals.size() - 1, "Normal");
firstEcrCentC = false;
}
 
totalCreditAntC += cred;
totalDebitAntC += deb;
sousTotalCredit += cred;
sousTotalDebit += deb;
long solde = totalDebitAntC - totalCreditAntC;
ooLine.put("DEBIT", (totalDebitAntC == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(totalDebitAntC, false)));
ooLine.put("CREDIT", (totalCreditAntC == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(totalCreditAntC, false)));
ooLine.put("SOLDE", (solde == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(solde, false)));
 
continue;
}
 
ooLine.put("DATE", dateFormatEcr.format((Date) rowEcr.getObject("DATE")));
 
ooLine.put("JOURNAL", rowEcr.getString("JOURNAL_CODE"));
ooLine.put("MOUVEMENT", rowEcr.getForeign("ID_MOUVEMENT").getObject("NUMERO"));
ooLine.put("LIBELLE", rowEcr.getObject("NOM"));
 
totalCredit += cred;
totalDebit += deb;
 
sousTotalCredit += cred;
sousTotalDebit += deb;
long solde = sousTotalDebit - sousTotalCredit;
 
ooLine.put("DEBIT", (deb == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(deb, false)));
ooLine.put("CREDIT", (cred == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(cred, false)));
ooLine.put("SOLDE", (solde == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(solde, false)));
 
style.put(tableauVals.size() - 1, "Normal");
i++;
}
 
}
 
}
 
// if (i >= size && j < endFill - debutFill + 1) {
// makeSousTotal(posLine, sousTotalDebit, sousTotalCredit);
// }
//
// posLine = firstLine + endFill;
/*
* if (this.mapStyleRow.get(new Integer(posLine - 1)) != null) {
* this.mapStyleRow.put(new Integer(posLine - 1), "Titre 2"); }
*/
 
// Total
// this.mCell.put("E" + posLine, (totalDebit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalDebit, false)));
// this.mCell.put("F" + posLine, (totalCredit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalCredit, false)));
// this.mCell.put("G" + posLine, (totalDebit - totalCredit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalDebit - totalCredit, false)));
//
// posLine += 2;
//
// // bas de page
// makePiedPage(posLine, this.compteDeb + " à " + this.compteEnd);
//
// posLine++;
// firstLine = posLine;
// this.nbPage++;
//
// if (i >= size && j >= (endFill - debutFill + 1)) {
//
// makeEntete(posLine);
// posLine += debutFill - 1;
// makeSousTotal(posLine, sousTotalDebit, sousTotalCredit);
// this.nbPage++;
// }
 
}
 
// Total
// this.mCell.put("E" + posLine, (totalDebit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalDebit, false)));
// this.mCell.put("F" + posLine, (totalCredit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalCredit, false)));
// this.mCell.put("G" + posLine, (totalDebit - totalCredit == 0) ? doubleZero : new
// Double(GestionDevise.currencyToString(totalDebit - totalCredit, false)));
Map<String, Object> sheetVals = new HashMap<String, Object>();
this.mapAllSheetValues.put(0, sheetVals);
 
if (size > 0) {
Map<String, Object> ooLine = new HashMap<String, Object>();
tableauVals.add(ooLine);
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sheetVals.put("TOTAL_DEBIT", (totalDebit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit, false)));
sheetVals.put("TOTAL_CREDIT", (totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalCredit, false)));
sheetVals.put("TOTAL_SOLDE", (totalDebit - totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false)));
}
 
sheetVals.put("TITRE_1", "GRAND LIVRE " + this.rowSociete.getString("TYPE") + " " + this.rowSociete.getString("NOM"));
sheetVals.put("DATE_EDITION", new Date());
sheetVals.put("TITRE_2", "Compte : " + this.compteDeb + " à " + this.compteEnd + ". Période du " + dateFormatEcr.format(this.dateDu) + " au " + dateFormatEcr.format(this.dateAu) + ".");
// on conserve la page d'origine du model
// if (this.nbPage > 0) {
// this.nbPage--;
// }
 
Date end = new Date();
System.err.println("///////// TAKE " + (end.getTime() - d.getTime()) + " millisecondes TO CREATE MAP");
}
 
private List<Integer> getListeCompteSolde() {
SQLSelect sel = new SQLSelect(base);
 
sel.addSelect(tableCompte.getField("ID"));
sel.addSelect(tableEcriture.getField("DEBIT"), "SUM");
sel.addSelect(tableEcriture.getField("CREDIT"), "SUM");
 
Where w;
if (this.compteDeb.equals(this.compteEnd)) {
w = new Where(tableCompte.getField("NUMERO"), "=", this.compteDeb);
} else {
w = new Where(tableCompte.getField("NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd);
}
 
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), "=", tableCompte.getField("ID")));
 
if (this.cumul) {
w = w.and(new Where(tableEcriture.getField("DATE"), "<=", this.dateAu));
} else {
w = w.and(new Where(tableEcriture.getField("DATE"), this.dateDu, this.dateAu));
}
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
if (this.lettrage == MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
} else {
if (this.lettrage == MODENONLETTREE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
 
}
}
 
sel.setWhere(w);
 
String req = sel.asString() + " GROUP BY \"COMPTE_PCE\".\"ID\"";
System.err.println(req);
List<Object[]> l = (List) base.getDataSource().execute(req, new ArrayListHandler());
List<Integer> list = new ArrayList<Integer>();
for (Object[] o : l) {
long credit = 0;
if (o[2] != null) {
credit = Long.valueOf(o[2].toString());
}
 
long debit = 0;
if (o[1] != null) {
debit = Long.valueOf(o[1].toString());
}
 
int id = Integer.valueOf(o[0].toString());
long solde = debit - credit;
if (solde == 0) {
list.add(id);
}
}
return list;
}
 
/**
* @param d date limite des cumuls
* @return Map<Integer id compte, Long solde(debit-credit)>
*/
private Map<Integer, Long> getCumulsAnterieur(Date d, List<Integer> listCompteSolde) {
SQLSelect sel = new SQLSelect(base);
 
sel.addSelect(tableEcriture.getField("ID_COMPTE_PCE"));
sel.addSelect(tableEcriture.getField("DEBIT"), "SUM");
sel.addSelect(tableEcriture.getField("CREDIT"), "SUM");
sel.addSelect(tableEcriture.getField("COMPTE_NUMERO"));
// sel.addSelect(tableEcriture.getField("ID_MOUVEMENT"));
Where w = (new Where(tableEcriture.getField("DATE"), "<", d));
w = w.and(new Where(tableEcriture.getField("ID_MOUVEMENT"), "=", tableMvt.getKey()));
 
if (this.compteDeb.equals(this.compteEnd)) {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "=", this.compteDeb));
} else {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd));
}
 
if (this.lettrage == MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
} else {
if (this.lettrage == MODENONLETTREE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
}
}
 
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), "=", tableCompte.getField("ID")));
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
if (listCompteSolde != null) {
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), listCompteSolde).not());
}
 
sel.setWhere(w);
 
String req = sel.asString() + " GROUP BY \"ECRITURE\".\"ID_COMPTE_PCE\", \"ECRITURE\".\"COMPTE_NUMERO\"";
System.err.println(req);
List<Object[]> l = (List) base.getDataSource().execute(req, new ArrayListHandler());
Map<Integer, Long> map = new HashMap<Integer, Long>();
 
int idCptFourn = ComptePCESQLElement.getId("401", "Fournisseurs");
int idCptClient = ComptePCESQLElement.getId("411", "Clients");
 
for (Object[] o : l) {
 
long credit = 0;
if (o[2] != null) {
credit = Long.valueOf(o[2].toString());
}
 
long debit = 0;
if (o[1] != null) {
debit = Long.valueOf(o[1].toString());
}
 
int id = Integer.valueOf(o[0].toString());
long solde = debit - credit;
map.put(id, solde);
if (o[3] != null) {
String numero = o[3].toString();
if (this.centralFourn && numero.startsWith("401")) {
Long lS = map.get(idCptFourn);
if (lS != null) {
lS += solde;
} else {
lS = new Long(solde);
}
map.put(idCptFourn, lS);
}
if (this.centralClient && numero.startsWith("411")) {
Long lS = map.get(idCptClient);
if (lS != null) {
lS += solde;
} else {
lS = new Long(solde);
}
map.put(idCptClient, lS);
}
}
}
 
return map;
}
 
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
public int getSize() {
return size;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ComptaPrefTreeNode.java
25,6 → 25,7
import org.openconcerto.erp.preferences.GenerationDocumentComptaPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocumentGestCommPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocumentPayePreferencePanel;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.erp.preferences.ImpressionGestCommPreferencePanel;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.erp.preferences.NumerotationPreferencePanel;
103,6 → 104,8
final PrefTreeNode nNum = new PrefTreeNode(NumerotationPreferencePanel.class, "Numérotation", new String[] { "numérotation" });
nsGlobale.add(nNum);
 
nsGlobale.add(new PrefTreeNode(GestionArticleGlobalPreferencePanel.class, "Gestion des articles", new String[] { "articles", "stock" }));
 
nsGlobale.add(new PrefTreeNode(GenerationDocGlobalPreferencePanel.class, "Génération des Documents", new String[] { "documents" }));
 
// Impression
118,7 → 121,7
 
// Emplacement des modéles
final PrefTreeNode nGeneration = new PrefTreeNode(EmptyPreferencePanel.class, "Génération des documents", new String[] { "générations", "document" });
final PrefTreeNode nLocModele = new PrefTreeNode(TemplatePreferencePanel.class, "Emplacement des modèles", new String[] { "destination" });
final PrefTreeNode nLocModele = new PrefTreeNode(TemplatePreferencePanel.class, "Modèles", new String[] { "destination", "modèle", "modele" });
nGeneration.add(nLocModele);
 
// Destination des documents générés
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/PlanComptableGPanel.java
231,19 → 231,18
this.add(split, c);
}
 
// TODO from UCDetector: Change visibility of Method "PlanComptableGPanel.creerJTable(ClasseCompte)" to private
// TODO from UCDetector: Change visibility of Method
// "PlanComptableGPanel.creerJTable(ClasseCompte)" to private
public JTable creerJTable(ClasseCompte ccTmp) { // NO_UCD
 
final PlanComptableGModel model;
if (this.radioCompteDeveloppe.isSelected()) {
model = new PlanComptableGModel(ccTmp, 3);
} else {
if (this.radioCompteAbrege.isSelected()) {
} else if (this.radioCompteAbrege.isSelected()) {
model = new PlanComptableGModel(ccTmp, 2);
} else {
model = new PlanComptableGModel(ccTmp, 1);
}
}
 
final JTable table = new JTable(model) {
public JToolTip createToolTip() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImpressionGrandLivrePanel.java
14,8 → 14,9
package org.openconcerto.erp.core.finance.accounting.ui;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.finance.accounting.report.GrandLivreSheet;
import org.openconcerto.erp.generationDoc.SpreadSheetGeneratorCompta;
import org.openconcerto.erp.core.finance.accounting.report.GrandLivreSheetXML;
import org.openconcerto.erp.generationDoc.SpreadSheetGeneratorListener;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
25,7 → 26,6
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
 
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
33,11 → 33,10
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;
 
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
254,27 → 253,45
bar.setValue(1);
new Thread(new Runnable() {
public void run() {
GrandLivreSheet bSheet = new GrandLivreSheet(dateDeb.getDate(), dateEnd.getDate(), compteDeb.getText().trim(), compteEnd.getText().trim(), mode, boxCumulsAnts.isSelected(),
!boxCompteSolde.isSelected(), boxCentralClient.isSelected(), boxCentralFourn.isSelected(), comboJrnl.getSelectedId());
final GrandLivreSheetXML bSheet = new GrandLivreSheetXML(dateDeb.getDate(), dateEnd.getDate(), compteDeb.getText().trim(), compteEnd.getText().trim(), mode, boxCumulsAnts
.isSelected(), !boxCompteSolde.isSelected(), boxCentralClient.isSelected(), boxCentralFourn.isSelected(), comboJrnl.getSelectedId());
try {
bSheet.createDocument();
 
if (bSheet.getSize() == 0) {
JOptionPane.showMessageDialog(ImpressionGrandLivrePanel.this, "Aucune écriture trouvée");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
taskEnd();
}
});
 
} else {
final SpreadSheetGeneratorCompta generator = new SpreadSheetGeneratorCompta(bSheet, "GrandLivre" + Calendar.getInstance().getTimeInMillis(), checkImpr.isSelected(),
checkVisu.isSelected(), false);
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bar.setValue(2);
generator.addGenerateListener(ImpressionGrandLivrePanel.this);
// bSheet.showPrintAndExport(false, false, true, true);
 
}
});
 
try {
// bSheet.getOrCreatePDFDocumentFile(true);
bSheet.getOrCreatePDFDocumentFile(true, true);
Gestion.openPDF(bSheet.getGeneratedPDFFile());
} catch (Exception exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
 
} catch (InterruptedException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
} catch (ExecutionException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
} finally {
 
taskEnd();
}
}
}).start();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/model/PlanComptableGModel.java
35,17 → 35,18
 
public class PlanComptableGModel extends AbstractTableModel {
 
private Vector titres = new Vector();
private Vector comptes = new Vector();
private Vector<String> titres = new Vector<String>();
private Vector<Compte> comptes = new Vector<Compte>();
 
// Compte ID - Vecteur compte index
private Map mapCompte = new HashMap();
private Map<Integer, Integer> mapCompte = new HashMap<Integer, Integer>();
 
/**
* Permet d'afficher le plan comptable général d'une classe
*
* @param classeDuCompte classe de compte à afficher
* @param typePlan type de plan 1 : base, 2 : abrégé, 3 : developpé
* @param typePlan type de plan 1 : base, 2 : abrégé, 3 : developpé (0: plan comptable
* entreprise)
*/
public PlanComptableGModel(ClasseCompte classeDuCompte, int typePlan) {
this(classeDuCompte, typePlan, "COMPTE_PCG");
52,6 → 53,7
}
 
protected PlanComptableGModel(ClasseCompte classeDuCompte, String table) {
// type de plan 0 pour plan comptable entreprise
this(classeDuCompte, 0, table);
}
 
62,11 → 64,9
@Override
protected String doInBackground() throws Exception {
// on recupere les comptes
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
SQLTable compteTable = base.getTable(table);
 
// SQLBase base = elt.getTable().getBase();
SQLSelect selCompte = new SQLSelect(base);
final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
final SQLTable compteTable = base.getTable(table);
final SQLSelect selCompte = new SQLSelect(base);
selCompte.addSelect(compteTable.getField("ID"));
selCompte.addSelect(compteTable.getField("NUMERO"));
selCompte.addSelect(compteTable.getField("NOM"));
76,19 → 76,16
String match = classeDuCompte.getTypeNumeroCompte();
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) {
function = "~";
// function = "SIMILAR TO";
// match = match.replace(".*", "%");
// match = match.replace("^", "");
}
 
Where w1 = new Where(compteTable.getField("NUMERO"), function, match);
Where w2;
if (typePlan == 0) {
w2 = null;
} else if (typePlan == 1) {
final Where w2;
if (typePlan == 1) {
w2 = new Where(compteTable.getField("ID_TYPE_COMPTE_PCG_BASE"), "!=", 1);
} else if (typePlan == 2) {
w2 = new Where(compteTable.getField("ID_TYPE_COMPTE_PCG_AB"), "!=", 1);
} else if (typePlan == 3 || typePlan == 0) {
w2 = null;
} else {
throw new IllegalArgumentException("Type de PCG inconnu : " + typePlan);
}
111,8 → 108,9
for (int i = 0; i < size; i++) {
Object[] objTmp = (Object[]) myListCompte.get(i);
 
PlanComptableGModel.this.mapCompte.put(new Integer(Integer.parseInt(objTmp[0].toString())), new Integer(PlanComptableGModel.this.comptes.size()));
PlanComptableGModel.this.comptes.add(new Compte(Integer.parseInt(objTmp[0].toString()), objTmp[1].toString(), objTmp[2].toString(), objTmp[3].toString()));
final Integer numero = new Integer(Integer.parseInt(objTmp[0].toString()));
PlanComptableGModel.this.mapCompte.put(numero, new Integer(PlanComptableGModel.this.comptes.size()));
PlanComptableGModel.this.comptes.add(new Compte(numero, objTmp[1].toString(), objTmp[2].toString(), objTmp[3].toString()));
}
}
return null;
146,27 → 144,27
 
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return ((Compte) this.comptes.get(rowIndex)).getNumero();
return this.comptes.get(rowIndex).getNumero();
} else if (columnIndex == 1) {
return ((Compte) this.comptes.get(rowIndex)).getNom();
return this.comptes.get(rowIndex).getNom();
}
return null;
}
 
public int getId(int row) {
return ((Compte) this.comptes.get(row)).getId();
return this.comptes.get(row).getId();
}
 
public Map getMapComptes() {
public Map<Integer, Integer> getMapComptes() {
return this.mapCompte;
}
 
public Vector getComptes() {
public Vector<Compte> getComptes() {
return this.comptes;
}
 
public String getInfosAt(int row) {
return ((Compte) this.comptes.get(row)).getInfos();
return this.comptes.get(row).getInfos();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/action/ListeDesEncaissementsAction.java
49,7 → 49,7
List<SQLField> fields = new ArrayList<SQLField>(2);
fields.add(elementEchClient.getTable().getField("MONTANT"));
 
IListTotalPanel totalPanel = new IListTotalPanel(frame.getPanel().getListe(), fields, null, "Total Global");
IListTotalPanel totalPanel = new IListTotalPanel(frame.getPanel().getListe(), fields, "Total Global");
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/CommercialSQLElement.java
14,26 → 14,12
package org.openconcerto.erp.core.humanresources.employe.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
 
public class CommercialSQLElement extends ComptaSQLConfElement {
 
public CommercialSQLElement() {
76,221 → 62,9
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
 
JTextField textInitiale;
JTextField textPrenom, textNom;
 
DocumentListener listener = new SimpleDocumentListener() {
 
@Override
public void update(DocumentEvent e) {
updateInititale();
return new CommercialSQLComponent(this);
}
};
 
private void updateInititale() {
String s = "";
if (this.textPrenom.getText().trim().length() > 0) {
s += this.textPrenom.getText().trim().charAt(0);
}
if (this.textNom.getText().trim().length() > 0) {
s += this.textNom.getText().trim().charAt(0);
}
this.textInitiale.setText(s);
}
 
public void addViews() {
this.setLayout(new GridBagLayout());
 
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Titre personnel
final JLabel label = new JLabel(getLabelFor("ID_TITRE_PERSONNEL"));
label.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label, c);
ElementComboBox selTitre = new ElementComboBox(false, 6);
 
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(selTitre, c);
 
// Nom
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
final JLabel label2 = new JLabel(getLabelFor("NOM"));
label2.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label2, c);
this.textNom = new JTextField(21);
c.gridx++;
c.weightx = 1;
this.add(this.textNom, c);
this.textNom.getDocument().addDocumentListener(this.listener);
 
// Prenom
c.gridx++;
c.weightx = 0;
final JLabel label3 = new JLabel(getLabelFor("PRENOM"));
label3.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label3, c);
this.textPrenom = new JTextField(21);
c.gridx++;
c.weightx = 1;
this.add(this.textPrenom, c);
this.textPrenom.getDocument().addDocumentListener(this.listener);
 
// // Initiales
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label4 = new JLabel("Initiales");
label4.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label4, c);
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
this.textInitiale = new JTextField(2);
this.textInitiale.setEditable(false);
this.add(this.textInitiale, c);
c.fill = GridBagConstraints.HORIZONTAL;
 
// Fonction
c.gridx++;
c.weightx = 0;
final JLabel label5 = new JLabel(getLabelFor("FONCTION"));
label5.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label5, c);
JTextField textFonction = new JTextField();
c.gridx++;
c.weightx = 1;
this.add(textFonction, c);
 
// Tel Standard
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label6 = new JLabel(getLabelFor("TEL_STANDARD"));
label6.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label6, c);
c.gridx++;
c.weightx = 1;
JTextField textTel = new JTextField();
this.add(textTel, c);
 
// Tel direct
c.gridx++;
c.weightx = 0;
final JLabel label7 = new JLabel(getLabelFor("TEL_DIRECT"));
label7.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label7, c);
JTextField textTelD = new JTextField();
c.gridx++;
c.weightx = 1;
this.add(textTelD, c);
 
// Tel Mobile
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label8 = new JLabel(getLabelFor("TEL_MOBILE"));
label8.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label8, c);
c.gridx++;
c.weightx = 1;
JTextField textTelM = new JTextField();
this.add(textTelM, c);
 
// Tel Perso
c.gridx++;
c.weightx = 0;
final JLabel label9 = new JLabel(getLabelFor("TEL_PERSONEL"));
label9.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label9, c);
JTextField textTelP = new JTextField();
c.gridx++;
c.weightx = 1;
this.add(textTelP, c);
 
// Tel Fax
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label10 = new JLabel(getLabelFor("FAX"));
label10.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label10, c);
c.gridx++;
c.weightx = 1;
JTextField textFax = new JTextField();
this.add(textFax, c);
 
// Tel Email
c.gridx++;
c.weightx = 0;
final JLabel label11 = new JLabel(getLabelFor("EMAIL"));
label11.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(label11, c);
JTextField textMail = new JTextField();
c.gridx++;
c.weightx = 1;
this.add(textMail, c);
 
// Modules
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
this.add(addP, c);
 
// User
 
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.weightx = 0;
final JLabel labelUser = new JLabel(getLabelFor("ID_USER_COMMON"));
labelUser.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelUser, c);
c.gridx++;
c.weightx = 1;
 
c.gridwidth = GridBagConstraints.REMAINDER;
ElementComboBox comboUser = new ElementComboBox(true, 25);
this.add(comboUser, c);
 
c.weighty = 1;
c.gridy++;
this.add(new JPanel(), c);
 
this.addRequiredSQLObject(selTitre, "ID_TITRE_PERSONNEL");
selTitre.setButtonsVisible(false);
this.addRequiredSQLObject(this.textNom, "NOM");
this.addRequiredSQLObject(this.textPrenom, "PRENOM");
 
this.addSQLObject(textFonction, "FONCTION");
 
this.addSQLObject(comboUser, "ID_USER_COMMON");
 
this.addSQLObject(textTel, "TEL_STANDARD");
this.addSQLObject(textTelD, "TEL_DIRECT");
 
this.addSQLObject(textTelM, "TEL_MOBILE");
this.addSQLObject(textTelP, "TEL_PERSONEL");
 
this.addSQLObject(textFax, "FAX");
this.addSQLObject(textMail, "EMAIL");
 
// Locks
DefaultGridBagConstraints.lockMinimumSize(this.textInitiale);
DefaultGridBagConstraints.lockMinimumSize(selTitre);
 
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".salesman";
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/CommercialSQLComponent.java
New file
0,0 → 1,291
/*
* 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.
*/
/*
* Créé le 30 mars 2012
*/
package org.openconcerto.erp.core.humanresources.employe.element;
 
import org.openconcerto.erp.core.humanresources.employe.panel.ObjectifEditPanel;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
 
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
 
public class CommercialSQLComponent extends BaseSQLComponent {
 
JTextField textInitiale;
JTextField textPrenom, textNom;
ObjectifEditPanel objectifPanel = new ObjectifEditPanel(getSelectedID());
 
DocumentListener listener = new SimpleDocumentListener() {
 
@Override
public void update(DocumentEvent e) {
updateInititale();
}
};
 
public CommercialSQLComponent(SQLElement elt) {
super(elt);
}
 
@Override
public void select(SQLRowAccessor r) {
// TODO Raccord de méthode auto-généré
super.select(r);
if (r == null) {
objectifPanel.setIdCommercial(-1);
} else {
objectifPanel.setIdCommercial(r.getID());
}
}
 
private void updateInititale() {
String s = "";
if (this.textPrenom.getText().trim().length() > 0) {
s += this.textPrenom.getText().trim().charAt(0);
}
if (this.textNom.getText().trim().length() > 0) {
s += this.textNom.getText().trim().charAt(0);
}
this.textInitiale.setText(s);
}
 
private final JTabbedPane pane = new JTabbedPane();
 
public void addViews() {
this.setLayout(new GridBagLayout());
 
GridBagConstraints c = new DefaultGridBagConstraints();
JPanel panelInfos = new JPanel(new GridBagLayout());
// Titre personnel
final JLabel label = new JLabel(getLabelFor("ID_TITRE_PERSONNEL"));
label.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label, c);
ElementComboBox selTitre = new ElementComboBox(false, 6);
 
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.gridwidth = GridBagConstraints.REMAINDER;
panelInfos.add(selTitre, c);
 
// Nom
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
final JLabel label2 = new JLabel(getLabelFor("NOM"));
label2.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label2, c);
this.textNom = new JTextField(21);
c.gridx++;
c.weightx = 1;
panelInfos.add(this.textNom, c);
this.textNom.getDocument().addDocumentListener(this.listener);
 
// Prenom
c.gridx++;
c.weightx = 0;
final JLabel label3 = new JLabel(getLabelFor("PRENOM"));
label3.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label3, c);
this.textPrenom = new JTextField(21);
c.gridx++;
c.weightx = 1;
panelInfos.add(this.textPrenom, c);
this.textPrenom.getDocument().addDocumentListener(this.listener);
 
// // Initiales
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label4 = new JLabel("Initiales");
label4.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label4, c);
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
this.textInitiale = new JTextField(4);
this.textInitiale.setEditable(false);
panelInfos.add(this.textInitiale, c);
c.fill = GridBagConstraints.HORIZONTAL;
 
// Fonction
c.gridx++;
c.weightx = 0;
final JLabel label5 = new JLabel(getLabelFor("FONCTION"));
label5.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label5, c);
JTextField textFonction = new JTextField();
c.gridx++;
c.weightx = 1;
panelInfos.add(textFonction, c);
 
// Tel Standard
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label6 = new JLabel(getLabelFor("TEL_STANDARD"));
label6.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label6, c);
c.gridx++;
c.weightx = 1;
JTextField textTel = new JTextField();
panelInfos.add(textTel, c);
 
// Tel direct
c.gridx++;
c.weightx = 0;
final JLabel label7 = new JLabel(getLabelFor("TEL_DIRECT"));
label7.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label7, c);
JTextField textTelD = new JTextField();
c.gridx++;
c.weightx = 1;
panelInfos.add(textTelD, c);
 
// Tel Mobile
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label8 = new JLabel(getLabelFor("TEL_MOBILE"));
label8.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label8, c);
c.gridx++;
c.weightx = 1;
JTextField textTelM = new JTextField();
panelInfos.add(textTelM, c);
 
// Tel Perso
c.gridx++;
c.weightx = 0;
final JLabel label9 = new JLabel(getLabelFor("TEL_PERSONEL"));
label9.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label9, c);
JTextField textTelP = new JTextField();
c.gridx++;
c.weightx = 1;
panelInfos.add(textTelP, c);
 
// Tel Fax
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel label10 = new JLabel(getLabelFor("FAX"));
label10.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label10, c);
c.gridx++;
c.weightx = 1;
JTextField textFax = new JTextField();
panelInfos.add(textFax, c);
 
// Tel Email
c.gridx++;
c.weightx = 0;
final JLabel label11 = new JLabel(getLabelFor("EMAIL"));
label11.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(label11, c);
JTextField textMail = new JTextField();
c.gridx++;
c.weightx = 1;
panelInfos.add(textMail, c);
 
// Modules
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = new JPanel();
addP.setOpaque(false);
this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
panelInfos.add(addP, c);
 
// User
 
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.weightx = 0;
final JLabel labelUser = new JLabel(getLabelFor("ID_USER_COMMON"));
labelUser.setHorizontalAlignment(SwingConstants.RIGHT);
panelInfos.add(labelUser, c);
c.gridx++;
c.weightx = 1;
 
c.gridwidth = GridBagConstraints.REMAINDER;
ElementComboBox comboUser = new ElementComboBox(true, 25);
panelInfos.add(comboUser, c);
 
c.weighty = 1;
c.gridy++;
JPanel panelLayouter = new JPanel();
panelLayouter.setOpaque(false);
panelInfos.add(panelLayouter, c);
 
GridBagConstraints cFull = new DefaultGridBagConstraints();
cFull.weightx = 1;
cFull.weighty = 1;
cFull.fill = GridBagConstraints.BOTH;
 
if (getMode() == Mode.MODIFICATION) {
pane.add("Informations", panelInfos);
 
pane.add("Objectifs", objectifPanel);
panelInfos.setOpaque(false);
this.add(pane, cFull);
} else {
this.add(panelInfos, cFull);
}
 
this.addRequiredSQLObject(selTitre, "ID_TITRE_PERSONNEL");
selTitre.setButtonsVisible(false);
this.addRequiredSQLObject(this.textNom, "NOM");
this.addRequiredSQLObject(this.textPrenom, "PRENOM");
 
this.addSQLObject(textFonction, "FONCTION");
 
this.addSQLObject(comboUser, "ID_USER_COMMON");
 
this.addSQLObject(textTel, "TEL_STANDARD");
this.addSQLObject(textTelD, "TEL_DIRECT");
 
this.addSQLObject(textTelM, "TEL_MOBILE");
this.addSQLObject(textTelP, "TEL_PERSONEL");
 
this.addSQLObject(textFax, "FAX");
this.addSQLObject(textMail, "EMAIL");
 
// Locks
DefaultGridBagConstraints.lockMinimumSize(this.textInitiale);
DefaultGridBagConstraints.lockMinimumSize(selTitre);
 
}
 
public JTabbedPane getModificationTabbedPane() {
return this.pane;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/ObjectifSQLElement.java
New file
0,0 → 1,72
/*
* 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.
*/
/*
* Créé le 26 mars 2012
*/
package org.openconcerto.erp.core.humanresources.employe.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class ObjectifSQLElement extends ComptaSQLConfElement {
 
public ObjectifSQLElement() {
super("OBJECTIF_COMMERCIAL", "un objectif commercial", "Objectifs commerciaux");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ANNEE");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ANNEE");
return l;
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
public void addViews() {
 
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
 
JTextField textNom = new JTextField();
JLabel labelNom = new JLabel(getLabelFor("ANNEE"));
 
this.add(labelNom, c);
this.add(textNom, c);
 
this.addSQLObject(textNom, "ANNEE");
}
};
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/panel/ObjectifEditPanel.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.
*/
/*
* Créé le 26 mars 2012
*/
package org.openconcerto.erp.core.humanresources.employe.panel;
 
import org.openconcerto.erp.core.common.ui.DeviseCellEditor;
import org.openconcerto.erp.core.common.ui.DeviseNiceTableCellRenderer;
import org.openconcerto.sql.Configuration;
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 org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.utils.model.DefaultIListModel;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class ObjectifEditPanel extends JPanel {
 
int idCommercial;
SQLTable tableObjectif = Configuration.getInstance().getRoot().findTable("OBJECTIF_COMMERCIAL");
final ListAnneeModel<Integer> listModel = new ListAnneeModel<Integer>();
final ObjectifTableModel tableModel = new ObjectifTableModel();
 
public ObjectifEditPanel(int idCommercial) {
super(new GridBagLayout());
this.idCommercial = idCommercial;
uiInit();
setOpaque(false);
}
 
public void setIdCommercial(int idCommercial) {
this.idCommercial = idCommercial;
listModel.loadData(idCommercial);
tableModel.loadData(this.idCommercial, 0);
}
 
private void uiInit() {
 
GridBagConstraints c = new DefaultGridBagConstraints();
 
this.add(new JLabelBold("Année"), c);
c.gridx++;
this.add(new JLabelBold("Objectifs mensuels"), c);
listModel.loadData(idCommercial);
final JList jList = new JList(listModel);
c.gridy++;
c.gridx = 0;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.2;
this.add(jList, c);
 
c.gridx++;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.8;
 
final JTable table = new JTable(tableModel);
DeviseCellEditor cellEditor = new DeviseCellEditor();
DeviseNiceTableCellRenderer rend = new DeviseNiceTableCellRenderer();
 
table.getColumnModel().getColumn(1).setCellEditor(cellEditor)
 
;
table.getColumnModel().getColumn(1).setCellRenderer(rend);
 
table.getColumnModel().getColumn(3).setCellEditor(cellEditor)
 
;
table.getColumnModel().getColumn(3).setCellRenderer(rend);
 
this.add(new JScrollPane(table), c);
jList.addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Raccord de méthode auto-généré
Integer annee = listModel.getElementAt(jList.getSelectedIndex());
tableModel.loadData(idCommercial, annee);
}
});
c.gridy++;
c.gridx = 0;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
this.add(new JButton(new AbstractAction("Ajouter une année") {
 
@Override
public void actionPerformed(ActionEvent e) {
addYear();
}
}), c);
 
}
 
private void addYear() {
// FIXME à mettre dans une transaction
SQLSelect sel = new SQLSelect(tableObjectif.getBase());
sel.addSelect(tableObjectif.getField("ANNEE"), "MAX");
sel.setWhere(new Where(tableObjectif.getField("ID_COMMERCIAL"), "=", this.idCommercial));
 
Object anneeObject = (Object) Configuration.getInstance().getBase().getDataSource().executeScalar(sel.asString());
int annee;
if (anneeObject == null) {
annee = Calendar.getInstance().get(Calendar.YEAR);
} else {
annee = (Integer) anneeObject;
annee++;
}
 
List<String> s = Arrays.asList("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
for (String string : s) {
SQLRowValues rowVals = new SQLRowValues(tableObjectif);
rowVals.put("ANNEE", annee);
rowVals.put("MOIS", string);
rowVals.put("MARGE_HT", Long.valueOf(0));
rowVals.put("POURCENT_MARGE", BigDecimal.ZERO);
rowVals.put("CHIFFRE_AFFAIRE", Long.valueOf(0));
rowVals.put("ID_COMMERCIAL", this.idCommercial);
try {
rowVals.insert();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
listModel.addElement(annee);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/panel/ObjectifTableModel.java
New file
0,0 → 1,156
/*
* 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.
*/
/*
* Créé le 26 mars 2012
*/
package org.openconcerto.erp.core.humanresources.employe.panel;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
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.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.table.AbstractTableModel;
 
public class ObjectifTableModel extends AbstractTableModel {
 
List<SQLField> cols = new ArrayList<SQLField>();
SQLTable tableObjectif = Configuration.getInstance().getRoot().findTable("OBJECTIF_COMMERCIAL");
List<SQLRowValues> values = new ArrayList<SQLRowValues>();
 
public ObjectifTableModel() {
cols.add(tableObjectif.getField("MOIS"));
cols.add(tableObjectif.getField("CHIFFRE_AFFAIRE"));
cols.add(tableObjectif.getField("POURCENT_MARGE"));
cols.add(tableObjectif.getField("MARGE_HT"));
 
}
 
@Override
public int getColumnCount() {
// TODO Raccord de méthode auto-généré
return cols.size();
}
 
@Override
public String getColumnName(int column) {
// TODO Raccord de méthode auto-généré
return Configuration.getInstance().getTranslator().getTitleFor(cols.get(column));
}
 
@Override
public Class<?> getColumnClass(int columnIndex) {
// TODO Raccord de méthode auto-généré
return cols.get(columnIndex).getType().getJavaType();
}
 
@Override
public int getRowCount() {
// TODO Raccord de méthode auto-généré
return values.size();
}
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Raccord de méthode auto-généré
return values.get(rowIndex).getObject(cols.get(columnIndex).getName());
}
 
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO Raccord de méthode auto-généré
super.setValueAt(aValue, rowIndex, columnIndex);
 
// FIXME check if aValue is null
 
SQLRowValues rowValuesAt = this.getRowValuesAt(rowIndex);
if (columnIndex == 1) {
BigDecimal decimal = (BigDecimal) rowValuesAt.getObject(cols.get(2).getName());
if (decimal != null) {
long result = Math.round(decimal.doubleValue() * (Long) aValue / 100.0D);
rowValuesAt.put(cols.get(3).getName(), result);
}
}
 
if (columnIndex == 2) {
Long decimal = (Long) rowValuesAt.getObject(cols.get(1).getName());
if (decimal != null) {
long result = Math.round(decimal * ((BigDecimal) aValue).doubleValue() / 100.0D);
rowValuesAt.put(cols.get(3).getName(), result);
}
}
 
if (columnIndex == 3) {
Long decimal = (Long) rowValuesAt.getObject(cols.get(1).getName());
if (decimal != null) {
double result = ((Long) aValue).doubleValue() / decimal.doubleValue() * 100.0D;
rowValuesAt.put(cols.get(2).getName(), new BigDecimal(result));
}
}
 
rowValuesAt.put(cols.get(columnIndex).getName(), aValue);
try {
rowValuesAt.update();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
this.fireTableDataChanged();
}
 
public void loadData(int idCommercial, Integer annee) {
 
if (idCommercial <= 1 || annee == null) {
this.values.clear();
} else {
SQLSelect sel = new SQLSelect(tableObjectif.getBase());
sel.addSelectStar(tableObjectif);
Where w = new Where(tableObjectif.getField("ID_COMMERCIAL"), "=", idCommercial);
w = w.and(new Where(tableObjectif.getField("ANNEE"), "=", annee));
sel.setWhere(w);
sel.addFieldOrder(tableObjectif.getOrderField());
List<SQLRow> rows = SQLRowListRSH.execute(sel);
List<SQLRowValues> rowValuesList = new ArrayList<SQLRowValues>();
for (SQLRow sqlRow : rows) {
rowValuesList.add(sqlRow.asRowValues());
}
this.values.clear();
this.values.addAll(rowValuesList);
}
this.fireTableDataChanged();
}
 
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
// TODO Raccord de méthode auto-généré
return (columnIndex == 1 || columnIndex == 2 || columnIndex == 3);
}
 
public SQLRowValues getRowValuesAt(int index) {
if (index >= 0) {
return this.values.get(index);
} else {
return null;
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/panel/ListAnneeModel.java
New file
0,0 → 1,80
/*
* 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.
*/
/*
* Créé le 27 mars 2012
*/
package org.openconcerto.erp.core.humanresources.employe.panel;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.AbstractListModel;
 
public class ListAnneeModel<T> extends AbstractListModel {
 
List<T> values = new ArrayList<T>();
 
public ListAnneeModel() {
 
}
 
public void loadData(int idCommercial) {
SQLTable tableObjectif = Configuration.getInstance().getRoot().findTable("OBJECTIF_COMMERCIAL");
SQLSelect sel = new SQLSelect(tableObjectif.getBase());
sel.addSelect(tableObjectif.getField("ANNEE"));
sel.setWhere(new Where(tableObjectif.getField("ID_COMMERCIAL"), "=", idCommercial));
sel.setDistinct(true);
 
List<Object[]> listAnnee = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().executeA(sel.asString());
clear();
for (Object[] object : listAnnee) {
addElement((T) object[0]);
}
}
 
@Override
public T getElementAt(int index) {
if (index >= 0 && values.size() > 0) {
// TODO Raccord de méthode auto-généré
return values.get(index);
} else {
return null;
}
}
 
@Override
public int getSize() {
// TODO Raccord de méthode auto-généré
return values.size();
}
 
public void addElement(T obj) {
int index = values.size();
values.add(obj);
fireIntervalAdded(this, index, index);
}
 
public void clear() {
int index1 = values.size() - 1;
values.clear();
if (index1 >= 0) {
fireIntervalRemoved(this, 0, index1);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/PanelOOSQLComponent.java
16,13 → 16,15
*/
package org.openconcerto.erp.panel;
 
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.erp.preferences.TemplatePreferencePanel;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.preferences.GenerationDocGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.cc.ITransformer;
44,11 → 46,18
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
this.setOpaque(false);
SQLPreferences prefs = new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete());
if (prefs.getBoolean(GenerationDocGlobalPreferencePanel.MULTIMOD, false)) {
 
if (TemplateNXProps.getInstance().getBooleanValue(TemplatePreferencePanel.MULTIMOD, false)) {
if (comp.getElement().getTable().getFieldsName().contains("ID_MODELE")) {
JLabel labelModele = new JLabel(comp.getLabelFor("ID_MODELE"));
ElementComboBox boxModele = new ElementComboBox();
String labelFor = comp.getLabelFor("ID_MODELE");
if (labelFor == null || labelFor.trim().length() == 0) {
labelFor = "Modéles";
}
JLabel labelModele = new JLabel(labelFor);
ElementComboBox boxModele = new ElementComboBox(true, 25);
SQLElement modeleElement = Configuration.getInstance().getDirectory().getElement("MODELE");
boxModele.init(modeleElement, modeleElement.getComboRequest(true));
comp.addView(boxModele, "ID_MODELE");
boxModele.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
62,6 → 71,7
}
});
this.add(labelModele, c);
DefaultGridBagConstraints.lockMinimumSize(boxModele);
this.add(boxModele, c);
} else {
System.err.println("Impossible d'ajouter la combo pour le choix des modèles car le champ ID_MODELE n'est pas présent dans la table " + comp.getElement().getTable().getName());
/trunk/OpenConcerto/src/org/openconcerto/erp/utils/ActionDB.java
27,9 → 27,9
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSchema;
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.utils.ChangeTable.ConcatStep;
import org.openconcerto.sql.utils.SQLCreateRoot;
import org.openconcerto.utils.ExceptionHandler;
 
37,6 → 37,7
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
80,7 → 81,11
final SQLCreateRoot createRoot = baseSQLDefault.getDefinitionSQL(sysRoot.getServer().getSQLSystem());
final SQLDataSource ds = sysRoot.getDataSource();
// be safe don't add DROP SCHEMA
ds.execute(createRoot.asString(newBase, false, true));
final List<String> sql = createRoot.asStringList(newBase, false, true, EnumSet.of(ConcatStep.ADD_FOREIGN));
// create root
ds.execute(sql.get(0));
// create tables (without constraints)
ds.execute(sql.get(1));
sysRoot.getRootsToMap().add(newBase);
// TODO find a more functional way
final boolean origVal = Boolean.getBoolean(SQLSchema.NOAUTO_CREATE_METADATA);
93,10 → 98,6
 
final Set<SQLTable> newTables = baseSQLNew.getTables();
int i = 0;
final SQLSyntax syntax = sysRoot.getServer().getSQLSystem().getSyntax();
// MAYBE SQLCreateRoot can avoid creating foreign constraints, then we insert data,
// finally SQLCreateRoot adds just the constraints
ds.execute(syntax.disableFKChecks(baseSQLNew));
for (final SQLTable table : newTables) {
String tableName = table.getName();
 
106,9 → 107,11
log(l, "Table " + tableName + " " + (i + 1) + "/" + newTables.size() + " OK");
i++;
}
ds.execute(syntax.enableFKChecks(baseSQLNew));
// create constraints
ds.execute(sql.get(2));
assert sql.size() == 3;
 
if (syntax.getSystem() == SQLSystem.POSTGRESQL) {
if (sysRoot.getServer().getSQLSystem() == SQLSystem.POSTGRESQL) {
log(l, "Maj des séquences des tables");
new FixSerial(sysRoot).changeAll(baseSQLNew);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/AbstractGenerationDocumentPreferencePanel.java
14,11 → 14,10
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.sql.Configuration;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.preferences.DefaultPreferencePanel;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.text.SimpleDocumentListener;
227,14 → 226,14
final File z = new File(".");
for (final Entry<Tuple2<String, String>, JTextField> entry : this.mapKeyTextOO.entrySet()) {
final File f = new File(entry.getValue().getText());
TemplateNXProps.getInstance().setProperty(entry.getKey().get1() + "OO", FileUtility.getPrimaryPath(z.getCanonicalFile(), f));
DocumentLocalStorageManager.getInstance().addDocumentDirectory(entry.getKey().get0(), new File(FileUtility.getPrimaryPath(z.getCanonicalFile(), f)));
TemplateNXProps.getInstance().setProperty(entry.getKey().get1() + "OO", FileUtils.relative(z, f));
DocumentLocalStorageManager.getInstance().addDocumentDirectory(entry.getKey().get0(), new File(FileUtils.relative(z, f)));
}
 
for (final Entry<Tuple2<String, String>, JTextField> entry : this.mapKeyTextPDF.entrySet()) {
final File f = new File(entry.getValue().getText());
TemplateNXProps.getInstance().setProperty(entry.getKey().get1() + "PDF", FileUtility.getPrimaryPath(z.getCanonicalFile(), f));
DocumentLocalStorageManager.getInstance().addPDFDirectory(entry.getKey().get0(), new File(FileUtility.getPrimaryPath(z.getCanonicalFile(), f)));
TemplateNXProps.getInstance().setProperty(entry.getKey().get1() + "PDF", FileUtils.relative(z, f));
DocumentLocalStorageManager.getInstance().addPDFDirectory(entry.getKey().get0(), new File(FileUtils.relative(z, f)));
}
 
} catch (final IOException e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/TemplateTableModel.java
New file
0,0 → 1,91
/*
* 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.preferences;
 
import org.openconcerto.erp.generationDoc.TemplateManager;
import org.openconcerto.erp.generationDoc.TemplateProvider;
 
import javax.swing.table.AbstractTableModel;
 
public class TemplateTableModel extends AbstractTableModel {
public TemplateTableModel() {
}
 
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
 
@Override
public String getColumnName(int column) {
if (column == 0) {
return "Modèle";
}
return "Synchronisé";
}
 
@Override
public int getRowCount() {
return TemplateManager.getInstance().getKnownTemplateIds().size();
}
 
@Override
public int getColumnCount() {
return 2;
}
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final String templateId = getTemplateId(rowIndex);
if (columnIndex == 0) {
return templateId;
} else {
final TemplateProvider p = TemplateManager.getInstance().getProvider(templateId);
if (p.isSynced(templateId, null, null)) {
return "oui";
} else {
return "non";
}
}
}
 
public TemplateProvider getTemplateProvider(int rowIndex) {
final String templateId = getTemplateId(rowIndex);
return TemplateManager.getInstance().getProvider(templateId);
}
 
public boolean isSynced(int rowIndex) {
return getTemplateProvider(rowIndex).isSynced(getTemplateId(rowIndex), null, null);
}
 
public void sync(int rowIndex) {
getTemplateProvider(rowIndex).sync(getTemplateId(rowIndex), null, null);
fireTableDataChanged();
}
 
public void unsync(int rowIndex) {
getTemplateProvider(rowIndex).unSync(getTemplateId(rowIndex), null, null);
fireTableDataChanged();
}
 
public void restore(int rowIndex) {
getTemplateProvider(rowIndex).restore(getTemplateId(rowIndex), null, null);
fireTableDataChanged();
}
 
public String getTemplateId(int rowIndex) {
return TemplateManager.getInstance().getKnownTemplateIds().get(rowIndex);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/TemplateNXProps.java
28,6 → 28,8
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.AbstractLocalTemplateProvider;
import org.openconcerto.erp.generationDoc.DefaultCloudTemplateProvider;
import org.openconcerto.erp.generationDoc.DefaultLocalTemplateProvider;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetXml;
65,9 → 67,7
 
if (!f2.exists()) {
final InputStream fConf = ComptaBasePropsConfiguration.getStreamStatic("/Configuration/Template.properties");
if (fConf == null) {
JOptionPane.showMessageDialog(null, "L'emplacement des modéles n'est pas défini.");
} else {
if (fConf != null) {
try {
StreamUtils.copy(fConf, f2);
fConf.close();
95,7 → 95,6
 
@Override
public String getPropertySuffix() {
 
return societeBaseName;
}
 
150,7 → 149,7
 
}
 
private void register(String templateId, String propertyBaseName, String defaultSubFolder) {
public void register(String templateId, String propertyBaseName, String defaultSubFolder) {
if (templateId == null) {
throw new IllegalArgumentException("null template id");
}
190,10 → 189,18
 
private void initDefaulTemplateProvider() {
final String property = getProperty("LocationTemplate");
final DefaultLocalTemplateProvider provider = new DefaultLocalTemplateProvider();
final AbstractLocalTemplateProvider provider;
 
final ComptaPropsConfiguration configuration = (ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance();
if (!configuration.isOnCloud()) {
provider = new DefaultLocalTemplateProvider();
if (property != null) {
provider.setBaseDirectory(new File(property));
((DefaultLocalTemplateProvider) provider).setBaseDirectory(new File(property));
}
} else {
provider = new DefaultCloudTemplateProvider(configuration.getSocieteID());
}
 
TemplateManager.getInstance().setDefaultProvider(provider);
TemplateManager.getInstance().dump();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDeclarationDocPreferencePanel.java
13,9 → 13,9
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.utils.FileUtility;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.preferences.DefaultPreferencePanel;
import org.openconcerto.utils.FileUtils;
 
import java.awt.Color;
import java.awt.GridBagConstraints;
134,9 → 134,9
File z = new File(".");
 
try {
TemplateNXProps.getInstance().setProperty("Location2033APDF", FileUtility.getPrimaryPath(z.getCanonicalFile(), f2033APDF));
TemplateNXProps.getInstance().setProperty("Location2033BPDF", FileUtility.getPrimaryPath(z.getCanonicalFile(), f2033BPDF));
TemplateNXProps.getInstance().setProperty("Location2033CPDF", FileUtility.getPrimaryPath(z.getCanonicalFile(), f2033CPDF));
TemplateNXProps.getInstance().setProperty("Location2033APDF", FileUtils.relative(z, f2033APDF));
TemplateNXProps.getInstance().setProperty("Location2033BPDF", FileUtils.relative(z, f2033BPDF));
TemplateNXProps.getInstance().setProperty("Location2033CPDF", FileUtils.relative(z, f2033CPDF));
} catch (IOException e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDocumentGestCommPreferencePanel.java
13,6 → 13,9
package org.openconcerto.erp.preferences;
 
import java.util.HashMap;
import java.util.Map;
 
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;
24,8 → 27,6
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;
import org.openconcerto.utils.Tuple2;
 
public class GenerationDocumentGestCommPreferencePanel extends AbstractGenerationDocumentPreferencePanel {
44,13 → 45,20
this.mapKeyLabel.put(Tuple2.create(CourrierClientSheet.TEMPLATE_ID, CourrierClientSheet.TEMPLATE_PROPERTY_NAME), getLabelFromTable("COURRIER_CLIENT"));
this.mapKeyLabel.put(Tuple2.create(ReleveChequeEmisSheet.TEMPLATE_ID, ReleveChequeEmisSheet.TEMPLATE_PROPERTY_NAME), "Relevé chèque émis");
this.mapKeyLabel.put(Tuple2.create(ReleveChequeSheet.TEMPLATE_ID, ReleveChequeSheet.TEMPLATE_PROPERTY_NAME), "Relevé chèque");
for (Tuple2<String, String> t : mapKeyLabelCustom.keySet()) {
this.mapKeyLabel.put(t, mapKeyLabelCustom.get(t));
}
// this.mapKeyLabel.put(SheetXml.tupleDefault.get0(), SheetXml.tupleDefault.get1());
// uiInit();
}
 
protected static Map<Tuple2<String, String>, String> mapKeyLabelCustom = new HashMap<Tuple2<String, String>, String>();
 
public String getTitleName() {
return "Destination des documents générés";
}
 
public static void addPref(Tuple2<String, String> template, String label) {
mapKeyLabelCustom.put(template, label);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GestionArticleGlobalPreferencePanel.java
New file
0,0 → 1,55
/*
* 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.
*/
/*
* Créé le 6 mars 2012
*/
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.ui.preferences.JavaPrefPreferencePanel;
import org.openconcerto.ui.preferences.PrefView;
import org.openconcerto.utils.PrefType;
 
public class GestionArticleGlobalPreferencePanel extends JavaPrefPreferencePanel {
public static String STOCK_FACT = "StockOnOrder";
public static String UNITE_VENTE = "UniteVenteActive";
public static String USE_CREATED_ARTICLE = "UseCreatedArticle";
public static String CREATE_ARTICLE_AUTO = "CreateArticleAuto";
 
public GestionArticleGlobalPreferencePanel() {
super("Gestion des articles", null);
setPrefs(new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()));
}
 
@Override
protected void addViews() {
PrefView<Boolean> view = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Gérer les sorties de stock avec les factures et non les bons de livraison", STOCK_FACT);
view.setDefaultValue(Boolean.TRUE);
this.addView(view);
 
PrefView<Boolean> view2 = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Gérer différentes unités de vente", UNITE_VENTE);
view2.setDefaultValue(Boolean.TRUE);
this.addView(view2);
 
PrefView<Boolean> view3 = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Utiliser uniquement des articles existant", USE_CREATED_ARTICLE);
view3.setDefaultValue(Boolean.FALSE);
this.addView(view3);
 
PrefView<Boolean> view4 = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Créer automatiquement les articles (si il n'y a aucune correspondance CODE, DESIGNATION)", CREATE_ARTICLE_AUTO);
view4.setDefaultValue(Boolean.TRUE);
this.addView(view4);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDocGlobalPreferencePanel.java
16,6 → 16,8
*/
package org.openconcerto.erp.preferences;
 
import javax.swing.JCheckBox;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.preferences.SQLPreferences;
25,7 → 27,10
 
public class GenerationDocGlobalPreferencePanel extends JavaPrefPreferencePanel {
public static String HISTORIQUE = "HistoriqueDocument";
public static String MULTIMOD = "MultiModele";
 
JCheckBox boxMultiMod = new JCheckBox("Activer la gestion multimodèle");
 
public GenerationDocGlobalPreferencePanel() {
super("Génération des documents", null);
setPrefs(new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()));
36,5 → 41,9
PrefView<Boolean> view = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Archiver les documents dans un dossier historique", HISTORIQUE);
view.setDefaultValue(Boolean.TRUE);
this.addView(view);
 
PrefView<Boolean> viewModele = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Activer la gestion multimodèle", MULTIMOD);
viewModele.setDefaultValue(Boolean.FALSE);
this.addView(viewModele);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/TemplatePreferencePanel.java
13,36 → 13,54
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.generationDoc.AbstractLocalTemplateProvider;
import org.openconcerto.erp.generationDoc.DefaultLocalTemplateProvider;
import org.openconcerto.erp.generationDoc.TemplateManager;
import org.openconcerto.erp.utils.FileUtility;
import org.openconcerto.erp.generationDoc.TemplateProvider;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.preferences.DefaultPreferencePanel;
import org.openconcerto.ui.table.TablePopupMouseListener;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
 
public class TemplatePreferencePanel extends DefaultPreferencePanel {
 
private JTextField textTemplate;
private JFileChooser fileChooser = null;
public static String MULTIMOD = "MultiModele";
JCheckBox boxMultiMod = new JCheckBox("Activer la gestion multimodèle");
 
private JButton bModify;
private JButton bUndo;
private JButton bSync;
 
public TemplatePreferencePanel() {
this.setLayout(new GridBagLayout());
final GridBagConstraints cPanel = new DefaultGridBagConstraints();
51,7 → 69,7
/*******************************************************************************************
* Emplacement
******************************************************************************************/
this.add(new JLabel("Emplacement des modèles"), cPanel);
this.add(new JLabel("Modèles des documents"), cPanel);
cPanel.gridx++;
cPanel.weightx = 1;
this.textTemplate = new JTextField();
63,16 → 81,16
cPanel.fill = GridBagConstraints.NONE;
this.add(buttonTemplate, cPanel);
 
final JPanel templates = createTemplateList();
templates.setOpaque(false);
cPanel.gridy++;
cPanel.fill = GridBagConstraints.BOTH;
cPanel.weightx = 1;
cPanel.weighty = 1;
cPanel.gridwidth = 3;
cPanel.gridx = 0;
this.add(boxMultiMod, cPanel);
this.add(templates, cPanel);
 
final JPanel spacer = new JPanel();
spacer.setOpaque(false);
cPanel.gridy++;
cPanel.weighty = 1;
this.add(spacer, cPanel);
 
buttonTemplate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
directoryChoose("template");
83,27 → 101,175
setValues();
}
 
private JPanel createTemplateList() {
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.NONE;
bModify = new JButton("Modifier");
bModify.setEnabled(false);
bModify.setOpaque(false);
p.add(bModify, c);
 
bUndo = new JButton("Rétablir");
bUndo.setEnabled(false);
bUndo.setOpaque(false);
c.gridx++;
p.add(bUndo, c);
bSync = new JButton("Synchroniser");
bSync.setEnabled(false);
bSync.setOpaque(false);
c.gridx++;
p.add(bSync, c);
final TemplateTableModel dm = new TemplateTableModel();
final JTable table = new JTable(dm);
TablePopupMouseListener.add(table, new ITransformer<MouseEvent, JPopupMenu>() {
@Override
public JPopupMenu transformChecked(MouseEvent input) {
final JPopupMenu res = new JPopupMenu();
final int selectedRow = table.getSelectedRow();
if (selectedRow >= 0) {
final JMenuItem menuItem = new JMenuItem(dm.getTemplateId(selectedRow));
res.add(menuItem);
menuItem.setEnabled(false);
res.addSeparator();
 
res.add(new AbstractAction("Modifier le modèle") {
 
@Override
public void actionPerformed(ActionEvent e) {
modifyTemplate(dm, table);
 
}
});
res.add(new AbstractAction("Modifier la configuration du modèle") {
 
@Override
public void actionPerformed(ActionEvent e) {
modifyTemplateXML(dm, table);
 
}
});
res.add(new AbstractAction("Modifier les paramètres d'impression") {
 
@Override
public void actionPerformed(ActionEvent e) {
modifyTemplateODSP(dm, table);
 
}
});
}
return res;
}
});
table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
TemplateProvider provider = dm.getTemplateProvider(row);
if (provider instanceof AbstractLocalTemplateProvider) {
final String templateId = dm.getTemplateId(row);
File f = ((AbstractLocalTemplateProvider) provider).getFileTemplate(templateId, null, null);
if (f == null || !f.exists()) {
tableCellRendererComponent.setBackground(Color.ORANGE);
if (f != null) {
setToolTipText(f.getAbsolutePath() + " not found");
} else {
setToolTipText("no file for template " + templateId);
}
} else {
if (isSelected) {
tableCellRendererComponent.setBackground(table.getSelectionBackground());
} else {
tableCellRendererComponent.setBackground(table.getBackground());
}
setToolTipText(f.getAbsolutePath());
}
}
return tableCellRendererComponent;
}
});
c.gridy++;
c.gridx = 0;
c.gridwidth = 3;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
p.add(new JScrollPane(table), c);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
if (row < 0) {
bModify.setEnabled(false);
bSync.setEnabled(false);
bUndo.setEnabled(false);
return;
}
boolean b = dm.isSynced(row);
if (b) {
bModify.setEnabled(true);
bSync.setEnabled(false);
bUndo.setEnabled(false);
} else {
bModify.setEnabled(true);
bSync.setEnabled(true);
bUndo.setEnabled(true);
}
 
}
});
bModify.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
modifyTemplate(dm, table);
}
});
bSync.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
dm.sync(row);
}
});
 
bUndo.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
dm.restore(row);
 
}
});
 
return p;
}
 
public void storeValues() {
 
final File z = new File(".");
final File f = new File(this.textTemplate.getText());
try {
TemplateNXProps.getInstance().setProperty("LocationTemplate", FileUtility.getPrimaryPath(z.getCanonicalFile(), f));
TemplateNXProps.getInstance().setProperty("LocationTemplate", FileUtils.relative(z, f));
final DefaultLocalTemplateProvider provider = new DefaultLocalTemplateProvider();
 
provider.setBaseDirectory(new File(FileUtility.getPrimaryPath(z.getCanonicalFile(), f)));
provider.setBaseDirectory(new File(FileUtils.relative(z, f)));
 
TemplateManager.getInstance().setDefaultProvider(provider);
} catch (IOException e) {
e.printStackTrace();
}
TemplateNXProps.getInstance().setProperty(MULTIMOD, String.valueOf(this.boxMultiMod.isSelected()));
 
TemplateNXProps.getInstance().store();
}
 
public void restoreToDefaults() {
this.boxMultiMod.setSelected(false);
 
}
 
public String getTitleName() {
123,7 → 289,6
} catch (IOException e) {
e.printStackTrace();
}
this.boxMultiMod.setSelected(TemplateNXProps.getInstance().getBooleanValue(MULTIMOD, false));
}
 
private void directoryChoose(final String type) {
152,4 → 317,94
});
}
 
public void modifyTemplate(final TemplateTableModel dm, final JTable table) {
int row = table.getSelectedRow();
dm.unsync(row);
// modify on OO
final TemplateProvider templateProvider = dm.getTemplateProvider(row);
if (templateProvider instanceof AbstractLocalTemplateProvider) {
final String templateId = dm.getTemplateId(row);
 
Thread t = new Thread(new Runnable() {
 
@Override
public void run() {
try {
final File fileTemplate = ((AbstractLocalTemplateProvider) templateProvider).getFileTemplate(templateId, null, null);
if (fileTemplate != null && fileTemplate.exists()) {
FileUtils.openFile(fileTemplate);
}
} catch (IOException e1) {
ExceptionHandler.handle("Impossible d'ouvrir le modèle", e1);
}
}
});
t.setName("TemplatePreferencePanel: open with OO");
t.setDaemon(true);
t.start();
 
}
}
 
public void modifyTemplateXML(final TemplateTableModel dm, final JTable table) {
int row = table.getSelectedRow();
dm.unsync(row);
// modify on OO
final TemplateProvider templateProvider = dm.getTemplateProvider(row);
if (templateProvider instanceof AbstractLocalTemplateProvider) {
final String templateId = dm.getTemplateId(row);
 
Thread t = new Thread(new Runnable() {
 
@Override
public void run() {
try {
final File fileTemplateConfiguration = ((AbstractLocalTemplateProvider) templateProvider).getFileTemplateConfiguration(templateId, null, null);
if (fileTemplateConfiguration != null && fileTemplateConfiguration.exists()) {
FileUtils.openFile(fileTemplateConfiguration);
} else {
JOptionPane.showMessageDialog(TemplatePreferencePanel.this, "Pas de fichier de configuration associé");
}
} catch (IOException e1) {
ExceptionHandler.handle("Impossible d'ouvrir la configuration du modèle", e1);
}
}
});
t.setName("TemplatePreferencePanel: open with OO");
t.setDaemon(true);
t.start();
 
}
 
}
 
public void modifyTemplateODSP(final TemplateTableModel dm, final JTable table) {
int row = table.getSelectedRow();
dm.unsync(row);
// modify on OO
final TemplateProvider templateProvider = dm.getTemplateProvider(row);
if (templateProvider instanceof AbstractLocalTemplateProvider) {
final String templateId = dm.getTemplateId(row);
 
Thread t = new Thread(new Runnable() {
 
@Override
public void run() {
try {
final File fileTemplatePrintConfiguration = ((AbstractLocalTemplateProvider) templateProvider).getFileTemplatePrintConfiguration(templateId, null, null);
if (fileTemplatePrintConfiguration != null && fileTemplatePrintConfiguration.exists()) {
FileUtils.openFile(fileTemplatePrintConfiguration);
}
} catch (IOException e1) {
ExceptionHandler.handle("Impossible d'ouvrir la configuration d'impression", e1);
}
}
});
t.setName("TemplatePreferencePanel: open with OO");
t.setDaemon(true);
t.start();
 
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/storage/CloudStorageEngine.java
New file
0,0 → 1,65
/*
* 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 org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.utils.StreamUtils;
import org.openconcerto.utils.sync.SyncClient;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
 
public class CloudStorageEngine implements StorageEngine {
 
@Override
public boolean isConfigured() {
return true;
}
 
@Override
public boolean allowAutoStorage() {
return true;
}
 
@Override
public void connect() throws IOException {
}
 
@Override
public void disconnect() throws IOException {
}
 
@Override
public void store(InputStream inStream, String remotePath, String title, boolean synchronous) throws IOException {
final File localFile = File.createTempFile("OpenConcerto", title);
remotePath = remotePath.replace('\\', '/');
try {
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
remotePath = config.getSocieteID() + "/" + remotePath;
final SyncClient client = new SyncClient("https://" + config.getStorageServer());
client.setVerifyHost(false);
StreamUtils.copy(inStream, localFile);
System.out.println("CloudStorageEngine: send file:" + localFile.getCanonicalPath() + " to " + remotePath + " " + title);
client.sendFile(localFile, remotePath, title, config.getToken());
} catch (Exception e) {
throw new IOException(e);
} finally {
if (localFile.exists()) {
localFile.delete();
}
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/Gestion.java
126,10 → 126,7
System.out.println(System.getProperty("java.runtime.version", "??") + " - " + System.getProperty("os.name", "??"));
ExceptionHandler.setForceUI(true);
ExceptionHandler.setForumURL("http://www.openconcerto.org/forum");
final boolean logRequests = Boolean.getBoolean("org.openconcerto.sql.logRequests");
if (logRequests) {
SQLRequestLog.setEnabled(true);
}
 
System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
// Mac
// only works with Aqua laf
155,6 → 152,7
 
System.setProperty("org.openconcerto.oo.useODSViewer", "true");
}
 
if (System.getProperty(State.DEAF) == null) {
System.setProperty(State.DEAF, "true");
}
182,6 → 180,13
System.setSecurityManager(null);
}
Configuration.setInstance(conf);
 
final boolean logRequests = Boolean.valueOf(conf.getProperty("logRequests", "false"));
 
if (logRequests) {
SQLRequestLog.setEnabled(true);
}
 
if (Boolean.valueOf(conf.getProperty("minimal", "false"))) {
System.setProperty(MINIMAL_PROP, Boolean.TRUE.toString());
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerConfigListModel.java
58,15 → 58,19
}
ServerFinder f = new ServerFinder();
File fH2 = new File(Configuration.getDefaultConfDir(), "OpenConcerto-GESTION_DEFAULT/DBData");
if (fH2.exists() && fH2.isDirectory()) {
if (ServerFinderPanel.containsValidH2DB(fH2)) {
final ServerFinderConfig c = new ServerFinderConfig();
c.setType(ServerFinderConfig.H2);
c.setFile(fH2);
if (new File(fH2, "OpenConcerto.h2.db").exists()) {
c.setProduct("H2 OpenConcerto found");
} else {
c.setProduct("Unknown H2 database");
confs.add(c);
}
fH2 = new File(Configuration.getDefaultConfDir(), "OpenConcerto/DBData");
if (ServerFinderPanel.containsValidH2DB(fH2)) {
final ServerFinderConfig c = new ServerFinderConfig();
c.setType(ServerFinderConfig.H2);
c.setFile(fH2);
c.setProduct("H2 OpenConcerto found");
confs.add(c);
}
List<String> l = f.getIPsToScan();
/trunk/OpenConcerto/src/org/openconcerto/erp/config/mappingCompta.xml
25,6 → 25,11
</TABLE>
<TABLE name="AFFAIRE">
<FIELD name="ID_CLIENT" label="Client" titlelabel="Client" />
<FIELD name="CCI" label="CCI" titlelabel="CCI" />
<FIELD name="ID_VERIFICATEUR" label="Chargé d'affaire"
titlelabel="Chargé d'affaire" />
<FIELD name="DATE_DEMARRAGE" label="Date de démarrage"
titlelabel="Date de démarrage" />
<FIELD name="MARCHE" label="Marché" titlelabel="Marché" />
<FIELD name="NUMERO" label="Numéro affaire" titlelabel="Numéro affaire" />
<FIELD name="DATE" label="Date" titlelabel="Date" />
62,6 → 67,8
<FIELD name="DATE_FIN_CONTRAT" label="Date de fin de contrat"
titlelabel="Date de fin de contrat" />
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="DUREE_PREVISIONNELLE" label="Durée prévue"
titlelabel="Durée prévue" />
<FIELD name="ID_DOSSIER" label="Dossier" titlelabel="Dossier" />
<FIELD name="ID_TAXE" label="TVA" titlelabel="TVA" />
<FIELD name="NOM" label="Libellé" titlelabel="Libellé" />
98,6 → 105,7
</TABLE>
 
<TABLE name="ARTICLE">
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="QTE_ACHAT" label="Quantité multiple d'achat à respecter"
titlelabel="Quantité multiple d'achat à respecter" />
<FIELD name="CODE_BARRE" label="Code barres" titlelabel="Code barres" />
117,8 → 125,8
<FIELD name="POIDS" label="Poids en Kg" titlelabel="Poids" />
<FIELD name="SERVICE" label="Service" titlelabel="Service" />
<FIELD name="ID_STOCK" label="Stock" titlelabel="Stock" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
152,7 → 160,7
<FIELD name="PV_HT" label="Prix vente HT" titlelabel="Prix vente HT" />
<FIELD name="PV_TTC" label="Prix vente TTC" titlelabel="Prix vente TTC" />
 
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
</TABLE>
 
<TABLE name="ARTICLE_DESIGNATION">
221,6 → 229,9
</TABLE>
 
<TABLE name="AVOIR_CLIENT_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="ID_PAYS" label="Pays d'origine" titlelabel="Pays d'origine" />
<FIELD name="CODE_DOUANIER" label="Code douanier" titlelabel="Code douanier" />
235,16 → 246,16
<FIELD name="PA_HT" label="PA Unitaire HT" titlelabel="PA Unitaire HT" />
<FIELD name="PV_HT" label="PV Unitaire HT" titlelabel="PV Unitaire HT" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="T_POIDS" label="Poids total" titlelabel="Poids total" />
<FIELD name="T_PA_HT" label="Total HA HT" titlelabel="Poids total" />
<FIELD name="T_PA_HT" label="Total achat HT" titlelabel="Poids total" />
<FIELD name="T_PV_HT" label="Total HT" titlelabel="Total HT" />
<FIELD name="MARGE_HT" label="Marge HT" titlelabel="Marge HT" />
<FIELD name="T_PV_TTC" label="Total TTC" titlelabel="Total TTC" />
<FIELD name="QTE" label="Quantité" titlelabel="Qté" />
<FIELD name="SERVICE" label="Service" titlelabel="Service" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
356,6 → 367,9
</TABLE>
 
<TABLE name="BON_RECEPTION_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="NOM" label="Libellé" titlelabel="Libellé" />
367,9 → 381,9
 
<FIELD name="QTE" label="Qté reçue" titlelabel="Qté reçue" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV² HT" titlelabel="PHA UV HT" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV² HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
414,6 → 428,9
<FIELD name="T_DEVISE" label="Total Devise" titlelabel="Total Devise" />
</TABLE>
<TABLE name="BON_DE_LIVRAISON_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="ID_PAYS" label="Pays d'origine" titlelabel="Pays d'origine" />
<FIELD name="CODE_DOUANIER" label="Code douanier" titlelabel="Code douanier" />
436,9 → 453,9
<FIELD name="QTE_LIVREE" label="Quantité livrée" titlelabel="Qté livrée" />
<FIELD name="QTE_A_LIVRER" label="Quantité à livrer" titlelabel="Qté à livrer" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
740,9 → 757,15
<FIELD name="T_POIDS" label="Poids total" titlelabel="Poids total" />
<FIELD name="ID_POLE_PRODUIT" label="Pôle produit" titlelabel="Pôle produit" />
<FIELD name="ID_DEVISE" label="Devise" titlelabel="Devise" />
<FIELD name="ID_CLIENT" label="Client" titlelabel="Client" />
<FIELD name="ID_ADRESSE" label="Adresse de livraison spécifique"
titlelabel="Adresse de livraison spécifique" />
</TABLE>
 
<TABLE name="COMMANDE_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="ID_DEVISE" label="Devise" titlelabel="Devise" />
<FIELD name="PA_DEVISE" label="PA Devise" titlelabel="PA Devise" />
<FIELD name="PA_DEVISE_T" label="PA Devise Total" titlelabel="PA Devise Total" />
754,11 → 777,11
<FIELD name="PA_HT" label="PA Unitaire HT" titlelabel="PA Unitaire HT" />
<FIELD name="PV_HT" label="PV Unitaire HT" titlelabel="PV Unitaire HT" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="QTE" label="Quantité" titlelabel="Qté" />
<FIELD name="SERVICE" label="Service" titlelabel="Service" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
800,6 → 823,9
</TABLE>
 
<TABLE name="COMMANDE_CLIENT_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="POURCENT_REMISE" label="% remise" titlelabel="% remise" />
<FIELD name="ID_PAYS" label="Pays d'origine" titlelabel="Pays d'origine" />
815,11 → 841,11
<FIELD name="MARGE_HT" label="Marge HT" titlelabel="Marge HT" />
<FIELD name="PV_HT" label="PV Unitaire HT" titlelabel="PV Unitaire HT" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="QTE" label="Quantité" titlelabel="Qté" />
<FIELD name="SERVICE" label="Service" titlelabel="Service" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
950,6 → 976,9
<FIELD name="T_DEVISE" label="Total Devise" titlelabel="Total Devise" />
</TABLE>
<TABLE name="DEVIS_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="MARGE_HT" label="Marge HT" titlelabel="Marge HT" />
<FIELD name="POURCENT_REMISE" label="% remise" titlelabel="% remise" />
965,15 → 994,15
<FIELD name="PA_HT" label="PA Unitaire HT" titlelabel="PA Unitaire HT" />
<FIELD name="PV_HT" label="PV Unitaire HT" titlelabel="PV Unitaire HT" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="T_POIDS" label="Poids total" titlelabel="Poids total" />
<FIELD name="T_PA_HT" label="Total HA HT" titlelabel="Total HA HT" />
<FIELD name="T_PA_HT" label="Total achat HT" titlelabel="Total achat HT" />
<FIELD name="T_PV_HT" label="Total HT" titlelabel="Total HT" />
<FIELD name="T_PV_TTC" label="Total TTC" titlelabel="Total TTC" />
<FIELD name="QTE" label="Quantité" titlelabel="Qté" />
<FIELD name="SERVICE" label="Service" titlelabel="Service" />
<FIELD name="PRIX_METRIQUE_VT_1" label="PV UV HT" titlelabel="PV UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="PHA UV HT" titlelabel="PHA UV HT" />
<FIELD name="PRIX_METRIQUE_VT_1" label="P.V. UV HT" titlelabel="P.V. UV HT" />
<FIELD name="PRIX_METRIQUE_HA_1" label="P.A. UV HT" titlelabel="P.A. UV HT" />
<FIELD name="VALEUR_METRIQUE_1" label="Longueur par défaut"
titlelabel="Longueur par défaut" />
<FIELD name="ID_METRIQUE_1" label="Métrique" titlelabel="Métrique" />
1028,6 → 1057,13
<FIELD name="ID_FOURNISSEUR" label="Fournisseur" titlelabel="Fournisseur" />
</TABLE>
 
<TABLE name="ECHEANCIER_CCI">
<FIELD name="DATE" label="Date" titlelabel="Date" />
<FIELD name="MONTANT_HT" label="Montant HT" titlelabel="Montant HT" />
<FIELD name="NOM" label="Intitulé" titlelabel="Intitulé" />
<FIELD name="ID_AFFAIRE" label="Affaire" titlelabel="Affaire" />
</TABLE>
 
<TABLE name="ECOTAXE">
<FIELD name="NOM" label="Ecotaxe" titlelabel="Ecotaxe" />
<FIELD name="MONTANT_HT" label="Montant ht" titlelabel="Montant ht" />
1238,6 → 1274,8
</TABLE>
 
<TABLE name="FOURNISSEUR">
<FIELD name="ID_COMPTE_PCE_CHARGE" label="Compte de charge par défaut"
titlelabel="Compte de charge par défaut" />
<FIELD name="TYPE" label="Type" titlelabel="Type" />
<FIELD name="RESPONSABLE" label="Responsable" titlelabel="Responsable" />
<FIELD name="TEL_P" label="Mobile" titlelabel="Mobile" />
1388,6 → 1426,8
<FIELD name="AFFAIRE_START" label="Prochain numéro" titlelabel="Prochain numéro" />
<FIELD name="AVOIR_FORMAT" label="Format" titlelabel="Format" />
<FIELD name="AVOIR_START" label="Prochain numéro" titlelabel="Prochain numéro" />
<FIELD name="AVOIR_F_FORMAT" label="Format" titlelabel="Format" />
<FIELD name="AVOIR_F_START" label="Prochain numéro" titlelabel="Prochain numéro" />
<FIELD name="DEVIS_FORMAT" label="Format" titlelabel="Format" />
<FIELD name="DEVIS_START" label="Prochain numéro" titlelabel="Prochain numéro" />
<FIELD name="BON_L_FORMAT" label="Format" titlelabel="Format" />
1412,6 → 1452,15
<FIELD name="COURRIER_FORMAT" label="Format" titlelabel="Format" />
<FIELD name="COURRIER_START" label="Prochain numéro" titlelabel="Prochain numéro" />
</TABLE>
<TABLE name="OBJECTIF_COMMERCIAL">
<FIELD name="ANNEE" label="Année" titlelabel="Année" />
<FIELD name="MOIS" label="Mois" titlelabel="Mois" />
<FIELD name="MARGE_HT" label="Marge HT" titlelabel="Marge HT" />
<FIELD name="POURCENT_MARGE" label="% Marge" titlelabel="% Marge" />
<FIELD name="CHIFFRE_AFFAIRE" label="Chiffre d'affaire"
titlelabel="Chiffre d'affaire" />
<FIELD name="ID_COMMERCIAL" label="Commercial" titlelabel="Commercial" />
</TABLE>
 
<TABLE name="ORDRE_MISSION">
<FIELD name="ID_VERIFICATEUR" label="Vérificateur" titlelabel="Vérificateur" />
1758,11 → 1807,15
<FIELD name="ID_REFERENCE_CLIENT" label="Référence client"
titlelabel="Référence client" />
<FIELD name="ID_VERIFICATEUR" label="Vérificateur" titlelabel="Vérificateur" />
<FIELD name="ID_MODELE" label="Modéle" titlelabel="Modéle" />
<FIELD name="CONTROLE_TECHNIQUE" label="Facture CTC" titlelabel="Facture CTC" />
<FIELD name="COMPTE_SERVICE_AUTO" label="Gestion automatique du compte de service"
titlelabel="Gestion automatique du compte de service" />
</TABLE>
<TABLE name="SAISIE_VENTE_FACTURE_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="ID_PAYS" label="Pays d'origine" titlelabel="Pays d'origine" />
<FIELD name="CODE_DOUANIER" label="Code douanier" titlelabel="Code douanier" />
1785,7 → 1838,7
<FIELD name="MARGE_HT" label="Marge HT" titlelabel="Marge HT" />
<FIELD name="PA_HT" label="PA Unitaire HT" titlelabel="PA Unitaire HT" />
<FIELD name="ID_TAXE" label="Taxe" titlelabel="Taxe" />
<FIELD name="POIDS" label="Poids" titlelabel="Poids" />
<FIELD name="POIDS" label="Poids UV" titlelabel="Poids UV" />
<FIELD name="QTE" label="Quantité" titlelabel="Qté" />
<FIELD name="QTE_LIVREE" label="Quantité livrée" titlelabel="Qté livrée" />
<FIELD name="LIVREE" label="Livrée" titlelabel="Livrée" />
1965,4 → 2018,9
<FIELD name="HEURE_ABS" label="Heures d'abscence" titlelabel="Heures d'abscence" />
</TABLE>
 
<TABLE name="UNITE_VENTE">
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="NOM" label="Libellè" titlelabel="Libellé" />
</TABLE>
 
</ROOT>
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerFinderPanel.java
90,7 → 90,7
 
ExceptionHandler.setForceUI(true);
ExceptionHandler.setForumURL("http://www.openconcerto.org/forum");
ProductInfo.setInstance(new ProductInfo("OpenConcerto_Configuration"));
ProductInfo.setInstance(new ProductInfo("OpenConcerto"));
PropsConfiguration conf = new PropsConfiguration(new Properties()) {
@Override
protected File createWD() {
122,12 → 122,28
});
}
 
public static final boolean containsValidH2DB(File dir) {
if (dir.exists()) {
File db = new File(dir, "OpenConcerto.h2.db");
if (db.exists() && db.length() > 50000) {
return true;
}
}
return false;
}
 
protected void loadConfigFile() {
this.textMainProperties.setText(confFile.getAbsolutePath());
if (!this.confFile.exists()) {
System.out.println("Unable to find: " + this.confFile.getAbsolutePath());
 
this.textFile.setText(new File(Configuration.getDefaultConfDir(), "OpenConcerto-GESTION_DEFAULT/DBData").getAbsolutePath());
final File dir1 = new File(Configuration.getDefaultConfDir(), "OpenConcerto-GESTION_DEFAULT/DBData");
final File dir2 = new File(Configuration.getDefaultConfDir(), "OpenConcerto/DBData");
if (containsValidH2DB(dir1)) {
this.textFile.setText(dir1.getAbsolutePath());
} else if (containsValidH2DB(dir2)) {
this.textFile.setText(dir2.getAbsolutePath());
}
return;
}
System.out.println("Loading: " + this.confFile.getAbsolutePath());
295,12 → 311,20
c.fill = GridBagConstraints.BOTH;
this.tabbedPane = new JTabbedPane(JTabbedPane.TOP);
this.add(this.tabbedPane, c);
this.tabbedPane.addTab("Configuration", createPanelConfig());
this.tabbedPane.addTab("Recherche", createPanelFinder());
final JPanel configurationPanel = createPanelConfig();
final JPanel findServerPanel = createPanelFinder();
if (getToken() == null) {
this.tabbedPane.addTab("Configuration", configurationPanel);
this.tabbedPane.addTab("Recherche", findServerPanel);
}
final ConfigCaissePanel createPanelCaisse = createPanelCaisse();
this.tabbedPane.addTab("Caisse", createPanelCaisse);
this.tabbedPane.addTab("Installation", new InstallationPanel(this));
this.tabbedPane.addTab("Cloud", new CloudPanel(this));
if (getToken() != null) {
this.tabbedPane.setSelectedIndex(2);
}
 
final JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 2, 1));
buttons.setOpaque(false);
/trunk/OpenConcerto/src/org/openconcerto/erp/config/InstallationPanel.java
13,6 → 13,8
package org.openconcerto.erp.config;
 
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.changer.convert.AddFK;
import org.openconcerto.sql.changer.correct.CorrectOrder;
import org.openconcerto.sql.changer.correct.FixSerial;
51,6 → 53,7
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
125,6 → 128,8
updateVariablePaye(table, "PART_SAL_GarantieMP", 23.83);
updateVariablePaye(table, "PART_PAT_GarantieMP", 38.98);
 
updateSocieteTable(conf.getRoot());
 
if (!table.getDBRoot().contains("DEVISE")) {
System.out.println("InstallationPanel.InstallationPanel() ADD DEVISE");
try {
223,6 → 228,11
});
i++;
final DBRoot root = conf.getSystemRoot().getRoot(childName);
try {
conf.getSystemRoot().getDataSource().execute("CREATE LANGUAGE plpgsql;");
} catch (Exception e) {
System.err.println("Warning: cannot add language plpgsql" + e.getMessage());
}
final SQLTable tableUndef = root.getTable(SQLTable.undefTable);
if (tableUndef != null && tableUndef.getField("UNDEFINED_ID").isNullable() == Boolean.FALSE) {
final AlterTable alterUndef = new AlterTable(tableUndef);
247,7 → 257,11
public Object create() throws SQLException {
fixUnboundedVarchar(root);
fixUnboundedNumeric(root);
try {
updateSocieteSchema(root);
} catch (Exception e) {
throw new SQLException(e);
}
updateToV1Dot2(root);
return null;
}
256,7 → 270,7
 
}
error = false;
} catch (Exception e1) {
} catch (Throwable e1) {
ExceptionHandler.handle("Echec de mise à jour", e1);
error = true;
}
280,7 → 294,7
}
 
});
 
if (finderPanel.getToken() == null) {
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(new JLabelBold("Création de l'utilisateur openconcerto dans la base"), c);
377,7 → 391,8
// public void actionPerformed(ActionEvent e) {
// File f = new File(chemin.getText());
// if (!f.exists()) {
// JOptionPane.showMessageDialog(InstallationPanel.this, "Impossible de trouver le fichier "
// JOptionPane.showMessageDialog(InstallationPanel.this,
// "Impossible de trouver le fichier "
// + chemin.getText());
// return;
// }
470,18 → 485,24
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;");
// 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;");
ds.execute("CREATE LANGUAGE plpgsql;");
 
} 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é.");
JOptionPane.showMessageDialog(null, "Paramètrage terminé.");
}
});
this.add(buttonPL, c);
 
}
c.gridy++;
c.gridx = 0;
c.weightx = 1;
641,6 → 662,13
}
}
 
final SQLTable tableEtatDevis = root.getTable("ETAT_DEVIS");
if (tableEtatDevis.getRow(5) == null && tableEtatDevis.getRowCount() <= 4) {
SQLRowValues rowVals = new SQLRowValues(tableEtatDevis);
rowVals.put("NOM", "En cours de rédaction");
rowVals.commit();
}
 
// Bon de livraison
{
SQLTable tableBL = root.getTable("BON_DE_LIVRAISON");
669,6 → 697,52
}
}
}
 
// Fournisseur
{
SQLTable tableBL = root.getTable("FOURNISSEUR");
boolean alterBL = false;
AlterTable t = new AlterTable(tableBL);
if (!tableBL.getFieldsName().contains("ID_COMPTE_PCE_CHARGE")) {
t.addForeignColumn("ID_COMPTE_PCE_CHARGE", root.getTable("COMPTE_PCE"));
alterBL = true;
}
if (alterBL) {
try {
ds.execute(t.asString());
tableBL.getSchema().updateVersion();
tableBL.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table FOURNISSEUR", ex);
}
}
}
 
// Numérotation
{
SQLTable tableNum = root.getTable("NUMEROTATION_AUTO");
boolean alterNum = false;
AlterTable t = new AlterTable(tableNum);
if (!tableNum.getFieldsName().contains("AVOIR_F_START")) {
t.addColumn("AVOIR_F_START", "integer DEFAULT 0");
alterNum = true;
}
if (!tableNum.getFieldsName().contains("AVOIR_F_FORMAT")) {
t.addVarCharColumn("AVOIR_F_FORMAT", 48);
alterNum = true;
}
 
if (alterNum) {
try {
ds.execute(t.asString());
tableNum.getSchema().updateVersion();
tableNum.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table NUMEROTATION_AUTO", ex);
}
}
}
 
SQLTable tableArticle = root.getTable("ARTICLE");
 
AlterTable t = new AlterTable(tableArticle);
698,11 → 772,11
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("ID_DEVISE")) {
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("ID_FOURNISSEUR")) {
t.addForeignColumn("ID_FOURNISSEUR", root.findTable("FOURNISSEUR"));
t.addForeignColumn("ID_FOURNISSEUR", root.findTable("FOURNISSEUR", true));
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("PV_U_DEVISE")) {
710,7 → 784,7
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("ID_DEVISE_HA")) {
t.addForeignColumn("ID_DEVISE_HA", root.findTable("DEVISE"));
t.addForeignColumn("ID_DEVISE_HA", root.findTable("DEVISE", true));
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("PA_DEVISE")) {
718,7 → 792,7
alterArticle = true;
}
if (!tableArticle.getFieldsName().contains("ID_PAYS")) {
t.addForeignColumn("ID_PAYS", root.findTable("PAYS"));
t.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
alterArticle = true;
}
if (alterArticle) {
733,6 → 807,26
 
// Création de la table Langue
boolean refetchRoot = false;
if (!root.contains("OBJECTIF_COMMERCIAL")) {
 
SQLCreateTable createObjectif = new SQLCreateTable(root, "OBJECTIF_COMMERCIAL");
createObjectif.addVarCharColumn("MOIS", 32);
createObjectif.addColumn("ANNEE", "integer");
createObjectif.addColumn("MARGE_HT", "bigint DEFAULT 0");
createObjectif.addColumn("POURCENT_MARGE", "numeric (16,8)");
createObjectif.addColumn("CHIFFRE_AFFAIRE", "bigint DeFAULT 0");
createObjectif.addForeignColumn("COMMERCIAL");
try {
ds.execute(createObjectif.asString());
insertUndef(createObjectif);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table OBJECTIF_COMMERCIAL", ex);
}
 
}
 
if (!root.contains("LANGUE")) {
 
SQLCreateTable createLangue = new SQLCreateTable(root, "LANGUE");
743,7 → 837,7
ds.execute(createLangue.asString());
insertUndef(createLangue);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
root.refetch(createLangue.getName());
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table LANGUE", ex);
}
767,7 → 861,7
 
SQLCreateTable createModele = new SQLCreateTable(root, "MODELE");
createModele.addVarCharColumn("NOM", 256);
createModele.addForeignColumn("ID_TYPE_MODELE", root.findTable("TYPE_MODELE"));
createModele.addForeignColumn("ID_TYPE_MODELE", root.findTable("TYPE_MODELE", true));
try {
ds.execute(createModele.asString());
insertUndef(createModele);
809,29 → 903,27
 
SQLCreateTable createTarif = new SQLCreateTable(root, "TARIF");
createTarif.addVarCharColumn("NOM", 256);
createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE"));
createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE", true));
createTarif.asString();
try {
ds.execute(createTarif.asString());
insertUndef(createTarif);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
root.refetch(createTarif.getName());
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table TARIF", ex);
}
}
if (refetchRoot)
root.refetch();
 
// Création de la table article Tarif
if (!root.contains("ARTICLE_TARIF")) {
 
SQLCreateTable createTarif = new SQLCreateTable(root, "ARTICLE_TARIF");
createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE"));
createTarif.addForeignColumn("ID_TARIF", root.findTable("TARIF"));
createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE"));
createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE", true));
createTarif.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
createTarif.addColumn("PV_HT", "bigint DEFAULT 0");
createTarif.addColumn("PV_TTC", "bigint DEFAULT 0");
createTarif.addColumn("PRIX_METRIQUE_VT_1", "bigint DEFAULT 0");
842,6 → 934,7
ds.execute(createTarif.asString());
insertUndef(createTarif);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table ARTICLE_TARIF", ex);
}
851,8 → 944,8
if (!root.contains("ARTICLE_DESIGNATION")) {
 
SQLCreateTable createTarif = new SQLCreateTable(root, "ARTICLE_DESIGNATION");
createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE"));
createTarif.addForeignColumn("ID_LANGUE", root.findTable("LANGUE"));
createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
createTarif.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
createTarif.addVarCharColumn("NOM", 1024);
createTarif.asString();
try {
859,11 → 952,50
ds.execute(createTarif.asString());
insertUndef(createTarif);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table ARTICLE_DESIGNATION", ex);
}
}
 
if (!root.contains("UNITE_VENTE")) {
 
SQLCreateTable createUnite = new SQLCreateTable(root, "UNITE_VENTE");
createUnite.addVarCharColumn("CODE", 32);
createUnite.addVarCharColumn("NOM", 256);
createUnite.addColumn("A_LA_PIECE", "boolean DEFAULT false");
createUnite.addVarCharColumn("INFOS", 256);
try {
ds.execute(createUnite.asString());
insertUndef(createUnite);
final String insert = "INSERT into "
+ getTableName(createUnite).quote()
+ "(\"CODE\",\"NOM\",\"A_LA_PIECE\",\"ORDRE\") VALUES('pièce','à la pièce',true,1),('m','mètres',false,2),('m²','mètres carré',false,3),('m3','mètres cube',false,4),('l','litres',false,5),('kg','kilos',false,6),('h','heures',false,7),('j','jours',false,8),('mois','mois',false,9)";
root.getDBSystemRoot().getDataSource().execute(insert);
tableDevis.getSchema().updateVersion();
refetchRoot = true;
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table UNITE_VENTE", ex);
}
 
}
 
// Chargement des tables fraichement créées
if (refetchRoot)
root.refetch();
 
if (!tableArticle.getFieldsName().contains("ID_UNITE_VENTE")) {
AlterTable alterTableArticle = new AlterTable(tableArticle);
alterTableArticle.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
try {
ds.execute(alterTableArticle.asString());
tableArticle.getSchema().updateVersion();
tableArticle.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout du champ UNITE_VENTE sur la table ARTICLE", ex);
}
}
 
SQLTable tableVFElt = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
addVenteEltField(tableVFElt, root);
 
893,7 → 1025,7
 
if (!tableCommande.getFieldsName().contains("ID_ADRESSE")) {
AlterTable alterCmd = new AlterTable(tableCommande);
alterCmd.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE"));
alterCmd.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE", true));
try {
ds.execute(alterCmd.asString());
tableCommande.getSchema().updateVersion();
902,7 → 1034,18
}
 
}
if (!tableCommande.getFieldsName().contains("ID_CLIENT")) {
AlterTable alterCmd = new AlterTable(tableCommande);
alterCmd.addForeignColumn("ID_CLIENT", root.findTable("CLIENT"));
try {
ds.execute(alterCmd.asString());
tableCommande.getSchema().updateVersion();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table COMMANDE", ex);
}
 
}
 
{
addTotalDeviseField(tableDevis, root);
addModeleField(tableDevis, root);
934,20 → 1077,20
boolean alterClient = false;
 
if (!tableClient.getFieldsName().contains("ID_TARIF")) {
tClient.addForeignColumn("ID_TARIF", root.findTable("TARIF"));
tClient.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
alterClient = true;
}
if (!tableClient.getFieldsName().contains("ID_PAYS")) {
tClient.addForeignColumn("ID_PAYS", root.findTable("PAYS"));
tClient.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
alterClient = true;
}
if (!tableClient.getFieldsName().contains("ID_LANGUE")) {
tClient.addForeignColumn("ID_LANGUE", root.findTable("LANGUE"));
tClient.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
alterClient = true;
}
 
if (!tableClient.getFieldsName().contains("ID_DEVISE")) {
tClient.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
tClient.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alterClient = true;
}
if (alterClient) {
968,11 → 1111,11
boolean alterPays = false;
 
if (!tablePays.getFieldsName().contains("ID_TARIF")) {
tPays.addForeignColumn("ID_TARIF", root.findTable("TARIF"));
tPays.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
alterPays = true;
}
if (!tablePays.getFieldsName().contains("ID_LANGUE")) {
tPays.addForeignColumn("ID_LANGUE", root.findTable("LANGUE"));
tPays.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
alterPays = true;
}
if (alterPays) {
1012,11 → 1155,11
boolean alterFourn = false;
 
if (!tableFournisseur.getFieldsName().contains("ID_LANGUE")) {
tFourn.addForeignColumn("ID_LANGUE", root.findTable("LANGUE"));
tFourn.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
alterFourn = true;
}
if (!tableFournisseur.getFieldsName().contains("ID_DEVISE")) {
tFourn.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
tFourn.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alterFourn = true;
}
if (!tableFournisseur.getFieldsName().contains("RESPONSABLE")) {
1138,7 → 1281,7
}
 
{
SQLTable tableContrat = root.findTable("CONTRAT_SALARIE");
SQLTable tableContrat = root.findTable("CONTRAT_SALARIE", true);
boolean alter2 = false;
AlterTable t2 = new AlterTable(tableContrat);
// UGRR
1171,7 → 1314,7
}
 
if (!tableContrat.getFieldsName().contains("ID_CODE_STATUT_CAT_CONV")) {
t2.addForeignColumn("ID_CODE_STATUT_CAT_CONV", root.findTable("CODE_STATUT_CAT_CONV"));
t2.addForeignColumn("ID_CODE_STATUT_CAT_CONV", root.findTable("CODE_STATUT_CAT_CONV", true));
alter2 = true;
}
 
1192,7 → 1335,7
boolean alter = false;
AlterTable t = new AlterTable(table);
if (!table.getFieldsName().contains("ID_DEVISE")) {
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alter = true;
}
 
1220,16 → 1363,24
t.addColumn("QTE_ACHAT", "integer DEFAULT 1");
alter = true;
}
// if (!table.getFieldsName().contains("ID_ARTICLE")) {
// t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE"));
// alter = true;
// }
if (!table.getFieldsName().contains("QTE_UNITAIRE")) {
t.addColumn("QTE_UNITAIRE", "numeric(16,6) DEFAULT 1");
alter = true;
}
if (!table.getFieldsName().contains("ID_UNITE_VENTE")) {
t.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
alter = true;
}
if (!table.getFieldsName().contains("ID_ARTICLE")) {
t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
alter = true;
}
if (!table.getFieldsName().contains("PA_DEVISE")) {
t.addColumn("PA_DEVISE", "bigint default 0");
alter = true;
}
if (!table.getFieldsName().contains("ID_DEVISE")) {
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alter = true;
}
 
1284,7 → 1435,7
alter = true;
}
if (!table.getFieldsName().contains("ID_TARIF")) {
t.addForeignColumn("ID_TARIF", root.findTable("TARIF"));
t.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
alter = true;
}
 
1307,10 → 1458,18
t.addColumn("QTE_ACHAT", "integer DEFAULT 1");
alter = true;
}
// if (!table.getFieldsName().contains("ID_ARTICLE")) {
// t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE"));
// alter = true;
// }
if (!table.getFieldsName().contains("QTE_UNITAIRE")) {
t.addColumn("QTE_UNITAIRE", "numeric(16,6) DEFAULT 1");
alter = true;
}
if (!table.getFieldsName().contains("ID_UNITE_VENTE")) {
t.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
alter = true;
}
if (!table.getFieldsName().contains("ID_ARTICLE")) {
t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
alter = true;
}
if (!table.getFieldsName().contains("CODE_DOUANIER")) {
t.addVarCharColumn("CODE_DOUANIER", 256);
alter = true;
1320,7 → 1479,7
alter = true;
}
if (!table.getFieldsName().contains("ID_PAYS")) {
t.addForeignColumn("ID_PAYS", root.findTable("PAYS"));
t.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
alter = true;
}
if (!table.getFieldsName().contains("MARGE_HT")) {
1329,7 → 1488,7
}
 
if (!table.getFieldsName().contains("ID_DEVISE")) {
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE"));
t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
alter = true;
}
if (!table.getFieldsName().contains("PV_U_DEVISE")) {
1359,7 → 1518,7
}
}
 
private void updateSocieteSchema(final DBRoot root) throws SQLException {
private void updateSocieteSchema(final DBRoot root) throws IOException, Exception {
final DBSystemRoot sysRoot = root.getDBSystemRoot();
final SQLDataSource ds = sysRoot.getDataSource();
System.out.println("InstallationPanel.InstallationPanel() UPDATE COMMERCIAL " + root);
1470,9 → 1629,9
// Suppression des champs 1.0
System.out.println("InstallationPanel.InstallationPanel() UPDATE FROM 1.0 " + root);
final List<ChangeTable<?>> changes = new ArrayList<ChangeTable<?>>();
 
List<String> tablesToRemove = new ArrayList<String>();
tablesToRemove.add("AFFAIRE");
tablesToRemove.add("AFFAIRE_ELEMENT");
tablesToRemove.add("RAPPORT");
tablesToRemove.add("CODE_MISSION");
tablesToRemove.add("FICHE_RENDEZ_VOUS");
1483,7 → 1642,6
tablesToRemove.add("FICHE_RENDEZ_VOUS_ELEMENT");
tablesToRemove.add("POURCENT_SERVICE");
tablesToRemove.add("PROPOSITION");
tablesToRemove.add("AFFAIRE_ELEMENT");
tablesToRemove.add("PROPOSITION_ELEMENT");
tablesToRemove.add("POLE_PRODUIT");
tablesToRemove.add("BANQUE_POLE_PRODUIT");
1490,9 → 1648,19
tablesToRemove.add("AFFACTURAGE");
tablesToRemove.add("SECTEUR_ACTIVITE");
 
//
final ModuleManager instance = new ModuleManager();
instance.setRoot(root);
final Set<String> modulesIds = instance.getDBInstalledModules().keySet();
final Set<String> allUsedTable = new HashSet<String>();
for (String id : modulesIds) {
Set<String> tableNames = instance.getCreatedItems(id).get0();
allUsedTable.addAll(tableNames);
}
System.out.println("Tables used by modules:" + allUsedTable);
final DatabaseGraph graph = sysRoot.getGraph();
for (String tableName : tablesToRemove) {
if (root.contains(tableName)) {
if (!allUsedTable.contains(tableName) && root.contains(tableName)) {
 
final SQLTable table = root.getTable(tableName);
for (final Link link : graph.getReferentLinks(table)) {
1629,6 → 1797,13
}
 
private void updateCommon(DBRoot root) throws SQLException {
 
// rm ID 43 - 47 de SOCIETE_COMMON
final SQLTable tableSociete = root.getTable("SOCIETE_COMMON");
String req3 = "DELETE FROM " + tableSociete.getSQLName().quote() + " WHERE ";
req3 += new Where(tableSociete.getKey(), 43, 47).getClause();
root.getDBSystemRoot().getDataSource().execute(req3);
 
// rm ID 3 à 49 de EXERCICE_COMMON
final SQLTable tableExercice = root.getTable("EXERCICE_COMMON");
String req1a = "DELETE FROM " + tableExercice.getSQLName().quote() + " WHERE ";
1649,11 → 1824,6
String req2 = updateBuilder.asString();
root.getDBSystemRoot().getDataSource().execute(req2);
}
// rm ID 43 - 47 de SOCIETE_COMMON
final SQLTable tableSociete = root.getTable("SOCIETE_COMMON");
String req3 = "DELETE FROM " + tableSociete.getSQLName().quote() + " WHERE ";
req3 += new Where(tableSociete.getKey(), 43, 47).getClause();
root.getDBSystemRoot().getDataSource().execute(req3);
 
// FK
new AddFK(root.getDBSystemRoot()).change(root);
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerFinderConfig.java
71,10 → 71,17
 
public void setFile(File file) {
if (file == null) {
JOptionPane.showMessageDialog(new JFrame(), "Dossier de base de donnée vide");
JOptionPane.showMessageDialog(new JFrame(), "Dossier de base de données non défini");
} else if (!file.exists()) {
JOptionPane.showMessageDialog(new JFrame(), "Dossier de base de donnée inexistant");
JOptionPane.showMessageDialog(new JFrame(), "Dossier de base de données inexistant");
} else {
final File h2File = new File(file, "OpenConcerto.h2.db");
if (!h2File.exists()) {
JOptionPane.showMessageDialog(new JFrame(), "Le dossier de base de données ne contient pas OpenConcerto.h2.db");
} else if (h2File.length() < 50000) {
JOptionPane.showMessageDialog(new JFrame(), "Le dossier de base de données contient un fichier OpenConcerto.h2.db vide");
}
}
this.file = file;
}
 
230,7 → 237,7
input.getRootsToMap().add("postgres");
}
}, null);
Number n = (Number) server.getBase("postgres").getDataSource().executeScalar("SELECT COUNT(*) FROM pg_user WHERE usename='openconcerto'");
Number n = (Number) server.getOrCreateBase("postgres").getDataSource().executeScalar("SELECT COUNT(*) FROM pg_user WHERE usename='openconcerto'");
if (n.intValue() > 0) {
return false;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ComptaPropsConfiguration.java
62,6 → 62,7
import org.openconcerto.erp.core.humanresources.employe.SituationFamilialeSQLElement;
import org.openconcerto.erp.core.humanresources.employe.element.CommercialSQLElement;
import org.openconcerto.erp.core.humanresources.employe.element.EtatCivilSQLElement;
import org.openconcerto.erp.core.humanresources.employe.element.ObjectifSQLElement;
import org.openconcerto.erp.core.humanresources.payroll.element.AcompteSQLElement;
import org.openconcerto.erp.core.humanresources.payroll.element.CaisseCotisationSQLElement;
import org.openconcerto.erp.core.humanresources.payroll.element.ClassementConventionnelSQLElement;
116,6 → 117,7
import org.openconcerto.erp.core.sales.product.element.MetriqueSQLElement;
import org.openconcerto.erp.core.sales.product.element.ModeVenteArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import org.openconcerto.erp.core.sales.quote.element.DevisItemSQLElement;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
153,6 → 155,8
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.erp.rights.ComptaTotalUserRight;
import org.openconcerto.erp.storage.CloudStorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.ShowAs;
170,7 → 174,6
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.task.TacheActionManager;
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
import org.openconcerto.ui.ReloadPanel;
import org.openconcerto.utils.DesktopEnvironment;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.NetUtils;
177,6 → 180,14
import org.openconcerto.utils.ProductInfo;
import org.openconcerto.utils.StringInputStream;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
191,7 → 202,7
import java.util.List;
import java.util.Properties;
 
import javax.swing.JDialog;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
273,7 → 284,7
final Properties props;
// webstart should be self-contained, e.g. if a user launches from the web it shoudln't
// read an old preference file but should always read its own configuration.
if (confFile.exists() && !inWebStart) {
if (confFile != null && confFile.exists() && !inWebStart) {
props = create(new FileInputStream(confFile), defaults);
} else {
final InputStream stream = ComptaPropsConfiguration.class.getResourceAsStream(PROPERTIES);
287,18 → 298,7
return new ComptaPropsConfiguration(props, inWebStart);
} catch (final IOException e) {
e.printStackTrace();
 
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ExceptionHandler.die("Impossible de lire le fichier de configuration.", e);
}
});
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
// never reached since we're already dead
return null;
}
320,10 → 320,11
}
 
//
String token = getProperty("token");
String token = getToken();
if (token != null) {
this.isServerless = false;
this.isOnCloud = true;
if (this.getProperty("storage.server") == null) {
InProgressFrame progress = new InProgressFrame();
progress.show("Connexion sécurisée au cloud en cours");
String result = NetUtils.getHTTPContent("https://cloud.openconcerto.org/getAuthInfo?token=" + token, false);
359,7 → 360,8
JOptionPane.showMessageDialog(new JFrame(), "Connexion impossible au Cloud");
System.exit(1);
}
 
}
StorageEngines.getInstance().addEngine(new CloudStorageEngine());
} else {
// Local database
setProperty("server.login", "openconcerto");
377,6 → 379,10
UserRightsManager.getInstance().register(new ComptaTotalUserRight());
}
 
public String getToken() {
return getProperty("token");
}
 
@Override
public void destroy() {
// since we used setupLogging() in the constructor (allows to remove confDir)
563,7 → 569,7
dir.addSQLElement(new CommandeClientElementSQLElement());
 
dir.addSQLElement(new CommercialSQLElement());
 
dir.addSQLElement(ObjectifSQLElement.class);
dir.addSQLElement(new ComptePCESQLElement());
dir.addSQLElement(new ComptePCGSQLElement());
 
655,6 → 661,7
dir.addSQLElement(new TypeReglementSQLElement());
 
dir.addSQLElement(new VariableSalarieSQLElement());
dir.addSQLElement(UniteVenteArticleSQLElement.class);
Collection<SQLElement> elements = dir.getElements();
for (SQLElement sqlElement : elements) {
GlobalMapper.getInstance().map(sqlElement.getCode() + ".element", this);
872,4 → 879,47
progress.dispose();
return server;
}
 
public static ComptaPropsConfiguration getInstanceCompta() {
return (ComptaPropsConfiguration) getInstance();
}
 
public String getStorageServer() {
return this.getProperty("storage.server");
}
 
public Image getCustomLogo() {
final File dir = new File(getConfFile().getParent());
final File file = new File(dir, "logo.png");
 
BufferedImage im = null;
if (file.exists()) {
try {
im = ImageIO.read(file);
if (im.getHeight() < 16) {
JOptionPane.showMessageDialog(new JFrame(), "Logo too small (height < 16 pixels)");
return null;
}
if (im.getWidth() < 200) {
JOptionPane.showMessageDialog(new JFrame(), "Logo too small (width < 200 pixels)");
return null;
}
final Graphics g = im.getGraphics();
 
g.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 11));
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final String str = "Powered by OpenConcerto";
final Rectangle2D r = g.getFontMetrics().getStringBounds(str, g);
g.setColor(new Color(255, 255, 255, 200));
g.fillRect(0, im.getHeight() - (int) r.getHeight() - 2, (int) r.getWidth() + 8, (int) r.getHeight() + 4);
g.setColor(Color.BLACK);
g.drawString(str, 4, im.getHeight() - 4);
g.dispose();
} catch (IOException e) {
e.printStackTrace();
}
 
}
return im;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/MainFrame.java
132,6 → 132,7
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
270,6 → 271,11
});
 
setInstance(this);
// Overrive logo
Image im = ComptaPropsConfiguration.getInstanceCompta().getCustomLogo();
if (im != null) {
image.setImage(im);
}
new NewsUpdater(this.image);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/config/NewsUpdater.java
53,7 → 53,6
out.close();
in.close();
final ImageIcon im = new ImageIcon(tempFile.getAbsolutePath());
System.out.println(im.getImageLoadStatus());
 
if (im.getImageLoadStatus() == MediaTracker.COMPLETE) {
SwingUtilities.invokeLater(new Runnable() {
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/JarModuleFactory.java
22,11 → 22,14
import java.util.Properties;
import java.util.jar.JarFile;
 
import net.jcip.annotations.ThreadSafe;
 
/**
* A module factory created from a {@link ModulePackager packaged} module.
*
* @author Sylvain CUAZ
*/
@ThreadSafe
public final class JarModuleFactory extends ModuleFactory {
 
private static Properties getProperties(final File jar) throws IOException {
84,6 → 87,7
 
protected final URL[] getClassPath() {
try {
// File is immutable and URI is stack confined
return new URL[] { this.jar.toURI().toURL() };
} catch (MalformedURLException e) {
// shouldn't happen since we create the URL from an URI
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleFactory.java
20,6 → 20,7
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
29,11 → 30,14
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import net.jcip.annotations.ThreadSafe;
 
/**
* Parse module properties, and allow to create modules.
*
* @author Sylvain CUAZ
*/
@ThreadSafe
public abstract class ModuleFactory {
 
public static final String NAME_KEY = "name";
101,13 → 105,13
this.contact = getRequiredProp(props, "contact");
final String depends = props.getProperty("depends", "").trim();
final String[] dependsArray = depends.length() == 0 ? new String[0] : dependsSplitPatrn.split(depends);
this.dependsPredicates = new HashMap<String, IPredicate<ModuleFactory>>(dependsArray.length);
final HashMap<String, IPredicate<ModuleFactory>> map = new HashMap<String, IPredicate<ModuleFactory>>(dependsArray.length);
for (final String depend : dependsArray) {
final Matcher dependMatcher = dependsPatrn.matcher(depend);
if (!dependMatcher.matches())
throw new IllegalArgumentException("'" + depend + "' doesn't match " + dependsPatrn.pattern());
final ModuleVersion depVersion = getVersion(dependMatcher, 2);
this.dependsPredicates.put(dependMatcher.group(1), new IPredicate<ModuleFactory>() {
map.put(dependMatcher.group(1), new IPredicate<ModuleFactory>() {
@Override
public boolean evaluateChecked(ModuleFactory input) {
return input.getVersion().compareTo(depVersion) >= 0;
114,6 → 118,7
}
});
}
this.dependsPredicates = Collections.unmodifiableMap(map);
 
final String entryPoint = checkMatch(javaIdentifiedPatrn, props.getProperty("entryPoint", "Module"), "Entry point");
this.mainClass = this.id + "." + entryPoint;
153,7 → 158,8
return this.dependsPredicates.get(f.getID()).evaluateChecked(f);
}
 
protected final ResourceBundle getResourceBundle() {
// ResourceBundle is thread-safe
protected synchronized final ResourceBundle getResourceBundle() {
if (this.rsrcBundle == null) {
// don't allow classes to simplify class loaders
this.rsrcBundle = ResourceBundle.getBundle(getID() + ".ModuleResources", Locale.getDefault(), getRsrcClassLoader(),
174,7 → 180,8
 
public abstract AbstractModule createModule(Map<String, AbstractModule> alreadyCreated) throws Exception;
 
protected final AbstractModule createModule(final Class<?> c) throws Exception {
// not sure if Class or Constructor are thread-safe
protected synchronized final AbstractModule createModule(final Class<?> c) throws Exception {
return (AbstractModule) c.getConstructor(ModuleFactory.class).newInstance(this);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleManager.java
45,6 → 45,7
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.ThreadFactory;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.cc.IdentityHashSet;
67,6 → 68,10
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
 
73,6 → 78,9
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
 
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
 
import org.jgrapht.DirectedGraph;
import org.jgrapht.EdgeFactory;
import org.jgrapht.graph.SimpleDirectedGraph;
82,9 → 90,12
*
* @author Sylvain CUAZ
*/
@ThreadSafe
public class ModuleManager {
 
private static final Logger L = Logger.getLogger(ModuleManager.class.getPackage().getName());
private static final Executor exec = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory(ModuleManager.class.getSimpleName()
+ " executor thread "));
 
private static final int MIN_VERSION = 0;
private static final String MODULE_COLNAME = "MODULE_NAME";
92,7 → 103,9
private static final String TABLE_COLNAME = "TABLE";
private static final String FIELD_COLNAME = "FIELD";
private static final String ISKEY_COLNAME = "KEY";
private static final String FWK_MODULE_TABLENAME = "FWK_MODULE_METADATA";
// Don't use String literals for the synchronized blocks
private static final String FWK_MODULE_TABLENAME = new String("FWK_MODULE_METADATA");
private static final String fileMutex = new String("modules");
private static ModuleManager instance = null;
 
public static synchronized ModuleManager getInstance() {
106,13 → 119,26
}
 
// only one version of each module
@GuardedBy("factories")
private final Map<String, ModuleFactory> factories;
// linked with dependencyGraph and to avoid starting twice the same module
// we synchronize the whole install/start and stop/uninstall
@GuardedBy("this")
private final Map<String, AbstractModule> runningModules;
// in fact it is also already guarded by "this"
@GuardedBy("modulesElements")
private final Map<String, Collection<SQLElement>> modulesElements;
// only in EDT
private final Map<String, ComponentsContext> modulesComponents;
// graph of running modules
@GuardedBy("this")
private final DirectedGraph<ModuleFactory, DirectedEdge<ModuleFactory>> dependencyGraph;
 
// perhaps add another mutex so we can query root or conf without having to wait for modules to
// install/uninstall
@GuardedBy("this")
private DBRoot root;
@GuardedBy("this")
private Configuration conf;
 
public ModuleManager() {
252,7 → 278,7
return true;
}
 
// *** modules (in EDT)
// *** modules (thread-safe)
 
/**
* Call the passed closure at a time when modules can be started. In particular this manager has
264,10 → 290,15
MainFrame.invoke(new Runnable() {
@Override
public void run() {
exec.execute(new Runnable() {
@Override
public void run() {
c.executeChecked(ModuleManager.this);
}
});
}
});
}
 
// call registerSQLElements() for any installed modules that might need it
// (e.g. if a module created a child table, as long as the table is in the database it needs to
308,6 → 339,27
}
 
/**
* Allow to access certain methods without a full {@link #setup(DBRoot, Configuration)}. If
* setup() is subsequently called it must be passed the same root instance.
*
* @param root the root.
* @throws IllegalStateException if already set.
* @see #getDBInstalledModules()
* @see #getCreatedItems(String)
*/
public synchronized final void setRoot(final DBRoot root) {
if (this.root != root) {
if (this.root != null)
throw new IllegalStateException("Root already set");
this.root = root;
}
}
 
public synchronized final boolean isSetup() {
return this.getRoot() != null && this.getConf() != null;
}
 
/**
* Initialise the module manager.
*
* @param root the root where the modules install.
317,17 → 369,18
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)
if (this.isSetup())
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;
final DBRoot currentRoot = this.getRoot();
this.setRoot(root);
this.conf = conf;
try {
this.registerRequiredModules();
} catch (Exception e) {
// allow setup() to be called again
this.root = null;
this.root = currentRoot;
this.conf = null;
throw e;
}
334,6 → 387,7
assert this.runningModules.isEmpty() && this.modulesComponents.isEmpty() : "registerRequiredModules() should not start modules";
}
 
// Preferences is thread-safe
private Preferences getPrefs() {
// modules are installed per business entity (perhaps we could add a per user option, i.e.
// for all businesses of all databases)
360,6 → 414,7
}
 
protected final ModuleVersion getModuleVersionInstalledLocally(String id) {
synchronized (fileMutex) {
final File versionFile = getLocalVersionFile(id);
if (versionFile.exists()) {
try {
371,6 → 426,7
return null;
}
}
}
 
public final Collection<String> getModulesInstalledLocally() {
return getModulesVersionInstalledLocally().keySet();
377,6 → 433,7
}
 
public final Map<String, ModuleVersion> getModulesVersionInstalledLocally() {
synchronized (fileMutex) {
final File dir = getLocalDirectory();
if (!dir.isDirectory())
return Collections.emptyMap();
389,9 → 446,11
}
return res;
}
}
 
private void setModuleInstalledLocally(ModuleFactory f, boolean b) {
try {
synchronized (fileMutex) {
if (b) {
final ModuleVersion vers = f.getVersion();
if (vers.getMerged() < MIN_VERSION)
403,6 → 462,7
// 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);
}
409,6 → 469,7
}
 
private SQLTable getInstalledTable(final DBRoot r) throws SQLException {
synchronized (FWK_MODULE_TABLENAME) {
if (!r.contains(FWK_MODULE_TABLENAME)) {
// store :
// - currently installed module (TABLE_COLNAME & FIELD_COLNAME are null)
427,10 → 488,11
 
r.createTable(createTable);
}
}
return r.getTable(FWK_MODULE_TABLENAME);
}
 
protected final DBRoot getRoot() {
public synchronized final DBRoot getRoot() {
return this.root;
}
 
438,7 → 500,7
return getRoot().getDBSystemRoot().getDataSource();
}
 
protected final Configuration getConf() {
public synchronized final Configuration getConf() {
return this.conf;
}
 
505,7 → 567,7
}
}
 
protected final boolean isModuleInstalledLocallyOrInDB(String id) throws SQLException {
protected synchronized final boolean isModuleInstalledLocallyOrInDB(String id) throws SQLException {
return this.isModuleInstalledLocally(id) || getDBInstalledModuleVersion(id) != null;
}
 
595,6 → 657,7
}
 
private void install(final AbstractModule module) throws Exception {
assert Thread.holdsLock(this);
final ModuleFactory factory = module.getFactory();
final ModuleVersion localVersion = getModuleVersionInstalledLocally(factory.getID());
final ModuleVersion lastInstalledVersion = getDBInstalledModuleVersion(factory.getID());
694,6 → 757,7
}
 
private void setupComponents(final AbstractModule module) throws SQLException {
assert SwingUtilities.isEventDispatchThread();
final String id = module.getFactory().getID();
if (!this.modulesComponents.containsKey(id)) {
final SQLElementDirectory dir = getDirectory();
708,6 → 772,13
startModules(Arrays.asList(getRequiredIDsPrefs().keys()));
}
 
/**
* Start modules that were deemed persistent.
*
* @throws Exception if an error occurs.
* @see #startModules(Collection, boolean)
* @see #stopModule(String, boolean)
*/
public final void startPreviouslyRunningModules() throws Exception {
final List<String> ids = Arrays.asList(getRunningIDsPrefs().keys());
startModules(ids);
722,7 → 793,18
return res.isEmpty();
}
 
public final Set<String> startModules(final Collection<String> ids, final boolean persistent) throws Exception {
/**
* Start the passed modules. If this method is called outside of the EDT the modules will be
* actually started using {@link SwingUtilities#invokeLater(Runnable)}, thus code that needs the
* module to be actually started must also be called inside an invokeLater().
*
* @param ids which modules to start.
* @param persistent <code>true</code> to start them the next time the application is launched,
* see {@link #startPreviouslyRunningModules()}.
* @return the started modules.
* @throws Exception if an error occurs.
*/
public synchronized final Set<String> startModules(final Collection<String> ids, final boolean persistent) throws Exception {
final Set<String> res = startModules(ids);
if (persistent) {
for (final String id : ids) {
740,9 → 822,9
 
// 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, final boolean inSetup) throws Exception {
private synchronized 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();
assert !inSetup || this.runningModules.isEmpty();
// add currently running modules so that ModuleFactory can use them
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>();
750,36 → 832,66
synchronized (this.factories) {
for (final String id : ids) {
final ModuleFactory f = getFactory(id);
if (canFactoryCreate(f, map)) {
for (final ModuleFactory useableFactory : map.keySet()) {
if (!modules.containsKey(useableFactory.getID()))
modules.put(useableFactory.getID(), useableFactory.createModule(Collections.unmodifiableMap(modules)));
}
} else {
if (!canFactoryCreate(f, map)) {
cannotCreate.add(id);
}
}
}
for (final ModuleFactory useableFactory : map.keySet()) {
final String id = useableFactory.getID();
if (inSetup || !this.runningModules.containsKey(id))
modules.put(id, useableFactory.createModule(Collections.unmodifiableMap(modules)));
}
// only keep modules created by this method
if (!inSetup)
modules.keySet().removeAll(this.runningModules.keySet());
 
if (start) {
for (final AbstractModule module : modules.values())
final Collection<AbstractModule> toStart = modules.values();
for (final AbstractModule module : toStart)
installAndRegister(module);
for (final AbstractModule module : toStart) {
final ModuleFactory f = module.getFactory();
final String id = f.getID();
try {
// execute right away if possible, allowing the caller to handle any exceptions
if (SwingUtilities.isEventDispatchThread()) {
startModule(module);
} else {
// keep the for outside to avoid halting the EDT too long
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
startModule(module);
} catch (Exception e) {
ExceptionHandler.handle(MainFrame.getInstance(), "Unable to start " + f, e);
}
}
});
}
} catch (Exception e) {
throw new Exception("Couldn't start module " + module, e);
}
 
this.runningModules.put(id, module);
 
// update graph
final boolean added = this.dependencyGraph.addVertex(f);
assert added : "Module was already in graph : " + f;
for (final String requiredID : f.getRequiredIDs())
this.dependencyGraph.addEdge(f, this.runningModules.get(requiredID).getFactory());
}
}
 
// remove dependencies
modules.keySet().retainAll(ids);
return Tuple2.create(modules, cannotCreate);
}
 
private final boolean startModule(final AbstractModule module) throws Exception {
final ModuleFactory f = module.getFactory();
final String id = f.getID();
if (isModuleRunning(id)) {
return false;
} else {
private final void installAndRegister(final AbstractModule module) throws Exception {
assert Thread.holdsLock(this);
assert !isModuleRunning(module.getFactory().getID());
try {
install(module);
} catch (Exception e) {
804,33 → 916,35
for (final SQLTable tableWithDoc : tablesWithMD) {
this.getDirectory().getElement(tableWithDoc).addToMDPath(mdVariant);
}
this.setupComponents(module);
module.start();
} catch (Exception e) {
throw new Exception("Couldn't start module " + module, e);
throw new Exception("Couldn't register module " + module, e);
}
this.runningModules.put(id, module);
}
 
// update graph
final boolean added = this.dependencyGraph.addVertex(f);
assert added : "Module was already in graph : " + f;
for (final String requiredID : f.getRequiredIDs())
this.dependencyGraph.addEdge(f, this.runningModules.get(requiredID).getFactory());
 
return true;
private final void startModule(final AbstractModule module) throws Exception {
assert SwingUtilities.isEventDispatchThread();
this.setupComponents(module);
module.start();
}
}
 
public final boolean isModuleRunning(final String id) {
assert SwingUtilities.isEventDispatchThread();
public synchronized final boolean isModuleRunning(final String id) {
return this.runningModules.containsKey(id);
}
 
public final Map<String, AbstractModule> getRunningModules() {
return Collections.unmodifiableMap(this.runningModules);
/**
* The modules that are currently running. NOTE : if {@link #startModules(Collection, boolean)}
* or {@link #stopModule(String, boolean)} wasn't called from the EDT the modules will only be
* actually started/stopped when the EDT executes the invokeLater(). In other words a module can
* be in the result but not yet on screen, or module can no longer be in the result but still on
* screen.
*
* @return the started modules.
*/
public synchronized final Map<String, AbstractModule> getRunningModules() {
return new HashMap<String, AbstractModule>(this.runningModules);
}
 
public final void stopModuleRecursively(final String id) {
public synchronized final void stopModuleRecursively(final String id) {
if (!this.isModuleRunning(id))
return;
 
846,8 → 960,7
this.stopModule(id, true);
}
 
public final void stopModule(final String id, final boolean persistent) {
assert SwingUtilities.isEventDispatchThread();
public synchronized final void stopModule(final String id, final boolean persistent) {
if (!this.isModuleRunning(id))
return;
 
857,8 → 970,25
throw new IllegalArgumentException("Dependents still running : " + deps);
this.dependencyGraph.removeVertex(f);
final AbstractModule m = this.runningModules.remove(id);
m.stop();
this.tearDownComponents(m);
try {
// execute right away if possible, allowing the caller to handle any exceptions
if (SwingUtilities.isEventDispatchThread()) {
stopModule(m);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
stopModule(m);
} catch (Exception e) {
ExceptionHandler.handle(MainFrame.getInstance(), "Unable to stop " + f, e);
}
}
});
}
} catch (Exception e) {
throw new IllegalStateException("Couldn't stop module " + m, e);
}
// perhaps record which element this module modified in start()
final String mdVariant = getMDVariant(f);
for (final SQLElement elem : this.getDirectory().getElements()) {
870,6 → 1000,12
assert !this.isModuleRunning(id);
}
 
private final void stopModule(final AbstractModule m) {
assert SwingUtilities.isEventDispatchThread();
m.stop();
this.tearDownComponents(m);
}
 
private void unregisterSQLElements(final AbstractModule module) {
final String id = module.getFactory().getID();
synchronized (this.modulesElements) {
883,6 → 1019,7
}
 
private void tearDownComponents(final AbstractModule module) {
assert SwingUtilities.isEventDispatchThread();
final String id = module.getFactory().getID();
if (this.modulesComponents.containsKey(id)) {
final ComponentsContext ctxt = this.modulesComponents.remove(id);
912,7 → 1049,7
 
// modules needing us are the ones currently started + the ones installed in the database
// that need one of our fields
private final Collection<String> getDependentModules(final String id) throws Exception {
private synchronized final Collection<String> getDependentModules(final String id) throws Exception {
final Set<String> depModules = new HashSet<String>(getDBDependentModules(id));
final AbstractModule runningModule = this.runningModules.get(id);
if (runningModule != null) {
931,7 → 1068,7
* first item isn't depended on).
* @throws Exception if an error occurs.
*/
public final List<String> getDependentModulesRecursively(final String id) throws Exception {
public synchronized final List<String> getDependentModulesRecursively(final String id) throws Exception {
final List<String> res = new ArrayList<String>();
for (final String depModule : getDependentModules(id)) {
res.add(depModule);
943,7 → 1080,7
}
 
// ids + modules depending on them in uninstallation order
private final LinkedHashSet<String> getAllOrderedDependentModulesRecursively(final Set<String> ids) throws Exception {
private synchronized final LinkedHashSet<String> getAllOrderedDependentModulesRecursively(final Set<String> ids) throws Exception {
final LinkedHashSet<String> depModules = new LinkedHashSet<String>();
for (final String id : ids) {
if (!depModules.contains(id)) {
969,7 → 1106,7
return res;
}
 
public final Collection<String> uninstall(final Set<String> ids, final boolean recurse) throws Exception {
public synchronized final Collection<String> uninstall(final Set<String> ids, final boolean recurse) throws Exception {
final Set<String> res;
if (!recurse) {
final LinkedHashSet<String> depModules = getAllOrderedDependentModulesRecursively(ids);
996,7 → 1133,7
this.uninstall(id, false);
}
 
public final Collection<String> uninstall(final String id, final boolean recurse) throws Exception {
public synchronized final Collection<String> uninstall(final String id, final boolean recurse) throws Exception {
// even if it wasn't installed locally we might want to uninstall it from the DB
if (!this.isModuleInstalledLocallyOrInDB(id))
return Collections.emptySet();
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/RuntimeModuleFactory.java
19,11 → 19,14
import java.util.Map;
import java.util.Properties;
 
import net.jcip.annotations.ThreadSafe;
 
/**
* A module factory which classes are already in the classpath.
*
* @author Sylvain CUAZ
*/
@ThreadSafe
public final class RuntimeModuleFactory extends ModuleFactory {
 
public RuntimeModuleFactory(final File props) throws IOException {
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/InstalledModulesPanel.java
33,10 → 33,12
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
 
public class InstalledModulesPanel extends JPanel {
120,8 → 122,13
JButton uninstallButton = new JButton(new AbstractAction("Désinstaller") {
@Override
public void actionPerformed(ActionEvent evt) {
final Collection<ModuleFactory> checkedRows = InstalledModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(InstalledModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final ModuleManager mngr = ModuleManager.getInstance();
final Collection<ModuleFactory> checkedRows = InstalledModulesPanel.this.tm.getCheckedRows();
final int answer = JOptionPane.showConfirmDialog(InstalledModulesPanel.this,
"Êtes-vous sûr de vouloir désinstaller ces modules ?\nToutes les données seront irrémédiablement effacées.", "Désinstallation de modules", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
129,7 → 136,6
return;
 
try {
// TODO uninstall out of EDT
final Set<String> ids = new HashSet<String>();
for (final ModuleFactory f : checkedRows) {
ids.add(f.getID());
141,13 → 147,28
if (selectAnswer == JOptionPane.NO_OPTION)
return;
}
final JDialog dialog = AvailableModulesPanel.displayDialog(InstalledModulesPanel.this,
"Désinstallation " + AvailableModulesPanel.MODULE_FMT.format(new Object[] { checkedRows.size() }));
new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
mngr.uninstall(ids, true);
return null;
}
 
protected void done() {
try {
this.get();
} catch (Exception e) {
ExceptionHandler.handle(InstalledModulesPanel.this, "Impossible de désinstaller les modules", e);
}
// some might have started
moduleFrame.reload();
dialog.dispose();
}
}.execute();
} catch (Exception e) {
ExceptionHandler.handle(InstalledModulesPanel.this, "Impossible de trouver les modules à désinstaller", e);
}
}
});
uninstallButton.setOpaque(false);
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AvailableModulesPanel.java
15,25 → 15,57
 
import org.openconcerto.sql.view.AbstractFileTransfertHandler;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.component.WaitIndeterminatePanel;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
 
import java.awt.Dialog.ModalityType;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.text.ChoiceFormat;
import java.text.MessageFormat;
import java.util.Collection;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
 
public class AvailableModulesPanel extends JPanel {
 
static final MessageFormat MODULE_FMT;
 
static {
final ChoiceFormat choiceForm = new ChoiceFormat(new double[] { 1, 2 }, new String[] { "d'un module", "de {0} modules" });
MODULE_FMT = new MessageFormat("{0}");
MODULE_FMT.setFormatByArgumentIndex(0, choiceForm);
}
 
// prevent the user from interacting when un/installing modules
static JDialog displayDialog(JComponent parent, final String text) {
final WaitIndeterminatePanel panel = new WaitIndeterminatePanel(text);
final JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(parent), ModalityType.APPLICATION_MODAL);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(parent);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
dialog.setVisible(true);
}
});
return dialog;
}
 
private final AvailableModuleTableModel tm;
 
AvailableModulesPanel(final ModuleFrame moduleFrame) {
76,18 → 108,35
@Override
public void actionPerformed(ActionEvent evt) {
final Collection<ModuleFactory> checkedRows = AvailableModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final JDialog dialog = displayDialog(AvailableModulesPanel.this, "Installation " + MODULE_FMT.format(new Object[] { checkedRows.size() }));
final ModuleManager mngr = ModuleManager.getInstance();
try {
// TODO install out of EDT
new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
for (final ModuleFactory f : checkedRows) {
mngr.startModule(f.getID(), true);
}
return null;
}
 
@Override
protected void done() {
try {
this.get();
} catch (Exception e) {
ExceptionHandler.handle(AvailableModulesPanel.this, "Impossible de démarrer les modules", e);
}
// some might have started
moduleFrame.reload();
dialog.dispose();
}
}.execute();
}
});
activateButton.setOpaque(false);
this.add(activateButton, c);
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleVersion.java
14,7 → 14,9
package org.openconcerto.erp.modules;
 
import org.openconcerto.utils.CompareUtils;
import net.jcip.annotations.Immutable;
 
@Immutable
public class ModuleVersion implements Comparable<ModuleVersion> {
 
public static final int MAX = 10000;
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction.java
55,6 → 55,7
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.io.InputStream;
import java.sql.SQLException;
203,6 → 204,10
};
 
final JImage image = new JImage(ComptaBasePropsConfiguration.class.getResource("logo.png"));
Image customImage = ComptaPropsConfiguration.getInstanceCompta().getCustomLogo();
if (customImage != null) {
image.setImage(customImage);
}
image.setBackground(Color.WHITE);
JPanel p = new JPanel();
 
/trunk/OpenConcerto/src/org/openconcerto/map/ui/ITextComboVilleViewer.java
14,6 → 14,7
package org.openconcerto.map.ui;
 
import org.openconcerto.map.model.Ville;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.component.ComboLockedMode;
import org.openconcerto.ui.component.IComboCacheListModel;
import org.openconcerto.ui.component.combo.ISearchableTextCombo;
29,18 → 30,26
import org.openconcerto.utils.checks.ValidObject;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
 
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
54,6 → 63,7
private static final long serialVersionUID = 3397210337907076649L;
private final ISearchableTextCombo text;
private final JButton button = new JButton("Afficher sur la carte");
private final JButton buttonAdd;
private Ville currentVille = null;
private final EmptyObjectHelper emptyHelper;
 
62,10 → 72,14
 
public ITextComboVilleViewer() {
this.setOpaque(false);
this.setLayout(new BorderLayout());
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.insets = new Insets(0, 0, 0, 2);
 
this.buttonAdd = new JButton(new ImageIcon(this.getClass().getResource("add.png")));
this.supp = new ValueChangeSupport<String>(this);
this.cache = new ITextComboCacheVille();
 
this.text = new ISearchableTextCombo(ComboLockedMode.LOCKED_ITEMS_UNLOCKED, 0, 17) {
@Override
protected String stringToT(String t) {
97,10 → 111,43
}
});
 
new IComboCacheListModel(this.cache).initCacheLater(this.text);
this.add(this.text, BorderLayout.CENTER);
final IComboCacheListModel comboCacheListModel = new IComboCacheListModel(this.cache);
comboCacheListModel.initCacheLater(this.text);
// Listen on data
final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
comboCacheListModel.reload();
}
};
 
this.add(this.button, BorderLayout.EAST);
this.addContainerListener(new ContainerListener() {
@Override
public void componentRemoved(ContainerEvent e) {
Ville.removeListener(listener);
}
 
@Override
public void componentAdded(ContainerEvent e) {
Ville.addListener(listener);
}
});
 
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(this.text, c);
c.weightx = 0;
c.gridx++;
this.button.setOpaque(false);
this.add(this.button, c);
c.gridx++;
this.buttonAdd.setPreferredSize(new Dimension(24, 16));
this.buttonAdd.setBorder(null);
this.buttonAdd.setOpaque(false);
this.buttonAdd.setContentAreaFilled(false);
this.buttonAdd.setFocusPainted(false);
this.buttonAdd.setFocusable(false);
this.add(this.buttonAdd, c);
this.button.addActionListener(new ActionListener() {
 
public void actionPerformed(final ActionEvent e) {
131,8 → 178,24
ITextComboVilleViewer.this.button.setEnabled(ITextComboVilleViewer.this.currentVille != null && ITextComboVilleViewer.this.isEnabled());
}
});
this.buttonAdd.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ITextComboVilleViewer.this), true);
 
final String rawTtext = text.getTextComp().getText();
d.setContentPane(new VilleEditorPanel(rawTtext));
d.setTitle("Nouvelle ville");
d.pack();
d.setResizable(false);
d.setLocationRelativeTo(ITextComboVilleViewer.this);
d.setVisible(true);
}
});
 
}
 
@Override
public void addEmptyListener(final EmptyListener l) {
this.emptyHelper.addListener(l);
210,4 → 273,5
public void setValue(final String val) {
this.text.setValue(val);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/map/ui/add.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/openconcerto/map/ui/add.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/src/org/openconcerto/map/ui/ITextComboCacheVille.java
16,13 → 16,12
import org.openconcerto.map.model.Ville;
import org.openconcerto.ui.component.ITextComboCache;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JOptionPane;
 
public class ITextComboCacheVille implements ITextComboCache {
final ArrayList<String> villesNames = Ville.getVillesNames();
final List<String> villesNames = Ville.getVillesNames();
 
public Ville createVilleFrom(String string) {
string = string.trim();
75,4 → 74,5
public String toString() {
return getClass().getSimpleName() + " with " + this.villesNames.size() + " cities";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/map/ui/VilleEditorPanel.java
New file
0,0 → 1,116
/*
* 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.map.ui;
 
import org.openconcerto.map.model.Ville;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
 
public class VilleEditorPanel extends JPanel implements ActionListener {
 
final JTextField textVille = new JTextField(20);
final JTextField textCodePostal = new JTextField(8);
final JButton buttonAdd = new JButton("Ajouter");
final JButton buttonCancel = new JButton("Annuler");
 
public VilleEditorPanel(String s) {
if (s == null)
s = "";
s = s.trim();
 
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Ville
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
this.add(new JLabel("Ville", SwingConstants.RIGHT), c);
c.gridx++;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.WEST;
this.add(textVille, c);
// Code postal
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
this.add(new JLabel("Code postal", SwingConstants.RIGHT), c);
c.gridx++;
c.gridwidth = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
this.add(textCodePostal, c);
// Buttons
c.gridx = 1;
c.gridy++;
c.gridwidth = 1;
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
this.add(buttonAdd, c);
c.gridwidth = 0;
c.gridx++;
c.weightx = 0;
this.add(buttonCancel, c);
 
if (!s.