OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 155 → Rev 156

/trunk/OpenConcerto/src/product.properties
1,5 → 1,5
NAME=OpenConcerto
VERSION=1.5.4
VERSION=1.6.2
ORGANIZATION_NAME=OpenConcerto
ORGANIZATION_ID=org.openconcerto
/trunk/OpenConcerto/src/META-INF/services/java.nio.file.spi.FileTypeDetector
New file
0,0 → 1,0
ilm.utils.mime.FreeDesktopMimeDetector
/trunk/OpenConcerto/src/org/jopenchart/DataModel1D.java
4,7 → 4,7
import java.util.List;
 
public class DataModel1D extends DataModel {
private final List<Number> l = new ArrayList<Number>();
private final List<Number> l = new ArrayList<>();
 
public DataModel1D() {
 
12,8 → 12,7
 
public DataModel1D(Number[] data) {
for (int i = 0; i < data.length; i++) {
Number number = data[i];
l.add(number);
l.add(data[i]);
}
}
 
21,15 → 20,15
this.addAll(list);
}
 
public void addAll(List<Number> data) {
public synchronized void addAll(List<Number> data) {
l.addAll(data);
}
 
public int getSize() {
public synchronized int getSize() {
return l.size();
}
 
public void setValueAt(int index, Number value) {
public synchronized void setValueAt(int index, Number value) {
ensureCapacity(index);
l.set(index, value);
}
40,37 → 39,34
}
}
 
public Number getValueAt(int index) {
public synchronized Number getValueAt(int index) {
ensureCapacity(index);
return l.get(index);
}
 
public Number getMaxValue() {
public synchronized Number getMaxValue() {
Number max = 0;
for (Number b : this.l) {
if (max == null) {
if (b != null && b.doubleValue() > max.doubleValue()) {
max = b;
} else if (b != null && b.doubleValue() > max.doubleValue()) {
max = b;
}
}
return max;
}
 
public Number getMinValue() {
public synchronized Number getMinValue() {
Number min = 0;
for (Number b : this.l) {
if (min == null) {
if (b != null && b.doubleValue() < min.doubleValue()) {
min = b;
} else if (b != null && b.doubleValue() < min.doubleValue()) {
min = b;
}
}
return min;
}
 
public void clear() {
for (int i = 0; i < this.getSize(); i++) {
public synchronized void clear() {
final int size = l.size();
for (int i = 0; i < size; i++) {
this.setValueAt(i, null);
}
}
/trunk/OpenConcerto/src/org/jopenchart/DataModel2D.java
7,10 → 7,10
public class DataModel2D extends DataModel {
 
private String[][] data;
private int rowCount;
private int colCount;
private List<String> rowLabels = new ArrayList<String>();
private List<String> colLabels = new ArrayList<String>();
private final int rowCount;
private final int colCount;
private List<String> rowLabels = new ArrayList<>();
private List<String> colLabels = new ArrayList<>();
 
public DataModel2D(int row, int col) {
this.rowCount = row;
27,24 → 27,24
this.rowLabels.add(String.valueOf((char) ('A' + i)));
}
for (int i = 0; i < col; i++) {
this.colLabels.add(String.valueOf(((1 + i))));
this.colLabels.add(String.valueOf(1 + i));
}
 
}
 
public String getValue(int row, int col) {
public synchronized String getValue(int row, int col) {
return data[row][col];
}
 
public void setValue(String value, int row, int col) {
public synchronized void setValue(String value, int row, int col) {
data[row][col] = value;
}
 
public String getColumnLabel(int col) {
public synchronized String getColumnLabel(int col) {
return this.colLabels.get(col);
}
 
public String getRowLabel(int row) {
public synchronized String getRowLabel(int row) {
return this.rowLabels.get(row);
}
 
/trunk/OpenConcerto/src/org/openconcerto/task/TodoListModel.java
152,7 → 152,7
for (TodoListElement elt : rowsDeleted) {
int index = this.elements.indexOf(elt);
if (index >= 0) {
removeRow(index);
elements.remove(index);
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/task/config/ComptaBasePropsConfiguration.java
23,10 → 23,12
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLFilter;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.users.CompanyAccessSQLElement;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.users.UserCommonSQLElement;
import org.openconcerto.sql.users.rights.RightSQLElement;
import org.openconcerto.sql.users.rights.UserRightSQLElement;
import org.openconcerto.task.TM;
import org.openconcerto.task.element.CompanyAccessSQLElement;
import org.openconcerto.task.element.TaskRightSQLElement;
import org.openconcerto.task.element.TaskSQLElement;
import org.openconcerto.utils.BaseDirs;
33,6 → 35,8
import org.openconcerto.utils.DesktopEnvironment;
import org.openconcerto.utils.LogUtils;
import org.openconcerto.utils.ProductInfo;
import org.openconcerto.utils.i18n.Grammar_fr;
import org.openconcerto.utils.i18n.NounClass;
 
import java.io.File;
import java.io.FileNotFoundException;
39,8 → 43,10
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
 
public abstract class ComptaBasePropsConfiguration extends PropsConfiguration {
125,13 → 131,21
}
 
@Override
protected List<String> getMappings() {
final List<String> res = new ArrayList<>(super.getMappings());
final String pkg = "/" + TM.class.getPackage().getName().replace('.', '/');
res.add(pkg + "/translation/SQLElementNames");
return res;
}
 
@Override
protected SQLElementDirectory createDirectory() {
final SQLElementDirectory dir = super.createDirectory();
 
// TACHE_COMMON points to SOCIETE but we never display it we don't need the full element
dir.addSQLElement(new ConfSQLElement("SOCIETE_COMMON", "une société", "sociétés"));
dir.addSQLElement(new ConfSQLElement("EXERCICE_COMMON", "un exercice", "exercices"));
dir.addSQLElement(new ConfSQLElement("ADRESSE_COMMON", "une adresse", "adresses"));
dir.addSQLElement(new ConfSQLElement("SOCIETE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.FEMININE, "société")));
dir.addSQLElement(new ConfSQLElement("EXERCICE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.MASCULINE, "exercice")));
dir.addSQLElement(new ConfSQLElement("ADRESSE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.FEMININE, "adresse")));
 
dir.addSQLElement(new TaskRightSQLElement());
dir.addSQLElement(new TaskSQLElement());
138,8 → 152,8
 
dir.addSQLElement(new UserCommonSQLElement(getRoot(), false));
dir.addSQLElement(new CompanyAccessSQLElement());
dir.addSQLElement(UserRightSQLElement.class);
dir.addSQLElement(RightSQLElement.class);
dir.addSQLElement(new UserRightSQLElement(getRoot()));
dir.addSQLElement(new RightSQLElement(getRoot()));
 
return dir;
}
164,8 → 178,15
 
protected final void setRowSociete(int id) {
this.idSociete = id;
this.rowSociete = getSystemRoot().findTable("SOCIETE_COMMON").getValidRow(this.getSocieteID());
final SQLTable tableSociete = getSystemRoot().findTable("SOCIETE_COMMON");
final SQLRow row = tableSociete.getRow(id);
if (row == null) {
throw new IllegalArgumentException("no row for id " + id + " in " + tableSociete);
} else if (!row.isValid()) {
throw new IllegalArgumentException("invalid row : " + row);
}
this.rowSociete = row;
}
 
public final SQLBase getSQLBaseSociete() {
return this.getRootSociete().getBase();
/trunk/OpenConcerto/src/org/openconcerto/task/ui/UserRightPanelDetail.java
179,14 → 179,15
private void swapOnDoubleClick(final JList list, MouseEvent e, String field) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
if (index >= 0) {
ListModel dlm = list.getModel();
Object item = dlm.getElementAt(index);
list.ensureIndexIsVisible(index);
User toUser = (User) item;
swapState(selectedUser, toUser, field);
 
}
}
}
 
protected void swapState(User user, User toUser, String field) {
final SQLSelect sel = new SQLSelect();
/trunk/OpenConcerto/src/org/openconcerto/task/element/CompanyAccessSQLElement.java
New file
0,0 → 1,49
/*
* 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.task.element;
 
import org.openconcerto.sql.element.ConfSQLElement;
 
import java.util.ArrayList;
import java.util.List;
 
public class CompanyAccessSQLElement extends ConfSQLElement {
 
public CompanyAccessSQLElement() {
super("ACCES_SOCIETE");
 
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_USER_COMMON");
l.add("ID_SOCIETE_COMMON");
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_USER_COMMON");
l.add("ID_SOCIETE_COMMON");
return l;
}
 
@Override
protected String createCode() {
return "common.company-access";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/task/element/TaskSQLElementBase.java
15,8 → 15,6
 
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.task.TM;
import org.openconcerto.utils.i18n.I18nUtils;
 
/**
* @author Sylvain CUAZ
23,10 → 21,6
*/
public abstract class TaskSQLElementBase extends ConfSQLElement {
 
{
this.setL18nPackageName(I18nUtils.getPackageName(TM.class));
}
 
public TaskSQLElementBase(final String tableName) {
super(tableName);
}
/trunk/OpenConcerto/src/org/openconcerto/task/translation/messages_es.properties
New file
0,0 → 1,20
summary=Summary :
todoBefore=Para hacer antes de {date, date, medium} en {date, time, short} por {user}
todoBefore.col=Hacer antes
ok=OK
cancel=Cancelar
taskToDo=Descripción de la tarea
assignedTo=Asignado a
created=Created
completed=Completado
deleteForbidden=Solo puedes eliminar tareas que creaste
assignedBy=Asignado por {user}\nEn {date, date, medium} por {date, time, short}
delete=Borrar
deleteSelectedTasks=Borrar {count, plural, =0 {selected tasks} one {the selected task} other {the # selected tasks}}
addTask=Nueva tarea
hideHistory= Ocultar historial
showDetails=Mostrar detalles
details=Detalles
markDone=Marca hecha
moveOneDay=Mover por un día
showTaskAssignedTo=Mostrar tarea asignada a ...
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_en.xml
1,4 → 1,8
<translations>
<element refid="common.company-access">
<FIELD name="USER_COMMON" label="User" />
<FIELD name="ID_SOCIETE_COMMON" label="Allowed company access" />
</element>
<element refid="TACHE_COMMON" name="task" />
<element refid="TACHE_RIGHTS" name="right for tasks" namePlural="rights for tasks" />
</translations>
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_es.xml
New file
0,0 → 1,8
<translations>
<element refid="common.company-access">
<FIELD name="USER_COMMON" label="Usario" />
<FIELD name="ID_SOCIETE_COMMON" label="Acceso a la sociedad" />
</element>
<element refid="TACHE_COMMON" name="tarea" />
<element refid="TACHE_RIGHTS" name="derechos para tareas" namePlural="derechos para tareas" />
</translations>
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_fr.xml
1,4 → 1,8
<translations>
<element refid="common.company-access">
<FIELD name="USER_COMMON" label="Utilisateur" />
<FIELD name="ID_SOCIETE_COMMON" label="Accés à la société" />
</element>
<element refid="TACHE_COMMON" nameClass="feminine" name="tâche" />
<element refid="TACHE_RIGHTS" nameClass="masculine" name="droit pour les tâches" namePlural="droits pour les tâches" />
</translations>
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_pl.xml
New file
0,0 → 1,8
<translations>
<element refid="common.company-access">
<FIELD name="USER_COMMON" label="User" />
<FIELD name="ID_SOCIETE_COMMON" label="Ustawienia dostępu" />
</element>
<element refid="TACHE_COMMON" name="task" />
<element refid="TACHE_RIGHTS" name="right for tasks" namePlural="rights for tasks" />
</translations>
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleManager.java
23,6 → 23,7
import org.openconcerto.sql.TM;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.SQLElementNamesFromXML;
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBFileCache;
57,6 → 58,7
import org.openconcerto.utils.CollectionMap2.Mode;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ExceptionUtils;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.SetMap;
import org.openconcerto.utils.StringUtils;
77,6 → 79,10
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
135,8 → 141,7
 
private static synchronized final Executor getExec() {
if (exec == null)
exec = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory(ModuleManager.class.getSimpleName()
exec = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory(ModuleManager.class.getSimpleName()
// not daemon since install() is not atomic
+ " executor thread ", false));
return exec;
172,24 → 177,11
 
private static final Integer TO_INSTALL_VERSION = 1;
 
@GuardedBy("ModuleManager.class")
private static ModuleManager instance = null;
private static final String OLD_BACKUP_DIR_SUFFIX = ".backup";
private static final String OLD_FAILED_DIR_SUFFIX = ".failed";
private static final String BACKUP_DIR = "Install backup";
private static final String FAILED_DIR = "Install failed";
 
public static synchronized ModuleManager getInstance() {
if (instance == null)
instance = new ModuleManager();
return instance;
}
 
static synchronized void resetInstance() {
if (instance != null) {
for (final String id : instance.getRunningModules().keySet()) {
instance.stopModuleRecursively(id);
}
instance = null;
}
}
 
// return true if the MainFrame is not displayable (or if there's none)
static private boolean noDisplayableFrame() {
final MainFrame mf = MainFrame.getInstance();
505,8 → 497,7
if (!toInstallFile.canRead() || !toInstallFile.isFile()) {
L.warning("Couldn't read " + toInstallFile);
} else {
final XMLDecoder dec = new XMLDecoder(new FileInputStream(toInstallFile));
try {
try (final XMLDecoder dec = new XMLDecoder(new FileInputStream(toInstallFile))) {
final Number version = (Number) dec.readObject();
if (version.intValue() != TO_INSTALL_VERSION.intValue())
throw new Exception("Version mismatch, expected " + TO_INSTALL_VERSION + " found " + version);
545,7 → 536,11
final boolean renamed = toInstallFile.renameTo(errorFile);
throw new Exception("Couldn't parse " + toInstallFile + " ; renamed : " + renamed, e);
} finally {
dec.close();
// Either the installation will succeed and we don't want to execute it again,
// or the installation will fail and we don't want to be caught in an endless
// loop (since there's no API to remove this file).
if (toInstallFile.exists() && !toInstallFile.delete())
throw new IOException("Couldn't delete " + toInstallFile);
}
}
}
579,8 → 574,6
this.createModules(userReferencesToInstall, NoChoicePredicate.NO_CHANGE, ModuleState.STARTED, persistent);
}
}
if (toInstallFile.exists() && !toInstallFile.delete())
throw new IOException("Couldn't delete " + toInstallFile);
this.inited = true;
}
 
647,13 → 640,14
}
 
protected final boolean isModuleInstalledLocally(String id) {
return getLocalVersionFile(id).exists();
final File versionFile = getLocalVersionFile(id);
return versionFile != null && versionFile.exists();
}
 
protected final ModuleVersion getModuleVersionInstalledLocally(String id) {
synchronized (fileMutex) {
final File versionFile = getLocalVersionFile(id);
if (versionFile.exists()) {
if (versionFile != null && versionFile.exists()) {
try {
return new ModuleVersion(Long.valueOf(FileUtils.read(versionFile)));
} catch (IOException e) {
779,10 → 773,54
return getConf().getDirectory();
}
 
final File getLocalDirectory() {
public final File getLocalDirectory() {
return new File(this.getConf().getConfDir(getRoot()), "modules");
}
 
public final Set<String> migrateOldTransientDirs() {
Set<String> res = Collections.emptySet();
final File[] listFiles = this.getLocalDirectory().listFiles();
if (listFiles != null) {
for (final File f : listFiles) {
if (f.isDirectory()) {
res = migrateOldDir(res, f, OLD_BACKUP_DIR_SUFFIX);
res = migrateOldDir(res, f, OLD_FAILED_DIR_SUFFIX);
}
}
}
return res;
}
 
private final String getOldID(final File f, final String oldSuffix) {
if (f.getName().endsWith(oldSuffix)) {
final String id = f.getName().substring(0, f.getName().length() - oldSuffix.length());
return ModuleReference.checkID(id, false);
}
return null;
}
 
private final Set<String> migrateOldDir(Set<String> res, final File f, final String oldSuffix) {
final String id = getOldID(f, oldSuffix);
if (id != null) {
final Path localFailedDir = getLocalFailedDirectory(id);
try {
if (Files.exists(localFailedDir)) {
// newer already exists, remove old one
FileUtils.rm_R(f);
} else {
Files.createDirectories(localFailedDir.getParent());
Files.move(f.toPath(), localFailedDir);
}
} catch (IOException e) {
L.log(Level.CONFIG, "Couldn't migrate " + f, e);
if (res.isEmpty())
res = new HashSet<>();
res.add(id);
}
}
return res;
}
 
// file specifying which module (and only those, dependencies won't be installed automatically)
// to install during the next application launch.
private final File getToInstallFile() {
789,13 → 827,54
return new File(getLocalDirectory(), "toInstall");
}
 
protected final File getLocalDirectory(final String id) {
private final File getLocalDataSubDir(final File f) {
// TODO return "Local Data" and a migration method
return f;
}
 
// => create "internal state" and "local data" folders inside getLocalDirectory() (i.e.
// module.id/local data and not local data/module.id so that we can easily copy to
// getLocalBackupDirectory() or uninstall a module)
 
private final Path getInternalStateSubDir(final Path f) {
// TODO return "Internal State" and a migration method
return f;
}
 
protected final File getLocalDataDirectory(final String id) {
return getLocalDataSubDir(this.getLocalDirectory(id));
}
 
private final Path getInternalStateDirectory(final String id) {
final File l = this.getLocalDirectory(id);
return l == null ? null : getInternalStateSubDir(l.toPath());
}
 
private final File getLocalDirectory(final String id) {
if (ModuleReference.checkID(id, false) == null)
return null;
return new File(this.getLocalDirectory(), id);
}
 
// TODO module might remove it since it's in getLocalDirectory()
// contains a copy of local module data during install
protected final Path getLocalBackupDirectory(final String id) {
// will be ignored by getModulesVersionInstalledLocally()
assert ModuleReference.checkID(BACKUP_DIR, false) == null;
return this.getLocalDirectory().toPath().resolve(BACKUP_DIR).resolve(id);
}
 
// contains local module data of the last failed install
protected final Path getLocalFailedDirectory(final String id) {
// will be ignored by getModulesVersionInstalledLocally()
assert ModuleReference.checkID(FAILED_DIR, false) == null;
return this.getLocalDirectory().toPath().resolve(FAILED_DIR).resolve(id);
}
 
private final File getLocalVersionFile(final String id) {
return new File(this.getLocalDirectory(id), "version");
final Path dir = this.getInternalStateDirectory(id);
if (dir == null)
return null;
return new File(dir.toFile(), "version");
}
 
public final ModuleVersion getDBInstalledModuleVersion(final String id) throws SQLException {
1022,12 → 1101,13
// it to dir
// Choice 2 is simpler since the module deals with the same directory in both install()
// and start()
final File backupDir;
final Path backupDir;
// check if we need a backup
if (localDir.exists()) {
backupDir = FileUtils.addSuffix(localDir, ".backup");
FileUtils.rm_R(backupDir);
FileUtils.copyDirectory(localDir, backupDir);
backupDir = getLocalBackupDirectory(factory.getID());
FileUtils.rm_R(backupDir, false);
Files.createDirectories(backupDir.getParent());
FileUtils.copyDirectory(localDir.toPath(), backupDir, false, StandardCopyOption.COPY_ATTRIBUTES);
} else {
backupDir = null;
FileUtils.mkdir_p(localDir);
1038,7 → 1118,8
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
final Tuple2<Set<String>, Set<SQLName>> alreadyCreatedItems = getCreatedItems(factory.getID());
final DBContext ctxt = new DBContext(localDir, localVersion, getRoot(), lastInstalledVersion, alreadyCreatedItems.get0(), alreadyCreatedItems.get1(), getDirectory());
final DBContext ctxt = new DBContext(getLocalDataSubDir(localDir), localVersion, getRoot(), lastInstalledVersion, alreadyCreatedItems.get0(), alreadyCreatedItems.get1(),
getDirectory());
// install local (i.e. ctxt stores the actions to carry on the DB)
// TODO pass a data source with no rights to modify the data definition (or
// even no rights to modify the data if DB version is up to date)
1056,17 → 1137,29
if (getRoot().getServer().getSQLSystem() == SQLSystem.MYSQL)
L.warning("MySQL cannot rollback DDL statements");
// keep failed install files and restore previous files
final File failed = FileUtils.addSuffix(localDir, ".failed");
if (failed.exists() && !FileUtils.rmR(failed))
L.warning("Couldn't remove " + failed);
if (!localDir.renameTo(failed)) {
L.warning("Couldn't move " + localDir + " to " + failed);
} else {
final Path failed = getLocalFailedDirectory(factory.getID());
boolean moved = false;
try {
FileUtils.rm_R(failed, false);
Files.createDirectories(failed.getParent());
Files.move(localDir.toPath(), failed);
final String errorMsg = "Couldn't install " + module + " :\n" + ExceptionUtils.getStackTrace(e);
// TODO as in getLocalVersionFile(), separate internal state (i.e. version and
// error) from module local data
Files.write(getInternalStateSubDir(failed).resolve("Install error.txt"), errorMsg.getBytes(StandardCharsets.UTF_8));
moved = true;
} catch (Exception e1) {
L.log(Level.WARNING, "Couldn't move " + localDir + " to " + failed, e1);
}
// restore if needed
if (moved && backupDir != null) {
assert !localDir.exists();
// restore if needed
if (backupDir != null && !backupDir.renameTo(localDir))
L.warning("Couldn't restore " + backupDir + " to " + localDir);
try {
Files.move(backupDir, localDir.toPath());
} catch (Exception e1) {
L.log(Level.WARNING, "Couldn't restore " + backupDir + " to " + localDir, e1);
}
}
throw e;
}
// DB transaction was committed, remove backup files
1083,10 → 1176,6
synchronized (this.modulesElements) {
// perhaps check that no other version of the module has been registered
if (!this.modulesElements.containsKey(id)) {
final String mdVariant = getMDVariant(module.getFactory());
// load now so that it's available to ModuleElement in setupElements()
final Set<SQLTable> tablesWithMD = loadTranslations(getConf().getTranslator(), module, mdVariant);
 
final SQLElementDirectory dir = getDirectory();
module.setupElements(dir);
final IdentityHashMap<SQLElement, SQLElement> elements = new IdentityHashMap<SQLElement, SQLElement>();
1125,6 → 1214,12
}
}
 
// Load translations after registering elements since SQLFieldTranslator needs them.
// If setupElements() needs translations then perhaps we should store translations
// with the element code, without needing the element.
final String mdVariant = getMDVariant(module.getFactory());
final Set<SQLTable> tablesWithMD = loadTranslations(getConf().getTranslator(), module, mdVariant);
 
// insert just loaded labels into the search path
for (final SQLTable tableWithDoc : tablesWithMD) {
final SQLElement sqlElem = this.getDirectory().getElement(tableWithDoc);
1546,13 → 1641,12
// call it before stopping/uninstalling
final boolean exit = this.isExitAllowed() && this.needExit(change);
 
final DepSolverGraph graph = change.getGraph();
final Set<ModuleReference> toRemove = change.getReferencesToRemove();
final Set<ModuleReference> removed;
if (toRemove.size() > 0) {
final Set<String> idsToInstall = change.getIDsToInstall();
 
// limit the number of requests
final Map<String, ModuleVersion> dbVersions = this.getDBInstalledModules();
removed = new HashSet<ModuleReference>();
for (final ModuleReference ref : toRemove) {
// don't uninstall modules to upgrade but since this loop might uninstall modules
1559,7 → 1653,7
// needed by ref, at least stop it like uninstallUnsafe() does
if (idsToInstall.contains(ref.getID()))
this.stopModule(ref.getID(), false);
else if (this.uninstallUnsafe(ref, !change.forceRemove(), dbVersions))
else if (this.uninstallUnsafe(ref, !change.forceRemove(), change.getInstallState()))
removed.add(ref);
}
} else {
1581,8 → 1675,7
if (toInstall.size() > 0 || (targetState.compareTo(ModuleState.INSTALLED) > 0 && change.getUserReferencesToInstall().size() > 0)) {
// record current time and actions
final File f = getToInstallFile();
final XMLEncoder xmlEncoder = new XMLEncoder(new FileOutputStream(f));
try {
try (final XMLEncoder xmlEncoder = new XMLEncoder(new FileOutputStream(f))) {
xmlEncoder.setExceptionListener(XMLCodecUtils.EXCEPTION_LISTENER);
xmlEncoder.setPersistenceDelegate(ModuleVersion.class, ModuleVersion.PERSIST_DELEGATE);
xmlEncoder.setPersistenceDelegate(ModuleReference.class, ModuleReference.PERSIST_DELEGATE);
1592,19 → 1685,14
xmlEncoder.writeObject(change.getUserReferencesToInstall());
xmlEncoder.writeObject(targetState);
xmlEncoder.writeObject(startPersistent);
xmlEncoder.close();
} catch (Exception e) {
// try to delete invalid file before throwing exception
try {
xmlEncoder.close();
} catch (Exception e1) {
e1.printStackTrace();
}
// "any catch or finally block is run after the resources have been closed."
f.delete();
throw e;
}
}
return ModulesStateChangeResult.onlyRemoved(removed);
return new ModulesStateChangeResult(removed, change.getReferencesToInstall(), graph, Collections.emptyMap());
}
 
// don't use getReferencesToInstall() as even if no modules need installing, their state
1612,9 → 1700,8
if (targetState.compareTo(ModuleState.CREATED) < 0)
return ModulesStateChangeResult.onlyRemoved(removed);
 
final DepSolverGraph graph = change.getGraph();
if (graph == null)
throw new IllegalArgumentException("target state is " + targetState + " but no graph was provided");
throw new IllegalArgumentException("target state is " + targetState + " but no graph was provided by " + change);
 
// modules created by this method
final Map<ModuleReference, AbstractModule> modules = new LinkedHashMap<ModuleReference, AbstractModule>(graph.getFactories().size());
1634,7 → 1721,7
assert module != null;
dependenciesModule.put(e.getKey(), module);
}
final AbstractModule createdModule = useableFactory.createModule(this.getLocalDirectory(id), Collections.unmodifiableMap(dependenciesModule));
final AbstractModule createdModule = useableFactory.createModule(this.getLocalDataDirectory(id), Collections.unmodifiableMap(dependenciesModule));
modules.put(useableFactory.getReference(), createdModule);
this.createdModules.put(useableFactory, createdModule);
 
1757,7 → 1844,9
final ListIterator<Locale> listIterator = CollectionUtils.getListIterator(langs, true);
while (listIterator.hasNext()) {
final Locale lang = listIterator.next();
final String resourceName = cntrl.toResourceName(cntrl.toBundleName(baseName, lang), "xml");
final SQLElementNamesFromXML elemNames = new SQLElementNamesFromXML(lang);
final String bundleName = cntrl.toBundleName(baseName, lang);
final String resourceName = cntrl.toResourceName(bundleName, "xml");
final InputStream ins = module.getClass().getResourceAsStream(resourceName);
// do not force to have one mapping for each locale
if (ins != null) {
1764,7 → 1853,7
L.config("module " + module.getName() + " loading translation from " + resourceName);
final Set<SQLTable> loadedTables;
try {
loadedTables = trns.load(getRoot(), mdVariant, ins).get0();
loadedTables = trns.load(getRoot(), mdVariant, ins, elemNames).get0();
} finally {
ins.close();
}
1772,6 → 1861,11
res.addAll(loadedTables);
found |= true;
}
 
// As in PropsConfiguration.loadTranslations(), perhaps load the class at
// module.getClass().getPackage().getName() + '.' + bundleName
// to allow more flexibility. Perhaps pass a ModuleSQLFieldTranslator to
// restrict what a module can do (and have SQLElementNamesFromXML, mdVariant).
}
}
}
1859,20 → 1953,31
return res;
}
 
public synchronized final void stopModuleRecursively(final String id) {
for (final ModuleReference ref : getRunningDependentModulesRecursively(id)) {
public final Set<ModuleReference> stopAllModules() {
// this method is not synchronized, so don't just return getRunningModules()
final Set<ModuleReference> res = new HashSet<>();
for (final String id : this.getRunningModules().keySet()) {
res.addAll(this.stopModuleRecursively(id));
}
return res;
}
 
public synchronized final List<ModuleReference> stopModuleRecursively(final String id) {
final List<ModuleReference> res = getRunningDependentModulesRecursively(id);
for (final ModuleReference ref : res) {
this.stopModule(ref.getID());
}
return res;
}
 
public final void stopModule(final String id) {
this.stopModule(id, true);
public final boolean stopModule(final String id) {
return this.stopModule(id, true);
}
 
// TODO pass ModuleReference instead of ID (need to change this.runningModules)
public synchronized final void stopModule(final String id, final boolean persistent) {
public synchronized final boolean stopModule(final String id, final boolean persistent) {
if (!this.isModuleRunning(id))
return;
return false;
 
final ModuleFactory f = this.runningModules.get(id).getFactory();
if (this.isAdminRequired(f.getReference()) && !currentUserIsAdmin())
1907,6 → 2012,7
final MenuAndActions menuAndActions = MenuManager.getInstance().createBaseMenuAndActions();
final ArrayList<AbstractModule> modules = new ArrayList<AbstractModule>(this.runningModules.values());
SwingThreadUtils.invoke(new Runnable() {
 
@Override
public void run() {
for (final AbstractModule m : modules) {
1914,11 → 2020,13
}
MenuManager.getInstance().setMenuAndActions(menuAndActions);
}
 
});
 
if (persistent)
getRunningIDsPrefs().remove(m.getFactory().getID());
assert !this.isModuleRunning(id);
return true;
}
 
private final void stopModule(final AbstractModule m) {
2131,6 → 2239,11
public DepSolverGraph getGraph() {
return null;
}
 
@Override
public String toString() {
return "Uninstall solution for " + this.getReferencesToRemove();
}
};
}
 
2146,45 → 2259,48
return this.uninstall(Collections.singleton(id), recurse, force);
}
 
// return vers if it matches ref
private final ModuleVersion filter(final ModuleVersion vers, final ModuleReference ref) {
return ref.getVersion() == null || vers != null && vers.equals(ref.getVersion()) ? vers : null;
// return the version in installed that matches ref
private final ModuleReference filter(final Set<ModuleReference> installed, final ModuleReference ref) {
for (final ModuleReference installedRef : installed) {
if (installedRef.getID().equals(ref.getID()) && (ref.getVersion() == null || installedRef.getVersion().equals(ref.getVersion())))
return installedRef;
}
return null;
}
 
// unsafe because this method doesn't check dependents
// dbVersions parameter to avoid requests to the DB
// return true if the mref was actually uninstalled (i.e. it was installed locally or remotely)
private boolean uninstallUnsafe(final ModuleReference mref, final boolean requireModule, Map<String, ModuleVersion> dbVersions) throws SQLException, Exception {
private boolean uninstallUnsafe(final ModuleReference mref, final boolean requireModule, final InstallationState installState) throws SQLException, Exception {
assert Thread.holdsLock(this);
final String id = mref.getID();
if (dbVersions == null)
dbVersions = this.getDBInstalledModules();
// versions to uninstall
final ModuleVersion localVersion = filter(this.getModuleVersionInstalledLocally(id), mref);
final ModuleVersion dbVersion = filter(dbVersions.get(id), mref);
final ModuleReference localRef = filter(installState.getLocal(), mref);
final ModuleReference dbRef = filter(installState.getRemote(), mref);
final ModuleVersion dbVersion = dbRef == null ? null : dbRef.getVersion();
 
// otherwise it will get re-installed the next launch
getRunningIDsPrefs().remove(id);
final Set<ModuleReference> refs = new HashSet<ModuleReference>(2);
if (localVersion != null)
refs.add(new ModuleReference(id, localVersion));
if (dbVersion != null)
refs.add(new ModuleReference(id, dbVersion));
if (localRef != null)
refs.add(localRef);
if (dbRef != null)
refs.add(dbRef);
setAdminRequiredModules(refs, false);
 
// only return after having cleared required, so that we don't need to install just to
// not require
if (localVersion == null && dbVersion == null)
if (localRef == null && dbRef == null)
return false;
 
if (dbVersion != null && !currentUserIsAdmin())
if (dbRef != null && !currentUserIsAdmin())
throw new IllegalStateException("Not allowed to uninstall " + id + " from the database");
 
// DB module
final AbstractModule module;
if (!this.isModuleRunning(id)) {
if (dbVersion == null) {
assert localVersion != null;
if (dbRef == null) {
assert localRef != null;
// only installed locally
module = null;
} else {
2191,7 → 2307,7
final SortedMap<ModuleVersion, ModuleFactory> available = this.factories.getVersions(id);
final ModuleReference ref;
if (available.containsKey(dbVersion)) {
ref = new ModuleReference(id, dbVersion);
ref = dbRef;
} else {
// perhaps modules should specify which versions they can uninstall
final SortedMap<ModuleVersion, ModuleFactory> moreRecent = available.headMap(dbVersion);
2208,9 → 2324,15
assert f != null;
// only call expensive method if necessary
if (!this.createdModules.containsKey(f)) {
// don't use the result, instead use this.createdModules since the module
// might have been created before
this.createModules(Collections.singleton(ref), NoChoicePredicate.NO_CHANGE, ModuleState.CREATED);
// * Don't use the result, instead use this.createdModules since the module
// might have been created before.
// * Cannot call directly applyChange(), we need DepSolver to create modules
// that ref depends on, as they might be required by
// AbstractModule.uninstall().
// * Cannot pass NoChoicePredicate.NO_CHANGE as ref won't be created if not
// already installed both locally and remotely. No installation will occur
// since we pass ModuleState.CREATED.
this.createModules(Collections.singleton(ref), NoChoicePredicate.ONLY_INSTALL, ModuleState.CREATED);
}
module = this.createdModules.get(f);
} else {
2228,6 → 2350,7
}
}
} else {
final ModuleVersion localVersion = localRef.getVersion();
if (!localVersion.equals(dbVersion))
L.warning("Someone else has changed the database version while we were running :" + localVersion + " != " + dbVersion);
module = this.runningModules.get(id);
2239,7 → 2362,7
SwingUtilities.invokeAndWait(EMPTY_RUNNABLE);
}
}
assert (module == null) == (!requireModule || dbVersion == null);
assert (module == null) == (!requireModule || dbRef == null);
 
SQLUtils.executeAtomic(getDS(), new SQLFactory<Object>() {
@Override
2249,11 → 2372,11
module.uninstall(root);
unregisterSQLElements(module);
}
if (localVersion != null)
setModuleInstalledLocally(new ModuleReference(id, localVersion), false);
if (localRef != null)
setModuleInstalledLocally(localRef, false);
 
// uninstall from DB
if (dbVersion != null) {
if (dbRef != null) {
final Tuple2<Set<String>, Set<SQLName>> createdItems = getCreatedItems(id);
final List<ChangeTable<?>> l = new ArrayList<ChangeTable<?>>();
final Set<String> tableNames = createdItems.get0();
2276,7 → 2399,7
root.refetch();
}
 
removeModuleFields(new ModuleReference(id, dbVersion));
removeModuleFields(dbRef);
}
return null;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AvailableModulesPanel.java
20,6 → 20,7
import org.openconcerto.erp.panel.UserExitConf;
import org.openconcerto.sql.view.AbstractFileTransfertHandler;
import org.openconcerto.ui.component.WaitIndeterminatePanel;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
 
81,9 → 82,8
return done;
}
 
static void applySolution(final ModuleManager mngr, final ModulePanel panel, final ModulesStateChange chosen, final boolean onlyInstall) {
static void applySolution(final ModuleManager mngr, final ModulePanel panel, final ModulesStateChange chosen, final ModuleState targetState) {
final String dialogTitle = "Gestion des modules";
final ModuleState targetState = onlyInstall ? ModuleState.INSTALLED : ModuleState.STARTED;
final int installSize = chosen.getReferencesToInstall().size();
final int uninstallSize = chosen.getReferencesToRemove().size();
if (installSize == 0 && uninstallSize == 0) {
118,7 → 118,10
new SwingWorker<ModulesStateChangeResult, Object>() {
@Override
protected ModulesStateChangeResult doInBackground() throws Exception {
return mngr.applyChange(chosen, ModuleState.REGISTERED);
// don't start the module in background (see below)
// don't go farther than requested
final ModuleState backgroundState = CompareUtils.min(targetState, ModuleState.REGISTERED);
return mngr.applyChange(chosen, backgroundState);
}
 
@Override
161,7 → 164,7
JOptionPane.showMessageDialog(panel, "Aucune ligne cochée", dialogTitle, JOptionPane.INFORMATION_MESSAGE);
return;
}
final ModuleManager mngr = ModuleManager.getInstance();
final ModuleManager mngr = panel.getModuleManager();
final Set<ModuleReference> refs = new HashSet<ModuleReference>();
final Set<ModuleReference> deniedRefs = new HashSet<ModuleReference>();
for (final ModuleRow f : checkedRows) {
195,7 → 198,7
cPanel.setRunnable(new Runnable() {
@Override
public void run() {
applySolution(mngr, panel, cPanel.getSolutionToApply(), onlyInstall);
applySolution(mngr, panel, cPanel.getSolutionToApply(), onlyInstall ? ModuleState.INSTALLED : ModuleState.STARTED);
}
});
final JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(panel), ModalityType.APPLICATION_MODAL);
253,7 → 256,7
return;
}
try {
ModuleManager.getInstance().addFactory(new JarModuleFactory(out));
panel.getModuleManager().addFactory(new JarModuleFactory(out));
} catch (IOException e) {
JOptionPane.showMessageDialog(panel, "Impossible d'intégrer le module.\n" + e.getMessage());
return;
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleLauncher.java
13,6 → 13,7
package org.openconcerto.erp.modules;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.modules.ModulePackager.ModuleFiles;
import org.openconcerto.utils.FileUtils;
68,6 → 69,6
 
Gestion.main(args);
// add after main() otherwise we could be overwritten by an older jar
ModuleManager.getInstance().addFactoryAndStart(factory, false);
ComptaPropsConfiguration.getInstanceCompta().getModuleManager().addFactoryAndStart(factory, false);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AbstractModule.java
114,13 → 114,13
 
protected abstract void start();
 
public List<ModulePreferencePanelDesc> getPrefDescriptors() {
public List<ModulePreferencePanelDesc> getPrefDescriptors(final DBRoot root) {
return Collections.emptyList();
}
 
public final Map<Boolean, List<ModulePreferencePanelDesc>> getPrefDescriptorsByLocation() {
public final Map<Boolean, List<ModulePreferencePanelDesc>> getPrefDescriptorsByLocation(final DBRoot root) {
final Map<Boolean, List<ModulePreferencePanelDesc>> res = new HashMap<Boolean, List<ModulePreferencePanelDesc>>();
for (final ModulePreferencePanelDesc desc : getPrefDescriptors()) {
for (final ModulePreferencePanelDesc desc : getPrefDescriptors(root)) {
final Boolean key = desc.isLocal();
final List<ModulePreferencePanelDesc> l;
if (!res.containsKey(key)) {
139,4 → 139,9
protected void uninstall(DBRoot root) {
 
}
 
@Override
public String toString() {
return this.getClass().getName() + " created from " + this.getFactory();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleTableModel.java
167,17 → 167,23
 
static private final EnumSet<Columns> BOOLEAN_COLS = EnumSet.of(Columns.CB, Columns.LOCAL, Columns.REMOTE, Columns.DB_REQUIRED, Columns.ADMIN_REQUIRED);
 
private final ModuleManager mngr;
private List<ModuleRow> list;
private final Set<ModuleRow> selection;
 
private boolean valid;
 
public ModuleTableModel() {
public ModuleTableModel(ModuleManager mngr) {
this.mngr = mngr;
this.selection = new HashSet<ModuleRow>();
this.list = Collections.emptyList();
this.valid = false;
}
 
public final ModuleManager getModuleManager() {
return this.mngr;
}
 
final void clear() {
this.selection.clear();
this.list = Collections.emptyList();
185,7 → 191,7
}
 
public final void reload() throws IOException, SQLException {
final ModuleManager mngr = ModuleManager.getInstance();
final ModuleManager mngr = this.getModuleManager();
final InstallationState installationState = new InstallationState(mngr);
final Map<ModuleReference, ModuleFactory> available = new HashMap<ModuleReference, ModuleFactory>();
for (final Entry<String, SortedMap<ModuleVersion, ModuleFactory>> e : mngr.getFactories().entrySet()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleElement.java
27,8 → 27,6
// needs DEFERRED since createCode() uses module
super(tableName, DEFERRED_CODE);
this.module = module;
// translations should be alongside the module
this.setL18nLocation(module.getClass());
// allow to access labels right away (see ModuleManager.registerSQLElements())
for (final String id : this.getAdditionalIDsForMDPath()) {
this.addToMDPath(ModuleManager.getMDVariant(new ModuleReference(id, null)));
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleFrame.java
24,35 → 24,22
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
public class ModuleFrame extends JFrame {
 
private static ModuleFrame INSTANCE = null;
private final ModulePanel tab1;
 
public static final ModuleFrame getInstance() {
// no need to sync
assert SwingUtilities.isEventDispatchThread();
if (INSTANCE == null) {
INSTANCE = new ModuleFrame(false);
INSTANCE.setLocationRelativeTo(null);
public ModuleFrame(final ModuleManager mngr) {
this(mngr, false);
}
return INSTANCE;
}
 
public static final ModuleFrame createInstallOnlyInstance() {
return new ModuleFrame(true);
}
 
private final ModulePanel tab1;
 
private ModuleFrame(final boolean onlyInstall) {
public ModuleFrame(final ModuleManager mngr, final boolean onlyInstall) {
this.setTitle("Modules");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
this.tab1 = new ModulePanel(this, onlyInstall);
this.tab1 = new ModulePanel(mngr, onlyInstall);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/DepSolverResult.java
13,6 → 13,8
package org.openconcerto.erp.modules;
 
import java.util.Objects;
 
public class DepSolverResult {
 
static public interface Factory {
27,9 → 29,11
public DepSolverResult(DepSolverResult parent, int tryCount, String error, DepSolverGraph graph) {
super();
this.parent = parent;
if (tryCount < 0)
throw new IllegalArgumentException("Negative try count : " + tryCount);
this.triesCount = tryCount;
this.error = error;
this.graph = graph;
this.graph = Objects.requireNonNull(graph, "graph");
}
 
/**
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleReference.java
20,6 → 20,7
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
 
52,10 → 53,22
return res;
}
 
static String checkID(final String id, final boolean throwExn) {
return checkMatch(idPatrn, id, "ID", throwExn);
}
 
static String checkMatch(final Pattern p, final String s, final String name) {
if (!p.matcher(s).matches())
return checkMatch(p, s, name, true);
}
 
static String checkMatch(final Pattern p, final String s, final String name, final boolean throwExn) {
Objects.requireNonNull(s, "string");
if (p.matcher(s).matches())
return s;
else if (throwExn)
throw new IllegalArgumentException(name + " doesn't match " + p.pattern());
return s;
else
return null;
}
 
static final Pattern javaIdentifiedPatrn = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*");
75,7 → 88,7
public ModuleReference(String id, ModuleVersion version) {
if (id == null)
throw new NullPointerException();
this.id = checkMatch(idPatrn, id.trim(), "ID");
this.id = checkID(id.trim(), true);
if (version != null)
version.checkValidity();
this.version = version;
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModulePreferencePanel.java
32,10 → 32,6
 
public abstract class ModulePreferencePanel extends JavaPrefPreferencePanel {
 
static private DBRoot getRoot() {
return ModuleManager.getInstance().getRoot();
}
 
static String getAppPrefPath() {
return Configuration.getInstance().getAppID() + '/';
}
77,16 → 73,22
}
 
private ITextComboCacheSQL createCache(final JavaPrefPreferencePanel prefPanel) {
return new ITextComboCacheSQL(getRoot(), prefPanel.getPrefPath() + '/' + this.getPrefKey());
return new ITextComboCacheSQL(((ModulePreferencePanel) prefPanel).getRoot(), prefPanel.getPrefPath() + '/' + this.getPrefKey());
}
}
 
public ModulePreferencePanel(final String title) {
private final DBRoot root;
 
public ModulePreferencePanel(final DBRoot root, final String title) {
super(title, null);
this.root = root;
}
 
public final DBRoot getRoot() {
return this.root;
}
 
public final void init(final ModuleFactory module, final boolean local) {
this.setPrefs(module.getPreferences(local, getRoot()));
this.setPrefs(module.getPreferences(local, this.getRoot()));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModulePanel.java
14,6 → 14,7
package org.openconcerto.erp.modules;
 
import org.openconcerto.erp.modules.ModuleManager.ModuleAction;
import org.openconcerto.erp.modules.ModuleManager.ModuleState;
import org.openconcerto.erp.modules.ModuleManager.NoChoicePredicate;
import org.openconcerto.erp.modules.ModuleTableModel.Columns;
import org.openconcerto.erp.modules.ModuleTableModel.ModuleRow;
65,12 → 66,12
 
private final ModuleTableModel tm;
 
ModulePanel(final ModuleFrame moduleFrame, final boolean onlyInstall) {
ModulePanel(final ModuleManager mngr, final boolean onlyInstall) {
this.setOpaque(false);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
 
this.tm = new ModuleTableModel();
this.tm = new ModuleTableModel(mngr);
final JTable t = new JTable(this.tm) {
// only force JTable size above its minimal size (i.e. otherwise use its preferred size
// and display scroll bars accordingly). Without this, some columns can be invisible
197,7 → 198,7
return;
}
 
final ModuleManager mngr = ModuleManager.getInstance();
final ModuleManager mngr = getModuleManager();
final boolean forceUninstall = (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0 && mngr.currentUserIsAdmin();
try {
final Set<ModuleReference> ids = new HashSet<ModuleReference>();
226,6 → 227,9
final JDialog dialog = AvailableModulesPanel.displayDialog(ModulePanel.this, "Calcul des dépendences");
new SwingWorker<ModulesStateChange, Object>() {
protected ModulesStateChange doInBackground() throws Exception {
// MAYBE find other solutions (e.g. instead of removing all modules
// depending on ids, find other modules that can fulfill their
// dependencies)
return mngr.getUninstallSolution(ids, true, forceUninstall);
}
 
258,7 → 262,7
return;
}
 
AvailableModulesPanel.applySolution(mngr, ModulePanel.this, solution, onlyInstall);
AvailableModulesPanel.applySolution(mngr, ModulePanel.this, solution, ModuleState.NOT_CREATED);
} catch (Exception e) {
ExceptionHandler.handle(ModulePanel.this, "Impossible de désinstaller les modules", e);
}
289,6 → 293,10
this.setTransferHandler(AvailableModulesPanel.createTransferHandler(this));
}
 
public final ModuleManager getModuleManager() {
return this.tm.getModuleManager();
}
 
public final void reload() {
try {
this.tm.reload();
320,7 → 328,7
 
@Override
public void actionPerformed(ActionEvent evt) {
final ModuleManager mngr = ModuleManager.getInstance();
final ModuleManager mngr = getModuleManager();
final String dialogTitle = this.start ? "Démarrage de modules" : "Arrêt de modules";
final Collection<ModuleRow> checkedRows = getSelection();
if (checkedRows.isEmpty()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateListFrameAbstractAction.java
13,6 → 13,8
package org.openconcerto.erp.action;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.element.SQLElement;
35,6 → 37,10
import org.openconcerto.ui.light.ListToolbarLine;
import org.openconcerto.ui.light.RowSelectionSpec;
import org.openconcerto.ui.light.TableSpec;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.i18n.MessageArgs;
import org.openconcerto.utils.i18n.NounClass;
import org.openconcerto.utils.i18n.TM.MissingMode;
import org.openconcerto.utils.i18n.TranslationManager;
 
import java.util.ArrayList;
42,16 → 48,41
import java.util.Iterator;
import java.util.List;
 
import javax.swing.JFrame;
 
import org.jdom2.Document;
import org.jdom2.input.DOMBuilder;
 
public abstract class CreateListFrameAbstractAction extends CreateFrameAbstractAction implements LightUIFrameProvider {
abstract public String getTableName();
public abstract class CreateListFrameAbstractAction<E extends SQLElement, F extends JFrame> extends GenericElementFrameAction<E, F> implements LightUIFrameProvider {
 
private static final String TRANSLATION_KEY = "listMenuItem.name";
private static final String[] TRANSLATION_KEY_ARRAY = new String[] { TRANSLATION_KEY };
 
private final ComptaPropsConfiguration conf;
 
protected CreateListFrameAbstractAction(final ComptaPropsConfiguration conf, final Class<? extends E> clazz) {
super(conf.getDirectory().getElement(clazz));
this.conf = conf;
// TODO use conf to find TM
final NounClass nounClass = this.getElem().getName().getNounClass();
final String[] translationKeys = nounClass == null ? TRANSLATION_KEY_ARRAY : new String[] { TRANSLATION_KEY + '.' + nounClass.getName(), TRANSLATION_KEY };
this.putValue(NAME, StringUtils.firstUp(TM.getTM().translateFirst(MissingMode.NULL, MessageArgs.create("elem", this.getElem().getName()), translationKeys)));
}
 
public final ComptaPropsConfiguration getConf() {
return this.conf;
}
 
@Override
protected void initFrame(F frame) {
super.initFrame(frame);
CreateFrameAbstractAction.initFrame(frame, this, getConf(), true);
}
 
@Override
public LightUIFrame getUIFrame(PropsConfiguration configuration) {
// Get SQLElement
SQLElement element = configuration.getDirectory().getElement(getTableName());
SQLElement element = getElem();
final String elementCode = element.getCode();
 
// Title of frame should be the element code with .title
/trunk/OpenConcerto/src/org/openconcerto/erp/action/PreferencesAction.java
15,6 → 15,7
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.finance.accounting.ui.ComptaPrefTreeNode;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.sql.Configuration;
import org.openconcerto.ui.preferences.PreferenceFrame;
import org.openconcerto.ui.state.WindowStateManager;
29,14 → 30,17
 
public class PreferencesAction extends AbstractAction {
 
public PreferencesAction() {
private final ModuleManager moduleManager;
 
public PreferencesAction(final ModuleManager mngr) {
super();
this.putValue(Action.NAME, "Préférences");
this.moduleManager = mngr;
}
 
@Override
public void actionPerformed(final ActionEvent e) {
final JFrame frame = new PreferenceFrame(new ComptaPrefTreeNode());
final JFrame frame = new PreferenceFrame(new ComptaPrefTreeNode(this.moduleManager));
frame.setIconImages(Gestion.getFrameIcon());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
/trunk/OpenConcerto/src/org/openconcerto/erp/action/GenericElementFrameAction.java
New file
0,0 → 1,39
/*
* 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.action;
 
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.SQLMenuItemHelper.AbstractSQLMenuItemAction;
 
import javax.swing.JFrame;
 
public abstract class GenericElementFrameAction<E extends SQLElement, F extends JFrame> extends AbstractSQLMenuItemAction<E> {
 
public GenericElementFrameAction(E elem) {
super(elem, null);
this.setCacheFrame(false);
}
 
protected abstract F instantiateFrame();
 
protected void initFrame(F f) {
}
 
@Override
protected final F createFrame() {
final F res = instantiateFrame();
this.initFrame(res);
return res;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateFrameAbstractAction.java
40,15 → 40,20
 
public void actionPerformed(ActionEvent e) {
final JFrame frame = createFrame();
initFrame(frame, this, Configuration.getInstance(), this.mustLoadState);
FrameUtil.show(frame);
}
 
protected static void initFrame(final JFrame frame, final Action action, final Configuration conf, final boolean mustLoadState) {
frame.setIconImages(Gestion.getFrameIcon());
 
final Object name = this.getValue(Action.NAME);
final Object name = action.getValue(Action.NAME);
WindowStateManager stateManager = null;
if (name != null) {
stateManager = new WindowStateManager(frame, new File(Configuration.getInstance().getConfDir(), "Configuration" + File.separator + "Frame" + File.separator + name.toString() + ".xml"),
stateManager = new WindowStateManager(frame, new File(conf.getConfDir(), "Configuration" + File.separator + "Frame" + File.separator + name.toString() + ".xml"),
true);
} else {
System.err.println("Warning: no action name for action " + this + ", unable to use a window state manager.");
System.err.println("Warning: no action name for action " + action + ", unable to use a window state manager.");
}
 
frame.pack();
63,8 → 68,6
}
 
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FrameUtil.show(frame);
 
}
 
abstract public JFrame createFrame();
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleSocieteAction.java
13,21 → 13,13
package org.openconcerto.erp.action;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.erp.core.common.element.SocieteCommonSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleSocieteAction extends CreateEditFrameAbstractAction<SocieteCommonSQLElement> {
 
public class NouvelleSocieteAction extends CreateFrameAbstractAction {
 
public NouvelleSocieteAction() {
super();
this.putValue(Action.NAME, "Nouvelle société");
public NouvelleSocieteAction(final PropsConfiguration conf) {
super(conf, SocieteCommonSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SOCIETE_COMMON"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateIListFrameAbstractAction.java
New file
0,0 → 1,56
/*
* 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.action;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSource;
 
public abstract class CreateIListFrameAbstractAction<E extends SQLElement> extends CreateListFrameAbstractAction<E, IListFrame> {
 
protected CreateIListFrameAbstractAction(final ComptaPropsConfiguration conf, final Class<? extends E> clazz) {
super(conf, clazz);
}
 
protected SQLTableModelSource createTableSource() {
return this.getElem().createTableSource();
}
 
protected String getPanelVariant() {
return null;
}
 
protected IListPanel instantiateListPanel(final SQLTableModelSource tableSource, String panelVariant) {
return new ListeAddPanel(tableSource.getElem(), new IListe(tableSource), panelVariant);
}
 
protected final IListPanel createListPanel() {
final SQLTableModelSource tableSource = this.createTableSource();
if (tableSource.getElem() != this.getElem())
throw new IllegalStateException("Element mismatch");
final IListPanel res = this.instantiateListPanel(tableSource, this.getPanelVariant());
if (res.getListe().getSource() != tableSource)
throw new IllegalStateException("Source mismatch");
return res;
}
 
@Override
protected final IListFrame instantiateFrame() {
return new IListFrame(createListPanel());
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateEditFrameAbstractAction.java
New file
0,0 → 1,47
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.action;
 
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.i18n.MessageArgs;
import org.openconcerto.utils.i18n.NounClass;
import org.openconcerto.utils.i18n.TM.MissingMode;
 
public class CreateEditFrameAbstractAction<E extends SQLElement> extends GenericElementFrameAction<E, EditFrame> {
 
private static final String TRANSLATION_KEY = "createMenuItem.name";
private static final String[] TRANSLATION_KEY_ARRAY = new String[] { TRANSLATION_KEY };
 
protected CreateEditFrameAbstractAction(final PropsConfiguration conf, final Class<? extends E> clazz) {
super(conf.getDirectory().getElement(clazz));
// TODO use conf to find TM
final NounClass nounClass = this.getElem().getName().getNounClass();
final String[] translationKeys = nounClass == null ? TRANSLATION_KEY_ARRAY : new String[] { TRANSLATION_KEY + '.' + nounClass.getName(), TRANSLATION_KEY };
this.putValue(NAME, StringUtils.firstUp(TM.getTM().translateFirst(MissingMode.NULL, MessageArgs.create("elem", this.getElem().getName()), translationKeys)));
}
 
@Override
protected final EditFrame instantiateFrame() {
return new EditFrame(getElem().createComponent(getComponentID()), EditPanel.CREATION);
}
 
protected String getComponentID() {
return SQLElement.DEFAULT_COMP_ID;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/AboutAction.java
14,15 → 14,23
package org.openconcerto.erp.action;
 
import org.openconcerto.erp.config.Benchmark;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.ui.InfoPanel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.ReloadPanel;
 
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
54,6 → 62,7
p.setLayout(new BorderLayout());
 
final JScrollPane contentPane = new JScrollPane(new InfoPanel());
p.add(createComptaInfoPanel(), BorderLayout.NORTH);
p.add(contentPane, BorderLayout.CENTER);
p.add(createBenchMarkPanel(), BorderLayout.SOUTH);
frame.setContentPane(p);
79,6 → 88,53
frame.setVisible(true);
}
 
private Component createComptaInfoPanel() {
final JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
final File confFile = ComptaPropsConfiguration.getConfFile(ComptaPropsConfiguration.productInfo);
String path = "";
if (confFile != null) {
path = confFile.getAbsolutePath();
}
c.fill = GridBagConstraints.NONE;
c.weightx = 0;
c.anchor = GridBagConstraints.EAST;
p.add(new JLabelBold("Fichier de configuration : "), c);
c.gridx++;
c.weightx = 1;
c.anchor = GridBagConstraints.WEST;
p.add(new JLabel(path), c);
c.gridy++;
c.gridx = 0;
final String serverIp = ComptaPropsConfiguration.getInstanceCompta().getServerIp();
if (serverIp.startsWith("file:")) {
final String dbPath = ComptaPropsConfiguration.getInstanceCompta().getServerIp().substring(5);
c.weightx = 0;
c.anchor = GridBagConstraints.EAST;
p.add(new JLabelBold("Fichier de base de données : "), c);
c.gridx++;
c.weightx = 1;
c.anchor = GridBagConstraints.WEST;
p.add(new JLabel(dbPath), c);
}
c.gridy++;
try {
c.gridx = 0;
c.weightx = 0;
c.anchor = GridBagConstraints.EAST;
p.add(new JLabelBold("Dossier des modules : "), c);
c.gridx++;
c.weightx = 1;
c.anchor = GridBagConstraints.WEST;
p.add(new JLabel(Gestion.MODULES_DIR.getCanonicalPath()), c);
} catch (IOException e) {
e.printStackTrace();
}
 
return p;
}
 
private JPanel createBenchMarkPanel() {
final JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction.java
35,7 → 35,6
import org.openconcerto.erp.rights.MenuComboRightEditor;
import org.openconcerto.erp.utils.NXDatabaseAccessor;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBase;
61,6 → 60,7
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.component.MutableListComboPopupListener;
import org.openconcerto.ui.preferences.EmailProps;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.JImage;
import org.openconcerto.utils.cc.IClosure;
71,6 → 71,7
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
90,10 → 91,12
import javax.swing.UIManager;
 
public class NouvelleConnexionAction extends CreateFrameAbstractAction {
private final ComptaPropsConfiguration conf;
private ConnexionPanel connexionPanel;
 
public NouvelleConnexionAction() {
public NouvelleConnexionAction(ComptaPropsConfiguration conf) {
super();
this.conf = conf;
this.putValue(Action.NAME, "Changer d'utilisateur");
}
 
101,7 → 104,7
// needed as done() must come after us
assert SwingUtilities.isEventDispatchThread();
 
final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
final ComptaPropsConfiguration comptaPropsConfiguration = this.conf;
 
Runnable r = new Runnable() {
 
135,20 → 138,22
}
comptaPropsConfiguration.setUpSocieteDataBaseConnexion(selectedSociete);
comptaPropsConfiguration.setupBarCodeIfNeeded();
 
File fMail2 = new File(comptaPropsConfiguration.getConfDir(), "Email" + selectedSociete + ".properties");
EmailProps.getInstance().setPropsFileName(fMail2.toString());
// needed by openEmergencyModuleManager()
UserRightsManager.getInstance().addRightForAdmins(new RightTuple(ModuleManager.MODULE_DB_RIGHT, true));
UserRightsManager.getInstance().addRightForAdmins(new RightTuple(BackupPanel.RIGHT_CODE, true));
// finish filling the configuration before going any further, otherwise the
// SQLElementDirectory is not coherent
ModuleManager.getInstance().setup(comptaPropsConfiguration.getRootSociete(), comptaPropsConfiguration);
final ModuleManager moduleMngr = comptaPropsConfiguration.getModuleManager();
try {
ModuleManager.getInstance().init();
moduleMngr.init();
} catch (Throwable e) {
// not OK to continue without required elements
openEmergencyModuleManager("Impossible de configurer les modules requis", e);
openEmergencyModuleManager(moduleMngr, "Impossible de configurer les modules requis", e);
return;
}
 
MenuManager.setInstance(
(Gestion.isMinimalMode() ? new MinimalMenuConfiguration(comptaPropsConfiguration) : new DefaultMenuConfiguration(comptaPropsConfiguration)).createMenuAndActions());
 
197,7 → 202,7
MutableListComboPopupListener.setLockOverridable(rights.isSuperUser());
 
StatusPanel.getInstance().fireStatusChanged();
final MainFrame f = new MainFrame();
final MainFrame f = new MainFrame(comptaPropsConfiguration);
String version = comptaPropsConfiguration.getVersion();
final String socTitle = comptaPropsConfiguration.getRowSociete() == null ? "" : ", [Société " + comptaPropsConfiguration.getRowSociete().getString("NOM") + "]";
f.setTitle(comptaPropsConfiguration.getAppName() + " " + version + socTitle);
209,7 → 214,7
public void run() {
// make sure the application is started with all required and mandatory
// modules
if (ModuleManager.getInstance().isInited()) {
if (moduleMngr.isInited()) {
final MainFrame mainFrame = MainFrame.getInstance();
mainFrame.initMenuBar();
FrameUtil.show(mainFrame);
216,7 → 221,7
}
}
}, null);
ModuleManager.getInstance().invoke(new IClosure<ModuleManager>() {
moduleMngr.invoke(new IClosure<ModuleManager>() {
@Override
public void executeChecked(ModuleManager input) {
// start modules before displaying the frame (e.g. avoid modifying a
230,7 → 235,7
// but don't continue right away otherwise connexion panel will
// be closed and the popup with it
try {
ExceptionHandler.handle(NouvelleConnexionAction.this.connexionPanel, "Impossible de démarrer les modules", exn).getDialogFuture().get();
ExceptionHandler.handle(NouvelleConnexionAction.this.connexionPanel, "Impossible de démarrer les modules", exn).get();
} catch (Exception e) {
e.printStackTrace();
}
237,7 → 242,7
}
SwingUtilities.invokeLater(showMainFrame);
} catch (Exception exn) {
openEmergencyModuleManager("Impossible de démarrer les modules requis", exn);
openEmergencyModuleManager(input, "Impossible de démarrer les modules requis", exn);
}
}
});
246,7 → 251,8
showMainFrame.get();
} catch (Throwable e) {
if (e.getMessage() != null && ((e.getMessage().contains("table") && e.getMessage().contains("not found")) || e.getMessage().contains("unknown field")
|| e.getMessage().contains("Couldn't add showAs"))) {
|| e.getMessage().contains("Couldn't add showAs") || e.getMessage().contains("Base de données non à jour"))) {
e.printStackTrace();
JOptionPane.showMessageDialog(new JFrame(),
"Votre base de données n'est pas à jour.\nUtilisez l'outil de configuration et pensez à l'achat du manuel !\n(" + e.getMessage() + ")");
return;
276,7 → 282,7
if (this.connexionPanel == null)
return null;
this.connexionPanel.initLocalization(getClass().getName(), Arrays.asList(Locale.FRANCE, Locale.CANADA_FRENCH, new Locale("fr", "CH"), new Locale("fr", "BE"), Locale.UK, Locale.CANADA,
Locale.US, Locale.GERMANY, new Locale("de", "CH"), new Locale("pl", "PL")));
Locale.US, Locale.GERMANY, new Locale("de", "CH"), new Locale("es", "ES"), new Locale("pl", "PL")));
 
p.add(this.connexionPanel, c);
final PanelFrame panelFrame = new PanelFrame(p, "Connexion");
313,6 → 319,9
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMMERCIAL"), 600);
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("PERIODE_VALIDITE"), 1000);
 
if (comptaConf.getRootSociete().contains("DEPOT_STOCK")) {
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("DEPOT_STOCK"), 600);
}
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TYPE_REGLEMENT"), 1000);
SQLBackgroundTableCache.getInstance().startCacheWatcher();
 
351,7 → 360,7
}
}
 
private void openEmergencyModuleManager(final String str, final Throwable e) {
private void openEmergencyModuleManager(ModuleManager mngr, final String str, final Throwable e) {
Log.get().log(Level.SEVERE, "Normal startup impossible, opening the module manager in order to resolve the issue.", e);
SwingUtilities.invokeLater(new Runnable() {
@Override
359,7 → 368,7
ExceptionHandler.handle(str, e);
// can't start since there's no main frame (and obviously no modules can be stopped
// since none are running)
final ModuleFrame fMod = ModuleFrame.createInstallOnlyInstance();
final ModuleFrame fMod = new ModuleFrame(mngr, true);
fMod.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fMod.setTitle(str);
FrameUtil.show(fMod);
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction_es.properties
New file
0,0 → 1,6
adminLogin = Administrateur
loginLabel=Login
passwordLabel=Contraseña
companyLabel=Sociedad
saveCheckBox=Recordar contraseña
buttonConnect=Conexión
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeBlSQLInjector.java
54,6 → 54,12
if (tableBl.contains("PORT_HT")) {
map(tableCmd.getField("PORT_HT"), tableBl.getField("PORT_HT"));
}
if (getSource().contains("FRAIS_DOCUMENT_HT") && getDestination().contains("FRAIS_DOCUMENT_HT")) {
map(getSource().getField("FRAIS_DOCUMENT_HT"), getDestination().getField("FRAIS_DOCUMENT_HT"));
}
if (getSource().contains("ID_TAXE_FRAIS_DOCUMENT") && getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
map(getSource().getField("ID_TAXE_FRAIS_DOCUMENT"), getDestination().getField("ID_TAXE_FRAIS_DOCUMENT"));
}
if (tableBl.contains("REMISE_HT")) {
map(tableCmd.getField("REMISE_HT"), tableBl.getField("REMISE_HT"));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/DevisCommandeSQLInjector.java
34,6 → 34,13
if (tableDevis.contains("PORT_HT") && tableCommande.contains("PORT_HT")) {
map(tableDevis.getField("PORT_HT"), tableCommande.getField("PORT_HT"));
}
 
if (getSource().contains("FRAIS_DOCUMENT_HT") && getDestination().contains("FRAIS_DOCUMENT_HT")) {
map(getSource().getField("FRAIS_DOCUMENT_HT"), getDestination().getField("FRAIS_DOCUMENT_HT"));
}
if (getSource().contains("ID_TAXE_FRAIS_DOCUMENT") && getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
map(getSource().getField("ID_TAXE_FRAIS_DOCUMENT"), getDestination().getField("ID_TAXE_FRAIS_DOCUMENT"));
}
mapDefaultValues(tableCommande.getField("SOURCE"), tableDevis.getName());
map(tableDevis.getField("ID_DEVIS"), tableCommande.getField("IDSOURCE"));
map(tableDevis.getField("ID_DEVIS"), tableCommande.getField("ID_DEVIS"));
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/DevisFactureSQLInjector.java
34,6 → 34,12
map(tableDevis.getField("T_ACOMPTE"), tableFacture.getField("T_ACOMPTE"));
}
map(tableDevis.getField("PORT_HT"), tableFacture.getField("PORT_HT"));
if (getSource().contains("FRAIS_DOCUMENT_HT") && getDestination().contains("FRAIS_DOCUMENT_HT")) {
map(getSource().getField("FRAIS_DOCUMENT_HT"), getDestination().getField("FRAIS_DOCUMENT_HT"));
}
if (getSource().contains("ID_TAXE_FRAIS_DOCUMENT") && getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
map(getSource().getField("ID_TAXE_FRAIS_DOCUMENT"), getDestination().getField("ID_TAXE_FRAIS_DOCUMENT"));
}
map(tableDevis.getField("REMISE_HT"), tableFacture.getField("REMISE_HT"));
map(tableDevis.getField("ID_CLIENT"), tableFacture.getField("ID_CLIENT"));
map(tableDevis.getField("ID_COMMERCIAL"), tableFacture.getField("ID_COMMERCIAL"));
76,6 → 82,14
transfertReference(srcRow, rowVals, "INFOS", "INFOS");
transfertNumberReference(srcRow, rowVals, tableElementDestination, "ID_SAISIE_VENTE_FACTURE");
 
if (getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
final SQLRowAccessor rowClient = srcRow.getForeign("ID_CLIENT");
SQLRowAccessor rowFrais = rowClient.getForeign("ID_FRAIS_DOCUMENT");
if (rowFrais != null && !rowFrais.isUndefined()) {
rowVals.put("FRAIS_DOCUMENT_HT", rowFrais.getLong("MONTANT_HT"));
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", rowFrais.getForeignID("ID_TAXE"));
}
}
if (myListItem.size() != 0) {
final SQLInjector injector = SQLInjector.getInjector(tableElementSource, tableElementDestination);
for (SQLRowAccessor rowElt : myListItem) {
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/DevisBlSQLInjector.java
33,7 → 33,7
}
mapDefaultValues(tableBon.getField("SOURCE"), tableBon.getName());
map(tableDevis.getField("ID_DEVIS"), tableBon.getField("IDSOURCE"));
if (tableDevis.getTable().contains("ID_POLE_PRODUIT")) {
if (tableDevis.getTable().contains("ID_POLE_PRODUIT") && tableBon.getTable().contains("ID_POLE_PRODUIT")) {
map(tableDevis.getField("ID_POLE_PRODUIT"), tableBon.getField("ID_POLE_PRODUIT"));
}
if (getSource().getTable().contains("ID_CLIENT_DEPARTEMENT")) {
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/BonFactureSQLInjector.java
52,6 → 52,12
if (tableBon.contains("PORT_HT")) {
map(tableBon.getField("PORT_HT"), tableFacture.getField("PORT_HT"));
}
if (getSource().contains("FRAIS_DOCUMENT_HT") && getDestination().contains("FRAIS_DOCUMENT_HT")) {
map(getSource().getField("FRAIS_DOCUMENT_HT"), getDestination().getField("FRAIS_DOCUMENT_HT"));
}
if (getSource().contains("ID_TAXE_FRAIS_DOCUMENT") && getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
map(getSource().getField("ID_TAXE_FRAIS_DOCUMENT"), getDestination().getField("ID_TAXE_FRAIS_DOCUMENT"));
}
if (tableBon.contains("REMISE_HT")) {
map(tableBon.getField("REMISE_HT"), tableFacture.getField("REMISE_HT"));
}
74,7 → 80,14
transfertReference(srcRow, rowVals, "NOM", "NOM");
transfertReference(srcRow, rowVals, "INFOS", "INFOS");
transfertNumberReference(srcRow, rowVals, tableElementDestination, "ID_SAISIE_VENTE_FACTURE");
 
if (getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
final SQLRowAccessor rowClient = srcRow.getForeign("ID_CLIENT");
SQLRowAccessor rowFrais = rowClient.getForeign("ID_FRAIS_DOCUMENT");
if (rowFrais != null && !rowFrais.isUndefined()) {
rowVals.put("FRAIS_DOCUMENT_HT", rowFrais.getLong("MONTANT_HT"));
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", rowFrais.getForeignID("ID_TAXE"));
}
}
if (myListItem.size() != 0) {
final SQLInjector injector = SQLInjector.getInjector(tableElementSource, tableElementDestination);
for (SQLRowAccessor rowElt : myListItem) {
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeFactureClientSQLInjector.java
35,6 → 35,12
if (tableCommande.contains("PORT_HT")) {
map(tableCommande.getField("PORT_HT"), tableFacture.getField("PORT_HT"));
}
if (getSource().contains("FRAIS_DOCUMENT_HT") && getDestination().contains("FRAIS_DOCUMENT_HT")) {
map(getSource().getField("FRAIS_DOCUMENT_HT"), getDestination().getField("FRAIS_DOCUMENT_HT"));
}
if (getSource().contains("ID_TAXE_FRAIS_DOCUMENT") && getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
map(getSource().getField("ID_TAXE_FRAIS_DOCUMENT"), getDestination().getField("ID_TAXE_FRAIS_DOCUMENT"));
}
if (tableCommande.contains("ACOMPTE_COMMANDE")) {
map(tableCommande.getField("ACOMPTE_COMMANDE"), tableFacture.getField("ACOMPTE_COMMANDE"));
}
80,6 → 86,14
transfertReference(srcRow, rowVals, "NOM", "NOM");
transfertReference(srcRow, rowVals, "INFOS", "INFOS");
transfertNumberReference(srcRow, rowVals, tableElementDestination, "ID_SAISIE_VENTE_FACTURE");
if (getDestination().contains("ID_TAXE_FRAIS_DOCUMENT")) {
final SQLRowAccessor rowClient = srcRow.getForeign("ID_CLIENT");
SQLRowAccessor rowFrais = rowClient.getForeign("ID_FRAIS_DOCUMENT");
if (rowFrais != null && !rowFrais.isUndefined()) {
rowVals.put("FRAIS_DOCUMENT_HT", rowFrais.getLong("MONTANT_HT"));
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", rowFrais.getForeignID("ID_TAXE"));
}
}
if (myListItem.size() != 0) {
final SQLInjector injector = SQLInjector.getInjector(tableElementSource, tableElementDestination);
for (SQLRowAccessor rowElt : myListItem) {
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/DevisBlEltSQLInjector.java
New file
0,0 → 1,28
/*
* 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.injector;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLInjector;
 
public class DevisBlEltSQLInjector extends SQLInjector {
public DevisBlEltSQLInjector(final DBRoot root) {
super(root, "DEVIS_ELEMENT", "BON_DE_LIVRAISON_ELEMENT", false);
createDefaultMap();
mapDefaultValues(getDestination().getField("QTE_LIVREE"), Integer.valueOf(0));
if (getDestination().contains("ID_DEVIS_ELEMENT")) {
map(getSource().getKey(), getDestination().getField("ID_DEVIS_ELEMENT"));
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SpreadSheetGenerator.java
14,6 → 14,7
package org.openconcerto.erp.generationDoc;
 
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.PreviewFrame;
import org.openconcerto.erp.preferences.TemplateNXProps;
216,14 → 217,13
fTmp.renameTo(fDest);
 
fDest = new File(this.destDirOO, this.destFileName + ".ods");
final InputStream stream = getStreamStatic(fODSP);
try (final InputStream stream = getStreamStatic(fODSP)) {
if (stream != null) {
// Copie de l'odsp
File odspOut = new File(this.destDirOO, this.destFileName + ".odsp");
StreamUtils.copy(stream, odspOut);
stream.close();
 
}
}
try {
ssheet.saveAs(fDest);
} catch (FileNotFoundException e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractJOOReportsSheet.java
231,7 → 231,7
}
}
 
private File getDocumentFile() {
public File getDocumentFile() {
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(getDefaultTemplateID());
return new File(outputDir, getFileName() + ".odt");
}
302,12 → 302,15
return init;
}
 
public File getPDFDocumentFile() {
final File outputPDFDirectory = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.templateId);
return new File(outputPDFDirectory, getFileName() + ".pdf");
}
 
public void exportToPdf() {
// Export vers PDF
final String fileName = getFileName();
final File fileOutOO = getDocumentFile();
final File outputPDFDirectory = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.templateId);
final File fileOutPDF = new File(outputPDFDirectory, fileName + ".pdf");
final File fileOutPDF = getPDFDocumentFile();
 
if (!fileOutOO.exists()) {
generate(false, false, "");
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractLocalTemplateProvider.java
47,7 → 47,7
throw new NullPointerException("null templateId");
}
File templateFile1 = getTemplateFromLocalFile(templateId, language, type);
if (templateFile1 != null && templateFile1.exists()) {
if (templateFile1 != null && templateFile1.exists() && !templateFile1.isDirectory()) {
return templateFile1;
}
File templateFile2 = getTemplateFromLocalFile(templateId + ".ods", language, type);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeColumnXML.java
24,12 → 24,16
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StreamUtils;
import org.openconcerto.utils.io.BOMSkipper;
 
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
46,7 → 50,7
public class OOgenerationListeColumnXML {
 
// Cache pour la recherche des styles
private static Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<Sheet, Map<String, Map<Integer, String>>>();
private static Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<>();
 
public static File genere(String modele, File pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values) {
return genere(modele, pathDest, fileDest, liste, values, new HashMap<Integer, Map<Integer, String>>(), null, null);
61,7 → 65,11
if (xmlConfiguration == null) {
throw new IllegalStateException("Template configuration " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
Document doc = builder.build(xmlConfiguration);
final BufferedReader xmlConfigurationReader = new BufferedReader(new InputStreamReader(xmlConfiguration, Charset.forName("UTF8")));
BOMSkipper.skip(xmlConfigurationReader);
final Document doc = builder.build(xmlConfigurationReader);
xmlConfigurationReader.close();
xmlConfiguration.close();
 
// On initialise un nouvel élément racine avec l'élément racine du
// document.
84,7 → 92,7
for (Integer i : liste.keySet()) {
final Sheet sheet = spreadSheet.getSheet(i);
List children = racine.getChildren("element" + i);
if (children.size() == 0) {
if (children.isEmpty()) {
children = racine.getChildren("element");
}
parseElementsXML(children, sheet, values.get(i));
138,7 → 146,7
}
Object oLastColTmp = tableau.getAttributeValue("lastColumn");
int lastColumn = -1;
int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
int endPageLine = Integer.parseInt(tableau.getAttributeValue("endPageLine"));
if (oLastColTmp != null) {
lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
}
202,11 → 210,7
*/
private static int fillTable(Element tableau, List<Map<String, Object>> liste, Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test, Map<Integer, String> style) {
 
// int nbPage = 1;
// int currentLineTmp = Integer.valueOf(tableau.getAttributeValue("firstLine"));
// int currentLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
// int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
int endLine = Integer.valueOf(tableau.getAttributeValue("endLine"));
int endLine = Integer.parseInt(tableau.getAttributeValue("endLine"));
 
List listElts = tableau.getChildren("element");
 
222,7 → 226,6
int currentCol = firstCol;
for (int i = 0; i < liste.size(); i++) {
Map<String, Object> mValues = liste.get(i);
// System.err.println(mValues);
if (currentCol != firstCol) {
for (int k = 0; k < endLine; k++) {
MutableCell<SpreadSheet> c1 = sheet.getCellAt(firstCol, k);
464,9 → 467,8
}
 
// Copie de l'odsp
try {
File odspOut = new File(pathDest, fileName + ".odsp");
InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);) {
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/ReportingTaxeComplementaireSheetXML.java
83,16 → 83,26
private static SQLTable tableVF = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE").getTable();
 
class TaxeComplRecap {
private final String code, nom;
private final String code, nom, numeroCptProduit, numeroCpt;
private BigDecimal percentTaxe, totalBase, qte;
 
public TaxeComplRecap(String code, String nom, BigDecimal percentTaxe) {
this.code = code;
this.nom = nom;
public TaxeComplRecap(SQLRowAccessor foreignTaxeCompl) {
this.code = foreignTaxeCompl.getString("CODE");
this.nom = foreignTaxeCompl.getString("NOM");
this.qte = BigDecimal.ZERO;
this.percentTaxe = percentTaxe;
this.percentTaxe = foreignTaxeCompl.getBigDecimal("POURCENT");
this.totalBase = BigDecimal.ZERO;
if (foreignTaxeCompl.getObject("ID_COMPTE_PCE") != null && !foreignTaxeCompl.isForeignEmpty("ID_COMPTE_PCE")) {
this.numeroCpt = foreignTaxeCompl.getForeign("ID_COMPTE_PCE").getString("NUMERO");
} else {
this.numeroCpt = "";
}
if (foreignTaxeCompl.getObject("ID_COMPTE_PCE_PRODUITS") != null && !foreignTaxeCompl.isForeignEmpty("ID_COMPTE_PCE_PRODUITS")) {
this.numeroCptProduit = foreignTaxeCompl.getForeign("ID_COMPTE_PCE_PRODUITS").getString("NUMERO");
} else {
this.numeroCptProduit = "";
}
}
 
public void cumul(BigDecimal qte, BigDecimal total) {
this.qte = qte.add(this.qte);
107,6 → 117,14
return nom;
}
 
public String getNumeroCpt() {
return numeroCpt;
}
 
public String getNumeroCptProduit() {
return numeroCptProduit;
}
 
public BigDecimal getQte() {
return qte;
}
142,8 → 160,10
rowvalsVFElt.put("T_PV_HT", null);
rowvalsVFElt.put("QTE", null);
rowvalsVFElt.put("QTE_UNITAIRE", null);
rowvalsVFElt.putRowValues("ID_ARTICLE").putRowValues("ID_TAXE_COMPLEMENTAIRE").putNulls("CODE", "NOM", "POURCENT");
 
final SQLRowValues rowValsTaxeCompl = rowvalsVFElt.putRowValues("ID_ARTICLE").putRowValues("ID_TAXE_COMPLEMENTAIRE");
rowValsTaxeCompl.putNulls("CODE", "NOM", "POURCENT");
rowValsTaxeCompl.putRowValues("ID_COMPTE_PCE_PRODUITS").putNulls("NUMERO", "NOM");
rowValsTaxeCompl.putRowValues("ID_COMPTE_PCE").putNulls("NUMERO", "NOM");
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowvalsVFElt);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
166,7 → 186,7
if (recap.containsKey(foreignTaxeCompl.getID())) {
r = recap.get(foreignTaxeCompl.getID());
} else {
r = new TaxeComplRecap(foreignTaxeCompl.getString("CODE"), foreignTaxeCompl.getString("NOM"), foreignTaxeCompl.getBigDecimal("POURCENT"));
r = new TaxeComplRecap(foreignTaxeCompl);
recap.put(foreignTaxeCompl.getID(), r);
}
r.cumul(sqlRowValues.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRowValues.getInt("QTE"))), sqlRowValues.getBigDecimal("T_PV_HT"));
186,6 → 206,9
for (TaxeComplRecap item : recap.values()) {
Map<String, Object> vals = new HashMap<String, Object>();
 
vals.put("COMPTE_NUMERO", item.getNumeroCpt());
vals.put("COMPTE_PRODUIT_NUMERO", item.getNumeroCptProduit());
 
vals.put("CODE", item.getCode());
vals.put("NOM", item.getNom());
vals.put("QTE", item.getQte());
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/DepotChequeXmlSheet.java
New file
0,0 → 1,44
/*
* 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.gestcomm;
 
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
 
public class DepotChequeXmlSheet extends AbstractSheetXMLWithDate {
 
public static final String TEMPLATE_ID = "DepotCheque";
public static final String TEMPLATE_PROPERTY_NAME = "LocationDepotCheque";
 
@Override
public String getName() {
 
return "DepotCheque" + this.row.getID();
}
 
public DepotChequeXmlSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("FacturePrinter");
this.elt = Configuration.getInstance().getDirectory().getElement("DEPOT_CHEQUE");
getDefaultTemplateId();
}
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/InvalidTemplateException.java
New file
0,0 → 1,26
/*
* 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;
 
public class InvalidTemplateException extends RuntimeException {
 
public InvalidTemplateException(String cause) {
super(cause);
}
 
public InvalidTemplateException(String cause, Exception e) {
super(cause, e);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/A4.java
28,6 → 28,6
final double width = (210 * DPI) / INCH_TO_MM;
final double height = (297 * DPI) / INCH_TO_MM;
setSize(width, height);
setImageableArea(hMargin, vMargin, width + 2 * hMargin, height - 2 * vMargin);
setImageableArea(hMargin, vMargin, width - 2 * hMargin, height - 2 * vMargin);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/DefaultLocalTemplateProvider.java
109,9 → 109,15
final File from = getFile(templateId + ext, language, type);
final File to = getLocalFile(templateId + ext, language, type);
try {
if (from.exists() && !to.exists()) {
if (from != null && to != null && from.exists() && !to.exists()) {
final File parentDir = to.getParentFile();
if (parentDir != null) {
if (!parentDir.exists()) {
parentDir.mkdirs();
}
FileUtils.copyFile(from, to);
}
}
} catch (IOException e) {
throw new IllegalStateException("Copie impossible", e);
}
140,7 → 146,7
for (int i = 0; i < EXTS.length; i++) {
final String ext = EXTS[i];
final File local = getLocalFile(templateId + ext, language, type);
if (local.exists()) {
if (local != null && local.exists()) {
local.delete();
ensureDelete(local);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/element/ModeleSQLElement.java
33,15 → 33,17
super("MODELE", "un modele ", "modeles");
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("NOM");
l.add("ID_TYPE_MODELE");
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("NOM");
l.add("ID_TYPE_MODELE");
return l;
52,7 → 54,7
 
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<String>();
final Set<String> s = new HashSet<>();
// s.add("NOM");
// s.add("ID_TYPE_MODELE");
return s;
65,8 → 67,13
};
}
 
@Override
public String getDescription(SQLRow fromRow) {
return fromRow.getString("NOM");
}
 
@Override
protected String createCode() {
return "document.template";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/element/TypeModeleSQLElement.java
16,8 → 16,7
*/
package org.openconcerto.erp.generationDoc.element;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.DBRoot;
33,16 → 32,12
import java.util.Map;
import java.util.Set;
 
public class TypeModeleSQLElement extends ConfSQLElement {
public class TypeModeleSQLElement extends ComptaSQLConfElement {
 
public TypeModeleSQLElement(DBRoot root) {
super(root.getTable("TYPE_MODELE"), "un type_modele ", "type_modeles");
super(root.getTable("TYPE_MODELE"), "un type de modèle", "types de modèles");
}
 
public TypeModeleSQLElement() {
this(Configuration.getInstance().getRoot());
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
91,17 → 86,20
 
if (this.template == null) {
this.template = new HashMap<String, String>();
SQLSelect sel = new SQLSelect(getTable().getBase());
SQLSelect sel = new SQLSelect();
sel.addSelectStar(getTable());
List<SQLRow> rows = (List<SQLRow>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
for (SQLRow sqlRow : rows) {
template.put(sqlRow.getString("TABLE"), sqlRow.getString("DEFAULT_MODELE"));
for (SQLRow sqlRow : SQLRowListRSH.execute(sel)) {
this.template.put(sqlRow.getString("TABLE"), sqlRow.getString("DEFAULT_MODELE"));
}
 
}
 
return template;
return this.template;
 
}
 
@Override
protected String createCode() {
return "document.template-type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
37,15 → 37,19
import org.openconcerto.utils.StreamUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.io.BOMSkipper;
 
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
77,12 → 81,12
private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 
// Cache pour la recherche des styles
private Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<Sheet, Map<String, Map<Integer, String>>>();
private Map<SQLRowAccessor, Map<String, Object>> taxe = new HashMap<SQLRowAccessor, Map<String, Object>>();
private Map<String, Map<Integer, SQLRowAccessor>> cacheForeign = new HashMap<String, Map<Integer, SQLRowAccessor>>();
private Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<>();
private Map<SQLRowAccessor, Map<String, Object>> taxe = new HashMap<>();
private Map<String, Map<Integer, SQLRowAccessor>> cacheForeign = new HashMap<>();
 
// Cache pour les SQLRow du tableau
private Map<String, List<? extends SQLRowAccessor>> rowsEltCache = new HashMap<String, List<? extends SQLRowAccessor>>();
private Map<String, List<? extends SQLRowAccessor>> rowsEltCache = new HashMap<>();
private final OOXMLCache rowRefCache = new OOXMLCache();
private final SQLRow row;
 
155,7 → 159,11
+ ((typeTemplate == null) ? "" : typeTemplate));
return null;
}
Document doc = builder.build(xmlConfiguration);
 
final BufferedReader xmlConfigurationReader = new BufferedReader(new InputStreamReader(xmlConfiguration, Charset.forName("UTF8")));
BOMSkipper.skip(xmlConfigurationReader);
final Document doc = builder.build(xmlConfigurationReader);
xmlConfigurationReader.close();
xmlConfiguration.close();
 
// On initialise un nouvel élément racine avec l'élément racine du document.
239,7 → 247,7
// et d'optimiser la recherche
Object oLastColTmp = tableau.getAttributeValue("lastColumn");
int lastColumn = -1;
int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
int endPageLine = Integer.parseInt(tableau.getAttributeValue("endPageLine"));
if (oLastColTmp != null) {
lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
}
251,8 → 259,8
return;
}
int nbPage = fillTable(tableau, row, sheet, mapStyle, true, rowLanguage);
int firstLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
int endLine = Integer.valueOf(tableau.getAttributeValue("endLine"));
int firstLine = Integer.parseInt(tableau.getAttributeValue("firstLine"));
int endLine = Integer.parseInt(tableau.getAttributeValue("endLine"));
Object printRangeObj = sheet.getPrintRanges();
 
System.err.println("Nombre de page == " + nbPage);
286,7 → 294,7
int lineToAdd = endPageLine - endLine;
String repeatedCount = tableau.getAttributeValue("repeatedCount");
if (repeatedCount != null && repeatedCount.trim().length() > 0) {
int count = Integer.valueOf(repeatedCount);
int count = Integer.parseInt(repeatedCount);
sheet.duplicateRows(firstLine, lineToAdd / count, count);
final int rest = lineToAdd % count;
// Si le nombre de ligne ne termine pas à la fin de la page
324,7 → 332,7
cell2.setValue("Page " + (i + start) + "/" + nbPageRef);
}
if (pageAdd != null && pageAdd.trim().length() > 0) {
int pAdd = Integer.valueOf(pageAdd);
int pAdd = Integer.parseInt(pageAdd);
for (int i = 0; i < pAdd; i++) {
Sheet s = sheet.getSpreadSheet().getSheet(idSheet + i + 1);
MutableCell<SpreadSheet> cell2 = s.getCellAt(pageRef);
362,7 → 370,7
SQLRowAccessor foreign = row.getForeign(field.getName());
 
if (c == null) {
Map<Integer, SQLRowAccessor> map = new HashMap<Integer, SQLRowAccessor>();
Map<Integer, SQLRowAccessor> map = new HashMap<>();
map.put(i, foreign);
cacheForeign.put(field.getName(), map);
} else {
371,7 → 379,6
 
return foreign;
}
// return row.getForeignRow(field.getName());
 
}
 
384,7 → 391,7
SQLBackgroundTableCacheItem prefsCpt = SQLBackgroundTableCache.getInstance().getCacheForTable(tableElt.getTable("PREFS_COMPTE"));
if (tableElt.contains("ID_TAXE") && tableElt.contains("T_PA_HT")) {
boolean achat = tableElt.contains("T_PA_TTC");
TotalCalculator calc = new TotalCalculator("T_PA_HT", achat ? "T_PA_HT" : "T_PV_HT", null, achat, null);
TotalCalculator calc = new TotalCalculator("T_PA_HT", achat ? "T_PA_HT" : "T_PV_HT", null, achat, null, null);
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean bServiceActive = Boolean.valueOf(val);
 
487,7 → 494,7
Map<SQLRowAccessor, Tuple2<BigDecimal, BigDecimal>> taxeCalc = calc.getMapHtTVARowTaux();
for (SQLRowAccessor sqlRow : taxeCalc.keySet()) {
Tuple2<BigDecimal, BigDecimal> v = taxeCalc.get(sqlRow);
Map<String, Object> m = new HashMap<String, Object>();
Map<String, Object> m = new HashMap<>();
m.put("MONTANT_HT", v.get0());
m.put("MONTANT_TVA", v.get1());
taxe.put(sqlRow, m);
510,12 → 517,9
 
StyleSQLElement styleElt = Configuration.getInstance().getDirectory().getElement(StyleSQLElement.class);
 
boolean cache = false;
String ref = tableau.getAttributeValue("table") + "_" + row.getTable().getName() + row.getID();
if (rowsEltCache.get(ref) == null) {
rowsEltCache.put(ref, tableElement.getRows());
} else {
cache = true;
}
List<Element> listElts = tableau.getChildren("element");
 
553,10 → 557,10
}
 
// Cache des valeurs
Map<Element, Object> mapValues = new HashMap<Element, Object>();
Map<Element, Object> mapValues = new HashMap<>();
 
// Test si l'ensemble des donnees tient sur la page courante
Map<String, Integer> tmpMapNbCel = new HashMap<String, Integer>();
Map<String, Integer> tmpMapNbCel = new HashMap<>();
int tmpNbCellule = fillTableLine(sheet, mapStyle, true, rowLanguage, tableElement, currentLine, listElts, numeroRef, rowElt, tmpMapNbCel, styleName, mapValues);
for (String s : tmpMapNbCel.keySet()) {
tmpNbCellule = Math.max(tmpNbCellule, tmpMapNbCel.get(s));
569,7 → 573,7
}
 
// Remplissage reel des cellules
Map<String, Integer> mapNbCel = new HashMap<String, Integer>();
Map<String, Integer> mapNbCel = new HashMap<>();
int nbCellule = fillTableLine(sheet, mapStyle, test, rowLanguage, tableElement, currentLine, listElts, numeroRef, rowElt, mapNbCel, styleName, mapValues);
 
for (String s : mapNbCel.keySet()) {
707,7 → 711,7
 
private void fillTaxeDocumentMap(Element tableau, Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test) {
 
int line = Integer.valueOf(tableau.getAttributeValue("firstLine"));
int line = Integer.parseInt(tableau.getAttributeValue("firstLine"));
List<Element> listElts = tableau.getChildren("element");
 
for (SQLRowAccessor rowTaxe : taxe.keySet()) {
953,12 → 957,10
}
 
// Copie de l'odsp
try {
File odspOut = new File(pathDest, fileName + ".odsp");
final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, null);
try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, null);) {
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
odspIn.close();
}
} catch (FileNotFoundException e) {
System.err.println("OOgenerationXML.saveSpreadSheet() : Le fichier odsp n'existe pas.");
985,7 → 987,7
System.err.println("End row search : " + rowCount);
for (int i = 0; i < rowCount; i++) {
int x = 0;
Map<Integer, String> mapCellStyle = new HashMap<Integer, String>();
Map<Integer, String> mapCellStyle = new HashMap<>();
String style = "";
 
for (int j = 0; j < columnCount; j++) {
1045,7 → 1047,7
List<Element> listTable = racine.getChildren("table");
 
Element tableau;
if (listTable.size() == 0) {
if (listTable.isEmpty()) {
return false;
} else {
if (listTable.get(0).getAttributeValue("table").equalsIgnoreCase("TVA")) {
1058,7 → 1060,7
 
Object oLastColTmp = tableau.getAttributeValue("lastColumn");
int lastColumn = -1;
int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
int endPageLine = Integer.parseInt(tableau.getAttributeValue("endPageLine"));
if (oLastColTmp != null) {
lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
24,12 → 24,16
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StreamUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.io.BOMSkipper;
 
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
62,7 → 66,11
if (xmlConfiguration == null) {
throw new IllegalStateException("Template configuration " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
Document doc = builder.build(xmlConfiguration);
final BufferedReader xmlConfigurationReader = new BufferedReader(new InputStreamReader(xmlConfiguration, Charset.forName("UTF8")));
BOMSkipper.skip(xmlConfigurationReader);
final Document doc = builder.build(xmlConfigurationReader);
xmlConfigurationReader.close();
xmlConfiguration.close();
 
// On initialise un nouvel élément racine avec l'élément racine du
// document.
74,6 → 82,7
throw new IllegalStateException("Template " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
 
Sheet sheet0 = spreadSheet.getSheet(0);
if (sheetName != null && sheetName.size() > 0) {
for (int i = 1; i < sheetName.size(); i++) {
83,7 → 92,12
}
 
for (Integer i : liste.keySet()) {
final Sheet sheet = spreadSheet.getSheet(i);
final Sheet sheet;
try {
sheet = spreadSheet.getSheet(i);
} catch (Exception e) {
throw new InvalidTemplateException("La feuille numéro " + i + " n'est pas dans le modèle", e);
}
List children = racine.getChildren("element" + i);
if (children.size() == 0) {
children = racine.getChildren("element");
96,6 → 110,7
parseListeXML(child, liste.get(i), sheet, mapStyle.get(i));
}
cacheStyle.clear();
 
// Sauvegarde du fichier
return saveSpreadSheet(spreadSheet, pathDest, fileDest, templateId, rowLanguage);
 
555,9 → 570,8
}
 
// Copie de l'odsp
try {
File odspOut = new File(pathDest, fileName + ".odsp");
InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);) {
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLCache.java
24,6 → 24,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.CompareUtils;
301,8 → 302,11
if (orderBy != null && orderBy.contains(".")) {
String fieldRefTable = orderBy.substring(0, orderBy.indexOf('.'));
String field = orderBy.substring(orderBy.indexOf('.') + 1, orderBy.length());
if (sel.getJoin(tableForeign.getField(fieldRefTable)) == null) {
sel.addJoin("LEFT", sel.getAlias(tableForeign).getField(fieldRefTable));
sel.addFieldOrder(sel.getAlias(tableForeign.getForeignTable(fieldRefTable)).getField(field));
}
SQLSelectJoin join = sel.getJoin(tableForeign.getField(fieldRefTable));
sel.addFieldOrder(join.getJoinedTable().getField(field));
} else {
sel.addFieldOrder(tableForeign.getOrderField());
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
15,7 → 15,10
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.PreviewFrame;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.quote.report.PaypalStamper;
import org.openconcerto.erp.generationDoc.element.TypeModeleSQLElement;
import org.openconcerto.erp.preferences.PayPalPreferencePanel;
import org.openconcerto.erp.storage.CloudStorageEngine;
import org.openconcerto.erp.storage.StorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
26,19 → 29,31
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.GraphicsEnvironment;
import java.awt.print.PrinterJob;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
213,8 → 228,7
}
 
} catch (Exception e) {
e.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
ExceptionHandler.handle("Impossible de charger le document OpenOffice " + pdfFile.getAbsolutePath() + "(viewer : " + useODSViewer + ")", e);
}
}
 
239,12 → 253,87
return this.meta;
}
 
public static void createPDF(final File generatedFile, final File pdfFile, final OpenDocument doc, String storagePath) {
public void createPDF(final File generatedFile, final File pdfFile, final OpenDocument doc, String storagePath) {
if (pdfFile == null) {
throw new IllegalArgumentException("null PDF file");
}
try {
if (VenteFactureXmlSheet.TEMPLATE_ID.equals(getDefaultTemplateId())) {
final SQLPreferences prefs = SQLPreferences.getMemCached(getElement().getTable().getDBRoot());
if (prefs.getBoolean(PayPalPreferencePanel.PAYPAL_INVOICE, false)) {
try {
final File inFile = File.createTempFile("oc_", pdfFile.getName());
SheetUtils.convert2PDF(doc, inFile);
PaypalStamper s = new PaypalStamper();
int x = prefs.getInt(PayPalPreferencePanel.PAYPAL_INVOICE_X, 0);
int y = prefs.getInt(PayPalPreferencePanel.PAYPAL_INVOICE_Y, 0);
 
// Reference
String ref = getSQLRow().getString("NUMERO");
// Montant : ex : 10.55
long cents = getSQLRow().getLong("NET_A_PAYER");
String amount = cents / 100 + "." + cents % 100;
// Devise
// TODO : autres devises
String currency = "EUR";
// POST
final URL url = new URL("https://cloud.openconcerto.org/payment");
final URLConnection con = url.openConnection();
final HttpURLConnection http = (HttpURLConnection) con;
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDefaultUseCaches(false);
 
String hyperlink = null;
// x-www-form-urlencoded
final Map<String, String> arguments = new HashMap<>();
arguments.put("pI", prefs.get(PayPalPreferencePanel.PAYPAL_CLIENTID, ""));
arguments.put("pS", prefs.get(PayPalPreferencePanel.PAYPAL_SECRET, ""));
arguments.put("ref", ref);
arguments.put("amount", amount);
arguments.put("currency", currency);
arguments.put("type", "paypal");
final StringJoiner sj = new StringJoiner("&");
for (Map.Entry<String, String> entry : arguments.entrySet()) {
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
}
final String postData = sj.toString();
System.err.println("SheetXml.createPDF() " + postData);
byte[] out = postData.getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try (OutputStream os = http.getOutputStream()) {
os.write(out);
}
if (http.getResponseCode() != 401) {
 
InputStream is = http.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
 
int numCharsRead;
char[] charArray = new char[1024];
StringBuilder sb = new StringBuilder();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
//
hyperlink = sb.toString();
}
s.addLink(inFile, pdfFile, x, y, hyperlink);
} catch (Exception e) {
e.printStackTrace();
SheetUtils.convert2PDF(doc, pdfFile);
}
 
} else {
SheetUtils.convert2PDF(doc, pdfFile);
}
} else {
SheetUtils.convert2PDF(doc, pdfFile);
}
 
} catch (Throwable e) {
ExceptionHandler.handle("Impossible de créer le PDF " + pdfFile.getAbsolutePath(), e);
}
421,8 → 510,23
File f;
try {
f = getOrCreateDocumentFile();
// ComptaPropsConfiguration.getOOConnexion().loadDocument(f, false);
if (f != null && f.exists()) {
OOUtils.open(f);
} else {
if (!GraphicsEnvironment.isHeadless()) {
if (f != null) {
JOptionPane.showMessageDialog(null, "Le fichier " + f.getAbsolutePath() + " est manquant");
} else {
JOptionPane.showMessageDialog(null, "Fichier manquant");
}
} else {
if (f != null) {
throw new FileNotFoundException(f.getAbsolutePath() + " missing");
} else {
throw new NullPointerException("null document");
}
}
}
} catch (Exception e) {
ExceptionHandler.handle("Impossible d'ouvrir le document.", e);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLField.java
84,6 → 84,9
// {
String field = this.elt.getAttributeValue("name");
 
if (field != null && field.trim().length() > 0 && !this.row.getTable().contains(field)) {
throw new InvalidTemplateException("Le champ " + field + " n'existe pas dans la table " + this.row.getTable().getName());
}
final SQLField sqlField = (field == null || field.trim().length() == 0) ? null : this.row.getTable().getField(field);
boolean isForeignField = (sqlField == null) ? false : this.row.getTable().getForeignKeys().contains(sqlField);
 
137,10 → 140,16
String typeComp = this.elt.getAttributeValue("type");
if (this.op != null && this.op.trim().length() > 0 && !(typeComp != null && typeComp.trim().length() > 0 && typeComp.toLowerCase().startsWith("deviselettre"))) {
String field2 = this.elt.getAttributeValue("name2");
if (!this.row.getTable().contains(field)) {
throw new InvalidTemplateException("Le champ " + field + " n'existe pas dans la table " + this.row.getTable().getName());
}
Number o = (Number) this.row.getObject(field);
 
Number o2;
if (field2 != null && field2.trim().length() > 0) {
if (!this.row.getTable().contains(field2)) {
throw new InvalidTemplateException("Le champ " + field2 + " n'existe pas dans la table " + this.row.getTable().getName());
}
o2 = (Number) this.row.getObject(field2);
} else {
o2 = Double.parseDouble(this.elt.getAttributeValue("number"));
223,6 → 232,9
}
stringValue = o.toString();
} else {
if (!this.row.getTable().contains(field)) {
throw new InvalidTemplateException("Le champ " + field + " n'existe pas dans la table " + this.row.getTable().getName());
}
Object o2 = this.row.getObject(field);
 
if (o2 != null && scale != null && scale.trim().length() > 0) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteFacture.java
139,12 → 139,14
 
SQLTable tableEchantillon = null;
BigDecimal portHT = BigDecimal.valueOf(saisieRow.getLong("PORT_HT")).movePointLeft(2);
BigDecimal fraisDocHT = BigDecimal.valueOf(saisieRow.getLong("FRAIS_DOCUMENT_HT")).movePointLeft(2);
TotalCalculator calc;
if (clientRow.getTable().contains("ID_COMPTE_PCE_PRODUIT") && !clientRow.isForeignEmpty("ID_COMPTE_PCE_PRODUIT")) {
calc = getValuesFromElement(false, false, "T_PV_HT", saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), portHT, saisieRow.getForeign("ID_TAXE_PORT"), tableEchantillon,
clientRow.getForeign("ID_COMPTE_PCE_PRODUIT"));
calc = getValuesFromElement(false, false, "T_PV_HT", saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), portHT, saisieRow.getForeign("ID_TAXE_PORT"), fraisDocHT,
saisieRow.getForeign("ID_TAXE_FRAIS_DOCUMENT"), tableEchantillon, clientRow.getForeign("ID_COMPTE_PCE_PRODUIT"));
} else {
calc = getValuesFromElement(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), portHT, saisieRow.getForeign("ID_TAXE_PORT"), tableEchantillon);
calc = getValuesFromElement(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), portHT, saisieRow.getForeign("ID_TAXE_PORT"), fraisDocHT,
saisieRow.getForeign("ID_TAXE_FRAIS_DOCUMENT"), tableEchantillon);
}
 
// On génére les ecritures si la facture n'est pas un acompte
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementAchat.java
72,6 → 72,9
}
 
SQLRow rowMvtSource = tableMouvement.getRow(mvtSource);
if (rowMvtSource == null) {
throw new IllegalStateException("Aucun mouvement source associé aux échéances.\n(Mouvement source : " + mvtSource + ", REGLER_MONTANT " + regMontantRow.getID() + ")");
}
 
// si paiement comptant
if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0)) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtFactureFournisseur.java
96,7 → 96,7
}
BigDecimal portHT = BigDecimal.valueOf(saisieRow.getLong("PORT_HT")).movePointLeft(2);
TotalCalculator calc = getValuesFromElement(rowFournisseur.getBoolean("UE"), true, "T_PA_HT", saisieRow, saisieRow.getTable().getTable("FACTURE_FOURNISSEUR_ELEMENT"), portHT,
saisieRow.getForeign("ID_TAXE_PORT"), null, rowCompteAchat);
saisieRow.getForeign("ID_TAXE_PORT"), BigDecimal.ZERO, null, null, rowCompteAchat);
 
long ttcLongValue = calc.getTotalTTC().movePointRight(2).longValue();
long htLongValue = calc.getTotalHT().movePointRight(2).longValue();
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementFactureFournisseur.java
70,7 → 70,7
// long l = ((Number) avoirRow.getObject("MONTANT_TTC")).longValue();
// prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue() - l);
// } else {
prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue());
prixTTC = new PrixTTC(((Long) saisieRow.getObject("NET_A_PAYER")).longValue());
// }
 
this.date = (Date) saisieRow.getObject("DATE");
192,7 → 192,7
// long l = ((Number) avoirRow.getObject("MONTANT_TTC")).longValue();
// prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue() - l);
// } else {
prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue());
prixTTC = new PrixTTC(((Long) saisieRow.getObject("NET_A_PAYER")).longValue());
// }
 
// Ajout dans cheque fournisseur
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtDepotChequeClient.java
New file
0,0 → 1,174
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
/*
* 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.generationEcritures;
 
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.StringUtils;
 
import java.util.ArrayList;
import java.util.List;
 
public class GenerationMvtDepotChequeClient extends GenerationEcritures {
 
private long montant;
 
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
private final SQLRow depot;
private SQLRowAccessor banque;
 
public GenerationMvtDepotChequeClient(SQLRow depot) {
this.montant = depot.getLong("MONTANT");
this.date = depot.getDate("DATE").getTime();
this.banque = depot.getForeign("ID_" + BanqueSQLElement.TABLENAME);
this.depot = depot;
// SQLRow chequeRow = base.getTable("CHEQUE_A_ENCAISSER").getRow(this.idCheque);
// String num = "";
// if (chequeRow != null && !chequeRow.isUndefined() &&
// chequeRow.getString("NUMERO").trim().length() > 0) {
// num = " N° " + chequeRow.getString("NUMERO");
// }
//
// if (s != null && s.trim().length() > 0) {
// this.nom = s + (num.trim().length() > 0 ? " - Cheque" + num : "");
// } else {
// this.nom = "Reglement cheque client" + num;
// }
}
 
public void genere() throws Exception {
System.err.println("génération des ecritures de règlement d'un cheque client du mouvement " + this.idMvt);
this.nom = this.depot.getString("NOM");
if (this.depot.getObject("ID_MOUVEMENT") == null || this.depot.isForeignEmpty("ID_MOUVEMENT")) {
this.idMvt = getNewMouvement(depot.getTable().getName(), depot.getID(), 1, this.nom);
} else {
this.idMvt = this.depot.getForeignID("ID_MOUVEMENT");
SQLRowValues rowValspiece = this.depot.getForeign("ID_MOUVEMENT").getForeign("ID_PIECE").createEmptyUpdateRow();
rowValspiece.put("NOM", this.nom);
rowValspiece.update();
}
 
// initialisation des valeurs de la map
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
if (this.banque == null || this.banque.isUndefined() || this.banque.isForeignEmpty("ID_JOURNAL")) {
fillJournalBanqueFromRow(depot);
} else {
int idJrnl = this.banque.getForeignID("ID_JOURNAL");
this.putValue("ID_JOURNAL", idJrnl);
}
 
List<Integer> pieceIDs = new ArrayList<Integer>();
SQLRowValues rowValsDepotElt = new SQLRowValues(depot.getTable().getTable("DEPOT_CHEQUE_ELEMENT"));
rowValsDepotElt.putNulls("MONTANT", "TIERS");
rowValsDepotElt.putRowValues("ID_CLIENT").putNulls("NOM", "ID_COMPTE_PCE");
final SQLRowValues rowValuesChq = rowValsDepotElt.putRowValues("ID_CHEQUE_A_ENCAISSER");
rowValuesChq.putNulls("SANS_VALEUR_ENCAISSEMENT").putRowValues("ID_MOUVEMENT").putNulls("ID_PIECE");
rowValuesChq.putNulls("ID_COMPTE_PCE_TIERS").putNulls("NUMERO");
List<SQLRowValues> cheques = SQLRowValuesListFetcher.create(rowValsDepotElt).fetch(new Where(rowValsDepotElt.getTable().getField("ID_DEPOT_CHEQUE"), "=", depot.getID()));
for (SQLRowValues sqlRowAccessor : cheques) {
final SQLRowAccessor clientRow = sqlRowAccessor.getForeign("ID_CLIENT");
// this.nom = this.nom + " " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
this.putValue("NOM", this.nom + " " + StringUtils.limitLength(clientRow.getString("NOM"), 20));
SQLRowAccessor chequeRow = sqlRowAccessor.getForeign("ID_CHEQUE_A_ENCAISSER");
pieceIDs.add(chequeRow.getForeign("ID_MOUVEMENT").getForeignID("ID_PIECE"));
// compte Clients
SQLRowAccessor rowCptTiers = chequeRow.getForeign("ID_COMPTE_PCE_TIERS");
int idCompteClient = rowCptTiers != null && !rowCptTiers.isUndefined() ? rowCptTiers.getID() : -1;
 
if (chequeRow.getBoolean("SANS_VALEUR_ENCAISSEMENT")) {
if (idCompteClient == -1) {
if (clientRow != null) {
idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
}
if (idCompteClient <= 1) {
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
if (idCompteClient <= 1) {
idCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients");
}
}
}
} else {
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_VALEUR_ENCAISSEMENT");
if (idCompteClient <= 1) {
idCompteClient = ComptePCESQLElement.getIdComptePceDefault("ValeurEncaissement");
}
}
 
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(sqlRowAccessor.getLong("MONTANT")));
SQLRow insertedRow = ajoutEcriture();
 
sqlRowAccessor.createEmptyUpdateRow().put("ID_ECRITURE", insertedRow.getID()).getGraph().store(StoreMode.COMMIT, false);
sqlRowAccessor.getForeign("ID_CHEQUE_A_ENCAISSER").createEmptyUpdateRow().put("ENCAISSE", Boolean.TRUE).getGraph().store(StoreMode.COMMIT, false);
}
// compte de reglement cheque, ...
fillCompteBanqueFromRow(depot, "VenteCheque", false);
this.putValue("NOM", this.nom);
this.putValue("DEBIT", new Long(this.montant));
this.putValue("CREDIT", new Long(0));
SQLRow insertedRow = ajoutEcriture();
 
depot.createEmptyUpdateRow().put("ID_MOUVEMENT", idMvt).put("ID_ECRITURE", insertedRow.getID()).getGraph().store(StoreMode.COMMIT, false);
 
pieceIDs.add(mouvementTable.getRow(idMvt).getForeignID("ID_PIECE"));
lettrageAuto(pieceIDs, this.date);
 
System.err.println("Ecritures générées pour le mouvement " + this.idMvt);
 
}
 
// private void setDateReglement(int idCheque, Date d) throws SQLException {
// if (idCheque > 1) {
// SQLRow chequeRow =
// Configuration.getInstance().getBase().getTable("CHEQUE_A_ENCAISSER").getRow(idCheque);
// final int sourceId = MouvementSQLElement.getSourceId(chequeRow.getInt("ID_MOUVEMENT"));
// SQLRow rowMvt = Configuration.getInstance().getBase().getTable("MOUVEMENT").getRow(sourceId);
//
// if (rowMvt.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
// SQLElement eltFacture =
// Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
// SQLRow saisieRow = eltFacture.getTable().getRow(rowMvt.getInt("IDSOURCE"));
// // On fixe la date du paiement
// SQLRowValues rowValsUpdateVF = saisieRow.createEmptyUpdateRow();
// rowValsUpdateVF.put("DATE_REGLEMENT", new Timestamp(d.getTime()));
// rowValsUpdateVF.update();
// }
// }
// }
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtTicketCaisse.java
79,7 → 79,7
GenerationMvtTicketCaisse.this.putValue("ID_MOUVEMENT", Integer.valueOf(GenerationMvtTicketCaisse.this.idMvt));
}
 
TotalCalculator calc = getValuesFromElement(rowTicket, rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"), BigDecimal.ZERO, null, null);
TotalCalculator calc = getValuesFromElement(rowTicket, rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"), BigDecimal.ZERO, null, BigDecimal.ZERO, null, null);
long ttcLongValue = calc.getTotalTTC().movePointRight(2).longValue();
 
// compte Vente Produits
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationEcritures.java
19,6 → 19,7
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.generationDoc.OOXMLCache;
import org.openconcerto.erp.generationEcritures.provider.AnalytiqueProvider;
import org.openconcerto.erp.generationEcritures.provider.AnalytiqueProviderManager;
import org.openconcerto.erp.preferences.DefaultNXProps;
26,11 → 27,13
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
40,6 → 43,7
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
92,6 → 96,9
return this.rowAnalytiqueSource;
}
 
private Date dDebEx = null;
private Date dCloture = null;
 
/**
* Ajout d'une écriture et maj des totaux du compte associé
*
106,7 → 113,8
// Report des valeurs pour accelerer les IListes
Number n = (Number) this.mEcritures.get("ID_JOURNAL");
if (n != null) {
SQLRow rowJrnl = journalTable.getRow(n.intValue());
final SQLBackgroundTableCacheItem cacheForTableJrnl = SQLBackgroundTableCache.getInstance().getCacheForTable(journalTable);
SQLRow rowJrnl = cacheForTableJrnl.getRowFromId(n.intValue());
if (rowJrnl == null) {
throw new IllegalArgumentException("Le journal qui a pour ID " + n + " a été archivé.");
}
116,7 → 124,11
 
Number n2 = (Number) this.mEcritures.get("ID_COMPTE_PCE");
if (n2 != null) {
SQLRow rowCpt = compteTable.getRow(n2.intValue());
final SQLBackgroundTableCacheItem cacheForTableCpt = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
SQLRow rowCpt = cacheForTableCpt.getRowFromId(n2.intValue());
if (rowCpt == null) {
rowCpt = compteTable.getRow(n2.intValue());
}
this.mEcritures.put("COMPTE_NUMERO", rowCpt.getString("NUMERO"));
this.mEcritures.put("COMPTE_NOM", rowCpt.getString("NOM"));
}
143,17 → 155,18
// TODO checker que les ecritures sont entrees à une date correcte
Date d = (Date) this.mEcritures.get("DATE");
 
if (this.dDebEx == null) {
SQLTable tableExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON");
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
SQLRow rowExercice = tableExercice.getRow(rowSociete.getInt("ID_EXERCICE_COMMON"));
Date dDebEx = (Date) rowExercice.getObject("DATE_DEB");
this.dDebEx = (Date) rowExercice.getObject("DATE_DEB");
this.dCloture = (Date) rowExercice.getObject("DATE_CLOTURE");
}
 
Date dCloture = (Date) rowExercice.getObject("DATE_CLOTURE");
 
if (dCloture != null) {
if (dCloture.after(d)) {
final String error = "Impossible de générer l'écriture pour la date " + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(d)
+ ". Cette date est postérieure à la date de clôture (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dCloture) + ")";
+ ". Cette date est antérieure à la date de clôture (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dCloture) + ")";
throw new IllegalArgumentException(error);
}
} else {
168,17 → 181,14
valEcriture.put("IDUSER_CREATE", UserManager.getInstance().getCurrentUser().getId());
 
try {
if (valEcriture.getInvalid() == null) {
// ajout de l'ecriture
SQLRow ecritureRow = valEcriture.insert();
// SQLRow ecritureRow = valEcriture.insert();
SQLRow ecritureRow = valEcriture.getGraph().store(StoreMode.INSERT, false).getStoredRow(valEcriture);
 
// TODO Analytique
addAssocAnalytiqueFromProvider(ecritureRow, this.rowAnalytiqueSource);
return ecritureRow;
} else {
System.err.println("GenerationEcritures.java :: Error in values for insert in table " + GenerationEcritures.ecritureTable.getName() + " : " + valEcriture.toString());
throw new IllegalArgumentException("Erreur lors de la génération des écritures données incorrectes. " + valEcriture);
}
 
} catch (SQLException e) {
System.err.println("Error insert row in " + GenerationEcritures.ecritureTable.getName() + " : " + e);
final SQLException eFinal = e;
368,27 → 378,41
return getNewMouvement(source, idSource, idPere, rowValsPiece);
}
 
protected TotalCalculator getValuesFromElement(SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, SQLTable tableEchantillon) {
return getValuesFromElement(false, false, "T_PV_HT", row, foreign, portHT, rowTVAPort, tableEchantillon, null);
protected TotalCalculator getValuesFromElement(SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, BigDecimal fraisDocHT, SQLRow rowTVAFraisDoc, SQLTable tableEchantillon) {
return getValuesFromElement(false, false, "T_PV_HT", row, foreign, portHT, rowTVAPort, fraisDocHT, rowTVAFraisDoc, tableEchantillon, null);
}
 
protected TotalCalculator getValuesFromElement(boolean intra, boolean achat, String fieldTotalHT, SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, SQLTable tableEchantillon,
SQLRow defaultCompte) {
protected TotalCalculator getValuesFromElement(boolean intra, boolean achat, String fieldTotalHT, SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, BigDecimal fraisDocHT,
SQLRow rowTVAFraisDoc, SQLTable tableEchantillon, SQLRow defaultCompte) {
 
TotalCalculator calc = new TotalCalculator("T_PA_HT", fieldTotalHT, null, achat, defaultCompte);
final SQLRow tiers;
if (achat) {
tiers = row.getForeign("ID_FOURNISSEUR");
} else {
tiers = row.getForeign("ID_CLIENT");
}
 
SQLRowAccessor rowCatCompta = null;
if (tiers.getObject("ID_CATEGORIE_COMPTABLE") != null && !tiers.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
rowCatCompta = tiers.getForeign("ID_CATEGORIE_COMPTABLE");
}
TotalCalculator calc = new TotalCalculator("T_PA_HT", fieldTotalHT, null, achat, defaultCompte, rowCatCompta);
calc.setIntraComm(intra);
 
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean bServiceActive = Boolean.valueOf(val);
 
calc.setServiceActive(bServiceActive != null && bServiceActive);
 
SQLBackgroundTableCacheItem cacheCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
if (row.getTable().contains("ID_COMPTE_PCE_SERVICE") && !row.isForeignEmpty("ID_COMPTE_PCE_SERVICE")) {
SQLRowAccessor serviceCompte = row.getForeign("ID_COMPTE_PCE_SERVICE");
if (!serviceCompte.isUndefined()) {
SQLRowAccessor serviceCompte = cacheCompte.getRowFromId(row.getForeignID("ID_COMPTE_PCE_SERVICE"));
if (serviceCompte != null && !serviceCompte.isUndefined()) {
calc.setRowDefaultCptService(serviceCompte);
}
}
if (row.getTable().contains("ID_COMPTE_PCE_VENTE") && !row.isForeignEmpty("ID_COMPTE_PCE_VENTE")) {
SQLRowAccessor produitCompte = row.getForeign("ID_COMPTE_PCE_VENTE");
SQLRowAccessor produitCompte = cacheCompte.getRowFromId(row.getForeignID("ID_COMPTE_PCE_VENTE"));
if (!produitCompte.isUndefined()) {
calc.setRowDefaultCptProduit(produitCompte);
}
395,11 → 419,14
}
long remise = 0;
BigDecimal totalAvtRemise = BigDecimal.ZERO;
OOXMLCache cacheRefRows = new OOXMLCache();
final List<? extends SQLRowAccessor> referentRows = cacheRefRows.getReferentRows(Arrays.asList(row), foreign);
if (row.getTable().contains("REMISE_HT")) {
remise = row.getLong("REMISE_HT");
if (remise != 0) {
List<SQLRow> rows = row.getReferentRows(foreign);
for (SQLRow sqlRow : rows) {
 
// List<SQLRow> rows = row.getReferentRows(foreign);
for (SQLRowAccessor sqlRow : referentRows) {
calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), 1, false);
}
 
429,10 → 456,10
}
calc.setRemise(valRemiseHTReel, totalAvtRemise);
 
List<SQLRow> rows = row.getReferentRows(foreign);
for (int i = 0; i < rows.size(); i++) {
SQLRow sqlRow = rows.get(i);
calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), i, i == rows.size() - 1);
// List<SQLRow> rows = row.getReferentRows(foreign);
for (int i = 0; i < referentRows.size(); i++) {
SQLRowAccessor sqlRow = referentRows.get(i);
calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), i, i == referentRows.size() - 1);
}
 
if (tableEchantillon != null) {
448,10 → 475,10
rowValsPort.put("ID_TAXE", rowTVAPort.getIDNumber());
 
final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
SQLRow rowDefaultCptPort;
if (rowTVAPort.getFloat("TAUX") > 0) {
rowDefaultCptPort = rowPrefsCompte.getForeign("ID_COMPTE_PCE_PORT_SOUMIS");
rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS"));
if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
try {
rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteSoumisTVA");
460,7 → 487,7
}
}
} else {
rowDefaultCptPort = rowPrefsCompte.getForeign("ID_COMPTE_PCE_PORT_NON_SOUMIS");
rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS"));
if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
try {
rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteNonSoumisTVA");
472,8 → 499,21
final SQLRowValues rowValsArt = rowValsPort.putRowValues("ID_ARTICLE");
rowValsArt.put(achat ? "ID_COMPTE_PCE_ACHAT" : "ID_COMPTE_PCE", rowDefaultCptPort.getID());
rowValsArt.put("ID_TAXE_COMPLEMENTAIRE", null);
rowValsArt.put("ID_FAMILLE_ARTICLE", null);
calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
}
 
if (rowTVAFraisDoc != null && !rowTVAFraisDoc.isUndefined()) {
// Frais documents
SQLRowValues rowValsFraisDoc = new SQLRowValues(foreign);
rowValsFraisDoc.put(achat ? "T_PA_HT" : "T_PV_HT", fraisDocHT);
rowValsFraisDoc.put("QTE", 1);
rowValsFraisDoc.put("ID_TAXE", rowTVAFraisDoc.getIDNumber());
rowValsFraisDoc.put("SERVICE", Boolean.TRUE);
rowValsFraisDoc.put("ID_FAMILLE_ARTICLE", null);
calc.addLine(rowValsFraisDoc, null, 1, false);
}
 
calc.checkResult();
return calc;
}
646,4 → 686,5
}
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirClient.java
100,9 → 100,10
 
TotalCalculator calc;
if (rowClient.getTable().contains("ID_COMPTE_PCE_PRODUIT") && !rowClient.isForeignEmpty("ID_COMPTE_PCE_PRODUIT")) {
calc = getValuesFromElement(false, false, "T_PV_HT", avoirRow, avoirRow.getTable().getTable("AVOIR_CLIENT_ELEMENT"), portHT, null, null, rowClient.getForeign("ID_COMPTE_PCE_PRODUIT"));
calc = getValuesFromElement(false, false, "T_PV_HT", avoirRow, avoirRow.getTable().getTable("AVOIR_CLIENT_ELEMENT"), portHT, null, BigDecimal.ZERO, null, null,
rowClient.getForeign("ID_COMPTE_PCE_PRODUIT"));
} else {
calc = getValuesFromElement(avoirRow, avoirRow.getTable().getTable("AVOIR_CLIENT_ELEMENT"), portHT, null, null);
calc = getValuesFromElement(avoirRow, avoirRow.getTable().getTable("AVOIR_CLIENT_ELEMENT"), portHT, null, BigDecimal.ZERO, null, null);
}
Map<SQLRowAccessor, Map<SQLRowAccessor, BigDecimal>> taxeCompl = calc.getMapHtTaxeCompl();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementVenteNG.java
63,7 → 63,12
 
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse, boolean avance)
throws Exception {
this(label, rowClient, ttc, d, modeReglement, source, mvtSource, createEncaisse, avance, rowClient.getString("NOM"), null);
}
 
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse, boolean avance, String tiers,
SQLRowAccessor cptTiers) throws Exception {
 
SQLRow typeRegRow = modeReglement.getForeignRow("ID_TYPE_REGLEMENT");
setRowAnalytiqueSource(source);
// iniatilisation des valeurs de la map
107,7 → 112,8
if (createEncaisse) {
SQLRowValues rowVals = new SQLRowValues(tableEncaisse);
rowVals.put("MONTANT", ttc.getLongValue());
rowVals.put("ID_CLIENT", rowClient.getID());
rowVals.put("ID_CLIENT", rowClient != null ? rowClient.getID() : null);
rowVals.put("TIERS", tiers);
rowVals.put("DATE", this.date);
if (typeRegRow.getID() >= TypeReglementSQLElement.TRAITE) {
Calendar c2 = modeReglement.getDate("DATE_VIREMENT");
154,9 → 160,9
 
Calendar c = modeReglement.getDate("DATE_DEPOT");
if (c != null) {
paiementCheque(c.getTime(), source, ttc, rowClient, modeReglement, mvtSource.getTable().getRow(idMvt), avance);
paiementCheque(c.getTime(), source, ttc, rowClient, modeReglement, mvtSource.getTable().getRow(idMvt), avance, tiers, cptTiers);
} else {
paiementCheque(this.date, source, ttc, rowClient, modeReglement, mvtSource.getTable().getRow(idMvt), avance);
paiementCheque(this.date, source, ttc, rowClient, modeReglement, mvtSource.getTable().getRow(idMvt), avance, tiers, cptTiers);
}
 
} else {
176,7 → 182,7
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES);
}
 
int idCompteClient = rowClient.getInt("ID_COMPTE_PCE");
int idCompteClient = cptTiers != null && !cptTiers.isUndefined() ? cptTiers.getID() : rowClient.getInt("ID_COMPTE_PCE");
if (avance) {
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_AVANCE_CLIENT");
if (idCompteClient <= 1) {
239,7 → 245,9
valEcheance.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
valEcheance.put("DATE", dateEch);
valEcheance.put("MONTANT", Long.valueOf(ttc.getLongValue()));
valEcheance.put("ID_CLIENT", rowClient.getID());
valEcheance.put("ID_CLIENT", rowClient == null ? null : rowClient.getID());
valEcheance.put("TIERS", tiers);
valEcheance.put("ID_COMPTE_PCE_TIERS", cptTiers == null || !cptTiers.isUndefined() ? null : cptTiers.getID());
if (source.getTable().equals(tableSaisieVenteFacture)) {
valEcheance.put("ID_SAISIE_VENTE_FACTURE", source.getID());
}
334,13 → 342,15
}
}
 
private void paiementCheque(Date dateEch, SQLRow source, PrixTTC ttc, SQLRow rowClient, SQLRow modeRegl, SQLRow mvtSource, boolean avance) throws Exception {
private void paiementCheque(Date dateEch, SQLRow source, PrixTTC ttc, SQLRow rowClient, SQLRow modeRegl, SQLRow mvtSource, boolean avance, String tiers, SQLRowAccessor cptTiers) throws Exception {
 
SQLRowValues valCheque = new SQLRowValues(base.getTable("CHEQUE_A_ENCAISSER"));
SQLPreferences prefs = SQLPreferences.getMemCached(valCheque.getTable().getDBRoot());
boolean createEcr = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CREATE_ECR_CHQ, true);
 
valCheque.put("ID_CLIENT", rowClient.getID());
valCheque.put("ID_CLIENT", rowClient == null ? null : rowClient.getID());
valCheque.put("ID_COMPTE_PCE_TIERS", cptTiers == null ? null : cptTiers.getID());
valCheque.put("TIERS", tiers);
valCheque.put("SANS_VALEUR_ENCAISSEMENT", !createEcr);
final String foreignBanqueFieldName = "ID_" + BanqueSQLElement.TABLENAME;
if (valCheque.getTable().contains(foreignBanqueFieldName))
364,7 → 374,7
}
 
if (createEcr) {
int idCompteClient = rowClient.getInt("ID_COMPTE_PCE");
int idCompteClient = cptTiers == null || cptTiers.isUndefined() ? rowClient.getInt("ID_COMPTE_PCE") : cptTiers.getID();
if (avance) {
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_AVANCE_CLIENT");
if (idCompteClient <= 1) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirFournisseur.java
15,9 → 15,11
 
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
 
91,6 → 93,7
SQLRow rowEcr = ajoutEcriture();
// addAssocAnalytiqueFromProvider(rowEcr, avoirRow);
 
SQLRowAccessor taxe = TaxeCache.getCache().getRowFromId(avoirRow.getForeignID("ID_TAXE"));
if (prixTVA.getLongValue() > 0) {
// compte TVA
int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_ACHAT");
100,11 → 103,21
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVAImmo");
}
} else {
if (rowFourn.getBoolean("UE")) {
idCompteTVA = taxe.getForeignID("ID_COMPTE_PCE_DED_INTRA");
if (idCompteTVA <= 1) {
idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_INTRA");
if (idCompteTVA <= 1) {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVAIntraComm");
}
}
} else {
idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_ACHAT");
if (idCompteTVA <= 1) {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVADeductible");
}
}
}
 
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.putValue("DEBIT", Long.valueOf(0));
112,10 → 125,13
ajoutEcriture();
 
if (rowFourn.getBoolean("UE")) {
int idCompteTVAIntra = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_INTRA");
int idCompteTVAIntra = taxe.getForeignID("ID_COMPTE_PCE_COLLECTE_INTRA");
if (idCompteTVAIntra <= 1) {
idCompteTVAIntra = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_INTRA");
if (idCompteTVAIntra <= 1) {
idCompteTVAIntra = ComptePCESQLElement.getIdComptePceDefault("TVAIntraComm");
}
}
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTVAIntra));
this.putValue("DEBIT", Long.valueOf(prixTVA.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentSQLElement.java
13,13 → 13,13
package org.openconcerto.erp.core.edm;
 
import java.util.ArrayList;
import java.util.List;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
 
import java.util.ArrayList;
import java.util.List;
 
public class AttachmentSQLElement extends ComptaSQLConfElement {
 
public static final String DIRECTORY_PREFS = "EDMdirectory";
64,6 → 64,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".attachment";
return "edm.attachment";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/Attachment.java
15,6 → 15,7
 
import org.openconcerto.sql.model.SQLRowValues;
 
import java.io.File;
import java.io.Serializable;
 
public class Attachment implements Serializable {
37,7 → 38,7
this.mimeType = rowAttachment.getString("MIMETYPE");
this.fileName = rowAttachment.getString("FILENAME");
this.fileSize = rowAttachment.getInt("FILESIZE");
this.storagePath = rowAttachment.getString("STORAGE_PATH");
this.storagePath = rowAttachment.getString("STORAGE_PATH").replace('\\', File.separatorChar);
this.storageFileName = rowAttachment.getString("STORAGE_FILENAME");
this.sourceTable = rowAttachment.getString("SOURCE_TABLE");
this.sourceId = rowAttachment.getInt("SOURCE_ID");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentUtils.java
13,18 → 13,6
package org.openconcerto.erp.core.edm;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
 
import javax.swing.JOptionPane;
 
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.storage.StorageEngine;
37,6 → 25,16
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.sync.SyncClient;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.List;
 
import javax.swing.JOptionPane;
 
public class AttachmentUtils {
 
public void uploadFile(File inFile, SQLRowAccessor rowSource, int idParent) {
51,7 → 49,7
int id = rowAttachment.getID();
 
final String folderId = String.valueOf((id / 1000) * 1000);
String subDir = "EDM" + File.separator + folderId;
String subDir = "EDM/" + folderId;
String fileNameID = String.valueOf(id);
String ext = "";
 
68,7 → 66,6
if (isOnCloud) {
 
String remotePath = subDir;
remotePath = remotePath.replace('\\', '/');
List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
for (StorageEngine storageEngine : engines) {
if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
124,13 → 121,8
rowValsAttachment.put("NAME", name);
rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
rowValsAttachment.put("SOURCE_ID", rowSource.getID());
Collection<MimeType> mimeTypes = MimeUtil.getMimeTypes(inFile);
if (mimeTypes != null && !mimeTypes.isEmpty()) {
final MimeType mimeType = (MimeType) mimeTypes.toArray()[0];
rowValsAttachment.put("MIMETYPE", mimeType.getMediaType() + "/" + mimeType.getSubType());
} else {
rowValsAttachment.put("MIMETYPE", "application/octet-stream");
}
final String mimeType = Files.probeContentType(inFile.toPath());
rowValsAttachment.put("MIMETYPE", mimeType != null ? mimeType : "application/octet-stream");
rowValsAttachment.put("FILENAME", fileName);
rowValsAttachment.put("FILESIZE", inFile.length());
rowValsAttachment.put("STORAGE_PATH", subDir);
189,7 → 181,9
// Get file out
File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
File storagePathFile = new File(dirRoot, subDir);
File fileIn = new File(storagePathFile, fileName);
File fileIn;
try {
fileIn = new File(storagePathFile, fileName).getCanonicalFile();
if (fileIn.exists()) {
final File outFile = new File(f, fileName);
try {
199,9 → 193,14
return null;
}
} else {
JOptionPane.showMessageDialog(null, "Le fichier n'existe pas sur le serveur!", "Erreur fichier", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "Le fichier n'existe pas sur le serveur!\n" + fileIn.getAbsolutePath(), "Erreur fichier", JOptionPane.ERROR_MESSAGE);
return null;
}
} catch (IOException e1) {
ExceptionHandler.handle("Impossible de trouver le fichier\n" + storagePathFile + File.pathSeparator + fileName, e1);
return null;
}
}
final File outFile = new File(f, fileName);
outFile.setReadOnly();
return outFile;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/tasks/planning/element/TacheSQLElement.java
13,7 → 13,7
package org.openconcerto.erp.core.tasks.planning.element;
 
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
 
22,7 → 22,7
 
import javax.swing.JTextField;
 
public class TacheSQLElement extends ConfSQLElement {
public class TacheSQLElement extends ComptaSQLConfElement {
 
public TacheSQLElement() {
super("TACHE_COMMON", "une tache", "taches");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientElementSQLElement.java
15,9 → 15,12
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.DeviseField;
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.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.UISQLComponent;
24,17 → 27,27
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
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 org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ListMap;
 
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
54,23 → 67,12
@Override
public void actionPerformed(ActionEvent e) {
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
final List<SQLRowAccessor> arts = new ArrayList<SQLRowAccessor>();
final Set<Integer> s = new HashSet<Integer>();
for (SQLRowValues sqlRowValues : selectedRows) {
if (sqlRowValues.getObject("ID_ARTICLE") != null && !sqlRowValues.isForeignEmpty("ID_ARTICLE")) {
SQLRowAccessor rowArt = sqlRowValues.getForeign("ID_ARTICLE");
if (!s.contains(rowArt.getID())) {
s.add(rowArt.getID());
arts.add(rowArt);
}
}
}
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
 
createCommandeF(arts);
createCommandeF(selectedRows);
}
});
}
78,9 → 80,130
}, true);
rowAction.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(rowAction);
 
PredicateRowAction rowActionCmd = new PredicateRowAction(new AbstractAction("Modifier la commande associée") {
 
@Override
public void actionPerformed(ActionEvent e) {
SQLRowValues selectedRow = IListe.get(e).getSelectedRow();
EditFrame f = new EditFrame(getForeignElement("ID_COMMANDE_CLIENT"), EditMode.MODIFICATION);
f.getSQLComponent().select(selectedRow.getForeignID("ID_COMMANDE_CLIENT"));
FrameUtil.showPacked(f);
}
 
}, true);
rowActionCmd.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(rowActionCmd);
 
if (getTable().getForeignTable("ID_USER_COMMON_CREATE").getRow(UserManager.getUserID()).getBoolean("ADMIN")) {
PredicateRowAction rowActionForceLivr = new PredicateRowAction(new AbstractAction("Forcer la livraison") {
 
@Override
public void actionPerformed(ActionEvent e) {
updateForceLivrer(e, Boolean.TRUE);
 
}
 
}, true);
rowActionForceLivr.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(rowActionForceLivr);
 
PredicateRowAction rowActionAnnuler = new PredicateRowAction(new AbstractAction("Annuler Forcer la livraison") {
 
@Override
public void actionPerformed(ActionEvent e) {
updateForceLivrer(e, Boolean.FALSE);
 
}
 
}, true);
rowActionAnnuler.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(rowActionAnnuler);
 
PredicateRowAction rowActionUpdateStockTh = new PredicateRowAction(new AbstractAction("Recalculer le stock théorique") {
 
@Override
public void actionPerformed(ActionEvent e) {
recalculStockTh();
 
}
 
}, true);
rowActionUpdateStockTh.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
getRowActions().add(rowActionUpdateStockTh);
 
}
 
}
 
private void updateForceLivrer(ActionEvent e, Boolean state) {
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
final Set<Integer> ids = new HashSet<Integer>();
for (SQLRowValues sqlRowValues : selectedRows) {
ids.add(sqlRowValues.getID());
}
UpdateBuilder build = new UpdateBuilder(getTable());
build.setObject("LIVRE_FORCED", state);
build.setWhere(new Where(getTable().getKey(), ids));
getTable().getDBSystemRoot().getDataSource().execute(build.asString());
IListe.get(e).getModel().updateAll();
}
 
public void recalculStockTh() {
 
// RAZ des stocks TH --> TH = REEL
final SQLTable tableStock = getTable().getDBRoot().findTable("STOCK");
String req = "UPDATE " + tableStock.getSQLName().quote() + " SET " + tableStock.getField("QTE_TH").getQuotedName() + " = " + tableStock.getField("QTE_REEL").getQuotedName() + ","
+ tableStock.getField("QTE_RECEPT_ATTENTE").getQuotedName() + " = 0," + tableStock.getField("QTE_LIV_ATTENTE").getQuotedName() + "=0";
tableStock.getDBSystemRoot().getDataSource().execute(req);
 
{
SQLSelect selCmdElt = new SQLSelect();
final SQLTable tableCmdElt = tableStock.getTable("COMMANDE_ELEMENT");
selCmdElt.addSelectStar(tableCmdElt);
Where w = new Where(tableCmdElt.getField("RECU_FORCED"), "=", Boolean.FALSE).and(new Where(tableCmdElt.getField("RECU"), "=", Boolean.FALSE));
selCmdElt.setWhere(w);
List<SQLRow> res = SQLRowListRSH.execute(selCmdElt);
if (res != null && res.size() > 0) {
StockItemsUpdater updater = new StockItemsUpdater(new StockLabel() {
 
@Override
public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
return "Commande fournisseur N°" + rowElt.getForeign("ID_COMMANDE").getString("NUMERO");
}
}, res.get(0), res, TypeStockUpdate.VIRTUAL_RECEPT, false);
try {
updater.update();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
{
SQLSelect selCmdElt = new SQLSelect();
final SQLTable tableCmdElt = tableStock.getTable("COMMANDE_CLIENT_ELEMENT");
selCmdElt.addSelectStar(tableCmdElt);
Where w = new Where(tableCmdElt.getField("LIVRE_FORCED"), "=", Boolean.FALSE).and(new Where(tableCmdElt.getField("LIVRE"), "=", Boolean.FALSE));
selCmdElt.setWhere(w);
List<SQLRow> res = SQLRowListRSH.execute(selCmdElt);
if (res != null && res.size() > 0) {
StockItemsUpdater updater = new StockItemsUpdater(new StockLabel() {
 
@Override
public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
return "Commande N°" + rowElt.getForeign("ID_COMMANDE_CLIENT").getString("NUMERO");
}
}, res.get(0), res, TypeStockUpdate.VIRTUAL_DELIVER, false);
try {
updater.update();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
 
@Override
protected String getParentFFName() {
return "ID_COMMANDE_CLIENT";
}
99,6 → 222,8
l.add("QTE");
l.add("QTE_UNITAIRE");
l.add("QTE_LIVREE");
l.add("LIVRE");
l.add("LIVRE_FORCED");
return l;
}
 
115,7 → 240,7
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
List<String> fields2copy = Arrays.asList("CODE", "NOM", "VALEUR_METRIQUE_1", "VALEUR_METRIQUE_2", "VALEUR_METRIQUE_3");
 
Set<Integer> art = new HashSet<Integer>();
// Set<Integer> art = new HashSet<Integer>();
for (SQLRowValues sqlRow : commandeClientEltsRows) {
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
149,7 → 274,7
MouvementStockSQLElement.createCommandeF(map, null, "", false);
}
 
public void createCommandeF(final List<? extends SQLRowAccessor> rowsArt) {
public void createCommandeF(final List<? extends SQLRowAccessor> rowsItems) {
 
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
156,11 → 281,18
@Override
public void run() {
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
final Set<Integer> stockChecked = new HashSet<Integer>();
for (SQLRowAccessor rowItem : rowsItems) {
if (rowItem.getObject("ID_ARTICLE") != null && !rowItem.isForeignEmpty("ID_ARTICLE")) {
SQLRowAccessor rowArticleFind = rowItem.getForeign("ID_ARTICLE");
 
for (SQLRowAccessor rowArticleFind : rowsArt) {
SQLRow row = rowArticleFind.asRow();
SQLRowAccessor rowStock = StockSQLElement.getStock(rowItem);
if (!stockChecked.contains(rowStock.getID())) {
stockChecked.add(rowStock.getID());
 
SQLRow row = rowArticleFind.asRow();
final int value = -Math.round(row.getForeign("ID_STOCK").getFloat("QTE_TH") - row.getFloat("QTE_MIN"));
int value = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
 
if (value > 0) {
 
SQLInjector inj = SQLInjector.getInjector(row.getTable(), row.getTable().getTable("COMMANDE_ELEMENT"));
176,6 → 308,8
map.add(rowArticleFind.getForeign("ID_FOURNISSEUR").asRow(), rowValsElt);
}
}
}
}
MouvementStockSQLElement.createCommandeF(map, null, "", false);
}
});
193,9 → 327,16
}
 
@Override
protected void _initListRequest(ListSQLRequest req) {
super._initListRequest(req);
req.addToGraphToFetch("ID_DEPOT_STOCK");
}
 
@Override
public ListMap<String, String> getShowAs() {
final ListMap<String, String> res = new ListMap<String, String>();
res.putCollection("ID_COMMANDE_CLIENT", "NUMERO", "ID_CLIENT", "DATE", "DATE_LIVRAISON_PREV");
res.putCollection("ID_COMMANDE_CLIENT", "NUMERO", "DATE", "DATE_LIVRAISON_PREV", "ID_CLIENT");
 
if (getTable().contains("ID_ARTICLE")) {
res.putCollection("ID_ARTICLE", "ID_FAMILLE_ARTICLE", "ID_FOURNISSEUR");
}
216,8 → 357,8
 
this.addSQLObject(new ElementComboBox(), "ID_STYLE", "left");
 
this.addRequiredSQLObject(new DeviseField(), "PA_HT", "left");
this.addSQLObject(new DeviseField(), "PV_HT", "right");
this.addRequiredSQLObject(new JTextField(), "PA_HT", "left");
this.addSQLObject(new JTextField(), "PV_HT", "right");
 
this.addSQLObject(new JTextField(), "POIDS", "left");
this.addSQLObject(new ElementComboBox(), "ID_TAXE", "right");
227,6 → 368,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/ChiffrageCommandeClientSQLElement.java
108,7 → 108,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".chiffrage";
return createCodeOfPackage() + ".chiffrage";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientSQLElement.java
25,6 → 25,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.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
323,11 → 324,16
final SQLTable tableCmdElt = tableCmd.getTable("COMMANDE_CLIENT_ELEMENT");
SQLRowValues rowValsElt = new SQLRowValues(tableCmdElt);
rowValsElt.put("QTE", null);
rowValsElt.put("ID_DEPOT_STOCK", null);
rowValsElt.put("QTE_UNITAIRE", null);
rowValsElt.put("ID_COMMANDE_CLIENT", rowVals);
 
SQLRowValues rowValsArt = new SQLRowValues(tableCmd.getTable("ARTICLE"));
rowValsArt.putRowValues("ID_STOCK").putNulls("QTE_REEL", "QTE_TH");
SQLRowValues rowValsStock = new SQLRowValues(tableCmd.getTable("STOCK"));
rowValsStock.putNulls("QTE_REEL", "QTE_TH");
rowValsStock.put("ID_DEPOT_STOCK", null);
rowValsStock.put("ID_ARTICLE", rowValsArt);
rowValsArt.put("ID_DEPOT_STOCK", null);
rowValsElt.put("ID_ARTICLE", rowValsArt);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
361,6 → 367,8
// Stock utilisé par la commande actuelle
StockCommande stockCmd = new StockCommande();
for (SQLRowValues item : sqlRowValues.getReferentRows(tableCmdElt)) {
 
if (item.getObject("ID_ARTICLE") != null && !item.isForeignEmpty("ID_ARTICLE")) {
final int foreignID = item.getForeignID("ID_ARTICLE");
 
// Stock = stock actuel dans la base - stock utilisé par les commandes
367,8 → 375,9
// déja testées -
// stock utilisé par la commande en cours (si 2 fois le meme article)
BigDecimal stock = BigDecimal.ZERO;
if (!item.getForeign("ID_ARTICLE").isForeignEmpty("ID_STOCK")) {
stock = new BigDecimal(item.getForeign("ID_ARTICLE").getForeign("ID_STOCK").getFloat("QTE_REEL"));
SQLRowAccessor rowStock = StockSQLElement.getStockFetched(item);
if (rowStock != null) {
stock = new BigDecimal(rowStock.getFloat("QTE_REEL"));
}
stock = stock.subtract(stockCmd.getQty(foreignID)).subtract(stockGlobalUsed.getQty(foreignID));
 
382,6 → 391,7
break;
}
}
}
 
if (inStock) {
Map<Integer, BigDecimal> m = stockCmd.getMap();
467,6 → 477,9
l.add("ID_COMMERCIAL");
l.add("T_HT");
l.add("T_TTC");
if (getTable().getFieldsName().contains("ACOMPTE_COMMANDE")) {
l.add("ACOMPTE_COMMANDE");
}
l.add("NOM");
l.add("INFOS");
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
591,7 → 604,12
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC",
((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)), DecimalUtils.HIGH_PRECISION));
final SQLRow foreignRow = rowArticleFind.getForeignRow("ID_FOURNISSEUR");
if (foreignRow != null && !foreignRow.isUndefined()) {
rowValsElt.put("ID_DEVISE", foreignRow.getForeignID("ID_DEVISE"));
} else {
rowValsElt.put("ID_DEVISE", rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
}
map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
}
 
612,6 → 630,8
rowVals.put("QTE", null);
rowVals.put("QTE_LIVREE", null);
rowVals.put("ID_ARTICLE", null);
rowVals.put("PV_HT", null);
rowVals.put("ID_COMMANDE_CLIENT_ELEMENT", null);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
629,7 → 649,7
return input;
}
});
comp.loadQuantity(fetcher.fetch());
comp.loadQuantity(fetcher.fetch(), "COMMANDE_CLIENT_ELEMENT");
 
}
 
678,4 → 698,10
return BigDecimal.ONE.movePointRight(2);
}
}
 
@Override
protected String createCode() {
return "sales.order";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/FacturationCommandeClientSQLElement.java
54,7 → 54,7
public static final String TABLENAME = "FACTURATION_COMMANDE_CLIENT";
 
public FacturationCommandeClientSQLElement() {
super(TABLENAME, "une terme de facturation de commande client", "termes de facturation commandes clients");
super(TABLENAME, "un terme de facturation de commande client", "termes de facturation commandes clients");
{
RowAction action = new RowAction(new AbstractAction("Facturer") {
 
276,7 → 276,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".facturation";
return createCodeOfPackage() + ".facturation";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/TransferCustomerOrderSQLElement.java
45,6 → 45,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transfer";
return createCodeOfPackage() + ".transfer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesElementsACommanderClientAction.java
13,11 → 13,13
package org.openconcerto.erp.core.sales.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.sales.order.element.CommandeClientElementSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.FieldRef;
28,16 → 30,17
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.state.WindowStateManager;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.cc.ITransformer;
45,7 → 48,6
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
53,36 → 55,23
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class ListeDesElementsACommanderClientAction extends CreateFrameAbstractAction {
final CommandeClientElementSQLElement eltCmd = (CommandeClientElementSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
public class ListeDesElementsACommanderClientAction extends CreateIListFrameAbstractAction<CommandeClientElementSQLElement> {
 
public ListeDesElementsACommanderClientAction() {
super();
this.putValue(Action.NAME, "Liste des éléments en attente de livraison");
public ListeDesElementsACommanderClientAction(final ComptaPropsConfiguration conf) {
super(conf, CommandeClientElementSQLElement.class);
}
 
private BaseSQLTableModelColumn colAvancement;
 
public JFrame createFrame() {
final JFrame frame = new JFrame("Eléments en attente de livraison");
// Actions
 
final JPanel orderPanel = createPanel();
 
frame.getContentPane().add(orderPanel);
FrameUtil.setBounds(frame);
final File file = IListFrame.getConfigFile(eltCmd, frame.getClass());
if (file != null)
new WindowStateManager(frame, file).loadState();
return frame;
@Override
protected String getPanelVariant() {
return this.getClass().getSimpleName();
}
 
JPanel createPanel() {
final SQLTableModelSourceOnline tableSource = eltCmd.getTableSource(true);
@Override
protected SQLTableModelSource createTableSource() {
final SQLTableModelSource tableSource = super.createTableSource();
final CommandeClientElementSQLElement eltCmd = getElem();
tableSource.getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
94,12 → 83,15
final String quoteQteU = new SQLName(input.getAlias(eltCmd.getTable()).getAlias(), "QTE_UNITAIRE").quote();
Where w = Where.createRaw(quoteQteL + " < (" + quoteQte + "*" + quoteQteU + ")", eltCmd.getTable().getField("QTE_LIVREE"), eltCmd.getTable().getField("QTE"),
eltCmd.getTable().getField("QTE_UNITAIRE"));
w = w.and(new Where(eltCmd.getTable().getField("LIVRE_FORCED"), "=", Boolean.FALSE));
input.setWhere(w);
return input;
}
});
 
BaseSQLTableModelColumn colStockR = new BaseSQLTableModelColumn("Stock Reel", Float.class) {
SQLPreferences prefs = SQLPreferences.getMemCached(eltCmd.getTable().getDBRoot());
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
BaseSQLTableModelColumn colStockD = new BaseSQLTableModelColumn("Dépôt", String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
106,12 → 98,12
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
final SQLRowAccessor foreign2 = foreign.getForeign("ID_STOCK");
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_REEL");
return foreign2.getForeign("ID_DEPOT_STOCK").getString("NOM");
}
}
return 0F;
return "";
}
 
@Override
118,22 → 110,24
public Set<FieldPath> getPaths() {
Path p = new Path(eltCmd.getTable());
p = p.add(p.getLast().getField("ID_ARTICLE"));
p = p.add(p.getLast().getField("ID_STOCK"));
return CollectionUtils.createSet(new FieldPath(p, "QTE_REEL"));
Path p2 = p.add(p.getLast().getTable("STOCK").getField("ID_ARTICLE"));
Path p3 = p2.add(p2.getLast().getField("ID_DEPOT_STOCK"));
Path p4 = p.add(p.getLast().getField("ID_DEPOT_STOCK"));
return CollectionUtils.createSet(new FieldPath(p3, "NOM"), new FieldPath(p4, "NOM"));
}
};
tableSource.getColumns().add(colStockR);
tableSource.getColumns().add(colStockD);
}
BaseSQLTableModelColumn colStockR = new BaseSQLTableModelColumn("Stock Reel", Float.class) {
 
BaseSQLTableModelColumn colLiv2 = new BaseSQLTableModelColumn("Stock TH", Float.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
final SQLRowAccessor foreign2 = foreign.getForeign("ID_STOCK");
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_TH");
return foreign2.getFloat("QTE_REEL");
}
}
return 0F;
143,133 → 137,95
public Set<FieldPath> getPaths() {
Path p = new Path(eltCmd.getTable());
p = p.add(p.getLast().getField("ID_ARTICLE"));
p = p.add(p.getLast().getField("ID_STOCK"));
return CollectionUtils.createSet(new FieldPath(p, "QTE_TH"));
Path p2 = p.add(p.getLast().getTable("STOCK").getField("ID_ARTICLE"));
return CollectionUtils.createSet(new FieldPath(p, "ID_DEPOT_STOCK"), new FieldPath(p2, "QTE_REEL"), new FieldPath(p2, "ID_DEPOT_STOCK"));
}
};
tableSource.getColumns().add(colLiv2);
tableSource.getColumns().add(colStockR);
 
BaseSQLTableModelColumn colStockMin = new BaseSQLTableModelColumn("Stock Min", Integer.class) {
BaseSQLTableModelColumn colLiv2 = new BaseSQLTableModelColumn("Stock TH", Float.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
return foreign.getInt("QTE_MIN");
if (foreign != null && !foreign.isUndefined()) {
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_TH");
}
}
return 0F;
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(eltCmd.getTable());
p = p.add(p.getLast().getField("ID_ARTICLE"));
 
return CollectionUtils.createSet(new FieldPath(p, "QTE_MIN"));
Path p2 = p.add(p.getLast().getTable("STOCK").getField("ID_ARTICLE"));
return CollectionUtils.createSet(new FieldPath(p, "ID_DEPOT_STOCK"), new FieldPath(p2, "QTE_TH"), new FieldPath(p2, "ID_DEPOT_STOCK"));
}
};
tableSource.getColumns().add(colStockMin);
tableSource.getColumns().add(colLiv2);
 
BaseSQLTableModelColumn colSug = new BaseSQLTableModelColumn("Qtè à commander", Float.class) {
BaseSQLTableModelColumn colStockMin = new BaseSQLTableModelColumn("Stock Min", Float.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
// final float qteCommande = r.getBigDecimal("QTE_UNITAIRE").multiply(new
// BigDecimal(r.getInt("QTE"))).subtract(r.getBigDecimal("QTE_LIVREE")).floatValue();
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
float qteMin = foreign.getFloat("QTE_MIN");
final SQLRowAccessor foreign2 = foreign.getForeign("ID_STOCK");
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
float manque = foreign2.getFloat("QTE_TH") - qteMin;
if (manque < 0) {
return -manque;
return foreign2.getFloat("QTE_MIN");
}
}
}
return 0F;
}
 
@Override
public Set<FieldPath> getPaths() {
Path pA = new Path(eltCmd.getTable());
 
pA = pA.add(pA.getLast().getField("ID_ARTICLE"));
Path p = pA.add(pA.getLast().getField("ID_STOCK"));
return CollectionUtils.createSet(new FieldPath(pA, "QTE_MIN"), new FieldPath(p, "QTE_TH"));
Path p = new Path(eltCmd.getTable());
p = p.add(p.getLast().getField("ID_ARTICLE"));
Path p2 = p.add(p.getLast().getTable("STOCK").getField("ID_ARTICLE"));
return CollectionUtils.createSet(new FieldPath(p, "ID_DEPOT_STOCK"), new FieldPath(p2, "QTE_MIN"), new FieldPath(p2, "ID_DEPOT_STOCK"));
}
};
tableSource.getColumns().add(colSug);
// colLiv2.setRenderer(new PercentTableCellRenderer());
tableSource.getColumns().add(colStockMin);
 
final ListeAddPanel panel = getPanel(eltCmd, tableSource);
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Calcul des besoins") {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLElement artElt = eltCmd.getForeignElement("ID_ARTICLE");
final SQLTableModelSourceOnline createTableSource = artElt.createTableSource();
createTableSource.getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
FieldRef refStock = input.getAlias(artElt.getTable().getForeignTable("ID_STOCK").getField("QTE_TH"));
 
SQLSelectJoin j = input.getJoinFromField(artElt.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
Where w = new Where(refStock, "<", artElt.getTable().getField("QTE_MIN"));
w = w.and(new Where(j.getJoinedTable().getKey(), "=", (Object) null));
input.setWhere(w);
// input.setHaving(Where.createRaw("COUNT(\"" + j.getJoinedTable().getKey()
// + "\")" + " = 0", Arrays.asList(j.getJoinedTable().getKey())));
return input;
}
});
 
BaseSQLTableModelColumn colSug = new BaseSQLTableModelColumn("Qtè à commander", Float.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
float qteMin = r.getFloat("QTE_MIN");
final SQLRowAccessor foreign2 = r.getForeign("ID_STOCK");
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
float qteMin = foreign2.getFloat("QTE_MIN");
float manque = foreign2.getFloat("QTE_TH") - qteMin;
if (manque < 0) {
return -manque;
}
}
}
return 0F;
 
return 0F;
}
 
@Override
public Set<FieldPath> getPaths() {
Path pA = new Path(artElt.getTable());
 
Path p = pA.add(pA.getLast().getField("ID_STOCK"));
return CollectionUtils.createSet(new FieldPath(pA, "QTE_MIN"), new FieldPath(p, "QTE_TH"));
Path p = new Path(eltCmd.getTable());
p = p.add(p.getLast().getField("ID_ARTICLE"));
Path p2 = p.add(p.getLast().getTable("STOCK").getField("ID_ARTICLE"));
return CollectionUtils.createSet(new FieldPath(p, "ID_DEPOT_STOCK"), new FieldPath(p2, "QTE_TH"), new FieldPath(p2, "QTE_MIN"), new FieldPath(p2, "ID_DEPOT_STOCK"));
}
};
createTableSource.getColumns().add(colSug);
tableSource.getColumns().add(colSug);
// colLiv2.setRenderer(new PercentTableCellRenderer());
 
IListe listeArt = new IListe(createTableSource);
final PredicateRowAction predicateACtion = new PredicateRowAction(new AbstractAction("Passer une commande fournisseur") {
 
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
eltCmd.createCommandeF(selectedRows);
return tableSource;
}
}, true);
predicateACtion.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
listeArt.addIListeAction(predicateACtion);
ListeViewPanel p = new ListeViewPanel(artElt, listeArt);
IListFrame f = new IListFrame(p);
FrameUtil.show(f);
}
}, true);
action.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
panel.getListe().addIListeAction(action);
return panel;
}
 
private BigDecimal getAvancementLFromBL(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("COMMANDE_CLIENT_ELEMENT"));
291,9 → 247,10
}
}
 
private ListeAddPanel getPanel(final SQLElement eltCmd, final SQLTableModelSourceOnline tableSource) {
final ListeAddPanel panel = new ListeAddPanel(eltCmd, new IListe(tableSource));
 
@Override
protected IListPanel instantiateListPanel(SQLTableModelSource tableSource, String panelVariant) {
final IListPanel panel = super.instantiateListPanel(tableSource, panelVariant);
final CommandeClientElementSQLElement eltCmd = getElem();
// final List<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>> fields = new
// ArrayList<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>>(2);
// fields.add(Tuple2.create(panel.getListe().getSource().getColumn(eltCmd.getTable().getField("T_HT")),
329,6 → 286,48
// bottomPanel.add(totalPanel, c2);
 
panel.add(bottomPanel, c);
 
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Calcul des besoins") {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLElement artElt = eltCmd.getForeignElement("ID_ARTICLE");
final SQLTableModelSourceOnline createTableSource = artElt.createTableSource();
createTableSource.getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
FieldRef refStock = input.getAlias(artElt.getTable().getForeignTable("ID_STOCK").getField("QTE_TH"));
 
SQLSelectJoin j = input.getJoinFromField(artElt.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
Where w = new Where(refStock, "<", artElt.getTable().getField("QTE_MIN"));
w = w.and(new Where(j.getJoinedTable().getKey(), "=", (Object) null));
input.setWhere(w);
// input.setHaving(Where.createRaw("COUNT(\"" + j.getJoinedTable().getKey()
// + "\")" + " = 0", Arrays.asList(j.getJoinedTable().getKey())));
return input;
}
});
 
IListe listeArt = new IListe(createTableSource);
final PredicateRowAction predicateACtion = new PredicateRowAction(new AbstractAction("Passer une commande fournisseur") {
 
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
eltCmd.createCommandeF(selectedRows);
}
}, true);
predicateACtion.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
listeArt.addIListeAction(predicateACtion);
ListeViewPanel p = new ListeViewPanel(artElt, listeArt);
IListFrame f = new IListFrame(p);
FrameUtil.show(f);
}
 
}, true);
action.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
panel.getListe().addIListeAction(action);
 
return panel;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesCommandesClientAction.java
116,8 → 116,8
@Override
public Set<FieldPath> getPaths() {
final Path p = new PathBuilder(eltCmd.getTable()).addTable("COMMANDE_CLIENT_ELEMENT").build();
return CollectionUtils.createSet(new FieldPath(p, "QTE_LIVREE"), new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p, "LIVRE_FORCED"),
new FieldPath(p, "LIVRE"));
return CollectionUtils.createSet(new FieldPath(p, "ID_ARTICLE"), new FieldPath(p, "PV_HT"), new FieldPath(p, "QTE_LIVREE"), new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"),
new FieldPath(p, "LIVRE_FORCED"), new FieldPath(p, "LIVRE"));
}
};
tableSource.getColumns().add(colLiv2);
155,6 → 155,8
BigDecimal totalQteL = BigDecimal.ZERO;
for (SQLRowAccessor row : rows) {
BigDecimal qte = row.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(row.getInt("QTE")));
// On ne prend en compte que les articles ou les lignes différentes de 0
if (!row.isForeignEmpty("ID_ARTICLE") || row.getBigDecimal("PV_HT").signum() != 0) {
totalQte = totalQte.add(qte);
if (row.getBoolean("LIVRE_FORCED") || row.getBoolean("LIVRE")) {
totalQteL = totalQteL.add(qte);
165,6 → 167,7
}
}
}
}
if (totalQte.signum() != 0) {
return totalQteL.divide(totalQte, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesFacturationCommandesClientAction.java
13,10 → 13,10
package org.openconcerto.erp.core.sales.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.sales.order.element.FacturationCommandeClientSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.Where;
23,26 → 23,22
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
 
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
 
public class ListeDesFacturationCommandesClientAction extends CreateFrameAbstractAction {
public class ListeDesFacturationCommandesClientAction extends CreateListFrameAbstractAction<FacturationCommandeClientSQLElement, JFrame> {
 
public ListeDesFacturationCommandesClientAction() {
super();
this.putValue(Action.NAME, "Echéancier de commandes clients");
public ListeDesFacturationCommandesClientAction(final ComptaPropsConfiguration conf) {
super(conf, FacturationCommandeClientSQLElement.class);
}
 
public JFrame createFrame() {
final JFrame frame = new JFrame("Echéancier de commandes clients");
@Override
protected JFrame instantiateFrame() {
final JFrame frame = new JFrame(String.valueOf(getValue(NAME)));
final JTabbedPane pane = new JTabbedPane();
 
final String tableName = FacturationCommandeClientSQLElement.TABLENAME;
final SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement(tableName);
if (eltCmd == null) {
throw new IllegalStateException("No elements for table " + tableName);
}
final SQLElement eltCmd = getElem();
 
final SQLField fieldFacture = eltCmd.getTable().getField("ID_SAISIE_VENTE_FACTURE");
// Elements à facturer
final Where wToInvoice = new Where(fieldFacture, "=", 1).or(new Where(fieldFacture, "=", (Object) null));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesCommandesClientItemsAction.java
13,12 → 13,13
package org.openconcerto.erp.core.sales.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel.Type;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.erp.core.sales.order.element.CommandeClientElementSQLElement;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
25,38 → 26,48
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.Tuple2;
 
import java.awt.GridBagConstraints;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class ListeDesCommandesClientItemsAction extends CreateIListFrameAbstractAction<CommandeClientElementSQLElement> {
 
public class ListeDesCommandesClientItemsAction extends CreateFrameAbstractAction {
public ListeDesCommandesClientItemsAction(final ComptaPropsConfiguration conf) {
super(conf, CommandeClientElementSQLElement.class);
}
 
public ListeDesCommandesClientItemsAction() {
super();
this.putValue(Action.NAME, "Liste des articles commandés");
@Override
protected SQLTableModelSource createTableSource() {
final SQLTableModelSource res = super.createTableSource();
res.getReq().setWhere(new Where(getElem().getTable().getField("ID_COMMANDE_CLIENT"), ">", 1));
return res;
}
 
public JFrame createFrame() {
final SQLElement element = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
@Override
protected IListPanel instantiateListPanel(final SQLTableModelSource tableSource, String panelVariant) {
return new ListeViewPanel(tableSource.getElem(), new IListe(tableSource));
}
 
final SQLTableModelSourceOnline tableSource = element.getTableSource(true);
IListe liste = new IListe(tableSource);
final ListeViewPanel listeAddPanel = new ListeViewPanel(element, liste);
listeAddPanel.getListe().getRequest().setWhere(new Where(element.getTable().getField("ID_COMMANDE_CLIENT"), ">", 1));
@Override
protected void initFrame(IListFrame frame) {
super.initFrame(frame);
final SQLElement element = getElem();
 
final IListPanel listeAddPanel = frame.getPanel();
final SQLTableModelSource tableSource = listeAddPanel.getListe().getSource();
 
final Set<FieldPath> paths = FieldPath.create(new Path(getElem().getTable()), Arrays.asList("QTE", "QTE_UNITAIRE", "QTE_LIVREE"));
BaseSQLTableModelColumn colStockR = new BaseSQLTableModelColumn("Qté restante à livrer", BigDecimal.class) {
 
@Override
72,8 → 83,7
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(element.getTable());
return CollectionUtils.createSet(new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p, "QTE_LIVREE"));
return paths;
}
};
tableSource.getColumns().add(colStockR);
92,8 → 102,8
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
listeAddPanel.add(total, c);
IListFrame frame = new IListFrame(listeAddPanel);
frame.setTextTitle("Liste des articles commandés");
 
frame.setTextTitle(String.valueOf(getValue(NAME)));
frame.getPanel().getListe().setModificationAllowed(false);
frame.getPanel().setAddVisible(false);
frame.getPanel().setSearchFullMode(true);
103,7 → 113,5
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
frame.getPanel().add(datePanel, c);
 
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/NouvelleCommandeClientAction.java
13,22 → 13,14
package org.openconcerto.erp.core.sales.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.erp.action.CreateEditFrameAbstractAction;
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleCommandeClientAction extends CreateEditFrameAbstractAction<CommandeClientSQLElement> {
 
public class NouvelleCommandeClientAction extends CreateFrameAbstractAction {
 
public NouvelleCommandeClientAction() {
super();
this.putValue(Action.NAME, "Commande client");
public NouvelleCommandeClientAction(final PropsConfiguration conf) {
super(conf, CommandeClientSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/component/CommandeClientSQLComponent.java
61,6 → 61,7
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.Color;
import java.awt.GridBagConstraints;
330,6 → 331,12
 
final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
 
if (rowClient.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowClient.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
table.setRowCatComptable(rowClient.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
table.setRowCatComptable(null);
}
 
if (!rowClient.isForeignEmpty("ID_COMMERCIAL")) {
comboCommercial.setValue(rowClient.getForeignID("ID_COMMERCIAL"));
}
336,6 → 343,7
int idClient = rowClient.getID();
comboContact.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_CLIENT"), "=", idClient));
} else {
table.setRowCatComptable(null);
comboContact.getRequest().setWhere(Where.FALSE);
// DevisSQLComponent.this.table.setTarif(null, false);
}
558,6 → 566,7
 
JTextField poids = new JTextField();
SQLRequestComboBox boxTaxePort = new SQLRequestComboBox(false, 8);
 
// addSQLObject(poids, "T_POIDS");
final TotalPanel totalTTC = new TotalPanel(this.table, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, fieldHA, fieldDevise, poids, null,
(getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
956,6 → 965,11
rowVals.put("ID_TAXE_PORT", taxeDefault.getID());
}
 
if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
}
 
return rowVals;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/account/VenteFactureSituationSQLComponent.java
17,12 → 17,12
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable.TypeCalcul;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.common.ui.Acompte;
import org.openconcerto.erp.core.common.ui.AcompteField;
import org.openconcerto.erp.core.common.ui.AcompteRowItemView;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
153,6 → 153,9
final SQLRequestComboBox sqlRequestComboBoxAdrL = (SQLRequestComboBox) getEditor("ID_ADRESSE_LIVRAISON");
 
final SQLRequestComboBox sqlRequestComboBox = (SQLRequestComboBox) getEditor("sales.invoice.customer");
final FactureSituationItemTable table = ((FactureSituationItemTable) getEditor("sales.invoice.partial.items.list"));
final TotalPanel total = ((TotalPanel) getEditor("sales.invoice.partial.total.amount"));
 
sqlRequestComboBox.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
166,9 → 169,19
.and(new Where(getTable().getTable("ADRESSE").getField("TYPE"), "=", AdresseType.Invoice.getId())));
sqlRequestComboBoxAdrL.getRequest().setWhere(new Where(getTable().getTable("ADRESSE").getField("ID_CLIENT"), "=", wantedID)
.and(new Where(getTable().getTable("ADRESSE").getField("TYPE"), "=", AdresseType.Delivery.getId())));
SQLRow rowCli = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
if (rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
total.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
table.setRowCatComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
total.setCategorieComptable(null);
table.setRowCatComptable(null);
}
} else {
sqlRequestComboBoxAdr.getRequest().setWhere(Where.FALSE);
sqlRequestComboBoxAdrL.getRequest().setWhere(Where.FALSE);
total.setCategorieComptable(null);
table.setRowCatComptable(null);
}
 
SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
188,7 → 201,6
sqlRequestComboBox.setEnabled(false);
 
final AcompteField acompteField = ((AcompteField) getEditor("sales.invoice.partial.amount"));
final FactureSituationItemTable table = ((FactureSituationItemTable) getEditor("sales.invoice.partial.items.list"));
acompteField.getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
197,7 → 209,6
table.calculPourcentage(a, TypeCalcul.CALCUL_FACTURABLE);
}
});
final TotalPanel total = ((TotalPanel) getEditor("sales.invoice.partial.total.amount"));
total.addValueListener(new PropertyChangeListener() {
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/NouveauSaisieVenteFactureAcompteAction.java
13,24 → 13,17
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.sales.account.VenteFactureSituationSQLComponent;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauSaisieVenteFactureAcompteAction extends NouveauSaisieVenteFactureAction {
 
public class NouveauSaisieVenteFactureAcompteAction extends CreateFrameAbstractAction {
 
public NouveauSaisieVenteFactureAcompteAction() {
super();
this.putValue(Action.NAME, "Facture");
public NouveauSaisieVenteFactureAcompteAction(final PropsConfiguration conf) {
super(conf);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE").createComponent(VenteFactureSituationSQLComponent.ID), EditMode.CREATION);
protected String getComponentID() {
return VenteFactureSituationSQLComponent.ID;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeDesFactureItemsAction.java
13,16 → 13,19
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
29,27 → 32,33
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class ListeDesFactureItemsAction extends CreateIListFrameAbstractAction<SaisieVenteFactureItemSQLElement> {
 
public class ListeDesFactureItemsAction extends CreateFrameAbstractAction {
public ListeDesFactureItemsAction(final ComptaPropsConfiguration conf) {
super(conf, SaisieVenteFactureItemSQLElement.class);
}
 
public ListeDesFactureItemsAction() {
super();
this.putValue(Action.NAME, "Liste des articles facturés");
@Override
protected SQLTableModelSource createTableSource() {
final SQLTableModelSource res = super.createTableSource();
res.getReq().setWhere(new Where(getElem().getTable().getField("ID_SAISIE_VENTE_FACTURE"), ">", 1));
return res;
}
 
public JFrame createFrame() {
final SQLElement element = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
@Override
protected IListPanel instantiateListPanel(SQLTableModelSource tableSource, String panelVariant) {
return new ListeViewPanel(tableSource.getElem(), new IListe(tableSource));
}
@Override
protected void initFrame(IListFrame frame) {
final SQLElement element = this.getElem();
 
IListe liste = new IListe(element.getTableSource(true));
final ListeViewPanel listeAddPanel = new ListeViewPanel(element, liste);
listeAddPanel.getListe().getRequest().setWhere(new Where(element.getTable().getField("ID_SAISIE_VENTE_FACTURE"), ">", 1));
List<SQLField> l = new ArrayList<SQLField>();
l.add(element.getTable().getField("QTE"));
l.add(element.getTable().getField("T_PA_HT"));
l.add(element.getTable().getField("T_PV_HT"));
l.add(element.getTable().getField("T_PV_TTC"));
final IListPanel listeAddPanel = frame.getPanel();
IListTotalPanel total = new IListTotalPanel(listeAddPanel.getListe(), l);
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridy = 2;
58,8 → 67,6
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
listeAddPanel.add(total, c);
IListFrame frame = new IListFrame(listeAddPanel);
frame.setTextTitle("Liste des articles facturés");
frame.getPanel().getListe().setModificationAllowed(false);
frame.getPanel().setAddVisible(false);
frame.getPanel().setSearchFullMode(true);
70,7 → 77,5
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
frame.getPanel().add(datePanel, c);
 
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/GenEtatStockAction.java
32,7 → 32,8
ReportingStockXmlSheet sheet = new ReportingStockXmlSheet(false);
 
sheet.createDocumentAsynchronous().get();
sheet.showPrintAndExport(true, false, false, false, false);
sheet.openDocument(false);
 
} catch (Exception e) {
ExceptionHandler.handle("Erreur de traitement", e);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/NouveauSaisieVenteFactureItemAction.java
13,22 → 13,14
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.erp.action.CreateEditFrameAbstractAction;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauSaisieVenteFactureItemAction extends CreateEditFrameAbstractAction<SaisieVenteFactureItemSQLElement> {
 
public class NouveauSaisieVenteFactureItemAction extends CreateFrameAbstractAction {
 
public NouveauSaisieVenteFactureItemAction() {
super();
this.putValue(Action.NAME, "Test élément d'une saisie de vente avec facture");
public NouveauSaisieVenteFactureItemAction(final PropsConfiguration conf) {
super(conf, SaisieVenteFactureItemSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/NouveauSaisieVenteFactureAction.java
13,22 → 13,14
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.erp.action.CreateEditFrameAbstractAction;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauSaisieVenteFactureAction extends CreateEditFrameAbstractAction<SaisieVenteFactureSQLElement> {
 
public class NouveauSaisieVenteFactureAction extends CreateFrameAbstractAction {
 
public NouveauSaisieVenteFactureAction() {
super();
this.putValue(Action.NAME, "Facture");
public NouveauSaisieVenteFactureAction(final PropsConfiguration conf) {
super(conf, SaisieVenteFactureSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/NouveauSaisieVenteComptoirAction.java
13,22 → 13,14
package org.openconcerto.erp.core.sales.invoice.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.erp.action.CreateEditFrameAbstractAction;
import org.openconcerto.erp.core.sales.pos.element.SaisieVenteComptoirSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauSaisieVenteComptoirAction extends CreateEditFrameAbstractAction<SaisieVenteComptoirSQLElement> {
 
public class NouveauSaisieVenteComptoirAction extends CreateFrameAbstractAction {
 
public NouveauSaisieVenteComptoirAction() {
super();
this.putValue(Action.NAME, "Saisie Vente Comptoir");
public NouveauSaisieVenteComptoirAction(final PropsConfiguration conf) {
super(conf, SaisieVenteComptoirSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_COMPTOIR"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/ListeDesEcheancesClientsPanel.java
36,6 → 36,7
import org.openconcerto.sql.view.IListener;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
60,7 → 61,8
private ListPanelEcheancesClients panelEcheances;
private EditFrame editEncaisse = null;
private EditFrame editRelance = null;
private JButton relancer, encaisser;
private JButton relancer;
private JButton encaisser;
 
public ListeDesEcheancesClientsPanel() {
this(false);
147,23 → 149,26
public void actionPerformed(ActionEvent e) {
 
List<Integer> selectedIds = ListeDesEcheancesClientsPanel.this.panelEcheances.getListe().getSelection().getSelectedIDs();
List<SQLRow> selectedRows = new ArrayList<SQLRow>(selectedIds.size());
List<SQLRow> selectedRows = new ArrayList<>(selectedIds.size());
int idCpt = -1;
int idClient = -1;
int idCptTiers = -1;
String tiers = "";
boolean showMessage = false;
 
String numeroFact = "";
StringBuilder numerosFacturesBuilders = new StringBuilder();
for (Integer integer : selectedIds) {
final SQLRow row = ListeDesEcheancesClientsPanel.this.panelEcheances.getListe().getSource().getPrimaryTable().getRow(integer);
// System.err.println("ListeDesEcheancesClientsPanel.ListeDesEcheancesClientsPanel().new
// ActionListener() {...}.actionPerformed()"
// + row);
 
selectedRows.add(row);
 
tiers = row.getString("TIERS");
String nom = row.getForeignRow("ID_MOUVEMENT").getForeignRow("ID_PIECE").getString("NOM");
numeroFact += " " + nom;
 
numerosFacturesBuilders.append(nom);
numerosFacturesBuilders.append(' ');
 
SQLRow rowClient = row.getForeignRow("ID_CLIENT");
if (rowClient != null && !rowClient.isUndefined()) {
int idTmp = rowClient.getInt("ID_COMPTE_PCE");
int idCliTmp = rowClient.getID();
if (idCpt > -1 && idCpt != idTmp) {
179,6 → 184,11
idClient = idCliTmp;
}
}
SQLRow rowCptTiers = row.getForeignRow("ID_COMPTE_PCE_TIERS");
if (rowCptTiers != null && !rowCptTiers.isUndefined()) {
idCptTiers = rowCptTiers.getID();
}
}
if (showMessage) {
int answer = JOptionPane.showConfirmDialog(null, "Attention vous avez sélectionné des factures ayant des clients différents. Voulez vous continuer?");
if (answer != JOptionPane.YES_OPTION) {
193,9 → 203,14
}
 
SQLRowValues rowVals = new SQLRowValues(encaisseElt.getTable());
 
if (idClient > -1) {
rowVals.put("ID_CLIENT", idClient);
rowVals.put("NOM", numeroFact);
}
rowVals.put("NOM", numerosFacturesBuilders.toString().trim());
rowVals.put("TIERS", tiers);
if (idCptTiers > -1) {
rowVals.put("ID_COMPTE_PCE_TIERS", idCptTiers);
}
 
final EncaisserMontantSQLComponent sqlComponent = (EncaisserMontantSQLComponent) ListeDesEcheancesClientsPanel.this.editEncaisse.getSQLComponent();
 
210,15 → 225,18
 
// Gestion de la souris
this.panelEcheances.getJTable().addMouseListener(new MouseAdapter() {
 
@Override
public void mousePressed(MouseEvent mE) {
 
if (mE.getButton() == MouseEvent.BUTTON1) {
// Mise à jour de l'echeance sur la frame de reglement
// si cette derniere est cree
final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
final SQLRow row = panelEcheances.getListe().getSelectedRow().asRow();
if (mE.getButton() == MouseEvent.BUTTON1) {
 
final SQLRowValues selectedRow = panelEcheances.getListe().getSelectedRow();
final SQLRow row = selectedRow.asRow();
if (row == null) {
JOptionPane.showMessageDialog(ListeDesEcheancesClientsPanel.this, "Selection", "Merci de sélectionner une ligne", JOptionPane.PLAIN_MESSAGE);
return;
}
if (ListeDesEcheancesClientsPanel.this.editEncaisse != null) {
final SQLRowValues rowVals = new SQLRowValues(base.getTable("ENCAISSER_MONTANT"));
rowVals.put("ID_ECHEANCE_CLIENT", row.getID());
237,19 → 255,13
final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
final SQLTable tableEch = base.getTable("ECHEANCE_CLIENT");
final SQLRow rowEch = tableEch.getRow(id);
final int idMvtSource = MouvementSQLElement.getSourceId(rowEch.getInt("ID_MOUVEMENT"));
final SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
 
int idMvtSource = MouvementSQLElement.getSourceId(rowEch.getInt("ID_MOUVEMENT"));
SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
 
if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
ListeDesEcheancesClientsPanel.this.relancer.setEnabled(false);
} else {
ListeDesEcheancesClientsPanel.this.relancer.setEnabled(true);
}
ListeDesEcheancesClientsPanel.this.relancer.setEnabled(rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE"));
ListeDesEcheancesClientsPanel.this.encaisser.setEnabled(true);
} else {
ListeDesEcheancesClientsPanel.this.relancer.setEnabled(false);
 
ListeDesEcheancesClientsPanel.this.encaisser.setEnabled(false);
}
 
260,16 → 272,13
 
}
 
private SQLRow rowSource;
 
private void relanceClient() {
 
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
final SQLElement relanceElt = Configuration.getInstance().getDirectory().getElement("RELANCE");
 
this.rowSource = this.panelEcheances.getListe().fetchSelectedRow();
final SQLRow rowSource = this.panelEcheances.getListe().fetchSelectedRow();
 
if (this.rowSource != null) {
if (rowSource != null) {
int idMvtSource = MouvementSQLElement.getSourceId(rowSource.getInt("ID_MOUVEMENT"));
SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
 
284,16 → 293,18
this.editRelance.addEditPanelListener(new EditPanelListener() {
 
public void cancelled() {
// rien
}
 
public void modified() {
// rien
}
 
public void deleted() {
// rien
}
 
public void inserted(int id) {
System.err.println("INSERTED " + id + " -- " + rowSource.getID());
int nbRelance = rowSource.getInt("NOMBRE_RELANCE");
nbRelance++;
 
305,7 → 316,7
rowValsEch.update(rowSource.getID());
relanceElt.getTable().getRow(id).createEmptyUpdateRow().put("ID_ECHEANCE_CLIENT", rowSource.getID()).commit();
} catch (SQLException e1) {
e1.printStackTrace();
ExceptionHandler.handle("erreur lors de la mise à jour du nombre de relances", e1);
}
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/ListeDesVentesPanel.java
22,6 → 22,7
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.GenerationResult;
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.IgnoreReason;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.ui.TextAreaTicketPanel;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
32,6 → 33,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.ITableModel;
158,7 → 160,7
// TODO dialog with label informing of the successful creation of message for n
// invoices/n2 messages too far in the future/n3 messages with collection date
// changed and having a button to open the file chooser
new SwingWorker<GenerationResult, Object>() {
new SwingWorker<GenerationResult, Void>() {
@Override
protected GenerationResult doInBackground() throws Exception {
return sepaMsgElem.generateXML(selectedIDs);
191,17 → 193,16
tmMap.put("missingInfoCount", missingInfoCount);
final StringBuilder msg = new StringBuilder(256);
msg.append(TM.getTM().trM("sddMessage.generation.someIgnored", tmMap));
msg.append('\n');
if (futureCount > 0) {
msg.append("- ");
msg.append("\n- ");
msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.future", tmMap));
}
if (duplicateCount > 0) {
msg.append("- ");
msg.append("\n- ");
msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.duplicateMandate", tmMap));
}
if (missingInfoCount > 0) {
msg.append("- ");
msg.append("\n- ");
msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.missingInfo", tmMap));
}
final int messageType = duplicateCount == 0 ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE;
214,6 → 215,26
}.execute();
}
}, false, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()));
// TODO remove once we have a join with {SENT, OK, DEFINITIVE_ERROR, TRANSIENT_ERROR}
this.listeFact.getListe().addIListeAction(new RowAction.PredicateRowAction(new AbstractAction("Prélever à nouveau", null) {
@Override
public void actionPerformed(ActionEvent e) {
final IListe l = IListe.get(e);
if (JOptionPane.showConfirmDialog(l, "Voulez-vous vraiment prélever à nouveau les factures sélectionnées ? Cette action est définitive.", "Prélever à nouveau",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION)
return;
final List<Integer> selectedIDs = l.getSelection().getSelectedIDs();
final UpdateBuilder upd = new UpdateBuilder(l.getSource().getPrimaryTable());
upd.setObject(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME, upd.getTable().getForeignTable(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME).getUndefinedIDNumber());
upd.setObject(SaisieVenteFactureSQLElement.END2END_FIELD_NAME, "");
// don't allow to debit already payed invoices
upd.setWhere(new Where(upd.getTable().getKey(), selectedIDs).and(Where.isNull(upd.getTable().getField("DATE_REGLEMENT"))));
 
upd.getTable().getDBSystemRoot().getDataSource().execute(upd.asString());
for (final Integer id : selectedIDs)
upd.getTable().fireTableModified(id, upd.getFieldsNames());
}
}, false, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()));
this.listeFact.setOpaque(false);
this.listeFact.getListe().setModificationAllowed(true);
final JTable tableFact = this.listeFact.getListe().getJTable();
299,7 → 320,15
@Override
protected void handleAction(JButton source, ActionEvent evt) {
if (source == this.buttonModifier) {
new PanelFrame(new TextAreaTicketPanel(this.getListe().fetchSelectedRow()), "Ticket").setVisible(true);
POSConfiguration posConf = POSConfiguration.getInstance();
try {
if (posConf == null)
posConf = POSConfiguration.setInstance();
} catch (Exception e) {
ExceptionHandler.handle(source, "Impossible d'initialiser la configuration de la caisse", e);
return;
}
new PanelFrame(new TextAreaTicketPanel(posConf, this.getListe().fetchSelectedRow()), "Ticket").setVisible(true);
} else {
super.handleAction(source, evt);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/component/SaisieVenteFactureSQLComponent.java
64,6 → 64,7
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.RowValuesTable;
73,9 → 74,9
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.ProductInfo;
import org.openconcerto.utils.cc.IFactory;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
83,7 → 84,6
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
148,10 → 148,18
int idCli = SaisieVenteFactureSQLComponent.this.comboClient.getWantedID();
if (idCli > 1) {
SQLRow rowCli = SaisieVenteFactureSQLComponent.this.client.getTable().getRow(idCli);
if (!rowCli.isForeignEmpty("ID_COMMERCIAL")) {
if (!isFilling() && !rowCli.isForeignEmpty("ID_COMMERCIAL")) {
comboCommercial.setValue(rowCli.getForeignID("ID_COMMERCIAL"));
}
 
if (rowCli.getFields().contains("ID_CATEGORIE_COMPTABLE") && rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
totalTTC.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
tableFacture.setRowCatComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
totalTTC.setCategorieComptable(null);
tableFacture.setRowCatComptable(null);
}
 
if (getMode() == SQLComponent.Mode.INSERTION || !isFilling()) {
SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
162,6 → 170,9
SaisieVenteFactureSQLComponent.this.eltModeRegl.setValue(rowValsModeRegl);
}
}
} else {
totalTTC.setCategorieComptable(null);
tableFacture.setRowCatComptable(null);
}
 
Where w = new Where(SaisieVenteFactureSQLComponent.this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE);
184,7 → 195,7
private PropertyChangeListener changeClientListener;
private ISQLCompteSelector compteSelService;
private JLabel labelCompteServ;
private ElementComboBox comboCommercial;
private ElementComboBox comboCommercial, comboPoleProduit;
private ElementComboBox comboVerificateur = new ElementComboBox();;
private SQLTable tableBanque = getTable().getTable(BanqueSQLElement.TABLENAME);
 
240,21 → 251,6
c.gridy++;
c.gridwidth = 1;
 
 
if (getTable().contains("ID_POLE_PRODUIT")) {
JLabel labelPole = new JLabel(getLabelFor("ID_POLE_PRODUIT"));
labelPole.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelPole, c);
c.gridx++;
ElementComboBox pole = new ElementComboBox();
 
this.add(pole, c);
this.addSQLObject(pole, "ID_POLE_PRODUIT");
c.gridy++;
c.gridwidth = 1;
c.gridx = 0;
}
 
/*******************************************************************************************
* * RENSEIGNEMENTS
******************************************************************************************/
339,12 → 335,11
c.fill = GridBagConstraints.HORIZONTAL;
this.comboCommercial = new ElementComboBox(false);
// Commercial
String field;
field = "ID_COMMERCIAL";
this.addRequiredSQLObject(this.comboCommercial, "ID_COMMERCIAL");
c.gridx++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel(getLabelFor(field), SwingConstants.RIGHT), c);
this.add(new JLabel(getLabelFor("ID_COMMERCIAL"), SwingConstants.RIGHT), c);
 
c.gridx++;
c.weightx = 1;
351,7 → 346,7
c.fill = GridBagConstraints.NONE;
 
this.add(this.comboCommercial, c);
this.addRequiredSQLObject(this.comboCommercial, field);
 
// Client
c.gridx = 0;
c.gridy++;
403,6 → 398,19
 
}
 
if (getTable().contains("ID_POLE_PRODUIT")) {
JLabel labelPole = new JLabel(getLabelFor("ID_POLE_PRODUIT"));
labelPole.setHorizontalAlignment(SwingConstants.RIGHT);
c.gridx++;
this.add(labelPole, c);
 
c.gridx++;
this.comboPoleProduit = new ElementComboBox();
this.add(this.comboPoleProduit, c);
this.addSQLObject(this.comboPoleProduit, "ID_POLE_PRODUIT");
DefaultGridBagConstraints.lockMinimumSize(this.comboPoleProduit);
}
 
if (
 
getTable().contains("ID_ECHEANCIER_CCI")) {
432,7 → 440,7
 
if (!isFilling()) {
SQLRow rowPole = selAffaire.getSelectedRow().getForeignRow("ID_POLE_PRODUIT");
comboCommercial.setValue(rowPole);
comboPoleProduit.setValue(rowPole);
}
} else {
echeancier.getRequest().setWhere(null);
715,7 → 723,69
}
});
}
final DeviseField textFraisDocHT = new DeviseField();
final SQLRequestComboBox boxTaxeFraisDoc = new SQLRequestComboBox(false, 8);
 
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
final boolean showFrais = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.FRAIS_DOCUMENT, false);
if (showFrais) {
 
JLabel labelFraisDocHT = new JLabel(getLabelFor("FRAIS_DOCUMENT_HT"));
labelFraisDocHT.setHorizontalAlignment(SwingConstants.RIGHT);
cFrais.gridx = 1;
cFrais.gridy++;
panelFrais.add(labelFraisDocHT, cFrais);
cFrais.gridx++;
panelFrais.add(textFraisDocHT, cFrais);
addView(textFraisDocHT, "FRAIS_DOCUMENT_HT");
 
JLabel labelTaxeFraisDocHT = new JLabel(getLabelFor("ID_TAXE_FRAIS_DOCUMENT"));
labelTaxeFraisDocHT.setHorizontalAlignment(SwingConstants.RIGHT);
cFrais.gridx = 1;
cFrais.gridy++;
panelFrais.add(labelTaxeFraisDocHT, cFrais);
cFrais.gridx++;
panelFrais.add(boxTaxeFraisDoc, cFrais);
this.addView(boxTaxeFraisDoc, "ID_TAXE_FRAIS_DOCUMENT", REQ);
 
boxTaxeFraisDoc.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
totalTTC.updateTotal();
}
});
 
textFraisDocHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
public void update(final DocumentEvent e) {
totalTTC.updateTotal();
}
});
 
comboClient.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!isFilling()) {
final int wantedID = comboClient.getWantedID();
long l = 0;
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
 
final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
SQLRow rowFrais = rowClient.getForeign("ID_FRAIS_DOCUMENT");
if (rowFrais != null && !rowFrais.isUndefined()) {
l = rowFrais.getLong("MONTANT_HT");
boxTaxeFraisDoc.setValue(rowFrais.getForeignID("ID_TAXE"));
}
textFraisDocHT.setValue(l);
}
}
}
});
}
 
// Remise
JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
767,6 → 837,7
 
totalTTC = new TotalPanel(this.tableFacture, fieldTEco, fieldHT, fieldTVA, this.fieldTTC, this.textPortHT, this.textRemiseHT, fieldService, fieldTHA, fieldDevise, poids, null,
(getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
totalTTC.setTextFraisDoc(textFraisDocHT, boxTaxeFraisDoc);
DefaultGridBagConstraints.lockMinimumSize(totalTTC);
cBottom.gridx++;
cBottom.weightx = 1;
1156,7 → 1227,7
}
 
private void createCompteServiceAuto(int id) throws SQLException {
SQLRow rowPole = this.comboCommercial.getSelectedRow();
SQLRow rowPole = this.comboPoleProduit.getSelectedRow();
SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
String verifInitiale = getInitialesFromVerif(rowVerif);
int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
1744,6 → 1815,10
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
vals.put("ID_TAXE_PORT", taxeDefault.getID());
}
if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
vals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
}
vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
System.err.println("Defaults " + vals);
return vals;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureItemSQLElement.java
16,44 → 16,71
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.rights.NXRights;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
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.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
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.JLabel;
import javax.swing.JTextField;
 
public class SaisieVenteFactureItemSQLElement extends ComptaSQLConfElement {
 
public SaisieVenteFactureItemSQLElement() {
super("SAISIE_VENTE_FACTURE_ELEMENT", "un article facturé", "articles facturés");
private final ComptaPropsConfiguration conf;
 
public SaisieVenteFactureItemSQLElement(final ComptaPropsConfiguration conf) {
super(conf.getRootSociete().getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
this.conf = conf;
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Transfert vers commande fournisseur") {
 
@Override
public void actionPerformed(ActionEvent e) {
SQLElement cmd = getDirectory().getElement("COMMANDE");
EditFrame f = new EditFrame(cmd, EditMode.CREATION);
f.getSQLComponent().select(transfertCommande(IListe.get(e).getSelectedRows()));
f.setVisible(true);
}
}, false);
action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(action);
}
 
public SaisieVenteFactureItemSQLElement(String tableName, String singular, String plural) {
super(tableName, singular, plural);
public final ComptaPropsConfiguration getConf() {
return this.conf;
}
 
@Override
62,6 → 89,44
return "ID_SAISIE_VENTE_FACTURE";
}
 
/**
* Transfert d'une commande en commande fournisseur
*
* @param commandeID
*/
public SQLRowValues transfertCommande(List<SQLRowValues> factItems) {
SQLTable tableCmd = getDirectory().getElement("COMMANDE").getTable();
SQLTable tableCmdElt = getDirectory().getElement("COMMANDE_ELEMENT").getTable();
SQLRowValues rowCmd = new SQLRowValues(tableCmd);
 
final Map<Integer, SQLRowValues> map = new HashMap<Integer, SQLRowValues>();
for (SQLRowAccessor sqlRow : factItems) {
// on récupére l'article qui lui correspond
SQLRow sqlRowFetch = sqlRow.asRow();
sqlRowFetch.fetchValues();
if (sqlRowFetch.getObject("ID_ARTICLE") != null && !sqlRowFetch.getForeign("ID_ARTICLE").isUndefined()) {
int idArt = sqlRowFetch.getForeignID("ID_ARTICLE");
if (map.containsKey(idArt)) {
SQLRowValues rowValsElt = map.get(idArt);
rowValsElt.put("QTE", rowValsElt.getInt("QTE") + sqlRowFetch.getInt("QTE"));
} else {
SQLInjector inj = SQLInjector.getInjector(sqlRowFetch.getForeign("ID_ARTICLE").getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(sqlRowFetch.getForeign("ID_ARTICLE").asRow()));
rowValsElt.put("ID_STYLE", sqlRowFetch.getObject("ID_STYLE"));
rowValsElt.put("QTE", sqlRowFetch.getObject("QTE"));
rowValsElt.put("T_POIDS", sqlRowFetch.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", ((BigDecimal) sqlRowFetch.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC",
((BigDecimal) sqlRowFetch.getObject("T_PA_HT")).multiply(new BigDecimal((sqlRowFetch.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("ID_COMMANDE", rowCmd);
map.put(idArt, rowValsElt);
}
}
 
}
return rowCmd;
}
 
/*
* (non-Javadoc)
*
266,6 → 331,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureSQLElement.java
22,6 → 22,7
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.edm.AttachmentAction;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.core.sales.account.PartialInvoiceEditGroup;
import org.openconcerto.erp.core.sales.account.VenteFactureSituationSQLComponent;
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeEditGroup;
28,6 → 29,7
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeSQLComponent;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.invoice.ui.DateReglementRenderer;
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;
88,6 → 90,7
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
628,4 → 631,9
 
});
}
 
@Override
protected String createCode() {
return "sales.invoice";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/EcheanceClientSQLElement.java
427,7 → 427,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".commitment";
return createCodeOfPackage() + ".commitment";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/TransferInvoiceSQLElement.java
45,6 → 45,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transfer";
return createCodeOfPackage() + ".transfer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/EtatStockInventaireXmlSheet.java
New file
0,0 → 1,277
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
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 java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
 
public class EtatStockInventaireXmlSheet extends AbstractListeSheetXml {
 
private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
 
public static final String TEMPLATE_ID = "EtatStockInventaire";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private Date date;
private SQLElement eltArticle;
private SQLElement eltStock;
 
public EtatStockInventaireXmlSheet(SQLRow etatStock) {
super();
this.row = etatStock;
 
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
 
}
 
@Override
public String getStoragePathP() {
return "Autres";
}
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
};
 
@Override
public String getName() {
if (this.date == null) {
this.date = new Date();
}
return "EtatStocks" + this.date.getTime();
}
 
protected void createListeValues() {
 
SQLRowValues rowVals = new SQLRowValues(this.row.getTable().getTable("ETAT_STOCK_ELEMENT"));
rowVals.put("QTE", null);
SQLRowValues rowValsArt = rowVals.putRowValues("ID_ARTICLE");
rowValsArt.put("ID_FAMILLE_ARTICLE", null);
rowValsArt.put("CODE", null);
rowValsArt.put("NOM", null);
rowValsArt.put("PA_HT", null);
rowValsArt.put("PV_HT", null);
 
SQLRowValuesListFetcher fetch = SQLRowValuesListFetcher.create(rowVals);
List<SQLRowValues> values = fetch.fetch(new Where(rowVals.getTable().getField("ID_ETAT_STOCK"), "=", this.row.getID()));
 
final SQLTable tableF = this.row.getTable().getTable("FAMILLE_ARTICLE");
SQLSelect selFam = new SQLSelect();
selFam.addSelect(tableF.getKey());
selFam.addSelect(tableF.getField("NOM"));
selFam.addSelect(tableF.getField("ID_FAMILLE_ARTICLE_PERE"));
 
List<SQLRow> fam = SQLRowListRSH.execute(selFam);
Map<Integer, SQLRow> mapF = new HashMap<Integer, SQLRow>();
for (SQLRow sqlRow : fam) {
mapF.put(sqlRow.getID(), sqlRow);
}
 
final SQLTable tableFourn = this.row.getTable().getTable("FOURNISSEUR");
SQLSelect selFourn = new SQLSelect();
selFourn.addSelect(tableFourn.getKey());
selFourn.addSelect(tableFourn.getField("NOM"));
 
List<SQLRow> fourn = SQLRowListRSH.execute(selFourn);
Map<Integer, SQLRow> mapFourn = new HashMap<Integer, SQLRow>();
for (SQLRow sqlRow : fourn) {
mapFourn.put(sqlRow.getID(), sqlRow);
}
 
Map<String, Line> linesFamilles = new HashMap<String, Line>();
Map<Line, Map<Line, List<Line>>> myValues = new TreeMap<Line, Map<Line, List<Line>>>(new Comparator<Line>() {
@Override
public int compare(Line o1, Line o2) {
return o1.getNomArt().compareTo(o2.getNomArt());
}
});
Line lineTotal = new Line("Total", "", BigDecimal.ZERO, BigDecimal.ZERO);
final HashMap<Integer, String> style = new HashMap<Integer, String>();
for (SQLRowValues vals : values) {
BigDecimal qte = vals.getBigDecimal("QTE");
 
SQLRowAccessor rowValsArticle = vals.getForeign("ID_ARTICLE");
BigDecimal ha = rowValsArticle.getBigDecimal("PA_HT").multiply(qte);
 
int idFamille = rowValsArticle.getForeignID("ID_FAMILLE_ARTICLE");
SQLRow rowF = mapF.get(idFamille);
Line lineArt = new Line(rowF == null || rowF.isUndefined() ? "Sans famille" : rowF.getString("NOM"), rowValsArticle.getString("NOM"), rowValsArticle.getString("CODE"), ha, qte);
 
// Init des lines familles
 
final Line lineF, lineSF;
if (rowF == null) {
if (!linesFamilles.containsKey("Undef")) {
linesFamilles.put("Undef", new Line("Sans famille", "", BigDecimal.ZERO, BigDecimal.ZERO));
linesFamilles.put("Undef-Undef", new Line("", "", BigDecimal.ZERO, BigDecimal.ZERO));
}
lineF = linesFamilles.get("Undef");
lineSF = linesFamilles.get("Undef-Undef");
} else if (rowF.getObject("ID_FAMILLE_ARTICLE_PERE") == null || rowF.isForeignEmpty("ID_FAMILLE_ARTICLE_PERE")) {
if (!linesFamilles.containsKey(String.valueOf(rowF.getID()))) {
linesFamilles.put(String.valueOf(rowF.getID()), new Line(rowF.getString("NOM"), "", BigDecimal.ZERO, BigDecimal.ZERO));
linesFamilles.put(String.valueOf(rowF.getID()) + "-Undef", new Line("", "", BigDecimal.ZERO, BigDecimal.ZERO));
}
if (!linesFamilles.containsKey(String.valueOf(rowF.getID()) + "-Undef")) {
linesFamilles.put(String.valueOf(rowF.getID()) + "-Undef", new Line("", "", BigDecimal.ZERO, BigDecimal.ZERO));
}
lineF = linesFamilles.get(String.valueOf(rowF.getID()));
lineSF = linesFamilles.get(String.valueOf(rowF.getID()) + "-Undef");
} else {
if (!linesFamilles.containsKey(String.valueOf(rowF.getID()))) {
linesFamilles.put(String.valueOf(rowF.getID()), new Line(rowF.getString("NOM"), "", BigDecimal.ZERO, BigDecimal.ZERO));
}
if (!linesFamilles.containsKey(String.valueOf(rowF.getForeignID("ID_FAMILLE_ARTICLE_PERE")))) {
SQLRow rowSF = mapF.get(rowF.getForeignID("ID_FAMILLE_ARTICLE_PERE"));
linesFamilles.put(String.valueOf(rowF.getForeignID("ID_FAMILLE_ARTICLE_PERE")), new Line(rowSF.getString("NOM"), "", BigDecimal.ZERO, BigDecimal.ZERO));
}
lineF = linesFamilles.get(String.valueOf(rowF.getForeignID("ID_FAMILLE_ARTICLE_PERE")));
lineSF = linesFamilles.get(String.valueOf(rowF.getID()));
}
 
// init values
if (!myValues.containsKey(lineF)) {
myValues.put(lineF, new TreeMap<Line, List<Line>>(new Comparator<Line>() {
@Override
public int compare(Line o1, Line o2) {
return o1.getNomArt().compareTo(o2.getNomArt());
}
}));
myValues.get(lineF).put(lineSF, new ArrayList<Line>());
}
Map<Line, List<Line>> mapSF = myValues.get(lineF);
if (!mapSF.containsKey(lineSF)) {
mapSF.put(lineSF, new ArrayList<Line>());
}
 
// Store values
List<Line> lines = mapSF.get(lineSF);
lines.add(lineArt);
lineTotal.add(lineArt);
lineF.add(lineArt);
lineSF.add(lineArt);
 
}
 
// Sort Values
List<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>();
 
for (Line f : myValues.keySet()) {
listValues.add(f.getMapXMLSheet());
style.put(style.keySet().size(), "Titre 1");
Map<Line, List<Line>> sfs = myValues.get(f);
for (Line sf : sfs.keySet()) {
// listValues.add(sf.getMapXMLSheet());
// style.put(style.keySet().size(), "Titre 2");
List<Line> vals = sfs.get(sf);
Collections.sort(vals, new Comparator<Line>() {
@Override
public int compare(Line o1, Line o2) {
return o1.getNomArt().compareTo(o2.getNomArt());
}
});
for (Line line : vals) {
listValues.add(line.getMapXMLSheet());
style.put(style.keySet().size(), "Normal");
}
}
}
 
listValues.add(lineTotal.getMapXMLSheet());
style.put(style.keySet().size(), "Titre 1");
 
final Map<String, Object> valuesSheet = new HashMap<String, Object>();
valuesSheet.put("DATE", "Au " + dateFormat.format(new Date()));
//
this.listAllSheetValues.put(0, listValues);
 
this.styleAllSheetValues.put(0, style);
this.mapAllSheetValues.put(0, valuesSheet);
}
 
class Line {
private final String nomArt;
private final String codeArt;
private final String famille;
private BigDecimal totalHA;
private BigDecimal qte;
 
public Line(String nomArt, String codeArt, BigDecimal totalHA, BigDecimal qte) {
this("", nomArt, codeArt, totalHA, qte);
}
 
public Line(String famille, String nomArt, String codeArt, BigDecimal totalHA, BigDecimal qte) {
this.famille = famille;
this.nomArt = nomArt;
this.codeArt = codeArt;
this.totalHA = totalHA;
this.qte = qte;
}
 
public BigDecimal getQte() {
return qte;
}
 
public String getCodeArt() {
return codeArt;
}
 
public String getNomArt() {
return nomArt;
}
 
public BigDecimal getTotalHA() {
return totalHA;
}
 
public void add(Line l) {
this.totalHA = this.totalHA.add(l.getTotalHA());
this.qte = this.qte.add(l.getQte());
}
 
public Map<String, Object> getMapXMLSheet() {
Map<String, Object> m = new HashMap<String, Object>();
m.put("FAMILLE", this.famille);
m.put("CODE", getCodeArt());
m.put("NOM", getNomArt());
m.put("QTE", getQte());
m.put("TOTAL_HA", getTotalHA());
return m;
}
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ReportingVenteXmlSheet.java
17,6 → 17,7
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
87,17 → 88,18
protected void createListeValues() {
 
SQLSelect sel = new SQLSelect();
sel.addRawSelect("SUM(\"QTE\"*\"QTE_UNITAIRE\")", "q");
final SQLTable tableItemFact = eltFactItem.getTable();
sel.addSelect(tableItemFact.getField("T_PA_HT"), "SUM");
sel.addSelect(tableItemFact.getField("T_PV_HT"), "SUM");
sel.addSelect(tableItemFact.getField("T_PV_TTC"), "SUM");
AliasedTable tableAlias = new AliasedTable(tableItemFact, "eltTable");
sel.addRawSelect("SUM(\"eltTable\".\"QTE\"*\"eltTable\".\"QTE_UNITAIRE\")", "q");
sel.addSelect(tableAlias.getField("T_PA_HT"), "SUM");
sel.addSelect(tableAlias.getField("T_PV_HT"), "SUM");
sel.addSelect(tableAlias.getField("T_PV_TTC"), "SUM");
final SQLTable tableArt = eltFactItem.getForeignElement("ID_ARTICLE").getTable();
sel.addSelect(tableItemFact.getField("ID_ARTICLE"));
sel.addSelect(tableAlias.getField("ID_ARTICLE"));
 
final SQLSelectJoin joinFact = sel.addJoin("LEFT", tableItemFact.getField("ID_" + eltFact.getTable().getName()));
final SQLSelectJoin joinFact = sel.addJoin("LEFT", tableAlias.getField("ID_" + eltFact.getTable().getName()));
 
Where wA = new Where(tableArt.getKey(), "=", tableItemFact.getField("ID_ARTICLE"));
Where wA = new Where(tableArt.getKey(), "=", tableAlias.getField("ID_ARTICLE"));
Where w = new Where(joinFact.getJoinedTable().getField("DATE"), this.du, this.au);
 
if (idS != null && idS.size() > 0) {
108,7 → 110,7
}
sel.setWhere(wA.and(w));
 
sel.addGroupBy(tableItemFact.getField("ID_ARTICLE"));
sel.addGroupBy(tableAlias.getField("ID_ARTICLE"));
 
List<Object[]> result = eltFact.getTable().getDBSystemRoot().getDataSource().executeA(sel.asString());
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ReportingClientPanel.java
New file
0,0 → 1,119
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.EmailComposer;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
public class ReportingClientPanel extends JPanel {
 
public ReportingClientPanel() {
super(new GridBagLayout());
 
JLabelBold title = new JLabelBold("Génération d'un relevé des factures d'un client");
 
JLabel labelCom = new JLabel("Relevé du client");
 
final ElementComboBox box = new ElementComboBox(true);
SQLElement element = Configuration.getInstance().getDirectory().getElement("CLIENT");
ComboSQLRequest comboRequest = element.getComboRequest(true);
// comboRequest.setUndefLabel("Tous");
box.init(element, comboRequest);
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(title, c);
c.gridy++;
c.gridwidth = 1;
this.add(labelCom, c);
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(box, c);
 
c.gridy++;
c.gridx = 0;
c.gridwidth = 1;
this.add(new JLabel("Facture émises entre le"), c);
final JDate d1 = new JDate();
c.gridx++;
this.add(d1, c);
c.gridx++;
this.add(new JLabel("et le"), c);
final JDate d2 = new JDate();
c.gridx++;
this.add(d2, c);
 
final JButton buttonValid = new JButton(new AbstractAction("Valider") {
 
@Override
public void actionPerformed(ActionEvent e) {
 
new Thread() {
public void run() {
 
final SQLRow selectedClient = box.getSelectedRow();
ReportingClientXml sheet = new ReportingClientXml(selectedClient, d1.getValue(), d2.getValue());
try {
sheet.createDocument();
// sheet.showPrintAndExport(false, false, false);
 
String mail = selectedClient.getString("MAIL");
 
try {
EmailComposer.getInstance().compose(mail, "", "", sheet.getGeneratedFile());
} catch (Exception exn) {
ExceptionHandler.handle(null, "Impossible de créer le courriel", exn);
}
 
} catch (Exception e) {
ExceptionHandler.handle("Une erreur est survenue lors de la création du document", e);
}
};
}.start();
 
}
});
c.gridx++;
this.add(buttonValid, c);
 
// Listener enabled/disabled button
buttonValid.setEnabled(false);
box.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent arg0) {
buttonValid.setEnabled(box.getWantedID() != SQLRow.NONEXISTANT_ID && box.getWantedID() != box.getRequest().getPrimaryTable().getUndefinedID());
}
});
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ReportingClientXml.java
New file
0,0 → 1,209
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
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.utils.cc.ITransformer;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
 
public class ReportingClientXml extends AbstractListeSheetXml {
 
public static final String TEMPLATE_ID = "ReportingClient";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private final Calendar toDay = Calendar.getInstance();
private final Date d1, d2;
private DateFormat format;
 
public ReportingClientXml(SQLRow rowClient, Date d1, Date d2) {
super(rowClient);
this.d1 = d1;
this.d2 = d2;
}
 
@Override
protected void createListeValues() {
final SQLTable table = Configuration.getInstance().getDirectory().getElement("CLIENT").getTable();
SQLRowValues rowVals = new SQLRowValues(table);
rowVals.putNulls("NOM");
 
final SQLTable tableFacture = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE").getTable();
SQLRowValues rowValsF = new SQLRowValues(tableFacture);
rowValsF.put("ID_CLIENT", rowVals);
rowValsF.putNulls("NUMERO", "NOM", "T_HT", "T_TTC", "DATE", "INFOS");
 
final SQLTable tableEch = Configuration.getInstance().getDirectory().getElement("ECHEANCE_CLIENT").getTable();
SQLRowValues rowValsE = new SQLRowValues(tableEch);
rowValsE.put("ID_SAISIE_VENTE_FACTURE", rowValsF);
rowValsE.putNulls("REGLE", "DATE", "MONTANT", "REG_COMPTA", "DATE_LAST_RELANCE");
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsF);
 
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
 
Where w = new Where(tableFacture.getField("ID_CLIENT"), "=", row.getID());
if (d1 != null || d2 != null) {
if (d1 == null) {
w = w.and(new Where(tableFacture.getField("DATE"), "<=", d2));
} else if (d2 == null) {
w = w.and(new Where(tableFacture.getField("DATE"), ">=", d1));
} else {
w = w.and(new Where(tableFacture.getField("DATE"), d1, d2));
}
}
input.setWhere(w);
return input;
}
});
 
List<SQLRowValues> l = fetcher.fetch();
 
this.mapAllSheetValues = new HashMap<Integer, Map<String, Object>>();
Map<String, Object> mapValues = new HashMap<String, Object>();
mapValues.put("CLIENT", this.row.getString("NOM"));
mapValues.put("DATE", toDay.getTime());
 
String upTo = "Invoices up to ";
String since = "Invoices since ";
String between = "Invoices between ";
String and = " and ";
if (this.row.getObject("ID_LANGUE") != null && this.row.getInt("ID_LANGUE") == 2) {
 
upTo = "Factures jusqu'au ";
since = "Factures depuis le ";
between = "Factures entre le ";
and = " et le ";
format = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
} else {
format = new SimpleDateFormat("d MMMM yyyy", Locale.US);
// format = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
}
 
if (d1 != null || d2 != null) {
if (d1 == null) {
mapValues.put("PERIOD", upTo + format.format(d2));
} else if (d2 == null) {
mapValues.put("PERIOD", since + format.format(d1));
 
} else {
mapValues.put("PERIOD", between + format.format(d1) + and + format.format(d2));
}
}
 
this.mapAllSheetValues.put(0, mapValues);
 
List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
 
this.listAllSheetValues.put(0, values);
this.styleAllSheetValues = new HashMap<Integer, Map<Integer, String>>();
Map<Integer, String> styles = new HashMap<Integer, String>();
this.styleAllSheetValues.put(0, styles);
 
Map<String, Object> total = new HashMap<String, Object>();
total.put("NUMERO_FACTURE", "TOTAL");
double totalTTC = 0;
double totalDu = 0;
for (SQLRowValues sqlRowValues : l) {
Map<String, Object> line = new HashMap<String, Object>();
line.put("NUMERO_FACTURE", sqlRowValues.getObject("NUMERO"));
line.put("INFOS", sqlRowValues.getObject("INFOS"));
line.put("NOM", sqlRowValues.getObject("NOM"));
 
Calendar c = sqlRowValues.getDate("DATE");
line.put("DATE", c.getTime());
 
final double ttc = sqlRowValues.getLong("T_TTC") / 100.0D;
line.put("T_TTC", ttc);
 
double du = 0;
 
// Client
SQLRowAccessor rowC = sqlRowValues.getForeign("ID_CLIENT");
if (rowC != null && !rowC.isUndefined()) {
line.put("CLIENT", rowC.getObject("NOM"));
}
 
Calendar dateEch = Calendar.getInstance();
dateEch.setTime(c.getTime());
// Echeance
Collection<SQLRowValues> echeances = sqlRowValues.getReferentRows(tableEch);
for (SQLRowValues sqlRowValues2 : echeances) {
if (!sqlRowValues2.getBoolean("REGLE") && !sqlRowValues2.getBoolean("REG_COMPTA")) {
du += sqlRowValues2.getLong("MONTANT") / 100.0D;
dateEch = sqlRowValues2.getDate("DATE");
}
}
 
line.put("ECHEANCE", dateEch.getTime());
 
line.put("DU", du);
line.put("REGLE", ttc - du);
 
totalTTC += ttc;
totalDu += du;
 
if (du == 0) {
styles.put(values.size(), "Normal");
} else {
if (!toDay.after(dateEch)) {
styles.put(values.size(), "Titre 1");
} else {
styles.put(values.size(), "Titre 2");
}
}
values.add(line);
}
 
total.put("T_TTC", totalTTC);
total.put("DU", totalDu);
total.put("REGLE", totalTTC - totalDu);
styles.put(values.size(), "Titre 3");
values.add(total);
 
}
 
@Override
public String getDefaultTemplateId() {
 
return TEMPLATE_ID;
}
 
@Override
public String getName() {
// TODO Auto-generated method stub
return "ReportingClient" + this.row.getString("NOM");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/report/PaypalStamper.java
New file
0,0 → 1,59
/*
* 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.quote.report;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfBorderArray;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
 
public class PaypalStamper {
 
public static void main(String[] args) throws Exception {
final PaypalStamper s = new PaypalStamper();
s.addLink(new File("Facture_2018-11-00422.pdf"), new File("paypal.pdf"), 33, 72, "https://www.openconerto.org");
}
 
/**
* @param x : 0 - 440
* @param y : 0 - 780
*/
public void addLink(File inFile, File outFile, int x, int y, String hyperlink) throws Exception {
if (hyperlink == null) {
throw new IllegalArgumentException("null link");
}
final PdfReader reader = new PdfReader(new FileInputStream(inFile));
final PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outFile));
final int page = reader.getNumberOfPages();
final Image img = Image.getInstance(this.getClass().getResource("payer-avec-paypal.png"));
final float w = img.getScaledWidth() / 3;
final float h = img.getScaledHeight() / 3;
// Add image on last page
stamper.getOverContent(page).addImage(img, w, 0, 0, h, x, y);
final Rectangle linkLocation = new Rectangle(x, y, x + w, y + h);
final PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(), linkLocation, PdfAnnotation.HIGHLIGHT_OUTLINE, new PdfAction(hyperlink));
link.setBorder(new PdfBorderArray(0, 0, 0));
// Add link on last page
stamper.addAnnotation(link, page);
stamper.close();
reader.close();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/report/payer-avec-paypal.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/report/payer-avec-paypal.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/NouveauDevisItemAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/NouvellePropositionAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/ListeDesElementsPropositionsAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/NouveauDevisAction.java
13,29 → 13,14
package org.openconcerto.erp.core.sales.quote.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.erp.action.CreateEditFrameAbstractAction;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauDevisAction extends CreateEditFrameAbstractAction<DevisSQLElement> {
 
public class NouveauDevisAction extends CreateFrameAbstractAction {
 
final SQLElement element = Configuration.getInstance().getDirectory().getElement("DEVIS");
 
public NouveauDevisAction() {
super();
 
final String pluralName = this.element.getPluralName();
this.putValue(Action.NAME, StringUtils.firstUpThenLow(pluralName));
public NouveauDevisAction(final PropsConfiguration conf) {
super(conf, DevisSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(this.element);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/ListeDesDevisActionTCP.java
New file
0,0 → 1,197
/*
* 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.quote.action;
 
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.sales.invoice.ui.ListeFactureRenderer;
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.DevisTextSheet;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetUtils;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.TableCellRendererUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
 
public class ListeDesDevisActionTCP extends CreateIListFrameAbstractAction<DevisSQLElement> implements MouseListener {
 
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
 
public ListeDesDevisActionTCP(final ComptaPropsConfiguration conf) {
super(conf, DevisSQLElement.class);
}
 
IListFrame frame = null;
 
 
 
public void mouseClicked(MouseEvent e) {
}
 
public void mousePressed(MouseEvent e) {
 
int selectedId = this.frame.getPanel().getListe().getSelectedId();
if (selectedId > 1 && e.getButton() == MouseEvent.BUTTON3) {
 
final SQLRow row = this.frame.getPanel().getListe().fetchSelectedRow();
JPopupMenu menu = new JPopupMenu();
final DevisTextSheet s = new DevisTextSheet(row);
 
// Voir le document
AbstractAction actionOpen = new AbstractAction("Voir le document") {
public void actionPerformed(ActionEvent e) {
s.generate(false, false, "");
s.showDocument();
}
};
JMenuItem openItem = new JMenuItem(actionOpen);
openItem.setFont(openItem.getFont().deriveFont(Font.BOLD));
menu.add(openItem);
 
final File outpuDirectory = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(s.getTemplateId());
List<File> files = SheetUtils.getHistorique(s.getFileName(), outpuDirectory);
if (files.size() > 0) {
JMenu item = new JMenu("Historique");
int i = 0;
for (final File file : files) {
JMenuItem subItem = new JMenuItem("Version " + i + " du " + this.dateFormat.format(new Date(file.lastModified())));
subItem.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (file.exists()) {
try {
final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
if (ooConnexion == null) {
return;
}
ooConnexion.loadDocument(file, false);
 
} catch (LinkageError ex) {
JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
} catch (Exception ex) {
ex.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document OpenOffice", ex);
}
 
}
}
});
i++;
item.add(subItem);
 
}
menu.add(item);
}
 
AbstractAction actionAcc = new AbstractAction("Marquer comme accepté") {
public void actionPerformed(ActionEvent e) {
SQLRowValues rowVals = IListe.get(e).fetchSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IListe.get(e).fetchSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
};
menu.add(actionAcc);
 
AbstractAction actionRefus = new AbstractAction("Marquer comme refusé") {
public void actionPerformed(ActionEvent e) {
SQLRowValues rowVals = IListe.get(e).fetchSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.REFUSE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IListe.get(e).fetchSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
};
menu.add(actionRefus);
 
// Voir le document
AbstractAction actionTransfert = new AbstractAction("Transférer en facture") {
public void actionPerformed(ActionEvent e) {
 
ListeDesDevisActionTCP.this.getElem().transfertFacture(row.getID());
}
};
menu.add(actionTransfert);
 
// Impression
AbstractAction actionPrint = new AbstractAction("Imprimer") {
public void actionPerformed(ActionEvent e) {
s.fastPrintDocument();
}
};
menu.add(actionPrint);
 
menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
}
}
 
public void mouseReleased(MouseEvent e) {
}
 
public void mouseEntered(MouseEvent e) {
}
 
public void mouseExited(MouseEvent e) {
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/action/ListeDesDevisAction.java
15,199 → 15,19
 
import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.sales.invoice.ui.ListeFactureRenderer;
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.DevisTextSheet;
import org.openconcerto.erp.core.sales.quote.ui.ListeDesDevisPanel;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.generationDoc.SheetUtils;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.TableCellRendererUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ListeDesDevisAction extends CreateListFrameAbstractAction<DevisSQLElement, PanelFrame> {
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
 
public class ListeDesDevisAction extends CreateListFrameAbstractAction implements MouseListener {
 
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
 
public ListeDesDevisAction() {
super();
final String pluralName = this.element.getPluralName();
this.putValue(Action.NAME, "Liste des " + pluralName);
public ListeDesDevisAction(final ComptaPropsConfiguration conf) {
super(conf, DevisSQLElement.class);
}
 
IListFrame frame = null;
final DevisSQLElement element = (DevisSQLElement) Configuration.getInstance().getDirectory().getElement("DEVIS");
 
public String getTableName() {
return "DEVIS";
}
 
public JFrame createFrame() {
final String pluralName = this.element.getPluralName();
final PanelFrame frame2 = new PanelFrame(new ListeDesDevisPanel(), "Liste des " + pluralName);
return frame2;
}
 
public void mouseClicked(MouseEvent e) {
}
 
public void mousePressed(MouseEvent e) {
 
int selectedId = this.frame.getPanel().getListe().getSelectedId();
if (selectedId > 1 && e.getButton() == MouseEvent.BUTTON3) {
 
final SQLRow row = this.frame.getPanel().getListe().fetchSelectedRow();
JPopupMenu menu = new JPopupMenu();
final DevisTextSheet s = new DevisTextSheet(row);
 
// Voir le document
AbstractAction actionOpen = new AbstractAction("Voir le document") {
public void actionPerformed(ActionEvent e) {
s.generate(false, false, "");
s.showDocument();
}
};
JMenuItem openItem = new JMenuItem(actionOpen);
openItem.setFont(openItem.getFont().deriveFont(Font.BOLD));
menu.add(openItem);
 
final File outpuDirectory = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(s.getTemplateId());
List<File> files = SheetUtils.getHistorique(s.getFileName(), outpuDirectory);
if (files.size() > 0) {
JMenu item = new JMenu("Historique");
int i = 0;
for (final File file : files) {
JMenuItem subItem = new JMenuItem("Version " + i + " du " + this.dateFormat.format(new Date(file.lastModified())));
subItem.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (file.exists()) {
try {
final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
if (ooConnexion == null) {
return;
protected PanelFrame instantiateFrame() {
return new PanelFrame(new ListeDesDevisPanel(), String.valueOf(getValue(NAME)));
}
ooConnexion.loadDocument(file, false);
 
} catch (LinkageError ex) {
JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
} catch (Exception ex) {
ex.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document OpenOffice", ex);
}
 
}
}
});
i++;
item.add(subItem);
 
}
menu.add(item);
}
 
AbstractAction actionAcc = new AbstractAction("Marquer comme accepté") {
public void actionPerformed(ActionEvent e) {
SQLRowValues rowVals = IListe.get(e).fetchSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IListe.get(e).fetchSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
};
menu.add(actionAcc);
 
AbstractAction actionRefus = new AbstractAction("Marquer comme refusé") {
public void actionPerformed(ActionEvent e) {
SQLRowValues rowVals = IListe.get(e).fetchSelectedRow().createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.REFUSE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IListe.get(e).fetchSelectedRow().getTable().fireTableModified(IListe.get(e).getSelectedId());
}
};
menu.add(actionRefus);
 
// Voir le document
AbstractAction actionTransfert = new AbstractAction("Transférer en facture") {
public void actionPerformed(ActionEvent e) {
 
ListeDesDevisAction.this.element.transfertFacture(row.getID());
}
};
menu.add(actionTransfert);
 
// Impression
AbstractAction actionPrint = new AbstractAction("Imprimer") {
public void actionPerformed(ActionEvent e) {
s.fastPrintDocument();
}
};
menu.add(actionPrint);
 
menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
}
}
 
public void mouseReleased(MouseEvent e) {
}
 
public void mouseEntered(MouseEvent e) {
}
 
public void mouseExited(MouseEvent e) {
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/ui/ListeDesDevisPanel.java
253,6 → 253,25
});
 
dateEnvoiCol.setEditable(true);
 
final BaseSQLTableModelColumn colAvancementLiv = new BaseSQLTableModelColumn("Livraison", BigDecimal.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
return getAvancementLFromBL(r);
}
 
@Override
public Set<FieldPath> getPaths() {
final Path p = new PathBuilder(eltDevis.getTable()).addTable("DEVIS_ELEMENT").build();
return CollectionUtils.createSet(new FieldPath(p, "ID_ARTICLE"), new FieldPath(p, "PV_HT"), new FieldPath(p, "QTE_LIVREE"), new FieldPath(p, "QTE"),
new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p, "LIVRE_FORCED"), new FieldPath(p, "LIVRE"));
}
};
lAttente.getColumns().add(colAvancementLiv);
colAvancementLiv.setRenderer(new PercentTableCellRenderer());
 
final BaseSQLTableModelColumn colAvancementCmd = new BaseSQLTableModelColumn("Commande", BigDecimal.class) {
 
@Override
420,6 → 439,32
return pane;
}
 
private BigDecimal getAvancementLFromBL(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("DEVIS_ELEMENT"));
BigDecimal totalQte = BigDecimal.ZERO;
BigDecimal totalQteL = BigDecimal.ZERO;
for (SQLRowAccessor row : rows) {
BigDecimal qte = row.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(row.getInt("QTE")));
// On ne prend en compte que les articles ou les lignes différentes de 0
if (!row.isForeignEmpty("ID_ARTICLE") || row.getBigDecimal("PV_HT").signum() != 0) {
totalQte = totalQte.add(qte);
if (row.getBoolean("LIVRE_FORCED") || row.getBoolean("LIVRE")) {
totalQteL = totalQteL.add(qte);
} else if (row.getBigDecimal("QTE_LIVREE") != null) {
final BigDecimal qteLivree = row.getBigDecimal("QTE_LIVREE");
if (qteLivree != null) {
totalQteL = totalQteL.add(qteLivree);
}
}
}
}
if (totalQte.signum() != 0) {
return totalQteL.divide(totalQte, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
} else {
return BigDecimal.ONE.movePointRight(2);
}
}
 
public Map<Integer, ListeAddPanel> getListePanel() {
return this.map;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/component/DevisSQLComponent.java
678,7 → 678,6
 
final TotalPanel totalTTC = new TotalPanel(this.table, fieldEco, this.fieldHT, fieldTVA, fieldTTC, textPortHT, this.textRemiseHT, fieldService, fieldHA, fieldDevise, poids, null,
(getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
 
cBottom.gridy = 0;
cBottom.gridx += 2;
cBottom.gridheight = 2;
1189,6 → 1188,10
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
rowVals.put("ID_TAXE_PORT", taxeDefault.getID());
}
if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
}
if (getTable().getFieldsName().contains("DATE_VALIDITE")) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
1364,6 → 1367,9
final SQLRow row = devis.getTable().getRow(idDevis);
final SQLRowValues rowVals = new SQLRowValues(devis.getTable());
rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
if (row.getObject("ID_TARIF") != null && !row.isForeignEmpty("ID_TARIF")) {
rowVals.put("ID_TARIF", row.getInt("ID_TARIF"));
}
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
 
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/TransferQuoteSQLElement.java
45,6 → 45,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transfer";
return createCodeOfPackage() + ".transfer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/EtatDevisSQLElement.java
66,6 → 66,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".state";
return createCodeOfPackage() + ".state";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisItemSQLElement.java
18,14 → 18,20
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.rights.NXRights;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.event.ActionEvent;
import java.util.ArrayList;
42,6 → 48,11
}
 
@Override
protected synchronized void _initTableSource(final SQLTableModelSource table) {
super._initTableSource(table);
}
 
@Override
protected String getParentFFName() {
 
return "ID_DEVIS";
105,6 → 116,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisSQLElement.java
24,6 → 24,7
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.core.sales.quote.ui.QuoteEditGroup;
import org.openconcerto.erp.core.sales.quote.ui.QuoteSQLComponent;
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
41,6 → 42,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
62,7 → 64,7
import org.openconcerto.ui.light.ColumnSpec;
import org.openconcerto.ui.light.ColumnsSpec;
import org.openconcerto.ui.light.CustomEditorProvider;
import org.openconcerto.ui.light.LightControler;
import org.openconcerto.ui.light.LightController;
import org.openconcerto.ui.light.LightUIButtonUnmanaged;
import org.openconcerto.ui.light.LightUIComboBox;
import org.openconcerto.ui.light.LightUIElement;
93,6 → 95,7
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
138,15 → 141,11
public String getPath() {
return this.getNumber() + "-" + this.getName();
}
};
}
 
public DevisSQLElement() {
this("un devis", "devis");
}
super(TABLENAME);
 
public DevisSQLElement(String singular, String plural) {
super(TABLENAME, singular, plural);
 
getRowActions().addAll(getDevisRowActions());
final QuoteEditGroup group = new QuoteEditGroup();
GlobalMapper.getInstance().map(QuoteSQLComponent.ID, group);
156,7 → 155,7
 
@Override
public Set<String> getReadOnlyFields() {
Set<String> s = new HashSet<String>();
Set<String> s = new HashSet<>();
s.add("T_ACOMPTE");
return s;
}
163,9 → 162,8
 
private List<RowAction> getDevisRowActions() {
 
List<RowAction> rowsActions = new ArrayList<RowAction>();
List<RowAction> rowsActions = new ArrayList<>();
 
// List<RowAction> list = new ArrayList<RowAction>();
// Transfert vers facture
RowAction factureAction = getDevis2FactureAction();
 
199,8 → 197,6
 
@Override
public void modified() {
// TODO Auto-generated method stub
 
}
 
@Override
214,14 → 210,10
 
@Override
public void deleted() {
// TODO Auto-generated method stub
 
}
 
@Override
public void cancelled() {
// TODO Auto-generated method stub
 
}
});
}
252,9 → 244,11
 
// Transfert vers commande
RowAction commandeAction = getDevis2CmdCliAction();
 
rowsActions.add(commandeAction);
 
RowAction blAction = getDevis2BlAction();
rowsActions.add(blAction);
 
RowAction accepteEtCmdAction = getAcceptAndCmdClientAction();
rowsActions.add(accepteEtCmdAction);
 
282,6 → 276,27
return rowsActions;
}
 
public RowAction getDevis2BlAction() {
return new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
 
final List<SQLRowValues> copySelectedRows = IListe.get(e).getSelectedRows();
transfertDevis(copySelectedRows, "BON_DE_LIVRAISON");
}
 
}, true, "sales.quote.create.customer.delivery") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getForeignID("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
return true;
}
}
return false;
}
};
}
 
public static void davBrowse(String s) throws Exception {
final boolean windows = System.getProperty("os.name").startsWith("Windows");
if (windows) {
307,10 → 322,11
editFrame.setVisible(true);
}
}, true, "sales.quote.clone") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
return (selection != null && selection.size() == 1);
}
};
};
}
 
public RowAction getRefuseAction() {
326,6 → 342,7
}
}
}, false, "sales.quote.refuse") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getForeignID("ID_ETAT_DEVIS") == EtatDevisSQLElement.EN_ATTENTE) {
333,8 → 350,8
}
}
return false;
}
};
};
}
 
public RowAction getAcceptAction() {
351,6 → 368,7
}
}
}, false, "sales.quote.accept") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
final int int1 = selection.get(0).getForeignID("ID_ETAT_DEVIS");
359,8 → 377,8
}
}
return false;
}
};
};
}
 
public RowAction getDevis2FactureAction() {
370,6 → 388,7
 
}
}, true, "sales.quote.create.invoice") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
boolean b = selection.size() > 0;
for (SQLRowAccessor sqlRowAccessor : selection) {
377,8 → 396,8
}
 
return b;
}
};
};
}
 
public RowAction getDevis2CmdFournAction() {
396,6 → 415,7
 
}
}, false, "sales.quote.create.supplier.order") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getForeignID("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
403,8 → 423,8
}
}
return false;
}
};
};
}
 
public RowAction getDevis2CmdCliAction() {
416,6 → 436,7
}
 
}, true, "sales.quote.create.customer.order") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getForeignID("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
423,8 → 444,8
}
}
return false;
}
};
};
}
 
public RowAction getAcceptAndCmdClientAction() {
442,6 → 463,7
transfertCommandeClient(IListe.get(e).getSelectedRows());
}
}, false, "sales.quote.accept.create.customer.order") {
@Override
public boolean enabledFor(java.util.List<org.openconcerto.sql.model.SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getForeignID("ID_ETAT_DEVIS") == EtatDevisSQLElement.EN_ATTENTE) {
449,12 → 471,11
}
}
return false;
}
};
};
}
 
public void transfertCommandeClient(final List<SQLRowValues> copySelectedRows) {
 
public void transfertDevis(final List<SQLRowValues> copySelectedRows, final String destTable) {
SwingWorker<Boolean, Object> worker = new SwingWorker<Boolean, Object>() {
@Override
protected Boolean doInBackground() throws Exception {
462,10 → 483,10
final SQLTable tableTransfert = getTable().getTable("TR_DEVIS");
SQLRowValues rowVals = new SQLRowValues(tableTransfert);
rowVals.put("ID_DEVIS", new SQLRowValues(getTable()).put("NUMERO", null));
rowVals.put("ID_COMMANDE", null);
rowVals.put("ID_" + destTable, null);
rowVals.put("ID", null);
 
final List<Number> lID = new ArrayList<Number>();
final List<Number> lID = new ArrayList<>();
for (SQLRowValues sqlRowValues : copySelectedRows) {
lID.add(sqlRowValues.getID());
}
476,7 → 497,7
@Override
public SQLSelect transformChecked(SQLSelect input) {
Where w = new Where(tableTransfert.getField("ID_DEVIS"), lID);
w = w.and(new Where(tableTransfert.getField("ID_COMMANDE_CLIENT"), "IS NOT", (Object) null));
w = w.and(new Where(tableTransfert.getField("ID_" + destTable), "IS NOT", (Object) null));
input.setWhere(w);
return input;
}
493,13 → 514,13
numero = numero.substring(0, numero.length() - 2);
String label = "Attention ";
if (rows.size() > 1) {
label += " les devis " + numero + " ont déjà été transféré en commande!";
label += " les devis " + numero + " ont déjà été transféré!";
} else {
label += " le devis " + numero + " a déjà été transféré en commande!";
label += " le devis " + numero + " a déjà été transféré!";
}
label += "\n Voulez vous continuer?";
 
int ans = JOptionPane.showConfirmDialog(null, label, "Transfert devis en commande", JOptionPane.YES_NO_OPTION);
int ans = JOptionPane.showConfirmDialog(null, label, "Transfert devis", JOptionPane.YES_NO_OPTION);
if (ans == JOptionPane.NO_OPTION) {
return Boolean.FALSE;
}
515,10 → 536,39
try {
Boolean b = get();
if (b != null && b) {
TransfertBaseSQLComponent.openTransfertFrame(copySelectedRows, "COMMANDE_CLIENT");
EditFrame frame = TransfertBaseSQLComponent.openTransfertFrame(copySelectedRows, destTable);
if (destTable.equalsIgnoreCase("BON_DE_LIVRAISON")) {
BonDeLivraisonSQLComponent comp = (BonDeLivraisonSQLComponent) frame.getSQLComponent();
final SQLTable tableElt = comp.getElement().getTable().getTable("BON_DE_LIVRAISON_ELEMENT");
SQLRowValues rowVals = new SQLRowValues(tableElt);
rowVals.put("QTE_UNITAIRE", null);
rowVals.put("QTE", null);
rowVals.put("QTE_LIVREE", null);
rowVals.put("ID_ARTICLE", null);
rowVals.put("PV_HT", null);
rowVals.put("ID_DEVIS_ELEMENT", null);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
List<Integer> ids = new ArrayList<>(copySelectedRows.size());
for (SQLRowValues sqlRowValues : copySelectedRows) {
ids.add(sqlRowValues.getID());
}
SQLSelectJoin joinBR = input.addJoin("RIGHT", tableElt.getTable("BON_DE_LIVRAISON_ELEMENT").getField("ID_BON_DE_LIVRAISON"));
SQLSelectJoin joinTR = input.addBackwardJoin("RIGHT", tableElt.getTable("TR_DEVIS").getField("ID_BON_DE_LIVRAISON"), joinBR.getJoinedTable().getAlias());
joinTR.setWhere(new Where(joinTR.getJoinedTable().getField("ID_DEVIS"), ids));
System.err.println(input.asString());
return input;
}
});
comp.loadQuantity(fetcher.fetch(), "DEVIS_ELEMENT");
}
}
} catch (Exception e) {
ExceptionHandler.handle("Erreur lors du transfert des devis en commande!", e);
ExceptionHandler.handle("Erreur lors du transfert des devis!", e);
}
super.done();
}
526,8 → 576,13
worker.execute();
}
 
public void transfertCommandeClient(final List<SQLRowValues> copySelectedRows) {
transfertDevis(copySelectedRows, "COMMANDE_CLIENT");
}
 
@Override
protected List<String> getComboFields() {
List<String> l = new ArrayList<String>();
List<String> l = new ArrayList<>(1);
l.add("NUMERO");
return l;
}
541,7 → 596,7
SQLTable tableCmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT").getTable();
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
List<SQLRow> rows = row.getReferentRows(elt.getTable());
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
final ListMap<SQLRow, SQLRowValues> map = new ListMap<>();
SQLRow rowDeviseF = null;
for (SQLRow sqlRow : rows) {
// on récupére l'article qui lui correspond
562,8 → 617,8
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE"), DecimalUtils.HIGH_PRECISION)));
rowValsElt.put("T_PA_TTC",
((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal(rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC", ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(BigDecimal.valueOf(rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0),
DecimalUtils.HIGH_PRECISION));
 
// gestion de la devise
rowDeviseF = sqlRow.getForeignRow("ID_DEVISE");
592,7 → 647,7
}
 
protected List<String> getListFields() {
List<String> l = new ArrayList<String>();
List<String> l = new ArrayList<>();
l.add("NUMERO");
l.add("DATE");
l.add("ID_CLIENT");
730,9 → 785,7
new LightUITextField("sales.quote.item.sales.unit.price"));
final ColumnSpec c7 = new ColumnSpec("sales.quote.item.quantity", Integer.class, "Quantité", new BigDecimal(1), true, new LightUITextField("sales.quote.item.quantity"));
 
final List<ColumnSpec> columnsSpec = new ArrayList<ColumnSpec>();
final List<String> possibleColumnIds = new ArrayList<String>();
 
final List<ColumnSpec> columnsSpec = new ArrayList<>(7);
columnsSpec.add(c1);
columnsSpec.add(c2);
columnsSpec.add(c3);
740,7 → 793,7
columnsSpec.add(c5);
columnsSpec.add(c6);
columnsSpec.add(c7);
 
final List<String> possibleColumnIds = new ArrayList<>(columnsSpec.size());
for (ColumnSpec c : columnsSpec) {
possibleColumnIds.add(c.getId());
}
819,7 → 872,7
// send: id,value
final SQLElement elem = configuration.getDirectory().getElement("DEVIS_ELEMENT");
final SQLTable table = elem.getTable();
final List<String> fieldsToFetch = new ArrayList<String>();
final List<String> fieldsToFetch = new ArrayList<>();
for (ColumnSpec cs : columnsSpec) {
String colId = cs.getId();
SQLField f = configuration.getFieldMapper().getSQLFieldForItem(colId);
834,27 → 887,25
final ListSQLRequest req = elem.createListRequest(fieldsToFetch, where, configuration.getShowAs());
List<SQLRowValues> fetchedRows = req.getValues();
 
List<Row> rows = new ArrayList<Row>();
List<Row> rows = new ArrayList<>();
for (final SQLRowValues vals : fetchedRows) {
Row r = new Row(vals.getID(), columnsSpec.size());
List<Object> values = new ArrayList<Object>();
List<Object> values = new ArrayList<>();
for (ColumnSpec cs : columnsSpec) {
String colId = cs.getId();
SQLField f = configuration.getFieldMapper().getSQLFieldForItem(colId);
if (f != null) {
Object object = vals.getObject(f.getName());
System.out.println("DevisSQLElement.getItemsCustomEditorProvider(...).createUIElement()" + f.getName() + ":" + object + ":" + object.getClass().getCanonicalName());
if (object instanceof SQLRowValues) {
SQLRowValues sqlRowValues = (SQLRowValues) object;
long rowId = sqlRowValues.getIDNumber().longValue();
List<SQLField> fieldsToExpand = configuration.getShowAs().getFieldExpand(sqlRowValues.getTable());
String strValue = "";
final StringBuilder b = new StringBuilder();
for (SQLField sqlField : fieldsToExpand) {
strValue += sqlRowValues.getObject(sqlField.getName()).toString() + " ";
b.append(sqlRowValues.getObject(sqlField.getName()).toString());
b.append(' ');
}
strValue = strValue.trim();
StringWithId str = new StringWithId(rowId, strValue);
object = str;
object = new StringWithId(rowId, b.toString().trim());
}
values.add(object);
} else {
884,33 → 935,33
LightUIButtonUnmanaged b1 = new LightUIButtonUnmanaged("up");
b1.setIcon("up.png");
panel.addControler(new ActivationOnSelectionControler(id, b1.getId()));
panel.addControler(new LightControler(LightControler.TYPE_UP, id, b1.getId()));
panel.addControler(new LightController(LightController.TYPE_UP, id, b1.getId()));
toolbarLine.addChild(b1);
 
final LightUIButtonUnmanaged b2 = new LightUIButtonUnmanaged("down");
b2.setIcon("down.png");
panel.addControler(new ActivationOnSelectionControler(id, b2.getId()));
panel.addControler(new LightControler(LightControler.TYPE_DOWN, id, b2.getId()));
panel.addControler(new LightController(LightController.TYPE_DOWN, id, b2.getId()));
toolbarLine.addChild(b2);
// Add
LightUIElement addButton = new LightUIButtonUnmanaged("add", "Ajouter une ligne");
panel.addControler(new LightControler(LightControler.TYPE_ADD_DEFAULT, id, addButton.getId()));
panel.addControler(new LightController(LightController.TYPE_ADD_DEFAULT, id, addButton.getId()));
toolbarLine.addChild(addButton);
// Insert
LightUIElement insertButton = new LightUIButtonUnmanaged("insert", "Insérer une ligne");
panel.addControler(new LightControler(LightControler.TYPE_INSERT_DEFAULT, id, insertButton.getId()));
panel.addControler(new LightController(LightController.TYPE_INSERT_DEFAULT, id, insertButton.getId()));
toolbarLine.addChild(insertButton);
 
// Copy
LightUIElement copyButton = new LightUIButtonUnmanaged("copy", "Dupliquer");
panel.addControler(new ActivationOnSelectionControler(id, copyButton.getId()));
panel.addControler(new LightControler(LightControler.TYPE_COPY, id, copyButton.getId()));
panel.addControler(new LightController(LightController.TYPE_COPY, id, copyButton.getId()));
toolbarLine.addChild(copyButton);
 
// Remove
LightUIElement removeButton = new LightUIButtonUnmanaged("remove", "Supprimer");
panel.addControler(new ActivationOnSelectionControler(id, removeButton.getId()));
panel.addControler(new LightControler(LightControler.TYPE_REMOVE, id, removeButton.getId()));
panel.addControler(new LightController(LightController.TYPE_REMOVE, id, removeButton.getId()));
toolbarLine.addChild(removeButton);
 
panel.addChild(toolbarLine);
928,4 → 979,9
});
return map;
}
 
@Override
protected String createCode() {
return "sales.quote";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisLogMailSQLElement.java
36,4 → 36,9
public DevisLogMailSQLElement(final DBRoot root) {
super((SQLTable) root.getCheckedChild(TABLENAME).getJDBC(), TO_OWNER_FIELDNAME);
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".log";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/component/ReferenceArticleSQLComponent.java
21,12 → 21,17
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.ArticleCodeClientTable;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.SupplierPriceListTable;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ArticleCategorieComptableTable;
import org.openconcerto.erp.core.sales.product.ui.ArticleDesignationTable;
import org.openconcerto.erp.core.sales.product.ui.ArticleTarifTable;
import org.openconcerto.erp.core.sales.product.ui.ProductItemListTable;
import org.openconcerto.erp.core.sales.product.ui.ProductQtyPriceListTable;
import org.openconcerto.erp.core.sales.product.ui.RowValuesTableEditionPanel;
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
38,9 → 43,11
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 org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.TitledSeparator;
47,6 → 54,7
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.preferences.DefaultProps;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
61,6 → 69,7
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
97,9 → 106,15
private ArticleDesignationTable tableDes = new ArticleDesignationTable();
private ArticleCodeClientTable tableCodeClient = new ArticleCodeClientTable();
private ArticleTarifTable tableTarifVente = new ArticleTarifTable(this);
private ArticleCategorieComptableTable tableCatComptable = new ArticleCategorieComptableTable();
private SupplierPriceListTable tableFourSec = new SupplierPriceListTable();
 
private ProductQtyPriceListTable tableTarifQteVente = new ProductQtyPriceListTable(this);
private ProductItemListTable tableBom;
private final JTextField textMarge = new JTextField(15);
private final JTextField textMarge = new JTextField(10);
private final JLabel labelMarge = new JLabel("% ");
private ElementComboBox boxCR;
private JCheckBox boxMargeWithCR;
 
private DocumentListener pieceHAArticle = new SimpleDocumentListener() {
 
139,10 → 154,19
ReferenceArticleSQLComponent.this.textMarge.getDocument().removeDocumentListener(ReferenceArticleSQLComponent.this.listenerMargeTextMarge);
if (ReferenceArticleSQLComponent.this.textPVHT.getText().trim().length() > 0 && ReferenceArticleSQLComponent.this.textPAHT.getText().trim().length() > 0) {
final BigDecimal vt = StringUtils.getBigDecimalFromUserText(ReferenceArticleSQLComponent.this.textPVHT.getText());
final BigDecimal ha = StringUtils.getBigDecimalFromUserText(ReferenceArticleSQLComponent.this.textPAHT.getText());
BigDecimal ha = StringUtils.getBigDecimalFromUserText(ReferenceArticleSQLComponent.this.textPAHT.getText());
 
if (vt != null && ha != null) {
if (vt.signum() != 0 && ha.signum() != 0) {
 
if (boxMargeWithCR.isSelected() && boxCR != null) {
SQLRow rowCR = boxCR.getSelectedRow();
if (rowCR != null && !rowCR.isUndefined()) {
BigDecimal cr = rowCR.getBigDecimal("POURCENT");
ha = ha.multiply(cr.movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
}
}
 
BigDecimal margeHT = vt.subtract(ha);
 
BigDecimal value;
162,6 → 186,7
} else {
ReferenceArticleSQLComponent.this.textMarge.setText("0");
}
labelMarge.setText("% (" + StringUtils.leftAlign(margeHT.setScale(2, RoundingMode.HALF_UP).toString(), 9) + ")");
}
}
}
184,18 → 209,34
BigDecimal ha = StringUtils.getBigDecimalFromUserText(this.textPAHT.getText());
if (ha != null && this.textMarge.getText().trim().length() > 0) {
 
if (boxMargeWithCR.isSelected() && boxCR != null) {
SQLRow rowCR = this.boxCR.getSelectedRow();
if (rowCR != null && !rowCR.isUndefined()) {
BigDecimal cr = rowCR.getBigDecimal("POURCENT");
ha = ha.multiply(cr.movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
}
}
 
BigDecimal d = StringUtils.getBigDecimalFromUserText(this.textMarge.getText());
if (d == null) {
d = BigDecimal.ZERO;
}
final BigDecimal vt;
if (DefaultNXProps.getInstance().getBooleanValue(TotalPanel.MARGE_MARQUE, false)) {
final BigDecimal e = BigDecimal.ONE.subtract(d.divide(BigDecimal.valueOf(100), DecimalUtils.HIGH_PRECISION));
if (e.signum() == 0) {
this.textPVHT.setText("0");
vt = BigDecimal.ZERO;
} else {
this.textPVHT.setText(ha.divide(e, DecimalUtils.HIGH_PRECISION).setScale(getTable().getField("PV_HT").getType().getDecimalDigits(), RoundingMode.HALF_UP).toString());
vt = ha.divide(e, DecimalUtils.HIGH_PRECISION).setScale(getTable().getField("PV_HT").getType().getDecimalDigits(), RoundingMode.HALF_UP);
}
} else {
BigDecimal result = ha.multiply(d.divide(BigDecimal.valueOf(100), DecimalUtils.HIGH_PRECISION).add(BigDecimal.ONE));
this.textPVHT.setText(result.setScale(getTable().getField("PV_HT").getType().getDecimalDigits(), RoundingMode.HALF_UP).toString());
vt = result.setScale(getTable().getField("PV_HT").getType().getDecimalDigits(), RoundingMode.HALF_UP);
this.textPVHT.setText(vt.toString());
}
this.textPVHT.setText(vt.toString());
BigDecimal margeHT = vt.subtract(ha);
labelMarge.setText("% (" + StringUtils.leftAlign(margeHT.setScale(2, RoundingMode.HALF_UP).toString(), 9) + ")");
}
}
}
214,6 → 255,8
this.checkObs.setVisible(true);
this.tableTarifVente.setArticleValues(r);
this.tableTarifVente.insertFrom("ID_ARTICLE", r.getID());
this.tableCatComptable.insertFrom("ID_ARTICLE", r.getID());
this.tableFourSec.insertFrom("ID_ARTICLE", r.getID());
this.tableTarifQteVente.insertFrom("ID_ARTICLE", r.getID());
if (this.tableBom != null) {
this.tableBom.insertFrom("ID_ARTICLE_PARENT", r.getID());
306,6 → 349,7
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
c.gridy++;
final ElementComboBox boxUnite = new ElementComboBox();
if (gestionUV) {
c.gridx = 0;
c.weightx = 0;
313,7 → 357,6
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
ElementComboBox boxUnite = new ElementComboBox();
DefaultGridBagConstraints.lockMinimumSize(boxUnite);
this.add(boxUnite, c);
this.addView(boxUnite, "ID_UNITE_VENTE");
330,6 → 373,35
this.addView(fieldSKU, "SKU");
c.fill = GridBagConstraints.HORIZONTAL;
 
c.gridy++;
if (gestionUV) {
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel(getLabelFor("QTE_UNITAIRE"), SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
final JTextField qte = new JTextField(10);
qte.setEditable(false);
 
this.add(qte, c);
this.addView(qte, "QTE_UNITAIRE", REQ);
boxUnite.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!boxUnite.isEmpty() && boxUnite.getSelectedId() == UniteVenteArticleSQLElement.A_LA_PIECE) {
qte.setText("1");
qte.setEditable(false);
} else {
qte.setEditable(true);
}
 
}
});
c.fill = GridBagConstraints.HORIZONTAL;
}
 
DefaultProps props = DefaultNXProps.getInstance();
 
// Article détaillé
460,8 → 532,19
ElementComboBox boxTaxeCompl = new ElementComboBox();
panel.add(boxTaxeCompl, c);
 
c.weightx = 0;
c.gridy++;
c.gridx = 0;
JLabel labelMatiere = new JLabel(getLabelFor("MATIERE"));
c.fill = GridBagConstraints.BOTH;
panel.add(labelMatiere, c);
c.weightx = 1;
c.gridx++;
SQLTextCombo comboMatiere = new SQLTextCombo();
panel.add(comboMatiere, c);
 
c.gridy++;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
TitledSeparator sep = new TitledSeparator(getLabelFor("INFOS"));
panel.add(sep, c);
472,6 → 555,7
panel.add(infos, c);
 
this.addSQLObject(infos, "INFOS");
this.addSQLObject(comboMatiere, "MATIERE");
this.addSQLObject(box, "ID_ECO_CONTRIBUTION");
this.addSQLObject(boxTaxeCompl, "ID_TAXE_COMPLEMENTAIRE");
return panel;
640,17 → 724,31
}
});
 
c.gridwidth = 1;
if (gestionStockMin) {
boolean visibleDepot = (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false));
c.gridx = 0;
c.gridy++;
c.weightx = 0;
panel.add(new JLabel(getLabelFor("QTE_MIN")), c);
final JLabel labelDepot = new JLabel(getLabelFor("ID_DEPOT_STOCK"));
panel.add(labelDepot, c);
labelDepot.setVisible(visibleDepot);
c.gridx++;
c.weightx = 1;
panel.add(fieldQteMin, c);
this.addView(fieldQteMin, "QTE_MIN");
ElementComboBox boxDepot = new ElementComboBox();
panel.add(boxDepot, c);
boxDepot.setVisible(visibleDepot);
this.addView(boxDepot, "ID_DEPOT_STOCK", REQ);
 
c.gridwidth = 1;
if (gestionStockMin) {
// c.gridx = 0;
// c.gridy++;
// c.weightx = 0;
// panel.add(new JLabel(getLabelFor("QTE_MIN")), c);
// c.gridx++;
// c.weightx = 1;
// panel.add(fieldQteMin, c);
// this.addView(fieldQteMin, "QTE_MIN");
 
c.gridx = 0;
c.gridy++;
c.weightx = 0;
700,12 → 798,16
this.addView(selAchat, "ID_COMPTE_PCE_ACHAT");
 
c.gridy++;
c.gridx = 0;
c.weighty = 1;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
final JPanel spacer = new JPanel();
spacer.setOpaque(false);
panel.add(spacer, c);
c.gridwidth = GridBagConstraints.REMAINDER;
 
panel.add(createCategorieComptablePanel(), c);
// final JPanel spacer = new JPanel();
// spacer.setOpaque(false);
// panel.add(spacer, c);
return panel;
}
 
752,14 → 854,86
}
});
} else {
 
// Tarif fournisseur
c.gridy++;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
TitledSeparator sep = new TitledSeparator("Tarifs fournisseurs");
panel.add(sep, c);
 
// Ajout fournisseur
c.gridwidth = 1;
c.weightx = 0;
c.gridy++;
c.gridx = 0;
panel.add(new JLabel("Ajouter le fournisseur "), c);
 
final ElementComboBox boxF = new ElementComboBox();
boxF.init(Configuration.getInstance().getDirectory().getElement("FOURNISSEUR"));
 
c.gridx++;
panel.add(boxF, c);
 
c.fill = GridBagConstraints.NONE;
c.gridx++;
JButton buttonAjouter = new JButton("Ajouter");
buttonAjouter.setOpaque(false);
panel.add(buttonAjouter, c);
c.gridx++;
JButton buttonSupprimer = new JButton("Supprimer");
buttonSupprimer.setOpaque(false);
panel.add(buttonSupprimer, c);
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.weightx = 1;
c.gridy++;
c.gridx = 0;
c.fill = GridBagConstraints.BOTH;
final JPanel spacer = new JPanel();
spacer.setOpaque(false);
panel.add(spacer, c);
this.tableFourSec.setOpaque(false);
panel.add(this.tableFourSec, c);
 
// Listeners
buttonAjouter.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
 
SQLRow rowCat = boxF.getSelectedRow();
if (rowCat == null || rowCat.isUndefined()) {
return;
}
int nbRows = tableFourSec.getModel().getRowCount();
 
// for (int i = 0; i < nbRows; i++) {
// SQLRowValues rowVals = tableFourSec.getModel().getRowValuesAt(i);
// int idTarif =
// Integer.parseInt(rowVals.getObject("ID_FOURNISSEUR").toString());
// if (idTarif == rowCat.getID()) {
// JOptionPane.showMessageDialog(null, "Impossible d'ajouter.\nLe fournisseur
// est déjà présent dans la liste!");
// return;
// }
// }
 
SQLRowValues rowVals = new SQLRowValues(Configuration.getInstance().getBase().getTable("ARTICLE_TARIF_FOURNISSEUR"));
if (getSelectedID() > 1) {
rowVals.put("ID_ARTICLE", getSelectedID());
}
rowVals.put("ID_FOURNISSEUR", rowCat.getID());
tableFourSec.getModel().addRow(rowVals);
}
});
buttonSupprimer.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
tableFourSec.removeSelectedRow();
}
});
}
return panel;
}
 
887,6 → 1061,83
return panel;
}
 
private JPanel createCategorieComptablePanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setOpaque(false);
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Ajout catégorie
c.gridwidth = 1;
c.weightx = 0;
c.gridy++;
c.gridx = 0;
panel.add(new JLabel("Ajouter la catégorie "), c);
 
final ElementComboBox boxCat = new ElementComboBox();
boxCat.init(Configuration.getInstance().getDirectory().getElement("CATEGORIE_COMPTABLE"));
 
c.gridx++;
panel.add(boxCat, c);
 
c.fill = GridBagConstraints.NONE;
c.gridx++;
JButton buttonAjouter = new JButton("Ajouter");
buttonAjouter.setOpaque(false);
panel.add(buttonAjouter, c);
c.gridx++;
JButton buttonSupprimer = new JButton("Supprimer");
buttonSupprimer.setOpaque(false);
panel.add(buttonSupprimer, c);
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridy++;
c.gridx = 0;
c.fill = GridBagConstraints.BOTH;
this.tableCatComptable.setOpaque(false);
panel.add(this.tableCatComptable, c);
 
// Listeners
buttonAjouter.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
 
SQLRow rowCat = boxCat.getSelectedRow();
if (rowCat == null || rowCat.isUndefined()) {
return;
}
int nbRows = tableCatComptable.getModel().getRowCount();
 
for (int i = 0; i < nbRows; i++) {
SQLRowValues rowVals = tableCatComptable.getModel().getRowValuesAt(i);
int idTarif = Integer.parseInt(rowVals.getObject("ID_CATEGORIE_COMPTABLE").toString());
if (idTarif == rowCat.getID()) {
JOptionPane.showMessageDialog(null, "Impossible d'ajouter.\nLa catégorie est déjà présente dans la liste!");
return;
}
}
 
SQLRowValues rowVals = new SQLRowValues(Configuration.getInstance().getBase().getTable("ARTICLE_CATEGORIE_COMPTABLE"));
if (getSelectedID() > 1) {
rowVals.put("ID_ARTICLE", getSelectedID());
}
rowVals.put("ID_CATEGORIE_COMPTABLE", rowCat.getID());
tableCatComptable.getModel().addRow(rowVals);
}
});
buttonSupprimer.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
tableCatComptable.removeSelectedRow();
}
});
return panel;
}
 
private JPanel createBOMpanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setOpaque(false);
997,7 → 1248,7
this.textMarge.getDocument().addDocumentListener(this.listenerMargeTextMarge);
cAchat.gridx++;
cAchat.weightx = 0;
p.add(new JLabel("% "), cAchat);
p.add(this.labelMarge, cAchat);
 
// Poids
JLabel labelPds = new JLabel(getLabelFor("POIDS"));
1026,7 → 1277,58
c.fill = GridBagConstraints.NONE;
 
this.add(p, c);
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
 
if (getTable().contains("ID_COUT_REVIENT")) {
// Cout de revient
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel(getLabelFor("ID_COUT_REVIENT"), SwingConstants.RIGHT), c);
 
JPanel pCR = new JPanel(new GridBagLayout());
GridBagConstraints cCR = new DefaultGridBagConstraints();
cCR.insets = new Insets(0, 0, 0, 4);
this.boxCR = new ElementComboBox(true, 15);
 
pCR.add(boxCR, cCR);
this.addView(boxCR, "ID_COUT_REVIENT");
DefaultGridBagConstraints.lockMinimumSize(boxCR);
boxCR.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!isFilling()) {
ReferenceArticleSQLComponent.this.textPVHT.getDocument().removeDocumentListener(ReferenceArticleSQLComponent.this.listenerMargeTextVT);
updateVtFromMarge();
ReferenceArticleSQLComponent.this.textPVHT.getDocument().addDocumentListener(ReferenceArticleSQLComponent.this.listenerMargeTextVT);
}
}
});
cCR.gridx++;
this.boxMargeWithCR = new JCheckBox(getLabelFor("MARGE_WITH_COUT_REVIENT"));
pCR.add(boxMargeWithCR, cCR);
addView(boxMargeWithCR, "MARGE_WITH_COUT_REVIENT");
boxMargeWithCR.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (!isFilling()) {
ReferenceArticleSQLComponent.this.textPVHT.getDocument().removeDocumentListener(ReferenceArticleSQLComponent.this.listenerMargeTextVT);
updateVtFromMarge();
ReferenceArticleSQLComponent.this.textPVHT.getDocument().addDocumentListener(ReferenceArticleSQLComponent.this.listenerMargeTextVT);
}
}
});
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
this.add(pCR, c);
}
 
// PV HT
c.gridx = 0;
c.gridy++;
1121,11 → 1423,13
this.taxeListener = new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
if (!isFilling()) {
if (ReferenceArticleSQLComponent.this.textPVHT.getText().trim().length() > 0) {
setTextTTC();
} else {
setTextHT();
}
}
tableTarifVente.fireModification();
}
};
1258,8 → 1562,11
 
@Override
public void update() {
SQLRow row = this.getTable().getRow(this.getSelectedID());
super.update();
this.tableTarifVente.updateField("ID_ARTICLE", getSelectedID());
this.tableCatComptable.updateField("ID_ARTICLE", getSelectedID());
this.tableFourSec.updateField("ID_ARTICLE", getSelectedID());
this.tableTarifQteVente.updateField("ID_ARTICLE", getSelectedID());
if (this.tableBom != null) {
this.tableBom.updateField("ID_ARTICLE_PARENT", getSelectedID());
1270,8 → 1577,26
if (this.codeFournisseurTable != null) {
this.codeFournisseurTable.updateField("ID_ARTICLE", getSelectedID());
}
 
((ReferenceArticleSQLElement) getElement()).initStock(getSelectedID());
 
SQLSelect sel = new SQLSelect();
SQLTable tableStock = getTable().getTable("STOCK");
sel.addSelect(tableStock.getKey());
Where w = new Where(tableStock.getField("ID_ARTICLE"), "=", getSelectedID()).and(new Where(tableStock.getField("ID_DEPOT_STOCK"), "=", row.getForeignID("ID_DEPOT_STOCK")));
sel.setWhere(w);
 
List<SQLRow> stock = SQLRowListRSH.execute(sel);
if (stock != null && stock.size() == 1) {
try {
row.createEmptyUpdateRow().put("ID_STOCK", stock.get(0).getID()).update();
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la mise à jour du stock principal", e);
}
}
 
}
 
/**
* Sélection d'un mode de vente pour l'article. Affiche les prix metriques requis et fixe les
* valeurs.
1324,6 → 1649,8
public int insert(SQLRow order) {
int id = super.insert(order);
this.tableTarifVente.updateField("ID_ARTICLE", id);
this.tableCatComptable.updateField("ID_ARTICLE", id);
this.tableFourSec.updateField("ID_ARTICLE", id);
this.tableTarifQteVente.updateField("ID_ARTICLE", id);
if (this.tableBom != null) {
this.tableBom.updateField("ID_ARTICLE_PARENT", id);
1333,6 → 1660,7
if (this.codeFournisseurTable != null) {
this.codeFournisseurTable.updateField("ID_ARTICLE", id);
}
((ReferenceArticleSQLElement) getElement()).initStock(id);
return id;
}
 
1341,12 → 1669,16
SQLRowValues rowVals = new SQLRowValues(getTable());
 
rowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
rowVals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
rowVals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
rowVals.put("QTE_UNITAIRE", BigDecimal.ONE);
rowVals.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
selectModeVente(ReferenceArticleSQLElement.A_LA_PIECE);
rowVals.put("VALEUR_METRIQUE_1", Float.valueOf("1.0"));
rowVals.put("PA_HT", BigDecimal.ZERO);
rowVals.put("QTE_UNITAIRE", BigDecimal.ONE);
rowVals.put("POIDS", Float.valueOf(0));
rowVals.put("GESTION_STOCK", Boolean.TRUE);
 
return rowVals;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleFournisseurSecondaireSQLElement.java
New file
0,0 → 1,89
/*
* 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.sql.sqlobject.ElementComboBox;
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.SwingConstants;
 
public class ArticleFournisseurSecondaireSQLElement extends ComptaSQLConfElement {
 
public ArticleFournisseurSecondaireSQLElement() {
super("ARTICLE_FOURNISSEUR_SECONDAIRE", "une liaison article fournisseur", "liaisons article fournisseur");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_FOURNISSEUR");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_FOURNISSEUR");
return l;
}
 
@Override
protected String getParentFFName() {
return "ID_ARTICLE";
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Famille père
final JLabel labelLangue = new JLabel(getLabelFor("ID_ARTICLE"), SwingConstants.RIGHT);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
this.add(labelLangue, c);
 
final ElementComboBox artBox = new ElementComboBox(true, 25);
DefaultGridBagConstraints.lockMinimumSize(artBox);
c.gridx++;
c.weightx = 1;
this.add(artBox, c);
 
this.addSQLObject(artBox, "ID_ARTICLE");
}
 
};
}
 
@Override
protected String createCode() {
return createCodeOfPackage() + ".supplier";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ReliquatSQLElement.java
48,7 → 48,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".reliquatbr";
return createCodeOfPackage() + ".reliquatbr";
}
}
 
187,6 → 187,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".reliquatbl";
return createCodeOfPackage() + ".reliquatbl";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/UniteVenteArticleSQLElement.java
94,6 → 94,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".unit";
return createCodeOfPackage() + ".unit";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ModeVenteArticleSQLElement.java
72,6 → 72,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".sale";
return createCodeOfPackage() + ".sale";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/MetriqueSQLElement.java
80,6 → 80,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".quantity";
return createCodeOfPackage() + ".quantity";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ProductItemSQLElement.java
17,7 → 17,6
import org.openconcerto.erp.core.sales.product.component.ProductItemGroup;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.utils.ListMap;
 
import java.util.ArrayList;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/SupplierPriceListTable.java
New file
0,0 → 1,134
/*
* 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.
*/
/*
* 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.finance.accounting.model.CurrencyConverter;
import org.openconcerto.erp.core.sales.product.ui.CurrencyWithSymbolRenderer;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.view.list.CellDynamicModifier;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.RowValuesTablePanel;
import org.openconcerto.sql.view.list.SQLTableElement;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Vector;
 
public class SupplierPriceListTable extends RowValuesTablePanel {
 
public SupplierPriceListTable() {
init();
uiInit();
}
 
/**
*
*/
protected void init() {
final SQLElement eProductCost = getSQLElement();
final SQLTable productPropertyTable = eProductCost.getTable();
final List<SQLTableElement> list = new Vector<SQLTableElement>();
 
final SQLTableElement eSupplier = new SQLTableElement(productPropertyTable.getField("ID_FOURNISSEUR"));
list.add(eSupplier);
// list.add(new SQLTableElement(productPropertyTable.getField("REF_FOURNISSEUR")));
// list.add(new SQLTableElement(productPropertyTable.getField("TYPE_REAPPRO")));
// list.add(new SQLTableElement(productPropertyTable.getField("ACHETEUR")));
list.add(new SQLTableElement(productPropertyTable.getField("CODE_PAYS_ORIGINE")));
final SQLTableElement ePrixAchatDevise = new SQLTableElement(productPropertyTable.getField("PRIX_ACHAT_DEVISE_F"));
 
Path p = new Path(getSQLElement().getTable()).addForeignTable("FOURNISSEUR").addForeignField("ID_DEVISE");
ePrixAchatDevise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
list.add(ePrixAchatDevise);
final SQLTableElement ePrixAchat = new SQLTableElement(productPropertyTable.getField("PRIX_ACHAT"));
ePrixAchat.setRenderer(new CurrencyWithSymbolRenderer());
final CurrencyConverter c = new CurrencyConverter();
ePrixAchat.setModifier(new CellDynamicModifier() {
 
@Override
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
if (row.getObject("ID_FOURNISSEUR") == null) {
return row.getBigDecimal("PRIX_ACHAT_DEVISE_F");
}
 
final String supplierCurrency = row.getForeign("ID_FOURNISSEUR").getForeign("ID_DEVISE").getString("CODE");
final BigDecimal prixAchatDevice = row.getBigDecimal("PRIX_ACHAT_DEVISE_F");
if (prixAchatDevice == null) {
return BigDecimal.ZERO;
}
try {
BigDecimal p = c.convert(prixAchatDevice, supplierCurrency, c.getCompanyCurrencyCode(), new Date(), true);
return p.setScale(2, RoundingMode.HALF_UP);
} catch (Exception e) {
e.printStackTrace();
}
 
return BigDecimal.ZERO;
}
});
ePrixAchat.setEditable(false);
list.add(ePrixAchat);
ePrixAchatDevise.addModificationListener(ePrixAchat);
ePrixAchatDevise.addModificationListener(eSupplier);
// final SQLTableElement eConditions = new
// SQLTableElement(productPropertyTable.getField("CONDITIONS"));
// eConditions.setEditor(new JComboBoxCellEditor(new
// JComboBox(ReferenceArticleSQLElement.CONDITIONS)));
// list.add(eConditions);
list.add(new SQLTableElement(productPropertyTable.getField("QTE")));
list.add(new SQLTableElement(productPropertyTable.getField("DATE_PRIX")));
 
list.add(new SQLTableElement(productPropertyTable.getField("DELAI_REAPPRO")));
list.add(new SQLTableElement(productPropertyTable.getField("DELAI_TRANSPORT")));
// list.add(new SQLTableElement(productPropertyTable.getField("PRIORITE")));
 
this.defaultRowVals = new SQLRowValues(getSQLElement().getTable());
this.defaultRowVals.put("QTE", 1);
this.defaultRowVals.put("PRIORITE", 1);
 
this.model = new RowValuesTableModel(eProductCost, list, productPropertyTable.getField("ID_FOURNISSEUR"), false, this.defaultRowVals);
 
this.table = new RowValuesTable(this.model, null);
}
 
protected String multiply(List<String> asList) {
return null;
}
 
public SQLElement getSQLElement() {
return Configuration.getInstance().getDirectory().getElement("ARTICLE_TARIF_FOURNISSEUR");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/FamilleEcoContributionSQLElement.java
13,9 → 13,10
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.ConfSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ListMap;
 
27,12 → 28,17
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class FamilleEcoContributionSQLElement extends ConfSQLElement {
public class FamilleEcoContributionSQLElement extends ComptaSQLConfElement {
 
public FamilleEcoContributionSQLElement() {
super("FAMILLE_ECO_CONTRIBUTION");
public FamilleEcoContributionSQLElement(final DBRoot root) {
super(root.getTable("FAMILLE_ECO_CONTRIBUTION"));
}
 
@Override
protected String createCode() {
return this.createCodeOfPackage() + ".ewaste-family";
}
 
protected List<String> getListFields() {
final List<String> list = new ArrayList<String>(2);
list.add("NOM");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ReferenceArticleSQLElement.java
15,11 → 15,14
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.edm.AttachmentAction;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.reports.history.ui.HistoriqueArticleFrame;
import org.openconcerto.erp.core.sales.product.action.InventairePanel;
import org.openconcerto.erp.core.sales.product.component.ReferenceArticleSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
import org.openconcerto.erp.generationDoc.gestcomm.FicheArticleXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.preferences.DefaultNXProps;
37,6 → 40,7
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
46,8 → 50,10
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.PanelFrame;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
 
import java.awt.event.ActionEvent;
55,7 → 61,9
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.AbstractAction;
70,7 → 78,7
public static final int AU_METRE_LARGEUR = 6;
private static final int PRIX_HA = 1;
private static final int PRIX_VT = 2;
protected final PredicateRowAction stock;
protected PredicateRowAction stock;
 
public static final String[] CONDITIONS = new String[] { "CFR", "CIF", "CPT", "DAT", "DDP", "DDU", "EXW", "FCA", "FOB" };
 
83,7 → 91,13
@Override
public void actionPerformed(ActionEvent e) {
 
PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), IListe.get(e).getSelectedRows()), "Mise à jour des stocks");
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
List<SQLRowAccessor> l = new ArrayList<SQLRowAccessor>();
for (SQLRowValues sqlRowValues : selectedRows) {
l.add(sqlRowValues.asRow().getForeign("ID_STOCK"));
}
 
PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), l), "Mise à jour des stocks");
FrameUtil.show(p);
 
}
91,6 → 105,18
stock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(stock);
 
PredicateRowAction history = new PredicateRowAction(new AbstractAction("Historique") {
 
@Override
public void actionPerformed(ActionEvent e) {
HistoriqueArticleFrame frame = new HistoriqueArticleFrame(ReferenceArticleSQLElement.this);
frame.selectId(IListe.get(e).getSelectedId());
frame.setVisible(true);
}
}, false, true);
history.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(history);
 
PredicateRowAction clone = new PredicateRowAction(new AbstractAction("Dupliquer") {
 
@Override
112,6 → 138,7
 
PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction().getAction(), true);
actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
getRowActions().add(actionAttachment);
}
 
192,7 → 219,10
l.add("ID_FAMILLE_ARTICLE");
l.add("ID_FOURNISSEUR");
l.add("SKU");
 
// if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
l.add("ID_STOCK");
// }
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean b = Boolean.valueOf(val);
if (b != null && b.booleanValue()) {
208,7 → 238,7
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
res.add(null, "CODE_BARRE");
}
res.addAll(null, "NOM", "ID_FAMILLE_ARTICLE");
res.addAll(null, "CODE", "NOM", "ID_FAMILLE_ARTICLE");
return res;
}
 
384,6 → 414,7
SQLRowValues vals = new SQLRowValues(row);
BigDecimal taux = BigDecimal.ONE.add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f));
vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux));
vals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
int idArticle;
try {
 
494,8 → 525,70
&& rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
}
 
public void initStock(int id) {
SQLRow row = getTable().getRow(id);
SQLSelect sel = new SQLSelect();
sel.addSelectStar(getTable().getTable("DEPOT_STOCK"));
List<SQLRow> rowsDepot = SQLRowListRSH.execute(sel);
 
SQLSelect selStock = new SQLSelect();
selStock.addSelectStar(getTable().getTable("STOCK"));
selStock.setWhere(new Where(getTable().getTable("STOCK").getField("ID_ARTICLE"), "=", id));
List<SQLRow> rowsStock = SQLRowListRSH.execute(selStock);
Map<Integer, SQLRow> initedDepot = new HashMap<>();
for (SQLRow sqlRow : rowsStock) {
initedDepot.put(sqlRow.getForeignID("ID_DEPOT_STOCK"), sqlRow);
}
 
List<StockItem> stockItems = new ArrayList<StockItem>();
for (SQLRow sqlRow : rowsDepot) {
try {
if (!initedDepot.keySet().contains(sqlRow.getID())) {
SQLRowValues rowVals = new SQLRowValues(getTable().getTable("STOCK"));
rowVals.put("ID_ARTICLE", row.getID());
rowVals.put("ID_DEPOT_STOCK", sqlRow.getID());
 
SQLRow rowStock = rowVals.commit();
if ((row.getObject("ID_DEPOT_STOCK") == null || row.isForeignEmpty("ID_DEPOT_STOCK")) && sqlRow.getID() == DepotStockSQLElement.DEFAULT_ID) {
row.createEmptyUpdateRow().put("ID_STOCK", rowStock.getID()).put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID).commit();
} else if (sqlRow.getID() == row.getForeignID("ID_DEPOT_STOCK")) {
row.createEmptyUpdateRow().put("ID_STOCK", rowStock.getID()).commit();
}
stockItems.add(new StockItem(row, rowStock));
 
} else {
SQLRow rowExisting = initedDepot.get(sqlRow.getID());
if ((row.getObject("ID_DEPOT_STOCK") == null || row.isForeignEmpty("ID_DEPOT_STOCK")) && sqlRow.getID() == DepotStockSQLElement.DEFAULT_ID) {
row.createEmptyUpdateRow().put("ID_STOCK", rowExisting.getID()).put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID).commit();
} else if (sqlRow.getID() == row.getForeignID("ID_DEPOT_STOCK")) {
row.createEmptyUpdateRow().put("ID_STOCK", rowExisting.getID()).commit();
}
stockItems.add(new StockItem(row, rowExisting));
}
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de l'initialisation du stock de l'article", e);
}
}
if (row.getReferentRows(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT")).size() > 0) {
ComposedItemStockUpdater up = new ComposedItemStockUpdater(getTable().getDBRoot(), stockItems);
try {
up.updateNomenclature(stockItems);
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de l'actualisation du stock!", e);
}
}
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".ref";
return createCodeOfPackage() + ".ref";
}
 
@Override
protected void _initComboRequest(ComboSQLRequest req) {
super._initComboRequest(req);
req.addToGraphToFetch("ID_DEPOT_STOCK");
// req.addForeignToGraphToFetch("ID_DEPOT_STOCK", Arrays.asList("ID"));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleCatComptableSQLElement.java
New file
0,0 → 1,92
/*
* 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.sql.sqlobject.ElementComboBox;
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.SwingConstants;
 
public class ArticleCatComptableSQLElement extends ComptaSQLConfElement {
 
public ArticleCatComptableSQLElement() {
super("ARTICLE_CATEGORIE_COMPTABLE", "une liaison article catégorie comptable", "liaisons article catégorie comptable");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_CATEGORIE_COMPTABLE");
l.add("ID_COMPTE_PCE_VENTE");
l.add("ID_COMPTE_PCE_ACHAT");
l.add("ID_TAXE");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_CATEGORIE_COMPTABLE");
return l;
}
 
@Override
protected String getParentFFName() {
return "ID_ARTICLE";
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Famille père
final JLabel labelLangue = new JLabel(getLabelFor("ID_ARTICLE"), SwingConstants.RIGHT);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
this.add(labelLangue, c);
 
final ElementComboBox artBox = new ElementComboBox(true, 25);
DefaultGridBagConstraints.lockMinimumSize(artBox);
c.gridx++;
c.weightx = 1;
this.add(artBox, c);
 
this.addSQLObject(artBox, "ID_ARTICLE");
}
 
};
}
 
@Override
protected String createCode() {
return createCodeOfPackage() + ".compta";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/EcoContributionSQLElement.java
13,11 → 13,11
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.ConfSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ListMap;
 
29,12 → 29,17
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class EcoContributionSQLElement extends ConfSQLElement {
public class EcoContributionSQLElement extends ComptaSQLConfElement {
 
public EcoContributionSQLElement() {
super("ECO_CONTRIBUTION");
public EcoContributionSQLElement(final DBRoot root) {
super(root.getTable("ECO_CONTRIBUTION"));
}
 
@Override
protected String createCode() {
return this.createCodeOfPackage() + ".ewaste-tax";
}
 
protected List<String> getListFields() {
final List<String> list = new ArrayList<String>(2);
list.add("ID_FAMILLE_ECO_CONTRIBUTION");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/CoutRevientSQLElement.java
New file
0,0 → 1,104
/*
* 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.sql.element.BaseSQLComponent;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ListMap;
 
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 CoutRevientSQLElement extends ComptaSQLConfElement {
 
public CoutRevientSQLElement() {
super("COUT_REVIENT");
}
 
protected List<String> getListFields() {
final List<String> list = new ArrayList<String>(2);
list.add("CODE");
list.add("NOM");
list.add("POURCENT");
return list;
}
 
protected List<String> getComboFields() {
final List<String> list = new ArrayList<String>(2);
list.add("CODE");
list.add("NOM");
list.add("POURCENT");
return list;
}
 
@Override
public ListMap<String, String> getShowAs() {
return ListMap.singleton(null, "CODE");
 
}
 
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Code
final JLabel labelCode = new JLabel(getLabelFor("CODE"));
c.weightx = 0;
this.add(labelCode, c);
c.gridx++;
c.weightx = 1;
final JTextField textCode = new JTextField();
this.add(textCode, c);
 
// Nom
c.gridx++;
c.weightx = 0;
final JLabel labelNom = new JLabel(getLabelFor("NOM"));
this.add(labelNom, c);
c.gridx++;
c.weightx = 1;
final JTextField textNom = new JTextField();
this.add(textNom, c);
 
// Famille
c.gridy++;
c.gridx = 0;
c.weightx = 0;
 
final JLabel labelTaux = new JLabel(getLabelFor("POURCENT"));
this.add(labelTaux, c);
c.gridx++;
c.weightx = 1;
final JTextField textTaux = new JTextField();
this.add(textTaux, c);
 
this.addRequiredSQLObject(textTaux, "POURCENT");
this.addRequiredSQLObject(textNom, "NOM");
this.addRequiredSQLObject(textCode, "CODE");
}
};
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleDesignationSQLElement.java
99,6 → 99,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".name";
return createCodeOfPackage() + ".name";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleTarifSQLElement.java
72,6 → 72,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".price";
return createCodeOfPackage() + ".price";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/FamilleArticleSQLElement.java
201,6 → 201,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".family";
return createCodeOfPackage() + ".family";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleCodeClientSQLElement.java
77,7 → 77,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".customcode";
return createCodeOfPackage() + ".customcode";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/SupplierPriceListSQLElement.java
New file
0,0 → 1,62
/*
* 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.SQLComponent;
 
import java.util.ArrayList;
import java.util.List;
 
public class SupplierPriceListSQLElement extends ComptaSQLConfElement {
public static final String ELEMENT_CODE = "supplier.pricelist";
 
public SupplierPriceListSQLElement() {
super("ARTICLE_TARIF_FOURNISSEUR");
}
 
@Override
protected String createCode() {
return ELEMENT_CODE;
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_FOURNISSEUR");
l.add("QTE");
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("ID_FOURNISSEUR");
return l;
}
 
@Override
protected String getParentFFName() {
return "ID_ARTICLE";
}
 
@Override
protected SQLComponent createComponent() {
// TODO Auto-generated method stub
return null;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleSQLElement.java
18,11 → 18,13
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.element.BaseSQLComponent;
import org.openconcerto.sql.element.ElementSQLObject;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.GestionDevise;
50,8 → 52,9
super("ARTICLE", "un article", "articles");
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>();
 
l.add("CODE");
l.add("NOM");
65,7 → 68,11
l.add("VALEUR_METRIQUE_3");
l.add("PRIX_METRIQUE_HA_1");
l.add("PRIX_METRIQUE_VT_1");
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
 
if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
l.add("ID_STOCK");
}
 
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean b = Boolean.valueOf(val);
75,8 → 82,9
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("CODE");
l.add("NOM");
return l;
95,8 → 103,7
private JTextField textNom, textCode;
private JTextField textPoids;
private DocumentListener htDocListener, ttcDocListener;
private PropertyChangeListener taxeListener;
final ElementComboBox comboSelTaxe = new ElementComboBox(false);
private final ElementComboBox comboSelTaxe = new ElementComboBox(false);
 
public void addViews() {
 
136,7 → 143,7
 
};
 
this.taxeListener = new PropertyChangeListener() {
PropertyChangeListener taxeListener = new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
 
229,7 → 236,7
 
this.textPVHT.getDocument().addDocumentListener(this.htDocListener);
this.textPVTTC.getDocument().addDocumentListener(this.ttcDocListener);
this.comboSelTaxe.addValueListener(this.taxeListener);
this.comboSelTaxe.addValueListener(taxeListener);
}
 
private void setTextHT() {
268,4 → 275,9
}
};
}
 
@Override
protected String createCode() {
return "sales.product";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/action/InventairePanel.java
14,6 → 14,7
package org.openconcerto.erp.core.sales.product.action;
 
import org.openconcerto.erp.core.common.ui.NumericTextField;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
21,7 → 22,6
import org.openconcerto.sql.model.DBRoot;
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.utils.SQLUtils;
import org.openconcerto.sql.view.list.IListe;
60,7 → 60,7
private final String mvtStockTableQuoted;
private static String defaultLabel = "Mise à jour des stocks";
 
public InventairePanel(final IListe liste, final List<? extends SQLRowAccessor> articles) {
public InventairePanel(final IListe liste, final List<? extends SQLRowAccessor> stocks) {
super(new GridBagLayout());
final SQLTable mvtStockTable = Configuration.getInstance().getRoot().findTable("MOUVEMENT_STOCK");
this.mvtStockTableQuoted = mvtStockTable.getSQLName().quote();
158,16 → 158,14
fieldReel.getDocument().addDocumentListener(l);
fieldRecpAtt.getDocument().addDocumentListener(l);
 
if (articles.size() == 1) {
SQLRowAccessor r = articles.get(0);
if (!r.isForeignEmpty("ID_STOCK")) {
SQLRowAccessor stock = r.getForeign("ID_STOCK");
if (stocks.size() == 1) {
SQLRowAccessor r = stocks.get(0);
SQLRowAccessor stock = r;
fieldReel.setText(String.valueOf(stock.getFloat("QTE_REEL")));
fieldLivAtt.setText(String.valueOf(stock.getFloat("QTE_LIV_ATTENTE")));
fieldRecpAtt.setText(String.valueOf(stock.getFloat("QTE_RECEPT_ATTENTE")));
fieldTh.setText(String.valueOf(stock.getFloat("QTE_TH")));
}
}
 
c.gridy++;
c.gridx = 0;
202,14 → 200,21
List<List<String>> multipleRequests = new ArrayList<List<String>>();
List<String> multipleRequestsHundred = new ArrayList<String>(100);
boolean usePrice = mvtStockTable.contains("PRICE");
 
List<StockItem> stockItems = new ArrayList<StockItem>();
final Date dateValue = date.getValue();
for (SQLRowAccessor sqlRowAccessor : articles) {
for (SQLRowAccessor sqlRowAccessor : stocks) {
if (multipleRequestsHundred.size() > 100) {
multipleRequests.add(multipleRequestsHundred);
multipleRequestsHundred = new ArrayList<String>(100);
}
StockItem item = new StockItem(sqlRowAccessor);
StockItem item = new StockItem(sqlRowAccessor.getForeign("ID_ARTICLE"), sqlRowAccessor);
if (!item.isStockInit()) {
((ReferenceArticleSQLElement) liste.getSource().getElem().getDirectory().getElement("ARTICLE")).initStock(sqlRowAccessor.getForeignID("ID_ARTICLE"));
SQLRow rowArticle = sqlRowAccessor.getForeign("ID_ARTICLE").asRow();
rowArticle.fetchValues();
item = new StockItem(rowArticle, rowArticle.getForeign("ID_STOCK"));
}
stockItems.add(item);
boolean modified = false;
if (qteReel != null && !NumberUtils.areNumericallyEqual(qteReel, item.getRealQty())) {
double diff = qteReel.doubleValue() - item.getRealQty();
235,20 → 240,9
if (item.isStockInit()) {
multipleRequestsHundred.add(item.getUpdateRequest());
} else {
SQLRowValues rowVals = new SQLRowValues(sqlRowAccessor.getTable().getForeignTable("ID_STOCK"));
rowVals.put("QTE_REEL", item.getRealQty());
rowVals.put("QTE_TH", item.getVirtualQty());
rowVals.put("QTE_LIV_ATTENTE", item.getDeliverQty());
rowVals.put("QTE_RECEPT_ATTENTE", item.getReceiptQty());
SQLRowValues rowValsArt = item.getArticle().createEmptyUpdateRow();
rowValsArt.put("ID_STOCK", rowVals);
try {
rowValsArt.commit();
} catch (SQLException e1) {
e1.printStackTrace();
throw new IllegalStateException();
}
}
}
 
}
multipleRequests.add(multipleRequestsHundred);
269,12 → 263,12
 
final DBRoot root = mvtStockTable.getDBRoot();
if (root.contains("ARTICLE_ELEMENT")) {
List<StockItem> stockItems = new ArrayList<StockItem>();
for (SQLRowAccessor sqlRowAccessor2 : articles) {
final SQLRow asRow = sqlRowAccessor2.asRow();
asRow.fetchValues();
stockItems.add(new StockItem(asRow));
}
// List<StockItem> stockItems = new ArrayList<StockItem>();
// for (SQLRowAccessor sqlRowAccessor2 : stocks) {
// final SQLRow asRow = sqlRowAccessor2.asRow();
// asRow.fetchValues();
// stockItems.add(new StockItem(asRow));
// }
// Mise à jour des stocks des nomenclatures
ComposedItemStockUpdater comp = new ComposedItemStockUpdater(root, stockItems);
try {
292,14 → 286,14
 
private String getMvtRequest(Date time, BigDecimal prc, double qteFinal, StockItem item, String label, boolean reel, boolean usePrice) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"NOM\",\"REEL\",\"ORDRE\"";
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"NOM\",\"REEL\",\"ORDRE\"";
 
if (usePrice && prc != null) {
mvtStockQuery += ",\"PRICE\"";
}
 
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + ",'" + label + "'," + reel + ", (SELECT (MAX(\"ORDRE\")+1) FROM "
+ mvtStockTableQuoted + ")";
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + "," + item.stock.getID() + ",'" + label + "'," + reel
+ ", (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
if (usePrice && prc != null) {
mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/action/ListeDesArticlesAction.java
22,13 → 22,14
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
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.model.graph.Path;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.view.ListeAddPanel;
52,6 → 53,7
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
82,8 → 84,10
final FamilleArticlePanel panelFam = new FamilleArticlePanel(elt.getForeignElement("ID_FAMILLE_ARTICLE"));
 
final SQLTableModelSourceOnline createTableSource = elt.createTableSource();
SQLPreferences prefs = SQLPreferences.getMemCached(elt.getTable().getDBRoot());
 
SQLTableModelColumn colStock;
SQLTableModelColumn colStock = null;
// if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
if (elt.getTable().getDBRoot().contains("ARTICLE_PRIX_REVIENT")) {
colStock = createTableSource.getColumn(createTableSource.getColumns().size() - 2);
} else {
120,7 → 124,7
colStock.setRenderer(ComptaSQLConfElement.CURRENCY_RENDERER);
createTableSource.getColumns().add(colStock);
}
// createTableSource.getColumns().add(colStock);
// }
final IListe liste = new IListe(createTableSource);
 
final ListeAddPanel panel = new ListeAddPanel(elt, liste) {
131,7 → 135,7
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = 2;
panel.add(new JLabel("Voulez vous supprimer ou rendre obsoléte?"), c);
JButton buttonObs = new JButton("Obsoléte");
JButton buttonObs = new JButton("Obsolète");
JButton buttonSuppr = new JButton("Supprimer");
c.gridy++;
panel.add(buttonObs, c);
205,6 → 209,9
// });
// }
// }
 
if (colStock != null) {
// && !prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
List<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>> fields = new ArrayList<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>>(1);
fields.add(Tuple2.create(colStock, IListTotalPanel.Type.SOMME));
 
215,7 → 222,7
c2.weightx = 0;
c2.fill = GridBagConstraints.NONE;
panel.add(total, c2);
 
}
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(panelFam), panel);
JPanel panelAll = new JPanel(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
300,18 → 307,20
if (panel.getCheckObsolete().isSelected()) {
w = new Where(this.sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
 
w = w.or(new Where(request.getAlias(this.sqlTableArticle.getForeignTable("ID_STOCK").getField("QTE_REEL")), ">", 0));
// FIXME Fonctionnement avec multidepot
// w = w.or(new
// Where(request.getAlias(this.sqlTableArticle.getForeignTable("ID_STOCK").getField("QTE_REEL")),
// ">", 0));
}
 
if (id > 1) {
SQLRow row = this.sqlTableFamilleArticle.getRow(id);
Set<Integer> idsMatch = new HashSet<>();
idsMatch.add(id);
 
fillChildren(idsMatch, CollectionUtils.createSet(id));
 
Where w2 = new Where(this.sqlTableArticle.getField("ID_FAMILLE_ARTICLE"), "=", this.sqlTableFamilleArticle.getKey());
 
String code = row.getString("CODE") + ".%";
final Where w3 = new Where(this.sqlTableFamilleArticle.getField("CODE"), "LIKE", code);
w2 = w2.and(w3.or(new Where(this.sqlTableFamilleArticle.getKey(), "=", id)));
 
w2 = w2.and(new Where(this.sqlTableFamilleArticle.getKey(), idsMatch));
if (w != null) {
w = w.and(w2);
} else {
321,4 → 330,23
}
return w;
}
 
private void fillChildren(Set<Integer> idsMatch, Set<Integer> father) {
SQLRowValues rowVals = new SQLRowValues(this.sqlTableFamilleArticle);
final String keyFieldName = rowVals.getTable().getKey().getName();
rowVals.put(keyFieldName, null);
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
List<SQLRowValues> children = fetcher.fetch(new Where(this.sqlTableFamilleArticle.getField("ID_FAMILLE_ARTICLE_PERE"), father));
Set<Integer> childToCheck = new HashSet<>();
for (SQLRowValues child : children) {
if (!idsMatch.contains(child.getID())) {
childToCheck.add(child.getID());
idsMatch.add(child.getID());
}
}
if (!childToCheck.isEmpty()) {
fillChildren(idsMatch, childToCheck);
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/ArticleTarifTable.java
29,6 → 29,7
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.RowValuesTablePanel;
import org.openconcerto.sql.view.list.SQLTableElement;
import org.openconcerto.ui.table.NumberCellRenderer;
import org.openconcerto.utils.DecimalUtils;
 
import java.math.BigDecimal;
121,6 → 122,16
this.defaultRowVals.put("PRIX_METRIQUE_VT_1", BigDecimal.ZERO);
this.defaultRowVals.put("PV_HT", BigDecimal.ZERO);
this.defaultRowVals.put("PV_TTC", BigDecimal.ZERO);
if (e.getTable().contains("POURCENT_REMISE")) {
final SQLTableElement tableElementDiscount = new SQLTableElement(e.getTable().getField("POURCENT_REMISE"), BigDecimal.class) {
@Override
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
};
tableElementDiscount.setRenderer(new NumberCellRenderer());
list.add(tableElementDiscount);
}
this.model = new RowValuesTableModel(e, list, e.getTable().getField("ID_TARIF"), false, this.defaultRowVals);
 
this.table = new RowValuesTable(this.model, null);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/GestionArticlePreferencePanel.java
36,7 → 36,7
 
private final JCheckBox checkModeVente, checkLongueur, checkLargeur, checkPoids;
private final JCheckBox checkService, checkVenteComptoir, checkShowPoids, checkShowStyle, checkSFE;
private final JCheckBox checkDevise, checkMarge;
private final JCheckBox checkMarge;
private JCheckBox checkSite;
 
public GestionArticlePreferencePanel() {
55,12 → 55,9
this.checkModeVente = new JCheckBox("Activer le mode de vente spécifique");
this.checkVenteComptoir = new JCheckBox("Activer le mode vente comptoir");
this.checkShowPoids = new JCheckBox("Voir le Poids");
this.checkDevise = new JCheckBox("Gérer les devises");
this.checkMarge = new JCheckBox("Afficher le taux de marque au lieu du taux de marge");
 
 
this.add(this.checkDevise, c);
c.gridy++;
this.add(this.checkMarge, c);
c.gridy++;
this.add(this.checkService, c);
109,7 → 106,6
props.setProperty("ShowSiteFacture", String.valueOf(this.checkSite.isSelected()));
}
props.setProperty("ArticleVenteComptoir", String.valueOf(this.checkVenteComptoir.isSelected()));
props.setProperty(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, String.valueOf(this.checkDevise.isSelected()));
props.setProperty(TotalPanel.MARGE_MARQUE, String.valueOf(this.checkMarge.isSelected()));
props.store();
}
123,7 → 119,6
this.checkService.setSelected(true);
this.checkSFE.setSelected(false);
this.checkVenteComptoir.setSelected(true);
this.checkDevise.setSelected(false);
this.checkMarge.setSelected(false);
if (this.checkSite != null) {
this.checkSite.setSelected(false);
172,8 → 167,6
// Show Style
this.checkShowStyle.setSelected(props.getBooleanValue("ArticleShowStyle", false));
 
// Devise
this.checkDevise.setSelected(props.getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false));
 
// Devise
this.checkMarge.setSelected(props.getBooleanValue(TotalPanel.MARGE_MARQUE, false));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/ArticleFournisseurSecondaireTable.java
New file
0,0 → 1,62
/*
* 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.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.RowValuesTablePanel;
import org.openconcerto.sql.view.list.SQLTableElement;
 
import java.util.List;
import java.util.Vector;
 
public class ArticleFournisseurSecondaireTable extends RowValuesTablePanel {
 
private SQLTable article = Configuration.getInstance().getBase().getTable("ARTICLE");
 
public ArticleFournisseurSecondaireTable() {
 
init();
uiInit();
 
}
 
/**
*
*/
protected void init() {
 
final SQLElement e = getSQLElement();
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
 
SQLTableElement f = new SQLTableElement(e.getTable().getField("ID_FOURNISSEUR"));
f.setEditable(false);
list.add(f);
 
this.defaultRowVals = new SQLRowValues(getSQLElement().getTable());
this.model = new RowValuesTableModel(e, list, e.getTable().getField("ID_FOURNISSEUR"), false, this.defaultRowVals);
 
this.table = new RowValuesTable(this.model, null);
}
 
public SQLElement getSQLElement() {
return Configuration.getInstance().getDirectory().getElement("ARTICLE_FOURNISSEUR_SECONDAIRE");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/ui/ArticleCategorieComptableTable.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.
*/
package org.openconcerto.erp.core.sales.product.ui;
 
import org.openconcerto.erp.core.common.ui.DeviseNumericHTConvertorCellEditor;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.component.ReferenceArticleSQLComponent;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
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.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.view.list.CellDynamicModifier;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.RowValuesTablePanel;
import org.openconcerto.sql.view.list.SQLTableElement;
import org.openconcerto.utils.DecimalUtils;
 
import java.math.BigDecimal;
import java.util.List;
import java.util.Vector;
 
public class ArticleCategorieComptableTable extends RowValuesTablePanel {
 
private SQLTableElement cat;
private SQLTable article = Configuration.getInstance().getBase().getTable("ARTICLE");
 
public ArticleCategorieComptableTable() {
 
init();
uiInit();
 
}
 
/**
*
*/
protected void init() {
 
final SQLElement e = getSQLElement();
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
 
this.cat = new SQLTableElement(e.getTable().getField("ID_CATEGORIE_COMPTABLE"));
this.cat.setEditable(false);
list.add(this.cat);
 
list.add(new SQLTableElement(e.getTable().getField("ID_COMPTE_PCE_VENTE")));
 
list.add(new SQLTableElement(e.getTable().getField("ID_TAXE_VENTE")));
list.add(new SQLTableElement(e.getTable().getField("ID_COMPTE_PCE_ACHAT")));
 
list.add(new SQLTableElement(e.getTable().getField("ID_TAXE_ACHAT")));
 
this.defaultRowVals = new SQLRowValues(getSQLElement().getTable());
this.model = new RowValuesTableModel(e, list, e.getTable().getField("ID_CATEGORIE_COMPTABLE"), false, this.defaultRowVals);
 
this.table = new RowValuesTable(this.model, null);
}
 
public SQLElement getSQLElement() {
return Configuration.getInstance().getDirectory().getElement("ARTICLE_CATEGORIE_COMPTABLE");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/model/ProductComponent.java
14,13 → 14,19
package org.openconcerto.erp.core.sales.product.model;
 
import org.openconcerto.erp.core.sales.product.model.ProductHelper.SupplierPriceField;
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
29,13 → 35,17
 
public class ProductComponent {
private final SQLRowAccessor product;
private final SQLRowAccessor source;
private final SQLRowAccessor stock;
private BigDecimal qty;
private final ProductHelper helper;
 
public ProductComponent(SQLRowAccessor product, BigDecimal qty) {
public ProductComponent(SQLRowAccessor product, BigDecimal qty, SQLRowAccessor source, SQLRowAccessor stock) {
this.product = product;
this.qty = qty;
this.helper = new ProductHelper(product.getTable().getDBRoot());
this.source = source;
this.stock = stock;
}
 
public SQLRowAccessor getProduct() {
42,6 → 52,14
return product;
}
 
public SQLRowAccessor getSource() {
return source;
}
 
public SQLRowAccessor getStock() {
return stock;
}
 
public BigDecimal getQty() {
return qty;
}
80,6 → 98,8
result = PriceByQty.getPriceForQty(qty.setScale(0, RoundingMode.HALF_UP).intValue(), prices, d);
if (result == null) {
result = PriceByQty.getPriceForQty(qty.setScale(0, RoundingMode.HALF_UP).intValue(), prices, lastDate);
} else if (prices.size() > 0) {
result = prices.get(0).getPrice();
}
}
if (result == null) {
112,16 → 132,87
return null;
}
 
public static ProductComponent createFromRowArticle(SQLRowAccessor rowArticle, SQLRowAccessor rowValsSource) {
SQLRowAccessor rowStock = getStock(rowArticle, rowArticle, rowValsSource);
 
return new ProductComponent(rowArticle, BigDecimal.ONE, rowValsSource, rowStock);
}
 
public static ProductComponent createFrom(SQLRowAccessor rowVals) {
return createFrom(rowVals, 1);
return createFrom(rowVals, 1, rowVals);
}
 
public static ProductComponent createFrom(SQLRowAccessor rowVals, int qteMultiple) {
public static ProductComponent createFrom(SQLRowAccessor rowVals, SQLRowAccessor rowValsSource) {
return createFrom(rowVals, 1, rowValsSource);
}
 
public static ProductComponent createFrom(SQLRowAccessor rowVals, int qteMultiple, SQLRowAccessor rowValsSource) {
 
if (rowVals.getForeign("ID_ARTICLE") == null || rowVals.isForeignEmpty("ID_ARTICLE")) {
throw new IllegalArgumentException("Aucun article associé à la row " + rowVals.getTable().getName() + " " + rowVals.getID());
}
final int qteMult = (rowVals.getTable().getName().equalsIgnoreCase("BON_DE_LIVRAISON_ELEMENT") ? rowVals.getInt("QTE_LIVREE") : rowVals.getInt("QTE"));
final int qte = qteMult * qteMultiple;
final BigDecimal qteUV = rowVals.getBigDecimal("QTE_UNITAIRE");
BigDecimal qteFinal = qteUV.multiply(new BigDecimal(qte), DecimalUtils.HIGH_PRECISION);
return new ProductComponent(rowVals.getForeign("ID_ARTICLE"), qteFinal);
SQLRowAccessor rowStock = getStock(rowVals.getForeign("ID_ARTICLE"), rowVals, rowValsSource);
 
// }
// else {
// rowStock = rowVals.getForeign("ID_ARTICLE").getForeign("ID_STOCK");
// }
return new ProductComponent(rowVals.getForeign("ID_ARTICLE"), qteFinal, rowValsSource, rowStock);
// return new ProductComponent(rowVals.getForeign("ID_ARTICLE"), qteFinal);
}
 
private static SQLRowAccessor getStock(SQLRowAccessor rowValsProduct, SQLRowAccessor rowValsElt, SQLRowAccessor rowValsSource) {
SQLRowAccessor rowStock = null;
final int idDepot;
if (rowValsSource.getFields().contains("ID_DEPOT_STOCK") && !rowValsSource.isForeignEmpty("ID_DEPOT_STOCK")) {
idDepot = rowValsSource.getForeignID("ID_DEPOT_STOCK");
} else {
if (rowValsElt.getForeign("ID_DEPOT_STOCK") != null && !rowValsElt.isForeignEmpty("ID_DEPOT_STOCK")) {
idDepot = rowValsElt.getForeignID("ID_DEPOT_STOCK");
} else {
idDepot = DepotStockSQLElement.DEFAULT_ID;
try {
rowValsElt.createEmptyUpdateRow().put("ID_DEPOT_STOCK", idDepot).commit();
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de l'initialisation du stock!", e);
}
 
}
}
 
SQLTable stockTable = rowValsElt.getTable().getTable("STOCK");
SQLRowValues putRowValuesStock = new SQLRowValues(stockTable);
putRowValuesStock.putNulls(stockTable.getTable().getFieldsName());
 
SQLRowValuesListFetcher fetch = SQLRowValuesListFetcher.create(putRowValuesStock);
Where w = new Where(putRowValuesStock.getTable().getField("ID_DEPOT_STOCK"), "=", idDepot);
Where w2 = new Where(putRowValuesStock.getTable().getField("ID_ARTICLE"), "=", rowValsProduct.getID());
Collection<SQLRowValues> rowValsResult = fetch.fetch(w.and(w2));
if (rowValsResult.size() == 0) {
SQLRowValues rowValsStock = new SQLRowValues(stockTable);
rowValsStock.put("ID_ARTICLE", rowValsProduct.getID());
rowValsStock.put("ID_DEPOT_STOCK", idDepot);
rowValsStock.put("QTE_TH", 0F);
rowValsStock.put("QTE_REEL", 0F);
rowValsStock.put("QTE_RECEPT_ATTENTE", 0F);
rowValsStock.put("QTE_LIV_ATTENTE", 0F);
try {
rowStock = rowValsStock.insert();
if (idDepot == DepotStockSQLElement.DEFAULT_ID) {
rowValsProduct.createEmptyUpdateRow().put("ID_STOCK", rowStock.getID()).commit();
}
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors la création du stock!", e);
}
} else if (rowValsResult.size() == 1) {
rowStock = rowValsResult.iterator().next();
} else if (rowValsResult.size() > 1) {
throw new IllegalStateException("2 lignes de stocks pour le même dépôt! Article " + rowValsProduct.getID() + " Depot " + rowValsElt.getForeignID("ID_DEPOT_STOCK"));
}
return rowStock;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/model/PriceByQty.java
56,6 → 56,9
});
for (PriceByQty priceByQty : list) {
if (priceByQty.qty > qty) {
if (result == null) {
result = priceByQty.price;
}
break;
}
if (result == null || priceByQty.startDate.before(d)) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/model/ProductHelper.java
24,6 → 24,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ListMap;
import org.openconcerto.utils.cc.ITransformer;
 
import java.math.BigDecimal;
211,11 → 212,12
return getChildWithQtyFrom(items, new HashSet<Integer>());
}
 
private List<ProductComponent> getChildWithQtyFrom(List<ProductComponent> items, Set<Integer> ancestors) {
private List<ProductComponent> getChildWithQtyFrom(List<ProductComponent> items, Set<Integer> ancestorsOrigin) {
 
if (root.contains("ARTICLE_ELEMENT")) {
 
int originalAncestorsSize = ancestors.size();
int originalAncestorsSize = ancestorsOrigin.size();
Set<Integer> ancestors = new HashSet<Integer>(ancestorsOrigin);
 
List<ProductComponent> result = new ArrayList<ProductComponent>();
 
222,17 → 224,22
// liste des ids parents
final List<Integer> parentsArticleIDs = new ArrayList<Integer>();
 
// ID Article -- component
ListMap<Integer, ProductComponent> productCompByID = new ListMap<Integer, ProductComponent>();
 
// Quantité par parents
Map<Integer, ProductComponent> productCompByID = new HashMap<Integer, ProductComponent>();
final Map<Integer, BigDecimal> qtyParent = new HashMap<Integer, BigDecimal>();
// final ListMap<Integer, BigDecimal> qtyParentIDSource = new HashMap<Integer,
// BigDecimal>();
for (ProductComponent p : items) {
parentsArticleIDs.add(p.getProduct().getID());
BigDecimal qty = BigDecimal.ZERO;
if (qtyParent.get(p.getProduct().getID()) != null) {
qty = qtyParent.get(p.getProduct().getID());
productCompByID.add(p.getProduct().getID(), p);
int idSource = p.getProduct().getID();
parentsArticleIDs.add(idSource);
// BigDecimal qty = BigDecimal.ZERO;
// if (qtyParent.get(idSource) != null) {
// qty = qtyParent.get(idSource);
// }
// qtyParent.put(idSource, qty.add(p.getQty()));
}
qtyParent.put(p.getProduct().getID(), qty.add(p.getQty()));
}
 
// get all childs
final SQLTable costTable = root.getTable("ARTICLE_ELEMENT");
239,8 → 246,10
 
SQLRowValues rowVals = new SQLRowValues(costTable);
 
final SQLRowValues stockRowValues = rowVals.putRowValues("ID_ARTICLE").put("ID", null).put("GESTION_STOCK", null).put("CODE", null).put("NOM", null).putRowValues("ID_STOCK");
stockRowValues.putNulls("QTE_TH", "QTE_RECEPT_ATTENTE", "QTE_REEL", "QTE_LIV_ATTENTE");
final SQLRowValues artRowValues = rowVals.putRowValues("ID_ARTICLE").putNulls("ID", "GESTION_STOCK", "CODE", "NOM", "ID_DEPOT_STOCK", "ID_UNITE_VENTE");
SQLRowValues stockRowVals = new SQLRowValues(root.getTable("STOCK"));
stockRowVals.putNulls("QTE_TH", "QTE_RECEPT_ATTENTE", "QTE_REEL", "QTE_LIV_ATTENTE", "ID_DEPOT_STOCK");
stockRowVals.put("ID_ARTICLE", artRowValues);
rowVals.putRowValues("ID_ARTICLE_PARENT").put("ID", null);
rowVals.put("QTE", null);
rowVals.put("QTE_UNITAIRE", null);
263,22 → 272,33
for (SQLRowValues childRowValues : childs) {
final SQLRowAccessor foreignArticleParent = childRowValues.getForeign("ID_ARTICLE_PARENT");
 
if (!childRowValues.isForeignEmpty("ID_ARTICLE") && childRowValues.getForeign("ID_ARTICLE") != null) {
ProductComponent childComponent = ProductComponent.createFrom(childRowValues);
if (childRowValues.getObject("ID_ARTICLE") != null && !childRowValues.isForeignEmpty("ID_ARTICLE")) {
 
List<ProductComponent> source = productCompByID.get(foreignArticleParent.getID());
// Test pour éviter les boucles dans les boms
if (!ancestors.contains(childComponent.getProduct().getID())) {
if (!ancestorsOrigin.contains(foreignArticleParent.getID())) {
ancestors.add(foreignArticleParent.getID());
for (ProductComponent productParent : source) {
 
final SQLRowAccessor foreignArticle = childRowValues.getForeign("ID_ARTICLE");
ProductComponent childComponent = ProductComponent.createFromRowArticle(foreignArticle, productParent.getSource());
 
// parentsArticleIDs.remove(foreignArticleParent.getID());
// Calcul de la quantité qte_unit * qte * qteMergedParent
childComponent.setQty(childComponent.getQty().multiply(qtyParent.get(foreignArticleParent.getID()), DecimalUtils.HIGH_PRECISION));
childComponent.setQty(childComponent.getQty().multiply(productParent.getQty(), DecimalUtils.HIGH_PRECISION));
 
// Cumul des valeurs si l'article est présent plusieurs fois dans le bom
ProductComponent existProduct = productCompByID.get(childComponent.getProduct().getID());
if (existProduct == null) {
// Cumul des valeurs si l'article est présent plusieurs fois dans le
// bom
// ProductComponent existProduct =
// productCompByID.get(childComponent.getProduct().getID());
// if (existProduct == null) {
// Maintenant on garde une ligne disctincte pour chaque kit
result.add(childComponent);
productCompByID.put(childComponent.getProduct().getID(), childComponent);
} else {
existProduct.addQty(childComponent.getQty());
// productCompByID.put(childComponent.getProduct().getID(),
// childComponent);
// } else {
// existProduct.addQty(childComponent.getQty());
// }
}
}
}
289,34 → 309,34
// Merge des valeurs
for (ProductComponent s : bomFromChilds) {
 
ProductComponent existProduct = productCompByID.get(s.getProduct().getID());
if (existProduct == null) {
// ProductComponent existProduct = productCompByID.get(s.getProduct().getID());
// if (existProduct == null) {
result.add(s);
productCompByID.put(s.getProduct().getID(), s);
} else {
existProduct.addQty(s.getQty());
// productCompByID.put(s.getProduct().getID(), s);
// } else {
// existProduct.addQty(s.getQty());
// }
}
}
}
 
// Ajout des articles présents dans l'ensemble de départ
if (originalAncestorsSize == 0) {
for (ProductComponent p : items) {
ProductComponent existProduct = productCompByID.get(p.getProduct().getID());
if (existProduct == null) {
// ProductComponent existProduct = productCompByID.get(p.getProduct().getID());
// if (existProduct == null) {
result.add(p);
productCompByID.put(p.getProduct().getID(), p);
} else {
existProduct.addQty(p.getQty());
// productCompByID.put(p.getProduct().getID(), p);
// } else {
// existProduct.addQty(p.getQty());
// }
}
}
}
 
// On supprime les ancestors (kits) du result
for (Integer anc : ancestors) {
ProductComponent comp = productCompByID.get(anc);
if (comp != null) {
result.remove(comp);
// ProductComponent comp = productCompByID.get(anc);
if (productCompByID.containsKey(anc)) {
result.removeAll(productCompByID.get(anc));
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseMenuPanel.java
13,7 → 13,6
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
69,7 → 68,7
@Override
public void actionPerformed(ActionEvent e) {
System.err.println("CaisseMenuPanel.CaisseMenuPanel(...).new ActionListener() {...}.actionPerformed()");
POSConfiguration.getInstance().printOnceOnFirstPrinter(new Printable() {
caisseFrame.getPOSConf().printOnceOnFirstPrinter(new Printable() {
 
@Override
public void print(TicketPrinter prt, int ticketWidth) {
163,9 → 162,9
final boolean quit = caisseFrame.getDB().fetchRegisterState().checkIfMoved();
if (!quit) {
frame.getControler().setLCD("Cloture", "En cours...", 0);
final int userID = POSConfiguration.getInstance().getUserID();
final int userID = caisseFrame.getPOSConf().getUserID();
final RegisterLog newLog = caisseFrame.getFiles().close(userID);
caisseFrame.getDB().close(userID, newLog);
caisseFrame.getDB().close(caisseFrame.getPOSConf(), newLog);
frame.getControler().setLCD("Cloture", "Terminee", 0);
// TODO lock down the UI until open again
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseFrame.java
26,6 → 26,7
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.RemoteShell;
import org.openconcerto.sql.element.SQLElementDirectory;
32,6 → 33,7
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.utils.ClassPathLoader;
import org.openconcerto.utils.ExceptionHandler;
50,10 → 52,12
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
64,12 → 68,14
import org.jdom2.JDOMException;
 
public class CaisseFrame extends JFrame {
private final POSConfiguration posConf;
private final ComptaPropsConfiguration conf;
private final RegisterFiles files;
private final RegisterDB registerDB;
final CaissePanel mainPanel;
 
CaisseFrame(final ComptaPropsConfiguration conf, final RegisterFiles files, final RegisterDB registerDB) throws Exception {
CaisseFrame(final POSConfiguration posConf, final ComptaPropsConfiguration conf, final RegisterFiles files, final RegisterDB registerDB) throws Exception {
this.posConf = posConf;
this.conf = conf;
this.files = files;
this.registerDB = registerDB;
78,6 → 84,10
setFocusable(true);
}
 
public final POSConfiguration getPOSConf() {
return this.posConf;
}
 
public final ComptaPropsConfiguration getConf() {
return this.conf;
}
107,10 → 117,11
System.setProperty("sun.java2d.pmoffscreen", "false");
System.setProperty(SQLBase.STRUCTURE_USE_XML, "true");
System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
if (POSConfiguration.getInstance().isUsingJPos()) {
final POSConfiguration posConf = POSConfiguration.setInstance();
if (posConf.isUsingJPos()) {
ClassPathLoader c = ClassPathLoader.getInstance();
try {
final List<String> posDirectories = POSConfiguration.getInstance().getJPosDirectories();
final List<String> posDirectories = posConf.getJPosDirectories();
for (String posDirectory : posDirectories) {
if (posDirectory != null && !posDirectory.trim().isEmpty()) {
c.addJarFromDirectory(new File(posDirectory.trim()));
122,30 → 133,65
c.load();
 
}
final ComptaPropsConfiguration conf = POSConfiguration.getInstance().createConnexion();
final ComptaPropsConfiguration conf = posConf.createConnexion();
 
final int userID = POSConfiguration.getInstance().getUserID();
final RegisterFiles registerFiles = new RegisterFiles(POSConfiguration.getInstance().getRootDir(), true, POSConfiguration.getInstance().getPosID());
final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), POSConfiguration.getInstance().getPosID());
 
final int userID = posConf.getUserID();
final int posID = posConf.getPosID();
final RegisterFiles registerFiles = new RegisterFiles(posConf.getRootDir(), true, posConf.getPosID());
final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), posConf.getPosID());
// check if register exists
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(new SQLRowValues(registerDB.getRegisterTable()));
if (fetcher.fetchOne(posID) == null) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(null, TM.tr("register.missing", posID), TM.tr("register.missing.title"), JOptionPane.ERROR_MESSAGE);
});
posConf.closeConnexion();
return;
}
// check before changing any state
final boolean quit = registerDB.fetchRegisterState().checkIfMoved();
if (quit) {
quit();
quit(posConf);
return;
}
 
final RegisterState reconciledState = registerFiles.doWithLock(new ExnTransformer<RegisterFiles, RegisterState, IOException>() {
final Logger logger = POSConfiguration.getLogger();
final RegisterState reconciledState;
try {
reconciledState = registerFiles.doWithLock(new ExnTransformer<RegisterFiles, RegisterState, Exception>() {
@Override
public RegisterState transformChecked(RegisterFiles input) throws IOException {
try {
return reconcileFSandDB(conf.getDirectory(), input, registerDB, userID);
public RegisterState transformChecked(RegisterFiles input) throws Exception {
return reconcileFSandDB(posConf, conf.getDirectory(), input, registerDB);
}
});
} catch (ReconcileException re) {
logger.log(Level.WARNING, "States couldn’t be reconciled, local : " + re.getLocalState() + ", remote : " + re.getRemoteState(), re);
final String generalMsg;
boolean onlyOptionPane = false;
if (re instanceof OutsideMeddlingException) {
generalMsg = TM.tr("register.notReconciled.outsideMeddling") + '\n';
onlyOptionPane = true;
} else if (re instanceof ResumeException) {
generalMsg = TM.tr("register.notReconciled.resumeFailed") + '\n';
} else {
generalMsg = "";
}
final String message = TM.getTM().trM("register.notReconciled." + re.getTranslationKey(), "localDate", re.getLocalState().copyDate(), "remoteDate", re.getRemoteState().copyDate());
if (onlyOptionPane) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(null, generalMsg + message, TM.tr("register.notReconciled.title"), JOptionPane.ERROR_MESSAGE);
});
} else {
ExceptionHandler.handle(generalMsg + message, re);
}
// ATTN this calls ComptaPropsConfiguration.tearDownLogging(), so even syserr is
// closed.
posConf.closeConnexion();
return;
} catch (Exception e) {
throw new IOException("Couldn't reconcile local and remote state", e);
}
}
});
POSConfiguration.getLogger().log(Level.INFO, "FS and DB states reconciled : {0}", reconciledState);
logger.log(Level.INFO, "FS and DB states reconciled : {0}", reconciledState);
 
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
169,11 → 215,11
}
}
if (state.getStatus() != Status.OPEN) {
POSConfiguration.getLogger().log(Level.FINE, "State not open ({0}), exiting", state);
POSConfiguration.getInstance().closeConnexion();
logger.log(Level.FINE, "State not open ({0}), exiting", state);
posConf.closeConnexion();
return;
}
POSConfiguration.getLogger().log(Level.INFO, "FS and DB states open, opening UI");
logger.log(Level.INFO, "FS and DB states open, opening UI");
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
184,7 → 230,7
e.printStackTrace();
}
try {
CaisseFrame f = new CaisseFrame(conf, registerFiles, registerDB);
CaisseFrame f = new CaisseFrame(posConf, conf, registerFiles, registerDB);
f.setUndecorated(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
195,8 → 241,8
f.setLocation(0, 0);
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (POSConfiguration.getInstance().getScreenWidth() > 0 && POSConfiguration.getInstance().getScreenHeight() > 0) {
f.setSize(new Dimension(POSConfiguration.getInstance().getScreenWidth() - f.getX(), POSConfiguration.getInstance().getScreenHeight() - f.getY()));
if (posConf.getScreenWidth() > 0 && posConf.getScreenHeight() > 0) {
f.setSize(new Dimension(posConf.getScreenWidth() - f.getX(), posConf.getScreenHeight() - f.getY()));
} else {
f.setSize(new Dimension(screenSize.getSize().width - f.getX(), screenSize.getSize().height - f.getY()));
}
219,7 → 265,71
}
}
 
private static RegisterState reconcileFSandDB(final SQLElementDirectory dir, final RegisterFiles files, final RegisterDB registerDB, final int userID)
public static class ReconcileException extends IllegalStateException {
private RegisterState localState, remoteState;
private final String translationKey;
 
protected ReconcileException(final String msg, final String key) {
this(msg, key, null);
}
 
protected ReconcileException(final String msg, final String key, final Throwable cause) {
super(Objects.requireNonNull(msg, "message"), cause);
this.translationKey = Objects.requireNonNull(key, "translation key");
}
 
public final RegisterState getLocalState() {
return this.localState;
}
 
public final RegisterState getRemoteState() {
return this.remoteState;
}
 
public final String getTranslationKey() {
return this.translationKey;
}
 
protected final ReconcileException init(final RegisterState localState, final RegisterState remoteState) {
this.localState = Objects.requireNonNull(localState, "local state");
this.remoteState = Objects.requireNonNull(remoteState, "remote state");
return this;
}
}
 
// the FS and/or DB states were modified outside of this software.
public static final class OutsideMeddlingException extends ReconcileException {
protected OutsideMeddlingException(final String msg, final String key) {
super(msg, key);
}
}
 
// the opening or closure was interrupted, the process was resumed but it failed.
public static final class ResumeException extends ReconcileException {
protected ResumeException(final String msg, final String key, final Throwable cause) {
super(msg, key, Objects.requireNonNull(cause, "missing cause"));
}
}
 
/*
* List of translations keys.
*/
private static final String unknownTK = "unknown";
// localOpen
private static final String open_datesMismatch = "open.datesMismatch";
private static final String localOpen_remoteClosed = "localOpen_remoteClosed";
private static final String localOpen_remoteMissing = "localOpen_remoteMissing";
// remoteOpen
private static final String localMissing_remoteReopen = "localMissing_remoteReopen";
private static final String localOpenFailed_remoteOpen = "localOpenFailed_remoteOpen";
private static final String localClosed_remoteCloseFailed = "localClosed_remoteCloseFailed";
private static final String localClosed_remoteOpen_datesMismatch = "localClosed_remoteOpen.datesMismatch";
// both closed
private static final String localMissing_remoteClosed = "localMissing_remoteClosed";
private static final String closed_datesMismatch = "closed.datesMismatch";
private static final String localClosed_remoteMissing = "localClosed_remoteMissing";
 
private static RegisterState reconcileFSandDB(final POSConfiguration posConf, final SQLElementDirectory dir, final RegisterFiles files, final RegisterDB registerDB)
throws IOException, JDOMException, ParseException, SQLException {
 
// *** find local and remote states
243,9 → 353,9
if (localState.getStatus() == Status.OBSOLETE) {
if (remoteState.hasDate())
throw new IllegalStateException("There remains obsolete receipts but DB can no longer import them : " + remoteState);
final List<Ticket> allTickets = POSConfiguration.getInstance().allTickets();
final List<Ticket> allTickets = posConf.allTickets();
POSConfiguration.getLogger().log(Level.INFO, "{0} obsolete receipt(s) will be stored in the DB", allTickets.size());
POSConfiguration.getInstance().commitAll(allTickets);
posConf.commitAll(allTickets);
final List<File> remainingReceipts = ReceiptCode.getReceiptsToImport(files.getPosID());
if (!remainingReceipts.isEmpty())
throw new IllegalStateException("Not all obsolete receipts could be imported : " + remainingReceipts);
261,6 → 371,7
// *** reconcile if possible
if (!localState.equals(remoteState)) {
POSConfiguration.getLogger().log(Level.INFO, "Different FS and DB state, will try to reconcile\nFS " + localState + " with\nDB " + remoteState);
final int userID = posConf.getUserID();
 
// OK because of the check above
final boolean localOpen = localState.getStatus() == Status.OPEN;
284,10 → 395,10
try {
if (localOpen) {
if (remoteOpen) {
throw new IllegalStateException("Both open with but with different dates");
throw new OutsideMeddlingException("Both open with but with different dates", open_datesMismatch);
} else {
// DB is at 0 or 5, local is at 2
throw new IllegalStateException("local is open but the DB isn't");
throw new OutsideMeddlingException("local is open but the DB isn't", remoteState.hasDate() ? localOpen_remoteClosed : localOpen_remoteMissing);
}
} else if (remoteOpen) {
assert remoteState.hasDate() : "Remote state open without date : " + remoteState;
298,18 → 409,18
// MAYBE allow it for new install, for now the receipts must be copied
// over
if (lastClosureDate != null)
throw new IllegalStateException("DB was closed (" + lastClosureDate + ") and now open, but local log is missing");
throw new OutsideMeddlingException("DB was closed and now open, but local log is missing", localMissing_remoteReopen);
try {
localState = files.open(userID, fetchedState).getRegisterState();
} catch (Exception e) {
throw new IllegalStateException("The local opening (following the already open DB) failed", e);
throw new ResumeException("The local opening (following the already open DB) failed", localOpenFailed_remoteOpen, e);
}
} else if (remoteState.compareDateTo(lastLog.getFirstRegisterEvent().getDate()) == 0) {
// at 4
try {
remoteState = registerDB.close(userID, files.getLastLog()).getRegisterState();
remoteState = registerDB.close(posConf, files.getLastLog()).getRegisterState();
} catch (Exception e) {
throw new IllegalStateException("The closure of the DB (following the already closed local) failed", e);
throw new ResumeException("The closure of the DB (following the already closed local) failed", localClosed_remoteCloseFailed, e);
}
} else if (lastClosureDate != null && localState.compareDateTo(lastClosureDate) == 0) {
// at 6, TODO factor with above
316,30 → 427,33
try {
localState = files.open(userID, fetchedState).getRegisterState();
} catch (Exception e) {
throw new IllegalStateException("The local opening (following the already open DB) failed", e);
throw new ResumeException("The local opening (following the already open DB) failed", localOpenFailed_remoteOpen, e);
}
} else {
// DB is at 1, local is between 4 and 6
throw new IllegalStateException("DB was opened for a different date");
throw new OutsideMeddlingException("DB was opened for a different date", localClosed_remoteOpen_datesMismatch);
}
} else {
assert !localOpen && !remoteOpen;
if (!localState.hasDate()) {
assert remoteState.hasDate() : "Both closed with no dates, but not equal";
// DB is at 5, local is at 0
// MAYBE allow it for new install, for now the receipts must be copied
// over
throw new IllegalStateException("DB was opened and closed, but local log is missing");
throw new OutsideMeddlingException("DB was opened and closed, but local log is missing", localMissing_remoteClosed);
} else if (remoteState.hasDate()) {
// DB is at 5, local is at 5 but not for the same day
assert remoteState.compareDateTo(localState) != 0 : "Both closed with equal dates, but not equal";
throw new IllegalStateException("DB was opened and closed for a different date");
throw new OutsideMeddlingException("DB was opened and closed for a different date", closed_datesMismatch);
} else {
// DB is at 0, local is between 4 and 6
throw new IllegalStateException("DB was never opened but local was closed");
throw new OutsideMeddlingException("DB was never opened but local was closed", localClosed_remoteMissing);
}
}
} catch (ReconcileException e) {
throw e.init(localState, remoteState);
} catch (Exception e) {
throw new IllegalStateException("States couldn't be reconciled, local : " + localState + ", remote : " + remoteState, e);
throw new ReconcileException("Unknown exception", unknownTK, e).init(localState, remoteState);
}
}
if (!remoteState.equals(localState))
347,9 → 461,9
return remoteState;
}
 
static public void quit() {
static public void quit(final POSConfiguration posConf) {
POSConfiguration.getLogger().log(Level.INFO, "User exit");
POSConfiguration.getInstance().closeConnexion();
posConf.closeConnexion();
Frame[] l = Frame.getFrames();
for (int i = 0; i < l.length; i++) {
Frame f = l[i];
365,7 → 479,7
 
@Override
public void dispose() {
quit();
quit(this.posConf);
// Fermeture
this.getControler().setLCD(" CAISSE FERMEE ", "", 0);
super.dispose();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ListeDesTicketsPanel.java
13,7 → 13,6
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.TicketPrinterConfiguration;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
288,7 → 287,7
Object selectedValue = ticketList.getSelectedValue();
int selectedIndex = l.getSelectedIndex();
if (selectedIndex == 0 && selectedValue != null) {
POSConfiguration.getInstance().printOnceOnFirstPrinter(((Printable) selectedValue));
this.frame.getPOSConf().printOnceOnFirstPrinter(((Printable) selectedValue));
} else if (selectedIndex == 1 && selectedValue != null) {
// Annulation du ticket
Ticket t = (Ticket) selectedValue;
305,7 → 304,7
public void setSelectedTicket(Object selectedValue) {
ticketP.clear();
if (selectedValue != null) {
POSConfiguration.getInstance().print(((Printable) selectedValue), new TicketPrinterConfiguration() {
this.frame.getPOSConf().print(((Printable) selectedValue), new TicketPrinterConfiguration() {
@Override
public TicketPrinter createTicketPrinter() {
return ticketP;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
13,7 → 13,6
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Categorie;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles.DifferentDayException;
155,7 → 154,7
// Valider
CaissePanel.this.controler.setLCD("Impression de", "votre ticket...", 0);
try {
POSConfiguration.getInstance().print(savedReceipt, (savedReceipt.isAdditionnalCopyRequested() ? 1 : 0));
caisseFrame.getPOSConf().print(savedReceipt, (savedReceipt.isAdditionnalCopyRequested() ? 1 : 0));
} catch (UnsatisfiedLinkError ex) {
JOptionPane.showMessageDialog(CaissePanel.this, "Erreur de configuration de la liaison à l'imprimante");
} catch (Throwable ex) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TextAreaTicketPanel.java
41,7 → 41,7
 
public class TextAreaTicketPanel extends JPanel {
 
public TextAreaTicketPanel(SQLRow row) {
public TextAreaTicketPanel(final POSConfiguration conf, SQLRow row) {
super(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.BOTH;
54,8 → 54,7
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
POSConfiguration.getInstance().print(ticket);
 
conf.print(ticket);
}
});
 
74,7 → 73,7
c.weighty = 1;
this.add(comp, c);
 
ticket.print(comp, POSConfiguration.getInstance().getTicketPrinterConfiguration1().getTicketWidth());
ticket.print(comp, conf.getTicketPrinterConfiguration1().getTicketWidth());
}
 
private Ticket createTicket(SQLRow row) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ConfigCaissePanel.java
57,7 → 57,7
 
public class ConfigCaissePanel extends JPanel {
 
private final POSConfiguration configuration = POSConfiguration.getInstance();
private final POSConfiguration configuration;
private int userId;
private int societeId;
private int caisseId;
80,6 → 80,11
 
public ConfigCaissePanel(final ServerFinderPanel serverFinderPanel) {
this.serverFinderPanel = serverFinderPanel;
try {
this.configuration = POSConfiguration.setInstance();
} catch (Exception e) {
throw new IllegalStateException("Couldn't initialise POSConfiguration", e);
}
 
setOpaque(false);
 
580,6 → 585,7
e.printStackTrace();
} finally {
server.destroy();
server.tearDownLogging(true);
}
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ListeDesClientsPanel.java
13,6 → 13,10
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.model.Client;
import org.openconcerto.ui.DefaultListModel;
import org.openconcerto.ui.touch.ScrollableList;
 
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
31,11 → 35,6
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Client;
import org.openconcerto.ui.DefaultListModel;
import org.openconcerto.ui.touch.ScrollableList;
 
public class ListeDesClientsPanel extends JPanel {
 
private ScrollableList clientList;
68,7 → 67,7
c.gridheight = 2;
 
ticketLlistModel = new DefaultListModel();
ticketLlistModel.addAll(new Vector<Client>(POSConfiguration.getInstance().allClients()));
ticketLlistModel.addAll(new Vector<Client>(caisseFrame.getPOSConf().allClients()));
final Font f = new Font("Arial", Font.PLAIN, 24);
clientList = new ScrollableList(ticketLlistModel) {
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/DetailClientPanel.java
13,7 → 13,6
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.TicketPrinterConfiguration;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.Client;
140,11 → 139,11
 
@Override
public void run() {
final TicketPrinterConfiguration conf1 = POSConfiguration.getInstance().getTicketPrinterConfiguration1();
final TicketPrinterConfiguration conf1 = caisseFrame.getPOSConf().getTicketPrinterConfiguration1();
if (conf1.isValid()) {
final TicketPrinter prt = conf1.createTicketPrinter();
final int ticketWidth = conf1.getTicketWidth();
client.printCredit(prt, ticketWidth, amount, paymentType, nouveauSolde);
client.printCredit(prt, caisseFrame.getPOSConf().getHeaderLines(), ticketWidth, amount, paymentType, nouveauSolde);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseControler.java
83,20 → 83,21
final ReceiptCode lastCode = lastReceiptEvent.getCode();
dayIndex = lastCode.getDayIndex() + 1;
}
this.t = new Ticket(POSConfiguration.getInstance().getPosID(), dayIndex, lastHash);
final POSConfiguration posConf = getPOSConf();
this.t = new Ticket(posConf.getPosID(), dayIndex, lastHash);
 
this.t.addPaiement(this.p1);
this.t.addPaiement(this.p2);
this.t.addPaiement(this.p3);
 
final int scanDelay = POSConfiguration.getInstance().getScanDelay();
final int scanDelay = posConf.getScanDelay();
this.r = new BarcodeReader(scanDelay);
this.r.start();
this.r.addBarcodeListener(this);
if (POSConfiguration.getInstance().getLCDType().equals("serial")) {
lcd = new ESCSerialDisplay(POSConfiguration.getInstance().getLCDPort());
if (posConf.getLCDType().equals("serial")) {
lcd = new ESCSerialDisplay(posConf.getLCDPort());
} else {
lcd = new PrinterPOSDisplay(POSConfiguration.getInstance().getLCDPort());
lcd = new PrinterPOSDisplay(posConf.getLCDPort());
}
this.setLCDDefaultDisplay(0);
}
105,6 → 106,10
return this.caisseFrame;
}
 
protected final POSConfiguration getPOSConf() {
return getCaisseFrame().getPOSConf();
}
 
public Article getArticleSelected() {
return this.articleSelected;
}
344,7 → 349,7
final String fileHash = this.t.save(files, dir);
final Ticket res = this.t;
final int newIndex = this.t.getNumber() + 1;
t = new Ticket(POSConfiguration.getInstance().getPosID(), newIndex, fileHash);
t = new Ticket(getPOSConf().getPosID(), newIndex, fileHash);
p1 = new Paiement(Paiement.ESPECES);
p2 = new Paiement(Paiement.CB);
p3 = new Paiement(Paiement.CHEQUE);
363,7 → 368,7
 
public void openDrawer() {
try {
final TicketPrinter prt = POSConfiguration.getInstance().getTicketPrinterConfiguration1().createTicketPrinter();
final TicketPrinter prt = getPOSConf().getTicketPrinterConfiguration1().createTicketPrinter();
prt.openDrawer();
} catch (Exception e) {
e.printStackTrace();
408,13 → 413,13
int cents = t.getTotalInCents();
setLCD(line1, "Total : " + TicketCellRenderer.centsToString(cents), delay);
} else {
setLCD(POSConfiguration.getInstance().getLCDLine1(), POSConfiguration.getInstance().getLCDLine2(), delay);
setLCD(getPOSConf().getLCDLine1(), getPOSConf().getLCDLine2(), delay);
}
}
 
public void sendCBRequest(final Paiement p) {
 
final String creditCardPort = POSConfiguration.getInstance().getCreditCardPort();
final String creditCardPort = getPOSConf().getCreditCardPort();
if (creditCardPort != null && creditCardPort.trim().length() > 2) {
final Thread t = new Thread(new Runnable() {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketPanel.java
124,7 → 124,8
if (selectedValue != null) {
final Article a = ((Pair<Article, Integer>) selectedValue).getFirst();
controler.setArticleSelected(a);
// If the category of the selected article does not match the current category of the categories list,
// If the category of the selected article does not match the current
// category of the categories list,
// then the corresponding article is not selected.
controler.setArticleSelected(a); // Dirty fix : use two refresh
}
141,7 → 142,7
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
try {
// Display caisse and Vendor ID
String InfoCaisseVendeur = "Caisse "+POSConfiguration.getInstance().getPosID() + " Vendeur " + POSConfiguration.getInstance().getUserID();
String InfoCaisseVendeur = "Caisse " + this.controler.getPOSConf().getPosID() + " Vendeur " + this.controler.getPOSConf().getUserID();
g.setColor(new Color(230, 230, 230));
g.setFont(getFont().deriveFont(28.0f));
g.drawString(InfoCaisseVendeur, 20, this.getHeight() - 50);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/CheckIntegrity.java
43,8 → 43,8
 
public class CheckIntegrity {
 
public static void main(String[] args) {
final POSConfiguration posConf = POSConfiguration.getInstance();
public static void main(String[] args) throws JDOMException, IOException {
final POSConfiguration posConf = POSConfiguration.setInstance();
final ComptaPropsConfiguration conf = posConf.createConnexion();
try {
for (final RegisterFiles files : RegisterFiles.scan(posConf.getRootDir())) {
231,8 → 231,12
throw new IllegalStateException("File hash in the DB doesn't match log : " + row.getString("FILE_HASH") + " != " + receiptEvent.getFileHash());
if (!Objects.equals(row.getString("FILE_HASH_PREVIOUS"), receipt.getPreviousHash()))
throw new IllegalStateException("Previous file hash in the DB doesn't match log");
if (row.getLong("TOTAL_TTC") != receipt.getPaidTotal())
throw new IllegalStateException("TTC in the DB " + row.getLong("TOTAL_TTC") + " doesn't match log " + receipt.getPaidTotal());
if (row.getLong("TOTAL_TTC") != receipt.getTotalInCents())
throw new IllegalStateException("TTC in the DB " + row.getLong("TOTAL_TTC") + " doesn't match log " + receipt.getTotalInCents());
// ATTN the paid amount isn't stored in the DB by
// POSConfiguration.importReceipts() so we can't check it exactly
if (row.getLong("TOTAL_TTC") > receipt.getPaidTotal())
throw new IllegalStateException("Paid amount in the log (" + receipt.getPaidTotal() + ") is less than total in the DB " + row.getLong("TOTAL_TTC"));
} catch (Exception exn) {
throw new IllegalStateException("Error while checking " + row + " against " + receipt + " in " + log, exn);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Client.java
14,7 → 14,6
package org.openconcerto.erp.core.sales.pos.model;
 
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.DefaultTicketPrinter;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.ui.TicketCellRenderer;
136,9 → 135,8
});
}
 
public void printCredit(TicketPrinter prt, int ticketWidth, BigDecimal amount, int paymentType, BigDecimal nouveauSolde) {
public void printCredit(TicketPrinter prt, List<TicketLine> headers, int ticketWidth, BigDecimal amount, int paymentType, BigDecimal nouveauSolde) {
prt.clearBuffer(this.getFullName() + " crédit");
List<TicketLine> headers = POSConfiguration.getInstance().getHeaderLines();
for (TicketLine line : headers) {
prt.addToBuffer(line);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Ticket.java
575,7 → 575,7
 
public TotalCalculator getTotalCalculator() {
final SQLTable tableElt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().findTable("SAISIE_VENTE_FACTURE_ELEMENT");
final TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null);
final TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null, null);
final String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
final Boolean bServiceActive = Boolean.valueOf(val);
calc.setServiceActive(bServiceActive != null && bServiceActive);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterState.java
93,6 → 93,11
return f.format(this.date);
}
 
// Date is mutable
public final Date copyDate() {
return this.hasDate() ? new Date(this.date.getTime()) : null;
}
 
@Override
public int hashCode() {
final int prime = 31;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterDB.java
218,7 → 218,7
 
// TODO monthly and yearly closures
 
public final DBState close(final int userID, final RegisterLog log) throws SQLException, ParseException {
public final DBState close(final POSConfiguration posConf, final RegisterLog log) throws SQLException, ParseException {
final List<ReceiptEntry> receiptEvents = log.getReceiptEvents();
final RegisterEntry closureEntry = log.getLastRegisterEvent();
if (closureEntry.getType() != EventType.REGISTER_CLOSURE)
236,10 → 236,10
final Date ourDate = closureEntry.getDate();
 
// verifications OK, proceed to import all receipts
POSConfiguration.getInstance().importReceipts(receipts, receiptEvents);
posConf.importReceipts(receipts, receiptEvents);
 
// actually close
final SQLRowValues registerVals = createUpdateVals(fetchedState, userID, Status.CLOSED, ourDate);
final SQLRowValues registerVals = createUpdateVals(fetchedState, posConf.getUserID(), Status.CLOSED, ourDate);
final SQLRowValues newLogEntry = CollectionUtils.getSole(registerVals.getReferentRows(getLogElement().getTable()));
if (newLogEntry == null)
throw new IllegalStateException("Missing log entry in " + registerVals);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/BarcodeReader.java
24,7 → 24,10
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
 
51,11 → 54,23
// non final car un TimerTask n'est pas reutilisable
private TimerTask task;
private boolean enable = true;
private boolean debug = false;
Map<Integer, String> mapCharacterFR = new HashMap<>();
 
public BarcodeReader(int maxInterKeyDelay) {
this.timer = null;
this.task = null;
this.maxInterKeyDelay = maxInterKeyDelay;
mapCharacterFR.put((int) '&', "1");
mapCharacterFR.put((int) 'é', "2");
mapCharacterFR.put((int) '"', "3");
mapCharacterFR.put((int) '\'', "4");
mapCharacterFR.put((int) '(', "5");
mapCharacterFR.put((int) '-', "6");
mapCharacterFR.put((int) 'è', "7");
mapCharacterFR.put((int) '_', "8");
mapCharacterFR.put((int) 'ç', "9");
mapCharacterFR.put((int) 'à', "0");
}
 
public synchronized void removeBarcodeListener(BarcodeListener l) {
115,35 → 130,61
if (this.firstTime < 0) {
this.firstTime = t;
}
int key = e.getKeyCode();
int keyCode = e.getKeyCode();
 
final long delay = t - this.firstTime;
if (key == KeyEvent.VK_BACK_SPACE || key == KeyEvent.VK_DELETE || (delay > maxInterKeyDelay && key != KeyEvent.VK_SHIFT)) {
if (keyCode == KeyEvent.VK_BACK_SPACE || keyCode == KeyEvent.VK_DELETE || (delay > maxInterKeyDelay && keyCode != KeyEvent.VK_SHIFT)) {
// touche normale
if (this.debug) {
System.err.println("TOuche normale " + keyCode);
}
this.eve.add(e);
redispatch();
return true;
}
 
final char key2 = e.getKeyChar();
final char keyChar = e.getKeyChar();
this.eve.add(e);
if (e.getID() == KeyEvent.KEY_RELEASED) {
if (key == KeyEvent.VK_SHIFT) {
if (keyCode == KeyEvent.VK_SHIFT) {
// rien
} else if (key2 == '*' || key2 == '$' || key2 == '+' || key2 == '/' || key2 == '%' || key2 == '-' | key2 == ' ') {
this.value += key2;
} else if (Character.isLetter(key2) || Character.isDigit(key2)) {
this.value += key2;
} else if (key >= KeyEvent.VK_0 && key <= KeyEvent.VK_9 || key >= KeyEvent.VK_A && key <= KeyEvent.VK_Z) {
if (this.debug) {
System.err.println("SHIFT " + keyCode);
}
} else if (keyChar == '*' || keyChar == '$' || keyChar == '+' || keyChar == '/' || keyChar == '%' || keyChar == ' ') {
this.value += keyChar;
if (this.debug) {
System.err.println("KEY " + keyCode + " - " + keyChar);
}
} else if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 || keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
// from KeyEvent : same as ASCII
this.value += (char) key;
} else if (key == KeyEvent.VK_ENTER && this.value.length() >= MIN_BARCODE_LENGTH) {
if (this.debug) {
System.err.println("[0-9] [A-Z] " + keyCode);
}
this.value += (char) keyCode;
} else if (keyCode == KeyEvent.VK_ENTER && this.value.length() >= MIN_BARCODE_LENGTH) {
// fin de code barre
if (this.debug) {
System.err.println("BARCODE OK ENTER OR LENGHT " + keyCode + " length = " + this.value.length() + " min length =" + MIN_BARCODE_LENGTH);
}
this.value = this.value.trim();
fire(this.value);
reset();
} else if (mapCharacterFR.containsKey((int) keyChar)) {
if (this.debug) {
System.err.println("MAP DEFAULT FR CHAR " + keyChar + " WITH " + mapCharacterFR.get((int) keyChar));
}
this.value += mapCharacterFR.get((int) keyChar);
} else if (Character.isLetter(keyChar) || Character.isDigit(keyChar)) {
this.value += keyChar;
if (this.debug) {
System.err.println("LETTER OR DIGIT " + keyChar);
}
} else {
// Caractere non code barre
if (this.debug) {
System.err.println("CHAR NON CODE BARRE " + e);
}
redispatch();
}
// lance un timer s'il reste des evenements non dispatchés
189,6 → 230,14
this.firstTime = -1;
}
 
public Map<Integer, String> getMapCharacterFR() {
return mapCharacterFR;
}
 
public void setDebug(boolean debug) {
this.debug = debug;
}
 
public static void main(String[] args) {
String delay = "80";
if (args.length > 0) {
223,6 → 272,13
panel.add(new JScrollPane(t1), c);
 
BarcodeReader reader = new BarcodeReader(d);
reader.setDebug(true);
 
System.err.println("FR MAP");
for (Entry<Integer, String> string : reader.getMapCharacterFR().entrySet()) {
System.err.println(string.getKey() + " --> " + string.getValue());
}
 
reader.addBarcodeListener(new BarcodeListener() {
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/POSConfiguration.java
79,6 → 79,7
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
117,14 → 118,27
private String LCDLine1 = "Bienvenue";
private String LCDLine2 = "ILM Informatique";
 
public static synchronized POSConfiguration getInstance() {
public static POSConfiguration createInstance() throws JDOMException, IOException {
POSConfiguration res = new POSConfiguration(getConfigFile(new File(".")));
res.loadConfiguration();
return res;
}
 
@Deprecated
public static synchronized POSConfiguration setInstance() throws JDOMException, IOException {
if (instance == null) {
instance = new POSConfiguration(getConfigFile(new File(".")));
instance.loadConfiguration();
instance = createInstance();
} else {
throw new IllegalStateException("already set");
}
return instance;
}
 
@Deprecated
public static synchronized POSConfiguration getInstance() {
return instance;
}
 
private POSConfiguration(final File confFile) {
this.confFile = confFile;
ticketPrinterConf1 = new TicketPrinterConfiguration();
341,8 → 355,10
if (idClient <= 0) {
idClient = defaultIDClient;
}
TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null);
 
// TODO fusionner TotalCalculator avec Ticket.GetTotalCalcutor
TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null, null);
 
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean bServiceActive = Boolean.valueOf(val);
calc.setServiceActive(bServiceActive != null && bServiceActive);
395,6 → 411,9
rowValsElt.put("ID_CLIENT", idClient);
 
long montant = Long.valueOf(paiement.getMontantInCents());
// Check si montant especes > especes données alors montant especes =
// montant donné - montant rendu
// TODO gérer ce cas si paiement multiple
if (ticket.getPaiements().size() == 1 && paiement.getType() == Paiement.ESPECES) {
montant = longValueTotal;
}
497,7 → 516,7
public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
return "Ticket N°" + rowOrigin.getString("NUMERO");
}
}, row, row.getReferentRows(getClientCaisse().getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")), TypeStockUpdate.REAL_DELIVER);
}, row, row.getReferentRows(getClientCaisse().getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")), TypeStockUpdate.REAL_VIRTUAL_DELIVER);
stockUpdater.update();
}
 
529,7 → 548,7
this.footerLines = footerLines;
}
 
private void loadConfiguration() {
private void loadConfiguration() throws JDOMException, IOException {
if (!isConfigurationFileCreated()) {
System.err.println("POSConfiguration.loadConfigurationFromXML() configuration not loaded. " + getConfigFile().getAbsolutePath() + " missing.");
return;
538,7 → 557,6
final SAXBuilder builder = new SAXBuilder();
File file = getConfigFile();
 
try {
System.out.println("POSConfiguration.loadConfigurationFromXML() loading " + file.getAbsolutePath());
Document document = builder.build(file);
// config
595,12 → 613,8
if (printers.size() > 1) {
configureTicketPrinter(this.ticketPrinterConf2, printers.get(1));
}
} catch (Exception e) {
e.printStackTrace();
}
 
}
 
private void configureTicketPrinter(TicketPrinterConfiguration conf, Element element) {
conf.setType(element.getAttributeValue("type"));
conf.setName(element.getAttributeValue("name"));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/CaisseJournalSQLElement.java
48,6 → 48,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".log";
return createCodeOfPackage() + ".log";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/CaisseTicketSQLElement.java
30,7 → 30,7
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("NUMERO");
l.add("NOM");
return l;
37,7 → 37,7
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("NUMERO");
l.add("NOM");
return l;
45,7 → 45,7
 
@Override
public ListMap<String, String> getShowAs() {
final ListMap<String, String> res = new ListMap<String, String>();
final ListMap<String, String> res = new ListMap<>();
res.putCollection(null, "NUMERO", "NOM");
return res;
 
64,4 → 64,10
}
};
}
 
@Override
protected String createCodeSuffix() {
return ".receipt";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/TicketCaisseSQLElement.java
77,6 → 77,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".ticket";
return createCodeOfPackage() + ".ticket";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/SaisieVenteComptoirSQLElement.java
806,6 → 806,7
rowVals.put("IDSOURCE", id);
rowVals.put("SOURCE", getTable().getName());
rowVals.put("ID_ARTICLE", rowVC.getInt("ID_ARTICLE"));
rowVals.put("ID_STOCK", rowVC.getForeign("ID_ARTICLE").getForeignID("ID_STOCK"));
rowVals.put("DATE", rowVC.getObject("DATE"));
 
try {
957,6 → 958,7
rowVals.put("IDSOURCE", getSelectedID());
rowVals.put("SOURCE", getTable().getName());
rowVals.put("ID_ARTICLE", row.getInt("ID_ARTICLE"));
rowVals.put("ID_STOCK", row.getForeign("ID_ARTICLE").getForeignID("ID_STOCK"));
rowVals.put("DATE", row.getObject("DATE"));
try {
SQLRow rowNew = rowVals.insert();
1030,6 → 1032,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".sale";
return createCodeOfPackage() + ".sale";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/ClôtureCaisseSQLElement.java
47,6 → 47,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".closure";
return createCodeOfPackage() + ".closure";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/price/element/DeviseSQLElement.java
13,10 → 13,9
package org.openconcerto.erp.core.sales.price.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.accounting.model.Currency;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.ui.DefaultGridBagConstraints;
32,16 → 31,12
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class DeviseSQLElement extends ConfSQLElement {
public class DeviseSQLElement extends ComptaSQLConfElement {
 
public DeviseSQLElement(DBRoot root) {
super(root.getTable("DEVISE"), "une devise", "devises");
}
 
public DeviseSQLElement() {
this(Configuration.getInstance().getRoot());
}
 
@Override
public boolean isShared() {
return true;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/price/element/TarifSQLElement.java
103,4 → 103,10
}
};
}
 
@Override
protected String createCodeSuffix() {
return ".list";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/component/BonDeLivraisonSQLComponent.java
24,6 → 24,7
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonItemSQLElement;
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement;
36,6 → 37,7
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
130,6 → 132,10
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
rowVals.put("ID_TAXE_PORT", taxeDefault.getID());
}
if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
rowVals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
}
return rowVals;
}
 
351,8 → 357,14
final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
int idClient = rowClient.getID();
comboContact.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_CLIENT"), "=", idClient));
if (rowClient.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowClient.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
tableBonItem.setRowCatComptable(rowClient.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
tableBonItem.setRowCatComptable(null);
}
} else {
comboContact.getRequest().setWhere(Where.FALSE);
tableBonItem.setRowCatComptable(null);
// DevisSQLComponent.this.table.setTarif(null, false);
}
}
380,7 → 392,7
// tableBonItem.setTarif(foreignRow, true);
SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
&& JOptionPane.showConfirmDialog(null, "Appliquer les tarifs associés au client?") == JOptionPane.YES_OPTION) {
&& JOptionPane.showConfirmDialog(null, TM.tr("deliveryForm.applyClientRates")) == JOptionPane.YES_OPTION) { //$NON-NLS-1$
boxTarif.setValue(foreignRow.getID());
// SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
// true);
393,7 → 405,7
});
 
// Bouton tout livrer
JButton boutonAll = new JButton("Tout livrer");
JButton boutonAll = new JButton(TM.tr("deliveryForm.shipAll")); //$NON-NLS-1$
 
boutonAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
511,7 → 523,6
this.allowEditable("TOTAL_POIDS", false);
final TotalPanel panelTotal = new TotalPanel(tableBonItem, fieldEco, textTotalHT, textTotalTVA, textTotalTTC, textPortHT, textRemiseHT, fieldService, fieldHA, fieldDevise, this.textPoidsTotal,
null, (getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
 
// if (b)