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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/core/common/ui/TotalCalculator.java
17,6 → 17,8
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
28,6 → 30,7
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
42,6 → 45,8
private boolean imputEcart = true;
private SQLRowAccessor rowDefaultCptProduit, rowDefaultCptService, rowDefaultCptTVACollecte, rowDefaultCptTVADeductible, rowDefaultCptAchat;
 
private final SQLRowAccessor rowCatComptable;
 
private SQLRowAccessor rowDefaultCptProduitStandard;
 
private double totalPoids;
72,8 → 77,8
private BigDecimal totalHTAvantRemise;
private boolean intraComm = false;
 
public TotalCalculator(String fieldHA, String fieldHT, String fieldDeviseTotal) {
this(fieldHA, fieldHT, fieldDeviseTotal, false, null);
public TotalCalculator(String fieldHA, String fieldHT, String fieldDeviseTotal, SQLRowAccessor rowCatComptable) {
this(fieldHA, fieldHT, fieldDeviseTotal, false, null, rowCatComptable);
}
 
public void setRowDefaultCptService(SQLRowAccessor rowDefaultCptService) {
84,7 → 89,7
this.intraComm = intraComm;
}
 
public TotalCalculator(String fieldHA, String fieldHT, String fieldDeviseTotal, boolean achat, SQLRowAccessor defaultCompte) {
public TotalCalculator(String fieldHA, String fieldHT, String fieldDeviseTotal, boolean achat, SQLRowAccessor defaultCompte, SQLRowAccessor rowCatComptable) {
 
this.achat = achat;
initValues();
93,13 → 98,16
this.fieldHA = fieldHA;
this.fieldHT = fieldHT;
final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
final SQLBackgroundTableCacheItem cacheForTablePref = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte);
final SQLBackgroundTableCacheItem cacheForTableCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte.getTable("COMPTE_PCE"));
final SQLRow rowPrefsCompte = cacheForTablePref.getRowFromId(2);
 
SQLPreferences prefs = SQLPreferences.getMemCached(tablePrefCompte.getDBRoot());
this.imputEcart = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.IMPUT_ECART, true);
 
// FIXME faire un fetcher pour ne pas faire 5 requetes (1 par getForeign)
// Comptes par défaut
this.rowDefaultCptService = rowPrefsCompte.getForeign("ID_COMPTE_PCE_VENTE_SERVICE");
this.rowDefaultCptService = cacheForTableCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_VENTE_SERVICE"));
if (this.rowDefaultCptService == null || this.rowDefaultCptService.isUndefined()) {
try {
this.rowDefaultCptService = ComptePCESQLElement.getRowComptePceDefault("VentesServices");
108,8 → 116,14
}
}
 
this.rowCatComptable = rowCatComptable;
 
if (defaultCompte == null || defaultCompte.isUndefined()) {
this.rowDefaultCptProduit = rowPrefsCompte.getForeign("ID_COMPTE_PCE_VENTE_PRODUIT");
 
if (rowCatComptable != null && !rowCatComptable.isUndefined() && !rowCatComptable.isForeignEmpty("ID_COMPTE_PCE_VENTE")) {
this.rowDefaultCptProduit = cacheForTableCompte.getRowFromId(rowCatComptable.getForeignID("ID_COMPTE_PCE_VENTE"));
} else {
this.rowDefaultCptProduit = cacheForTableCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_VENTE_PRODUIT"));
if (this.rowDefaultCptProduit == null || this.rowDefaultCptProduit.isUndefined()) {
try {
this.rowDefaultCptProduit = ComptePCESQLElement.getRowComptePceDefault("VentesProduits");
117,12 → 131,13
e.printStackTrace();
}
}
}
} else {
this.rowDefaultCptProduit = defaultCompte;
}
this.rowDefaultCptProduitStandard = this.rowDefaultCptProduit;
 
this.rowDefaultCptTVACollecte = rowPrefsCompte.getForeign("ID_COMPTE_PCE_TVA_VENTE");
this.rowDefaultCptTVACollecte = cacheForTableCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_TVA_VENTE"));
if (this.rowDefaultCptTVACollecte == null || this.rowDefaultCptTVACollecte.isUndefined()) {
try {
this.rowDefaultCptTVACollecte = ComptePCESQLElement.getRowComptePceDefault("TVACollectee");
131,7 → 146,7
}
}
 
this.rowDefaultCptTVADeductible = rowPrefsCompte.getForeign("ID_COMPTE_PCE_TVA_ACHAT");
this.rowDefaultCptTVADeductible = cacheForTableCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_TVA_ACHAT"));
if (this.rowDefaultCptTVADeductible == null || this.rowDefaultCptTVADeductible.isUndefined()) {
try {
this.rowDefaultCptTVADeductible = ComptePCESQLElement.getRowComptePceDefault("TVADeductible");
141,7 → 156,10
}
 
if (defaultCompte == null || defaultCompte.isUndefined()) {
this.rowDefaultCptAchat = rowPrefsCompte.getForeign("ID_COMPTE_PCE_ACHAT");
if (rowCatComptable != null && !rowCatComptable.isUndefined() && !rowCatComptable.isForeignEmpty("ID_COMPTE_PCE_ACHAT")) {
this.rowDefaultCptProduit = cacheForTableCompte.getRowFromId(rowCatComptable.getForeignID("ID_COMPTE_PCE_ACHAT"));
} else {
this.rowDefaultCptAchat = cacheForTableCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_ACHAT"));
if (this.rowDefaultCptAchat == null || this.rowDefaultCptAchat.isUndefined()) {
try {
this.rowDefaultCptAchat = ComptePCESQLElement.getRowComptePceDefault("Achats");
149,6 → 167,7
e.printStackTrace();
}
}
}
} else {
this.rowDefaultCptAchat = defaultCompte;
}
290,6 → 309,7
 
BigDecimal ttc;
BigDecimal totalTVA;
final SQLBackgroundTableCacheItem cacheForTableCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(cptArticle.getTable());
 
if (tva == null || tva.isUndefined()) {
ttc = ht;
305,27 → 325,31
if (this.intraComm) {
 
// Intra comm TTC=HT et solde de TVA
rowCptTva = tva.getForeign("ID_COMPTE_PCE_DED_INTRA");
rowCptTva = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_DED_INTRA"));
if (rowCptTva == null || rowCptTva.isUndefined()) {
rowCptTva = this.rowDefaultCptTVADeductible;
}
 
SQLRowAccessor rowCptTvaIntra = tva.getForeign("ID_COMPTE_PCE_COLLECTE_INTRA");
SQLRowAccessor rowCptTvaIntra = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_COLLECTE_INTRA"));
if (rowCptTvaIntra == null || rowCptTvaIntra.isUndefined()) {
rowCptTvaIntra = this.rowDefaultCptTVADeductible;
}
 
if (mapHtTVAIntra.get(rowCptTvaIntra) == null) {
mapHtTVAIntra.put(rowCptTvaIntra, totalTVA);
} else {
BigDecimal l = mapHtTVAIntra.get(rowCptTvaIntra);
mapHtTVAIntra.put(rowCptTvaIntra, l.add(totalTVA));
}
 
ht = ttc;
ttc = ht;
} else if (this.achat) {
rowCptTva = tva.getForeign("ID_COMPTE_PCE_DED");
rowCptTva = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_DED"));
if (rowCptTva == null || rowCptTva.isUndefined()) {
rowCptTva = this.rowDefaultCptTVADeductible;
}
} else {
rowCptTva = tva.getForeign("ID_COMPTE_PCE_COLLECTE");
rowCptTva = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_COLLECTE"));
if (rowCptTva == null || rowCptTva.isUndefined()) {
rowCptTva = this.rowDefaultCptTVACollecte;
}
437,14 → 461,20
if (mapTVA == null || lastTVAfetchedTime + 30 * 1000 < System.currentTimeMillis()) {
fetchTVA();
}
Integer idTVA = null;
if (rowAccessorLine.getObject("ID_TAXE") != null && !rowAccessorLine.isForeignEmpty("ID_TAXE")) {
idTVA = rowAccessorLine.getForeignID("ID_TAXE");
} else {
final SQLRowAccessor foreignTVA = rowAccessorLine.getForeign("ID_TAXE");
Integer idTVA = null;
if (foreignTVA != null) {
idTVA = foreignTVA.getID();
}
}
SQLRowAccessor tva = mapTVA.get(idTVA);
 
SQLRowAccessor cpt = (achat ? this.rowDefaultCptAchat : this.rowDefaultCptProduit);
final SQLBackgroundTableCacheItem cacheForTableCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(cpt.getTable());
 
if (!achat) {
// Total Service
if (bServiceActive != null && bServiceActive && service != null && service.booleanValue()) {
451,19 → 481,32
totalService = totalService.add(totalLineHT);
cpt = this.rowDefaultCptService;
if (tva != null && !tva.isForeignEmpty("ID_COMPTE_PCE_VENTE_SERVICE")) {
cpt = tva.getForeign("ID_COMPTE_PCE_VENTE_SERVICE");
cpt = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_VENTE_SERVICE"));
}
} else {
// Compte defini par défaut dans la TVA
if (tva != null && !tva.isForeignEmpty("ID_COMPTE_PCE_VENTE")) {
cpt = tva.getForeign("ID_COMPTE_PCE_VENTE");
cpt = cacheForTableCompte.getRowFromId(tva.getForeignID("ID_COMPTE_PCE_VENTE"));
}
 
}
}
if (article != null && !article.isUndefined()) {
SQLRowAccessor cptCatComptable = null;
// TODO Optimiser les requetes
if (rowCatComptable != null && !rowCatComptable.isUndefined()) {
String suffix = (this.achat ? "_ACHAT" : "_VENTE");
Collection<? extends SQLRowAccessor> rows = article.getReferentRows(compteTable.getTable("ARTICLE_CATEGORIE_COMPTABLE"));
for (SQLRowAccessor sqlRowAccessor : rows) {
if (sqlRowAccessor.getForeignID("ID_CATEGORIE_COMPTABLE") == this.rowCatComptable.getID()) {
cptCatComptable = cacheForTableCompte.getRowFromId(rowCatComptable.getForeignID("ID_COMPTE_PCE" + suffix));
}
}
}
 
if (cptCatComptable == null) {
String suffix = (this.achat ? "_ACHAT" : "");
SQLRowAccessor compteArticle = article.getForeign("ID_COMPTE_PCE" + suffix);
SQLRowAccessor compteArticle = cacheForTableCompte.getRowFromId(article.getForeignID("ID_COMPTE_PCE" + suffix));
if (compteArticle != null && !compteArticle.isUndefined()) {
cpt = compteArticle;
} else {
472,15 → 515,19
while (familleArticle != null && !familleArticle.isUndefined() && !unique.contains(familleArticle)) {
 
unique.add(familleArticle);
SQLRowAccessor compteFamilleArticle = familleArticle.getForeign("ID_COMPTE_PCE" + suffix);
if (familleArticle.getObject("ID_COMPTE_PCE" + suffix) != null && !familleArticle.isForeignEmpty("ID_COMPTE_PCE" + suffix)) {
SQLRowAccessor compteFamilleArticle = cacheForTableCompte.getRowFromId(familleArticle.getForeignID("ID_COMPTE_PCE" + suffix));
if (compteFamilleArticle != null && !compteFamilleArticle.isUndefined()) {
cpt = compteFamilleArticle;
break;
}
 
}
familleArticle = familleArticle.getForeign("ID_FAMILLE_ARTICLE_PERE");
}
}
} else {
cpt = cptCatComptable;
}
if (!achat) {
SQLRowAccessor taxeCompl = (article.getFields().contains("ID_TAXE_COMPLEMENTAIRE") && article.getObject("ID_TAXE_COMPLEMENTAIRE") != null
&& !article.isForeignEmpty("ID_TAXE_COMPLEMENTAIRE") ? article.getForeign("ID_TAXE_COMPLEMENTAIRE") : null);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractAchatArticleItemTable.java
113,6 → 113,7
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
final boolean showDmdAchat = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_DEMANDE_ACHAT, false);
final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
this.supplierCode = prefs.getBoolean(GestionArticleGlobalPreferencePanel.SUPPLIER_PRODUCT_CODE, false);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
155,6 → 156,10
};
list.add(tableElementArticle);
 
// Article
SQLTableElement tableElementDepot = new SQLTableElement(e.getTable().getField("ID_DEPOT_STOCK"), true, true, true);
list.add(tableElementDepot);
 
if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
list.add(tableFamille);
231,7 → 236,8
final SQLTableElement tableElement_ValeurMetrique1 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_1"), Float.class);
list.add(tableElement_ValeurMetrique1);
// Prix d'achat HT de la métrique 1
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class);
final DeviseNumericHTConvertorCellEditor editorPAHT = new DeviseNumericHTConvertorCellEditor(e.getTable().getField("PRIX_METRIQUE_HA_1"));
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class, editorPAHT);
tableElement_PrixMetrique1_AchatHT.setRenderer(new CurrencyWithSymbolRenderer());
list.add(tableElement_PrixMetrique1_AchatHT);
 
245,7 → 251,7
final SQLTableElement tableElement_PA_Devise = new SQLTableElement(e.getTable().getField("PA_DEVISE"), BigDecimal.class);
Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
tableElement_PA_Devise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Devise
list.add(tableElement_Devise);
 
319,7 → 325,7
list.add(this.service);
}
 
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Prix d'achat HT devise
this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PA_DEVISE_T"), BigDecimal.class);
this.tableElementTotalDevise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
429,6 → 435,7
completionFields.add("ID_ECO_CONTRIBUTION");
}
completionFields.add("ID_UNITE_VENTE");
completionFields.add("QTE_UNITAIRE");
completionFields.add("PA_HT");
completionFields.add("PV_HT");
completionFields.add("POIDS");
605,7 → 612,7
}
 
});
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
 
if (tableElement_PA_Devise != null) {
tableElement_PA_Devise.addModificationListener(tableElement_PrixMetrique1_AchatHT);
681,7 → 688,7
System.out.println(row);
}
Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
 
editorPAHT.setTaxe(resultTaux);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION).setScale(tableElementTotalTTC.getDecimalDigits(),
BigDecimal.ROUND_HALF_UP);
727,6 → 734,8
setColumnVisible(model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
setColumnVisible(model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
 
setColumnVisible(model.getColumnForField("ID_DEPOT_STOCK"), prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false));
 
// Calcul automatique du poids unitaire
tableElement_ValeurMetrique1.addModificationListener(tableElementPoids);
tableElement_ValeurMetrique2.addModificationListener(tableElementPoids);
1040,7 → 1049,11
 
return BigDecimal.ZERO;
}
 
}
if (field.equalsIgnoreCase("ID_TAXE") && this.rowCatComptable != null) {
return this.rowCatComptable.getForeignID("ID_TAXE_VENTE");
}
return null;
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/TotalPanel.java
16,6 → 16,7
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
69,6 → 70,7
private DeviseField textService, textServiceSel;
private DeviseField textHA, textHASel;
private JTextField marge, margeSel;
private DeviseField textFraisDoc, textFraisDocSel;
private boolean gestionHA = false;
private PropertyChangeSupport supp;
private int columnIndexEchHT = -1;
75,6 → 77,7
private int columnIndexEchTTC = -1;
private SQLTableElement ha;
private SQLRequestComboBox selPortTVA;
private SQLRequestComboBox selFraisDocTVA = null;
private AcompteField facturable;
private boolean intraComm = false;
 
110,7 → 113,8
this.textPortHT = textPortHT;
this.textRemiseHT = textRemiseHT;
this.textService = textService;
 
this.textFraisDoc = new DeviseField();
this.textFraisDocSel = new DeviseField();
this.textTotalHTSel = new DeviseField(true);
this.textServiceSel = new DeviseField();
this.textTotalEcoSel = new DeviseField();
142,6 → 146,8
reconfigure(this.textHA);
reconfigure(this.marge);
reconfigure(this.textTotalHTSel);
reconfigure(this.textFraisDoc);
reconfigure(this.textFraisDocSel);
reconfigure(this.textTotalEcoSel);
reconfigure(this.textTotalTVASel);
reconfigure(this.textTotalTTCSel);
168,7 → 174,7
 
// Collone 1 : Selection
c.gridx++;
this.add(new JLabelBold("Sélection"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.selection")), c); //$NON-NLS-1$
c.gridy++;
c.gridx = 1;
c.gridwidth = 2;
180,8 → 186,8
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
if (this.gestionHA) {
final JLabel labelMarge = new JLabel("Marge");
final JLabel labelHA = new JLabel((this.ha == articleItemTable.getPrebilanElement()) ? "Budget prévisionnel" : "Total achat HT");
final JLabel labelMarge = new JLabel(TM.tr("TotalPanel.margin")); //$NON-NLS-1$
final JLabel labelHA = new JLabel((this.ha == articleItemTable.getPrebilanElement()) ? TM.tr("TotalPanel.estimatedBudget") : TM.tr("TotalPanel.purchaseTotal.taxExcluded")); //$NON-NLS-1$//$NON-NLS-2$
 
// Total HA HT
c.gridy++;
220,7 → 226,7
c.gridx = 1;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(getLabelBoldFor(textTotalHT.getField(), "Total HT"), c);
this.add(getLabelBoldFor(textTotalHT.getField(), TM.tr("TotalPanel.total.taxExcluded")), c); //$NON-NLS-1$
 
c.gridx++;
c.weightx = 1;
231,7 → 237,7
c.gridx = 1;
c.gridy++;
c.weightx = 0;
this.add(new JLabel("Service HT inclus "), c);
this.add(new JLabel(TM.tr("TotalPanel.service.taxExcluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textServiceSel, c);
241,7 → 247,7
c.gridx = 1;
c.gridy++;
c.weightx = 0;
this.add(getLabelFor(textTotalTVA.getField(), "Total TVA"), c);
this.add(getLabelFor(textTotalTVA.getField(), TM.tr("TotalPanel.total.VAT")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textTotalTVASel, c);
259,7 → 265,7
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(getLabelFor(textTotalDevise.getField(), "Total Devise"), c);
this.add(getLabelFor(textTotalDevise.getField(), TM.tr("TotalPanel.currencyTotal")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textTotalDeviseSel, c);
272,7 → 278,7
c.gridx = 1;
c.gridy++;
c.weightx = 0;
this.add(new JLabel("Dont Eco-Contrib."), c);
this.add(new JLabel(TM.tr("TotalPanel.ecoTax")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textTotalEcoSel, c);
284,7 → 290,7
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(getLabelFor(textTotalTTC.getField(), "Total TTC"), c);
this.add(getLabelFor(textTotalTTC.getField(), TM.tr("TotalPanel.total.taxIncluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textTotalTTCSel, c);
302,7 → 308,7
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.gridx++;
this.add(new JLabelBold("Global"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.global")), c); //$NON-NLS-1$
c.gridy++;
c.gridx = 4;
c.gridwidth = 2;
312,8 → 318,8
c.gridwidth = 1;
c.weightx = 0;
if (this.gestionHA) {
final JLabel labelMarge = new JLabel("Marge");
final JLabel labelHA = new JLabel((this.ha == articleItemTable.getPrebilanElement()) ? "Budget prévisionnel" : "Total achat HT");
final JLabel labelMarge = new JLabel(TM.tr("TotalPanel.margin")); //$NON-NLS-1$
final JLabel labelHA = new JLabel((this.ha == articleItemTable.getPrebilanElement()) ? TM.tr("TotalPanel.estimatedBudget") : TM.tr("TotalPanel.purchaseTotal.taxExcluded")); //$NON-NLS-1$//$NON-NLS-2$
 
// Total HA HT
c.gridy++;
349,7 → 355,7
c.gridy++;
c.gridx = 4;
c.weightx = 0;
this.add(getLabelBoldFor(textTotalHT.getField(), "Total HT"), c);
this.add(getLabelBoldFor(textTotalHT.getField(), TM.tr("TotalPanel.total.taxExcluded")), c); //$NON-NLS-1$
 
c.gridx++;
c.weightx = 1;
360,7 → 366,7
c.gridx = 4;
c.gridy++;
c.weightx = 0;
this.add(new JLabelBold("Service HT inclus "), c);
this.add(new JLabelBold(TM.tr("TotalPanel.service.taxExcluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textService, c);
369,7 → 375,7
c.gridx = 4;
c.gridy++;
c.weightx = 0;
this.add(getLabelBoldFor(textTotalTVA.getField(), "Total TVA"), c);
this.add(getLabelBoldFor(textTotalTVA.getField(), TM.tr("TotalPanel.total.VAT")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(textTotalTVA, c);
389,7 → 395,7
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(getLabelBoldFor(textTotalDevise.getField(), "Total Devise"), c);
this.add(getLabelBoldFor(textTotalDevise.getField(), TM.tr("TotalPanel.currencyTotal")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
textTotalDevise.setFont(textTotalHT.getFont());
401,7 → 407,7
c.gridx = 4;
c.gridy++;
c.weightx = 0;
this.add(new JLabel("Dont Eco-Contrib."), c);
this.add(new JLabel(TM.tr("TotalPanel.ecoTax")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textTotalEco, c);
413,7 → 419,7
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(getLabelBoldFor(textTotalTTC.getField(), "Total TTC"), c);
this.add(getLabelBoldFor(textTotalTTC.getField(), TM.tr("TotalPanel.total.taxIncluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
textTotalTTC.setFont(textTotalHT.getFont());
428,6 → 434,11
});
}
 
public void setTextFraisDoc(DeviseField textFraisDoc, SQLRequestComboBox boxTVA) {
this.textFraisDoc = textFraisDoc;
this.selFraisDocTVA = boxTVA;
}
 
public void setIntraComm(boolean intraComm) {
this.intraComm = intraComm;
updateTotal();
490,6 → 501,12
this.defaultRowCompteProduit = row;
}
 
private SQLRowAccessor rowCatComptable = null;
 
public void setCategorieComptable(SQLRowAccessor row) {
this.rowCatComptable = row;
}
 
/**
*
*/
496,7 → 513,7
public void updateTotal() {
 
final long valRemiseHT;
final BigDecimal valPortHT;
final BigDecimal valPortHT, fraisDoc;
 
clearTextField();
// Clone rows to be thread safe
579,6 → 596,28
} else {
rowValsPort = null;
}
// Frais documents
if (textFraisDoc.getText().trim().length() > 0) {
if (!textFraisDoc.getText().trim().equals("-")) {
long p = GestionDevise.parseLongCurrency(textFraisDoc.getText().trim());
fraisDoc = new BigDecimal(p).movePointLeft(2);
} else {
fraisDoc = BigDecimal.ZERO;
}
} else {
fraisDoc = BigDecimal.ZERO;
}
final SQLRow tvafraisDoc = selFraisDocTVA == null ? null : selFraisDocTVA.getSelectedRow();
final SQLRowValues rowValsFraisDoc;
if (tvafraisDoc != null && fraisDoc.signum() != 0 && !tvafraisDoc.isUndefined()) {
rowValsFraisDoc = new SQLRowValues(articleTable.getSQLElement().getTable());
rowValsFraisDoc.put(articleTable.getPrixTotalHTElement().getField().getName(), fraisDoc);
rowValsFraisDoc.put("QTE", 1);
rowValsFraisDoc.put("ID_TAXE", tvafraisDoc.getIDNumber());
rowValsFraisDoc.put("SERVICE", Boolean.TRUE);
} else {
rowValsFraisDoc = null;
}
 
final Boolean isServiceActive = bServiceActive;
if (worker != null) {
599,7 → 638,7
SQLTableElement tableElementTotalHT = articleTable.getPrixTotalHTElement();
String fieldHT = (tableElementTotalHT == null ? null : tableElementTotalHT.getField().getName());
 
final TotalCalculator calc = new TotalCalculator(fieldHA, fieldHT, fieldDevise, achat, null);
final TotalCalculator calc = new TotalCalculator(fieldHA, fieldHT, fieldDevise, achat, null, rowCatComptable);
calc.setIntraComm(intraComm);
if (defaultRowCompteProduit != null) {
calc.setRowDefaultCptProduit(defaultRowCompteProduit);
663,6 → 702,10
calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 0, false);
}
 
if (rowValsFraisDoc != null) {
calc.addLine(rowValsFraisDoc, null, 0, false);
}
 
// Verification du resultat ht +tva = ttc
calc.checkResult();
if (Thread.currentThread().isInterrupted()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/TotalCommandePanel.java
17,6 → 17,7
package org.openconcerto.erp.core.common.ui;
 
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
63,7 → 64,7
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.gridx++;
this.add(new JLabelBold("Global"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.global")), c); //$NON-NLS-1$
c.gridy++;
c.gridx = 4;
c.gridwidth = 2;
75,7 → 76,7
 
// Total HA HT
c.gridy++;
this.add(new JLabel("Total achat HT"), c);
this.add(new JLabel(TM.tr("TotalPanel.purchaseTotal.taxExcluded")), c); //$NON-NLS-1$
 
c.gridx++;
c.weightx = 1;
85,7 → 86,7
c.gridy++;
c.gridx = 4;
c.weightx = 0;
this.add(new JLabel("Marge"), c);
this.add(new JLabel(TM.tr("TotalPanel.margin")), c); //$NON-NLS-1$
 
c.gridx++;
c.weightx = 1;
104,7 → 105,7
c.gridy++;
c.gridx = 4;
c.weightx = 0;
this.add(new JLabelBold("Total HT"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.total.taxExcluded")), c); //$NON-NLS-1$
 
c.gridx++;
c.weightx = 1;
115,7 → 116,7
c.gridx = 4;
c.gridy++;
c.weightx = 0;
this.add(new JLabelBold("Service HT inclus "), c);
this.add(new JLabelBold(TM.tr("TotalPanel.service.taxExcluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(this.textService, c);
124,7 → 125,7
c.gridx = 4;
c.gridy++;
c.weightx = 0;
this.add(new JLabelBold("Total TVA"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.total.VAT")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
this.add(textTotalTVA, c);
143,7 → 144,7
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabelBold("Total TTC"), c);
this.add(new JLabelBold(TM.tr("TotalPanel.total.taxIncluded")), c); //$NON-NLS-1$
c.gridx++;
c.weightx = 1;
textTotalTTC.setFont(textTotalHT.getFont());
158,11 → 159,11
}
 
public void loadFromCmd(SQLRowAccessor rowCmd) {
this.textTotalHT.setValue(rowCmd.getLong("T_HT"));
this.textTotalTVA.setValue(rowCmd.getLong("T_TVA"));
this.textTotalTTC.setValue(rowCmd.getLong("T_TTC"));
this.textTotalHA.setValue(rowCmd.getLong("T_HA"));
this.marge.setValue(rowCmd.getLong("T_HT") - rowCmd.getLong("T_HA"));
this.textTotalHT.setValue(rowCmd.getLong("T_HT")); //$NON-NLS-1$
this.textTotalTVA.setValue(rowCmd.getLong("T_TVA")); //$NON-NLS-1$
this.textTotalTTC.setValue(rowCmd.getLong("T_TTC")); //$NON-NLS-1$
this.textTotalHA.setValue(rowCmd.getLong("T_HA")); //$NON-NLS-1$
this.marge.setValue(rowCmd.getLong("T_HT") - rowCmd.getLong("T_HA")); //$NON-NLS-1$ //$NON-NLS-2$
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/IListFilterDatePanel.java
14,6 → 14,7
package org.openconcerto.erp.core.common.ui;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
48,7 → 49,7
public class IListFilterDatePanel extends JPanel {
 
private JDate dateDu, dateAu;
private static final String CUSTOM_COMBO_ITEM = "Personnalisée";
private static final String CUSTOM_COMBO_ITEM = TM.tr("dateFilter.custom");
private Map<IListe, SQLField> mapList;
// Cache des transformers initiaux
private Map<IListe, ITransformer<SQLSelect, SQLSelect>> mapListTransformer;
93,7 → 94,7
 
// ALL
Date emptyDate = null;
mapDefault.put("Sans filtrage", Tuple2.create(emptyDate, emptyDate));
mapDefault.put(TM.tr("dateFilter.none"), Tuple2.create(emptyDate, emptyDate));
 
Calendar c = Calendar.getInstance();
// Année courante
105,7 → 106,7
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d2 = c.getTime();
mapDefault.put("Année courante", Tuple2.create(d1, d2));
mapDefault.put(TM.tr("dateFilter.currentYear"), Tuple2.create(d1, d2));
 
// Année précedente
clearTimeSchedule(c);
118,7 → 119,7
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d4 = c.getTime();
mapDefault.put("Année précédente", Tuple2.create(d3, d4));
mapDefault.put(TM.tr("dateFilter.previousYear"), Tuple2.create(d3, d4));
 
// Mois courant
c = Calendar.getInstance();
128,7 → 129,7
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d6 = c.getTime();
mapDefault.put("Mois courant", Tuple2.create(d5, d6));
mapDefault.put(TM.tr("dateFilter.currentMonth"), Tuple2.create(d5, d6));
 
// Mois précédent
c = Calendar.getInstance();
139,7 → 140,7
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d8 = c.getTime();
mapDefault.put("Mois précédent", Tuple2.create(d7, d8));
mapDefault.put(TM.tr("dateFilter.previousMonth"), Tuple2.create(d7, d8));
 
// semaine courante
c = Calendar.getInstance();
149,7 → 150,7
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d10 = c.getTime();
mapDefault.put("Semaine courante", Tuple2.create(d9, d10));
mapDefault.put(TM.tr("dateFilter.currentWeek"), Tuple2.create(d9, d10));
 
// semaine précédente
c = Calendar.getInstance();
160,7 → 161,7
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d12 = c.getTime();
mapDefault.put("Semaine précédente", Tuple2.create(d11, d12));
mapDefault.put(TM.tr("dateFilter.previousWeek"), Tuple2.create(d11, d12));
 
// Exercice courant
SQLRow rowEx = ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getForeignRow("ID_EXERCICE_COMMON");
171,7 → 172,7
 
final Tuple2<Date, Date> exerciceTuple = Tuple2.create(c1.getTime(), c2.getTime());
if (findItem(exerciceTuple, mapDefault).equals(CUSTOM_COMBO_ITEM)) {
mapDefault.put("Exercice courant", exerciceTuple);
mapDefault.put(TM.tr("dateFilter.currentFiscalYear"), exerciceTuple);
}
 
// Custom
202,7 → 203,7
 
public void init(Map<IListe, SQLField> mapList, Map<String, Tuple2<Date, Date>> m) {
 
this.setBorder(BorderFactory.createTitledBorder("Période"));
this.setBorder(BorderFactory.createTitledBorder(TM.tr("dateFilter.range")));
this.mapList = mapList;
 
this.mapListTransformer = new HashMap<IListe, ITransformer<SQLSelect, SQLSelect>>();
242,9 → 243,9
});
}
// Filtre
this.add(new JLabel("Du"), c);
this.add(new JLabel(TM.tr("dateFilter.from")), c);
this.add(this.dateDu, c);
this.add(new JLabel("Au"), c);
this.add(new JLabel(TM.tr("dateFilter.to")), c);
this.add(this.dateAu, c);
this.dateAu.addValueListener(this.listener);
this.dateDu.addValueListener(this.listener);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/NumberCellRenderer.java
New file
0,0 → 1,51
/*
* 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.common.ui;
 
import org.openconcerto.ui.table.TableCellRendererUtils;
 
import java.awt.Component;
import java.text.DecimalFormat;
 
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
 
public class NumberCellRenderer extends DefaultTableCellRenderer {
DecimalFormat decimalFormat = new DecimalFormat("##,##0.00");
private final String suffix;
 
public NumberCellRenderer() {
this("");
}
 
public NumberCellRenderer(String suffix) {
super();
this.suffix = suffix;
}
 
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final Component res = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
TableCellRendererUtils.setColors(res, table, isSelected);
((JLabel) res).setHorizontalAlignment(SwingConstants.RIGHT);
if (value == null) {
((JLabel) res).setText("");
} else {
((JLabel) res).setText(decimalFormat.format(((Number) value).doubleValue()) + this.suffix);
}
return res;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/DeviseCellEditor.java
26,7 → 26,9
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.AbstractCellEditor;
42,8 → 44,9
*
*/
public class DeviseCellEditor extends AbstractCellEditor implements TableCellEditor, MouseListener {
private JTextField textField = new JTextField();
private float taxe = 19.6F;
private final JTextField textField = new JTextField();
private float taxe = -1;
private final List<KeyListener> keyL = new ArrayList<>();
 
public DeviseCellEditor() {
// Mimic JTable.GenericEditor behavior
51,10 → 54,28
this.textField.setHorizontalAlignment(JTextField.RIGHT);
// On ne peut saisir qu'un chiffre à 2 décimales
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
for (KeyListener keyListener : keyL) {
keyListener.keyPressed(e);
}
}
 
@Override
public void keyReleased(KeyEvent e) {
for (KeyListener keyListener : keyL) {
keyListener.keyReleased(e);
}
}
 
@Override
public void keyTyped(java.awt.event.KeyEvent keyEvent) {
 
final char keychar = keyEvent.getKeyChar();
 
for (KeyListener keyListener : keyL) {
keyListener.keyTyped(keyEvent);
}
 
if (keychar == KeyEvent.VK_BACK_SPACE) {
return;
}
63,7 → 84,6
int pointPosition = textField.getText().indexOf('.');
if (Character.isDigit(keychar)) {
if (pointPosition > -1) {
// System.err.println("Text Selected :: " + textField.getSelectedText());
if (textField.getSelectedText() == null) {
if (textField.getCaretPosition() <= pointPosition) {
return;
84,7 → 104,6
return;
if (keychar == KeyEvent.VK_MINUS && (textField.getText().indexOf('-') < 0) && textField.getCaretPosition() == 0)
return;
 
keyEvent.consume();
}
});
91,8 → 110,8
 
// on sélectionne tout lors de la selection
textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
 
textField.selectAll();
}
});
99,11 → 118,11
}
 
public void addKeyListener(KeyListener l) {
this.textField.addKeyListener(l);
this.keyL.add(l);
}
 
@Override
public boolean isCellEditable(EventObject e) {
 
if (e instanceof MouseEvent) {
return ((MouseEvent) e).getClickCount() >= 2;
}
111,9 → 130,16
}
 
public Object getCellEditorValue() {
 
return new Long(GestionDevise.parseLongCurrency(this.textField.getText()));
long l;
try {
l = GestionDevise.parseLongCurrency(this.textField.getText());
} catch (Exception e) {
// invalid text from copy/paste
l = 0;
System.err.println("DeviseCellEditor.getCellEditorValue() cannot parse " + this.textField.getText());
}
return Long.valueOf(l);
}
 
public void setConvertToTTCEnable(boolean b) {
if (b) {
127,10 → 153,8
this.taxe = d;
}
 
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
 
// System.err.println("Devise cell editor get Component " + value);
 
this.textField.setText(GestionDevise.currencyToString(value == null ? 0 : ((Long) value).longValue()));
this.textField.selectAll();
this.textField.grabFocus();
137,24 → 161,29
return this.textField;
}
 
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
 
// nothing
}
 
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
 
// nothing
}
 
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
// nothing
}
 
@Override
public void mouseReleased(MouseEvent e) {
// nothing
}
 
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (textField.getText().trim().length() > 0 && e.getButton() == MouseEvent.BUTTON3) {
if (this.taxe > 0 && textField.getText().trim().length() > 0 && e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu menuDroit = new JPopupMenu();
menuDroit.add(new AbstractAction("Convertir en HT (TVA " + taxe + ")") {
 
161,7 → 190,15
public void actionPerformed(ActionEvent e) {
 
String s = textField.getText();
PrixTTC p = new PrixTTC(GestionDevise.parseLongCurrency(s));
long l;
try {
l = GestionDevise.parseLongCurrency(s);
} catch (Exception ex) {
// invalid text from copy/paste
l = 0;
System.err.println("DeviseCellEditor.mousePressed() cannot parse " + s);
}
PrixTTC p = new PrixTTC(l);
textField.setText(GestionDevise.currencyToString(p.calculLongHT(taxe / 100.0)));
}
});
171,8 → 208,4
}
}
 
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractArticleItemTable.java
26,7 → 26,9
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.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.RowValuesTable;
69,6 → 71,7
protected SQLTableElement tableElementPoidsTotal;
protected SQLTableElement tableElementEcoID, tableElementEco, tableElementEcoTotal;
protected SQLTableElement prebilan;
protected SQLRowAccessor rowCatComptable;
private RowValuesTableModel model;
protected SQLRowValues defaultRowVals;
private List<JButton> buttons = null;
91,6 → 94,10
uiInit();
}
 
public void setRowCatComptable(SQLRowAccessor rowCatComptable) {
this.rowCatComptable = rowCatComptable;
}
 
/**
*
*/
262,12 → 269,24
SQLPreferences prefs = SQLPreferences.getMemCached(tableArticle.getDBRoot());
final boolean createArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
 
if (createArticle) {
 
SQLRowValues rowValsToFetch = new SQLRowValues(eltArticleTable.getTable());
rowValsToFetch.putNulls(eltArticleTable.getTable().getFieldsName());
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsToFetch);
Where w = new Where(eltArticleTable.getTable().getField("CODE"), "!=", "");
w = w.and(new Where(eltArticleTable.getTable().getField("NOM"), "!=", ""));
Where w2 = new Where(eltArticleTable.getTable().getField("ID_ARTICLE"), "!=", tableArticle.getUndefinedID());
w2 = w2.or(new Where(eltArticleTable.getTable().getField("ID_ARTICLE"), "!=", (Object) null));
final List<SQLRowValues> resultNonAssigned = fetcher.fetch(w.and(w2).and(new Where(eltArticleTable.getTable().getForeignKeys(eltSource.getTable()).iterator().next(), "=", id)));
 
// On récupére les articles qui composent la table
final List<SQLRow> listElts = eltSource.getTable().getRow(id).getReferentRows(eltArticleTable.getTable());
// final List<SQLRow> listElts =
// eltSource.getTable().getRow(id).getReferentRows(eltArticleTable.getTable());
final SQLRowValues rowArticle = new SQLRowValues(tableArticle);
final Set<SQLField> fields = tableArticle.getFields();
 
for (final SQLRow rowElt : listElts) {
for (final SQLRowAccessor rowElt : resultNonAssigned) {
// final SQLRow foreignRow = rowElt.getForeignRow("ID_ARTICLE");
// if (foreignRow == null || foreignRow.isUndefined()) {
final Set<String> fieldsName = rowElt.getTable().getFieldsName();
297,6 → 316,7
}
// ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
}
}
// }
}
 
480,6 → 500,7
for (int i = eltsList.size() - 1; i >= 0; i--) {
SQLRowAccessor sqlRowArticleChildElement = eltsList.get(i);
final SQLRowAccessor foreignArticleChild = sqlRowArticleChildElement.getForeign("ID_ARTICLE");
if (foreignArticleChild != null && !foreignArticleChild.isUndefined()) {
final SQLRowValues row2Insert = new SQLRowValues(this.model.getDefaultRowValues());
 
m.fillRowValues(foreignArticleChild, fieldsFrom, row2Insert);
552,10 → 573,10
Map<String, Integer> allStyleByName = getSQLElement().getDirectory().getElement(StyleSQLElement.class).getAllStyleByName();
row2Insert.put("ID_STYLE", allStyleByName.get("Composant"));
this.model.addRowAt(index + 1, row2Insert);
 
}
}
}
}
 
protected List<AbstractAction> getAdditionnalMouseAction(final int rowIndex) {
return Collections.emptyList();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractVenteArticleItemTable.java
109,6 → 109,7
 
public static final String EDIT_PRIX_VENTE_CODE = "CORPS_EDITER_PRIX_VENTE";
public static final String SHOW_PRIX_ACHAT_CODE = "CORPS_VOIR_PRIX_ACHAT";
public static final String SHOW_PRIX_VENTE_CODE = "CORPS_VOIR_PRIX_VENTE";
public static final String LOCK_PRIX_MIN_VENTE_CODE = "CORPS_VERROU_PRIX_MIN_VENTE";
 
public AbstractVenteArticleItemTable() {
264,6 → 265,7
final boolean filterFamilleArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.FILTER_BY_FAMILY, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
 
final UserRights rights = UserRightsManager.getCurrentUserRights();
final boolean editVTPrice = rights.haveRight(EDIT_PRIX_VENTE_CODE);
289,6 → 291,10
list.add(tableFamille);
 
// Article
SQLTableElement tableElementDepot = new SQLTableElement(e.getTable().getField("ID_DEPOT_STOCK"), true, true, true);
list.add(tableElementDepot);
 
// Article
SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true);
list.add(tableElementArticle);
 
321,12 → 327,10
list.add(tableElementDelai);
}
 
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Code Douanier
final SQLTableElement tableElementCodeDouane = new SQLTableElement(e.getTable().getField("CODE_DOUANIER"));
list.add(tableElementCodeDouane);
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
final SQLTableElement tableElementPays = new SQLTableElement(e.getTable().getField("ID_PAYS"));
list.add(tableElementPays);
}
427,7 → 431,7
 
SQLTableElement eltDevise = null;
SQLTableElement eltUnitDevise = null;
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Devise
eltDevise = new SQLTableElement(e.getTable().getField("ID_DEVISE"));
list.add(eltDevise);
727,7 → 731,7
this.totalHA.setEditable(false);
list.add(this.totalHA);
 
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Total HT
this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PV_T_DEVISE"), BigDecimal.class) {
@Override
838,7 → 842,21
defaultRowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
defaultRowVals.put("CODE", "");
defaultRowVals.put("NOM", "");
final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("ID_TAXE"), false, defaultRowVals);
final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("ID_TAXE"), false, defaultRowVals) {
@Override
public void commitData() {
int size = getRowCount();
for (int i = 0; i < size; i++) {
SQLRowValues rowVals = getRowValuesAt(i);
if (rowVals.getObject("PV_U_DEVISE") == null) {
rowVals.put("PV_U_DEVISE", rowVals.getObject("PRIX_METRIQUE_VT_1"));
final BigDecimal globalQty = rowVals.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(rowVals.getInt("QTE")));
rowVals.put("PV_T_DEVISE", rowVals.getBigDecimal("PRIX_METRIQUE_VT_1").multiply(globalQty));
}
}
super.commitData();
}
};
setModel(model);
 
this.table = new RowValuesTable(model, getConfigurationFile());
855,15 → 873,13
if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
completionField.add("ID_ECO_CONTRIBUTION");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("POURCENT_REMISE");
 
if (showDevise) {
completionField.add("CODE_DOUANIER");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("ID_PAYS");
}
completionField.add("POURCENT_REMISE");
completionField.add("ID_UNITE_VENTE");
completionField.add("QTE_UNITAIRE");
completionField.add("PA_HT");
completionField.add("PV_HT");
completionField.add("ID_TAXE");
883,10 → 899,8
if (getSQLElement().getTable().getFieldsName().contains("DESCRIPTIF")) {
completionField.add("DESCRIPTIF");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
completionField.add("ID_DEVISE");
}
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
completionField.add("PV_U_DEVISE");
}
if (getSQLElement().getTable().getFieldsName().contains("QTE_ACHAT") && sqlTableArticle.getTable().getFieldsName().contains("QTE_ACHAT")) {
921,8 → 935,8
final SQLTable tableStock = sqlTableArticle.getTable("STOCK");
input.andWhere(new Where(tableStock.getKey(), "=", sqlTableArticle.getField("ID_STOCK")));
input.setExcludeUndefined(false, tableStock);
Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE).or(new Where(input.getAlias(tableStock.getKey()), "=", tableStock.getUndefinedID()))
.or(new Where(input.getAlias(tableStock.getField("QTE_REEL")), ">", 0));
Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE)
.or(new Where(input.getAlias(tableStock.getKey()), "!=", tableStock.getUndefinedID()).and(new Where(input.getAlias(tableStock.getField("QTE_REEL")), ">", 0)));
 
if (input.getWhere() != null) {
input.setWhere(input.getWhere().and(w));
1189,7 → 1203,7
}
});
 
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
this.qte.addModificationListener(tableElementTotalDevise);
qteU.addModificationListener(tableElementTotalDevise);
if (eltUnitDevise != null) {
1330,7 → 1344,7
 
});
 
if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
if (eltUnitDevise != null) {
eltUnitDevise.addModificationListener(tableElement_PrixMetrique1_VenteHT);
}
1446,9 → 1460,12
setColumnVisible(getModel().getColumnForField("ID_FAMILLE_ARTICLE"), filterFamilleArticle);
 
setColumnVisible(model.getColumnForField("PRIX_METRIQUE_HA_1"), showHAPrice);
setColumnVisible(model.getColumnForField("MARGE_HT"), showHAPrice);
setColumnVisible(model.getColumnForField("T_PA_HT"), showHAPrice);
 
 
setColumnVisible(model.getColumnForField("ID_DEPOT_STOCK"), prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false));
 
for (String string : visibilityMap.keySet()) {
setColumnVisible(model.getColumnForField(string), visibilityMap.get(string));
}
1539,15 → 1556,15
 
protected Object tarifCompletion(SQLRowAccessor row, String field, SQLRowAccessor rowDest, boolean fromCompletion) {
 
if (row != null && !row.isUndefined() && getSQLElement().getTable().getDBRoot().contains("ARTICLE_PRIX_REVIENT")
&& (field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") || field.equalsIgnoreCase("PA_HT"))) {
if (row != null && !row.isUndefined() && (field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") || field.equalsIgnoreCase("PA_HT"))) {
 
if (getSQLElement().getTable().getDBRoot().contains("ARTICLE_PRIX_REVIENT")) {
final BigDecimal prc;
if (row.getBoolean("AUTO_PRIX_REVIENT_NOMENCLATURE")) {
ProductHelper helper = new ProductHelper(row.getTable().getDBRoot());
prc = helper.getBomPriceForQuantity(1, row.getReferentRows(row.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT")), TypePrice.ARTICLE_PRIX_REVIENT);
} else {
ProductComponent productComp = new ProductComponent(row, BigDecimal.ONE);
ProductComponent productComp = new ProductComponent(row, BigDecimal.ONE, null, null);
prc = productComp.getPRC(new Date());
}
if (prc == null) {
1554,7 → 1571,12
return BigDecimal.ZERO;
}
return prc;
} else if (getSQLElement().getTable().getDBRoot().contains("COUT_REVIENT") && row.getObject("ID_COUT_REVIENT") != null && !row.isForeignEmpty("ID_COUT_REVIENT")) {
BigDecimal ha = row.getBigDecimal(field);
BigDecimal percent = row.getForeign("ID_COUT_REVIENT").getBigDecimal("POURCENT");
return ha.multiply(percent.movePointLeft(2).add(BigDecimal.ONE)).setScale(ha.precision(), RoundingMode.HALF_UP);
}
}
 
if (getTarif() != null && !getTarif().isUndefined()) {
Collection<? extends SQLRowAccessor> rows = row.getReferentRows(tableArticleTarif);
1633,6 → 1655,10
}
}
 
if (field.equalsIgnoreCase("ID_TAXE_VENTE") && this.rowCatComptable != null) {
return this.rowCatComptable.getForeignID("ID_TAXE_VENTE");
}
 
if ((field.equalsIgnoreCase("POURCENT_REMISE"))) {
return new Acompte(BigDecimal.ZERO, BigDecimal.ZERO);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/SQLJavaEditor.java
275,19 → 275,29
Object interpreterResult = interpreter.interpret(bR, "memory");
bR.close();
try {
// this.status.setText(interpreter.getVariableNames().toString());
this.status.setText("Code correct, valeur de retour = " + interpreter.getVariable(varCallName).toString());
 
final Object variableValue = interpreter.getVariable(varCallName);
if (variableValue != null && Number.class.isAssignableFrom(variableValue.getClass())) {
this.status.setText("Code correct, valeur de retour = " + variableValue);
this.setCodeValid(true);
return interpreter.getVariable(varCallName);
} else {
this.status.setText("Code correct, valeur de retour incorrecte = " + variableValue);
setCodeValid(false);
return null;
}
} catch (IllegalStateException iSE) {
if (interpreterResult != null) {
// this.status.setText(interpreter.getVariableNames().toString());
if (interpreterResult != null && Number.class.isAssignableFrom(interpreterResult.getClass())) {
this.status.setText("Code correct, valeur de retour = " + interpreterResult.toString());
this.setCodeValid(true);
bR.close();
return interpreterResult;
} else {
// this.status.setText(interpreter.getVariableNames().toString());
this.status.setText("Code correct, valeur de retour incorrecte = " + interpreterResult);
setCodeValid(false);
return null;
}
} else {
this.status.setText("Aucune valeur de retour");
this.setCodeValid(false);
return null;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/NumericTextField.java
35,6 → 35,7
 
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
 
public class NumericTextField extends JTextField implements ValueWrapper<BigDecimal>, Documented, RowItemViewComponent {
192,9 → 193,19
if (this.getText().trim().length() == 0) {
return null;
} else {
try {
return new BigDecimal(this.getText().trim());
} catch (NumberFormatException ex) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setText("0");
}
});
return BigDecimal.ZERO;
}
}
}
 
@Override
public void addValueListener(PropertyChangeListener l) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/component/SocieteCommonSQLElement.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/DepartementSQLElement.java
28,7 → 28,7
public class DepartementSQLElement extends ComptaSQLConfElement {
 
public DepartementSQLElement() {
super("DEPARTEMENT", "Département", "Départements");
super("DEPARTEMENT", "un département", "départements");
}
 
protected List<String> getListFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/ComptaSQLConfElement.java
13,7 → 13,6
package org.openconcerto.erp.core.common.element;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLTable;
35,20 → 34,24
return baseSociete;
}
 
{
this.setL18nLocation(Gestion.class);
protected static SQLTable findTable(String tableName) {
return getBaseSociete().findTable(tableName, true);
}
 
public ComptaSQLConfElement(String tableName, String singular, String plural) {
super(getBaseSociete().findTable(tableName, true), singular, plural);
this(findTable(tableName), singular, plural);
}
 
public ComptaSQLConfElement(SQLTable table, String singular, String plural) {
super(table, singular, plural);
}
 
public ComptaSQLConfElement(String tableName) {
this(tableName, null);
}
 
public ComptaSQLConfElement(String tableName, String code) {
this(getBaseSociete().findTable(tableName, true), code);
this(findTable(tableName), code);
}
 
public ComptaSQLConfElement(SQLTable table) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/BanqueSQLElement.java
28,7 → 28,7
public static final String TABLENAME = ProductInfo.getInstance().getName().equals("OpenConcerto") ? "BANQUE" : "BANQUE_POLE_PRODUIT";
 
public BanqueSQLElement() {
super(TABLENAME, "une banque", "banques");
super(TABLENAME);
}
 
@Override
40,7 → 40,7
 
@Override
protected List<String> getComboFields() {
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>(2);
list.add("CODE");
list.add("NOM");
return list;
48,10 → 48,9
 
@Override
protected List<String> getListFields() {
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>(4);
list.add("CODE");
list.add("NOM");
 
list.add("ID_JOURNAL");
list.add("ID_COMPTE_PCE");
return list;
76,4 → 75,9
}
};
}
 
@Override
protected String createCode() {
return "bank";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/LangueSQLElement.java
29,7 → 29,7
public class LangueSQLElement extends ComptaSQLConfElement {
 
public LangueSQLElement() {
super("LANGUE", "Langue", "Langue");
super("LANGUE", "une langue", "langues");
}
 
protected List<String> getListFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/SocieteJoinSQLElement.java
13,16 → 13,11
package org.openconcerto.erp.core.common.element;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.element.JoinSQLElement;
import org.openconcerto.sql.model.SQLTable;
 
public abstract class SocieteJoinSQLElement extends JoinSQLElement {
 
{
this.setL18nLocation(Gestion.class);
}
 
public SocieteJoinSQLElement(SQLTable table, final String... fieldsToOwner) {
super(table, fieldsToOwner);
}
33,7 → 28,7
}
 
protected final String createCodeFromPackage() {
return SocieteSQLConfElement.createCodeFromPackage(SocieteSQLConfElement.getLastNonAbstractClass(this.getClass(), SocieteJoinSQLElement.class));
return SocieteSQLConfElement.createCodeOfPackage(SocieteSQLConfElement.getLastNonAbstractClass(this.getClass(), SocieteJoinSQLElement.class));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/PaysSQLElement.java
30,7 → 30,7
public class PaysSQLElement extends ComptaSQLConfElement {
 
public PaysSQLElement() {
super("PAYS", "Pays", "Pays");
super("PAYS", "un pays", "pays");
}
 
protected List<String> getListFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/NumerotationAutoSQLElement.java
67,6 → 67,7
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
 
import javax.swing.Icon;
import javax.swing.JCheckBox;
442,17 → 443,30
 
private static String getNextForMonth(Class<? extends SQLElement> clazz, Date d, SQLRowAccessor rowNum) {
 
final SQLTable table = Configuration.getInstance().getDirectory().getElement(clazz).getTable();
List<SQLTable> tables = new ArrayList<>();
SQLTable table = Configuration.getInstance().getDirectory().getElement(clazz).getTable();
tables.add(table);
final String s = map.get(clazz);
for (Entry<Class<? extends SQLElement>, String> entry : map.entrySet()) {
if (!entry.getKey().equals(clazz) && entry.getValue().equals(s)) {
tables.add(Configuration.getInstance().getDirectory().getElement(entry.getKey()).getTable());
}
}
 
final String pattern = rowNum.getString(s + FORMAT);
final Tuple2<String, String> prefixSuffix = getPrefixAndSuffix(pattern, d);
final String prefix = prefixSuffix.get0();
final String suffix = prefixSuffix.get1();
final String decimalPattern = "'" + prefix + "'" + suffix;
final DecimalFormat format = new DecimalFormat(decimalPattern);
int value = 0;
 
Where w = new Where(table.getField("NUMERO"), "LIKE", "%" + prefix + "%");
for (SQLTable sqlTable : tables) {
 
final SQLSelect sel = new SQLSelect();
sel.addSelect(table.getField("NUMERO"));
sel.addSelect(table.getKey());
sel.addSelect(sqlTable.getField("NUMERO"));
sel.addSelect(sqlTable.getKey());
Where w = new Where(sqlTable.getField("NUMERO"), "LIKE", "%" + prefix + "%");
 
sel.setWhere(w);
SQLDataSource source = Configuration.getInstance().getBase().getDataSource();
461,9 → 475,6
 
final List<SQLRow> l = (List<SQLRow>) source.execute(sel.asString(), new IResultSetHandler(createFromSelect, false));
 
final String decimalPattern = "'" + prefix + "'" + suffix;
final DecimalFormat format = new DecimalFormat(decimalPattern);
int value = 0;
for (SQLRow sqlRow : l) {
 
final String numero = sqlRow.getString("NUMERO");
476,6 → 487,7
exn.printStackTrace();
}
}
}
final String result = format.format(value + 1);
System.err.println("NumerotationAutoSQLElement.getNextForMonth(): " + result);
return result;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/AdresseCommonSQLElement.java
14,8 → 14,6
package org.openconcerto.erp.core.common.element;
 
import org.openconcerto.erp.core.common.component.AdresseCommonSQLComponent;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.utils.ListMap;
23,16 → 21,12
import java.util.ArrayList;
import java.util.List;
 
public class AdresseCommonSQLElement extends ConfSQLElement {
public class AdresseCommonSQLElement extends ComptaSQLConfElement {
 
public AdresseCommonSQLElement(DBRoot root) {
super(root.getTable("ADRESSE_COMMON"), "une adresse", "adresses");
}
 
public AdresseCommonSQLElement() {
this(Configuration.getInstance().getRoot());
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("RUE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/SocieteSQLConfElement.java
13,7 → 13,6
package org.openconcerto.erp.core.common.element;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.element.SQLElement;
75,9 → 74,6
public static final String ACTION_ID_ADD = "add";
public static final String ACTION_ID_MODIFY = "modify";
public static final String ACTION_ID_REMOVE = "remove";
{
this.setL18nLocation(Gestion.class);
}
 
public SocieteSQLConfElement(SQLTable table, String singular, String plural) {
super(singular, plural, table);
111,23 → 107,35
 
@Override
protected String createCode() {
return createCodeFromPackage();
final String suffix = this.createCodeSuffix();
if (suffix.indexOf(' ') >= 0)
throw new IllegalStateException("Suffix contains space : '" + suffix + "'");
if (suffix.length() < 2)
throw new IllegalStateException("Suffix too short : '" + suffix + "'");
return createCodeOfPackage() + suffix;
}
 
protected String createCodeSuffix() {
return this.createCodeSuffixFromTable();
}
 
protected final String createCodeSuffixFromTable() {
return '.' + this.getTable().getName();
}
 
/**
* Return a code that doesn't change when subclassing to allow to easily change a SQLElement
* while keeping the same code. To achieve that, the code isn't
* {@link #createCodeFromPackage(Class) computed} with <code>this.getClass()</code>. We iterate
* up through our superclass chain, and as soon as we find an abstract class, we stop and use
* the previous class (i.e. non abstract). E.g. any direct subclass of
* {@link ComptaSQLConfElement} will still use <code>this.getClass()</code>, but so is one of
* its subclass.
* {@link #createCodeOfPackage(Class) computed} with <code>this.getClass()</code>. We iterate up
* through our superclass chain, and as soon as we find an abstract class, we stop and use the
* previous class (i.e. non abstract). E.g. any direct subclass of {@link ComptaSQLConfElement}
* will still use <code>this.getClass()</code>, but so is one of its subclass.
*
* @return a code computed from the superclass just under the first abstract superclass.
* @see #createCodeFromPackage(Class)
* @see #createCodeOfPackage(Class)
*/
protected final String createCodeFromPackage() {
return createCodeFromPackage(getLastNonAbstractClass());
protected final String createCodeOfPackage() {
return createCodeOfPackage(getLastNonAbstractClass());
}
 
private final Class<? extends SocieteSQLConfElement> getLastNonAbstractClass() {
150,12 → 158,17
return prev.asSubclass(superClass);
}
 
static protected String createCodeFromPackage(final Class<? extends SQLElement> cl) {
String canonicalName = cl.getName();
if (canonicalName.contains("erp.core") && canonicalName.contains(".element")) {
int i = canonicalName.indexOf("erp.core") + 9;
static private final String ERP_CORE = ".erp.core.";
static private final String ERP_ELEMENT = ".erp.element.";
 
static protected String createCodeOfPackage(final Class<? extends SQLElement> cl) {
String canonicalName = cl.getPackage().getName();
if (canonicalName.contains(ERP_CORE) && canonicalName.contains(".element")) {
int i = canonicalName.indexOf(ERP_CORE) + ERP_CORE.length();
int j = canonicalName.indexOf(".element");
canonicalName = canonicalName.substring(i, j);
} else if (canonicalName.contains(ERP_ELEMENT)) {
canonicalName = canonicalName.substring(canonicalName.indexOf(ERP_ELEMENT) + ERP_ELEMENT.length());
}
return canonicalName;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/SocieteCommonSQLElement.java
New file
0,0 → 1,561
/*
* 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.common.element;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.panel.ChargementCreationSocietePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.ElementSQLObject;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.graph.TablesMap;
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;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.utils.ListMap;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
 
/**
* Sociétés existantes avec le nom de la base associée
*/
public class SocieteCommonSQLElement extends ComptaSQLConfElement {
 
private static final String TABLE_NAME = "SOCIETE_COMMON";
 
static public final DBRoot getRoot(final SQLRow company) {
try {
return getRoot(company, false);
} catch (SQLException e) {
// shouldn't happen since we don't allow refresh
throw new IllegalStateException(e);
}
}
 
static public final DBRoot getRoot(final SQLRow company, final boolean allowRefresh) throws SQLException {
final String rootName = company.getString("DATABASE_NAME");
final DBSystemRoot sysRoot = company.getTable().getDBSystemRoot();
if (allowRefresh && !sysRoot.contains(rootName)) {
sysRoot.addRootToMap(rootName);
sysRoot.refresh(TablesMap.createFromTables(rootName, Collections.singleton(TABLE_NAME)), true);
}
return sysRoot.getRoot(rootName);
}
 
public SocieteCommonSQLElement(DBRoot root) {
super(root.getTable(TABLE_NAME), "une société", "sociétés");
}
 
@Override
public ListMap<String, String> getShowAs() {
return ListMap.singleton(null, getListFields());
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
return l;
}
 
public final static Date getDateDebutExercice() {
 
SQLTable tableExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON");
 
SQLRow societeRow = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
return (Date) tableExercice.getRow(societeRow.getInt("ID_EXERCICE_COMMON")).getObject("DATE_DEB");
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
 
private JTextField textNom, textNumSiret, textNumNII, textNumAPE;
private JTextField textNumTel, textNumFax, textEmail, textNumUrssaff;
// private ITextArea textAdresse;
private JComboBox combo;
private JLabel labelPlan;
private ElementSQLObject eltExercice;
private TitledSeparator sep, sepPlan;
private SQLTextCombo textType;
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
this.textNom = new JTextField();
this.textNumAPE = new JTextField();
this.textNumNII = new JTextField();
this.textNumSiret = new JTextField();
this.textNumTel = new JTextField();
this.textNumFax = new JTextField();
this.textEmail = new JTextField();
this.textType = new SQLTextCombo();
this.textNumUrssaff = new JTextField();
 
/***********************************************************************************
* Informations générales
**********************************************************************************/
TitledSeparator sepInfos = new TitledSeparator("Informations générales");
c.gridwidth = 4;
c.gridx = 0;
c.gridy++;
this.add(sepInfos, c);
 
// Type
c.gridy++;
c.gridwidth = 1;
c.weightx = 0;
JLabel labelType = new JLabel(getLabelFor("TYPE"));
labelType.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelType, c);
 
c.gridx++;
c.gridwidth = 1;
c.weightx = 1;
this.add(this.textType, c);
 
// Nom
c.gridx++;
c.gridwidth = 1;
c.weightx = 0;
JLabel labelNom = new JLabel(getLabelFor("NOM"));
labelNom.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNom, c);
 
c.gridx++;
c.gridwidth = 1;
c.weightx = 1;
this.add(this.textNom, c);
 
// Numero Siret
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelNumSiret = new JLabel(getLabelFor("NUM_SIRET"));
labelNumSiret.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNumSiret, c);
 
c.gridx++;
c.weightx = 1;
this.add(this.textNumSiret, c);
 
// Numero NII
c.gridx++;
c.weightx = 0;
JLabel labelNumNII = new JLabel(getLabelFor("NUM_NII"));
labelNumNII.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNumNII, c);
 
c.gridx++;
c.weightx = 1;
this.add(this.textNumNII, c);
 
// Numero URSSAF
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelNumUrs = new JLabel(getLabelFor("NUMERO_URSSAF"));
labelNumUrs.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNumUrs, c);
 
c.gridx++;
c.weightx = 1;
this.add(this.textNumUrssaff, c);
 
// Numero APE
c.gridx++;
c.weightx = 0;
JLabel labelNumAPE = new JLabel(getLabelFor("NUM_APE"));
labelNumAPE.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNumAPE, c);
 
c.gridx++;
c.weightx = 1;
this.add(this.textNumAPE, c);
 
// Org social
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelIDSoc = new JLabel(getLabelFor("ORG_PROTECTION_SOCIAL_ID"));
labelIDSoc.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelIDSoc, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldIDSoc = new JTextField();
this.add(fieldIDSoc, c);
this.addView(fieldIDSoc, "ORG_PROTECTION_SOCIAL_ID");
 
// RCS
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelRCS = new JLabel(getLabelFor("RCS"));
labelRCS.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelRCS, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldRCS = new JTextField();
this.add(fieldRCS, c);
this.addView(fieldRCS, "RCS");
 
// Capital
c.gridx++;
c.weightx = 0;
JLabel labelCapital = new JLabel(getLabelFor("CAPITAL"));
labelCapital.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelCapital, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldCapital = new JTextField();
this.add(fieldCapital, c);
this.addView(fieldCapital, "CAPITAL");
 
// IBAN
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelIban = new JLabel(getLabelFor("IBAN"));
labelIban.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelIban, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldIban = new JTextField();
this.add(fieldIban, c);
this.addView(fieldIban, "IBAN");
 
// BIC
c.gridx++;
c.weightx = 0;
JLabel labelBIC = new JLabel(getLabelFor("BIC"));
labelBIC.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelBIC, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldBIC = new JTextField();
this.add(fieldBIC, c);
this.addView(fieldBIC, "BIC");
 
// SEPA creditor
c.gridx = 0;
c.gridy++;
c.weightx = 0;
JLabel labelICS = new JLabel(getLabelFor("SEPA_CREDITOR_ID"));
labelICS.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelICS, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldICS = new JTextField();
this.add(fieldICS, c);
this.addView(fieldICS, "SEPA_CREDITOR_ID");
 
// Assurance
if (getTable().contains("NUMERO_POLICE")) {
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelPolice = new JLabel(getLabelFor("NUMERO_POLICE"));
labelPolice.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelPolice, c);
 
c.gridx++;
c.weightx = 1;
JTextField fieldPolice = new JTextField();
this.add(fieldPolice, c);
this.addView(fieldPolice, "NUMERO_POLICE");
}
 
// Adresse
final TitledSeparator sepAdresse = new TitledSeparator(getLabelFor("ID_ADRESSE_COMMON"));
c.gridx = 0;
c.gridy++;
c.gridwidth = 4;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
this.add(sepAdresse, c);
this.addView("ID_ADRESSE_COMMON", REQ + ";" + DEC + ";" + SEP);
ElementSQLObject eltAdr = (ElementSQLObject) this.getView("ID_ADRESSE_COMMON");
c.gridy++;
this.add(eltAdr, c);
// Contact
JPanel panelContact = new JPanel();
panelContact.setLayout(new GridBagLayout());
panelContact.setBorder(BorderFactory.createTitledBorder("Contacts"));
final GridBagConstraints cc = new DefaultGridBagConstraints();
 
// Numero de telephone
JLabel labelNumTel = new JLabel(getLabelFor("NUM_TEL"));
labelNumTel.setHorizontalAlignment(SwingConstants.RIGHT);
cc.weightx = 0;
panelContact.add(labelNumTel, cc);
 
cc.gridx++;
cc.weightx = 1;
panelContact.add(this.textNumTel, cc);
 
// Numero de fax
cc.gridy++;
cc.gridx = 0;
cc.weightx = 0;
JLabel labelNumFax = new JLabel(getLabelFor("NUM_FAX"));
labelNumFax.setHorizontalAlignment(SwingConstants.RIGHT);
panelContact.add(labelNumFax, cc);
 
cc.gridx++;
cc.weightx = 1;
panelContact.add(this.textNumFax, cc);
 
// EMail
cc.gridx = 0;
cc.gridy++;
cc.weightx = 0;
JLabel labelEMail = new JLabel(getLabelFor("MAIL"));
labelEMail.setHorizontalAlignment(SwingConstants.RIGHT);
panelContact.add(labelEMail, cc);
 
cc.gridx++;
cc.weightx = 1;
panelContact.add(this.textEmail, cc);
 
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
this.add(panelContact, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
 
// Devise
if (getTable().contains("ID_DEVISE")) {
c.gridy++;
c.gridx = 0;
c.weightx = 0;
c.gridwidth = 1;
JLabel labelDevise = new JLabel(getLabelFor("ID_DEVISE"));
labelDevise.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelDevise, c);
 
c.gridx++;
c.gridwidth = 3;
c.fill = GridBagConstraints.NONE;
ElementComboBox boxDevise = new ElementComboBox();
this.add(boxDevise, c);
this.addView(boxDevise, "ID_DEVISE");
}
 
/***********************************************************************************
* DATE D'EXERCICE
**********************************************************************************/
this.sep = new TitledSeparator("Date de l'exercice");
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.gridy++;
c.insets = new Insets(10, 2, 1, 2);
c.fill = GridBagConstraints.HORIZONTAL;
this.add(this.sep, c);
 
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.weighty = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(2, 2, 1, 2);
 
this.addView("ID_EXERCICE_COMMON", REQ + ";" + DEC + ";" + SEP);
this.eltExercice = (ElementSQLObject) this.getView("ID_EXERCICE_COMMON");
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(this.eltExercice, c);
 
// Regime fiscale
/*
* c.gridx = 0; c.gridy++; c.gridwidth = 1; c.weightx = 0; JLabel labelRegime = new
* JLabel("Régime fiscale ");
* labelRegime.setHorizontalAlignment(SwingConstants.RIGHT); this.add(labelRegime,
* c);
*/
 
/***********************************************************************************
* Choix du plan comptable
**********************************************************************************/
this.sepPlan = new TitledSeparator("Plan comptable de l'entreprise");
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.gridy++;
c.insets = new Insets(10, 2, 1, 2);
this.add(this.sepPlan, c);
JPanel panelPlan = new JPanel();
this.labelPlan = new JLabel("Choix du plan comptable", SwingConstants.RIGHT);
this.combo = new JComboBox();
this.combo.addItem("Base");
this.combo.addItem("Abrégé");
this.combo.addItem("Développé");
panelPlan.add(this.labelPlan);
panelPlan.add(this.combo);
 
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.insets = new Insets(2, 2, 1, 2);
c.fill = GridBagConstraints.NONE;
this.add(panelPlan, c);
 
c.gridy++;
final JPanel additionalPanel = new JPanel();
this.add(additionalPanel, c);
this.setAdditionalFieldsPanel(new FormLayouter(additionalPanel, 2, 1));
 
this.addRequiredSQLObject(this.textNom, "NOM");
// this.addSQLObject(this.textAdresse, "ADRESSE");
this.addRequiredSQLObject(this.textNumAPE, "NUM_APE");
this.addRequiredSQLObject(this.textNumNII, "NUM_NII");
this.addRequiredSQLObject(this.textNumSiret, "NUM_SIRET");
this.addSQLObject(this.textEmail, "MAIL");
this.addSQLObject(this.textNumTel, "NUM_TEL");
this.addSQLObject(this.textNumFax, "NUM_FAX");
this.addSQLObject(this.textNumUrssaff, "NUMERO_URSSAF");
this.addSQLObject(this.textType, "TYPE");
}
 
public int insert(SQLRow order) {
int id = super.insert(order);
SQLRow row = getTable().getRow(id);
SQLRowValues rowVals = row.getForeignRow("ID_EXERCICE_COMMON").createEmptyUpdateRow();
rowVals.put("ID_SOCIETE_COMMON", id);
try {
rowVals.update();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
creationBase(id, this.combo.getSelectedIndex());
return id;
}
 
/*
* public int insert() {
*
* int id = super.insert(); creationBase(id); return id; }
*/
 
private void creationBase(int id, int typePCG) {
 
System.err.println("display chargement societe panel");
 
PanelFrame frameChargement = new PanelFrame(new ChargementCreationSocietePanel(id, typePCG), "Création d'une société");
frameChargement.setVisible(true);
 
/*
* System.err.println("Création de la base");
* ActionDB.dupliqueMySQLDB("Default", "OpenConcerto" + id); SQLRowValues
* rowVals = new SQLRowValues(getTable()); rowVals.put("DATABASE_NAME", "OpenConcerto"
* + id); try { rowVals.update(id); } catch (SQLException e) {
*
* e.printStackTrace(); }
*/
/*
* SQLTable comptePCETable = ((ComptaPropsConfiguration)
* Configuration.getInstance()).getSQLBaseSociete().getTable("COMPTE_PCE"); SQLTable
* comptePCGTable = ((ComptaPropsConfiguration)
* Configuration.getInstance()).getSQLBaseSociete().getTable("COMPTE_PCG"); // MAYBE
* Vérifier qu'aucun n'est deja créé???? // On crée le PCE à partir du PCG
* selectionné; SQLSelect selCompte = new SQLSelect(getTable().getBase());
* selCompte.addSelect(comptePCGTable.getField("NUMERO"));
* selCompte.addSelect(comptePCGTable.getField("NOM"));
* selCompte.addSelect(comptePCGTable.getField("INFOS"));
*
* if (this.combo.getSelectedIndex() == 0) {
* selCompte.setWhere("ID_TYPE_COMPTE_PCG_BASE", "!=", 1); } else { if
* (this.combo.getSelectedIndex() == 1) {
* selCompte.setWhere("ID_TYPE_COMPTE_PCG_AB", "!=", 1); } }
*
* String reqCompte = selCompte.asString(); Object obRep =
* getTable().getBase().getDataSource().execute(reqCompte, new ArrayListHandler());
*
* List tmpCpt = (List) obRep;
*
* for (int i = 0; i < tmpCpt.size(); i++) { Object[] tmp = (Object[])
* tmpCpt.get(i);
*
* SQLRowValues vals = new SQLRowValues(comptePCETable); vals.put("NUMERO", tmp[0]);
* vals.put("NOM", tmp[1]); vals.put("INFOS", tmp[2]);
*
* try { vals.insert(); } catch (SQLException e) { e.printStackTrace(); } }
*/
}
 
@Override
public void select(SQLRowAccessor r) {
super.select(r);
if (r != null) {
disableEdition();
}
}
 
@Override
public void update() {
// TODO Auto-generated method stub
super.update();
ComptaPropsConfiguration.getInstanceCompta().getRowSociete().fetchValues();
}
 
public void disableEdition() {
this.combo.setVisible(false);
this.labelPlan.setVisible(false);
this.eltExercice.setEditable(InteractionMode.DISABLED);
this.sepPlan.setVisible(false);
}
};
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/HistoriqueClientFrame.java
59,6 → 59,7
mapList.put("Avoirs", Arrays.asList("AVOIR_CLIENT"));
mapList.put("Articles facturés", Arrays.asList("SAISIE_VENTE_FACTURE_ELEMENT"));
mapList.put("Articles proposés", Arrays.asList("DEVIS_ELEMENT"));
mapList.put("Encaissements", Arrays.asList("ENCAISSER_MONTANT"));
Map<SQLTable, SQLField> map = new HashMap<SQLTable, SQLField>();
map.put(b.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), b.getTable("SAISIE_VENTE_FACTURE_ELEMENT").getField("ID_SAISIE_VENTE_FACTURE"));
map.put(b.getTable("DEVIS_ELEMENT"), b.getTable("DEVIS_ELEMENT").getField("ID_DEVIS"));
68,8 → 69,8
Where wNotRegle = new Where(tableEch.getField("REGLE"), "=", Boolean.FALSE);
wNotRegle = wNotRegle.and(new Where(tableEch.getField("REG_COMPTA"), "=", Boolean.FALSE));
 
this.listPanel = new ListeHistoriquePanel("Clients", JListSQLTablePanel.createComboRequest(Configuration.getInstance().getDirectory().getElement(b.getTable("CLIENT")), true), mapList,
bilanPanel, map, wNotRegle);
this.listPanel = new ListeHistoriquePanel("Clients", JListSQLTablePanel.createComboRequest(Configuration.getInstance().getDirectory().getElement(b.getTable("CLIENT")), false), mapList,
bilanPanel, map, null, wNotRegle);
this.listPanel.addListenerTable(new TableModelListener() {
public void tableChanged(TableModelEvent arg0) {
bilanPanel.updateRelance(HistoriqueClientFrame.this.listPanel.getListId("RELANCE"));
119,6 → 120,45
});
 
this.panelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 
// // Daet filter
// Map<IListe, SQLField> listeFilter = new HashMap<IListe, SQLField>();
// IListe listeRel = this.listPanel.getIListeFromTableName("RELANCE");
// listeFilter.put(listeRel, listeRel.getModel().getTable().getField("DATE"));
// IListe listeVtC = this.listPanel.getIListeFromTableName("SAISIE_VENTE_COMPTOIR");
// listeFilter.put(listeVtC, listeVtC.getModel().getTable().getField("DATE"));
// IListe listeDevis = this.listPanel.getIListeFromTableName("DEVIS");
// listeFilter.put(listeDevis, listeDevis.getModel().getTable().getField("DATE"));
//
// IListe listeChq = this.listPanel.getIListeFromTableName("CHEQUE_A_ENCAISSER");
// listeFilter.put(listeChq, listeChq.getModel().getTable().getField("DATE"));
//
// IListe listeEch = this.listPanel.getIListeFromTableName("ECHEANCE_CLIENT");
// listeFilter.put(listeEch, listeEch.getModel().getTable().getField("DATE"));
// IListe listedevisElt = this.listPanel.getIListeFromTableName("DEVIS_ELEMENT");
// listeFilter.put(listedevisElt,
// listedevisElt.getModel().getTable().getForeignTable("ID_DEVIS").getField("DATE"));
//
// IListe listeAvoir = this.listPanel.getIListeFromTableName("AVOIR_CLIENT");
// listeFilter.put(listeAvoir, listeAvoir.getModel().getTable().getField("DATE"));
//
// IListe listefactElt =
// this.listPanel.getIListeFromTableName("SAISIE_VENTE_FACTURE_ELEMENT");
// listeFilter.put(listefactElt,
// listefactElt.getModel().getTable().getForeignTable("ID_SAISIE_VENTE_FACTURE").getField("DATE"));
//
// IListe listeFact = this.listPanel.getIListeFromTableName("SAISIE_VENTE_FACTURE");
// listeFilter.put(listeFact, listeFact.getModel().getTable().getField("DATE"));
//
// final IListFilterDatePanel panel = new IListFilterDatePanel(listeFilter,
// IListFilterDatePanel.getDefaultMap());
// GridBagConstraints c = new DefaultGridBagConstraints();
// c.gridy = 4;
// c.gridwidth = GridBagConstraints.REMAINDER;
// c.weightx = 1;
// c.gridx=0;
// this.listPanel.add(panel);
 
}
 
public PanelFrame getFrame() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/HistoriqueArticleFrame.java
New file
0,0 → 1,95
/*
* 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.reports.history.ui;
 
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.users.rights.JListSQLTablePanel;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JFrame;
 
public class HistoriqueArticleFrame {
 
private PanelFrame panelFrame;
private ListeHistoriquePanel listPanel;
 
public HistoriqueArticleFrame(SQLElement articleElt) {
 
// List<String> l = new ArrayList<String>();
Map<String, List<String>> mapList = new HashMap<String, List<String>>();
 
mapList.put("Proposés", Arrays.asList("DEVIS_ELEMENT"));
mapList.put("Commandés (clients)", Arrays.asList("COMMANDE_CLIENT_ELEMENT"));
mapList.put("Livrés", Arrays.asList("BON_DE_LIVRAISON_ELEMENT"));
mapList.put("Facturés", Arrays.asList("SAISIE_VENTE_FACTURE_ELEMENT"));
 
mapList.put("Commandés (fournisseurs)", Arrays.asList("COMMANDE_ELEMENT"));
 
this.listPanel = new ListeHistoriquePanel("Articles", JListSQLTablePanel.createComboRequest(articleElt, true), mapList, null, null, null);
 
for (int i = 0; i < 4; i++) {
IListPanel panel = this.listPanel.getListePanel(i);
final SQLTable primaryTable = panel.getListe().getSource().getPrimaryTable();
List<SQLField> asList = new ArrayList<>();
asList.add(primaryTable.getField("QTE"));
if (primaryTable.contains("T_PV_HT")) {
asList.add(primaryTable.getField("T_PV_HT"));
} else {
asList.add(primaryTable.getField("T_PA_HT"));
}
IListTotalPanel totalPanel = new IListTotalPanel(panel.getListe(), asList);
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridy += 2;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
panel.add(totalPanel, c);
}
 
this.panelFrame = new PanelFrame(this.listPanel, "Historique client");
this.panelFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
listPanel.removeAllTableListener();
};
});
 
this.panelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
 
public PanelFrame getFrame() {
return this.panelFrame;
}
 
public void selectId(int id) {
this.listPanel.selectIDinJList(id);
}
 
public void setVisible(boolean b) {
this.panelFrame.setVisible(b);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java
312,10 → 312,9
});
// request.setWhere(where);
}
} else {
}
// Evite de charger les listes completes à la création de la fenetre
request.setWhere(Where.FALSE);
}
 
if (elt.getTable().contains("ID_MOUVEMENT")) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/product/component/ArticleFournisseurSQLComponent.java
496,15 → 496,6
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;
panel.add(new JLabel(getLabelFor("QTE_ACHAT")), c);
c.gridx++;
c.weightx = 1;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/product/element/ArticleFournisseurSQLElement.java
93,6 → 93,6
 
@Override
protected String createCode() {
return createCodeFromPackage();
return createCodeOfPackage();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/product/element/FamilleArticleFounisseurSQLElement.java
171,6 → 171,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".family";
return createCodeOfPackage() + ".family";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSQLElement.java
New file
0,0 → 1,202
/*
* 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.supplychain.stock.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.sales.invoice.report.EtatStockInventaireXmlSheet;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.SwingThreadUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
 
public class EtatStockSQLElement extends ComptaSQLConfElement {
 
public EtatStockSQLElement() {
super("ETAT_STOCK");
setDefaultGroup(new EtatStockGroup());
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Créer un état de stock") {
 
@Override
public void actionPerformed(ActionEvent e) {
EtatStockSnapshotCreator creator = new EtatStockSnapshotCreator(new Date(), getTable().getDBRoot());
creator.create();
}
}, true);
action.setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE));
getRowActions().add(action);
}
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Voir les articles") {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLElement element = getDirectory().getElement("ETAT_STOCK_ELEMENT");
SQLTableModelSource source = element.createTableSource(new Where(element.getTable().getField("ID_ETAT_STOCK"), "=", IListe.get(e).getSelectedId()));
final ListeViewPanel panel = new ListeViewPanel(element, new IListe(source));
IListFrame frame = new IListFrame(panel);
FrameUtil.show(frame);
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Export pour inventaire") {
@Override
public void actionPerformed(ActionEvent e) {
EtatStockInventaireXmlSheet sheet = new EtatStockInventaireXmlSheet(IListe.get(e).getSelectedRow().asRow());
try {
sheet.createDocument();
sheet.showPrintAndExport(true, false, false, false, false);
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de la création de l'inventaire", e1);
}
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Import Inventaire") {
@Override
public void actionPerformed(ActionEvent e) {
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource());
final FileDialog fd = new FileDialog(frame, "Import Inventaire", FileDialog.LOAD);
fd.setVisible(true);
if (fd.getFile() != null) {
final File f = new File(fd.getDirectory(), fd.getFile());
if (!f.exists()) {
JOptionPane.showMessageDialog(null, "Le ficher selectionné n'existe pas", "Erreur", JOptionPane.ERROR_MESSAGE);
} else if (f.isDirectory()) {
JOptionPane.showMessageDialog(null, "Le fichier selectionné n'est pas valide", "Erreur", JOptionPane.ERROR_MESSAGE);
} else {
new Thread(new Runnable() {
 
@Override
public void run() {
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter();
try {
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(final SQLDataSource ds) throws SQLException, IOException {
 
impoter.importArticles(f, getTable().getDBRoot());
return null;
}
});
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de l'importation", e1);
}
 
}
}).start();
}
}
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<>(3);
l.add("DATE");
l.add("MONTANT_HA");
l.add("INVENTAIRE");
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<>(2);
l.add("DATE");
l.add("MONTANT_HA");
return l;
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new GroupSQLComponent(this) {
 
@Override
public JComponent createEditor(String id) {
if (id.equals("supplychain.stock.state.items")) {
return new EtatStockTable((JTextField) getEditor("MONTANT_HA"));
} else {
return super.createEditor(id);
}
}
 
@Override
public void select(SQLRowAccessor r) {
super.select(r);
EtatStockTable table = (EtatStockTable) getEditor("supplychain.stock.state.items");
if (r != null) {
table.insertFrom("ID_ETAT_STOCK", r.getID());
}
}
 
@Override
public void update() {
super.update();
EtatStockTable table = (EtatStockTable) getEditor("supplychain.stock.state.items");
table.updateField("ID_ETAT_STOCK", getSelectedID());
}
};
}
 
@Override
protected String createCode() {
return createCodeOfPackage() + ".state";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/InventaireFromEtatStockImporter.java
New file
0,0 → 1,384
/*
* 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.supplychain.stock.element;
 
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
import org.openconcerto.erp.core.sales.product.model.ProductHelper;
import org.openconcerto.erp.core.sales.product.model.ProductHelper.SupplierPriceField;
import org.openconcerto.erp.importer.ArrayTableModel;
import org.openconcerto.erp.importer.DataImporter;
import org.openconcerto.sql.Configuration;
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.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.utils.SQLUtils;
 
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
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.Map;
import java.util.Set;
 
import org.apache.commons.dbutils.ResultSetHandler;
 
public class InventaireFromEtatStockImporter {
 
Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>();
List<String> codeKits = new ArrayList<String>();
 
public InventaireFromEtatStockImporter() {
 
}
 
public void importArticles(File file, DBRoot root) throws IOException, SQLException {
 
final SQLTable table = root.findTable("ARTICLE");
final SQLTable tableArtElt = root.findTable("ARTICLE_ELEMENT");
 
Map<String, SQLRowValues> articles = getArticles();
 
final DataImporter importer = new DataImporter(table) {
@Override
protected void customizeRowValuesToFetch(SQLRowValues vals) {
 
vals.putRowValues("ID_STOCK").putNulls("ID", "QTE_REEL", "QTE_TH", "ID_DEPOT_STOCK");
}
};
importer.setSkipFirstLine(true);
 
ArrayTableModel m = importer.createModelFrom(file);
 
Calendar c = Calendar.getInstance();
// c.set(Calendar.DAY_OF_MONTH, 1);
// c.set(Calendar.MONTH, Calendar.JANUARY);
// c.set(Calendar.HOUR_OF_DAY, 0);
Date today = c.getTime();
 
// TODO ne pas vider les stocks des kits, recalculer les stocks des kits
 
SQLRowValues rowVals = new SQLRowValues(table.getTable("ETAT_STOCK"));
rowVals.put("DATE", today);
rowVals.put("INVENTAIRE", Boolean.TRUE);
SQLRow rowEtat = rowVals.commit();
 
for (int i = 1; i < m.getRowCount(); i++) {
List<Object> o = m.getLineValuesAt(i);
if (o.size() >= 5) {
System.err.println(o);
String code = o.get(1).toString();
if (code.trim().length() > 0) {
 
final String stringQty = o.get(4).toString();
Double qty = stringQty.trim().length() == 0 ? 0 : Double.valueOf(stringQty);
final String stringQtyOld = o.get(3).toString();
float qtyOld = stringQtyOld.trim().length() == 0 ? 0 : Float.valueOf(stringQtyOld);
 
SQLRowValues match = articles.get(code);
if (match != null) {
 
SQLRowAccessor stockValues = match.getForeign("ID_STOCK");
 
final SQLTable tableMvt = table.getTable("MOUVEMENT_STOCK");
SQLRowValues rowValsMvtStockClotureFermeture = new SQLRowValues(tableMvt);
rowValsMvtStockClotureFermeture.put("QTE", -qtyOld);
rowValsMvtStockClotureFermeture.put("NOM", "Clôture stock avant inventaire");
rowValsMvtStockClotureFermeture.put("ID_ARTICLE", match.getID());
rowValsMvtStockClotureFermeture.put("DATE", today);
rowValsMvtStockClotureFermeture.put("REEL", Boolean.TRUE);
rowValsMvtStockClotureFermeture.put("ID_STOCK", stockValues.getID());
 
BigDecimal prc = getPRC(match, Math.round(qtyOld), today);
if (prc == null) {
prc = BigDecimal.ZERO;
}
if (tableMvt.contains("PRICE")) {
rowValsMvtStockClotureFermeture.put("PRICE", prc);
}
rowValsMvtStockClotureFermeture.put("CLOTURE", Boolean.TRUE);
rowValsMvtStockClotureFermeture.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsMvtStockClotureFermeture.getGraph().store(StoreMode.COMMIT, false);
 
SQLRowValues rowValsItem = new SQLRowValues(table.getTable("ETAT_STOCK_ELEMENT"));
rowValsItem.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsItem.put("PA", prc);
rowValsItem.put("PV", BigDecimal.ZERO);
rowValsItem.put("QTE", qtyOld);
rowValsItem.put("T_PA", prc.multiply(new BigDecimal(qtyOld)));
rowValsItem.put("T_PV", BigDecimal.ZERO);
rowValsItem.put("CODE", match.getString("CODE"));
rowValsItem.put("NOM", match.getString("NOM"));
rowValsItem.put("ID_ARTICLE", match.getID());
rowValsItem.getGraph().store(StoreMode.COMMIT, false);
 
SQLRowValues rowValsMvtStockClotureOuverture = new SQLRowValues(tableMvt);
rowValsMvtStockClotureOuverture.put("QTE", qty);
rowValsMvtStockClotureOuverture.put("NOM", "Mise en stock inventaire");
rowValsMvtStockClotureOuverture.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsMvtStockClotureOuverture.put("ID_ARTICLE", match.getID());
rowValsMvtStockClotureOuverture.put("DATE", today);
rowValsMvtStockClotureOuverture.put("REEL", Boolean.TRUE);
rowValsMvtStockClotureOuverture.put("ID_STOCK", stockValues.getID());
rowValsMvtStockClotureOuverture.put("OUVERTURE", Boolean.TRUE);
if (tableMvt.contains("PRICE")) {
rowValsMvtStockClotureOuverture.put("PRICE", getPRC(match, qty.intValue(), today));
}
rowValsMvtStockClotureOuverture.getGraph().store(StoreMode.COMMIT, false);
 
if (!match.isForeignEmpty("ID_STOCK")) {
match.getForeign("ID_STOCK").createEmptyUpdateRow().put("QTE_REEL", qty).commit();
} else {
final SQLRowValues createEmptyUpdateRow = match.createEmptyUpdateRow();
createEmptyUpdateRow.putRowValues("ID_STOCK").put("QTE_REEL", qty);
createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false);
 
}
 
} else {
System.err.println("Aucun article correspondant au code " + code);
}
}
}
}
 
/**
* Mise à jour des kits
*/
 
List<String> reqs = new ArrayList<String>();
for (String code : codeKits) {
System.err.println(code);
SQLRowValues rowValsKit = kits.get(code);
StockItem item = new StockItem(rowValsKit, rowValsKit.getForeign("ID_STOCK"));
Collection<SQLRowValues> elts = rowValsKit.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
for (SQLRowValues sqlRowValues : elts) {
if (sqlRowValues.getForeign("ID_ARTICLE") != null) {
item.addItemComponent(new StockItemComponent(new StockItem(sqlRowValues.getForeign("ID_ARTICLE"), sqlRowValues.getForeign("ID_ARTICLE").getForeign("ID_STOCK")),
sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
}
}
item.updateQtyFromChildren();
reqs.add(item.getUpdateRequest());
}
 
List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(reqs.size());
for (String s : reqs) {
handlers.add(null);
}
// FIXME FIRE TABLE CHANGED TO UPDATE ILISTE ??
SQLUtils.executeMultiple(table.getDBSystemRoot(), reqs, handlers);
 
/**
* Mise à jour des prix mini
*/
// for (SQLRowValues rowValsArt : rowValsArtNonSync) {
// SQLRow rowArt = rowValsArt.asRow();
// List<SQLRow> rowsPVMin =
// rowArt.getReferentRows(tableArtElt.getTable("ARTICLE_PRIX_MIN_VENTE"));
// List<SQLRow> rowsPA =
// rowArt.getReferentRows(tableArtElt.getTable("ARTICLE_TARIF_FOURNISSEUR"));
//
// // On récupére les derniers prix min valides
// Map<Integer, SQLRow> mapLastValidRows = new HashMap<Integer, SQLRow>();
// for (SQLRow rowPVMin : rowsPVMin) {
// final int qteMinPrice = rowPVMin.getInt("QTE");
// SQLRow rowValsLastValid = mapLastValidRows.get(qteMinPrice);
// if (rowValsLastValid == null || rowValsLastValid.getDate("DATE") == null ||
// rowValsLastValid.getDate("DATE").before(rowPVMin.getDate("DATE"))) {
// mapLastValidRows.put(qteMinPrice, rowPVMin);
// }
// }
//
// // On récupére les derniers Prix d'achat valide
// Map<Integer, SQLRow> mapLastValidAchatRows = new HashMap<Integer, SQLRow>();
// for (SQLRow rowPA : rowsPA) {
// final int qtePRC = rowPA.getInt("QTE");
// SQLRow rowValsLastValid = mapLastValidAchatRows.get(qtePRC);
// if (rowValsLastValid == null || rowValsLastValid.getDate("DATE_PRIX") == null ||
// rowValsLastValid.getDate("DATE_PRIX").before(rowPA.getDate("DATE_PRIX"))) {
// mapLastValidAchatRows.put(qtePRC, rowPA);
// }
// }
//
// // Mise à jour, si Prix < au prix min, du PRC et des prix min
// for (Integer qte : mapLastValidAchatRows.keySet()) {
// SQLRow rowVals = mapLastValidAchatRows.get(qte);
// checkMinPrice(rowVals, mapLastValidRows.get(qte));
// }
// }
 
}
 
private void checkMinPrice(SQLRow rowValsSuplierLastValid, SQLRow lastValidRow) {
boolean update = false;
final ProductHelper helper = new ProductHelper(rowValsSuplierLastValid.getTable().getDBRoot());
 
BigDecimal result = helper.getEnumPrice(rowValsSuplierLastValid, SupplierPriceField.COEF_PRIX_MINI);
if (result != null) {
final int qteSuplier = rowValsSuplierLastValid.getInt("QTE");
 
final Calendar date2 = rowValsSuplierLastValid.getDate("DATE_PRIX");
if (date2 != null) {
if (lastValidRow != null) {
final Calendar date1 = lastValidRow.getDate("DATE");
if ((date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) && date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)
&& date1.get(Calendar.DAY_OF_MONTH) == date2.get(Calendar.DAY_OF_MONTH)) || date1.after(date2)) {
if (lastValidRow.getBigDecimal("PRIX") != null && lastValidRow.getInt("QTE") <= qteSuplier) {
try {
lastValidRow.asRowValues().put("PRIX", result).commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// purchaseMinPriceListTable.setPriceMin(result);
update = true;
}
} else {
if (date1.before(date2)) {
SQLRowValues rowValsToInsert = new SQLRowValues(lastValidRow.getTable());
rowValsToInsert.put("PRIX", result);
rowValsToInsert.put("DATE", rowValsSuplierLastValid.getObject("DATE_PRIX"));
rowValsToInsert.put("QTE", rowValsSuplierLastValid.getObject("QTE"));
rowValsToInsert.put("ID_ARTICLE", rowValsSuplierLastValid.getInt("ID_ARTICLE"));
try {
rowValsToInsert.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
 
}
 
public BigDecimal getPRC(SQLRowValues rowVals, int qty, Date d) {
// SQLTable table = rowVals.getTable().getDBRoot().getTable("ARTICLE_PRIX_REVIENT");
// Collection<SQLRow> prcs = rowVals.asRow().getReferentRows(table);
//
// BigDecimal result = null;
// final List<PriceByQty> prices = new ArrayList<PriceByQty>();
//
// for (SQLRow row : prcs) {
// Calendar date = Calendar.getInstance();
// date.set(Calendar.DAY_OF_MONTH, 1);
// date.set(Calendar.MONTH, 1);
// date.set(Calendar.YEAR, 2001);
// if (row.getObject("DATE") != null) {
// date = row.getDate("DATE");
// }
// prices.add(new PriceByQty(row.getLong("QTE"), row.getBigDecimal("PRIX"),
// date.getTime()));
// }
//
// result = PriceByQty.getPriceForQty(qty, prices, d);
// if (result == null) {
// // Can occur during editing
// result = BigDecimal.ZERO;
// }
 
ProductComponent comp = new ProductComponent(rowVals, new BigDecimal(qty), null, null);
return comp.getPRC(d);
// return result;
}
 
private Map<String, SQLRowValues> getArticles() throws SQLException {
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
SQLRowValues graph = new SQLRowValues(table);
graph.put("ID", null);
graph.put("CODE", null);
graph.put("NOM", null);
graph.put("NOM", null);
graph.putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
 
final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT");
SQLRowValues artElt = new SQLRowValues(tableArtElt);
artElt.put("ID", null);
artElt.put("QTE", null);
artElt.put("QTE_UNITAIRE", null);
artElt.put("ID_ARTICLE_PARENT", graph);
artElt.putRowValues("ID_ARTICLE").putNulls("ID", "CODE", "NOM").putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph);
List<SQLRowValues> results = fetcher.fetch();
 
Calendar c = Calendar.getInstance();
// c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.MONTH, -2);
c.set(Calendar.DAY_OF_MONTH, 31);
Date dEndYear = c.getTime();
 
Map<String, SQLRowValues> vals = new HashMap<String, SQLRowValues>();
for (SQLRowValues sqlRowValues : results) {
final String code = sqlRowValues.getString("CODE");
vals.put(code, sqlRowValues);
 
final Set<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
if (referentRows.size() == 0) {
// if (!sqlRowValues.isForeignEmpty("ID_STOCK")) {
// SQLRowAccessor rowValsStock = sqlRowValues.getForeign("ID_STOCK");
// int qteReel = rowValsStock.getInt("QTE_REEL");
// {
// SQLRowValues rowValsMvtStockCloture = new
// SQLRowValues(table.getTable("MOUVEMENT_STOCK"));
// rowValsMvtStockCloture.put("QTE", -qteReel);
// rowValsMvtStockCloture.put("NOM", "Clôture du stock avant inventaire");
// rowValsMvtStockCloture.put("ID_ARTICLE", sqlRowValues.getID());
// rowValsMvtStockCloture.put("DATE", dEndYear);
// rowValsMvtStockCloture.put("REEL", Boolean.TRUE);
// rowValsMvtStockCloture.put("PRICE", getPRC(sqlRowValues, qteReel, dEndYear));
// rowValsMvtStockCloture.commit();
//
// rowValsStock.createEmptyUpdateRow().put("QTE_REEL", 0).commit();
// }
//
// } else {
// sqlRowValues.putRowValues("ID_STOCK").commit();
// }
} else {
boolean contains = false;
for (SQLRowValues sqlRowValues2 : referentRows) {
if (!sqlRowValues2.isForeignEmpty("ID_ARTICLE") && sqlRowValues2.getForeign("ID_ARTICLE") != null && sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE") != null) {
if (codeKits.contains(sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE"))) {
contains = true;
break;
}
}
}
if (!contains) {
codeKits.add(0, code);
} else {
codeKits.add(code);
}
kits.put(code, sqlRowValues);
// if (sqlRowValues.isForeignEmpty("ID_STOCK")) {
// sqlRowValues.putRowValues("ID_STOCK").commit();
// }
}
}
return vals;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStock.java
New file
0,0 → 1,72
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.math.BigDecimal;
 
public class EtatStock {
 
private SQLRowAccessor article;
private BigDecimal pa, pv, qte;
 
public EtatStock(SQLRowAccessor article) {
this.article = article;
this.pa = BigDecimal.ZERO;
this.pv = BigDecimal.ZERO;
this.qte = BigDecimal.ZERO;
}
 
public BigDecimal getPa() {
return pa;
}
 
public BigDecimal getPv() {
return pv;
}
 
public SQLRowAccessor getArticle() {
return article;
}
 
public BigDecimal getQte() {
return qte;
}
 
public void setQte(BigDecimal qte) {
this.qte = qte;
}
 
public void setPa(BigDecimal pa) {
this.pa = pa;
}
 
public void setPv(BigDecimal pv) {
this.pv = pv;
}
 
public BigDecimal getTotalPV() {
return this.pv.multiply(qte);
}
 
public BigDecimal getTotalPA() {
return this.pa.multiply(qte);
}
 
public BigDecimal getEcart() {
return getTotalPV().subtract(getTotalPA());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSnapshotCreator.java
New file
0,0 → 1,174
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLRow;
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 org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.ITransformer;
 
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class EtatStockSnapshotCreator {
 
private final Date d;
private final DBRoot root;
 
public EtatStockSnapshotCreator(Date d, DBRoot root) {
this.d = d;
this.root = root;
}
 
public void create() {
// Récupération des inventaires
SQLTable tableEtatStock = this.root.getTable("ETAT_STOCK");
SQLSelect sel = new SQLSelect();
sel.addSelectStar(tableEtatStock);
Where wEtat = new Where(tableEtatStock.getField("INVENTAIRE"), "=", Boolean.TRUE);
sel.setWhere(wEtat);
List<SQLRow> rowsEtatStock = SQLRowListRSH.execute(sel);
Map<Integer, Integer> mapEtatStock = new HashMap<Integer, Integer>();
for (SQLRow sqlRow : rowsEtatStock) {
SQLTable tableMvtStock = this.root.getTable("MOUVEMENT_STOCK");
SQLSelect selMvt = new SQLSelect();
selMvt.addSelect(tableMvtStock.getKey(), "MIN");
Where wMvt = new Where(tableMvtStock.getField("OUVERTURE"), "=", Boolean.TRUE);
wMvt = new Where(tableMvtStock.getField("ID_ETAT_STOCK"), "=", sqlRow.getID());
selMvt.setWhere(wMvt);
Integer idMvt = (Integer) tableMvtStock.getDBSystemRoot().getDataSource().executeScalar(selMvt.asString());
if (idMvt != null) {
mapEtatStock.put(sqlRow.getID(), idMvt);
}
}
 
Map<Integer, EtatStock> mapStockSnap = new HashMap<Integer, EtatStock>();
{
final SQLTable tableStock = this.root.getTable("MOUVEMENT_STOCK");
 
final SQLRowValues vals = new SQLRowValues(tableStock);
 
vals.put("QTE", null);
if (tableStock.contains("PRICE")) {
vals.put("PRICE", null);
}
vals.put("ID_ARTICLE", null);
// Calendar cal0116 = Calendar.getInstance();
// cal0116.set(2016, Calendar.JANUARY, 1, 0, 0, 0);
// final Date dateDeb = cal0116.getTime();
 
// Récupération du dernier etat de stock
SQLSelect selEtatD = new SQLSelect();
selEtatD.addSelectStar(tableEtatStock);
Where wEtatD = new Where(tableEtatStock.getField("INVENTAIRE"), "=", Boolean.TRUE);
selEtatD.setWhere(wEtatD);
List<SQLRow> rowsEtatStockD = SQLRowListRSH.execute(selEtatD);
SQLRow rowEtatStockDeb = null;
for (SQLRow sqlRow : rowsEtatStockD) {
 
if (sqlRow.getDate("DATE").getTime().before(this.d)) {
if (rowEtatStockDeb == null || rowEtatStockDeb.getDate("DATE").before(sqlRow.getDate("DATE"))) {
rowEtatStockDeb = sqlRow;
}
}
 
}
final Date dateDeb;
final Integer idMvtStockDeb;
if (rowEtatStockDeb != null) {
dateDeb = rowEtatStockDeb.getDate("DATE").getTime();
idMvtStockDeb = mapEtatStock.get(rowEtatStockDeb.getID());
} else {
dateDeb = null;
idMvtStockDeb = null;
}
 
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(vals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect sel) {
 
Where w = (new Where(tableStock.getField("DATE"), "<=", d));
 
if (dateDeb != null) {
w = w.and(new Where(tableStock.getField("DATE"), ">=", dateDeb));
w = w.and(new Where(tableStock.getKey(), ">=", idMvtStockDeb));
w = w.and(new Where(tableStock.getField("CLOTURE"), "!=", Boolean.TRUE));
}
w = w.and(new Where(tableStock.getField("REEL"), "=", Boolean.TRUE));
 
sel.setWhere(w);
return sel;
}
});
 
List<SQLRowValues> list = fetcher.fetch();
 
BigDecimal totalHT = BigDecimal.ZERO;
for (int i = 0; i < list.size(); i++) {
SQLRowValues rowVF = list.get(i);
if (!rowVF.isForeignEmpty("ID_ARTICLE") && rowVF.getForeignID("ID_ARTICLE") > rowVF.getForeign("ID_ARTICLE").getTable().getUndefinedID()) {
final int foreignIDArt = rowVF.getForeignID("ID_ARTICLE");
if (!mapStockSnap.containsKey(foreignIDArt)) {
mapStockSnap.put(foreignIDArt, new EtatStock(rowVF.getForeign("ID_ARTICLE")));
}
EtatStock et = mapStockSnap.get(foreignIDArt);
et.setQte(et.getQte().add(new BigDecimal(rowVF.getFloat("QTE"))));
BigDecimal bigDecimal = BigDecimal.ZERO;
if (tableStock.contains("PRICE")) {
bigDecimal = rowVF.getBigDecimal("PRICE");
}
et.setPa(bigDecimal);
totalHT = totalHT.add(bigDecimal.multiply(new BigDecimal(rowVF.getFloat("QTE"), DecimalUtils.HIGH_PRECISION)));
}
}
 
SQLRowValues rowVals = new SQLRowValues(tableEtatStock);
rowVals.put("DATE", d);
rowVals.put("MONTANT_HA", totalHT);
 
for (EtatStock etatItem : mapStockSnap.values()) {
SQLRowValues rowValsItem = new SQLRowValues(tableEtatStock.getTable("ETAT_STOCK_ELEMENT"));
rowValsItem.put("ID_ETAT_STOCK", rowVals);
rowValsItem.put("PA", etatItem.getPa());
rowValsItem.put("PV", etatItem.getPv());
rowValsItem.put("QTE", etatItem.getQte());
rowValsItem.put("T_PA", etatItem.getTotalPA());
rowValsItem.put("T_PV", etatItem.getTotalPV());
rowValsItem.put("CODE", etatItem.getArticle().getString("CODE"));
rowValsItem.put("NOM", etatItem.getArticle().getString("NOM"));
rowValsItem.put("ID_ARTICLE", etatItem.getArticle().getID());
}
try {
rowVals.commit();
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la création de l'état", e);
}
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItem.java
41,30 → 41,39
};
 
private double realQty, virtualQty, receiptQty, deliverQty;
public SQLRowAccessor article;
public SQLRowAccessor article, stock;
 
List<StockItemComponent> components = new ArrayList<StockItemComponent>();
 
public StockItem(SQLRowAccessor article) {
public StockItem(SQLRowAccessor article, SQLRowAccessor stock) {
this.article = article;
if (this.article.isForeignEmpty("ID_STOCK")) {
this.realQty = 0;
this.virtualQty = 0;
this.receiptQty = 0;
this.deliverQty = 0;
} else {
SQLRowAccessor row = this.article.getForeign("ID_STOCK");
this.realQty = row.getFloat("QTE_REEL");
this.virtualQty = row.getFloat("QTE_TH");
this.receiptQty = row.getFloat("QTE_RECEPT_ATTENTE");
this.deliverQty = row.getFloat("QTE_LIV_ATTENTE");
this.stock = stock;
this.realQty = stock.getFloat("QTE_REEL");
this.virtualQty = stock.getFloat("QTE_TH");
this.receiptQty = stock.getFloat("QTE_RECEPT_ATTENTE");
this.deliverQty = stock.getFloat("QTE_LIV_ATTENTE");
}
}
 
public void updateQty(double qty, TypeStockMouvement t) {
updateQty(qty, t, false);
}
 
public void setDeliverQty(double deliverQty) {
this.deliverQty = deliverQty;
}
 
public void setRealQty(double realQty) {
this.realQty = realQty;
}
 
public void setReceiptQty(double receiptQty) {
this.receiptQty = receiptQty;
}
 
public void setVirtualQty(double virtualQty) {
this.virtualQty = virtualQty;
}
 
public SQLRowAccessor getArticle() {
return article;
};
73,10 → 82,19
this.components.add(item);
};
 
public void updateQtyFromChildren() throws IllegalArgumentException {
public boolean updateQtyFromChildren() throws IllegalArgumentException {
if (components.size() == 0) {
throw new IllegalArgumentException("Impossible de calculé les quantités depuis les composants. Cet article n'est pas composé!");
if (this.article.isUndefined()) {
return false;
}
String code = "";
if (this.article != null && this.article.getFields().contains("CODE") && this.article.getString("CODE") != null) {
code = this.article.getString("CODE");
}
System.err.println("Impossible de mettre à jour le stock, l'articel n'est pas une nomenclature " + code);
return false;
 
}
StockItemComponent comp = components.get(0);
double real = comp.getItem().getRealQty() == 0 ? 0 : Math.ceil(comp.getItem().getRealQty() / (comp.getQty() * comp.getQtyUnit().doubleValue()));
double virtual = comp.getItem().getVirtualQty() == 0 ? 0 : Math.ceil(comp.getItem().getVirtualQty() / (comp.getQty() * comp.getQtyUnit().doubleValue()));
90,13 → 108,14
// La quantité du kit ne peut être négative
this.realQty = Math.max(0, real);
this.virtualQty = Math.max(0, virtual);
return true;
}
 
public void fillCommandeFournisseur(ListMap<SQLRow, SQLRowValues> cmd) {
 
// TODO Gestion Stock Min par depot
SQLPreferences prefs = new SQLPreferences(article.getTable().getDBRoot());
boolean gestionStockMin = prefs.getBoolean(GestionArticleGlobalPreferencePanel.WARNING_STOCK_MIN, true);
if (article.getTable().getFieldsName().contains("QTE_MIN") && gestionStockMin && article.getObject("QTE_MIN") != null && getRealQty() < article.getInt("QTE_MIN")) {
if (gestionStockMin && stock.getObject("QTE_MIN") != null && getRealQty() < stock.getFloat("QTE_MIN")) {
// final float qteShow = qteNvlle;
SQLInjector inj = SQLInjector.getInjector(article.getTable(), article.getTable().getTable("COMMANDE_ELEMENT"));
final SQLRow asRow = article.asRow();
103,7 → 122,7
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(asRow));
rowValsElt.put("ID_STYLE", 2);
final SQLRowAccessor unite = article.getForeign("ID_UNITE_VENTE");
final double qteElt = article.getInt("QTE_MIN") - getRealQty();
final double qteElt = stock.getFloat("QTE_MIN") - getRealQty();
if (unite.isUndefined() || unite.getBoolean("A_LA_PIECE")) {
rowValsElt.put("QTE", Math.round(qteElt));
rowValsElt.put("QTE_UNITAIRE", BigDecimal.ONE);
213,7 → 232,7
}
 
public boolean isStockInit() {
return !this.article.isForeignEmpty("ID_STOCK");
return this.stock != null && !this.stock.isUndefined();
}
 
public void clearStockValues() {
224,9 → 243,9
}
 
public String getUpdateRequest() {
final SQLTable stockTable = this.article.getTable().getForeignTable("ID_STOCK");
final SQLTable stockTable = this.stock.getTable();
UpdateBuilder update = new UpdateBuilder(stockTable);
update.setWhere(new Where(stockTable.getKey(), "=", getArticle().getForeign("ID_STOCK").getID()));
update.setWhere(new Where(stockTable.getKey(), "=", this.stock.getID()));
update.setObject("QTE_REEL", getRealQty());
update.setObject("QTE_TH", getVirtualQty());
update.setObject("QTE_LIV_ATTENTE", getDeliverQty());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItemsTHUpdater.java
New file
0,0 → 1,60
/*
* 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.supplychain.stock.element;
 
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
import org.openconcerto.erp.core.sales.product.model.ProductHelper;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLDataSource;
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.utils.SQLUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
import org.openconcerto.utils.RTInterruptedException;
import org.openconcerto.utils.Tuple3;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import org.apache.commons.dbutils.ResultSetHandler;
 
public class StockItemsTHUpdater extends StockItemsUpdater {
 
public StockItemsTHUpdater(StockLabel label, SQLRowAccessor rowSource, List<? extends SQLRowAccessor> items, TypeStockUpdate t) {
super(label, rowSource, items, t);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/DepotStockSQLElement.java
New file
0,0 → 1,85
/*
* 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.supplychain.stock.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.DefaultGridBagConstraints;
import 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 DepotStockSQLElement extends ComptaSQLConfElement {
 
public static int DEFAULT_ID = 2;
 
public DepotStockSQLElement() {
super("DEPOT_STOCK", "un dépôt", "dépôts");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("NOM");
return l;
}
 
@Override
public ListMap<String, String> getShowAs() {
return ListMap.singleton(null, "NOM");
}
 
/*
* (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();
 
// Qté Réelle
JLabel labelQteR = new JLabel(getLabelFor("NOM"));
this.add(labelQteR, c);
 
c.gridx++;
JTextField textNom = new JTextField(25);
this.add(textNom, c);
 
this.addSQLObject(textNom, "NOM");
}
};
}
 
@Override
protected String createCode() {
return createCodeOfPackage() + ".depot";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockTable.java
New file
0,0 → 1,107
/*
* 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.supplychain.stock.element;
 
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.SQLRowValues;
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.util.ArrayList;
import java.util.List;
 
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class EtatStockTable extends RowValuesTablePanel {
 
public EtatStockTable(final JTextField fieldTotal) {
 
init();
uiInit();
this.table.getModel().addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
BigDecimal total = BigDecimal.ZERO;
for (int i = 0; i < table.getRowValuesTableModel().getRowCount(); i++) {
total = total.add(table.getRowValuesTableModel().getRowValuesAt(i).getBigDecimal("T_PA"));
}
fieldTotal.setText(total.toString());
}
});
 
}
 
/**
*
*/
protected void init() {
 
final SQLElement e = getSQLElement();
 
final List<SQLTableElement> list = new ArrayList<>();
list.add(new SQLTableElement(e.getTable().getField("ID_ARTICLE")));
list.add(new SQLTableElement(e.getTable().getField("CODE")));
list.add(new SQLTableElement(e.getTable().getField("NOM")));
final SQLTableElement achat = new SQLTableElement(e.getTable().getField("PA")) {
@Override
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
};
achat.setRenderer(new CurrencyWithSymbolRenderer());
 
list.add(achat);
final SQLTableElement qte = new SQLTableElement(e.getTable().getField("QTE")) {
@Override
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
 
};
 
list.add(qte);
SQLTableElement totalHA = new SQLTableElement(e.getTable().getField("T_PA"));
totalHA.setRenderer(new CurrencyWithSymbolRenderer());
list.add(totalHA);
 
this.defaultRowVals = new SQLRowValues(getSQLElement().getTable());
this.model = new RowValuesTableModel(e, list, e.getTable().getField("ID_ARTICLE"), false, this.defaultRowVals);
this.table = new RowValuesTable(this.model, null);
 
// Calcul automatique du prix de vente unitaire HT
 
qte.addModificationListener(totalHA);
achat.addModificationListener(totalHA);
totalHA.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
return row.getBigDecimal("QTE").multiply(row.getBigDecimal("PA"));
}
});
 
}
 
public SQLElement getSQLElement() {
return Configuration.getInstance().getDirectory().getElement("ETAT_STOCK_ELEMENT");
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockItemSQLElement.java
New file
0,0 → 1,65
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.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 EtatStockItemSQLElement extends ComptaSQLConfElement {
 
public EtatStockItemSQLElement() {
super("ETAT_STOCK_ELEMENT");
setDefaultGroup(new EtatStockGroup());
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("QTE");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_ARTICLE");
l.add("QTE");
// l.add("PA");
return l;
}
//
// @Override
// public ListMap<String, String> getShowAs() {
// ListMap<String, String> map = new ListMap<String, String>();
// map.add("ID_ARTICLE", "CODE");
// map.add("ID_ARTICLE", "NOM");
// return map;
// }
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return null;
}
 
@Override
protected String createCode() {
return createCodeOfPackage() + ".state.items";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItemsUpdater.java
58,6 → 58,7
private final TypeStockUpdate type;
private final boolean createMouvementStock;
private final SQLRowAccessor rowSource;
private boolean resetStockTH = false;
 
private boolean headless = false;
 
135,10 → 136,15
rowVals.put("QTE_TH", stockItem.getVirtualQty());
rowVals.put("QTE_LIV_ATTENTE", stockItem.getDeliverQty());
rowVals.put("QTE_RECEPT_ATTENTE", stockItem.getReceiptQty());
rowVals.put("ID_ARTICLE", stockItem.getArticle().getID());
rowVals.put("ID_DEPOT_STOCK", stockItem.stock.getForeignID("ID_DEPOT_STOCK"));
rowVals.commit();
if (stockItem.getArticle().getForeignID("ID_DEPOT_STOCK") == stockItem.stock.getForeignID("ID_DEPOT_STOCK")) {
SQLRowValues rowValsArt = stockItem.getArticle().createEmptyUpdateRow();
rowValsArt.put("ID_STOCK", rowVals);
rowValsArt.commit();
}
}
if (!this.type.isEntry()) {
stockItem.fillCommandeFournisseur(cmd);
}
210,7 → 216,7
rowValsStock.put("QTE_RECEPT_ATTENTE", null);
rowValsStock.put("QTE_LIV_ATTENTE", null);
 
rowValsArt.put("ID_STOCK", rowValsStock);
rowVals.put("ID_STOCK", rowValsStock);
rowVals.put("ID_ARTICLE", rowValsArt);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
233,11 → 239,11
List<SQLRowValues> result = fetcher.fetch();
for (SQLRowValues sqlRowValues : result) {
final StockItem item;
if (!items.containsKey(sqlRowValues.getForeignIDNumber("ID_ARTICLE"))) {
item = new StockItem(sqlRowValues.getForeign("ID_ARTICLE"));
items.put(sqlRowValues.getForeignIDNumber("ID_ARTICLE"), item);
if (!items.containsKey(sqlRowValues.getForeignIDNumber("ID_STOCK"))) {
item = new StockItem(sqlRowValues.getForeign("ID_ARTICLE"), sqlRowValues.getForeign("ID_STOCK"));
items.put(sqlRowValues.getForeignIDNumber("ID_STOCK"), item);
} else {
item = items.get(sqlRowValues.getForeignIDNumber("ID_ARTICLE"));
item = items.get(sqlRowValues.getForeignIDNumber("ID_STOCK"));
}
final TypeStockMouvement t;
if (sqlRowValues.getBoolean("REEL")) {
277,7 → 283,7
}
}
if ((!r.getTable().contains("NIVEAU") || r.getInt("NIVEAU") == level) && !r.isForeignEmpty("ID_ARTICLE") && r.getForeign("ID_ARTICLE") != null) {
productComponents.add(ProductComponent.createFrom(r, qte));
productComponents.add(ProductComponent.createFrom(r, qte, r));
}
} else if (r.getInt("NIVEAU") < level) {
// BREAK si on sort de l'article composé
295,7 → 301,8
*/
private List<StockItem> fetch() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
List<StockItem> stockItems = new ArrayList<StockItem>(items.size());
Map<Number, StockItem> stockItems = new HashMap<Number, StockItem>();
 
String mvtStockTableQuoted = rowSource.getTable().getTable("MOUVEMENT_STOCK").getSQLName().quote();
 
// Liste des éléments à mettre à jour
326,7 → 333,13
for (ProductComponent productComp : boms) {
 
if (productComp.getProduct().getBoolean("GESTION_STOCK") && productComp.getQty().signum() != 0) {
StockItem stockItem = new StockItem(productComp.getProduct());
final StockItem stockItem;
if (!stockItems.containsKey(productComp.getStock().getID())) {
stockItem = new StockItem(productComp.getProduct(), productComp.getStock());
stockItems.put(productComp.getStock().getID(), stockItem);
} else {
stockItem = stockItems.get(productComp.getStock().getID());
}
double qteFinal = productComp.getQty().doubleValue();
 
// reliquat
341,20 → 354,20
}
 
stockItem.updateQty(qteFinal, this.type.getType());
stockItems.add(stockItem);
 
if (this.createMouvementStock) {
final Date time = this.rowSource.getDate("DATE").getTime();
BigDecimal prc = productComp.getPRC(time);
if (this.type.getType() == TypeStockMouvement.REEL || this.type.getType() == TypeStockMouvement.REEL_THEORIQUE || this.type.getType() == TypeStockMouvement.RETOUR) {
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"SOURCE\",\"IDSOURCE\",\"NOM\",\"REEL\",\"ORDRE\"";
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"SOURCE\",\"IDSOURCE\",\"NOM\",\"REEL\",\"ORDRE\"";
 
if (prc != null) {
mvtStockQuery += ",\"PRICE\"";
}
 
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + productComp.getProduct().getID() + ",'" + this.rowSource.getTable().getName() + "',"
+ this.rowSource.getID() + ",'" + this.label.getLabel(this.rowSource, productComp.getProduct()) + "',true, (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted
+ ")";
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + productComp.getProduct().getID() + "," + productComp.getStock().getID() + ",'"
+ this.rowSource.getTable().getName() + "'," + this.rowSource.getID() + ",'" + this.label.getLabel(this.rowSource, productComp.getProduct())
+ "',true, (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
if (prc != null) {
mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
}
362,14 → 375,14
this.requests.add(mvtStockQuery);
}
if (this.type.getType() == TypeStockMouvement.THEORIQUE || this.type.getType() == TypeStockMouvement.REEL_THEORIQUE || this.type.getType() == TypeStockMouvement.RETOUR) {
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"SOURCE\",\"IDSOURCE\",\"NOM\",\"REEL\",\"ORDRE\"";
String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"SOURCE\",\"IDSOURCE\",\"NOM\",\"REEL\",\"ORDRE\"";
if (prc != null) {
mvtStockQuery += ",\"PRICE\"";
}
 
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + productComp.getProduct().getID() + ",'" + this.rowSource.getTable().getName() + "',"
+ this.rowSource.getID() + ",'" + this.label.getLabel(this.rowSource, productComp.getProduct()) + "',false, (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted
+ ")";
mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + productComp.getProduct().getID() + "," + productComp.getStock().getID() + ",'"
+ this.rowSource.getTable().getName() + "'," + this.rowSource.getID() + ",'" + this.label.getLabel(this.rowSource, productComp.getProduct())
+ "',false, (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
if (prc != null) {
mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
}
380,6 → 393,10
}
}
 
return stockItems;
return new ArrayList<StockItem>(stockItems.values());
}
 
public void setResetStockTH(boolean resetStockTH) {
this.resetStockTH = resetStockTH;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockSQLElement.java
14,16 → 14,37
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.sales.product.action.InventairePanel;
import org.openconcerto.erp.generationDoc.gestcomm.FicheArticleXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
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.sql.sqlobject.ElementComboBox;
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.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
31,32 → 52,122
 
public StockSQLElement() {
super("STOCK", "un stock", "stocks");
getRowActions().addAll(new MouseSheetXmlListeListener(FicheArticleXmlSheet.class).getRowActions());
PredicateRowAction stock = new PredicateRowAction(new AbstractAction("Mettre à jour les stocks") {
 
@Override
public void actionPerformed(ActionEvent e) {
 
PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), IListe.get(e).getSelectedRows()), "Mise à jour des stocks");
FrameUtil.show(p);
 
}
}, true, false);
stock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(stock);
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("QTE_REEL");
// l.add("QTE_TH");
return l;
return Arrays.asList("ID_ARTICLE", "QTE_MIN", "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE", "ID_DEPOT_STOCK");
}
 
@Override
public Set<String> getReadOnlyFields() {
Set<String> s = new HashSet<>();
if (getTable().contains("ID_ARTICLE")) {
s.add("ID_ARTICLE");
}
s.add("QTE_TH");
s.add("QTE_REEL");
s.add("QTE_LIV_ATTENTE");
s.add("QTE_RECEPT_ATTENTE");
if (getTable().contains("ID_DEPOT_STOCK")) {
s.add("ID_DEPOT_STOCK");
}
return s;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("QTE_REEL");
// l.add("QTE_TH");
return l;
return Arrays.asList("ID_DEPOT_STOCK", "QTE_REEL");
}
 
@Override
public boolean isPrivate() {
return true;
protected String getParentFFName() {
return "ID_ARTICLE";
}
 
@Override
public ListMap<String, String> getShowAs() {
if (getTable().contains("ID_DEPOT_STOCK")) {
return ListMap.singleton(null, "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE", "ID_DEPOT_STOCK");
} else {
return ListMap.singleton(null, "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
}
}
 
public static SQLRowAccessor getStockFetched(SQLRowAccessor rowValsSource) {
SQLRowAccessor rowStock = null;
final int idDepot;
if (rowValsSource.getForeign("ID_DEPOT_STOCK") != null && !rowValsSource.isForeignEmpty("ID_DEPOT_STOCK")) {
idDepot = rowValsSource.getForeignID("ID_DEPOT_STOCK");
} else {
idDepot = rowValsSource.getForeign("ID_ARTICLE").getForeignID("ID_DEPOT_STOCK");
}
SQLTable stockTable = rowValsSource.getTable().getTable("STOCK");
 
Collection<? extends SQLRowAccessor> rows = rowValsSource.getForeign("ID_ARTICLE").getReferentRows(stockTable);
for (SQLRowAccessor sqlRowAccessor : rows) {
if (sqlRowAccessor.getForeignID("ID_DEPOT_STOCK") == idDepot) {
rowStock = sqlRowAccessor;
break;
}
}
 
return rowStock;
}
 
public static SQLRowAccessor getStock(SQLRowAccessor rowValsSource) {
 
SQLRowAccessor rowStock = null;
final int idDepot;
if (rowValsSource.getForeign("ID_DEPOT_STOCK") != null && !rowValsSource.isForeignEmpty("ID_DEPOT_STOCK")) {
idDepot = rowValsSource.getForeignID("ID_DEPOT_STOCK");
} else {
idDepot = rowValsSource.getForeign("ID_ARTICLE").getForeignID("ID_DEPOT_STOCK");
}
SQLTable stockTable = rowValsSource.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"), "=", rowValsSource.getForeignID("ID_ARTICLE"));
Collection<SQLRowValues> rowValsResult = fetch.fetch(w.and(w2));
if (rowValsResult.isEmpty()) {
SQLRowValues rowValsStock = new SQLRowValues(stockTable);
rowValsStock.put("ID_ARTICLE", rowValsSource.getForeignID("ID_ARTICLE"));
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) {
rowValsSource.getForeign("ID_ARTICLE").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 " + rowValsSource.getForeign("ID_ARTICLE").getID() + " Depot " + idDepot);
}
return rowStock;
}
 
/*
* (non-Javadoc)
*
66,35 → 177,94
 
return new BaseSQLComponent(this) {
 
private JTextField textQteReel;
 
// , textQteTh;
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Article
JLabel labelA = new JLabel(getLabelFor("ID_ARTICLE"));
c.weightx = 0;
this.add(labelA, c);
 
c.gridx++;
ElementComboBox boxA = new ElementComboBox();
this.add(boxA, c);
 
// Depot
JLabel labelD = new JLabel(getLabelFor("ID_DEPOT_STOCK"));
c.gridx++;
c.weightx = 0;
this.add(labelD, c);
 
c.gridx++;
ElementComboBox boxD = new ElementComboBox();
this.add(boxD, c);
 
// Qté Réelle
JLabel labelQteR = new JLabel(getLabelFor("QTE_REEL"));
c.gridx = 0;
c.gridy++;
c.weightx = 0;
this.add(labelQteR, c);
 
c.gridx++;
this.textQteReel = new JTextField(6);
this.add(this.textQteReel, c);
JTextField textQteReel = new JTextField(6);
this.add(textQteReel, c);
 
// Qté Théorique
// c.gridy++;
// c.gridx = 0;
// JLabel labelQteTh = new JLabel(getLabelFor("QTE_TH"));
// this.add(labelQteTh, c);
//
// c.gridx++;
// this.textQteTh = new JTextField(6, false);
// this.add(this.textQteTh, c);
// Qté Réelle
JLabel labelQteT = new JLabel(getLabelFor("QTE_TH"));
c.gridx++;
c.weightx = 0;
this.add(labelQteT, c);
 
this.addSQLObject(this.textQteReel, "QTE_REEL");
// this.addSQLObject(this.textQteTh, "QTE_TH");
c.gridx++;
JTextField textQteT = new JTextField(6);
this.add(textQteT, c);
 
// Qté Réelle
JLabel labelQteRe = new JLabel(getLabelFor("QTE_RECEPT_ATTENTE"));
c.gridx = 0;
c.gridy++;
c.weightx = 0;
this.add(labelQteRe, c);
 
c.gridx++;
JTextField textQteRe = new JTextField(6);
this.add(textQteRe, c);
 
JLabel labelQteL = new JLabel(getLabelFor("QTE_LIV_ATTENTE"));
c.gridx++;
c.weightx = 0;
this.add(labelQteL, c);
 
c.gridx++;
JTextField textQteL = new JTextField(6);
this.add(textQteL, c);
 
// Qté Min
JLabel labelQteTMin = new JLabel(getLabelFor("QTE_MIN"));
c.gridx = 0;
c.gridy++;
c.weightx = 0;
this.add(labelQteTMin, c);
 
c.gridx++;
JTextField textQteMin = new JTextField(6);
this.add(textQteMin, c);
 
this.addSQLObject(textQteReel, "QTE_REEL");
this.addSQLObject(textQteT, "QTE_TH");
this.addSQLObject(textQteMin, "QTE_MIN");
this.addSQLObject(textQteL, "QTE_LIV_ATTENTE");
this.addSQLObject(textQteRe, "QTE_RECEPT_ATTENTE");
this.addSQLObject(boxA, "ID_ARTICLE");
this.addSQLObject(boxD, "ID_DEPOT_STOCK");
}
};
}
 
@Override
protected String createCode() {
return "supplychain.stock";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
17,6 → 17,7
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
import org.openconcerto.erp.core.supplychain.order.ui.CommandeItemTable;
import org.openconcerto.erp.core.supplychain.supplier.component.MouvementStockSQLComponent;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
40,7 → 41,6
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
 
import java.math.BigDecimal;
58,8 → 58,16
super("MOUVEMENT_STOCK", "un mouvement de stock", "mouvements de stock");
}
 
@Override
public ListMap<String, String> getShowAs() {
ListMap<String, String> map = new ListMap<String, String>();
map.putCollection("ID_STOCK", "ID_DEPOT_STOCK");
return map;
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_STOCK");
l.add("DATE");
l.add("NOM");
l.add("ID_ARTICLE");
91,19 → 99,14
 
}
 
// public CollectionMap<SQLRow, List<SQLRowValues>> updateStock(List<Integer> ids) {
// return updateStock(ids, false);
// }
 
private final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
 
/**
* Mise à jour des stocks ajoute la quantité si archive est à false
*
* @param id mouvement stock
* @param archive
* @throws SQLException
*/
public ListMap<SQLRow, SQLRowValues> updateStock(Collection<SQLRow> rowsMvt, boolean archive) {
public ListMap<SQLRow, SQLRowValues> updateStock(Collection<SQLRow> rowsMvt, boolean archive) throws SQLException {
// FIXME: if (SwingUtilities.isEventDispatchThread()) {
// throw new IllegalStateException("This method must be called outside of EDT");
// }
112,23 → 115,27
// Stock Th : inc/dec QTE_TH, inc/dec QTE_LIV_ATTENTE/inc/dec
// QTE_RECEPT_ATTENTE
 
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
SQLTable tableCmdElt = Configuration.getInstance().getBase().getTable("COMMANDE_ELEMENT");
final ListMap<SQLRow, SQLRowValues> map = new ListMap<>();
final SQLTable tableCommandeElement = Configuration.getInstance().getBase().getTable("COMMANDE_ELEMENT");
final SQLElement elementStock = Configuration.getInstance().getDirectory().getElement("STOCK");
 
for (SQLRow rowMvtStock : rowsMvt) {
 
boolean retour = rowMvtStock.getString("SOURCE") == null || rowMvtStock.getString("SOURCE").startsWith("AVOIR_CLIENT");
// Mise à jour des stocks
SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
SQLElement eltStock = Configuration.getInstance().getDirectory().getElement("STOCK");
 
final SQLRow rowArticle = rowMvtStock.getForeignRow("ID_ARTICLE");
 
SQLRow rowStock = rowArticle.getForeignRow(("ID_STOCK"));
SQLRow rowStock = rowMvtStock.getForeignRow(("ID_STOCK"));
if (rowStock == null || rowStock.isUndefined()) {
rowStock = rowArticle.getForeign("ID_STOCK");
}
 
if (rowMvtStock.getBoolean("REEL")) {
float qte = rowStock.getFloat("QTE_REEL");
float qteMvt = rowMvtStock.getFloat("QTE");
 
SQLRowValues rowVals = new SQLRowValues(eltStock.getTable());
SQLRowValues rowVals = new SQLRowValues(elementStock.getTable());
 
float qteNvlle;
float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
161,33 → 168,18
rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
 
try {
if (rowStock.getID() <= 1) {
SQLRow row = rowVals.insert();
SQLRowValues rowValsArt = new SQLRowValues(eltArticle.getTable());
rowValsArt.put("ID_STOCK", row.getID());
 
final int idArticle = rowArticle.getID();
if (idArticle > 1) {
rowValsArt.update(idArticle);
}
} else {
rowVals.update(rowStock.getID());
}
} catch (SQLException e) {
 
ExceptionHandler.handle("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"));
}
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
boolean gestionStockMin = prefs.getBoolean(GestionArticleGlobalPreferencePanel.WARNING_STOCK_MIN, true);
 
if (!archive && rowArticle.getTable().getFieldsName().contains("QTE_MIN") && gestionStockMin && rowArticle.getObject("QTE_MIN") != null && qteNvlle < rowArticle.getInt("QTE_MIN")) {
if (!archive && gestionStockMin && rowStock.getObject("QTE_MIN") != null && qteNvlle < rowStock.getFloat("QTE_MIN")) {
// final float qteShow = qteNvlle;
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCommandeElement);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticle));
rowValsElt.put("ID_STYLE", 2);
final SQLRow unite = rowArticle.getForeign("ID_UNITE_VENTE");
final float qteElt = rowArticle.getInt("QTE_MIN") - qteNvlle;
final float qteElt = rowStock.getFloat("QTE_MIN") - qteNvlle;
if (unite.isUndefined() || unite.getBoolean("A_LA_PIECE")) {
rowValsElt.put("QTE", Math.round(qteElt));
rowValsElt.put("QTE_UNITAIRE", BigDecimal.ONE);
199,15 → 191,16
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * qteElt);
rowValsElt.put("T_PA_HT", rowValsElt.getLong("PA_HT") * qteElt);
rowValsElt.put("T_PA_TTC", rowValsElt.getLong("T_PA_HT") * (rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0));
 
map.add(rowArticle.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
 
}
} catch (SQLException e) {
throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
}
} else {
float qte = rowStock.getFloat("QTE_TH");
float qteMvt = rowMvtStock.getFloat("QTE");
 
SQLRowValues rowVals = new SQLRowValues(eltStock.getTable());
SQLRowValues rowVals = new SQLRowValues(elementStock.getTable());
 
float qteNvlle;
float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
241,23 → 234,10
rowVals.put("QTE_TH", qteNvlle);
rowVals.put("QTE_RECEPT_ATTENTE", qteNvlleEnAttenteRecept);
rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
 
try {
if (rowStock.getID() <= 1) {
SQLRow row = rowVals.insert();
SQLRowValues rowValsArt = new SQLRowValues(eltArticle.getTable());
rowValsArt.put("ID_STOCK", row.getID());
 
final int idArticle = rowArticle.getID();
if (idArticle > 1) {
rowValsArt.update(idArticle);
}
} else {
rowVals.update(rowStock.getID());
}
} catch (SQLException e) {
 
ExceptionHandler.handle("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"));
throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
}
}
 
328,6 → 308,8
cmp.getRowValuesTable().getRowValuesTableModel().clearRows();
}
 
CommandeItemTable itemTable = cmp.getRowValuesTablePanel();
 
final RowValuesTableModel model = cmp.getRowValuesTable().getRowValuesTableModel();
for (SQLRowValues rowValsElt : e.getValue()) {
SQLRowValues rowValsMatch = null;
346,8 → 328,14
model.putValue(qte + rowValsElt.getInt("QTE"), index, "QTE");
} else {
model.addRow(rowValsElt);
if (rowValsElt.getObject("ID_ARTICLE") != null && !rowValsElt.isForeignEmpty("ID_ARTICLE")) {
Object o = itemTable.tarifCompletion(rowValsElt.getForeign("ID_ARTICLE").asRow(), "PRIX_METRIQUE_HA_1");
if (o != null) {
model.putValue(o, model.getRowCount() - 1, "PRIX_METRIQUE_HA_1");
}
}
}
}
 
frame.pack();
FrameUtil.show(frame);
400,6 → 388,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transaction";
return createCodeOfPackage() + ".transaction";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockGroup.java
New file
0,0 → 1,29
/*
* 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.supplychain.stock.element;
 
import org.openconcerto.ui.group.Group;
import org.openconcerto.ui.group.LayoutHints;
 
public class EtatStockGroup extends Group {
public EtatStockGroup() {
super("supplychain.stock.state");
addItem("DATE");
addItem("MONTANT_HA");
 
addItem("supplychain.stock.state.items", LayoutHints.DEFAULT_LIST_HINTS);
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/ComposedItemStockUpdater.java
14,6 → 14,7
package org.openconcerto.erp.core.supplychain.stock.element;
 
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.SQLRowValuesListFetcher;
23,10 → 24,13
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
 
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
40,6 → 44,8
private final List<StockItem> itemsUpdated;
private final DBRoot root;
 
/// FIXME mettre à jour les stocks des kits à partir des feuilles
 
/**
* Met à jour les stocks des nomenclature composé par un des articles de itemsUpdated
*
59,14 → 65,22
public void update() throws SQLException {
// Liste des nomenclatures dépendantes des itemsUpdated
List<StockItem> items = getAllComposedItemToUpdate();
updateNomenclature(items);
}
 
public void updateNomenclature(List<StockItem> items) throws SQLException {
 
// Fecth des articles liés
getAllChildren(items);
 
List<StockItem> removedBadItem = new ArrayList<>();
// Mise à jour des stocks
for (StockItem stockItem : items) {
stockItem.updateQtyFromChildren();
if (!stockItem.updateQtyFromChildren()) {
removedBadItem.add(stockItem);
}
}
items.removeAll(removedBadItem);
 
SQLTable stockTable = root.getTable("STOCK");
List<String> requests = new ArrayList<String>();
73,7 → 87,7
for (StockItem stockItem : items) {
if (stockItem.isStockInit()) {
UpdateBuilder update = new UpdateBuilder(stockTable);
update.setWhere(new Where(stockTable.getKey(), "=", stockItem.getArticle().getForeign("ID_STOCK").getID()));
update.setWhere(new Where(stockTable.getKey(), "=", stockItem.stock.getID()));
update.setObject("QTE_REEL", stockItem.getRealQty());
update.setObject("QTE_TH", stockItem.getVirtualQty());
update.setObject("QTE_LIV_ATTENTE", stockItem.getDeliverQty());
85,11 → 99,16
rowVals.put("QTE_TH", stockItem.getVirtualQty());
rowVals.put("QTE_LIV_ATTENTE", stockItem.getDeliverQty());
rowVals.put("QTE_RECEPT_ATTENTE", stockItem.getReceiptQty());
rowVals.put("ID_ARTICLE", stockItem.getArticle().getID());
rowVals.put("ID_DEPOT_STOCK", stockItem.stock.getForeignID("ID_DEPOT_STOCK"));
rowVals.commit();
if (stockItem.getArticle().getForeignID("ID_DEPOT_STOCK") == stockItem.stock.getForeignID("ID_DEPOT_STOCK")) {
SQLRowValues rowValsArt = stockItem.getArticle().createEmptyUpdateRow();
rowValsArt.put("ID_STOCK", rowVals);
rowValsArt.commit();
}
}
}
 
List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(requests.size());
for (String s : requests) {
106,15 → 125,17
*/
private void getAllChildren(List<StockItem> items) {
final SQLTable tableArticle = this.root.getTable("ARTICLE");
final int undefDepot = tableArticle.getTable("DEPOT_STOCK").getUndefinedID();
final SQLRowValues rowValsArt = new SQLRowValues(tableArticle);
rowValsArt.put(tableArticle.getKey().getName(), null);
 
SQLRowValues rowValsStock = new SQLRowValues(tableArticle.getForeignTable("ID_STOCK"));
SQLRowValues rowValsStock = new SQLRowValues(this.root.getTable("STOCK"));
rowValsStock.put("QTE_REEL", null);
rowValsStock.put("QTE_TH", null);
rowValsStock.put("QTE_RECEPT_ATTENTE", null);
rowValsStock.put("QTE_LIV_ATTENTE", null);
rowValsArt.put("ID_STOCK", rowValsStock);
rowValsStock.put("ID_DEPOT_STOCK", null);
rowValsStock.put("ID_ARTICLE", rowValsArt);
 
final SQLTable tableArticleElt = this.root.getTable("ARTICLE_ELEMENT");
SQLRowValues rowValsArtItem = new SQLRowValues(tableArticleElt);
124,12 → 145,14
rowValsArtItem.put("ID_ARTICLE_PARENT", null);
 
final List<Integer> ids = new ArrayList<Integer>();
Map<Integer, StockItem> mapItem = new HashMap<Integer, StockItem>();
Map<Tuple2<Integer, Integer>, StockItem> mapItem = new HashMap<Tuple2<Integer, Integer>, StockItem>();
for (StockItem stockItem : items) {
final int id = stockItem.getArticle().getID();
ids.add(id);
mapItem.put(id, stockItem);
if (stockItem.stock.getForeignID("ID_DEPOT_STOCK") != undefDepot) {
mapItem.put(Tuple2.create(id, stockItem.stock.getForeignID("ID_DEPOT_STOCK")), stockItem);
}
}
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsArtItem);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
147,10 → 170,48
 
final SQLRowAccessor article = sqlRowValues.getForeign("ID_ARTICLE");
final SQLRowAccessor articleParent = sqlRowValues.getForeign("ID_ARTICLE_PARENT");
mapItem.get(articleParent.getID()).addItemComponent(new StockItemComponent(new StockItem(article), sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
if (article != null && !article.isUndefined()) {
final Collection<? extends SQLRowAccessor> referentStockRows = article.getReferentRows(this.root.getTable("STOCK"));
 
{
// Init Stock if no depot
if (referentStockRows.size() == 0) {
// init default stock depot
SQLRowValues rowVals = new SQLRowValues(article.getTable().getTable("STOCK"));
rowVals.put("ID_ARTICLE", article.getID());
rowVals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
try {
SQLRow rowStock = rowVals.commit();
article.createEmptyUpdateRow().put("ID_STOCK", rowStock.getID()).commit();
 
System.err.println("NO DEPOT STOCK FOR ITEM " + articleParent.getID() + " -- PARENT " + articleParent.getID());
StockItem stockItem = mapItem.get(Tuple2.create(articleParent.getID(), DepotStockSQLElement.DEFAULT_ID));
if (stockItem != null) {
stockItem.addItemComponent(new StockItemComponent(new StockItem(article, rowStock), sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
} else {
System.err.println("Unable to find stock of item ARTICLE " + articleParent.getID() + " DEPOT " + DepotStockSQLElement.DEFAULT_ID);
}
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de l'initialisation du stock de l'article", e);
}
}
}
 
for (SQLRowAccessor sqlRowAccessor : referentStockRows) {
StockItem stockItem = mapItem.get(Tuple2.create(articleParent.getID(), sqlRowAccessor.getForeignID("ID_DEPOT_STOCK")));
if (stockItem != null) {
stockItem.addItemComponent(new StockItemComponent(new StockItem(article, sqlRowAccessor), sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
} else if (sqlRowAccessor.getForeignID("ID_DEPOT_STOCK") == sqlRowAccessor.getTable().getForeignTable("ID_DEPOT_STOCK").getUndefinedID()) {
stockItem = mapItem.get(Tuple2.create(articleParent.getID(), DepotStockSQLElement.DEFAULT_ID));
stockItem.addItemComponent(new StockItemComponent(new StockItem(article, sqlRowAccessor), sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
} else {
System.err.println("Unable to find stock of item ARTICLE " + articleParent.getID() + " DEPOT " + sqlRowAccessor.getForeignID("ID_DEPOT_STOCK"));
}
}
}
}
}
 
/**
* @return l'ensemble des stockItems composés à mettre à jour
*/
168,6 → 229,7
for (SQLRowValues sqlRowValues : list) {
result.put(sqlRowValues.getID(), sqlRowValues);
}
// Liste des nomenclatures dépendantes des nomenclatures (kit dans kits)
while (size > 0) {
 
List<SQLRowValues> l = getComposedItemToUpdate(ids);
178,7 → 240,7
if (size > 0) {
ids.clear();
for (SQLRowValues r : l) {
ids.add(r.getID());
ids.add(r.getForeignID("ID_ARTICLE"));
}
}
}
186,7 → 248,7
List<StockItem> items = new ArrayList<StockItem>(result.size());
for (SQLRowValues rowVals : result.values()) {
 
StockItem item = new StockItem(rowVals);
StockItem item = new StockItem(rowVals.getForeign("ID_ARTICLE"), rowVals);
items.add(item);
}
return items;
203,29 → 265,30
final SQLRowValues rowValsArt = new SQLRowValues(tableArticle);
rowValsArt.put(tableArticle.getKey().getName(), null);
 
SQLRowValues rowValsStock = new SQLRowValues(tableArticle.getForeignTable("ID_STOCK"));
SQLRowValues rowValsStock = new SQLRowValues(this.root.getTable("STOCK"));
rowValsStock.put("QTE_REEL", null);
rowValsStock.put("QTE_TH", null);
rowValsStock.put("QTE_RECEPT_ATTENTE", null);
rowValsStock.put("QTE_LIV_ATTENTE", null);
rowValsArt.put("ID_STOCK", rowValsStock);
rowValsStock.put("ID_ARTICLE", rowValsArt);
rowValsStock.put("ID_DEPOT_STOCK", null);
 
final SQLTable tableArticleElt = this.root.getTable("ARTICLE_ELEMENT");
SQLRowValues rowValsArtItem = new SQLRowValues(tableArticleElt);
rowValsArtItem.put("ID_ARTICLE_PARENT", rowValsArt);
// SQLRowValues rowValsArtItem = new SQLRowValues(tableArticleElt);
// rowValsArtItem.put("ID_ARTICLE_PARENT", rowValsArt);
// rowValsArtItem.put("QTE", null);
// rowValsArtItem.put("QTE_UNITAIRE", null);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsArt);
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsStock);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
final SQLSelectJoin joinFromField = input.getJoinFromField(tableArticleElt.getField("ID_ARTICLE_PARENT"));
SQLSelectJoin joinFromField = input.addJoin("RIGHT", tableArticleElt, new Where(tableArticleElt.getField("ID_ARTICLE_PARENT"), "=", input.getTable("STOCK").getField("ID_ARTICLE")));
Where w = new Where(joinFromField.getJoinedTable().getField("ID_ARTICLE"), ids);
joinFromField.setWhere(w);
Where w2 = new Where(joinFromField.getJoinedTable().getKey(), "is not", (Object) null);
input.setWhere(w2);
input.clearOrder();
input.setDistinct(true);
return input;
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockFromInventoryFileCreator.java
New file
0,0 → 1,165
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.erp.core.sales.product.model.PriceByQty;
import org.openconcerto.erp.importer.ArrayTableModel;
import org.openconcerto.erp.importer.DataImporter;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
 
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
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.Map;
import java.util.Set;
 
public class EtatStockFromInventoryFileCreator {
 
// Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>();
// List<String> codeKits = new ArrayList<String>();
// List<SQLRowValues> rowValsArtNonSync = new ArrayList<SQLRowValues>();
 
public void importArticles(File file, Date d) throws IOException, SQLException {
 
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
Map<String, SQLRowValues> articles = getArticles();
 
final DataImporter importer = new DataImporter(table) {
@Override
protected void customizeRowValuesToFetch(SQLRowValues vals) {
 
vals.putRowValues("ID_STOCK").putNulls("ID", "QTE_REEL", "QTE_TH");
}
};
importer.setSkipFirstLine(true);
 
ArrayTableModel m = importer.createModelFrom(file);
 
SQLRowValues rowValsEtatStock = new SQLRowValues(table.getTable("ETAT_STOCK"));
rowValsEtatStock.put("DATE", d);
SQLRow etatStock = rowValsEtatStock.commit();
BigDecimal total = BigDecimal.ZERO;
for (int i = 0; i < m.getRowCount(); i++) {
List<Object> o = m.getLineValuesAt(i);
String code = o.get(0).toString();
if (code.trim().length() == 0) {
break;
}
final String stringQty = o.get(3).toString();
Integer qty = stringQty.trim().length() == 0 ? 0 : Integer.valueOf(stringQty);
 
SQLRowValues match = articles.get(code);
if (match != null) {
 
SQLRowValues stockValues = new SQLRowValues(table.getTable("ETAT_STOCK_ELEMENT"));
 
final BigDecimal qtyB = new BigDecimal(qty);
stockValues.put("QTE", qtyB);
stockValues.put("NOM", match.getString("NOM"));
stockValues.put("CODE", match.getString("CODE"));
stockValues.put("ID_ARTICLE", match.getID());
final BigDecimal prc = getPRC(match, qty, d);
stockValues.put("PA", prc);
final BigDecimal totalElt = prc.multiply(qtyB);
stockValues.put("T_PA", totalElt);
stockValues.put("ID_ETAT_STOCK", etatStock.getID());
stockValues.commit();
 
total = total.add(totalElt);
 
} else {
System.err.println("Aucun article correspondant au code " + code);
}
}
etatStock.createEmptyUpdateRow().put("MONTANT_HA", total).commit();
}
 
public BigDecimal getPRC(SQLRowValues rowVals, int qty, Date d) {
if (rowVals.getTable().getDBRoot().contains("ARTICLE_PRIX_REVIENT")) {
SQLTable table = rowVals.getTable().getDBRoot().getTable("ARTICLE_PRIX_REVIENT");
Collection<SQLRow> prcs = rowVals.asRow().getReferentRows(table);
 
BigDecimal result = null;
final List<PriceByQty> prices = new ArrayList<PriceByQty>();
 
for (SQLRow row : prcs) {
Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_MONTH, 1);
date.set(Calendar.MONTH, 1);
date.set(Calendar.YEAR, 2001);
if (row.getObject("DATE") != null) {
date = row.getDate("DATE");
}
prices.add(new PriceByQty(row.getLong("QTE"), row.getBigDecimal("PRIX"), date.getTime()));
}
 
result = PriceByQty.getPriceForQty(qty, prices, d);
if (result == null) {
// Can occur during editing
result = BigDecimal.ZERO;
}
return result;
} else {
return rowVals.getBigDecimal("PA_HT");
}
}
 
private Map<String, SQLRowValues> getArticles() throws SQLException {
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
SQLRowValues graph = new SQLRowValues(table);
graph.put("ID", null);
graph.put("CODE", null);
graph.put("SYNC_ID", null);
graph.put("NOM", null);
graph.put("PA_HT", null);
graph.putRowValues("ID_STOCK").putNulls("ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
 
final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT");
SQLRowValues artElt = new SQLRowValues(tableArtElt);
artElt.put("ID", null);
artElt.put("QTE", null);
artElt.put("QTE_UNITAIRE", null);
artElt.put("ID_ARTICLE_PARENT", graph);
artElt.putRowValues("ID_ARTICLE").putNulls("ID", "CODE", "NOM").putRowValues("ID_STOCK").putNulls("QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph);
List<SQLRowValues> results = fetcher.fetch();
 
Map<String, SQLRowValues> vals = new HashMap<String, SQLRowValues>();
for (SQLRowValues sqlRowValues : results) {
 
final Set<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
// On ne prend que les articles simples
if (referentRows.size() == 0) {
final String code = sqlRowValues.getString("CODE");
vals.put(code, sqlRowValues);
 
} else {
 
}
}
return vals;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/ElementStockSQLElement.java
117,6 → 117,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/action/ListeDesDepotsStocksAction.java
New file
0,0 → 1,34
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesDepotsStocksAction extends CreateFrameAbstractAction {
 
public ListeDesDepotsStocksAction() {
super();
this.putValue(Action.NAME, "Liste des dépots de stocks");
}
 
public JFrame createFrame() {
return new IListFrame(new ListeAddPanel(Configuration.getInstance().getDirectory().getElement("DEPOT_STOCK")));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/action/ListeDesMouvementsStockAction.java
13,13 → 13,12
package org.openconcerto.erp.core.supplychain.stock.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.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
28,22 → 27,20
import java.awt.event.MouseEvent;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
 
public class ListeDesMouvementsStockAction extends CreateFrameAbstractAction {
public class ListeDesMouvementsStockAction extends CreateIListFrameAbstractAction<MouvementStockSQLElement> {
 
public ListeDesMouvementsStockAction() {
super();
this.putValue(Action.NAME, "Liste des mouvements de stock");
public ListeDesMouvementsStockAction(final ComptaPropsConfiguration conf) {
super(conf, MouvementStockSQLElement.class);
}
 
public JFrame createFrame() {
@Override
protected void initFrame(IListFrame frame) {
super.initFrame(frame);
 
final SQLElement element = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
final IListFrame frame = new IListFrame(new ListeAddPanel(element));
final SQLElement element = getElem();
 
JTable table = frame.getPanel().getListe().getJTable();
 
72,6 → 69,5
c.anchor = GridBagConstraints.CENTER;
datePanel.setFilterOnDefault();
frame.getPanel().add(datePanel, c);
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/action/ListeDesStocksAction.java
New file
0,0 → 1,145
/*
* 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.supplychain.stock.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
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.view.ListeAddPanel;
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.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
 
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
 
public class ListeDesStocksAction extends CreateFrameAbstractAction {
 
public ListeDesStocksAction() {
super();
this.putValue(Action.NAME, "Liste des stocks");
 
}
 
public JFrame createFrame() {
SQLElement eltStock = Configuration.getInstance().getDirectory().getElement("STOCK");
final SQLTable stockTable = eltStock.getTable();
final SQLTable depotTable = stockTable.getForeignTable("ID_DEPOT_STOCK");
 
List<SQLRow> rowsEtat = SQLBackgroundTableCache.getInstance().getCacheForTable(depotTable).getRows();
 
JTabbedPane tabs = new JTabbedPane();
 
for (final SQLRow sqlRow : rowsEtat) {
 
final SQLTableModelSourceOnline tableSource = eltStock.getTableSource(true);
 
SQLTableModelColumn colStock;
if (stockTable.getDBRoot().contains("ARTICLE_PRIX_REVIENT")) {
colStock = tableSource.getColumn(tableSource.getColumns().size() - 2);
} else {
 
colStock = new BaseSQLTableModelColumn("Valeur HT du stock", BigDecimal.class) {
 
@Override
protected Object show_(SQLRowAccessor stock) {
 
if (stock == null || stock.isUndefined()) {
return BigDecimal.ZERO;
} else {
float qte = stock.getFloat("QTE_REEL");
BigDecimal ha = stock.getForeign("ID_ARTICLE").getBigDecimal("PA_HT");
 
BigDecimal total = ha.multiply(new BigDecimal(qte), DecimalUtils.HIGH_PRECISION);
if (total.signum() == 1) {
return total;
} else {
return BigDecimal.ZERO;
}
}
}
 
@Override
public Set<FieldPath> getPaths() {
final SQLTable table = stockTable;
Path p = new Path(table);
Path p2 = new Path(table).addForeignField("ID_ARTICLE");
return CollectionUtils.createSet(new FieldPath(p2, "PA_HT"));
}
};
colStock.setRenderer(ComptaSQLConfElement.CURRENCY_RENDERER);
tableSource.getColumns().add(colStock);
}
 
tableSource.getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.setWhere(new Where(input.getTable("STOCK").getField("ID_DEPOT_STOCK"), "=", sqlRow.getID()));
return input;
}
});
 
final IListe liste = new IListe(tableSource);
ListeAddPanel panel = new ListeAddPanel(eltStock, liste);
panel.setAddVisible(false);
panel.setDeleteVisible(false);
List<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>> fields = new ArrayList<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>>(1);
fields.add(Tuple2.create(colStock, IListTotalPanel.Type.SOMME));
 
IListTotalPanel total = new IListTotalPanel(liste, fields, null, "Total");
GridBagConstraints c2 = new DefaultGridBagConstraints();
c2.gridy = 4;
c2.anchor = GridBagConstraints.EAST;
c2.weightx = 0;
c2.fill = GridBagConstraints.NONE;
panel.add(total, c2);
tabs.add(sqlRow.getString("NOM"), panel);
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
panel.add(tabs, c);
return new PanelFrame(panel, "Liste des stocks");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/action/ListeDesEtatsStocksAction.java
New file
0,0 → 1,24
/*
* 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.supplychain.stock.action;
 
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.supplychain.stock.element.EtatStockSQLElement;
 
public class ListeDesEtatsStocksAction extends CreateIListFrameAbstractAction<EtatStockSQLElement> {
public ListeDesEtatsStocksAction(final ComptaPropsConfiguration conf) {
super(conf, EtatStockSQLElement.class);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/action/NouvelleSaisieMouvementStockAction.java
13,22 → 13,14
package org.openconcerto.erp.core.supplychain.stock.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.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleSaisieMouvementStockAction extends CreateEditFrameAbstractAction<MouvementStockSQLElement> {
 
public class NouvelleSaisieMouvementStockAction extends CreateFrameAbstractAction {
 
public NouvelleSaisieMouvementStockAction() {
super();
this.putValue(Action.NAME, "Saisie d'un mouvement de stock");
public NouvelleSaisieMouvementStockAction(final PropsConfiguration conf) {
super(conf, MouvementStockSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/element/EcheanceFournisseurSQLElement.java
230,6 → 230,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".commitment";
return createCodeOfPackage() + ".commitment";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/element/FournisseurSQLElement.java
19,9 → 19,9
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.request.ComboSQLRequest.KeepMode;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.request.ListSQLRequest;
 
import java.util.ArrayList;
import java.util.Arrays;
37,8 → 37,9
getRowActions().add(actionAttachment);
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(8);
l.add("CODE");
l.add("NOM");
l.add("TYPE");
50,8 → 51,9
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("CODE");
return l;
80,4 → 82,9
public SQLComponent createComponent() {
return new FournisseurSQLComponent(this);
}
 
@Override
protected String createCode() {
return "supplychain.supplier";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/action/NouveauFournisseurAction.java
13,23 → 13,14
package org.openconcerto.erp.core.supplychain.supplier.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.supplychain.supplier.element.FournisseurSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauFournisseurAction extends CreateEditFrameAbstractAction<FournisseurSQLElement> {
 
public class NouveauFournisseurAction extends CreateFrameAbstractAction {
 
public NouveauFournisseurAction() {
super();
this.putValue(Action.NAME, "Test Fournisseur");
public NouveauFournisseurAction(final PropsConfiguration conf) {
super(conf, FournisseurSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("FOURNISSEUR"));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/component/MouvementStockSQLComponent.java
18,7 → 18,9
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
25,6 → 27,9
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
37,10 → 42,6
 
public class MouvementStockSQLComponent extends BaseSQLComponent {
 
private SQLTextCombo textLib;
private JTextField textQte;
private JDate date;
 
public MouvementStockSQLComponent(SQLElement element) {
super(element);
}
47,7 → 48,7
 
@Override
public Set<String> getPartialResetNames() {
Set<String> s = new HashSet<String>();
Set<String> s = new HashSet<>(2);
s.add("QTE");
s.add("ID_ARTICLE");
return s;
58,13 → 59,13
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Libellé
JLabel labelLib = new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT);
final JLabel labelLib = new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT);
this.add(labelLib, c);
 
c.gridx++;
c.weightx = 1;
this.textLib = new SQLTextCombo();
this.add(this.textLib, c);
final SQLTextCombo textLib = new SQLTextCombo();
this.add(textLib, c);
 
// Date
c.gridx++;
73,8 → 74,8
this.add(labelDate, c);
 
c.gridx++;
this.date = new JDate(true);
this.add(this.date, c);
final JDate date = new JDate(true);
this.add(date, c);
 
// Article
final ElementComboBox articleSelect = new ElementComboBox();
81,7 → 82,7
 
c.gridx = 0;
c.gridy++;
JLabel labelArticle = new JLabel(getLabelFor("ID_ARTICLE"), SwingConstants.RIGHT);
final JLabel labelArticle = new JLabel(getLabelFor("ID_ARTICLE"), SwingConstants.RIGHT);
this.add(labelArticle, c);
 
c.gridx++;
89,6 → 90,20
c.weightx = 1;
this.add(articleSelect, c);
 
// Article
final SQLRequestComboBox articleStock = new SQLRequestComboBox();
c.gridwidth = 1;
c.weightx = 0;
c.gridx = 0;
c.gridy++;
final JLabel labelStock = new JLabel(getLabelFor("ID_STOCK"), SwingConstants.RIGHT);
this.add(labelStock, c);
 
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1;
this.add(articleStock, c);
 
// QTE
c.gridwidth = 1;
c.weightx = 0;
95,18 → 110,18
c.gridy++;
c.gridx = 0;
c.anchor = GridBagConstraints.EAST;
JLabel labelQte = new JLabel(getLabelFor("QTE"), SwingConstants.RIGHT);
final JLabel labelQte = new JLabel(getLabelFor("QTE"), SwingConstants.RIGHT);
this.add(labelQte, c);
 
c.gridx++;
c.fill = GridBagConstraints.NONE;
this.textQte = new JTextField(6);
final JTextField textQte = new JTextField(6);
c.weighty = 0;
c.anchor = GridBagConstraints.NORTHWEST;
this.add(this.textQte, c);
this.add(textQte, c);
 
c.gridx++;
JCheckBox boxReel = new JCheckBox(getLabelFor("REEL"));
final JCheckBox boxReel = new JCheckBox(getLabelFor("REEL"));
this.add(boxReel, c);
addView(boxReel, "REEL");
 
115,14 → 130,25
final JPanel comp = new JPanel();
comp.setOpaque(false);
this.add(comp, c);
DefaultGridBagConstraints.lockMinimumSize(this.textQte);
DefaultGridBagConstraints.lockMaximumSize(this.textQte);
this.addRequiredSQLObject(this.textQte, "QTE");
this.addSQLObject(this.textLib, "NOM");
DefaultGridBagConstraints.lockMinimumSize(textQte);
DefaultGridBagConstraints.lockMaximumSize(textQte);
this.addRequiredSQLObject(textQte, "QTE");
this.addSQLObject(textLib, "NOM");
this.addRequiredSQLObject(articleSelect, "ID_ARTICLE");
this.addRequiredSQLObject(this.date, "DATE");
this.addRequiredSQLObject(articleStock, "ID_STOCK");
this.addRequiredSQLObject(date, "DATE");
 
articleStock.getRequest().setWhere(Where.FALSE);
articleSelect.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
articleStock.getRequest().setWhere(new Where(articleStock.getRequest().getPrimaryTable().getField("ID_ARTICLE"), "=", articleSelect.getWantedID()));
}
});
 
}
 
@Override
protected SQLRowValues createDefaults() {
SQLRowValues rowVals = new SQLRowValues(getTable());
133,7 → 159,11
@Override
public int insert(SQLRow order) {
int id = super.insert(order);
try {
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(getTable().getRow(id)), false);
} catch (SQLException e) {
throw new IllegalStateException("Impossible de metter à jour les stocks pour l'id " + id, e);
}
return id;
}
 
140,9 → 170,13
@Override
public void update() {
int id = getSelectedID();
try {
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(getTable().getRow(id)), true);
super.update();
((MouvementStockSQLElement) getElement()).updateStock(Arrays.asList(getTable().getRow(id)), false);
} catch (SQLException e) {
throw new IllegalStateException("Impossible de metter à jour les stocks pour l'id " + id, e);
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/element/AvoirFournisseurSQLElement.java
26,8 → 26,9
super("AVOIR_FOURNISSEUR", "une facture d'avoir fournisseur", "factures d'avoir fournisseur");
}
 
@Override
public List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(7);
l.add("NUMERO");
l.add("ID_FOURNISSEUR");
l.add("NOM");
38,8 → 39,9
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(4);
l.add("DATE");
l.add("NOM");
l.add("NUMERO");
56,4 → 58,8
return new AvoirFournisseurSQLComponent();
}
 
@Override
protected String createCodeSuffix() {
return ".note";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/action/NouvelAvoirFournisseurAction.java
13,22 → 13,14
package org.openconcerto.erp.core.supplychain.credit.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.supplychain.credit.element.AvoirFournisseurSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelAvoirFournisseurAction extends CreateEditFrameAbstractAction<AvoirFournisseurSQLElement> {
 
public class NouvelAvoirFournisseurAction extends CreateFrameAbstractAction {
 
public NouvelAvoirFournisseurAction() {
super();
this.putValue(Action.NAME, "Avoir fournisseur");
public NouvelAvoirFournisseurAction(final PropsConfiguration conf) {
super(conf, AvoirFournisseurSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("AVOIR_FOURNISSEUR"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/purchase/importer/FacturXImporter.java
New file
0,0 → 1,173
/*
* 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.supplychain.purchase.importer;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
 
import com.lowagie.text.pdf.PRStream;
import com.lowagie.text.pdf.PdfArray;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfString;
 
public class FacturXImporter {
public static final String TYPE_MINIMUM = "urn:factur-x.eu:1p0:minimum";
public static final String TYPE_BASIC = "urn:cen.eu:en16931:2017:compliant:factur-x.eu:1p0:basic";
public static final String RSM_NS = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
public static final String RAM_NS = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
public static final String UDT_NS = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100";
 
public FacturXImporter() {
 
}
 
public boolean importFromPDF(File file) throws IOException, JDOMException, ParseException {
Map<String, byte[]> files = new HashMap<>();
 
PdfReader reader = new PdfReader(new FileInputStream(file));
PdfDictionary root = reader.getCatalog();
PdfDictionary names = root.getAsDict(PdfName.NAMES); // may be null
PdfDictionary embeddedFilesDict = names.getAsDict(PdfName.EMBEDDEDFILES); // may be null
PdfArray embeddedFiles = embeddedFilesDict.getAsArray(PdfName.NAMES); // may be null
 
int len = embeddedFiles.size();
for (int i = 0; i < len; i += 2) {
PdfString name = embeddedFiles.getAsString(i); // should always be present
PdfDictionary fileSpec = embeddedFiles.getAsDict(i + 1); // ditto
 
PdfDictionary streams = fileSpec.getAsDict(PdfName.EF);
PRStream stream = null;
 
if (streams.contains(PdfName.UF))
stream = (PRStream) streams.getAsStream(PdfName.UF);
else
stream = (PRStream) streams.getAsStream(PdfName.F); // Default stream for backwards
// compatibility
 
if (stream != null) {
files.put(name.toUnicodeString(), PdfReader.getStreamBytes((PRStream) stream));
}
}
 
if (!files.containsKey("factur-x.xml")) {
return false;
}
SAXBuilder builder = new SAXBuilder();
 
Namespace nsRMS = Namespace.getNamespace(RSM_NS);
Namespace nsRAM = Namespace.getNamespace(RAM_NS);
Namespace nsUDT = Namespace.getNamespace(UDT_NS);
 
log(new String(files.get("factur-x.xml")));
 
Document document = (Document) builder.build(new ByteArrayInputStream(files.get("factur-x.xml")));
Element rootNode = document.getRootElement();
 
Element exchangedDocumentContext = rootNode.getChild("ExchangedDocumentContext", nsRMS);
Element guidelineSpecifiedDocumentContextParameter = exchangedDocumentContext.getChild("GuidelineSpecifiedDocumentContextParameter", nsRAM);
//
String type = guidelineSpecifiedDocumentContextParameter.getChildText("ID", nsRAM);
log("type de FacturX : " + type);
 
Element exchangedDocument = rootNode.getChild("ExchangedDocument", nsRMS);
String numeroFacture = exchangedDocument.getChildText("ID", nsRAM);
log("numéro de facture : " + numeroFacture);
// Type de facture
// 380 : Facture commerciale
// 381 : Avoir (note de crédit)
// 384 : Facture rectificative
// 386 : Facture d'acompte
String typeFacture = exchangedDocument.getChildText("TypeCode", nsRAM);
log("type de facture : " + typeFacture);
 
Element dateTimeString = exchangedDocument.getChild("IssueDateTime", nsRAM).getChild("DateTimeString", nsUDT);
if (!dateTimeString.getAttributeValue("format").equals("102")) {
throw new IllegalArgumentException("invalid date format : " + dateTimeString.getAttributeValue("format"));
}
String txtDateTimeString = dateTimeString.getText();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
Date dateFacture = df.parse(txtDateTimeString);
log("date de facture : " + dateFacture);
String commentaire = "";
if (exchangedDocument.getChild("IncludedNote", nsRAM) != null && exchangedDocument.getChild("IncludedNote").getChild("Content", nsRAM) != null) {
commentaire = exchangedDocument.getChild("IncludedNote", nsRAM).getChildText("Content", nsRAM);
}
log("commentaire : " + commentaire);
//
final Element supplyChainTradeTransaction = rootNode.getChild("SupplyChainTradeTransaction", nsRMS);
 
Element applicableHeaderTradeAgreement = supplyChainTradeTransaction.getChild("ApplicableHeaderTradeAgreement", nsRAM);
Element sellerTradeParty = applicableHeaderTradeAgreement.getChild("SellerTradeParty", nsRAM);
final String nomFournisseur = sellerTradeParty.getChildText("Name", nsRAM);
log("nom du fournisseur : " + nomFournisseur);
Element specifiedLegalOrganization = sellerTradeParty.getChild("SpecifiedLegalOrganization", nsRAM);
String siretFournisseur = specifiedLegalOrganization.getChildText("ID", nsRAM);
log("SIRET du fournisseur : " + siretFournisseur);
 
Element postalTradeAddress = sellerTradeParty.getChild("PostalTradeAddress", nsRAM);
String codePays = postalTradeAddress.getChildText("CountryID", nsRAM);
log("Code pays du fournisseur : " + codePays);
 
Element specifiedTaxRegistration = sellerTradeParty.getChild("SpecifiedTaxRegistration", nsRAM);
String tvaFournisseur = specifiedTaxRegistration.getChildText("ID", nsRAM);
log("TVA du fournisseur : " + tvaFournisseur);
 
//
// Element applicableHeaderTradeDelivery =
// supplyChainTradeTransaction.getChild("ApplicableHeaderTradeDelivery", nsRAM);
 
//
Element applicableHeaderTradeSettlement = supplyChainTradeTransaction.getChild("ApplicableHeaderTradeSettlement", nsRAM);
String codeDevise = applicableHeaderTradeSettlement.getChildText("InvoiceCurrencyCode", nsRAM);
log("code devise : " + codeDevise);
 
Element specifiedTradeSettlementHeaderMonetarySummation = applicableHeaderTradeSettlement.getChild("SpecifiedTradeSettlementHeaderMonetarySummation", nsRAM);
BigDecimal totalHT = new BigDecimal(specifiedTradeSettlementHeaderMonetarySummation.getChildText("TaxBasisTotalAmount", nsRAM));
BigDecimal totalTax = new BigDecimal(specifiedTradeSettlementHeaderMonetarySummation.getChildText("TaxTotalAmount", nsRAM));
BigDecimal totalTTC = new BigDecimal(specifiedTradeSettlementHeaderMonetarySummation.getChildText("GrandTotalAmount", nsRAM));
BigDecimal totalNetPayer = new BigDecimal(specifiedTradeSettlementHeaderMonetarySummation.getChildText("DuePayableAmount", nsRAM));
log("total HT : " + totalHT);
log("total TVA : " + totalTax);
log("total TTC : " + totalTTC);
log("total à payer : " + totalNetPayer);
return true;
 
}
 
private void log(String string) {
System.err.println(string);
}
 
public static void main(String[] args) throws Exception {
FacturXImporter i = new FacturXImporter();
i.importFromPDF(new File("test/FacturX/Facture_FR_MINIMUM.pdf"));
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/NouvelleFactureFournisseurAction.java
13,22 → 13,14
package org.openconcerto.erp.core.supplychain.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.supplychain.order.element.FactureFournisseurSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleFactureFournisseurAction extends CreateEditFrameAbstractAction<FactureFournisseurSQLElement> {
 
public class NouvelleFactureFournisseurAction extends CreateFrameAbstractAction {
 
public NouvelleFactureFournisseurAction() {
super();
this.putValue(Action.NAME, "Facture fournisseur");
public NouvelleFactureFournisseurAction(final PropsConfiguration conf) {
super(conf, FactureFournisseurSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("FACTURE_FOURNISSEUR"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/NouvelleDemandePrixAction.java
13,21 → 13,14
package org.openconcerto.erp.core.supplychain.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.supplychain.order.element.DemandePrixSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleDemandePrixAction extends CreateEditFrameAbstractAction<DemandePrixSQLElement> {
 
public class NouvelleDemandePrixAction extends CreateFrameAbstractAction {
public NouvelleDemandePrixAction() {
super();
this.putValue(Action.NAME, "Demande Prix");
public NouvelleDemandePrixAction(final PropsConfiguration conf) {
super(conf, DemandePrixSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("DEMANDE_PRIX"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/NouvelleCommandeAction.java
13,21 → 13,14
package org.openconcerto.erp.core.supplychain.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.supplychain.order.element.CommandeSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouvelleCommandeAction extends CreateEditFrameAbstractAction<CommandeSQLElement> {
 
public class NouvelleCommandeAction extends CreateFrameAbstractAction {
public NouvelleCommandeAction() {
super();
this.putValue(Action.NAME, "Commande Fournisseur");
public NouvelleCommandeAction(final PropsConfiguration conf) {
super(conf, CommandeSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("COMMANDE"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesDemandesPrixAction.java
13,30 → 13,12
package org.openconcerto.erp.core.supplychain.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
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.SQLTableModelSourceOnline;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.supplychain.order.element.DemandePrixSQLElement;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesDemandesPrixAction extends CreateFrameAbstractAction {
public ListeDesDemandesPrixAction() {
super();
this.putValue(Action.NAME, "Liste des demandes de prix");
public class ListeDesDemandesPrixAction extends CreateIListFrameAbstractAction<DemandePrixSQLElement> {
public ListeDesDemandesPrixAction(final ComptaPropsConfiguration conf) {
super(conf, DemandePrixSQLElement.class);
}
 
public JFrame createFrame() {
 
final SQLElement elementCmd = Configuration.getInstance().getDirectory().getElement("DEMANDE_PRIX");
final SQLTableModelSourceOnline tableSource = elementCmd.getTableSource(true);
final IListFrame frame = new IListFrame(new ListeAddPanel(elementCmd, new IListe(tableSource)));
 
return frame;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesElementsACommanderAction.java
13,74 → 13,39
package org.openconcerto.erp.core.supplychain.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.sql.Configuration;
import org.openconcerto.erp.core.supplychain.order.element.CommandeElementSQLElement;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.FieldRef;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.list.SQLTableModelSource;
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;
 
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.Arrays;
import java.util.Collection;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class ListeDesElementsACommanderAction extends CreateFrameAbstractAction {
public class ListeDesElementsACommanderAction extends CreateIListFrameAbstractAction<CommandeElementSQLElement> {
 
public ListeDesElementsACommanderAction() {
super();
this.putValue(Action.NAME, "Liste des éléments en attente de réception");
public ListeDesElementsACommanderAction(final ComptaPropsConfiguration conf) {
super(conf, CommandeElementSQLElement.class);
}
 
private BaseSQLTableModelColumn colAvancement;
 
public JFrame createFrame() {
final JFrame frame = new JFrame("Eléments à réceptionner");
// Actions
final SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT");
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 SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT");
final SQLTableModelSourceOnline tableSource = eltCmd.getTableSource(true);
@Override
protected SQLTableModelSource createTableSource() {
final SQLTableModelSource tableSource = super.createTableSource();
final SQLElement eltCmd = getElem();
tableSource.getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
92,19 → 57,18
final String quoteQteU = new SQLName(input.getAlias(eltCmd.getTable()).getAlias(), "QTE_UNITAIRE").quote();
Where w = Where.createRaw(quoteQteL + " < (" + quoteQte + "*" + quoteQteU + ")", eltCmd.getTable().getField("QTE_RECUE"), eltCmd.getTable().getField("QTE"),
eltCmd.getTable().getField("QTE_UNITAIRE"));
w = w.and(new Where(eltCmd.getTable().getField("RECU_FORCED"), "=", Boolean.FALSE));
input.setWhere(w);
return input;
}
});
 
final ListeAddPanel panel = getPanel(eltCmd, tableSource);
 
return panel;
return tableSource;
}
 
private ListeAddPanel getPanel(final SQLElement eltCmd, final SQLTableModelSourceOnline tableSource) {
final ListeAddPanel panel = new ListeAddPanel(eltCmd, new IListe(tableSource));
 
@Override
protected IListPanel instantiateListPanel(final SQLTableModelSource tableSource, String panelVariant) {
final IListPanel panel = super.instantiateListPanel(tableSource, panelVariant);
// 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")),
121,7 → 85,7
c.gridy = 4;
 
// Date panel
final IListFilterDatePanel datePanel = new IListFilterDatePanel(panel.getListe(), eltCmd.getTable().getForeignTable("ID_COMMANDE").getField("DATE"), IListFilterDatePanel.getDefaultMap());
final IListFilterDatePanel datePanel = new IListFilterDatePanel(panel.getListe(), getElem().getTable().getForeignTable("ID_COMMANDE").getField("DATE"), IListFilterDatePanel.getDefaultMap());
 
datePanel.setFilterOnDefault();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesDemandesAchatsAction.java
13,30 → 13,12
package org.openconcerto.erp.core.supplychain.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
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.SQLTableModelSourceOnline;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.supplychain.order.element.DemandeAchatItemSQLElement;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesDemandesAchatsAction extends CreateFrameAbstractAction {
public ListeDesDemandesAchatsAction() {
super();
this.putValue(Action.NAME, "Liste des demandes d'achat");
public class ListeDesDemandesAchatsAction extends CreateIListFrameAbstractAction<DemandeAchatItemSQLElement> {
public ListeDesDemandesAchatsAction(final ComptaPropsConfiguration conf) {
super(conf, DemandeAchatItemSQLElement.class);
}
 
public JFrame createFrame() {
 
final SQLElement elementCmd = Configuration.getInstance().getDirectory().getElement("DEMANDE_ACHAT_ELEMENT");
final SQLTableModelSourceOnline tableSource = elementCmd.getTableSource(true);
final IListFrame frame = new IListFrame(new ListeAddPanel(elementCmd, new IListe(tableSource)));
 
return frame;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/NouveauSaisieAchatAction.java
13,22 → 13,14
package org.openconcerto.erp.core.supplychain.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.supplychain.order.element.SaisieAchatSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauSaisieAchatAction extends CreateEditFrameAbstractAction<SaisieAchatSQLElement> {
 
public class NouveauSaisieAchatAction extends CreateFrameAbstractAction {
 
public NouveauSaisieAchatAction() {
super();
this.putValue(Action.NAME, "Achat fournisseur");
public NouveauSaisieAchatAction(final PropsConfiguration conf) {
super(conf, SaisieAchatSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("SAISIE_ACHAT"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/FactureFournisseurSQLComponent.java
35,7 → 35,9
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.UserManager;
47,6 → 49,7
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.preferences.DefaultProps;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.Color;
55,6 → 58,7
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.sql.SQLException;
 
import javax.swing.JLabel;
import javax.swing.JPanel;
72,13 → 76,17
private final ITextArea infos = new ITextArea(3, 3);
private ElementComboBox fourn = new ElementComboBox();
private ElementComboBox comptePCE = new ElementComboBox();
private ElementComboBox avoirFourn = new ElementComboBox();
private DefaultElementSQLObject compAdr;
private PanelOOSQLComponent panelOO;
final JPanel panelAdrSpec = new JPanel(new GridBagLayout());
private JDate dateCommande = new JDate();
private final JTextField fieldTaux = new JTextField(15);
private final DeviseField textNetAPayer = new DeviseField(15);
private final JLabel labelTaux = new JLabel();
private ElementSQLObject eltModeRegl;
DeviseField fieldTTC = new DeviseField();
DeviseField avoirTTC = new DeviseField();
private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
170,6 → 178,28
this.add(this.fourn, c);
addRequiredSQLObject(this.fourn, "ID_FOURNISSEUR");
 
fourn.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = fourn.getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
 
final SQLRow rowF = getTable().getForeignTable("ID_FOURNISSEUR").getRow(wantedID);
 
if (rowF.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowF.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
table.setRowCatComptable(rowF.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
table.setRowCatComptable(null);
}
 
} else {
table.setRowCatComptable(null);
}
}
});
this.fourn.addModelListener("wantedID", this.listenerModeReglDefaut);
 
// Champ Module
c.gridx = 0;
c.gridy++;
181,9 → 211,11
c.gridy++;
c.gridwidth = 1;
 
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
 
final ElementComboBox boxDevise = new ElementComboBox();
 
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Devise
c.gridx = 0;
c.gridy++;
204,15 → 236,20
@Override
public void propertyChange(PropertyChangeEvent evt) {
table.setFournisseur(fourn.getSelectedRow());
SQLRow row = fourn.getSelectedRow();
if (!isFilling()) {
SQLRow row = fourn.getSelectedRow();
if (row != null && !row.isUndefined() && !row.isForeignEmpty("ID_DEVISE")) {
boxDevise.setValue(row.getForeignID("ID_DEVISE"));
}
}
 
if (row != null && !row.isUndefined()) {
avoirFourn.getRequest().setWhere(new Where(avoirFourn.getRequest().getPrimaryTable().getField("ID_FOURNISSEUR"), "=", row.getID()));
} else {
avoirFourn.getRequest().setWhere(null);
}
}
});
this.fourn.addModelListener("wantedID", this.listenerModeReglDefaut);
 
if (getTable().contains("TAUX_APPLIQUE")) {
// Devise
297,7 → 334,7
c.weighty = 1;
c.gridwidth = 4;
this.add(this.table, c);
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
 
boxDevise.addValueListener(new PropertyChangeListener() {
 
330,12 → 367,14
table.setFournisseur(fourn.getSelectedRow());
if (!isFilling()) {
SQLRow row = fourn.getSelectedRow();
if (row != null && !row.isUndefined()) {
row.fetchValues();
if (row != null && !row.isUndefined() && !row.isForeignEmpty("ID_COMPTE_PCE_CHARGE")) {
if (!row.isForeignEmpty("ID_COMPTE_PCE_CHARGE")) {
comptePCE.setValue(row.getForeign("ID_COMPTE_PCE_CHARGE"));
}
}
}
}
});
// Bottom
c.gridy++;
490,7 → 529,6
DeviseField fieldHT = new DeviseField();
DeviseField fieldEco = new DeviseField();
DeviseField fieldTVA = new DeviseField();
DeviseField fieldTTC = new DeviseField();
DeviseField fieldDevise = new DeviseField();
DeviseField fieldService = new DeviseField();
fieldHT.setOpaque(false);
505,6 → 543,14
addRequiredSQLObject(fieldTTC, "T_TTC");
addRequiredSQLObject(fieldService, "T_SERVICE");
 
fieldTTC.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update(DocumentEvent e) {
refreshText();
}
 
});
 
// Disable
this.allowEditable("T_ECO_CONTRIBUTION", false);
this.allowEditable("T_HT", false);
528,6 → 574,12
panel.add(totalTTC, c);
 
c.gridy += 3;
c.gridheight = 1;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
panel.add(createPanelAvoir(), c);
 
c.gridy += 4;
c.gridheight = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
607,12 → 659,15
// Création des articles
this.table.createArticle(idFacture, this.getElement());
 
new GenerationMvtFactureFournisseur(getTable().getRow(idFacture));
final SQLRow rowA = getTable().getRow(idFacture);
new GenerationMvtFactureFournisseur(rowA);
 
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(getTable().getRow(idFacture));
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(rowA);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
 
commitAvoir(null, rowA);
 
return idFacture;
}
 
619,6 → 674,7
@Override
public void update() {
 
SQLRow rowFactureOld = getTable().getRow(getSelectedID());
super.update();
SQLRow row = getTable().getRow(getSelectedID());
this.table.updateField("ID_FACTURE_FOURNISSEUR", row.getID());
638,8 → 694,41
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(row);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
commitAvoir(rowFactureOld, row);
}
 
public void commitAvoir(SQLRow rowFactureOld, SQLRow rowFacture) {
try {
if (rowFactureOld != null && rowFactureOld.getObject("ID_AVOIR_FOURNISSEUR") != null && !rowFactureOld.isForeignEmpty("ID_AVOIR_FOURNISSEUR")
&& (rowFacture.getObject("ID_AVOIR_FOURNISSEUR") == null || rowFacture.isForeignEmpty("ID_AVOIR_FOURNISSEUR"))) {
 
SQLRow rowAvoir = rowFactureOld.getForeignRow("ID_AVOIR_FOURNISSEUR");
 
SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
 
// Soldé
rowVals.put("SOLDE", Boolean.FALSE);
 
rowVals.update();
 
}
 
// on solde l'avoir
if (rowFacture.getObject("ID_AVOIR_FOURNISSEUR") != null && !rowFacture.isForeignEmpty("ID_AVOIR_FOURNISSEUR")) {
 
SQLRow rowAvoir = rowFacture.getForeignRow("ID_AVOIR_FOURNISSEUR");
 
SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
rowVals.put("SOLDE", Boolean.TRUE);
 
rowVals.update();
 
}
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors la mise à jour de l'avoir associée!", e);
}
}
 
public void setDefaults() {
this.resetValue();
this.table.getModel().clearRows();
684,6 → 773,82
return this.table.getRowValuesTable();
}
 
private JPanel createPanelAvoir() {
JPanel panelAvoir = new JPanel(new GridBagLayout());
panelAvoir.setOpaque(false);
GridBagConstraints cA = new DefaultGridBagConstraints();
JLabel labelAvoir = new JLabel(getLabelFor("ID_AVOIR_FOURNISSEUR"));
labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
cA.weightx = 1;
labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
panelAvoir.add(labelAvoir, cA);
cA.weightx = 0;
cA.gridx++;
this.avoirFourn = new ElementComboBox();
this.avoirFourn.setAddIconVisible(false);
panelAvoir.add(this.avoirFourn, cA);
final JLabel labelTotalAvoir = new JLabel("Total à régler");
this.textNetAPayer.setEditable(false);
cA.gridx++;
cA.weightx = 0;
panelAvoir.add(labelTotalAvoir, cA);
cA.gridx++;
cA.weightx = 0;
panelAvoir.add(this.textNetAPayer, cA);
addView(textNetAPayer, "NET_A_PAYER");
this.textNetAPayer.setHorizontalAlignment(SwingConstants.RIGHT);
 
addView(this.avoirFourn, "ID_AVOIR_FOURNISSEUR");
addView(avoirTTC, "AVOIR_TTC");
this.avoirFourn.addValueListener(new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
refreshText();
}
 
});
 
return panelAvoir;
}
 
private void refreshText() {
Number n = this.fieldTTC.getValue();
long totalAvoirTTC = 0;
long netAPayer = 0;
long ttc = 0;
if (n != null) {
netAPayer = n.longValue();
ttc = n.longValue();
}
 
if (this.avoirFourn.getSelectedId() > 1) {
SQLTable tableAvoir = getTable().getForeignTable("ID_AVOIR_FOURNISSEUR");
if (n != null) {
SQLRow rowAvoir = tableAvoir.getRow(this.avoirFourn.getSelectedId());
long totalAvoir = ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue();
if (getSelectedID() > 1) {
SQLRow row = getTable().getRow(getSelectedID());
int idAvoirOld = row.getInt("ID_AVOIR_FOURNISSEUR");
if (idAvoirOld == rowAvoir.getID()) {
totalAvoir += Long.valueOf(row.getObject("AVOIR_TTC").toString());
}
}
 
long l = ttc - totalAvoir;
if (l < 0) {
l = 0;
totalAvoirTTC = ttc;
} else {
totalAvoirTTC = totalAvoir;
}
netAPayer = l;
}
}
 
this.textNetAPayer.setValue(netAPayer);
this.avoirTTC.setValue(totalAvoirTTC);
}
 
@Override
protected void refreshAfterSelect(SQLRowAccessor rSource) {
if (this.dateCommande.getValue() != null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
43,6 → 43,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
69,6 → 70,7
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.util.List;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
168,7 → 170,27
c.fill = GridBagConstraints.NONE;
this.add(this.fourn, c);
addRequiredSQLObject(this.fourn, "ID_FOURNISSEUR");
fourn.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = fourn.getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
 
final SQLRow rowF = getTable().getForeignTable("ID_FOURNISSEUR").getRow(wantedID);
 
if (rowF.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowF.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
table.setRowCatComptable(rowF.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
table.setRowCatComptable(null);
}
 
} else {
table.setRowCatComptable(null);
}
}
});
 
if (!getTable().getFieldsName().contains("LIVRER")) {
// Commande en cours
JCheckBox boxEnCours = new JCheckBox(getLabelFor("EN_COURS"));
454,8 → 476,11
c.gridy++;
c.gridwidth = 1;
 
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
 
final ElementComboBox boxDevise = new ElementComboBox();
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
// Devise
c.gridx = 0;
c.gridy++;
553,7 → 578,7
c.weighty = 1;
c.gridwidth = 4;
this.add(this.table, c);
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
if (showDevise) {
 
boxDevise.addValueListener(new PropertyChangeListener() {
 
915,10 → 940,7
}
 
super.select(r);
if (r != null) {
this.table.insertFrom("ID_COMMANDE", r.getID());
}
}
 
@Override
public void update() {
1099,4 → 1121,39
}
 
}
 
public void duplicate(final int idCmd) {
 
final SQLElement cmd = Configuration.getInstance().getDirectory().getElement("COMMANDE");
final SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT");
 
if (idCmd > 1) {
final SQLRow row = cmd.getTable().getRow(idCmd);
final SQLRowValues rowVals = new SQLRowValues(cmd.getTable());
rowVals.put("ID_FOURNISSEUR", row.getInt("ID_FOURNISSEUR"));
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
 
this.select(rowVals);
}
 
final List<SQLRow> myListItem = cmd.getTable().getRow(idCmd).getReferentRows(cmdElt.getTable());
 
if (myListItem.size() != 0) {
this.table.getModel().clearRows();
 
for (final SQLRow rowElt : myListItem) {
 
final SQLRowValues rowVals = rowElt.createUpdateRow();
rowVals.clearPrimaryKeys();
this.table.getModel().addRow(rowVals);
final int rowIndex = this.table.getModel().getRowCount() - 1;
this.table.getModel().fireTableModelModified(rowIndex);
}
} else {
this.table.getModel().clearRows();
}
this.table.getModel().fireTableDataChanged();
this.table.repaint();
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/FabricantSQLElement.java
66,7 → 66,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".manufacturor";
return createCodeOfPackage() + ".manufacturor";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/EtatDemandeAchatItemSQLElement.java
75,7 → 75,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".achat.state";
return createCodeOfPackage() + ".achat.state";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeElementSQLElement.java
17,11 → 17,25
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
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 java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JTextField;
 
public class CommandeElementSQLElement extends ComptaSQLConfElement {
28,9 → 42,59
 
public CommandeElementSQLElement() {
super("COMMANDE_ELEMENT", "un element de commande", "éléments de commande");
 
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"), EditMode.MODIFICATION);
f.getSQLComponent().select(selectedRow.getForeignID("ID_COMMANDE"));
FrameUtil.showPacked(f);
}
 
}, true);
rowActionCmd.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(rowActionCmd);
 
if (getTable().getForeignTable("ID_USER_COMMON_CREATE").getRow(UserManager.getUserID()).getBoolean("ADMIN")) {
PredicateRowAction rowActionA = new PredicateRowAction(new AbstractAction("Forcer la réception") {
 
@Override
public void actionPerformed(ActionEvent e) {
updateForceLivrer(e, Boolean.TRUE);
}
 
}, true);
rowActionA.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(rowActionA);
PredicateRowAction rowActionC = new PredicateRowAction(new AbstractAction("Annuler forcer la réception") {
 
@Override
public void actionPerformed(ActionEvent e) {
updateForceLivrer(e, Boolean.FALSE);
}
 
}, true);
rowActionC.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(rowActionC);
}
}
 
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("RECU_FORCED", state);
build.setWhere(new Where(getTable().getKey(), ids));
getTable().getDBSystemRoot().getDataSource().execute(build.asString());
IListe.get(e).getModel().updateAll();
}
 
@Override
protected String getParentFFName() {
return "ID_COMMANDE";
}
44,11 → 108,15
l.add("ID_ARTICLE");
l.add("PA_HT");
l.add("PV_HT");
l.add("T_PA_HT");
l.add("T_PV_HT");
l.add("ID_TAXE");
l.add("QTE");
l.add("QTE_UNITAIRE");
l.add("QTE_RECUE");
l.add("POIDS");
l.add("RECU_FORCED");
l.add("RECU");
return l;
}
 
85,6 → 153,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/FactureFournisseurSQLElement.java
24,7 → 24,9
import org.openconcerto.utils.ListMap;
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public class FactureFournisseurSQLElement extends ComptaSQLConfElement {
 
41,6 → 43,13
}
}
 
@Override
public Set<String> getReadOnlyFields() {
Set<String> s = new HashSet<>();
s.add("NET_A_PAYER");
return s;
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("NUMERO");
79,6 → 88,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".invoice.purchase";
return createCodeOfPackage() + ".invoice.purchase";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandePrixSQLElement.java
90,7 → 90,7
}
 
public DemandePrixSQLElement() {
super("DEMANDE_PRIX", "une demande de prix fournisseur", "demandes de prix fournisseur");
super("DEMANDE_PRIX");
 
MouseSheetXmlListeListener l = new MouseSheetXmlListeListener(DemandePrixSheetXML.class) {
 
192,7 → 192,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".demande";
return createCodeOfPackage() + ".demande";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/TransferSupplierOrderSQLElement.java
44,6 → 44,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transfer";
return createCodeOfPackage() + ".transfer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/FactureFournisseurElementSQLElement.java
84,6 → 84,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + "invoice.purchase.item";
return createCodeOfPackage() + "invoice.purchase.item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandeAchatItemSQLElement.java
55,7 → 55,7
public class DemandeAchatItemSQLElement extends ComptaSQLConfElement {
 
public DemandeAchatItemSQLElement() {
super("DEMANDE_ACHAT_ELEMENT", "une demande d'achat", "demandes d'achat");
super("DEMANDE_ACHAT_ELEMENT");
{
PredicateRowAction actionP = new PredicateRowAction(new AbstractAction("Créer à partir de") {
 
416,7 → 416,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".demande.achat";
return createCodeOfPackage() + ".demande.achat";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/EtatDemandePrixSQLElement.java
71,7 → 71,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".state";
return createCodeOfPackage() + ".state";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/SaisieAchatSQLElement.java
81,7 → 81,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".purchase";
return createCodeOfPackage() + ".purchase";
}
 
public void transfertAvoir(int idFacture) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandePrixItemSQLElement.java
78,7 → 78,7
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".demande.item";
return createCodeOfPackage() + ".demande.item";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeSQLElement.java
26,6 → 26,7
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.TreesOfSQLRows;
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;
33,8 → 34,10
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.ITransformer;
79,6 → 82,8
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(factureAction);
 
getRowActions().add(getCloneAction());
 
PredicateRowAction tagValidAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
 
95,8 → 100,9
getRowActions().add(tagValidAction);
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(8);
l.add("NUMERO");
l.add("NOM");
l.add("DATE");
108,8 → 114,9
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(3);
l.add("NUMERO");
l.add("NOM");
l.add("DATE");
140,7 → 147,7
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
List<Integer> ids = new ArrayList<Integer>(selectedRows.size());
final List<Integer> ids = new ArrayList<>(selectedRows.size());
for (SQLRowValues sqlRowValues : selectedRows) {
ids.add(sqlRowValues.getID());
}
147,7 → 154,6
SQLSelectJoin joinBR = input.addJoin("RIGHT", tableElt.getTable("BON_RECEPTION_ELEMENT").getField("ID_BON_RECEPTION"));
SQLSelectJoin joinTR = input.addBackwardJoin("RIGHT", tableElt.getTable("TR_COMMANDE").getField("ID_BON_RECEPTION"), joinBR.getJoinedTable().getAlias());
joinTR.setWhere(new Where(joinTR.getJoinedTable().getField("ID_COMMANDE"), ids));
System.err.println(input.asString());
return input;
}
});
160,14 → 166,11
* @param commandeID
*/
public void transfertFacture(int commandeID) {
 
SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_ACHAT");
EditFrame editFactureFrame = new EditFrame(elt);
editFactureFrame.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage());
 
SaisieAchatSQLComponent comp = (SaisieAchatSQLComponent) editFactureFrame.getSQLComponent();
 
// comp.setDefaults();
comp.loadCommande(commandeID);
 
editFactureFrame.pack();
175,7 → 178,27
editFactureFrame.setVisible(true);
}
 
public RowAction getCloneAction() {
return new RowAction(new AbstractAction() {
 
public void actionPerformed(ActionEvent e) {
SQLRowAccessor selectedRow = IListe.get(e).getSelectedRow();
 
SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("COMMANDE");
EditFrame editFrame = new EditFrame(eltFact, EditPanel.CREATION);
 
((CommandeSQLComponent) editFrame.getSQLComponent()).duplicate(selectedRow.getID());
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);
}
};
}
 
@Override
protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
 
for (SQLRow row : trees.getRows()) {
200,4 → 223,8
super.archive(trees, cutLinks);
}
 
@Override
protected String createCode() {
return "supplychain.order";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/action/NouveauBonReceptionElementAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/action/NouveauBonReceptionAction.java
13,22 → 13,14
package org.openconcerto.erp.core.supplychain.receipt.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.supplychain.receipt.element.BonReceptionSQLElement;
import org.openconcerto.sql.PropsConfiguration;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class NouveauBonReceptionAction extends CreateEditFrameAbstractAction<BonReceptionSQLElement> {
 
public class NouveauBonReceptionAction extends CreateFrameAbstractAction {
 
public NouveauBonReceptionAction() {
super();
this.putValue(Action.NAME, "Bon de réception");
public NouveauBonReceptionAction(final PropsConfiguration conf) {
super(conf, BonReceptionSQLElement.class);
}
 
@Override
public JFrame createFrame() {
return new EditFrame(Configuration.getInstance().getDirectory().getElement("BON_RECEPTION"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
199,6 → 199,27
this.tableBonItem = new BonReceptionItemTable();
this.addRequiredSQLObject(this.fournisseur, "ID_FOURNISSEUR");
 
fournisseur.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = fournisseur.getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
 
final SQLRow rowF = getTable().getForeignTable("ID_FOURNISSEUR").getRow(wantedID);
 
if (rowF.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowF.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
tableBonItem.setRowCatComptable(rowF.getForeign("ID_CATEGORIE_COMPTABLE"));
} else {
tableBonItem.setRowCatComptable(null);
}
 
} else {
tableBonItem.setRowCatComptable(null);
}
}
});
 
// Devise
c.gridx = 0;
c.gridy++;
438,7 → 459,7
this.allowEditable("TOTAL_TVA", false);
this.allowEditable("TOTAL_TTC", false);
 
final TotalPanel totalTTC = new TotalPanel(this.tableBonItem, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, null, null,
final TotalPanel totalTTC = new TotalPanel(this.tableBonItem, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, textPoidsTotal, null,
(getTable().contains("ID_TAXE_PORT") ? comboTaxePort : null), null);
 
c.gridx++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/CodeFournisseurSQLElement.java
58,6 → 58,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".productcode";
return createCodeOfPackage() + ".productcode";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/TransferReceiptSQLElement.java
43,6 → 43,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transfer";
return createCodeOfPackage() + ".transfer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionElementSQLElement.java
80,6 → 80,6
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
return createCodeOfPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionSQLElement.java
51,7 → 51,7
public class BonReceptionSQLElement extends ComptaSQLConfElement {
 
public BonReceptionSQLElement() {
super("BON_RECEPTION", "un bon de réception", "Bons de réception");
super("BON_RECEPTION", "un bon de réception", "bons de réception");
 
PredicateRowAction actionsTRFA = new PredicateRowAction(new AbstractAction("Transfert vers facture fournisseur") {
public void actionPerformed(ActionEvent e) {
81,8 → 81,9
return ListMap.singleton(null, "NUMERO", "DATE");
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(5);
l.add("NUMERO");
l.add("DATE");
l.add("ID_FOURNISSEUR");
91,8 → 92,9
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(2);
l.add("NUMERO");
l.add("DATE");
return l;
119,8 → 121,6
editFactureFrame.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage());
 
SaisieAchatSQLComponent comp = (SaisieAchatSQLComponent) editFactureFrame.getSQLComponent();
 
// comp.setDefaults();
comp.loadBonReception(brID);
editFactureFrame.pack();
editFactureFrame.setState(JFrame.NORMAL);
151,7 → 151,7
@Override
protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
List<Object> cmds = null;
List<Integer> ids = new ArrayList<Integer>();
List<Integer> ids = new ArrayList<>();
for (SQLRow row : trees.getRows()) {
cmds = getCmdFrom(row.getID());
ids.add(row.getID());
178,4 → 178,9
updateCmdElement(cmds, id);
}
}
 
@Override
protected String createCodeSuffix() {
return ".note";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ModeleCourrierClientSQLElement.java
88,6 → 88,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".mailtemplate";
return this.createCodeOfPackage() + ".mailtemplate";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerGroup.java
88,6 → 88,8
gState.addItem("ID_COMMERCIAL");
gState.addItem("ID_LANGUE");
gState.addItem("ID_TARIF");
gState.addItem("ID_CATEGORIE_COMPTABLE");
gState.addItem("ID_FRAIS_DOCUMENT");
 
final Group gCustomProduct = new Group("customerrelationship.customer.customproduct", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gCustomProduct.addItem("customerrelationship.customer.customproduct", new LayoutHints(true, true, true, true, true, true, true, true));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
189,4 → 189,8
return new ClientNormalSQLComponent(this);
}
 
@Override
protected String createCode() {
return "customerrelationship.customer";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CourrierClientSQLElement.java
337,6 → 337,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".mail";
return this.createCodeOfPackage() + ".mail";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/TypeLettreRelanceSQLElement.java
56,6 → 56,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".chaseletter.type";
return this.createCodeOfPackage() + ".chaseletter.type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ContactSQLElement.java
13,15 → 13,14
package org.openconcerto.erp.core.customerrelationship.customer.element;
 
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
 
import java.awt.event.ActionEvent;
 
import javax.swing.AbstractAction;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
 
public class ContactSQLElement extends ContactSQLElementBase {
 
static public class ContactFournisseurSQLElement extends ContactSQLElement {
43,7 → 42,6
 
protected ContactSQLElement(String tableName) {
super(tableName);
this.setL18nLocation(Gestion.class);
PredicateRowAction action = new PredicateRowAction(new AbstractAction() {
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CompteClientTransactionSQLELement.java
43,6 → 43,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".account.transaction";
return this.createCodeOfPackage() + ".account.transaction";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ReferenceClientSQLElement.java
70,6 → 70,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".ref";
return this.createCodeOfPackage() + ".ref";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerCategorySQLElement.java
55,6 → 55,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".category";
return this.createCodeOfPackage() + ".category";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLComponent.java
13,41 → 13,8
package org.openconcerto.erp.core.customerrelationship.customer.element;
 
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.text.DecimalFormat;
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.Set;
 
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.component.AdresseSQLComponent;
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
86,11 → 53,46
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.component.InteractionMode;
 
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.text.DecimalFormat;
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.Set;
 
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
 
// Client without CTech link (i.e. there's one and only table in the DB)
public class ClientNormalSQLComponent extends BaseSQLComponent {
 
private int idDefaultCompteClient = 1;
private JCheckBox checkAdrLivraison, checkAdrFacturation;
private JCheckBox checkAdrFacturation;
 
private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
private ElementComboBox boxPays = null;
private final ElementComboBox boxTarif = new ElementComboBox();
97,7 → 99,7
 
protected boolean showMdr = true;
 
private ElementSQLObject componentPrincipale, componentLivraison, componentFacturation;
private ElementSQLObject componentPrincipale, componentFacturation;
private AdresseClientItemTable adresseTable = new AdresseClientItemTable();
private JCheckBox boxGestionAutoCompte;
private Map<SQLField, JCheckBox> mapCheckLivraison = new HashMap<SQLField, JCheckBox>();
141,7 → 143,16
// Code
JLabel labelCode = new JLabel(getLabelFor("CODE"));
labelCode.setHorizontalAlignment(SwingConstants.RIGHT);
this.textCode = new JUniqueTextField();
this.textCode = new JUniqueTextField() {
@Override
public String getAutoRefreshNumber() {
if (getMode() == Mode.INSERTION) {
return NumerotationAutoSQLElement.getNextNumero(getElement().getClass());
} else {
return null;
}
}
};
c.gridx++;
c.weightx = 0;
c.weighty = 0;
448,15 → 459,6
c.fill = GridBagConstraints.BOTH;
this.add(textInfos, c);
 
this.checkAdrLivraison.addActionListener(new ActionListener() {
 
public void actionPerformed(java.awt.event.ActionEvent e) {
boolean b = checkAdrLivraison.isSelected();
componentLivraison.setEditable((!b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
componentLivraison.setCreated(!b);
};
});
 
this.checkAdrFacturation.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean b = checkAdrFacturation.isSelected();
479,9 → 481,6
this.addSQLObject(textInfos, "INFOS");
this.addSQLObject(this.compteSel, "ID_COMPTE_PCE");
 
this.checkAdrFacturation.setSelected(true);
this.checkAdrLivraison.setSelected(true);
 
}
 
private Component createAdressesComponent() {
501,6 → 500,7
this.componentPrincipale.setOpaque(false);
tabbedAdresse.add(getLabelFor("ID_ADRESSE"), this.componentPrincipale);
tabbedAdresse.setOpaque(false);
 
// Adr facturation
JPanel panelFacturation = new JPanel(new GridBagLayout());
panelFacturation.setOpaque(false);
507,15 → 507,30
GridBagConstraints cPanelF = new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 1, 2, 1), 0, 0);
 
this.addView("ID_ADRESSE_F", DEC + ";" + SEP);
 
this.componentFacturation = (ElementSQLObject) this.getView("ID_ADRESSE_F");
this.componentFacturation.setOpaque(false);
this.componentFacturation.setCreatedUIVisible(false);
((AdresseSQLComponent) componentFacturation.getSQLChild()).setDestinataireVisible(true);
 
panelFacturation.add(this.componentFacturation, cPanelF);
 
this.checkAdrFacturation = new JCheckBox("Adresse de facturation identique à la principale");
this.checkAdrFacturation.setOpaque(false);
cPanelF.gridy++;
panelFacturation.add(this.checkAdrFacturation, cPanelF);
tabbedAdresse.add(getLabelFor("ID_ADRESSE_F"), panelFacturation);
 
this.checkAdrFacturation.addActionListener(new ActionListener() {
 
public void actionPerformed(java.awt.event.ActionEvent e) {
boolean b = checkAdrFacturation.isSelected();
 
componentFacturation.setEditable(!b ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
componentFacturation.setCreated(!b);
}
});
checkAdrFacturation.setSelected(true);
 
Set<SQLField> fieldsAdr = getTable().getForeignKeys("ADRESSE");
List<SQLField> fieldsAdrOrder = new ArrayList<SQLField>(fieldsAdr);
Collections.sort(fieldsAdrOrder, new Comparator<SQLField>() {
536,13 → 551,13
GridBagConstraints cPanelL = new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 1, 2, 1), 0, 0);
 
this.addView(fieldName, DEC + ";" + SEP);
this.componentLivraison = (ElementSQLObject) this.getView(fieldName);
this.componentLivraison.setOpaque(false);
this.componentLivraison.setCreatedUIVisible(false);
 
panelLivraison.add(this.componentLivraison, cPanelL);
final ElementSQLObject componentLivraison = (ElementSQLObject) this.getView(fieldName);
componentLivraison.setOpaque(false);
((AdresseSQLComponent) componentLivraison.getSQLChild()).setDestinataireVisible(true);
panelLivraison.add(componentLivraison, cPanelL);
 
checkAdrLivraison = new JCheckBox("Adresse de livraison identique à l'adresse principale");
final JCheckBox checkAdrLivraison = new JCheckBox("Adresse de livraison identique à l'adresse principale");
checkAdrLivraison.setOpaque(false);
cPanelL.gridy++;
panelLivraison.add(checkAdrLivraison, cPanelL);
553,6 → 568,7
 
public void actionPerformed(java.awt.event.ActionEvent e) {
boolean b = checkAdrLivraison.isSelected();
 
componentLivraison.setEditable((!b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
componentLivraison.setCreated(!b);
}
647,7 → 663,21
setCompteVisible(!(boxGestionAutoCompte.isSelected() && getSelectedID() <= 1));
}
});
 
c.gridwidth = 1;
c.gridy++;
c.gridx = 0;
c.weightx = 0;
p.add(new JLabel(getLabelFor("ID_COMPTE_PCE_SERVICE")), c);
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx++;
c.weightx = 1;
ISQLCompteSelector compteSelService = new ISQLCompteSelector();
p.add(compteSelService, c);
this.addView(compteSelService, "ID_COMPTE_PCE_SERVICE");
}
 
return p;
}
 
749,9 → 779,12
public int insert(SQLRow order) {
 
// incrémentation du numéro auto
if (NumerotationAutoSQLElement.getNextNumero(ClientNormalSQLElement.class, new Date()).equalsIgnoreCase(this.textCode.getText().trim())) {
if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()).equalsIgnoreCase(this.textCode.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(this.tableNum);
int val = this.tableNum.getRow(2).getInt("CLIENT_START");
 
final SQLRow rowNumAuto = this.tableNum.getRow(2);
if (rowNumAuto.getObject("CLIENT_START") != null) {
int val = rowNumAuto.getInt("CLIENT_START");
val++;
rowVals.put("CLIENT_START", new Integer(val));
 
761,6 → 794,7
e.printStackTrace();
}
}
}
 
int id = super.insert(order);
 
778,7 → 812,7
SQLRow r;
 
vals.put("MARCHE_PUBLIC", Boolean.TRUE);
vals.put("CODE", NumerotationAutoSQLElement.getNextNumero(ClientNormalSQLElement.class, new Date()));
vals.put("CODE", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
 
// Mode de règlement par defaut
try {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerSQLElement.java
14,11 → 14,13
package org.openconcerto.erp.core.customerrelationship.customer.element;
 
import org.openconcerto.erp.core.edm.AttachmentAction;
import org.openconcerto.erp.core.reports.history.ui.HistoriqueClientFrame;
import org.openconcerto.sql.element.GlobalMapper;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.request.SQLFieldTranslator;
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.light.LightUIElement;
26,8 → 28,11
import org.openconcerto.ui.light.LightUIPanel;
import org.openconcerto.ui.light.SimpleTextLine;
 
import java.awt.event.ActionEvent;
import java.util.List;
 
import javax.swing.AbstractAction;
 
public class CustomerSQLElement extends ClientNormalSQLElement {
 
public CustomerSQLElement() {
40,8 → 45,21
actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionAttachment);
 
PredicateRowAction actionHistory = new PredicateRowAction(new AbstractAction("Historique client") {
 
@Override
public void actionPerformed(ActionEvent e) {
HistoriqueClientFrame histoFrame = new HistoriqueClientFrame();
int idClient = IListe.get(e).getSelectedId();
histoFrame.selectId(idClient);
histoFrame.setVisible(true);
}
}, true);
actionHistory.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionHistory);
 
}
 
@Override
public SQLComponent createComponent() {
final GroupSQLComponent c = new CustomerSQLComponent(this);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientDepartementSQLElement.java
55,6 → 55,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".department";
return this.createCodeOfPackage() + ".department";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/RelanceSQLElement.java
50,7 → 50,7
public class RelanceSQLElement extends ComptaSQLConfElement {
 
public RelanceSQLElement() {
super("RELANCE", "relance client", "relances clients");
super("RELANCE", "une relance client", "relances clients");
}
 
protected List<String> getListFields() {
300,6 → 300,6
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".chaseletter";
return this.createCodeOfPackage() + ".chaseletter";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerSQLComponent.java
159,6 → 159,8
return new SQLSearchableTextCombo(ComboLockedMode.UNLOCKED, 1, 20, false);
} else if (id.equals("SITE_INTERNET")) {
return new TextFieldWithWebBrowsing();
} else if (id.equals("SIRET")) {
return new JTextField(20);
} else if (id.equals("DATE")) {
return new JDate(true);
} else if (id.equals("customerrelationship.customer.contacts")) {
263,7 → 265,7
 
int attempt = 0;
// on verifie qu'un client du meme numero n'a pas été inséré entre temps
if (!this.code.checkValidation(false)) {
if (this.code.getText().trim().length() > 0 && !this.code.checkValidation(false)) {
while (attempt < JUniqueTextField.RETRY_COUNT) {
String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass());
this.code.setText(num);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/NouveauContactAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/NouveauClientAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesDepartementsClientsAction.java
13,32 → 13,12
package org.openconcerto.erp.core.customerrelationship.customer.action;
 
import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.customer.element.ClientDepartementSQLElement;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesDepartementsClientsAction extends CreateListFrameAbstractAction {
 
public ListeDesDepartementsClientsAction() {
super();
this.putValue(Action.NAME, "Liste des services clients");
public class ListeDesDepartementsClientsAction extends CreateIListFrameAbstractAction<ClientDepartementSQLElement> {
public ListeDesDepartementsClientsAction(final ComptaPropsConfiguration conf) {
super(conf, ClientDepartementSQLElement.class);
}
 
@Override
public String getTableName() {
return "CLIENT_DEPARTEMENT";
}
 
public JFrame createFrame() {
SQLElement eltClientDpt = Configuration.getInstance().getDirectory().getElement("CLIENT_DEPARTEMENT");
 
final ListeAddPanel panel = new ListeAddPanel(eltClientDpt);
IListFrame frame = new IListFrame(panel);
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesContactsAction.java
13,29 → 13,14
package org.openconcerto.erp.core.customerrelationship.customer.action;
 
import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.customer.element.ContactSQLElement;
 
import javax.swing.Action;
import javax.swing.JFrame;
public class ListeDesContactsAction extends CreateIListFrameAbstractAction<ContactSQLElement> {
 
public class ListeDesContactsAction extends CreateListFrameAbstractAction {
 
public ListeDesContactsAction() {
super();
this.putValue(Action.NAME, "Liste des contacts");
public ListeDesContactsAction(final ComptaPropsConfiguration conf) {
super(conf, ContactSQLElement.class);
}
 
public JFrame createFrame() {
final ComptaBasePropsConfiguration conf = ((ComptaBasePropsConfiguration) Configuration.getInstance());
return new IListFrame(new ListeAddPanel(conf.getDirectory().getElement("CONTACT")));
}
 
@Override
public String getTableName() {
return "CONTACT";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesClientsAction.java
13,47 → 13,31
package org.openconcerto.erp.core.customerrelationship.customer.action;
 
import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.customer.element.ClientNormalSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.element.CustomerSQLElement;
import org.openconcerto.erp.core.sales.invoice.ui.EcheanceRenderer;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLTable;
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.SQLTableModelSource;
 
import java.util.Set;
 
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTable;
 
public class ListeDesClientsAction extends CreateListFrameAbstractAction {
public class ListeDesClientsAction extends CreateIListFrameAbstractAction<ClientNormalSQLElement> {
 
public ListeDesClientsAction() {
super();
this.putValue(Action.NAME, "Liste des clients");
public ListeDesClientsAction(final ComptaPropsConfiguration conf) {
super(conf, CustomerSQLElement.class);
}
 
@Override
public String getTableName() {
return "CLIENT";
}
protected void initFrame(IListFrame frame) {
super.initFrame(frame);
 
protected SQLTableModelSource getTableSource() {
SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
return Configuration.getInstance().getDirectory().getElement(tableClient).getTableSource(true);
}
SQLTable tableModeReglement = getElem().getDirectory().getElement("MODE_REGLEMENT").getTable();
 
public JFrame createFrame() {
SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
SQLTable tableModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT").getTable();
 
final ListeAddPanel panel = new ListeAddPanel(Configuration.getInstance().getDirectory().getElement(tableClient), new IListe(getTableSource()));
IListFrame frame = new IListFrame(panel);
 
// Renderer
final EcheanceRenderer rend = EcheanceRenderer.getInstance();
JTable jTable = frame.getPanel().getListe().getJTable();
69,8 → 53,7
}
}
 
panel.setSearchFullMode(true);
panel.setSelectRowOnAdd(false);
return frame;
frame.getPanel().setSearchFullMode(true);
frame.getPanel().setSelectRowOnAdd(false);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/action/NouveauCourrierClientAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauAssociationCpteAnalytiqueAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouvelleEcritureAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauClotureManuelleAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauJournalAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauExerciceAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauGestionAnalytiqueAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauComptePCEAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauComptePCGAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauClotureSansAnouveauxAction.java
New file
0,0 → 1,37
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.finance.accounting.ui.ClotureSansAnouveauxPanel;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class NouveauClotureSansAnouveauxAction extends CreateFrameAbstractAction {
 
public NouveauClotureSansAnouveauxAction() {
super();
this.putValue(Action.NAME, "Assistant Clôture2");
}
 
@Override
public JFrame createFrame() {
final PanelFrame panelFrame = new PanelFrame(new ClotureSansAnouveauxPanel(), "Assistant Clôture2");
panelFrame.pack();
panelFrame.setResizable(false);
return panelFrame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/ListeDesEcrituresAction.java
141,67 → 141,26
frame.getPanel().setReloadVisible(true);
frame.getPanel().getListe().setModificationAllowed(false);
 
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu menuDroit = new JPopupMenu();
menuDroit.add(new AbstractAction("Consultation du compte") {
public void actionPerformed(ActionEvent event) {
SQLRowAccessor row = frame.getPanel().getListe().getSelectedRow();
((EcritureSQLElement) element).consultationCompte(ComptePCESQLElement.getRow(row.getString("COMPTE_NUMERO"), row.getString("COMPTE_NOM")));
}
});
menuDroit.add(new AbstractAction("Contrepassation") {
public void actionPerformed(ActionEvent event) {
EcritureSQLElement.contrePassationPiece(frame.getPanel().getListe().getSelectedId());
}
});
// menuDroit.add(new AbstractAction("Valider le mouvement") {
// table.addMouseListener(new MouseAdapter() {
// @Override
// public void mouseReleased(MouseEvent e) {
// if (e.getButton() == MouseEvent.BUTTON3) {
// JPopupMenu menuDroit = new JPopupMenu();
//
// if (e.getModifiersEx() == 128) {
// menuDroit.add(new AbstractAction("Mettre à jour les noms de piéces") {
// public void actionPerformed(ActionEvent event) {
// if (JOptionPane.showConfirmDialog(null, "Etes vous sûr de vouloir valider le
// mouvement?") == JOptionPane.YES_OPTION) {
// EcritureSQLElement.validationEcritures(frame.getPanel().getListe().getSelectedRow().getInt("ID_MOUVEMENT"));
//
// correctNomPiece();
// }
// });
// }
//
// menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
// }
// }
// });
 
menuDroit.add(new AbstractAction("Dupliquer") {
public void actionPerformed(ActionEvent event) {
EcritureSQLElement.dupliquer(frame.getPanel().getListe().fetchSelectedRow());
}
});
 
menuDroit.add(new AbstractAction("Gérer l'analytique") {
public void actionPerformed(ActionEvent event) {
PanelFrame frameAssoc = new PanelFrame(new AssociationAnalytiquePanel(frame.getPanel().getListe().getSelectedRow().asRow()), "Association analytique");
frameAssoc.setVisible(true);
}
});
 
menuDroit.add(new AbstractAction("Voir la source") {
public void actionPerformed(ActionEvent event) {
 
SQLRow row = frame.getPanel().getListe().fetchSelectedRow();
 
MouvementSQLElement.showSource(row.getInt("ID_MOUVEMENT"));
}
});
 
if (e.getModifiersEx() == 128) {
menuDroit.add(new AbstractAction("Mettre à jour les noms de piéces") {
public void actionPerformed(ActionEvent event) {
 
correctNomPiece();
}
});
}
 
menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
}
}
});
 
frame.getPanel().getListe().getModel().invokeLater(new Runnable() {
public void run() {
int rowCount = frame.getPanel().getListe().getModel().getRowCount() - 1;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/ListeDesCategorieComptableAction.java
New file
0,0 → 1,34
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesCategorieComptableAction extends CreateFrameAbstractAction {
 
public ListeDesCategorieComptableAction() {
super();
this.putValue(Action.NAME, "Liste des catégories comptables");
}
 
public JFrame createFrame() {
return new IListFrame(new ListeAddPanel(Configuration.getInstance().getDirectory().getElement("CATEGORIE_COMPTABLE")));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ComptaPrefTreeNode.java
34,6 → 34,7
import org.openconcerto.erp.preferences.MailRelancePreferencePanel;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.erp.preferences.NumerotationPreferencePanel;
import org.openconcerto.erp.preferences.PayPalPreferencePanel;
import org.openconcerto.erp.preferences.PayeGlobalPreferencePanel;
import org.openconcerto.erp.preferences.SauvegardeEnLignePreferencePanel;
import org.openconcerto.erp.preferences.SauvegardeFichierPreferencePanel;
51,7 → 52,7
import javax.swing.tree.DefaultMutableTreeNode;
 
public class ComptaPrefTreeNode extends DefaultMutableTreeNode {
public ComptaPrefTreeNode() {
public ComptaPrefTreeNode(final ModuleManager moduleManager) {
super(" Préférences");
 
// Globale
120,6 → 121,10
nsGlobale.add(new PrefTreeNode(GestionCommercialeGlobalPreferencePanel.class, "Gestion des piéces commericales", new String[] { "transfert", "numéro" }));
nsGlobale.add(new PrefTreeNode(MailRelancePreferencePanel.class, "Email de relance", new String[] { "relance", "mail" }));
 
// PayPal
final PrefTreeNode nPayPall = new PrefTreeNode(PayPalPreferencePanel.class, "PayPal", new String[] { "paypal", "facture" });
nsGlobale.add(nPayPall);
 
// Impression
final PrefTreeNode nPrint = new PrefTreeNode(EmptyPreferencePanel.class, "Impression", new String[] { "Impressions" });
final PrefTreeNode nPrintGestComm = new PrefTreeNode(ImpressionGestCommPreferencePanel.class, "Gestion commerciale", new String[] { "impression" });
157,9 → 162,10
final PrefTreeNode nMail = new PrefTreeNode(EmailNode.class, "EMail", new String[] { "email", "mail", "courriel" });
nsPoste.add(nMail);
 
 
// add preferences for modules
for (final AbstractModule module : ModuleManager.getInstance().getRunningModules().values()) {
for (final Entry<Boolean, List<ModulePreferencePanelDesc>> e : module.getPrefDescriptorsByLocation().entrySet()) {
for (final AbstractModule module : moduleManager.getRunningModules().values()) {
for (final Entry<Boolean, List<ModulePreferencePanelDesc>> e : module.getPrefDescriptorsByLocation(moduleManager.getRoot()).entrySet()) {
final DefaultMutableTreeNode node = e.getKey() ? nsPoste : nsGlobale;
final List<ModulePreferencePanelDesc> descs = e.getValue();
if (descs.size() > 1) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/GestionPlanComptableEFrame.java
152,7 → 152,7
eltComptePCE.archive(id);
} catch (SQLException e) {
e.printStackTrace();
ExceptionHandler.handle("Erreur lors de la suppression du compte.");
ExceptionHandler.handle("Erreur lors de la suppression du compte.", e);
}
System.out.println("Compte Supprimé");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteCloturePreferencePanel.java
23,7 → 23,7
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.request.SQLFieldTranslator;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.preferences.DefaultPreferencePanel;
34,7 → 34,9
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
public class CompteCloturePreferencePanel extends DefaultPreferencePanel {
private ISQLCompteSelector selCompteOuverture, selCompteFermeture, selCompteResultat, selCompteResultatPerte;
136,7 → 138,14
this.rowPrefCompteVals.put("CREATE_NUL_SOLDE_ECR", this.boxCompteSolde.isSelected());
 
try {
final Object[] pb = this.rowPrefCompteVals.getInvalid();
if (pb != null) {
final SQLFieldTranslator trans = Configuration.getInstance().getTranslator();
JOptionPane.showMessageDialog(SwingUtilities.getRoot(this), "Impossible de valider les modifications! Le champ <"
+ trans.getLabelFor(this.rowPrefCompteVals.getTable().getField(pb[0].toString())) + "> pointe sur un compte invalide!(" + pb[1] + ")");
} else {
this.rowPrefCompteVals.update();
}
} catch (SQLException e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/PointagePanel.java
38,6 → 38,7
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.warning.JLabelWarning;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.Color;
import java.awt.Dimension;
74,6 → 75,8
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class PointagePanel extends JPanel {
 
241,6 → 244,7
this.dateDeb.addValueListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
changeListRequest();
PointagePanel.this.model.updateTotauxCompte();
}
});
 
250,6 → 254,7
this.dateFin.addValueListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
changeListRequest();
PointagePanel.this.model.updateTotauxCompte();
}
});
 
288,7 → 293,7
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 4;
c.gridheight = 3;
this.model = new PointageModel(this.selCompte.getSelectedId());
this.model = new PointageModel(this.selCompte.getSelectedId(), this);
JTable table = new JTable(this.model);
table.setRowHeight(FontUtils.getPreferredRowHeight(table));
// AlternateTableCellRenderer.setAllColumns(table);
438,25 → 443,22
}
});
 
// Gestion du code de releve
this.codePointage.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
 
PointagePanel.this.warningPanel.setVisible((PointagePanel.this.codePointage.getText().trim().length() == 0));
PointagePanel.this.buttonPointer.setEnabled((PointagePanel.this.codePointage.getText().trim().length() != 0));
this.ecriturePanel.getListe().addListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
PointagePanel.this.model.updateTotauxCompte();
}
});
 
public void removeUpdate(DocumentEvent e) {
// Gestion du code de releve
this.codePointage.getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
public void update(DocumentEvent e) {
PointagePanel.this.warningPanel.setVisible((PointagePanel.this.codePointage.getText().trim().length() == 0));
PointagePanel.this.buttonPointer.setEnabled((PointagePanel.this.codePointage.getText().trim().length() != 0));
PointagePanel.this.model.updateTotauxCompte();
}
 
public void insertUpdate(DocumentEvent e) {
 
PointagePanel.this.warningPanel.setVisible((PointagePanel.this.codePointage.getText().trim().length() == 0));
PointagePanel.this.buttonPointer.setEnabled((PointagePanel.this.codePointage.getText().trim().length() != 0));
}
});
 
changeListRequest();
502,6 → 504,18
menu.show(mE.getComponent(), mE.getPoint().x, mE.getPoint().y);
}
 
public Date getDateDeb() {
return this.dateDeb.getValue();
}
 
public Date getDateFin() {
return this.dateFin.getDate();
}
 
public String getCodePointage() {
return this.codePointage.getText();
}
 
/* Panel Warning no numero releve */
private void createPanelWarning() {
 
558,6 → 572,10
this.model.updateTotauxCompte();
}
 
public ListPanelEcritures getEcriturePanel() {
return ecriturePanel;
}
 
// Pointe la ligne passée en parametre
private void actionDepointage(int rowIndex) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalPanel.java
13,10 → 13,8
package org.openconcerto.erp.core.finance.accounting.ui;
 
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.sql.Configuration;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
36,6 → 34,8
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
42,7 → 42,6
import java.util.Date;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
49,6 → 48,7
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
81,6 → 81,17
return input;
}
});
this.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0)
if (isDisplayable()) {
listeEcr.addIListeActions(ecrElt.getRowActions());
 
} else {
listeEcr.removeIListeActions(ecrElt.getRowActions());
}
}
});
GridBagConstraints cListe = new DefaultGridBagConstraints();
cListe.fill = GridBagConstraints.BOTH;
cListe.gridwidth = 1;
157,10 → 168,25
 
final JCheckBox boxAutoInsert = new JCheckBox("Insertion automatique");
 
final SaisieJournalItemTable table = new SaisieJournalItemTable(defaultRowVals, boxAutoInsert);
JPanel panelBottom = new JPanel(new GridBagLayout());
GridBagConstraints cB = new DefaultGridBagConstraints();
 
panelBottom.add(new JLabel(TM.tr("accounting.editing.piece.label")), cB);
cB.gridx++;
final JTextField textPiece = new JTextField();
panelBottom.add(textPiece, cB);
 
final SaisieJournalItemTable table = new SaisieJournalItemTable(defaultRowVals, boxAutoInsert, textPiece);
table.setPanel(this);
 
split.setBottomComponent(table);
cB.gridwidth = GridBagConstraints.REMAINDER;
cB.weightx = 1;
cB.weighty = 1;
cB.fill = GridBagConstraints.BOTH;
cB.gridy++;
cB.gridx = 0;
panelBottom.add(table, cB);
split.setBottomComponent(panelBottom);
 
this.add(split, c);
 
201,7 → 227,7
 
@Override
public void actionPerformed(ActionEvent e) {
table.createSaisie(defaultRowVals);
table.createSaisie(defaultRowVals, textPiece);