Dépôt officiel du code source de l'ERP OpenConcerto
/trunk/OpenConcerto/src/META-INF/services/java.nio.file.spi.FileTypeDetector |
---|
New file |
0,0 → 1,0 |
ilm.utils.mime.FreeDesktopMimeDetector |
/trunk/OpenConcerto/src/org/openconcerto/utils/FileUtils.java |
---|
38,6 → 38,7 |
import java.net.URL; |
import java.nio.channels.FileChannel; |
import java.nio.charset.Charset; |
import java.nio.charset.StandardCharsets; |
import java.nio.file.CopyOption; |
import java.nio.file.DirectoryStream; |
import java.nio.file.DirectoryStream.Filter; |
97,6 → 98,9 |
} |
public static void openFile(File f) throws IOException { |
if (!f.exists()) { |
throw new FileNotFoundException(f.getAbsolutePath() + " not found"); |
} |
if (Desktop.isDesktopSupported()) { |
Desktop d = Desktop.getDesktop(); |
if (d.isSupported(Desktop.Action.OPEN)) { |
616,6 → 620,10 |
return readUTF8(new FileInputStream(f)); |
} |
public static final String readUTF8(Path p) throws IOException { |
return new String(Files.readAllBytes(p), StandardCharsets.UTF_8); |
} |
public static final String readUTF8(InputStream ins) throws IOException { |
return read(ins, StringUtils.UTF8); |
} |
900,6 → 908,9 |
* @throws IOException if the file can't be opened. |
*/ |
public static final void open(File f, String[] executables) throws IOException { |
if (!f.exists()) { |
throw new FileNotFoundException(f.getAbsolutePath() + " not found"); |
} |
try { |
openNative(f); |
} catch (IOException exn) { |
/trunk/OpenConcerto/src/org/openconcerto/utils/ProcessStreams.java |
---|
19,6 → 19,7 |
import java.io.InputStreamReader; |
import java.io.OutputStream; |
import java.io.PrintStream; |
import java.lang.ProcessBuilder.Redirect; |
import java.util.concurrent.Callable; |
import java.util.concurrent.CountDownLatch; |
import java.util.concurrent.ExecutorService; |
35,6 → 36,10 |
static public enum Action { |
/** |
* Redirect process streams to ours. |
* |
* @deprecated use {@link ProcessStreams#redirect(ProcessBuilder)} (or |
* {@link Redirect#INHERIT} directly) as it makes sure that |
* {@link Process#waitFor()} only returns once all streams are flushed. |
*/ |
REDIRECT, |
/** |
52,6 → 57,10 |
DO_NOTHING |
} |
static public final ProcessBuilder redirect(final ProcessBuilder pb) throws IOException { |
return pb.redirectErrorStream(true).redirectOutput(Redirect.INHERIT); |
} |
static public final Process handle(final Process p, final Action action) throws IOException { |
if (action == Action.CLOSE) { |
p.getInputStream().close(); |
/trunk/OpenConcerto/src/org/openconcerto/utils/ExceptionHandler.java |
---|
25,6 → 25,7 |
import java.awt.Desktop.Action; |
import java.awt.Dialog; |
import java.awt.Dimension; |
import java.awt.FlowLayout; |
import java.awt.Font; |
import java.awt.Frame; |
import java.awt.GraphicsEnvironment; |
47,8 → 48,10 |
import java.net.URL; |
import java.nio.charset.Charset; |
import java.util.Map; |
import java.util.concurrent.CompletableFuture; |
import java.util.concurrent.Future; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.atomic.AtomicInteger; |
import java.util.logging.Level; |
import java.util.logging.Logger; |
import java.util.regex.Pattern; |
66,7 → 69,6 |
import javax.swing.ScrollPaneConstants; |
import javax.swing.SwingUtilities; |
import javax.swing.UIManager; |
import javax.swing.text.JTextComponent; |
/** |
* Allow to display an exception both on the GUI and on the console. |
81,6 → 83,9 |
private static boolean showProbably = false; |
private static IFactory<String> softwareInfos = null; |
private static ThrowableHandler tHandler = null; |
private static boolean safeToExit = false; |
private static final CompletableFuture<Boolean> FALSE_FUTURE = CompletableFuture.completedFuture(Boolean.FALSE); |
private static final CompletableFuture<Boolean> TRUE_FUTURE = CompletableFuture.completedFuture(Boolean.TRUE); |
public static void setThrowableHandler(ThrowableHandler handler) { |
tHandler = handler; |
90,11 → 95,19 |
forumURL = url; |
} |
public synchronized static void setShowProbably(boolean showProbably) { |
public static void setSafeToExit(boolean b) { |
safeToExit = b; |
} |
public static void setSubmitErrorAutoEnabled(boolean b) { |
submitErrorAuto = b; |
} |
public static synchronized void setShowProbably(boolean showProbably) { |
ExceptionHandler.showProbably = showProbably; |
} |
public synchronized static boolean isShowProbably() { |
public static synchronized boolean isShowProbably() { |
return ExceptionHandler.showProbably; |
} |
120,21 → 133,25 |
* @param comp the modal parent of the error window. |
* @param msg the message to display. |
* @param originalExn the cause, can be <code>null</code>. |
* @return an exception. |
* @return a future completed when the error is handled (e.g. the user clicked on the dialog), |
* <code>false</code> if the error couldn't be displayed to the user. |
*/ |
static public ExceptionHandler handle(Component comp, String msg, Throwable originalExn) { |
static public Future<Boolean> handle(Component comp, String msg, Throwable originalExn) { |
final Future<Boolean> res; |
if (tHandler != null && tHandler.handle(msg, originalExn)) { |
return new ExceptionHandler(msg, originalExn); |
res = TRUE_FUTURE; |
} else { |
res = new ExceptionHandler(comp, msg, originalExn, false).display(); |
} |
return new ExceptionHandler(comp, msg, originalExn, false); |
assert res != null; |
return res; |
} |
static public RuntimeException handle(String msg, Throwable originalExn) { |
static public Future<Boolean> handle(String msg, Throwable originalExn) { |
return handle(null, msg, originalExn); |
} |
static public RuntimeException handle(String msg) { |
static public Future<Boolean> handle(String msg) { |
return handle(msg, null); |
} |
147,7 → 164,9 |
* @return an exception. |
*/ |
static public RuntimeException die(String msg, Throwable originalExn) { |
return new ExceptionHandler(null, msg, originalExn); |
final ExceptionHandler res = new ExceptionHandler(null, msg, originalExn); |
res.display(); |
return res; |
} |
static public RuntimeException die(String msg) { |
160,27 → 179,31 |
// the comp on which to display the popup, may be null |
private final Component comp; |
private final Future<?> future; |
private final boolean quit; |
protected static AtomicInteger openedWindows = new AtomicInteger(0); |
private static boolean forceUI; |
private static boolean submitErrorAuto = false; |
public static void setForceUI(boolean forceUI) { |
ExceptionHandler.forceUI = forceUI; |
} |
private Future<?> display(final boolean error) { |
private Future<Boolean> display() { |
final boolean error = this.quit; |
final String msg = this.getMessage(); |
// write out the message as soon as possible |
getLogger().log(error ? Level.SEVERE : Level.INFO, null, this); |
// then show it to the user |
if (!GraphicsEnvironment.isHeadless() || forceUI) { |
if (openedWindows.get() > 3) { |
return FALSE_FUTURE; |
} |
final FutureTask<Boolean> run = new FutureTask<>(() -> { |
return showMsgHardened(msg, error); |
}); |
if (SwingUtilities.isEventDispatchThread()) { |
showMsgHardened(msg, error); |
run.run(); |
} else { |
final FutureTask<?> run = new FutureTask<Object>(new Runnable() { |
public void run() { |
showMsgHardened(msg, error); |
} |
}, null); |
if (error) { |
try { |
SwingUtilities.invokeAndWait(run); |
191,19 → 214,16 |
} else { |
SwingUtilities.invokeLater(run); |
} |
} |
return run; |
} |
return TRUE_FUTURE; |
} |
return null; |
} |
public final Future<?> getDialogFuture() { |
return this.future; |
} |
protected final void showMsgHardened(final String msg, final boolean error) { |
protected final Boolean showMsgHardened(final String msg, final boolean error) { |
try { |
showMsg(msg, error); |
return Boolean.TRUE; |
} catch (Throwable e) { |
// sometimes the VM cannot display the dialog, in that case don't crash the EDT as the |
// message has already been logged. Further if this class is used in |
217,6 → 237,7 |
// nothing |
} |
} |
return Boolean.FALSE; |
} |
protected final void showMsg(final String msg, final boolean quit) { |
320,62 → 341,6 |
} |
})); |
final javax.swing.Action submitAction = new AbstractAction("Soumettre l'erreur") { |
@Override |
public void actionPerformed(ActionEvent e) { |
submitError(p, textArea); |
} |
private void submitError(final JPanel p, final JTextComponent textArea) { |
final Charset cs = StringUtils.UTF8; |
try { |
ProductInfo productInfo = ProductInfo.getInstance(); |
String name = "", version = ""; |
if (productInfo != null) { |
name = productInfo.getName(); |
version = productInfo.getProperty(ProductInfo.VERSION, version); |
} |
final Map<Info, String> systemInfos = SystemInfo.get(false); |
final String os = systemInfos.remove(Info.OS); |
final String java = systemInfos.toString(); |
final String encodedData = "java=" + PercentEncoder.encode(java, cs) + "&os=" + PercentEncoder.encode(os, cs) + "&software=" + PercentEncoder.encode(name + version, cs) + "&stack=" |
+ PercentEncoder.encode(computeSoftwareInformations() + "\n\n" + textArea.getText(), cs); |
final String request = "http://bugreport.ilm-informatique.fr:5000/bugreport"; |
final URL url = new URL(request); |
final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
connection.setDoOutput(true); |
connection.setRequestMethod("POST"); |
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); |
connection.setRequestProperty("charset", cs.name()); |
final byte[] bytes = encodedData.getBytes(cs); |
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); |
final OutputStream outputStream = connection.getOutputStream(); |
outputStream.write(bytes); |
outputStream.flush(); |
// Get the response |
final StringBuilder answer = new StringBuilder(); |
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
String line; |
while ((line = reader.readLine()) != null) { |
answer.append(line); |
} |
outputStream.close(); |
reader.close(); |
connection.disconnect(); |
JOptionPane.showMessageDialog(p, "Merci d'avoir envoyé le rapport d'erreur au service technique.\nIl sera analysé prochainement."); |
} catch (Exception ex) { |
ex.printStackTrace(); |
} |
} |
}; |
btnPanel.add(new JButton(submitAction)); |
c.fill = GridBagConstraints.NONE; |
c.anchor = GridBagConstraints.EAST; |
p.add(btnPanel, c); |
400,9 → 365,10 |
message = msg + "\n\n" + message; |
} |
message += "\n"; |
message += |
getTrace(); |
message += getTrace(); |
if (submitErrorAuto) { |
submitError(message); |
} |
textArea.setText(message); |
textArea.setEditable(false); |
420,9 → 386,22 |
c.fill = GridBagConstraints.NONE; |
c.weighty = 0; |
c.insets = new Insets(2, 4, 2, 4); |
JPanel closePanel = new JPanel(); |
closePanel.setLayout(new FlowLayout()); |
if (safeToExit) { |
closePanel.add(new JButton(new AbstractAction("Quitter") { |
@Override |
public void actionPerformed(ActionEvent e) { |
System.exit(2); |
} |
})); |
} |
final JButton buttonClose = new JButton("Fermer"); |
p.add(buttonClose, c); |
closePanel.add(buttonClose); |
p.add(closePanel, c); |
final Window window = this.comp == null ? null : SwingUtilities.getWindowAncestor(this.comp); |
final JDialog f; |
if (window instanceof Frame) { |
432,7 → 411,7 |
} |
f.setContentPane(p); |
f.pack(); |
f.setSize(580, 680); |
f.setSize(780, 580); |
f.setMinimumSize(new Dimension(380, 380)); |
f.setLocationRelativeTo(this.comp); |
final ActionListener al = new ActionListener() { |
439,12 → 418,12 |
@Override |
public void actionPerformed(ActionEvent e) { |
openedWindows.decrementAndGet(); |
if (quit) { |
System.exit(1); |
} else { |
f.dispose(); |
} |
} |
}; |
buttonClose.addActionListener(al); |
453,10 → 432,13 |
@Override |
public void windowClosing(WindowEvent e) { |
al.actionPerformed(null); |
} |
}); |
openedWindows.incrementAndGet(); |
f.setVisible(true); |
} |
private String getTrace() { |
485,17 → 467,70 |
private ExceptionHandler(Component comp, String msg, Throwable cause, boolean quit) { |
super(msg, cause); |
this.comp = comp; |
this.future = this.display(quit); |
this.quit = quit; |
} |
public ExceptionHandler(String msg, Throwable cause) { |
super(msg, cause); |
this.comp = null; |
this.future = null; |
private void submitError(String error) { |
final Charset cs = StringUtils.UTF8; |
try { |
ProductInfo productInfo = ProductInfo.getInstance(); |
String name = "", version = ""; |
if (productInfo != null) { |
name = productInfo.getName(); |
version = productInfo.getProperty(ProductInfo.VERSION, version); |
} |
final Map<Info, String> systemInfos = SystemInfo.get(false); |
final String os = systemInfos.remove(Info.OS); |
final String java = systemInfos.toString(); |
final String encodedData = "java=" + PercentEncoder.encode(java, cs) + "&os=" + PercentEncoder.encode(os, cs) + "&software=" + PercentEncoder.encode(name + version, cs) + "&stack=" |
+ PercentEncoder.encode(computeSoftwareInformations() + "\n\n" + error, cs); |
Thread t = new Thread(new Runnable() { |
@Override |
public void run() { |
final String request = "http://bugreport.ilm-informatique.fr:5000/bugreport"; |
try { |
System.err.println("ExceptionHandler.submitError"); |
final URL url = new URL(request); |
final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
connection.setDoOutput(true); |
connection.setRequestMethod("POST"); |
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); |
connection.setRequestProperty("charset", cs.name()); |
final byte[] bytes = encodedData.getBytes(cs); |
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); |
final OutputStream outputStream = connection.getOutputStream(); |
outputStream.write(bytes); |
outputStream.flush(); |
// Get the response |
final StringBuilder answer = new StringBuilder(); |
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
String line; |
while ((line = reader.readLine()) != null) { |
answer.append(line); |
} |
outputStream.close(); |
reader.close(); |
connection.disconnect(); |
} catch (Exception e) { |
e.printStackTrace(); |
} |
} |
}); |
t.start(); |
} catch (Exception ex) { |
ex.printStackTrace(); |
} |
} |
public static void main(String[] args) throws Exception { |
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); |
ExceptionHandler.handle("Fichier de configuration corrompu\n\nmulti\nline", new IllegalStateException("Id manquant")); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/Grammar_es.java |
---|
New file |
0,0 → 1,123 |
/* |
* 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.utils.i18n; |
import java.util.Arrays; |
import java.util.Collection; |
import java.util.Locale; |
import net.jcip.annotations.Immutable; |
@Immutable |
public class Grammar_es extends Grammar { |
static private final Grammar_es INSTANCE = new Grammar_es(); |
public static Grammar_es getInstance() { |
return INSTANCE; |
} |
private Grammar_es() { |
this(Locale.forLanguageTag("es")); |
} |
protected Grammar_es(final Locale l) { |
super(l); |
} |
@Override |
protected Collection<? extends VariantKey> createVariantKeys() { |
return Arrays.asList(SINGULAR, PLURAL, INDEFINITE_ARTICLE_SINGULAR, INDEFINITE_ARTICLE_PLURAL, DEFINITE_ARTICLE_SINGULAR, DEFINITE_ARTICLE_PLURAL, DEMONSTRATIVE_SINGULAR, DEMONSTRATIVE_PLURAL, |
INDEFINITE_NUMERAL, DEFINITE_NUMERAL, DEMONSTRATIVE_NUMERAL, INDEFINITE_ORDINAL, DEFINITE_ORDINAL); |
} |
@Override |
protected Collection<? extends NounClass> createNounClasses() { |
return Arrays.asList(NounClass.FEMININE, NounClass.MASCULINE); |
} |
public final Phrase createPhrase(final String singular) { |
return this.createPhrase(singular, null); |
} |
public final Phrase createPhrase(final String singular, final String plural) { |
final Phrase res = new Phrase(this, singular, null); |
if (plural != null) |
res.putVariant(PLURAL, plural); |
return res; |
} |
@Override |
public String getVariant(Phrase noun, VariantKey key) { |
final String res; |
if (key.equals(SINGULAR)) { |
res = noun.getBase(); |
} else if (key.equals(INDEFINITE_ARTICLE_SINGULAR)) { |
res = (noun.getNounClass() == NounClass.FEMININE ? "una " : "un ") + getSingular(noun); |
} else if (key.equals(DEFINITE_ARTICLE_SINGULAR)) { |
res = getDefiniteArticle(noun) + getSingular(noun); |
} else if (key.equals(DEMONSTRATIVE_SINGULAR)) { |
res = (noun.getNounClass() == NounClass.FEMININE ? "esta " : "este ") + getSingular(noun); |
} else if (key.equals(PLURAL)) { |
res = getPlural(noun.getBase()); |
} else if (key.equals(INDEFINITE_ARTICLE_PLURAL)) { |
res = (noun.getNounClass() == NounClass.FEMININE ? "unas " : "unos ") + getPlural(noun); |
} else if (key.equals(DEFINITE_ARTICLE_PLURAL)) { |
res = (noun.getNounClass() == NounClass.FEMININE ? "las " : "los ") + getPlural(noun); |
} else if (key.equals(DEMONSTRATIVE_PLURAL)) { |
res = (noun.getNounClass() == NounClass.FEMININE ? "estas " : "estos ") + getPlural(noun); |
} else if (key.equals(INDEFINITE_NUMERAL)) { |
res = "{0, plural, =0 {" + getZero(noun) + "} one {# " + getSingular(noun) + "} other {# " + getPlural(noun) + "}}"; |
} else if (key.equals(DEFINITE_NUMERAL)) { |
res = "{0, plural, =0 {" + getZero(noun) + "} one {" + getVariant(noun, DEFINITE_ARTICLE_SINGULAR) + "} other {" + (noun.getNounClass() == NounClass.FEMININE ? "las " : "los ") + " # " |
+ getPlural(noun) + "}}"; |
} else if (key.equals(DEMONSTRATIVE_NUMERAL)) { |
res = "{0, plural, =0 {" + getZero(noun) + "} one {" + getVariant(noun, DEMONSTRATIVE_SINGULAR) + "} other {" + (noun.getNounClass() == NounClass.FEMININE ? "estas " : "estos ") + " # " |
+ getPlural(noun) + "}}"; |
} else if (key.equals(DEFINITE_ORDINAL) || key.equals(INDEFINITE_ORDINAL)) { |
final boolean estFéminin = noun.getNounClass() == NounClass.FEMININE; |
final String article = key.equals(DEFINITE_ORDINAL) ? (estFéminin ? "la " : "el ") : ""; |
res = article + "{0, ordinal, %digits-ordinal" + (estFéminin ? "-feminine" : "") + "} " + getSingular(noun); |
} else { |
res = null; |
} |
return res; |
} |
protected String getZero(Phrase noun) { |
return (noun.getNounClass() == NounClass.MASCULINE ? "ningún " : "ninguna ") + noun.getBase(); |
} |
protected String getDefiniteArticle(Phrase noun) { |
if (noun.getNounClass() == NounClass.MASCULINE || noun.getBase().startsWith("a") || noun.getBase().startsWith("ha")) |
return "el "; |
else |
return "la "; |
} |
protected String getSingular(Phrase noun) { |
final String res = noun.getVariant(SINGULAR); |
return res == null ? noun.getBase() : res; |
} |
protected String getPlural(Phrase noun) { |
final String res = noun.getVariant(PLURAL); |
return res == null ? getPlural(noun.getBase()) : res; |
} |
protected String getPlural(String noun) { |
return noun + 's'; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/Grammar_fr.java |
---|
84,11 → 84,11 |
} else if (key.equals(DEMONSTRATIVE_PLURAL)) { |
res = "ces " + getPlural(noun); |
} else if (key.equals(INDEFINITE_NUMERAL)) { |
res = "{0, plural, =0 {auc" + getVariant(noun, INDEFINITE_ARTICLE_SINGULAR) + "} one {# " + getSingular(noun) + "} other {# " + getPlural(noun) + "}}"; |
res = "{0, plural, =0 {auc" + noun.getVariant(INDEFINITE_ARTICLE_SINGULAR) + "} one {# " + getSingular(noun) + "} other {# " + getPlural(noun) + "}}"; |
} else if (key.equals(DEFINITE_NUMERAL)) { |
res = "{0, plural, =0 {auc" + getVariant(noun, INDEFINITE_ARTICLE_SINGULAR) + "} one {" + getVariant(noun, DEFINITE_ARTICLE_SINGULAR) + "} other {les # " + getPlural(noun) + "}}"; |
res = "{0, plural, =0 {auc" + noun.getVariant(INDEFINITE_ARTICLE_SINGULAR) + "} one {" + noun.getVariant(DEFINITE_ARTICLE_SINGULAR) + "} other {les # " + getPlural(noun) + "}}"; |
} else if (key.equals(DEMONSTRATIVE_NUMERAL)) { |
res = "{0, plural, =0 {auc" + getVariant(noun, INDEFINITE_ARTICLE_SINGULAR) + "} one {" + getVariant(noun, DEMONSTRATIVE_SINGULAR) + "} other {ces # " + getPlural(noun) + "}}"; |
res = "{0, plural, =0 {auc" + noun.getVariant(INDEFINITE_ARTICLE_SINGULAR) + "} one {" + noun.getVariant(DEMONSTRATIVE_SINGULAR) + "} other {ces # " + getPlural(noun) + "}}"; |
} else if (key.equals(DEFINITE_ORDINAL) || key.equals(INDEFINITE_ORDINAL)) { |
final boolean estFéminin = noun.getNounClass() == NounClass.FEMININE; |
final String article = key.equals(DEFINITE_ORDINAL) ? (estFéminin ? "la " : "le ") : ""; |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/translation/messages_en.properties |
---|
7,7 → 7,7 |
memory=memory |
megabytes={0} MB |
processors={0} processor{0,choice,1#|1<s} |
processors={0, plural, one { # processor } other { # processors } } |
os=Operating system |
javaVersion=Version <b>{0}</b> of {1} |
javaHome=installation directory |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/translation/messages_fr.properties |
---|
7,7 → 7,7 |
memory=mémoire |
megabytes={0} Mo |
processors={0} processor{0,choice,1#|1<s} |
processors={0, plural, one { # processeur } other { # processeurs } } |
os=Système d''exploitation |
javaVersion=Version <b>{0}</b> de {1} |
javaHome=dossier d'installation |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/translation/messages_pl.properties |
---|
New file |
0,0 → 1,29 |
true_key=prawdziwe |
false_key=fa\u0142szywy |
yes_key=tak |
no_key=Nie |
linkOpenError=Error while opening {0} |
memory=pami\u0119ci |
megabytes={0} MB |
processors={0, plural, one { # procesora } other { # procesorów } } |
os=Operating system |
javaVersion=Version <b>{0}</b> of {1} |
javaHome=installation directory |
no.laf=No look and feel |
user=u\u017Cytkownika |
home.dir=home directory |
cwd=current directory |
network=Network |
hardwareAddress=adres sprz\u0119towy |
interfaceFullName=full name |
interfaceState=state |
interfaceStateUp=up |
interfaceStateDown=down |
cut=Wytnij |
copy=Kopi\u0119 |
paste=Wklej |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/LocalizedInstances.java |
---|
14,6 → 14,7 |
package org.openconcerto.utils.i18n; |
import org.openconcerto.utils.Log; |
import org.openconcerto.utils.ReflectUtils; |
import org.openconcerto.utils.Tuple2; |
import org.openconcerto.utils.Value; |
88,19 → 89,20 |
// test emptiness to not mix languages |
for (Locale targetLocale = locale; targetLocale != null && l.isEmpty(); targetLocale = this.cntrl.getFallbackLocale(baseName, targetLocale)) { |
localeRes = targetLocale; |
// e.g. "fr_FR", "fr" |
for (final Locale candidate : this.cntrl.getCandidateLocales(baseName, targetLocale)) { |
// e.g. org.acme.MyClass_fr |
final String bundleName = this.cntrl.toBundleName(baseName, candidate); |
// code first |
final Class<?> loadedClass = loadClass(bundleName, cl); |
if (loadedClass != null && this.clazz.isAssignableFrom(loadedClass)) { |
final Class<? extends T> subclazz = loadedClass.asSubclass(this.clazz); |
final Class<? extends T> subclazz = ReflectUtils.getSubclass(bundleName, this.clazz, cl.getClassLoader()); |
if (subclazz != null) { |
try { |
final Value<? extends T> instance = this.getInstance(subclazz); |
if (instance.hasValue()) |
l.add(instance.getValue()); |
else |
Log.get().warning(loadedClass + " exists but the constructor wasn't found"); |
Log.get().warning(subclazz + " exists but the constructor wasn't found"); |
} catch (Exception e) { |
Log.get().log(Level.WARNING, "Couldn't create an instance using " + subclazz, e); |
} |
118,14 → 120,6 |
return Tuple2.create(localeRes, l); |
} |
private final Class<?> loadClass(final String name, final Class<?> cl) { |
try { |
return Class.forName(name, true, cl.getClassLoader()); |
} catch (ClassNotFoundException e) { |
return null; |
} |
} |
/** |
* The no-arg static method to use. |
* |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TM.java |
---|
21,6 → 21,7 |
import java.beans.Introspector; |
import java.io.IOException; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.Collections; |
import java.util.HashMap; |
import java.util.LinkedHashMap; |
28,6 → 29,7 |
import java.util.Locale; |
import java.util.Map; |
import java.util.MissingResourceException; |
import java.util.Objects; |
import java.util.Properties; |
import java.util.regex.Matcher; |
import java.util.regex.Pattern; |
49,9 → 51,37 |
public class TM { |
static public enum MissingMode { |
EXCEPTION, NULL, STRING |
EXCEPTION { |
@Override |
protected String returnMissing(TM tm, String key) throws MissingResourceException { |
throw new MissingResourceException("Missing translation", tm.getBaseName(), key); |
} |
}, |
NULL { |
@Override |
protected String returnMissing(TM tm, String key) { |
return null; |
} |
}, |
STRING { |
@Override |
protected String returnMissing(TM tm, String key) { |
return '!' + key + '!'; |
} |
}; |
protected abstract String returnMissing(final TM tm, final String key) throws MissingResourceException; |
// method to avoid array allocation and Arrays.toString() |
protected final String returnResult(final TM tm, final String res, final String key) throws MissingResourceException { |
return res == null ? this.returnMissing(tm, key) : res; |
} |
protected final String returnResult(final TM tm, final String res, final String... keys) throws MissingResourceException { |
return res == null ? this.returnMissing(tm, Arrays.toString(keys)) : res; |
} |
} |
static public final String NOUN_CLASS_PROP = "nounClass"; |
static { |
assert NOUN_CLASS_PROP.equals(Introspector.decapitalize(NounClass.class.getSimpleName())); |
178,21 → 208,40 |
} |
public final String translate(final MissingMode mode, final String key, final Object... args) throws MissingResourceException { |
return translate(mode, key, new MessageArgs(args)); |
return translate(mode, key, args.length == 0 ? MessageArgs.getEmpty() : new MessageArgs(args)); |
} |
public final String translateFirst(final MissingMode mode, final String... keys) throws MissingResourceException { |
return translateFirst(mode, MessageArgs.getEmpty(), keys); |
} |
/** |
* Return the first non-<code>null</code> result. |
* |
* @param mode what to do if all keys are <code>null</code>. |
* @param args the arguments. |
* @param keys the keys to search for. |
* @return the first non-<code>null</code> result. |
* @throws MissingResourceException if {@link MissingMode#EXCEPTION} and all keys are |
* <code>null</code>. |
*/ |
public final String translateFirst(final MissingMode mode, final MessageArgs args, final String... keys) throws MissingResourceException { |
String res = null; |
for (int i = 0; i < keys.length && res == null; i++) { |
final String key = keys[i]; |
if (key != null) |
res = this.translate(MissingMode.NULL, key, args); |
} |
return mode.returnResult(this, res, keys); |
} |
private final String translate(final MissingMode mode, final String key, MessageArgs args) throws MissingResourceException { |
Objects.requireNonNull(mode, "Null mode"); |
Objects.requireNonNull(key, "Null key"); |
Objects.requireNonNull(args, "Null arguments"); |
final String res = this.translations.translate(key, args); |
if (res == null) { |
if (mode == MissingMode.STRING) |
return '!' + key + '!'; |
else if (mode == MissingMode.NULL) |
return null; |
else |
throw new MissingResourceException("Missing translation", this.getBaseName(), key); |
return mode.returnResult(this, res, key); |
} |
return res; |
} |
protected MessageArgs replaceMap(final MessageArgs args, final String msg) { |
final MessageArgs res; |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/Grammar_pl.java |
---|
New file |
0,0 → 1,55 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.i18n; |
import java.util.Arrays; |
import java.util.Collection; |
import java.util.Locale; |
import net.jcip.annotations.Immutable; |
@Immutable |
public class Grammar_pl extends Grammar { |
static private final Grammar_pl INSTANCE = new Grammar_pl(); |
public static Grammar_pl getInstance() { |
return INSTANCE; |
} |
private Grammar_pl() { |
this(Locale.forLanguageTag("pl")); |
} |
protected Grammar_pl(final Locale l) { |
super(l); |
} |
@Override |
protected Collection<? extends VariantKey> createVariantKeys() { |
return Arrays.asList(SINGULAR, PLURAL, INDEFINITE_ARTICLE_SINGULAR, INDEFINITE_ARTICLE_PLURAL, DEFINITE_ARTICLE_SINGULAR, DEFINITE_ARTICLE_PLURAL, DEMONSTRATIVE_SINGULAR, DEMONSTRATIVE_PLURAL, |
INDEFINITE_NUMERAL, DEFINITE_NUMERAL, DEMONSTRATIVE_NUMERAL, INDEFINITE_ORDINAL, DEFINITE_ORDINAL); |
} |
@Override |
protected Collection<? extends NounClass> createNounClasses() { |
return Arrays.asList(NounClass.FEMININE, NounClass.MASCULINE, NounClass.NEUTER); |
} |
@Override |
public String getVariant(Phrase noun, VariantKey key) { |
// TODO |
return noun.getBase(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/Phrase.java |
---|
18,17 → 18,18 |
import java.util.HashMap; |
import java.util.HashSet; |
import java.util.Map; |
import java.util.Objects; |
import java.util.Set; |
import com.ibm.icu.text.MessageFormat; |
import com.ibm.icu.text.MessagePattern; |
import net.jcip.annotations.GuardedBy; |
import net.jcip.annotations.ThreadSafe; |
import com.ibm.icu.text.MessageFormat; |
import com.ibm.icu.text.MessagePattern; |
/** |
* A phrase and its declension. E.g. "light bulb or electrical outlet" and |
* "light bulbs or electrical outlets". |
* A phrase and its declension. E.g. "light bulb or electrical outlet" and "light bulbs or |
* electrical outlets". |
* |
* @author Sylvain |
* @see <a href="Wikipedia">http://en.wikipedia.org/wiki/Declension</a> |
46,7 → 47,7 |
@GuardedBy("this") |
private final Map<Object, String> variants; |
@GuardedBy("this") |
private final Set<Object> explicitVariants; |
private final Set<VariantKey> explicitVariants; |
public Phrase(Grammar grammar, String base, NounClass nounClass) { |
super(); |
61,7 → 62,7 |
} else { |
this.variants = new HashMap<Object, String>(); |
this.variants.put(null, this.getBase()); |
this.explicitVariants = new HashSet<Object>(); |
this.explicitVariants = new HashSet<>(); |
} |
} |
88,6 → 89,22 |
return this.putVariant(key, variant, true); |
} |
/** |
* Put a variant only if needed, i.e. if {@link #getVariant(VariantKey)} doesn't already return |
* <code>variant</code>. This is useful to keep {@link #getExplicitVariants()} to a minimum. |
* |
* @param key which variant, e.g. plural. |
* @param variant the value, e.g. feet. |
* @return <code>true</code> if the variant was put. |
*/ |
public final synchronized boolean putVariantIfDifferent(final VariantKey key, final String variant) { |
final boolean diff = !variant.equals(this.getVariant(key)); |
if (diff) { |
this.putVariant(key, variant); |
} |
return diff; |
} |
private final synchronized String putVariant(final VariantKey key, final String variant, final boolean explicit) { |
final String res = this.variants.put(key, variant); |
if (explicit) { |
99,6 → 116,16 |
} |
/** |
* The variants that have been explicitly set by {@link #putVariant(VariantKey, String)}, as |
* opposed to variants computed automatically by the {@link #getGrammar() grammar}. |
* |
* @return all explicit variants. |
*/ |
public synchronized Set<VariantKey> getExplicitVariants() { |
return this.explicitVariants == null ? null : new HashSet<>(this.explicitVariants); |
} |
/** |
* Get a variant. If the asked variant wasn't put by {@link #putVariant(VariantKey, String)}, |
* the {@link #getGrammar() grammar} is {@link Grammar#getVariant(Phrase, VariantKey) used}. |
* |
140,6 → 167,31 |
} |
@Override |
public synchronized int hashCode() { |
return Objects.hash(this.base, this.explicitVariants, this.grammar, this.nounClass); |
} |
@Override |
public synchronized boolean equals(Object obj) { |
if (this == obj) |
return true; |
if (obj == null) |
return false; |
if (getClass() != obj.getClass()) |
return false; |
final Phrase o = (Phrase) obj; |
final boolean fast = Objects.equals(this.base, o.base) && Objects.equals(this.explicitVariants, o.explicitVariants) && Objects.equals(this.grammar, o.grammar) |
&& Objects.equals(this.nounClass, o.nounClass); |
if (!fast || this.variants == null) |
return fast; |
for (final VariantKey e : this.explicitVariants) { |
if (!Objects.equals(this.variants.get(e), o.variants.get(e))) |
return false; |
} |
return true; |
} |
@Override |
public String toString() { |
final String cl = this.getNounClass() == null ? " " : " (" + this.getNounClass().getName() + ") "; |
final String gr = this.getGrammar() == null ? "" : " with " + this.getGrammar(); |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/MessageArgs.java |
---|
13,15 → 13,15 |
package org.openconcerto.utils.i18n; |
import java.util.HashMap; |
import java.util.Collections; |
import java.util.LinkedHashMap; |
import java.util.Map; |
import java.util.TreeSet; |
import com.ibm.icu.text.MessageFormat; |
import net.jcip.annotations.ThreadSafe; |
import com.ibm.icu.text.MessageFormat; |
/** |
* {@link MessageFormat} can take numbered or named arguments, this class unifies both. This class |
* is thread safe if the array or map isn't modified. |
33,6 → 33,16 |
return m instanceof LinkedHashMap; |
} |
static private final MessageArgs EMPTY = new MessageArgs(new Object[0]); |
public final static MessageArgs getEmpty() { |
return EMPTY; |
} |
public final static MessageArgs create(final String key, final Object value) { |
return new MessageArgs(Collections.singletonMap(key, value)); |
} |
private final boolean mapPrimary; |
private Object[] array; |
private Map<String, ?> map; |
82,12 → 92,16 |
protected synchronized Map<String, ?> getMap() { |
if (this.map == null) { |
final int stop = this.array.length; |
final Map<String, Object> res = new HashMap<String, Object>(stop); |
if (stop == 0) { |
this.map = Collections.emptyMap(); |
} else { |
final Map<String, Object> res = new LinkedHashMap<>(stop); |
for (int i = 0; i < stop; i++) { |
res.put(String.valueOf(i), this.array[i]); |
} |
this.map = res; |
this.map = Collections.unmodifiableMap(res); |
} |
} |
return this.map; |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/File.java |
---|
New file |
0,0 → 1,35 |
/* |
* 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.utils.mime; |
import java.io.IOException; |
import java.nio.file.Path; |
import java.nio.file.Paths; |
import java.util.Arrays; |
public class File { |
public static void main(String[] args) throws IOException { |
if (args.length == 0) { |
System.out.println(File.class.getName() + " file..."); |
System.out.println("Allow to find the MIME type of files"); |
System.out.println("The '" + FreeDesktopMimeDetector.DEFAULT_MODE + "' property can be set to " + Arrays.asList(FreeDesktopMimeDetector.Mode.values())); |
System.out.println("\tthe default is the first one, see http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html#idm140625828606432"); |
System.exit(1); |
} |
for (final String f : args) { |
final Path p = Paths.get(f); |
System.out.println(f + '\t' + new FreeDesktopMimeDetector().probeContentType(p)); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/FileMagicMimeDetector.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.utils.mime; |
import java.io.IOException; |
import java.nio.file.Path; |
import java.nio.file.spi.FileTypeDetector; |
/** |
* <p> |
* The <a |
* href="http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html" |
* >freedesktop Shared MIME-Info</a> only contains basic magic support. In particular it misses |
* indirect offset and calculations that <a href="http://www.darwinsys.com/file">file</a> supports. |
* For example these features are needed for <a |
* href="https://github.com/file/file/blob/master/magic/Magdir/msooxml">MS OOXML</a>. |
* </p> |
* |
* @see <a href="https://github.com/file/file/blob/master/doc/magic.man">Magic Format</a> |
*/ |
public class FileMagicMimeDetector extends FileTypeDetector { |
@Override |
public String probeContentType(Path path) throws IOException { |
throw new UnsupportedOperationException(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/MimeType.java |
---|
New file |
0,0 → 1,205 |
/* |
* 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. |
*/ |
/* |
* Copyright 2007-2009 Medsea Business Solutions S.L. |
* |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
* in compliance with the License. You may obtain a copy of the License at |
* |
* http://www.apache.org/licenses/LICENSE-2.0 |
* |
* Unless required by applicable law or agreed to in writing, software distributed under the License |
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
* or implied. See the License for the specific language governing permissions and limitations under |
* the License. |
*/ |
package org.openconcerto.utils.mime; |
import java.io.Serializable; |
import java.util.regex.Pattern; |
/** |
* This class represents a simple MimeType object. A mime type is made up of two parts |
* <code><media type>/<sub type></code>. The media type can be something like |
* <code>application</code> or <code>text</code> and the the sub type can be something like |
* <code>xml</code> or <code>plain</code>. |
* |
* Both the media type and sub type can also be the wild card <code>*</code> such as |
* <code>*/*</code> and <code>text/*</code>. Note, if the media type is the wild card then |
* the sub type must also be a wild card. |
* |
* @author Steven McArdle |
* |
*/ |
public class MimeType implements Serializable { |
private static final long serialVersionUID = -1324243127744494894L; |
private static final Pattern mimeSplitter = Pattern.compile("[/;]++"); |
protected String mediaType = "*"; |
protected String subType = "*"; |
// This is a estimate of how specific this mime type is |
private int specificity = 1; |
/** |
* Construct a MimeType from another MimeType instance |
* |
* @param mimeType |
*/ |
public MimeType(final MimeType mimeType) { |
this.mediaType = mimeType.mediaType; |
this.subType = mimeType.subType; |
this.specificity = mimeType.specificity; |
} |
/** |
* Construct a mime type from a String such as <code>text/plain</code>. It tries to ensure that |
* the mime type pattern passed in is correctly formatted. |
* |
* @param mimeType |
* @throws IllegalArgumentException |
*/ |
public MimeType(final String mimeType) throws IllegalArgumentException { |
if (mimeType == null || mimeType.trim().length() == 0) { |
throw new IllegalArgumentException("Invalid MimeType [" + mimeType + "]"); |
} |
String[] parts = mimeSplitter.split(mimeType.trim()); |
if (parts.length > 0) { |
// Treat as the mediaType |
mediaType = getValidMediaType(parts[0]); |
} |
if (parts.length > 1) { |
subType = getValidSubType(parts[1]); |
} |
} |
/** |
* Get the media type part of the mime type. |
* |
* @return media type |
*/ |
public String getMediaType() { |
return mediaType; |
} |
/** |
* Get the sub type of the mime type |
* |
* @return sub type |
*/ |
public String getSubType() { |
return subType; |
} |
/** |
* See if this MimeType is the same as the passed in mime type string |
* |
* @param mimeType as a String |
* @return true if the MimeType passed in has the same media and sub types, else returns false. |
*/ |
private boolean match(final String mimeType) { |
return toString().equals(mimeType); |
} |
/** |
* Get the hashCode of this MimeType. The hashCode is calculate as (31 * mediaType.hashCode()) + |
* subType.hashCode() |
* |
* @return calculated hashCode |
* @see Object#hashCode() |
*/ |
public int hashCode() { |
return (31 * mediaType.hashCode()) + subType.hashCode(); |
} |
/** |
* Overrides the equals method of <code>java.lang.Object</code>. This is able to compare against |
* another MimeType instance or a string representation of a mime type. |
* |
* @return true if the types match else false. |
* @see Object#equals(Object o) |
*/ |
public boolean equals(Object o) { |
if (o instanceof MimeType) { |
if (this.mediaType.equals(((MimeType) o).mediaType) && this.subType.equals(((MimeType) o).subType)) { |
return true; |
} |
} else if (o instanceof String) { |
return match((String) o); |
} |
return false; |
} |
/** |
* Overrides the toString method of <code>java.lang.Object</code>. |
* |
* @return String representation i.e. <code><media type>/<sub type>. |
* @see Object#toString() |
*/ |
public String toString() { |
return mediaType + "/" + subType; |
} |
/** |
* This indicates how specific the mime types is i.e. how good a match the mime type is when |
* returned from the getMimeTypes(...) calls. |
* <p> |
* This is calculated by the number of times this MimeType would be returned if the Collection |
* was not normalised. The higher the count the more MimeDetectors have matched this type. As |
* this can be a false positive for types such as application/octect-stream and text/plain where |
* they would be returned by multiple MimeDetector(s). These types are referred to as root mime |
* types where ALL mime types derive from application/octet-stream and all text/* types derive |
* from text/plan so in these cases we set the specificity to 0 no matter how many times they |
* match. This ensures they are regarded as the least specific in the returned Collection. |
* </p> |
* |
* @return how specific this MimeType is according to the rest of the MimeTypes in a Collection. |
*/ |
public int getSpecificity() { |
return specificity; |
} |
/* |
* Set the value of the specificity. The higher the value the more specific a MimeType is. |
*/ |
void setSpecificity(final int specificity) { |
this.specificity = specificity; |
} |
/* |
* Check the media type at least looks valid. TODO: Enforce more rigorous checking of valid |
* media types. |
*/ |
private String getValidMediaType(final String mediaType) { |
if (mediaType == null || mediaType.trim().length() == 0) { |
return "*"; |
} |
return mediaType; |
} |
/* |
* Check the sub type at least looks valid. TODO: Enforce more rigorous checking of valid sub |
* types. |
*/ |
private String getValidSubType(final String subType) { |
if (subType == null || subType.trim().length() == 0 || "*".equals(mediaType)) { |
// If the mediaType is a wild card then the sub type must also be a wild card |
return "*"; |
} |
return subType; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/mime.cache |
---|
Cannot display: file marked as a binary type. |
svn:mime-type = application/octet-stream |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/mime.cache |
---|
New file |
Property changes: |
Added: svn:mime-type |
+application/octet-stream |
\ No newline at end of property |
/trunk/OpenConcerto/src/org/openconcerto/utils/mime/FreeDesktopMimeDetector.java |
---|
New file |
0,0 → 1,772 |
/* |
* 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.utils.mime; |
/* |
* Copyright 2007-2009 Medsea Business Solutions S.L. |
* |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
* in compliance with the License. You may obtain a copy of the License at |
* |
* http://www.apache.org/licenses/LICENSE-2.0 |
* |
* Unless required by applicable law or agreed to in writing, software distributed under the License |
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
* or implied. See the License for the specific language governing permissions and limitations under |
* the License. |
*/ |
import org.openconcerto.utils.CollectionUtils; |
import org.openconcerto.utils.Log; |
import org.openconcerto.utils.OSFamily; |
import org.openconcerto.utils.StreamUtils; |
import java.io.BufferedInputStream; |
import java.io.ByteArrayOutputStream; |
import java.io.File; |
import java.io.FileInputStream; |
import java.io.IOException; |
import java.io.InputStream; |
import java.net.URL; |
import java.nio.ByteBuffer; |
import java.nio.channels.FileChannel; |
import java.nio.file.Path; |
import java.nio.file.spi.FileTypeDetector; |
import java.util.ArrayList; |
import java.util.Collection; |
import java.util.Collections; |
import java.util.Comparator; |
import java.util.HashSet; |
import java.util.LinkedHashSet; |
import java.util.List; |
import java.util.logging.Level; |
import java.util.regex.Pattern; |
/** |
* <p> |
* The Opendesktop shared mime database contains glob rules and magic number lookup information to |
* enable applications to detect the mime types of files. |
* </p> |
* <p> |
* This class uses the mime.cache file which is one of the files created by the update-mime-database |
* application. This file is a memory mapped file that enables the database to be updated and copied |
* without interrupting applications. |
* </p> |
* <p> |
* This implementation follows the memory mapped spec so it is not required to restart an |
* application using this mime detector should the underlying mime.cache database change. |
* </p> |
* <p> |
* For a complete description of the information contained in this file please see: |
* http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html |
* </p> |
* <p> |
* This class also follows, where possible, the RECOMENDED order of detection as detailed in this |
* spec. Thanks go to Mathias Clasen at Red Hat for pointing me to the original xdgmime |
* implementation http://svn.gnome.org/viewvc/glib/trunk/ |
* gio/xdgmime/xdgmimecache.c?revision=7784&view=markup |
* </p> |
* More up to date : https://github.com/GNOME/beagle/blob/master/beagle/glue/xdgmime/xdgmimecache.c |
* |
* @author Steven McArdle |
* @see <a |
* href="http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html">Shared |
* MIME-Info</a> |
*/ |
@SuppressWarnings({ "unqualified-field-access" }) |
public class FreeDesktopMimeDetector extends FileTypeDetector { |
public static enum Mode { |
/** |
* <a href= |
* "http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html#idm140625828606432" |
* >Recommended checking order</a> |
*/ |
RECOMMENDED, DATA_ONLY, NAME_ONLY |
} |
public static final String DEFAULT_CACHE = "freeDesktop.mime.cache"; |
public static final String DEFAULT_MODE = "freeDesktop.mime.mode"; |
static private Mode getDefaultMode() { |
final String m = System.getProperty(DEFAULT_MODE); |
if (m != null) { |
try { |
return Mode.valueOf(m.toUpperCase()); |
} catch (Exception e) { |
Log.get().log(Level.CONFIG, "Ignoring invalid mode : " + m, e); |
} |
} |
return Mode.RECOMMENDED; |
} |
private static File mimeCacheFile = OSFamily.getInstance() == OSFamily.Windows ? null : new File("/usr/share/mime/mime.cache"); |
static private boolean canReadFile(final File f, final String msg) { |
if (f == null) |
return false; |
final boolean res = f.isFile() && f.canRead(); |
if (!res) |
Log.get().config(msg + f); |
return res; |
} |
static private Object getDefaultCache() { |
final String m = System.getProperty(DEFAULT_CACHE); |
final File f = m != null ? new File(m) : null; |
if (canReadFile(f, "Ignoring invalid passed file : ")) { |
return f; |
} else if (canReadFile(mimeCacheFile, "Ignoring invalid system file : ")) { |
return mimeCacheFile; |
} else { |
final URL res = FreeDesktopMimeDetector.class.getResource("mime.cache"); |
if (res == null) |
throw new IllegalStateException("No mime.cache found for " + FreeDesktopMimeDetector.class); |
return res; |
} |
} |
private final ByteBuffer content; |
private final Mode mode; |
public FreeDesktopMimeDetector() throws IOException { |
this(getDefaultCache(), getDefaultMode()); |
} |
public FreeDesktopMimeDetector(final File mimeCacheFile, final Mode mode) throws IOException { |
this((Object) mimeCacheFile, mode); |
} |
public FreeDesktopMimeDetector(final InputStream is, final Mode mode) throws IOException { |
this((Object) is, mode); |
} |
// InputStream will be closed |
private FreeDesktopMimeDetector(final Object cache, final Mode mode) throws IOException { |
if (cache instanceof File || cache instanceof FileInputStream) { |
// Map the mime.cache file as a memory mapped file |
try (final FileInputStream is = cache instanceof FileInputStream ? (FileInputStream) cache : new FileInputStream((File) cache); final FileChannel rCh = is.getChannel();) { |
content = rCh.map(FileChannel.MapMode.READ_ONLY, 0, rCh.size()); |
} |
} else { |
final ByteArrayOutputStream out = new ByteArrayOutputStream(250 * 1024); |
try (final InputStream is = cache instanceof URL ? ((URL) cache).openStream() : (InputStream) cache) { |
StreamUtils.copy(is, out); |
} |
content = ByteBuffer.wrap(out.toByteArray()); |
} |
this.mode = mode; |
} |
@Override |
public String probeContentType(Path path) throws IOException { |
final Collection<String> col; |
switch (this.mode) { |
case RECOMMENDED: |
col = this.getMimeTypesFile(path.toFile()); |
break; |
case DATA_ONLY: |
try (final InputStream is = new BufferedInputStream(new FileInputStream(path.toFile()))) { |
col = this.getMimeTypesInputStream(is); |
} |
break; |
case NAME_ONLY: |
col = this.getMimeTypesFileName(path.getFileName().toString()); |
break; |
default: |
throw new IllegalStateException("Unknown mode : " + this.mode); |
} |
return CollectionUtils.getFirst(col); |
} |
/** |
* This method resolves mime types closely in accordance with the RECOMENDED order of detection |
* detailed in the Opendesktop shared mime database specification |
* http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html See |
* the Recommended checking order. |
* |
* @param fileName the name to inspect. |
* @return a collection of MIME types. |
*/ |
public Collection<String> getMimeTypesFileName(String fileName) { |
Collection<WeightedMimeType> mimeTypes = new ArrayList<WeightedMimeType>(); |
// Lookup the globbing methods first |
lookupMimeTypesForGlobFileName(fileName, mimeTypes); |
return normalizeWeightedMimeList(mimeTypes); |
} |
/** |
* This method resolves mime types closely in accordance with the RECOMENDED order of detection |
* detailed in the Opendesktop shared mime database specification |
* http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html See |
* the Recommended checking order. |
* |
* @param file the file to inspect. |
* @return a collection of MIME types. |
* @throws IOException if the file couldn't be read. |
*/ |
public Collection<String> getMimeTypesFile(File file) throws IOException { |
Collection<String> mimeTypes = getMimeTypesFileName(file.getName()); |
if (!file.exists()) { |
return mimeTypes; |
} |
try (final InputStream is = new BufferedInputStream(new FileInputStream(file))) { |
return _getMimeTypes(mimeTypes, is); |
} |
} |
/** |
* This method is unable to perform glob matching as no name is available. This means that it |
* does not follow the recommended order of detection defined in the shared mime database spec |
* http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html |
* |
* @param in the stream to inspect.s |
* @return a collection of MIME types. |
* @throws IOException if the stream couldn't be read. |
*/ |
public Collection<String> getMimeTypesInputStream(InputStream in) throws IOException { |
return lookupMimeTypesForMagicData(in); |
} |
/** |
* This method is unable to perform glob matching as no name is available. This means that it |
* does not follow the recommended order of detection defined in the shared mime database spec |
* http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html |
* |
* @param data the data to inspect. |
* @return a collection of MIME types. |
*/ |
public Collection<String> getMimeTypesByteArray(byte[] data) { |
return lookupMagicData(data); |
} |
@Override |
public String toString() { |
return this.getClass().getSimpleName() + " using the mime.cache file version [" + getMajorVersion() + "." + getMinorVersion() + "]."; |
} |
public String dump() { |
return "{MAJOR_VERSION=" + getMajorVersion() + " MINOR_VERSION=" + getMinorVersion() + " ALIAS_LIST_OFFSET=" + getAliasListOffset() + " PARENT_LIST_OFFSET=" + getParentListOffset() |
+ " LITERAL_LIST_OFFSET=" + getLiteralListOffset() + " REVERSE_SUFFIX_TREE_OFFSET=" + getReverseSuffixTreeOffset() + " GLOB_LIST_OFFSET=" + getGlobListOffset() + " MAGIC_LIST_OFFSET=" |
+ getMagicListOffset() + " NAMESPACE_LIST_OFFSET=" + getNameSpaceListOffset() + " ICONS_LIST_OFFSET=" + getIconListOffset() + " GENERIC_ICONS_LIST_OFFSET=" |
+ getGenericIconListOffset() + "}"; |
} |
private Collection<String> lookupMimeTypesForMagicData(InputStream in) throws IOException { |
int offset = 0; |
int len = getMaxExtents(); |
byte[] data = new byte[len]; |
// Mark the input stream |
in.mark(len); |
try { |
// Since an InputStream might return only some data (not all |
// requested), we have to read in a loop until |
// either EOF is reached or the desired number of bytes have been |
// read. |
int restBytesToRead = len; |
while (restBytesToRead > 0) { |
int bytesRead = in.read(data, offset, restBytesToRead); |
if (bytesRead < 0) |
break; // EOF |
offset += bytesRead; |
restBytesToRead -= bytesRead; |
} |
} finally { |
// Reset the input stream to where it was marked. |
in.reset(); |
} |
return lookupMagicData(data); |
} |
private Collection<String> lookupMagicData(byte[] data) { |
Collection<String> mimeTypes = new ArrayList<String>(); |
int listOffset = getMagicListOffset(); |
int numEntries = content.getInt(listOffset); |
int offset = content.getInt(listOffset + 8); |
for (int i = 0; i < numEntries; i++) { |
final int matchOffset = offset + (16 * i); |
final String mimeType = compareToMagicData(matchOffset, data); |
if (mimeType != null) { |
mimeTypes.add(mimeType); |
} else { |
final String nonMatch = getMimeType(content.getInt(matchOffset + 4)); |
mimeTypes.remove(nonMatch); |
} |
} |
return mimeTypes; |
} |
private String compareToMagicData(int offset, byte[] data) { |
// TODO |
// int priority = content.getInt(offset); |
int mimeOffset = content.getInt(offset + 4); |
int numMatches = content.getInt(offset + 8); |
int matchletOffset = content.getInt(offset + 12); |
for (int i = 0; i < numMatches; i++) { |
if (matchletMagicCompare(matchletOffset + (i * 32), data)) { |
return getMimeType(mimeOffset); |
} |
} |
return null; |
} |
private boolean matchletMagicCompare(int offset, byte[] data) { |
int n_children = content.getInt(offset + 24); |
int child_offset = content.getInt(offset + 28); |
if (magic_matchlet_compare_to_data(offset, data)) { |
if (n_children == 0) |
return true; |
for (int i = 0; i < n_children; i++) { |
if (matchletMagicCompare(child_offset + 32 * i, data)) |
return true; |
} |
} |
return false; |
} |
private boolean magic_matchlet_compare_to_data(int offset, byte[] data) { |
int rangeStart = content.getInt(offset); |
int rangeLength = content.getInt(offset + 4); |
int dataLength = content.getInt(offset + 12); |
int dataOffset = content.getInt(offset + 16); |
int maskOffset = content.getInt(offset + 20); |
for (int i = rangeStart; i <= rangeStart + rangeLength; i++) { |
boolean validMatch = true; |
if (i + dataLength > data.length) { |
return false; |
} |
if (maskOffset != 0) { |
for (int j = 0; j < dataLength; j++) { |
if ((content.get(dataOffset + j) & content.get(maskOffset + j)) != (data[j + i] & content.get(maskOffset + j))) { |
validMatch = false; |
break; |
} |
} |
} else { |
for (int j = 0; j < dataLength; j++) { |
if (content.get(dataOffset + j) != data[j + i]) { |
validMatch = false; |
break; |
} |
} |
} |
if (validMatch) { |
return true; |
} |
} |
return false; |
} |
private void lookupGlobLiteral(String fileName, Collection<WeightedMimeType> mimeTypes) { |
int listOffset = getLiteralListOffset(); |
int numEntries = content.getInt(listOffset); |
int min = 0; |
int max = numEntries - 1; |
while (max >= min) { |
int mid = (min + max) / 2; |
String literal = getString(content.getInt((listOffset + 4) + (12 * mid))); |
int cmp = literal.compareTo(fileName); |
if (cmp < 0) { |
min = mid + 1; |
} else if (cmp > 0) { |
max = mid - 1; |
} else { |
String mimeType = getMimeType(content.getInt((listOffset + 4) + (12 * mid) + 4)); |
int weight = content.getInt((listOffset + 4) + (12 * mid) + 8); |
mimeTypes.add(new WeightedMimeType(mimeType, literal, weight)); |
return; |
} |
} |
} |
private void lookupGlobFileNameMatch(String fileName, Collection<WeightedMimeType> mimeTypes) { |
final int listOffset = getGlobListOffset(); |
final int numEntries = content.getInt(listOffset); |
final int entriesOffset = listOffset + 4; |
for (int i = 0; i < numEntries; i++) { |
final int entryOffset = entriesOffset + 12 * 1; |
final int offset = content.getInt(entryOffset); |
final int mimeTypeOffset = content.getInt(entryOffset + 4); |
final int weightNFlags = content.getInt(entryOffset + 8); |
final int weight = weightNFlags & 0xFF; |
final boolean cs = (weightNFlags & 0x100) != 0; |
final Pattern pattern = Pattern.compile(getString(offset, true), !cs ? (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) : 0); |
if (pattern.matcher(fileName).matches()) { |
final String mimeType = getMimeType(mimeTypeOffset); |
final String globPattern = getString(offset, false); |
mimeTypes.add(new WeightedMimeType(mimeType, globPattern, weight)); |
} |
} |
} |
private Collection<String> normalizeWeightedMimeList(Collection<WeightedMimeType> weightedMimeTypes) { |
if (weightedMimeTypes.isEmpty()) |
return Collections.emptySet(); |
Collection<WeightedMimeType> mimeTypes = new LinkedHashSet<WeightedMimeType>(); |
// Sort the weightedMimeTypes |
Collections.sort((List<WeightedMimeType>) weightedMimeTypes, new Comparator<WeightedMimeType>() { |
public int compare(WeightedMimeType obj1, WeightedMimeType obj2) { |
return obj1.weight - obj2.weight; |
} |
}); |
// Keep only globs with the biggest weight. They are in weight order at |
// this point |
int weight = 0; |
int patternLen = 0; |
for (final WeightedMimeType mw : weightedMimeTypes) { |
if (weight < mw.weight) { |
weight = mw.weight; |
} |
if (weight >= mw.weight) { |
if (mw.pattern.length() > patternLen) { |
patternLen = mw.pattern.length(); |
} |
mimeTypes.add(mw); |
} |
} |
// Now keep only the longest patterns |
for (final WeightedMimeType mw : weightedMimeTypes) { |
if (mw.pattern.length() < patternLen) { |
mimeTypes.remove(mw); |
} |
} |
// Could possibly have multiple mimeTypes here with the same weight and |
// pattern length. Can even have multiple entries for the same type so |
// lets remove |
// any duplicates by copying entries to a HashSet that can only have a |
// single instance |
// of each type |
Collection<String> _mimeTypes = new HashSet<String>(); |
for (final WeightedMimeType mw : mimeTypes) { |
_mimeTypes.add(mw.toString()); |
} |
return _mimeTypes; |
} |
private void lookupMimeTypesForGlobFileName(String fileName, Collection<WeightedMimeType> mimeTypes) { |
if (fileName == null) { |
return; |
} |
lookupGlobLiteral(fileName, mimeTypes); |
if (!mimeTypes.isEmpty()) { |
return; |
} |
int len = fileName.length(); |
lookupGlobSuffix(fileName, false, len, mimeTypes); |
if (mimeTypes.isEmpty()) { |
lookupGlobSuffix(fileName, true, len, mimeTypes); |
} |
if (mimeTypes.isEmpty()) { |
lookupGlobFileNameMatch(fileName, mimeTypes); |
} |
} |
private void lookupGlobSuffix(String fileName, boolean ignoreCase, int len, Collection<WeightedMimeType> mimeTypes) { |
int listOffset = getReverseSuffixTreeOffset(); |
int numEntries = content.getInt(listOffset); |
int offset = content.getInt(listOffset + 4); |
lookupGlobNodeSuffix(fileName, numEntries, offset, ignoreCase, len, mimeTypes, new StringBuffer()); |
} |
private void lookupGlobNodeSuffix(final String fileName, final int numEntries, final int offset, final boolean ignoreCase, int len, Collection<WeightedMimeType> mimeTypes, StringBuffer pattern) { |
final char character = ignoreCase ? fileName.toLowerCase().charAt(len - 1) : fileName.charAt(len - 1); |
if (character == 0) { |
return; |
} |
int min = 0; |
int max = numEntries - 1; |
while (max >= min && len >= 0) { |
int mid = (min + max) / 2; |
char matchChar = (char) content.getInt(offset + (12 * mid)); |
if (ignoreCase) |
matchChar = Character.toLowerCase(matchChar); |
if (matchChar < character) { |
min = mid + 1; |
} else if (matchChar > character) { |
max = mid - 1; |
} else { |
len--; |
// first leaf nodes (matchChar==0) then tree nodes |
final int numChildren = content.getInt(offset + (12 * mid) + 4); |
final int firstChildOffset = content.getInt(offset + (12 * mid) + 8); |
if (len > 0) { |
pattern.append(matchChar); |
lookupGlobNodeSuffix(fileName, numChildren, firstChildOffset, ignoreCase, len, mimeTypes, pattern); |
} |
// if the name did not match a longer pattern, try to match this one |
if (mimeTypes.isEmpty()) { |
for (int i = 0; i < numChildren; i++) { |
final int childOffset = firstChildOffset + (12 * i); |
if (content.getInt(childOffset) != 0) { |
// not a leaf node anymore |
break; |
} |
final int mimeOffset = content.getInt(childOffset + 4); |
final int weightNFlags = content.getInt(childOffset + 8); |
final int weight = weightNFlags & 0xFF; |
final boolean cs = (weightNFlags & 0x100) != 0; |
if (!(cs && ignoreCase)) |
mimeTypes.add(new WeightedMimeType(getMimeType(mimeOffset), pattern.toString(), weight)); |
} |
} |
return; |
} |
} |
} |
static class WeightedMimeType extends MimeType { |
private static final long serialVersionUID = 1L; |
String pattern; |
int weight; |
WeightedMimeType(String mimeType, String pattern, int weight) { |
super(mimeType); |
this.pattern = pattern; |
this.weight = weight; |
} |
} |
private int getMaxExtents() { |
return content.getInt(getMagicListOffset() + 4); |
} |
private String aliasLookup(String alias) { |
int aliasListOffset = getAliasListOffset(); |
int min = 0; |
int max = content.getInt(aliasListOffset) - 1; |
while (max >= min) { |
int mid = (min + max) / 2; |
// content.position((aliasListOffset + 4) + (mid * 8)); |
int aliasOffset = content.getInt((aliasListOffset + 4) + (mid * 8)); |
int mimeOffset = content.getInt((aliasListOffset + 4) + (mid * 8) + 4); |
int cmp = getMimeType(aliasOffset).compareTo(alias); |
if (cmp < 0) { |
min = mid + 1; |
} else if (cmp > 0) { |
max = mid - 1; |
} else { |
return getMimeType(mimeOffset); |
} |
} |
return null; |
} |
private String unaliasMimeType(String mimeType) { |
String lookup = aliasLookup(mimeType); |
return lookup == null ? mimeType : lookup; |
} |
private boolean isMimeTypeSubclass(String mimeType, String subClass) { |
String umimeType = unaliasMimeType(mimeType); |
String usubClass = unaliasMimeType(subClass); |
MimeType _mimeType = new MimeType(umimeType); |
MimeType _subClass = new MimeType(usubClass); |
if (umimeType.compareTo(usubClass) == 0) { |
return true; |
} |
if (isSuperType(usubClass) && (_mimeType.getMediaType().equals(_subClass.getMediaType()))) { |
return true; |
} |
// Handle special cases text/plain and application/octet-stream |
if (usubClass.equals("text/plain") && _mimeType.getMediaType().equals("text")) { |
return true; |
} |
if (usubClass.equals("application/octet-stream")) { |
return true; |
} |
int parentListOffset = getParentListOffset(); |
int numParents = content.getInt(parentListOffset); |
int min = 0; |
int max = numParents - 1; |
while (max >= min) { |
int med = (min + max) / 2; |
int offset = content.getInt((parentListOffset + 4) + (8 * med)); |
String parentMime = getMimeType(offset); |
int cmp = parentMime.compareTo(umimeType); |
if (cmp < 0) { |
min = med + 1; |
} else if (cmp > 0) { |
max = med - 1; |
} else { |
offset = content.getInt((parentListOffset + 4) + (8 * med) + 4); |
int _numParents = content.getInt(offset); |
for (int i = 0; i < _numParents; i++) { |
int parentOffset = content.getInt((offset + 4) + (4 * i)); |
if (isMimeTypeSubclass(getMimeType(parentOffset), usubClass)) { |
return true; |
} |
} |
break; |
} |
} |
return false; |
} |
private boolean isSuperType(String mimeType) { |
return mimeType.endsWith("/*"); |
} |
private int getGenericIconListOffset() { |
return content.getInt(36); |
} |
private int getIconListOffset() { |
return content.getInt(32); |
} |
private int getNameSpaceListOffset() { |
return content.getInt(28); |
} |
private int getMagicListOffset() { |
return content.getInt(24); |
} |
private int getGlobListOffset() { |
return content.getInt(20); |
} |
private int getReverseSuffixTreeOffset() { |
return content.getInt(16); |
} |
private int getLiteralListOffset() { |
return content.getInt(12); |
} |
private int getParentListOffset() { |
return content.getInt(8); |
} |
private int getAliasListOffset() { |
return content.getInt(4); |
} |
private short getMinorVersion() { |
return content.getShort(2); |
} |
private short getMajorVersion() { |
return content.getShort(0); |
} |
private String getMimeType(int offset) { |
return getString(offset); |
} |
private String getString(int offset) { |
return getString(offset, false); |
} |
private String getString(int offset, boolean regularExpression) { |
int position = content.position(); |
content.position(offset); |
StringBuffer buf = new StringBuffer(); |
char c = 0; |
while ((c = (char) content.get()) != 0) { |
if (regularExpression) { |
switch (c) { |
case '.': |
buf.append("\\"); |
break; |
case '*': |
case '+': |
case '?': |
buf.append("."); |
} |
} |
buf.append(c); |
} |
// Reset position |
content.position(position); |
if (regularExpression) { |
buf.insert(0, '^'); |
buf.append('$'); |
} |
return buf.toString(); |
} |
private Collection<String> _getMimeTypes(Collection<String> mimeTypes, final InputStream in) throws IOException { |
if (mimeTypes.isEmpty() || mimeTypes.size() > 1) { |
Collection<String> _mimeTypes = getMimeTypesInputStream(in); |
if (!_mimeTypes.isEmpty()) { |
if (!mimeTypes.isEmpty()) { |
// more than one glob matched |
// Check for same mime type |
for (final String mimeType : mimeTypes) { |
if (_mimeTypes.contains(mimeType)) { |
// mimeTypes = new ArrayList(); |
mimeTypes.add(mimeType); |
// return mimeTypes; |
} |
// Check for mime type subtype |
for (final String _mimeType : _mimeTypes) { |
if (isMimeTypeSubclass(mimeType, _mimeType)) { |
// mimeTypes = new ArrayList(); |
mimeTypes.add(mimeType); |
// return mimeTypes; |
} |
} |
} |
} else { |
// No globs matched but we have magic matches |
return _mimeTypes; |
} |
} |
} |
return mimeTypes; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/SleepingQueue.java |
---|
18,6 → 18,7 |
import java.beans.PropertyChangeListener; |
import java.beans.PropertyChangeSupport; |
import java.lang.Thread.UncaughtExceptionHandler; |
import java.util.Collection; |
import java.util.Deque; |
import java.util.concurrent.Callable; |
227,6 → 228,13 |
} |
public final void start() { |
this.start(null); |
} |
public final void start(final IClosure<Thread> customizeThread) { |
customizeThread(this.tasksQueue); |
if (customizeThread != null) |
customizeThread.executeChecked(this.tasksQueue); |
synchronized (this) { |
this.tasksQueue.start(); |
this.setState(RunningState.RUNNING); |
338,14 → 346,25 |
} |
/** |
* An exception was thrown by a task. This implementation merely |
* {@link Exception#printStackTrace()}. |
* An exception was thrown by a task. This implementation uses |
* {@link Thread#getUncaughtExceptionHandler()} or |
* {@link Thread#getDefaultUncaughtExceptionHandler()} if available, otherwise falls back to |
* just {@link Exception#printStackTrace()}. To set the handler, {@link #start(IClosure)} can be |
* used. |
* |
* @param exn the exception thrown. |
*/ |
protected void exceptionThrown(final ExecutionException exn) { |
final Thread thr = this.tasksQueue; |
UncaughtExceptionHandler h = thr.getUncaughtExceptionHandler(); |
if (h == null) |
h = Thread.getDefaultUncaughtExceptionHandler(); |
if (h != null) { |
h.uncaughtException(thr, exn); |
} else { |
exn.printStackTrace(); |
} |
} |
/** |
* Cancel all queued tasks and the current task. |
617,7 → 636,6 |
private final class SingleThreadedExecutor extends DropperQueue<FutureTask<?>> { |
private SingleThreadedExecutor() { |
super(SleepingQueue.this.name + System.currentTimeMillis()); |
customizeThread(this); |
} |
@Override |
/trunk/OpenConcerto/src/org/openconcerto/utils/StreamUtils.java |
---|
13,11 → 13,9 |
package org.openconcerto.utils; |
import java.io.BufferedOutputStream; |
import java.io.BufferedWriter; |
import java.io.ByteArrayOutputStream; |
import java.io.File; |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
24,6 → 22,9 |
import java.io.OutputStreamWriter; |
import java.io.Writer; |
import java.nio.charset.Charset; |
import java.nio.file.Files; |
import java.nio.file.StandardCopyOption; |
import java.util.logging.Level; |
public class StreamUtils { |
48,6 → 49,7 |
* @throws IOException if an error occurs while reading or writing. |
*/ |
public static void copy(InputStream in, OutputStream out) throws IOException { |
// TODO use in.transferTo(out) in Java 9 |
copy(in, out, 512 * 1024); |
} |
56,6 → 58,8 |
} |
public static long copy(InputStream in, OutputStream out, final int bufferSize, final long length) throws IOException { |
if (bufferSize < 1) |
throw new IllegalArgumentException("Buffer size too small : " + bufferSize); |
final byte[] buffer = new byte[bufferSize]; |
long totalCount = 0; |
final boolean copyAll = length < 0; |
62,10 → 66,14 |
while (copyAll || totalCount < length) { |
final long toRead = copyAll ? buffer.length : Math.min(length - totalCount, buffer.length); |
// since buffer.length is an int |
assert 0 <= toRead && toRead <= Integer.MAX_VALUE; |
assert 0 < toRead && toRead <= Integer.MAX_VALUE; |
final int count = in.read(buffer, 0, (int) toRead); |
if (count == -1) |
if (count <= 0) { |
// like Files.copy(InputStream, OutputStream), stop if reading 0 bytes |
if (count == 0) |
Log.get().log(Level.WARNING, "", new IllegalStateException("read() returned 0 for " + in)); |
break; |
} |
totalCount += count; |
out.write(buffer, 0, count); |
} |
75,14 → 83,8 |
} |
public static void copy(InputStream ins, File out) throws IOException { |
// buffered since read() in copy(InputStream, OutputStream) may return 1 byte at a time |
final OutputStream ous = new BufferedOutputStream(new FileOutputStream(out)); |
try { |
copy(ins, ous); |
} finally { |
ous.close(); |
Files.copy(ins, out.toPath(), StandardCopyOption.REPLACE_EXISTING); |
} |
} |
/** |
* Read until the end of the stream is reached. NOTE : since this method didn't create the |
/trunk/OpenConcerto/src/org/openconcerto/utils/ntp/Message.java |
---|
New file |
0,0 → 1,448 |
/* |
* 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.utils.ntp; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
public final class Message { |
/** Maximum message length (in bytes), without authentication */ |
public static final int MAXIMUM_LENGTH = 384; |
/** Leap Indicator. */ |
private byte byLeapIndicator; |
/** Version Number. */ |
private byte byVersionNumber = 0x04; |
/** Client mode. */ |
private byte byMode = 0x03; |
/** Stratum. */ |
private byte byStratum; |
/** Poll Interval. */ |
private byte byPollInterval; |
/** Precision. */ |
private byte byPrecision; |
/** Rood Delay. */ |
private double dRootDelay; |
/** Root Dispersion. */ |
private double dRootDispersion; |
/** Reference Identifier. */ |
private byte[] sReferenceIdentifier = "LOCL".getBytes(); |
/** Reference Timestamp. */ |
private Timestamp tReferenceTimestamp = Timestamp.ZERO; |
/** Originate Timestamp. */ |
private Timestamp tOriginateTimestamp = Timestamp.ZERO; |
/** Receive Timestamp. */ |
private Timestamp tReceiveTimestamp = Timestamp.ZERO; |
/** Transmit Timestamp. */ |
private Timestamp tTransmitTimestamp = Timestamp.ZERO; |
/** |
* Returns the Leap Indicator. |
* |
* @return the Leap Indicator. |
*/ |
public byte getLeapIndicator() { |
return byLeapIndicator; |
} |
/** |
* Sets the Leap Indicator. |
* |
* @param byLeapIndicator the Leap Indicator. |
*/ |
public void setLeapIndicator(final byte byLeapIndicator) { |
this.byLeapIndicator = byLeapIndicator; |
} |
/** |
* Returns the Version Number. |
* |
* @return the Version Number. |
*/ |
public byte getVersionNumber() { |
return byVersionNumber; |
} |
/** |
* Sets the Version Number. |
* |
* @param byVersionNumber the Version Number. |
*/ |
public void setVersionNumber(final byte byVersionNumber) { |
this.byVersionNumber = byVersionNumber; |
} |
/** |
* Returns the Mode. |
* |
* @return the Mode. |
*/ |
public byte getMode() { |
return byMode; |
} |
/** |
* Sets the Mode. |
* |
* @param byMode the Mode. |
*/ |
public void setMode(final byte byMode) { |
this.byMode = byMode; |
} |
/** |
* Returns the Stratum. |
* |
* @return the Stratum. |
*/ |
public byte getStratum() { |
return byStratum; |
} |
/** |
* Sets the Stratum. |
* |
* @param byStratum the Stratum. |
*/ |
public void setStratum(final byte byStratum) { |
this.byStratum = byStratum; |
} |
/** |
* Returns the Poll Interval. |
* |
* @return the Poll Interval. |
*/ |
public byte getPollInterval() { |
return byPollInterval; |
} |
/** |
* Sets the Poll Interval. |
* |
* @param byPollInterval the Poll Interval. |
*/ |
public void setPollInterval(final byte byPollInterval) { |
this.byPollInterval = byPollInterval; |
} |
/** |
* Returns the Precision. |
* |
* @return the Precision. |
*/ |
public byte getPrecision() { |
return byPrecision; |
} |
/** |
* Sets the Precision. |
* |
* @param byPrecision the Precision. |
*/ |
public void setPrecision(final byte byPrecision) { |
this.byPrecision = byPrecision; |
} |
/** |
* Returns the Root Delay. |
* |
* @return the Root Delay. |
*/ |
public double getRootDelay() { |
return dRootDelay; |
} |
/** |
* Sets the Root Delay. |
* |
* @param dRootDelay the Root Delay. |
*/ |
public void setRootDelay(final double dRootDelay) { |
this.dRootDelay = dRootDelay; |
} |
/** |
* Returns the Root Dispersion. |
* |
* @return the Root Dispersion. |
*/ |
public double getRootDispersion() { |
return dRootDispersion; |
} |
/** |
* Sets the Root Dispersion. |
* |
* @param dRootDispersion the Root Dispersion. |
*/ |
public void setRootDispersion(final double dRootDispersion) { |
this.dRootDispersion = dRootDispersion; |
} |
/** |
* Returns the Reference Identifier. |
* |
* @return the Reference Identifier. |
*/ |
public byte[] getReferenceIdentifier() { |
return sReferenceIdentifier; |
} |
/** |
* Sets the Reference Identifier. |
* |
* @param sReferenceIdentifier the Reference Identifier. |
*/ |
public void setReferenceIdentifier(final byte[] sReferenceIdentifier) { |
this.sReferenceIdentifier = sReferenceIdentifier; |
} |
/** |
* Returns the Reference Timestamp. |
* |
* @return the Reference Timestamp. |
*/ |
public Timestamp getReferenceTimestamp() { |
return tReferenceTimestamp; |
} |
/** |
* Sets the Reference Timestamp. |
* |
* @param tReferenceTimestamp the Reference Timestamp. |
*/ |
public void setReferenceTimestamp(final Timestamp tReferenceTimestamp) { |
this.tReferenceTimestamp = tReferenceTimestamp; |
} |
/** |
* Returns the Originate Timestamp. |
* |
* @return the Originate Timestamp. |
*/ |
public Timestamp getOriginateTimestamp() { |
return tOriginateTimestamp; |
} |
/** |
* Sets the Originate Timestamp. |
* |
* @param tOriginateTimestamp the Originate Timestamp. |
*/ |
public void setOriginateTimestamp(final Timestamp tOriginateTimestamp) { |
this.tOriginateTimestamp = tOriginateTimestamp; |
} |
/** |
* Returns the Receive Timestamp. |
* |
* @return the Receive Timestamp. |
*/ |
public Timestamp getReceiveTimestamp() { |
return tReceiveTimestamp; |
} |
/** |
* Sets the Receive Timestamp. |
* |
* @param tReceiveTimestamp the Receive Timestamp. |
*/ |
public void setReceiveTimestamp(final Timestamp tReceiveTimestamp) { |
this.tReceiveTimestamp = tReceiveTimestamp; |
} |
/** |
* Returns the Transmit Timestamp. |
* |
* @return the Transmit Timestamp. |
*/ |
public Timestamp getTransmitTimestamp() { |
return tTransmitTimestamp; |
} |
/** |
* Sets the Transmit Timestamp. |
* |
* @param tTransmitTimestamp the Transmit Timestamp. |
*/ |
public void setTransmitTimestamp(final Timestamp tTransmitTimestamp) { |
this.tTransmitTimestamp = tTransmitTimestamp; |
} |
/** |
* Encodes an SNTP message to a byte stream. |
* |
* @param output the byte stream. |
*/ |
public void encodeMessage(final OutputStream output) throws IOException { |
byte flags = (byte) (this.getLeapIndicator() << 6); |
flags += (byte) (this.getVersionNumber() << 3); |
flags += this.getMode(); |
output.write(flags); |
output.write(this.getStratum()); |
output.write(this.getPollInterval()); |
output.write(this.getPrecision()); |
encodeFixedPoint(this.getRootDelay(), output); |
encodeFixedPoint(this.getRootDispersion(), output); |
encodeBitstring(this.getReferenceIdentifier(), output); |
encodeTimestamp(this.getReferenceTimestamp(), output); |
encodeTimestamp(this.getOriginateTimestamp(), output); |
encodeTimestamp(this.getReceiveTimestamp(), output); |
encodeTimestamp(this.getTransmitTimestamp(), output); |
} |
/** |
* Decodes an SNTP message from a byte stream. |
* |
* @param input the byte stream. |
* @return the message. |
*/ |
public static Message decodeMessage(final InputStream input) throws IOException { |
final Message message = new Message(); |
final byte flags = (byte) input.read(); |
message.setLeapIndicator((byte) (flags >> 6)); |
message.setVersionNumber((byte) ((flags >> 3) & 0x07)); |
message.setMode((byte) (flags & 0x07)); |
message.setStratum((byte) input.read()); |
message.setPollInterval((byte) input.read()); |
message.setPrecision((byte) input.read()); |
message.setRootDelay(decodeFixedPoint(input)); |
message.setRootDispersion(decodeFixedPoint(input)); |
message.setReferenceIdentifier(decodeBitstring(input)); |
message.setReferenceTimestamp(decodeTimestamp(input)); |
message.setOriginateTimestamp(decodeTimestamp(input)); |
message.setReceiveTimestamp(decodeTimestamp(input)); |
message.setTransmitTimestamp(decodeTimestamp(input)); |
return message; |
} |
/** |
* Encodes a 32 bit number to a byte stream. |
* |
* @param number the number to encode. |
* @param output the byte stream. |
* @throws IOException if an error occurs while writting to the stream. |
*/ |
private static void encode32(final long number, final OutputStream output) throws IOException { |
for (int i = 3; i >= 0; i--) { |
output.write((int) ((number >> (8 * i)) & 0xFF)); |
} |
} |
/** |
* Decodes a 32 bit number from a byte stream. |
* |
* @param input the byte stream. |
* @return the decoded number. |
* @throws IOException if an error occurs while reading from the stream. |
*/ |
private static long decode32(final InputStream input) throws IOException { |
long number = 0; |
for (int i = 0; i < 4; i++) { |
number = (number << 8) + input.read(); |
} |
return number; |
} |
/** |
* Encodes a 32-bit bitstring to a byte stream. |
* |
* @param bitstring the bitstring to encode. |
* @param output the byte stream. |
* @throws IOException if an error occurs while writting to the stream. |
*/ |
private static void encodeBitstring(final byte[] bitstring, final OutputStream output) throws IOException { |
final byte[] temp = { 0, 0, 0, 0 }; |
System.arraycopy(bitstring, 0, temp, 0, bitstring.length); |
output.write(temp); |
} |
/** |
* Decodes a 32-bit bitstring from a byte stream. |
* |
* @param input the byte stream. |
* @return the decoded string. |
* @throws IOException if an error occurs while reading from the stream. |
*/ |
private static byte[] decodeBitstring(final InputStream input) throws IOException { |
final byte[] bitstring = new byte[4]; |
input.read(bitstring, 0, 4); |
return bitstring; |
} |
/** |
* Encodes a 32 bit fixed-point number to a byte stream. |
* |
* @param number the fixed-point number to encode. |
* @param output the byte stream. |
* @throws IOException if an error occurs while writting to the stream. |
*/ |
private static void encodeFixedPoint(final double number, final OutputStream output) throws IOException { |
encode32((long) (number * 0x10000L), output); |
} |
/** |
* Decodes a 32 bit fixed-point number from a byte stream. The binary point is between bits 15 |
* and 16. |
* |
* @param input the byte stream. |
* @return the decoded fixed-point number. |
* @throws IOException if an error occurs while reading from the stream. |
*/ |
private static double decodeFixedPoint(final InputStream input) throws IOException { |
return ((double) decode32(input)) / 0x10000L; |
} |
/** |
* Encodes a timestamp to a byte stream. |
* |
* @param timestamp the timestamp to encode. |
* @param output the byte stream. |
* @throws IOException if an error occurs while writting to the stream. |
*/ |
private static void encodeTimestamp(final Timestamp timestamp, final OutputStream output) throws IOException { |
encode32(timestamp.getInteger(), output); |
encode32(timestamp.getFraction(), output); |
} |
/** |
* Decodes a timestamp from a byte stream. |
* |
* @param input the byte stream. |
* @return the decoded timestamp. |
* @throws IOException if an error occurs while reading from the stream. |
*/ |
private static Timestamp decodeTimestamp(final InputStream input) throws IOException { |
final long integer = decode32(input); |
final long fraction = decode32(input); |
return new Timestamp(integer, fraction); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ntp/SNTPClient.java |
---|
New file |
0,0 → 1,116 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.ntp; |
import java.io.ByteArrayInputStream; |
import java.io.ByteArrayOutputStream; |
import java.io.IOException; |
import java.net.DatagramPacket; |
import java.net.DatagramSocket; |
import java.net.InetAddress; |
import java.net.SocketException; |
public class SNTPClient { |
protected final DatagramSocket socket; |
/** |
* The SNTP time is referenced to 01/01/1900-00:00. On the other hand, Unix systems and Java |
* reference time to 01/01/1970-00:00. This means that convertion is necessary. |
*/ |
private static final long SECS_1900_1970 = 2208988800L; |
/** |
* Constructor. |
* |
* @param timeout the response timeout (in milliseconds). |
* @throws IllegalArgumentException if the timeout is invalid. |
* @throws SocketException if an error occurs while creating the socket. |
*/ |
public SNTPClient() throws SocketException { |
this.socket = new DatagramSocket(); |
// 10s timeout |
socket.setSoTimeout(10000); |
} |
/** |
* Retrieves the network time offset from an SNTP server. |
* |
* @param host the server host address (IP or DNS). |
* @param port the server port. |
* @return the network time offset (in milliseconds). |
* |
* @throws IOException if an error occurs while contacting the server. |
*/ |
public long getOffsetInMillis(final String host, final int port) throws IOException { |
final InetAddress addr = InetAddress.getByName(host); |
// Send |
final Message smessage = new Message(); |
smessage.setTransmitTimestamp(toTimestamp(System.currentTimeMillis())); |
final ByteArrayOutputStream output = new ByteArrayOutputStream(); |
smessage.encodeMessage(output); |
final byte[] data = output.toByteArray(); |
output.close(); |
DatagramPacket rpacket = new DatagramPacket(data, data.length, addr, port); |
socket.send(rpacket); |
// Receive |
final DatagramPacket packet = new DatagramPacket(new byte[Message.MAXIMUM_LENGTH], Message.MAXIMUM_LENGTH); |
socket.receive(packet); |
final long destinationTime = System.currentTimeMillis(); |
final Message rmessage = Message.decodeMessage(new ByteArrayInputStream(packet.getData())); |
final long originalTime = fromTimestamp(rmessage.getOriginateTimestamp()); |
final long receiveTime = fromTimestamp(rmessage.getReceiveTimestamp()); |
final long transmitTime = fromTimestamp(rmessage.getTransmitTimestamp()); |
return ((receiveTime - originalTime) + (transmitTime - destinationTime)) / 2; |
} |
public void close() { |
socket.close(); |
} |
/** |
* Converts Java time to an SNTP timestamp. |
* |
* @param time the Java time (in milliseconds). |
* @return the SNTP timestamp. |
*/ |
private static Timestamp toTimestamp(final long time) { |
final double temp = ((double) time) / 1000D; |
final long integer = (long) Math.floor(temp); |
final long fraction = (long) ((temp - (double) integer) * 0x100000000L); |
return new Timestamp(integer + SECS_1900_1970, fraction); |
} |
/** |
* Converts an SNTP timestamp to Java time. |
* |
* @param timestamp the timestamp. |
* @return the Java time (in milliseconds). |
*/ |
private static final long fromTimestamp(final Timestamp timestamp) { |
long time = (timestamp.getInteger() - SECS_1900_1970) * 1000L; |
time += (timestamp.getFraction() * 1000L) / 0x100000000L; |
return time; |
} |
public static void main(String[] args) throws IOException { |
final SNTPClient client = new SNTPClient(); |
final long offset = client.getOffsetInMillis("fr.pool.ntp.org", 123); |
client.close(); |
System.out.println(offset); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ntp/Timestamp.java |
---|
New file |
0,0 → 1,36 |
/* |
* 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.utils.ntp; |
public final class Timestamp { |
public static final Timestamp ZERO = new Timestamp(0, 0); |
private final long integer; |
private final long fraction; |
public Timestamp(final long integer, final long fraction) { |
this.integer = integer; |
this.fraction = fraction; |
} |
public long getInteger() { |
return integer; |
} |
public long getFraction() { |
return fraction; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/TableSorter.java |
---|
37,6 → 37,8 |
import javax.swing.Icon; |
import javax.swing.JLabel; |
import javax.swing.JTable; |
import javax.swing.SwingConstants; |
import javax.swing.SwingUtilities; |
import javax.swing.event.TableModelEvent; |
import javax.swing.event.TableModelListener; |
import javax.swing.table.AbstractTableModel; |
45,6 → 47,8 |
import javax.swing.table.TableColumnModel; |
import javax.swing.table.TableModel; |
import net.jcip.annotations.Immutable; |
/** |
* TableSorter is a decorator for TableModels; adding sorting functionality to a supplied |
* TableModel. TableSorter does not store or copy the data in its TableModel; instead it maintains a |
51,16 → 55,18 |
* map from the row indexes of the view to the row indexes of the model. As requests are made of the |
* sorter (like getValueAt(row, col)) they are passed to the underlying model after the row numbers |
* have been translated via the internal mapping array. This way, the TableSorter appears to hold |
* another copy of the table with the rows in a different order. <p/>TableSorter registers itself as |
* a listener to the underlying model, just as the JTable itself would. Events recieved from the |
* model are examined, sometimes manipulated (typically widened), and then passed on to the |
* TableSorter's listeners (typically the JTable). If a change to the model has invalidated the |
* order of TableSorter's rows, a note of this is made and the sorter will resort the rows the next |
* time a value is requested. <p/>When the tableHeader property is set, either by using the |
* setTableHeader() method or the two argument constructor, the table header may be used as a |
* complete UI for TableSorter. The default renderer of the tableHeader is decorated with a renderer |
* that indicates the sorting status of each column. In addition, a mouse listener is installed with |
* the following behavior: |
* another copy of the table with the rows in a different order. |
* <p/> |
* TableSorter registers itself as a listener to the underlying model, just as the JTable itself |
* would. Events recieved from the model are examined, sometimes manipulated (typically widened), |
* and then passed on to the TableSorter's listeners (typically the JTable). If a change to the |
* model has invalidated the order of TableSorter's rows, a note of this is made and the sorter will |
* resort the rows the next time a value is requested. |
* <p/> |
* When the tableHeader property is set, either by using the setTableHeader() method or the two |
* argument constructor, the table header may be used as a complete UI for TableSorter. The default |
* renderer of the tableHeader is decorated with a renderer that indicates the sorting status of |
* each column. In addition, a mouse listener is installed with the following behavior: |
* <ul> |
* <li>Mouse-click: Clears the sorting status of all other columns and advances the sorting status |
* of that column through three values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to NOT_SORTED |
72,8 → 78,9 |
* column do not cancel the statuses of columns that are already sorting - giving a way to initiate |
* a compound sort. |
* </ul> |
* <p/>This is a long overdue rewrite of a class of the same name that first appeared in the swing |
* table demos in 1997. |
* <p/> |
* This is a long overdue rewrite of a class of the same name that first appeared in the swing table |
* demos in 1997. |
* |
* @author Philip Milne |
* @author Brendon McLean |
92,11 → 99,13 |
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED); |
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() { |
@Override |
public int compare(Object o1, Object o2) { |
return ((Comparable) o1).compareTo(o2); |
} |
}; |
public static final Comparator LEXICAL_COMPARATOR = new Comparator() { |
public static final Comparator<Object> LEXICAL_COMPARATOR = new Comparator<Object>() { |
@Override |
public int compare(Object o1, Object o2) { |
return o1.toString().compareTo(o2.toString()); |
} |
108,8 → 117,8 |
private JTableHeader tableHeader; |
private MouseListener mouseListener; |
private TableModelListener tableModelListener; |
private Map columnComparators = new HashMap(); |
private List sortingColumns = new ArrayList(); |
private Map<Class<?>, Comparator<?>> columnComparators = new HashMap<>(); |
private final List<Directive> sortingColumns = new ArrayList<>(); |
private boolean enabled; |
private boolean sorting; |
144,6 → 153,9 |
} |
public void setTableModel(TableModel tableModel) { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
if (this.tableModel != null) { |
this.tableModel.removeTableModelListener(tableModelListener); |
} |
188,6 → 200,9 |
} |
public void setTableHeader(JTableHeader tableHeader) { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
if (this.tableHeader != null) { |
this.tableHeader.removeMouseListener(mouseListener); |
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer(); |
207,9 → 222,22 |
return sortingColumns.size() != 0; |
} |
public final List<Directive> getSortingColumns() { |
return Collections.unmodifiableList(this.sortingColumns); |
} |
public void setSortingColumns(List<Directive> sortingColumns) { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
this.sortingColumns.clear(); |
this.sortingColumns.addAll(sortingColumns); |
sortingStatusChanged(); |
} |
private Directive getDirective(int column) { |
for (int i = 0; i < sortingColumns.size(); i++) { |
Directive directive = (Directive) sortingColumns.get(i); |
Directive directive = sortingColumns.get(i); |
if (directive.column == column) { |
return directive; |
} |
234,6 → 262,9 |
} |
private synchronized void sortingStatusChanged() { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
this.sortingStatusChanged(true); |
} |
271,7 → 302,7 |
sortingStatusChanged(fire); |
} |
public void setColumnComparator(Class type, Comparator comparator) { |
public void setColumnComparator(Class<?> type, Comparator<?> comparator) { |
if (comparator == null) { |
columnComparators.remove(type); |
} else { |
280,8 → 311,8 |
} |
protected Comparator getComparator(int column) { |
Class columnType = tableModel.getColumnClass(column); |
Comparator comparator = (Comparator) columnComparators.get(columnType); |
Class<?> columnType = tableModel.getColumnClass(column); |
Comparator<?> comparator = columnComparators.get(columnType); |
if (comparator != null) { |
return comparator; |
} |
292,6 → 323,9 |
} |
private Row[] getViewToModel() { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
if (viewToModel == null) { |
int tableModelRowCount = tableModel.getRowCount(); |
viewToModel = new Row[tableModelRowCount]; |
318,6 → 352,9 |
} |
private int[] getModelToView() { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
if (modelToView == null) { |
int n = getViewToModel().length; |
modelToView = new int[n]; |
334,31 → 371,50 |
// TableModel interface methods |
@Override |
public int getRowCount() { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
return (tableModel == null) ? 0 : tableModel.getRowCount(); |
} |
@Override |
public int getColumnCount() { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
return (tableModel == null) ? 0 : tableModel.getColumnCount(); |
} |
@Override |
public String getColumnName(int column) { |
return tableModel.getColumnName(column); |
} |
public Class getColumnClass(int column) { |
@Override |
public Class<?> getColumnClass(int column) { |
return tableModel.getColumnClass(column); |
} |
@Override |
public boolean isCellEditable(int row, int column) { |
return tableModel.isCellEditable(modelIndex(row), column); |
} |
@Override |
public Object getValueAt(int row, int column) { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
return tableModel.getValueAt(modelIndex(row), column); |
} |
@Override |
public void setValueAt(Object aValue, int row, int column) { |
if (!SwingUtilities.isEventDispatchThread()) { |
throw new IllegalStateException("must be called from EDT"); |
} |
tableModel.setValueAt(aValue, modelIndex(row), column); |
} |
376,7 → 432,7 |
// Helper classes |
private class Row implements Comparable { |
private class Row implements Comparable<Row> { |
private int modelIndex; |
public Row(int index) { |
383,12 → 439,13 |
this.modelIndex = index; |
} |
public int compareTo(Object o) { |
@Override |
public int compareTo(Row o) { |
int row1 = modelIndex; |
int row2 = ((Row) o).modelIndex; |
int row2 = o.modelIndex; |
for (Iterator it = sortingColumns.iterator(); it.hasNext();) { |
Directive directive = (Directive) it.next(); |
for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) { |
Directive directive = it.next(); |
int column = directive.column; |
Object o1 = tableModel.getValueAt(row1, column); |
Object o2 = tableModel.getValueAt(row2, column); |
413,6 → 470,7 |
} |
private class TableModelHandler implements TableModelListener { |
@Override |
public void tableChanged(TableModelEvent e) { |
// If we're not sorting by anything, just pass the event along. |
if (!isSorting()) { |
487,6 → 545,7 |
} |
private class MouseHandler extends MouseAdapter { |
@Override |
public void mouseClicked(MouseEvent e) { |
JTableHeader h = (JTableHeader) e.getSource(); |
TableColumnModel columnModel = h.getColumnModel(); |
523,6 → 582,7 |
this.priority = priority; |
} |
@Override |
public void paintIcon(Component c, Graphics g, int x, int y) { |
Color color = c == null ? Color.GRAY : c.getBackground(); |
// In a compound sort, make each succesive triangle 20% |
556,10 → 616,12 |
g.translate(-x, -y); |
} |
@Override |
public int getIconWidth() { |
return size; |
} |
@Override |
public int getIconHeight() { |
return size; |
} |
572,11 → 634,12 |
this.tableCellRenderer = tableCellRenderer; |
} |
@Override |
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { |
Component c = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); |
if (c instanceof JLabel) { |
JLabel l = (JLabel) c; |
l.setHorizontalTextPosition(JLabel.LEFT); |
l.setHorizontalTextPosition(SwingConstants.LEFT); |
int modelColumn = table.convertColumnIndexToModel(column); |
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize())); |
} |
584,13 → 647,27 |
} |
} |
private static class Directive { |
private int column; |
private int direction; |
@Immutable |
public static class Directive { |
private final int column; |
private final int direction; |
public Directive(int column, int direction) { |
this.column = column; |
this.direction = direction; |
} |
public final int getColumn() { |
return this.column; |
} |
public final int getDirection() { |
return this.direction; |
} |
@Override |
public String toString() { |
return this.getClass().getSimpleName() + " " + this.getDirection() + " on column " + this.getColumn(); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/CompareUtils.java |
---|
312,4 → 312,12 |
} |
return null; |
} |
static public final <T extends Comparable<? super T>> T min(final T o1, final T o2) { |
return o1.compareTo(o2) < 0 ? o1 : o2; |
} |
static public final <T extends Comparable<? super T>> T max(final T o1, final T o2) { |
return o1.compareTo(o2) < 0 ? o2 : o1; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ExceptionUtils.java |
---|
81,7 → 81,7 |
} |
static public String getStackTrace(Throwable cause) { |
final StringWriter res = new StringWriter(128); |
final StringWriter res = new StringWriter(8192); |
final PrintWriter pw = new PrintWriter(res); |
try { |
cause.printStackTrace(pw); |
/trunk/OpenConcerto/src/org/openconcerto/utils/ReflectUtils.java |
---|
13,6 → 13,7 |
package org.openconcerto.utils; |
import java.beans.Expression; |
import java.lang.reflect.Array; |
import java.lang.reflect.Constructor; |
import java.lang.reflect.GenericArrayType; |
29,7 → 30,10 |
public final class ReflectUtils { |
/** |
* Find a constructor with compatible parameters. |
* Find a constructor with compatible parameters. NOTE: This follow a simpler algorithm than the |
* one in the JLS (<a href= |
* "https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2.5">15.12.2.5. |
* Choosing the Most Specific Method</a>). |
* |
* @param cls the class to find a constructor for, not <code>null</code>. |
* @param parameterTypes types of parameters the constructor must accept. |
58,6 → 62,35 |
} |
} |
@SuppressWarnings("unchecked") |
static public final <T> T createInstance(final Class<T> clazz, Object... args) throws Exception { |
// too difficult to order superclasses and all implemented interfaces of args in order to |
// find the most specific constructor |
return (T) new Expression(clazz, "new", args).getValue(); |
} |
/** |
* Return the class with the passed name if it is a subclass of <code>clazz</code>. |
* |
* @param name the name of the class, not <code>null</code>. |
* @param clazz the superclass, not <code>null</code>. |
* @return the requested class, <code>null</code> if {@link ClassNotFoundException not found} or |
* not a {@link Class#asSubclass(Class) subclass} of <code>clazz</code>. |
*/ |
static public final <T> Class<? extends T> getSubclass(final String name, final Class<T> clazz) { |
return getSubclass(name, clazz, clazz.getClassLoader()); |
} |
static public final <T> Class<? extends T> getSubclass(final String name, final Class<T> clazz, final ClassLoader cl) { |
final Class<?> res; |
try { |
res = Class.forName(name, true, cl); |
} catch (ClassNotFoundException e) { |
return null; |
} |
return clazz.isAssignableFrom(res) ? res.asSubclass(clazz) : null; |
} |
static private Map<Type, Type> resolveTypes(Class<?> c, Class<?> raw) { |
final Map<Type, Type> res = new HashMap<Type, Type>(); |
if (!raw.isAssignableFrom(c)) |
/trunk/OpenConcerto/src/org/openconcerto/task/element/TaskSQLElementBase.java |
---|
15,8 → 15,6 |
import org.openconcerto.sql.element.ConfSQLElement; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.task.TM; |
import org.openconcerto.utils.i18n.I18nUtils; |
/** |
* @author Sylvain CUAZ |
23,10 → 21,6 |
*/ |
public abstract class TaskSQLElementBase extends ConfSQLElement { |
{ |
this.setL18nPackageName(I18nUtils.getPackageName(TM.class)); |
} |
public TaskSQLElementBase(final String tableName) { |
super(tableName); |
} |
/trunk/OpenConcerto/src/org/openconcerto/task/element/CompanyAccessSQLElement.java |
---|
New file |
0,0 → 1,49 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.task.element; |
import org.openconcerto.sql.element.ConfSQLElement; |
import java.util.ArrayList; |
import java.util.List; |
public class CompanyAccessSQLElement extends ConfSQLElement { |
public CompanyAccessSQLElement() { |
super("ACCES_SOCIETE"); |
} |
@Override |
protected List<String> getListFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("ID_USER_COMMON"); |
l.add("ID_SOCIETE_COMMON"); |
return l; |
} |
@Override |
protected List<String> getComboFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("ID_USER_COMMON"); |
l.add("ID_SOCIETE_COMMON"); |
return l; |
} |
@Override |
protected String createCode() { |
return "common.company-access"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_es.xml |
---|
New file |
0,0 → 1,8 |
<translations> |
<element refid="common.company-access"> |
<FIELD name="USER_COMMON" label="Usario" /> |
<FIELD name="ID_SOCIETE_COMMON" label="Acceso a la sociedad" /> |
</element> |
<element refid="TACHE_COMMON" name="tarea" /> |
<element refid="TACHE_RIGHTS" name="derechos para tareas" namePlural="derechos para tareas" /> |
</translations> |
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_fr.xml |
---|
1,4 → 1,8 |
<translations> |
<element refid="common.company-access"> |
<FIELD name="USER_COMMON" label="Utilisateur" /> |
<FIELD name="ID_SOCIETE_COMMON" label="Accés à la société" /> |
</element> |
<element refid="TACHE_COMMON" nameClass="feminine" name="tâche" /> |
<element refid="TACHE_RIGHTS" nameClass="masculine" name="droit pour les tâches" namePlural="droits pour les tâches" /> |
</translations> |
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_pl.xml |
---|
New file |
0,0 → 1,8 |
<translations> |
<element refid="common.company-access"> |
<FIELD name="USER_COMMON" label="User" /> |
<FIELD name="ID_SOCIETE_COMMON" label="Ustawienia dostępu" /> |
</element> |
<element refid="TACHE_COMMON" name="task" /> |
<element refid="TACHE_RIGHTS" name="right for tasks" namePlural="rights for tasks" /> |
</translations> |
/trunk/OpenConcerto/src/org/openconcerto/task/translation/messages_es.properties |
---|
New file |
0,0 → 1,20 |
summary=Summary : |
todoBefore=Para hacer antes de {date, date, medium} en {date, time, short} por {user} |
todoBefore.col=Hacer antes |
ok=OK |
cancel=Cancelar |
taskToDo=Descripción de la tarea |
assignedTo=Asignado a |
created=Created |
completed=Completado |
deleteForbidden=Solo puedes eliminar tareas que creaste |
assignedBy=Asignado por {user}\nEn {date, date, medium} por {date, time, short} |
delete=Borrar |
deleteSelectedTasks=Borrar {count, plural, =0 {selected tasks} one {the selected task} other {the # selected tasks}} |
addTask=Nueva tarea |
hideHistory= Ocultar historial |
showDetails=Mostrar detalles |
details=Detalles |
markDone=Marca hecha |
moveOneDay=Mover por un día |
showTaskAssignedTo=Mostrar tarea asignada a ... |
/trunk/OpenConcerto/src/org/openconcerto/task/translation/SQLElementNames_en.xml |
---|
1,4 → 1,8 |
<translations> |
<element refid="common.company-access"> |
<FIELD name="USER_COMMON" label="User" /> |
<FIELD name="ID_SOCIETE_COMMON" label="Allowed company access" /> |
</element> |
<element refid="TACHE_COMMON" name="task" /> |
<element refid="TACHE_RIGHTS" name="right for tasks" namePlural="rights for tasks" /> |
</translations> |
/trunk/OpenConcerto/src/org/openconcerto/task/TodoListModel.java |
---|
152,7 → 152,7 |
for (TodoListElement elt : rowsDeleted) { |
int index = this.elements.indexOf(elt); |
if (index >= 0) { |
removeRow(index); |
elements.remove(index); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/task/config/ComptaBasePropsConfiguration.java |
---|
23,10 → 23,12 |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLFilter; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.users.CompanyAccessSQLElement; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.users.UserCommonSQLElement; |
import org.openconcerto.sql.users.rights.RightSQLElement; |
import org.openconcerto.sql.users.rights.UserRightSQLElement; |
import org.openconcerto.task.TM; |
import org.openconcerto.task.element.CompanyAccessSQLElement; |
import org.openconcerto.task.element.TaskRightSQLElement; |
import org.openconcerto.task.element.TaskSQLElement; |
import org.openconcerto.utils.BaseDirs; |
33,6 → 35,8 |
import org.openconcerto.utils.DesktopEnvironment; |
import org.openconcerto.utils.LogUtils; |
import org.openconcerto.utils.ProductInfo; |
import org.openconcerto.utils.i18n.Grammar_fr; |
import org.openconcerto.utils.i18n.NounClass; |
import java.io.File; |
import java.io.FileNotFoundException; |
39,8 → 43,10 |
import java.io.IOException; |
import java.io.InputStream; |
import java.sql.SQLException; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.Collections; |
import java.util.List; |
import java.util.Properties; |
public abstract class ComptaBasePropsConfiguration extends PropsConfiguration { |
125,13 → 131,21 |
} |
@Override |
protected List<String> getMappings() { |
final List<String> res = new ArrayList<>(super.getMappings()); |
final String pkg = "/" + TM.class.getPackage().getName().replace('.', '/'); |
res.add(pkg + "/translation/SQLElementNames"); |
return res; |
} |
@Override |
protected SQLElementDirectory createDirectory() { |
final SQLElementDirectory dir = super.createDirectory(); |
// TACHE_COMMON points to SOCIETE but we never display it we don't need the full element |
dir.addSQLElement(new ConfSQLElement("SOCIETE_COMMON", "une société", "sociétés")); |
dir.addSQLElement(new ConfSQLElement("EXERCICE_COMMON", "un exercice", "exercices")); |
dir.addSQLElement(new ConfSQLElement("ADRESSE_COMMON", "une adresse", "adresses")); |
dir.addSQLElement(new ConfSQLElement("SOCIETE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.FEMININE, "société"))); |
dir.addSQLElement(new ConfSQLElement("EXERCICE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.MASCULINE, "exercice"))); |
dir.addSQLElement(new ConfSQLElement("ADRESSE_COMMON", Grammar_fr.getInstance().createPhrase(NounClass.FEMININE, "adresse"))); |
dir.addSQLElement(new TaskRightSQLElement()); |
dir.addSQLElement(new TaskSQLElement()); |
138,8 → 152,8 |
dir.addSQLElement(new UserCommonSQLElement(getRoot(), false)); |
dir.addSQLElement(new CompanyAccessSQLElement()); |
dir.addSQLElement(UserRightSQLElement.class); |
dir.addSQLElement(RightSQLElement.class); |
dir.addSQLElement(new UserRightSQLElement(getRoot())); |
dir.addSQLElement(new RightSQLElement(getRoot())); |
return dir; |
} |
164,8 → 178,15 |
protected final void setRowSociete(int id) { |
this.idSociete = id; |
this.rowSociete = getSystemRoot().findTable("SOCIETE_COMMON").getValidRow(this.getSocieteID()); |
final SQLTable tableSociete = getSystemRoot().findTable("SOCIETE_COMMON"); |
final SQLRow row = tableSociete.getRow(id); |
if (row == null) { |
throw new IllegalArgumentException("no row for id " + id + " in " + tableSociete); |
} else if (!row.isValid()) { |
throw new IllegalArgumentException("invalid row : " + row); |
} |
this.rowSociete = row; |
} |
public final SQLBase getSQLBaseSociete() { |
return this.getRootSociete().getBase(); |
/trunk/OpenConcerto/src/org/openconcerto/task/ui/UserRightPanelDetail.java |
---|
179,14 → 179,15 |
private void swapOnDoubleClick(final JList list, MouseEvent e, String field) { |
if (e.getClickCount() == 2) { |
int index = list.locationToIndex(e.getPoint()); |
if (index >= 0) { |
ListModel dlm = list.getModel(); |
Object item = dlm.getElementAt(index); |
list.ensureIndexIsVisible(index); |
User toUser = (User) item; |
swapState(selectedUser, toUser, field); |
} |
} |
} |
protected void swapState(User user, User toUser, String field) { |
final SQLSelect sel = new SQLSelect(); |
/trunk/OpenConcerto/src/org/openconcerto/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/mail/action/NouveauCourrierClientAction.java |
---|
File deleted |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/DeviseHistoriqueSQLElement.java |
---|
14,7 → 14,7 |
package org.openconcerto.erp.core.finance.accounting.element; |
import org.openconcerto.erp.core.finance.accounting.component.DeviseHistoriqueSQLComponent; |
import org.openconcerto.sql.element.ConfSQLElement; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.sql.element.GlobalMapper; |
import org.openconcerto.sql.element.SQLComponent; |
21,7 → 21,7 |
import java.util.ArrayList; |
import java.util.List; |
public class DeviseHistoriqueSQLElement extends ConfSQLElement { |
public class DeviseHistoriqueSQLElement extends ComptaSQLConfElement { |
public DeviseHistoriqueSQLElement() { |
super("DEVISE_HISTORIQUE"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/RepartitionAnalytiqueSQLElement.java |
---|
55,6 → 55,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".distribution"; |
return createCodeOfPackage() + ".distribution"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ExerciceCommonSQLElement.java |
---|
13,9 → 13,8 |
package org.openconcerto.erp.core.finance.accounting.element; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.sql.element.BaseSQLComponent; |
import org.openconcerto.sql.element.ConfSQLElement; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLRowValues; |
32,16 → 31,12 |
import javax.swing.JLabel; |
public class ExerciceCommonSQLElement extends ConfSQLElement { |
public class ExerciceCommonSQLElement extends ComptaSQLConfElement { |
public ExerciceCommonSQLElement(DBRoot root) { |
super(root.getTable("EXERCICE_COMMON"), "un excercice", "exercices"); |
super(root.getTable("EXERCICE_COMMON"), "un exercice", "exercices"); |
} |
public ExerciceCommonSQLElement() { |
this(Configuration.getInstance().getRoot()); |
} |
@Override |
public boolean isPrivate() { |
return true; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/FraisDocumentSQLElement.java |
---|
New file |
0,0 → 1,178 |
/* |
* 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.element; |
import org.openconcerto.erp.core.common.ui.DeviseField; |
import org.openconcerto.erp.core.finance.tax.model.TaxeCache; |
import org.openconcerto.sql.element.BaseSQLComponent; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.sqlobject.SQLRequestComboBox; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.utils.GestionDevise; |
import org.openconcerto.utils.ListMap; |
import org.openconcerto.utils.text.SimpleDocumentListener; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
import java.beans.PropertyChangeEvent; |
import java.beans.PropertyChangeListener; |
import java.util.ArrayList; |
import java.util.HashSet; |
import java.util.List; |
import java.util.Set; |
import javax.swing.JLabel; |
import javax.swing.JTextField; |
import javax.swing.event.DocumentEvent; |
import com.ibm.icu.math.BigDecimal; |
public class FraisDocumentSQLElement extends ComptaSQLConfElement { |
public FraisDocumentSQLElement() { |
super("FRAIS_DOCUMENT"); |
} |
protected List<String> getListFields() { |
final List<String> list = new ArrayList<String>(2); |
list.add("CODE"); |
list.add("NOM"); |
list.add("MONTANT_HT"); |
list.add("ID_TAXE"); |
list.add("MONTANT_TTC"); |
return list; |
} |
protected List<String> getComboFields() { |
final List<String> list = new ArrayList<String>(2); |
list.add("CODE"); |
list.add("NOM"); |
list.add("MONTANT_TTC"); |
return list; |
} |
@Override |
public Set<String> getReadOnlyFields() { |
Set<String> s = new HashSet<>(); |
s.add("MONTANT_TTC"); |
return s; |
} |
@Override |
public ListMap<String, String> getShowAs() { |
return ListMap.singleton(null, "CODE", "NOM"); |
} |
public SQLComponent createComponent() { |
return new BaseSQLComponent(this) { |
public void addViews() { |
this.setLayout(new GridBagLayout()); |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
// Code |
final JLabel labelCode = new JLabel(getLabelFor("CODE")); |
c.weightx = 0; |
this.add(labelCode, c); |
c.gridx++; |
c.weightx = 1; |
final JTextField textCode = new JTextField(); |
this.add(textCode, c); |
// Nom |
c.gridx++; |
c.weightx = 0; |
final JLabel labelNom = new JLabel(getLabelFor("NOM")); |
this.add(labelNom, c); |
c.gridx++; |
c.weightx = 1; |
final JTextField textNom = new JTextField(); |
this.add(textNom, c); |
// Montant |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
final JLabel labelTaux = new JLabel(getLabelFor("MONTANT_HT")); |
this.add(labelTaux, c); |
c.gridx++; |
c.weightx = 1; |
final DeviseField textTaux = new DeviseField(); |
this.add(textTaux, c); |
c.gridx++; |
c.weightx = 0; |
final JLabel labelTaxe = new JLabel(getLabelFor("ID_TAXE")); |
this.add(labelTaxe, c); |
c.gridx++; |
c.weightx = 1; |
final SQLRequestComboBox boxTaxe = new SQLRequestComboBox(); |
this.add(boxTaxe, c); |
c.gridx++; |
c.weightx = 0; |
final JLabel labelTTC = new JLabel(getLabelFor("MONTANT_TTC")); |
this.add(labelTTC, c); |
c.gridx++; |
c.weightx = 1; |
final DeviseField textTTC = new DeviseField(); |
textTTC.setEditable(false); |
this.add(textTTC, c); |
this.addRequiredSQLObject(boxTaxe, "ID_TAXE"); |
boxTaxe.addModelListener("wantedID", new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
textTTC.setValue(getMontantTTC(textTaux, boxTaxe)); |
} |
}); |
textTaux.getDocument().addDocumentListener(new SimpleDocumentListener() { |
@Override |
public void update(DocumentEvent e) { |
textTTC.setValue(getMontantTTC(textTaux, boxTaxe)); |
} |
}); |
this.addRequiredSQLObject(textTTC, "MONTANT_TTC"); |
this.addRequiredSQLObject(textTaux, "MONTANT_HT"); |
this.addRequiredSQLObject(textNom, "NOM"); |
this.addRequiredSQLObject(textCode, "CODE"); |
} |
public long getMontantTTC(DeviseField fieldHT, SQLRequestComboBox boxTVA) { |
long l = 0; |
long p = GestionDevise.parseLongCurrency(fieldHT.getText().trim()); |
if (!boxTVA.isEmpty()) { |
Float t = TaxeCache.getCache().getTauxFromId(boxTVA.getWantedID()); |
if (t != null) { |
l = new BigDecimal(p).multiply(new BigDecimal(t).movePointLeft(2).add(BigDecimal.ONE)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); |
} |
} |
return l; |
} |
}; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmSQLElement.java |
---|
51,7 → 51,6 |
import java.util.ArrayList; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashSet; |
import java.util.List; |
import java.util.Set; |
428,6 → 427,11 |
return id; |
} |
@Override |
public Set<String> getPartialResetNames() { |
return null; |
} |
public void loadMouvement(int idMvt) { |
this.tableKm.loadMouvement(idMvt, false); |
} |
483,8 → 487,32 |
List<SQLRow> listEcr = rowSaisieKm.getForeignRow("ID_MOUVEMENT").getReferentRows(ecritureTable); |
// Fix bug sur saisie journal qui ne mettait pas l'id mouvement sur la |
// saisie |
boolean fixMvt = false; |
if (myListKmItem != null && rowSaisieKm.isForeignEmpty("ID_MOUVEMENT")) { |
for (SQLRow rowKmElement : myListKmItem) { |
if (!rowKmElement.isForeignEmpty("ID_ECRITURE")) { |
SQLRow rowEcr = rowKmElement.getForeign("ID_ECRITURE"); |
if (!rowEcr.isForeignEmpty("ID_MOUVEMENT")) { |
rowSaisieKm.createEmptyUpdateRow().put("ID_MOUVEMENT", rowEcr.getForeignID("ID_MOUVEMENT")).commit(); |
rowSaisieKm.fetchValues(); |
listEcr = rowSaisieKm.getForeignRow("ID_MOUVEMENT").getReferentRows(ecritureTable); |
fixMvt = true; |
break; |
} |
} |
} |
} |
if (myListKmItem != null) { |
// Mise à jour du nom de la pièce |
final SQLRow mvt = rowSaisieKm.getForeign("ID_MOUVEMENT"); |
final SQLRow piece = mvt.getForeign("ID_PIECE"); |
String labelSaisie = rowSaisieKm.getString("NOM"); |
piece.createEmptyUpdateRow().put("NOM", (labelSaisie.length() == 0 ? "Saisie au km " : labelSaisie)).commit(); |
// Mise à jour des écritures |
for (SQLRow rowKmElement : myListKmItem) { |
int idCpt = ComptePCESQLElement.getId(rowKmElement.getString("NUMERO"), rowKmElement.getString("NOM")); |
505,9 → 533,13 |
if (tableElt.contains("NOM_PIECE")) { |
vals.put("NOM_PIECE", rowKmElement.getObject("NOM_PIECE")); |
} |
if (rowKmElement.getInt("ID_ECRITURE") > 1) { |
SQLRow rowTmp = ecritureTable.getRow(rowKmElement.getInt("ID_ECRITURE")); |
if (fixMvt) { |
vals.put("ID_MOUVEMENT", rowSaisieKm.getObject("ID_MOUVEMENT")); |
} |
if (!rowTmp.getBoolean("VALIDE")) { |
vals.update(rowKmElement.getInt("ID_ECRITURE")); |
} else { |
672,6 → 704,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".userentry"; |
return createCodeOfPackage() + ".userentry"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/NatureCompteSQLElement.java |
---|
25,7 → 25,7 |
public class NatureCompteSQLElement extends ComptaSQLConfElement { |
public NatureCompteSQLElement() { |
super("NATURE_COMPTE", "Nature du compte", "Nature du compte"); |
super("NATURE_COMPTE", "une nature du compte", "natures du compte"); |
} |
protected List<String> getListFields() { |
55,6 → 55,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".account.kind"; |
return createCodeOfPackage() + ".account.kind"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/RepartitionAnalytiqueElementSQLElement.java |
---|
52,6 → 52,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".distributionitem"; |
return createCodeOfPackage() + ".distributionitem"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AssociationAnalytiqueSQLElement.java |
---|
70,7 → 70,7 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".analytic.relation"; |
return createCodeOfPackage() + ".analytic.relation"; |
} |
@Override |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AxeAnalytiqueSQLElement.java |
---|
53,6 → 53,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".analytic.axis"; |
return createCodeOfPackage() + ".analytic.axis"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/JournalSQLElement.java |
---|
123,6 → 123,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".book"; |
return createCodeOfPackage() + ".book"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AnalytiqueSQLElement.java |
---|
908,6 → 908,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".analytic"; |
return createCodeOfPackage() + ".analytic"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/MouvementSQLElement.java |
---|
232,7 → 232,7 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".entry"; |
return createCodeOfPackage() + ".entry"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCESQLElement.java |
---|
57,6 → 57,7 |
import javax.swing.AbstractAction; |
import javax.swing.JCheckBox; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JTextField; |
import javax.swing.event.DocumentEvent; |
313,11 → 314,8 |
Object obEcriture = base.getDataSource().execute(reqEcriture, new ArrayListHandler()); |
List myListEcriture = (List) obEcriture; |
if (myListEcriture.size() != 0) { |
System.err.println("Impossible de supprimer un compte mouvementé!"); |
ExceptionHandler.handle("", new Exception("Impossible de supprimer un compte mouvementé!")); |
JOptionPane.showMessageDialog(null, "Impossible de supprimer un compte mouvementé!"); |
} else { |
super.archive(new TreesOfSQLRows(this, row), cutLinks); |
} |
437,7 → 435,7 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".code.enterprise"; |
return createCodeOfPackage() + ".code.enterprise"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCGSQLElement.java |
---|
167,6 → 167,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".code.national"; |
return createCodeOfPackage() + ".code.national"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AssociationCompteAnalytiqueSQLElement.java |
---|
153,6 → 153,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".analytic.account.relation"; |
return createCodeOfPackage() + ".analytic.account.relation"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/EcritureSQLElement.java |
---|
18,6 → 18,7 |
import org.openconcerto.erp.core.common.ui.DeviseField; |
import org.openconcerto.erp.core.common.ui.PanelFrame; |
import org.openconcerto.erp.core.edm.AttachmentAction; |
import org.openconcerto.erp.core.finance.accounting.ui.AssociationAnalytiquePanel; |
import org.openconcerto.erp.core.finance.accounting.ui.ConsultationCompteFrame; |
import org.openconcerto.erp.core.finance.accounting.ui.LettrageRenderer; |
import org.openconcerto.erp.core.finance.accounting.ui.ListEcritureRenderer; |
46,6 → 47,7 |
import org.openconcerto.sql.utils.SQLUtils.SQLFactory; |
import org.openconcerto.sql.view.EditFrame; |
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.SQLTableModelColumn; |
91,8 → 93,61 |
PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction("ID_MOUVEMENT").getAction(), true); |
actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(actionAttachment); |
PredicateRowAction consult = new PredicateRowAction(new AbstractAction("Consultation du compte") { |
public void actionPerformed(ActionEvent event) { |
SQLRowAccessor row = IListe.get(event).getSelectedRow(); |
consultationCompte(ComptePCESQLElement.getRow(row.getString("COMPTE_NUMERO"), row.getString("COMPTE_NOM"))); |
} |
}, false); |
consult.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(consult); |
PredicateRowAction contre = new PredicateRowAction(new AbstractAction("Contrepassation") { |
public void actionPerformed(ActionEvent event) { |
EcritureSQLElement.contrePassationPiece(IListe.get(event).getSelectedId()); |
} |
}, false); |
contre.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(contre); |
// menuDroit.add(new AbstractAction("Valider le mouvement") { |
// 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")); |
// } |
// } |
// }); |
PredicateRowAction clone = new PredicateRowAction(new AbstractAction("Dupliquer") { |
public void actionPerformed(ActionEvent event) { |
EcritureSQLElement.dupliquer(IListe.get(event).fetchSelectedRow()); |
} |
}, false); |
clone.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(clone); |
PredicateRowAction an = new PredicateRowAction(new AbstractAction("Gérer l'analytique") { |
public void actionPerformed(ActionEvent event) { |
PanelFrame frameAssoc = new PanelFrame(new AssociationAnalytiquePanel(IListe.get(event).getSelectedRow().asRow()), "Association analytique"); |
frameAssoc.setVisible(true); |
} |
}, false); |
an.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(an); |
PredicateRowAction show = new PredicateRowAction(new AbstractAction("Voir la source") { |
public void actionPerformed(ActionEvent event) { |
SQLRow row = IListe.get(event).fetchSelectedRow(); |
MouvementSQLElement.showSource(row.getInt("ID_MOUVEMENT")); |
} |
}, false); |
show.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(show); |
} |
@Override |
protected String getParentFFName() { |
return "ID_MOUVEMENT"; |
677,7 → 732,7 |
} |
} else { |
ExceptionHandler.handle("Impossible de supprimer le mouvement n°" + rowMvt.getInt("NUMERO") + " car il est validé."); |
JOptionPane.showMessageDialog(null, "Impossible de supprimer le mouvement n°" + rowMvt.getInt("NUMERO") + " car il est validé."); |
} |
} |
760,7 → 815,7 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".entry.item"; |
return createCodeOfPackage() + ".entry.item"; |
} |
public static void dupliquer(SQLRow selectedRow) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ClasseCompteSQLElement.java |
---|
53,6 → 53,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".accountclass"; |
return createCodeOfPackage() + ".accountclass"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/TypeComptePCGSQLElement.java |
---|
51,6 → 51,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".account.type"; |
return createCodeOfPackage() + ".account.type"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmItemSQLElement.java |
---|
64,6 → 64,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".userentry.item"; |
return createCodeOfPackage() + ".userentry.item"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/PieceSQLElement.java |
---|
68,6 → 68,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".piece"; |
return createCodeOfPackage() + ".piece"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/PosteAnalytiqueSQLElement.java |
---|
16,6 → 16,8 |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.sql.element.BaseSQLComponent; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.request.ComboSQLRequest; |
import org.openconcerto.sql.sqlobject.ElementComboBox; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
50,6 → 52,12 |
return list; |
} |
@Override |
protected void _initComboRequest(ComboSQLRequest req) { |
super._initComboRequest(req); |
req.setWhere(new Where(getTable().getField("OBSOLETE"), "=", Boolean.FALSE)); |
} |
public SQLComponent createComponent() { |
return new BaseSQLComponent(this) { |
public void addViews() { |
83,6 → 91,12 |
this.add(box, c); |
this.addRequiredSQLObject(box, "DEFAULT"); |
c.gridx++; |
JCheckBox boxObs = new JCheckBox(getLabelFor("OBSOLETE")); |
c.weightx = 1; |
this.add(boxObs, c); |
this.addRequiredSQLObject(boxObs, "OBSOLETE"); |
} |
}; |
} |
89,6 → 103,6 |
@Override |
protected String createCode() { |
return createCodeFromPackage() + ".analytic.set"; |
return createCodeOfPackage() + ".analytic.set"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/CategorieComptableSQLElement.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.finance.accounting.element; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.erp.model.ISQLCompteSelector; |
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.JPanel; |
import javax.swing.JTextField; |
import javax.swing.SwingConstants; |
public class CategorieComptableSQLElement extends ComptaSQLConfElement { |
public CategorieComptableSQLElement() { |
super("CATEGORIE_COMPTABLE", "une catégorie comptable", "catégories comptable"); |
} |
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() { |
ListMap<String, String> map = new ListMap<String, String>(); |
map.add(null, "NOM"); |
return map; |
} |
public SQLComponent createComponent() { |
return new BaseSQLComponent(this) { |
@Override |
protected void addViews() { |
this.setLayout(new GridBagLayout()); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
JLabel labelNom = new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT); |
this.add(labelNom, c); |
c.gridx++; |
c.weightx = 1; |
c.fill = GridBagConstraints.NONE; |
JTextField fieldNom = new JTextField(40); |
DefaultGridBagConstraints.lockMinimumSize(fieldNom); |
this.add(fieldNom, c); |
JLabel labelTaxe = new JLabel(getLabelFor("ID_TAXE_VENTE"), SwingConstants.RIGHT); |
c.fill = GridBagConstraints.HORIZONTAL; |
c.gridx = 0; |
c.gridy++; |
this.add(labelTaxe, c); |
c.gridx++; |
c.weightx = 1; |
c.gridwidth = GridBagConstraints.REMAINDER; |
ISQLCompteSelector compteTaxe = new ISQLCompteSelector(); |
this.add(compteTaxe, c); |
JLabel labelCompteVt = new JLabel(getLabelFor("ID_COMPTE_PCE_VENTE"), SwingConstants.RIGHT); |
c.gridx = 0; |
c.gridy++; |
c.weightx = 0; |
c.gridwidth = 1; |
c.fill = GridBagConstraints.HORIZONTAL; |
this.add(labelCompteVt, c); |
c.gridx++; |
c.weightx = 1; |
c.gridwidth = GridBagConstraints.REMAINDER; |
ISQLCompteSelector compteVt = new ISQLCompteSelector(); |
this.add(compteVt, c); |
JLabel labelCompteAchat = new JLabel(getLabelFor("ID_COMPTE_PCE_ACHAT"), SwingConstants.RIGHT); |
c.fill = GridBagConstraints.HORIZONTAL; |
c.gridwidth = 1; |
c.gridx = 0; |
c.gridy++; |
this.add(labelCompteAchat, c); |
c.gridx++; |
c.weightx = 1; |
c.gridwidth = GridBagConstraints.REMAINDER; |
ISQLCompteSelector compteAchat = new ISQLCompteSelector(); |
this.add(compteAchat, c); |
JLabel labelTaxeAchat = new JLabel(getLabelFor("ID_TAXE_ACHAT"), SwingConstants.RIGHT); |
c.fill = GridBagConstraints.HORIZONTAL; |
c.gridwidth = 1; |
c.gridx = 0; |
c.gridy++; |
this.add(labelTaxeAchat, c); |
c.gridx++; |
c.weightx = 1; |
c.gridwidth = GridBagConstraints.REMAINDER; |
ISQLCompteSelector compteTaxeAchat = new ISQLCompteSelector(); |
this.add(compteTaxeAchat, c); |
// Spacer |
c.gridy++; |
c.weighty = 1; |
c.anchor = GridBagConstraints.NORTHWEST; |
this.add(new JPanel(), c); |
this.addSQLObject(compteAchat, "ID_COMPTE_PCE_ACHAT"); |
this.addSQLObject(compteVt, "ID_COMPTE_PCE_VENTE"); |
this.addSQLObject(compteTaxe, "ID_TAXE_VENTE"); |
this.addSQLObject(compteTaxeAchat, "ID_TAXE_ACHAT"); |
this.addRequiredSQLObject(fieldNom, "NOM"); |
} |
}; |
} |
@Override |
protected String createCode() { |
return "finance.accounting.category"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator.java |
---|
14,20 → 14,19 |
package org.openconcerto.erp.core.finance.accounting.report; |
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic; |
import org.openconcerto.utils.ExceptionHandler; |
import java.awt.Color; |
import java.awt.Desktop; |
import java.io.File; |
import java.io.FileNotFoundException; |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.util.Calendar; |
import java.util.HashMap; |
import java.util.Date; |
import java.util.Map; |
import javax.swing.JOptionPane; |
import com.ibm.icu.text.SimpleDateFormat; |
import com.lowagie.text.Document; |
import com.lowagie.text.DocumentException; |
import com.lowagie.text.Rectangle; |
38,69 → 37,43 |
import com.lowagie.text.pdf.PdfWriter; |
public abstract class PdfGenerator { |
private int marginX, marginY; |
private int offsetX, offsetY; |
private int templateOffsetX, templateOffsetY; |
private int offsetX; |
private int offsetY; |
private int templateOffsetX; |
private int templateOffsetY; |
private PdfContentByte cb; |
private Document document; |
private BaseFont bf, bfb; |
private BaseFont bf; |
private BaseFont bfb; |
private int width; |
private Map map; |
private String fileNameIn, fileNameOut; |
private Map<String, String> map; |
private String fileNameIn; |
private String fileNameOut; |
private File directoryOut; |
private File fOut; |
public static void main(String[] args) { |
new PdfGenerator_2033B().generateFrom(null); |
// HashMap h = new HashMap(); |
// h.put("NOM","Front Software"); |
// new PdfGenerator_2033A().generateFrom(h); |
} |
PdfGenerator(String fileNameIn, String fileNameOut, String directoryOut) { |
this.fileNameIn = "/Configuration/Template/PDF/" + fileNameIn; |
this.fileNameOut = fileNameOut; |
System.err.println("First folder " + directoryOut); |
this.directoryOut = new File(directoryOut, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); |
} |
public void open(File f) { |
if (Desktop.isDesktopSupported()) { |
Desktop d = Desktop.getDesktop(); |
if (d.isSupported(Desktop.Action.OPEN)) { |
public void generateFrom(Map<String, String> m) { |
try { |
d.open(f.getCanonicalFile()); |
} catch (IOException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} |
} else { |
JOptionPane.showMessageDialog(null, "Cette action n'est pas supporté par votre système d'exploitation."); |
} |
} else { |
JOptionPane.showMessageDialog(null, "Votre système d'exploitation n'est pas supporté."); |
} |
} |
public void generateFrom(Map m) { |
try { |
if (m == null) { |
System.out.println("Filling with defaults"); |
System.err.println(this + " : filling with defaults"); |
} |
this.map = m; |
init(); |
this.cb.beginText(); |
generate(); |
this.cb.endText(); |
// step 5: we close the document |
// FIXME ASK IF CLOSE WRITER |
this.document.close(); |
System.out.println("done!"); |
} catch (FileNotFoundException e) { |
ExceptionHandler.handle("Impossible de générer le fichier. \n" + e, e); |
} |
114,41 → 87,26 |
try { |
reader = new PdfReader(getStreamStatic(this.fileNameIn)); |
// we retrieve the total number of pages |
int n = reader.getNumberOfPages(); |
// we retrieve the size of the first page |
Rectangle psize = reader.getPageSize(1); |
final Rectangle psize = reader.getPageSize(1); |
psize.setRight(psize.getRight() - this.templateOffsetX); |
psize.setTop(psize.getTop() - this.templateOffsetY); |
this.width = (int) psize.getWidth(); |
float height = psize.getHeight(); |
// step 1: creation of a document-object |
int MARGIN = 32; |
this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN); |
// step 2: we create a writer that listens to the document |
int margin = 32; |
this.document = new Document(psize, margin, margin, margin, margin); |
if (!this.directoryOut.exists()) { |
this.directoryOut.mkdirs(); |
} |
System.err.println("Directory out " + this.directoryOut.getAbsolutePath()); |
File f = new File(this.directoryOut, this.fileNameOut); |
if (f.exists()) { |
f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut)); |
f = new File(this.directoryOut, this.fileNameOut); |
} |
final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); |
final String computedFileName = sdf.format(new Date()) + "-" + this.fileNameOut; |
System.err.println("Creation du fichier " + f.getAbsolutePath()); |
writer = PdfWriter.getInstance(this.document, new FileOutputStream(f)); |
fOut = new File(this.directoryOut, computedFileName); |
System.err.println("Creation du fichier " + fOut.getCanonicalPath()); |
writer = PdfWriter.getInstance(this.document, new FileOutputStream(fOut)); |
this.document.open(); |
// step 4: we add content |
this.cb = writer.getDirectContent(); |
System.out.println("There are " + n + " pages in the document."); |
this.document.newPage(); |
PdfImportedPage page1 = writer.getImportedPage(reader, 1); |
160,10 → 118,8 |
} catch (FileNotFoundException fE) { |
throw fE; |
} catch (IOException e) { |
e.printStackTrace(); |
} catch (DocumentException e) { |
e.printStackTrace(); |
} catch (IOException | DocumentException e) { |
throw new IllegalStateException(e); |
} finally { |
if (reader != null) { |
reader.close(); |
171,34 → 127,29 |
} |
} |
abstract public void generate(); |
public abstract void generate(); |
protected void setMargin(int i, int j) { |
this.marginX = i; |
this.marginY = j; |
public File getGeneratedFile() { |
return this.fOut; |
} |
protected void setOffset(int i, int j) { |
this.offsetX = i; |
this.offsetY = j; |
} |
protected void setTemplateOffset(int i, int j) { |
this.templateOffsetX = i; |
this.templateOffsetY = j; |
} |
protected void addSplittedText(String code, String string, int fromx, int y, double deltax) { |
float x = fromx - this.offsetX - this.templateOffsetX; |
int x = fromx - this.offsetX - this.templateOffsetX; |
y = y - this.offsetY - this.templateOffsetY; |
boolean error = false; |
String s = string; |
if (this.map != null) { |
s = (String) this.map.get(code); |
s = this.map.get(code); |
} |
if (s == null) { |
s = code; |
209,13 → 160,11 |
for (int i = 0; i < s.length(); i++) { |
char c = s.charAt(i); |
String sub = String.valueOf(c); |
this.cb.showTextAligned(PdfContentByte.ALIGN_LEFT, sub, x, y, 0); |
x += deltax; |
} |
if (error) { |
this.cb.setColorStroke(Color.BLACK); |
} |
240,8 → 189,6 |
} |
protected void addTextRight(String code, String string, int i, int j) { |
// addText(PdfContentByte.ALIGN_RIGHT, code, string, i, j, 0); |
int a = PdfContentByte.ALIGN_RIGHT; |
int k = 0; |
249,13 → 196,10 |
this.cb.showTextAligned(a, string, i, j, k); |
else { |
boolean error = false; |
String s = (String) this.map.get(code); |
String s = this.map.get(code); |
if (s == null) { |
System.out.println("Impossibe de trouver: " + code + " Set color red"); |
s = code; |
error = true; |
// cb.setColorFill(Color.RED); |
} else { |
if (s.equalsIgnoreCase("-0.0")) { |
s = "0.0"; |
262,10 → 206,8 |
} |
s = insertCurrencySpaces(s); |
} |
System.out.println("print " + s); |
this.cb.showTextAligned(a, s, i, j, k); |
if (error) { |
System.out.println(" Set color black"); |
this.cb.setColorStroke(Color.BLACK); |
} |
} |
273,23 → 215,17 |
} |
private final void addText(int a, String code, String string, int i, int j, int k) { |
if (this.map == null) |
this.cb.showTextAligned(a, string, i, j, k); |
else { |
boolean error = false; |
String s = (String) this.map.get(code); |
String s = this.map.get(code); |
if (s == null) { |
System.out.println("Impossibe de trouver: " + code + " Set color red"); |
s = code; |
error = true; |
// cb.setColorFill(Color.RED); |
} |
System.out.println("print " + s); |
this.cb.showTextAligned(a, s, i, j, k); |
if (error) { |
System.out.println(" Set color black"); |
this.cb.setColorStroke(Color.BLACK); |
} |
} |
300,16 → 236,13 |
} |
protected static String insertCurrencySpaces(String string) { |
StringBuffer s = new StringBuffer(); |
final StringBuilder s = new StringBuilder(); |
for (int i = string.length() - 1; i >= 0; i--) { |
s.insert(0, string.charAt(i)); |
if ((i - string.length()) % 3 == 0) { |
s.insert(0, " "); |
} |
} |
return s.toString().trim(); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map3310.java |
---|
17,7 → 17,6 |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.erp.preferences.TemplateNXProps; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLBase; |
import org.openconcerto.sql.model.SQLRow; |
25,10 → 24,6 |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.utils.GestionDevise; |
import java.io.File; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.Map; |
38,12 → 33,11 |
public class Map3310 extends Thread { |
private Map<String, Object> m; |
private final DateFormat format = new SimpleDateFormat("ddMMyyyy"); |
private Map<String, String> m; |
private JProgressBar bar; |
private Date dateDebut, dateFin; |
private final static SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
private Date dateDebut; |
private Date dateFin; |
private static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE"); |
private static final SQLTable tableCompte = Configuration.getInstance().getRoot().findTable("COMPTE_PCE"); |
private SQLRowValues rowPrefCompteVals = new SQLRowValues(tablePrefCompte); |
117,12 → 111,11 |
SQLRow rowCompteTVAImmo = tableCompte.getRow(idCompteTVAImmo); |
PdfGenerator_3310 p = new PdfGenerator_3310(); |
this.m = new HashMap<String, Object>(); |
this.m = new HashMap<String, String>(); |
long v010 = -this.sommeCompte.soldeCompte(70, 70, true, this.dateDebut, this.dateFin); |
this.m.put("A01", GestionDevise.round(v010)); |
// long vA02 = this.sommeCompte.soldeCompte(70, 70, true, this.dateDebut, this.dateFin); |
this.m.put("A02", ""); |
long tvaIntra = -this.sommeCompte.sommeCompteFils(rowCompteTVAIntra.getString("NUMERO"), this.dateDebut, this.dateFin); |
long achatsIntra = this.sommeCompte.sommeCompteFils(rowCompteAchatIntra.getString("NUMERO"), this.dateDebut, this.dateFin); |
193,12 → 186,7 |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
String file = TemplateNXProps.getInstance().getStringProperty("Location3310PDF") + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) + File.separator |
+ "result_3310_2.pdf"; |
System.err.println(file); |
File f = new File(file); |
Gestion.openPDF(f); |
Gestion.openPDF(p.getGeneratedFile()); |
Map3310.this.bar.setValue(100); |
} |
}); |
206,9 → 194,7 |
} |
public Map3310(JProgressBar bar, Date dateDeb, Date dateFin) { |
this.bar = bar; |
if (dateDeb == null && dateFin == null) { |
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
SQLRow rowExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON").getRow(rowSociete.getInt("ID_EXERCICE_COMMON")); |
215,7 → 201,6 |
dateFin = (Date) rowExercice.getObject("DATE_FIN"); |
dateDeb = (Date) rowExercice.getObject("DATE_DEB"); |
} |
this.dateDebut = dateDeb; |
this.dateFin = dateFin; |
this.sommeCompte = new SommeCompte(); |
222,7 → 207,6 |
} |
public Map3310(JProgressBar bar) { |
this(bar, null, null); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator_3310.java |
---|
18,20 → 18,14 |
public class PdfGenerator_3310 extends PdfGenerator { |
public PdfGenerator_3310() { |
super("3310_2.pdf", "result_3310_2.pdf", TemplateNXProps.getInstance().getStringProperty("Location3310PDF")); |
super("3310_2.pdf", "3310_2.pdf", TemplateNXProps.getInstance().getStringProperty("Location3310PDF")); |
setTemplateOffset(0, 0); |
setOffset(0, 0); |
setMargin(32, 32); |
} |
public void generate() { |
setFontBold(14); |
// Copyright |
setFontRoman(9); |
String cc = "Document généré par le logiciel Bloc, (c) Front Software 2006"; |
setFontRoman(10); |
long t = 53L; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033A.java |
---|
16,15 → 16,12 |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.erp.preferences.TemplateNXProps; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.utils.GestionDevise; |
import java.io.File; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.Map; |
34,7 → 31,7 |
public class Map2033A extends Thread { |
private Map<String, Object> m; |
private Map<String, String> m; |
private final DateFormat format = new SimpleDateFormat("ddMMyyyy"); |
private JProgressBar bar; |
private Date dateDebut, dateFin; |
51,7 → 48,7 |
public void run() { |
PdfGenerator_2033A p = new PdfGenerator_2033A(); |
this.m = new HashMap<String, Object>(); |
this.m = new HashMap(); |
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
this.m.put("NOM", rowSociete.getString("TYPE") + " " + rowSociete.getString("NOM")); |
860,11 → 857,7 |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
final String file = TemplateNXProps.getInstance().getStringProperty("Location2033APDF") + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) + File.separator |
+ "result_2033A.pdf"; |
File f = new File(file); |
Gestion.openPDF(f); |
Gestion.openPDF(p.getGeneratedFile()); |
Map2033A.this.bar.setValue(100); |
} |
}); |
876,9 → 869,7 |
} |
public Map2033A(JProgressBar bar, Date dateDeb, Date dateFin, SQLRow posteAnalytique) { |
this.bar = bar; |
if (dateDeb == null && dateFin == null) { |
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
SQLRow rowExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON").getRow(rowSociete.getInt("ID_EXERCICE_COMMON")); |
889,8 → 880,6 |
this.dateDebut = dateDeb; |
this.dateFin = dateFin; |
this.sommeCompte = new SommeCompte(posteAnalytique); |
// this.sommeCompte.setRemoveClotureCompte(true); |
} |
public Map2033A(JProgressBar bar) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033B.java |
---|
16,15 → 16,12 |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.erp.preferences.TemplateNXProps; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.utils.GestionDevise; |
import java.io.File; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.Map; |
496,10 → 493,7 |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
final String file = TemplateNXProps.getInstance().getStringProperty("Location2033BPDF") + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) + File.separator |
+ "result_2033B.pdf"; |
File f = new File(file); |
Gestion.openPDF(f); |
Gestion.openPDF(p.getGeneratedFile()); |
Map2033B.this.bar.setValue(100); |
} |
}); |
510,7 → 504,6 |
} |
public Map2033B(JProgressBar bar, Date dateDeb, Date dateFin, SQLRow rowPosteAnalytique) { |
this.bar = bar; |
if (dateDeb == null && dateFin == null) { |
523,7 → 516,6 |
this.dateDeb = dateDeb; |
this.dateFin = dateFin; |
this.sommeCompte = new SommeCompte(rowPosteAnalytique); |
// this.sommeCompte.setRemoveClotureCompte(true); |
} |
public Map2033B(JProgressBar b) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator_2033A.java |
---|
21,12 → 21,9 |
public class PdfGenerator_2033A extends PdfGenerator { |
public PdfGenerator_2033A() { |
super("2033A.pdf", "result_2033A.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033APDF")); |
super("2033A.pdf", "2033A.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033APDF")); |
setTemplateOffset(0, 0); |
setOffset(0, 0); |
setMargin(32, 32); |
} |
public void generate() { |
50,23 → 47,17 |
} |
final String adresse = rowAdresse.getString("RUE") + ", " + rowAdresse.getString("CODE_POSTAL") + " " + ville; |
System.err.println(adresse); |
addText("ADRESSE", adresse, 100, 759); |
addSplittedText("SIRET", rowSociete.getString("NUM_SIRET").replaceAll(" ", ""), 82, 735, 17); |
// addSplittedText("APE", rowSociete.getString("NUM_APE"), 366, 794 - 18 - 18, 16); |
addSplittedText("CLOS1", "08202006", 502, 689, 9.7); |
// addSplittedText("CLOS2", "08202006", 502, 707, 9.7); |
addSplittedText("DUREE1", "12", 211 - 28, 758, 14); |
// addSplittedText("DUREE2", "88", 366, 741, 14); |
// Copyright |
setFontRoman(9); |
String cc = "Document généré par le logiciel Bloc, (c) Front Software 2006"; |
addText("", cc, getWidth() - 2, 16, 90); |
addText("", "Document généré par le logiciel OpenConcerto", getWidth() - 2, 16, 90); |
setFontRoman(10); |
long t = 53L; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator_2033B.java |
---|
20,11 → 20,9 |
public class PdfGenerator_2033B extends PdfGenerator { |
public PdfGenerator_2033B() { |
super("2033B.pdf", "result_2033B.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033BPDF")); |
super("2033B.pdf", "2033B.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033BPDF")); |
setTemplateOffset(0, 0); |
setOffset(0, 0); |
setMargin(32, 32); |
} |
public void generate() { |
35,12 → 33,10 |
setFontRoman(12); |
addSplittedText("CLOS1", "08202006", 410, 790, 9.7); |
// addSplittedText("CLOS2", "08202006", 502, 809, 9.7); |
// Copyright |
setFontRoman(9); |
String cc = "Document généré par le logiciel Bloc, (c) Front Software 2006"; |
addText("", cc, getWidth() - 2, 460, 90); |
addText("", "Document généré par le logiciel OpenConcerto", getWidth() - 2, 460, 90); |
setFontRoman(10); |
long t = 143785123456L; |
49,7 → 45,6 |
int cellHeight = 18; |
final int colN = 487; |
for (; y > 720; y -= cellHeight) { |
addTextRight("PRODUIT1." + yy, insertCurrencySpaces("" + t), 400, y); |
addTextRight("PRODUIT2." + yy, insertCurrencySpaces("" + t), colN, y); |
addTextRight("PRODUIT3." + yy, insertCurrencySpaces("" + t), 580, y); |
57,7 → 52,6 |
} |
y += 2; |
for (; y > 630; y -= cellHeight) { |
addTextRight("PRODUIT2." + yy, insertCurrencySpaces("" + t), colN, y); |
addTextRight("PRODUIT3." + yy, insertCurrencySpaces("" + t), 580, y); |
yy++; |
176,7 → 170,6 |
// |
addTextRight("T1." + yy, insertCurrencySpaces("" + t), 226, y); |
addTextRight("T2." + yy, insertCurrencySpaces("" + t), 461, y); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator_2033C.java |
---|
21,24 → 21,21 |
public class PdfGenerator_2033C extends PdfGenerator { |
public PdfGenerator_2033C() { |
super("2033C.pdf", "result_2033C.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033CPDF")); |
super("2033C.pdf", "2033C.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033CPDF")); |
setTemplateOffset(0, 0); |
setOffset(0, 0); |
setMargin(32, 32); |
} |
public void generate() { |
setFontBold(14); |
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
final SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
addText("NOM", rowSociete.getString("TYPE") + " " + rowSociete.getString("NOM"), 245, 794); |
setFontRoman(12); |
// Copyright |
setFontRoman(9); |
String cc = "Document généré par le logiciel Bloc, (c) Front Software 2006"; |
addText("", cc, 350, 31, 0); |
addText("", "Document généré par le logiciel OpenConcerto", 350, 31, 0); |
setFontRoman(10); |
long t = 785123456L; |
45,7 → 42,6 |
int yy = 0; |
int y = 724; |
for (int i = 0; i < 10; i++) { |
addTextRight("IMMO1." + yy, insertCurrencySpaces("" + t), 225, y); |
addTextRight("IMMO2." + yy, insertCurrencySpaces("" + t), 316, y); |
addTextRight("IMMO3." + yy, insertCurrencySpaces("" + t), 407, y); |
57,12 → 53,10 |
y -= 18; |
y -= 18; |
for (int i = 0; i < 8; i++) { |
addTextRight("AM1." + yy, insertCurrencySpaces("" + t), 282, y); |
addTextRight("AM2." + yy, insertCurrencySpaces("" + t), 384, y); |
addTextRight("AM3." + yy, insertCurrencySpaces("" + t), 486, y); |
addTextRight("AM4." + yy, insertCurrencySpaces("" + t), 587, y); |
yy++; |
y -= 18; |
} |
71,13 → 65,11 |
y -= 18; |
y -= 18; |
for (int i = 0; i < 10; i++) { |
addText("VAL1." + yy, "Nature", 40, y); |
addTextRight("VAL2." + yy, insertCurrencySpaces("" + t), 219, y); |
addTextRight("VAL3." + yy, insertCurrencySpaces("" + t), 293, y); |
addTextRight("VAL4." + yy, insertCurrencySpaces("" + t), 367, y); |
addTextRight("VAL5." + yy, insertCurrencySpaces("" + t), 441, y); |
addTextRight("VAL6." + yy, insertCurrencySpaces("" + t), 515, y); |
addTextRight("VAL7." + yy, insertCurrencySpaces("" + t), 587, y); |
yy++; |
89,7 → 81,6 |
addTextRight("TOT3." + yy, insertCurrencySpaces("" + t), 293 - 8, y); |
addTextRight("TOT4." + yy, insertCurrencySpaces("" + t), 367 - 8, y); |
addTextRight("TOT5." + yy, insertCurrencySpaces("" + t), 441 - 8, y); |
addTextRight("TOT6." + yy, insertCurrencySpaces("" + t), 515 - 8, y); |
addTextRight("TOT7." + yy, insertCurrencySpaces("" + t), 587, y); |
yy++; |
101,13 → 92,10 |
addTextRight("TOT7." + yy, insertCurrencySpaces("" + t), 587, y); |
yy++; |
y -= 18; |
setFontBold(10); |
y += 2; |
addTextRight("TOT6." + yy, insertCurrencySpaces("" + t), 515 - 8, y); |
addTextRight("TOT7." + yy, insertCurrencySpaces("" + t), 587, y); |
yy++; |
y -= 18; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PdfGenerator_2033E.java |
---|
21,18 → 21,15 |
public class PdfGenerator_2033E extends PdfGenerator { |
public PdfGenerator_2033E() { |
super("2033E.pdf", "result_2033E.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033E")); |
super("2033E.pdf", "2033E.pdf", TemplateNXProps.getInstance().getStringProperty("Location2033E")); |
setTemplateOffset(0, 0); |
setOffset(0, 0); |
setMargin(32, 32); |
} |
public void generate() { |
setFontBold(14); |
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
final SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
addText("NOM", rowSociete.getString("TYPE") + " " + rowSociete.getString("NOM"), 138, 722); |
setFontRoman(12); |
addText("OUVERT", "1er janvier 2004", 105, 703); |
addText("CLOS", "31 décembre 2004", 274, 703); |
40,8 → 37,7 |
// Copyright |
setFontRoman(9); |
String cc = "Document généré par le logiciel Bloc, (c) Front Software 2006"; |
addText("", cc, 350, 161, 0); |
addText("", "Document généré par le logiciel OpenConcerto", 350, 161, 0); |
setFontRoman(10); |
long t = 785123456L; |
48,17 → 44,13 |
int yy = 0; |
int y = 651; |
for (int i = 0; i < 8; i++) { |
addTextRight("PROD1." + yy, insertCurrencySpaces("" + t), 563, y); |
yy++; |
y -= 18; |
} |
y -= 18; |
for (int i = 0; i < 11; i++) { |
addTextRight("CONSO1." + yy, insertCurrencySpaces("" + t), 563, y); |
yy++; |
y -= 18; |
} |
66,10 → 58,6 |
// |
addTextRight("TOT1." + yy, insertCurrencySpaces("" + t), 563, y); |
yy++; |
y -= 18; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/BalanceSheet.java |
---|
142,6 → 142,13 |
} else { |
w = w.and(new Where(tableCompte.getField("NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd)); |
} |
// FIXME use flag cloture |
Where wCloture = new Where(tableEcriture.getField("NOM"), "NOT LIKE", "Fermeture du compte%"); |
wCloture = wCloture.and(new Where(tableEcriture.getField("DATE"), "=", this.dateAu)); |
wCloture = wCloture.or(new Where(tableEcriture.getField("DATE"), "<", this.dateAu)); |
w = w.and(wCloture); |
sel.setWhere(w); |
String req = sel.asString() + " AND \"ECRITURE\".\"ID_COMPTE_PCE\" = \"COMPTE_PCE\".\"ID\" GROUP BY \"COMPTE_PCE\".\"NUMERO\", \"COMPTE_PCE\".\"ID\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/NouveauAssociationCpteAnalytiqueAction.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/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/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/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/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/ui/ClotureSansAnouveauxPanel.java |
---|
New file |
0,0 → 1,517 |
/* |
* 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.ui; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.erp.element.objet.Compte; |
import org.openconcerto.erp.generationEcritures.GenerationMvtVirement; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLBase; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLSelect; |
import org.openconcerto.sql.model.SQLSystem; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.utils.SQLUtils; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.JDate; |
import org.openconcerto.ui.JLabelBold; |
import org.openconcerto.utils.ExceptionHandler; |
import java.awt.Component; |
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.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
import javax.swing.JButton; |
import javax.swing.JCheckBox; |
import javax.swing.JFrame; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.JProgressBar; |
import javax.swing.SwingUtilities; |
import org.apache.commons.dbutils.handlers.ArrayListHandler; |
public class ClotureSansAnouveauxPanel extends JPanel { |
private final JDate dateOuv = new JDate(); |
private final JDate dateFerm = new JDate(); |
private SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
private final SQLTable societe = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON"); |
private final SQLTable exercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON"); |
private final SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete(); |
// private final SQLRow rowExercice = |
// this.exercice.getRow(this.rowSociete.getInt("ID_EXERCICE_COMMON")); |
private final Map<Object, Long> mRAN = new HashMap<Object, Long>(); |
private JButton valider = new JButton("Valider"); |
private JButton annul = new JButton("Annuler"); |
private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); |
private JLabel opEnCours = new JLabel("Etat: en attente de validation"); |
private JCheckBox boxValid = new JCheckBox("Je confirme avoir effectué toutes les opérations nécessaires."); |
private JProgressBar bar = new JProgressBar(0, 4); |
public ClotureSansAnouveauxPanel() { |
this.setLayout(new GridBagLayout()); |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
c.fill = GridBagConstraints.HORIZONTAL; |
c.anchor = GridBagConstraints.WEST; |
c.gridx = 0; |
c.gridy = 0; |
c.gridwidth = GridBagConstraints.REMAINDER; |
c.gridheight = 1; |
c.weightx = 0; |
c.weighty = 0; |
JLabel rappel = new JLabelBold("Opérations à effectuer avant de continuer: "); |
JLabel label = new JLabel("- report des charges et produits constatés d'avance"); |
JLabel label2 = new JLabel("- report des charges à payer et produits à recevoir"); |
JLabel label3 = new JLabel("- impression du bilan, compte de résultat, grand livre, journaux et balance"); |
JLabel label5 = new JLabel("- génération les écritures comptables des payes"); |
JLabel label4 = new JLabel("Il est préférable de réaliser une sauvegarde avant de continuer."); |
JLabel op = new JLabelBold("Opérations qui vont etre effectuées: "); |
JLabel labelValid = new JLabel("- validation de toutes les écritures concernant la période de l'exercice."); |
JLabel labelSoldeGestion = new JLabel("- soldes de tous les comptes de gestions 6* et 7*"); |
JLabel labelSoldeBilan = new JLabel("- soldes de tous les comptes de bilan"); |
JLabel labelAN = new JLabel("- report des à nouveaux"); |
c.gridy = GridBagConstraints.RELATIVE; |
c.gridx = 0; |
// Date de l'ancien exercice |
// Calendar dDebut = this.rowExercice.getDate("DATE_DEB"); |
// Calendar dFin = this.rowExercice.getDate("DATE_FIN"); |
// JLabel labelAncienExercice = new JLabel("Clôture de l'exercice du " + |
// dateFormat.format(dDebut.getTime()) + " au " + dateFormat.format(dFin.getTime())); |
// this.add(labelAncienExercice, c); |
c.insets = new Insets(10, 2, 1, 2); |
this.add(rappel, c); |
this.add(label, c); |
this.add(label2, c); |
this.add(label3, c); |
this.add(label5, c); |
this.add(label4, c); |
c.insets = new Insets(15, 2, 1, 2); |
this.add(op, c); |
c.insets = new Insets(10, 2, 1, 2); |
this.add(labelValid, c); |
this.add(labelSoldeGestion, c); |
this.add(labelSoldeBilan, c); |
this.add(labelAN, c); |
// Date du prochain exercice |
c.gridwidth = 1; |
c.gridy = GridBagConstraints.RELATIVE; |
c.gridx = 0; |
c.gridx = GridBagConstraints.RELATIVE; |
c.fill = GridBagConstraints.NONE; |
this.add(new JLabel("Date du nouvel exercice du "), c); |
// dDebut.set(Calendar.YEAR, dDebut.get(Calendar.YEAR) + 1); |
// this.dateOuv.setValue(dDebut.getTime()); |
this.add(this.dateOuv, c); |
this.add(new JLabel("au"), c); |
// dFin.set(Calendar.YEAR, dFin.get(Calendar.YEAR) + 1); |
// this.dateFerm.setValue(dFin.getTime()); |
this.add(this.dateFerm, c); |
c.gridx = 0; |
c.fill = GridBagConstraints.HORIZONTAL; |
c.gridwidth = 2; |
c.weightx = 1; |
this.add(this.opEnCours, c); |
c.gridwidth = 4; |
c.gridx = 0; |
c.weightx = 1; |
this.add(this.bar, c); |
// |
this.add(this.boxValid, c); |
// Button |
final JPanel buttonBar = new JPanel(); |
buttonBar.add(this.valider); |
buttonBar.add(this.annul); |
c.fill = GridBagConstraints.NONE; |
c.anchor = GridBagConstraints.EAST; |
c.gridx = 0; |
this.add(buttonBar, c); |
final PropertyChangeListener listener = new PropertyChangeListener() { |
public void propertyChange(PropertyChangeEvent evt) { |
ClotureSansAnouveauxPanel.this.valider.setEnabled(isDateValid()); |
} |
}; |
// this.dateFerm.addValueListener(listener); |
// this.dateOuv.addValueListener(listener); |
// TODO afficher le deroulement de etapes apres validation |
this.valider.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent e) { |
valider.setEnabled(false); |
dateFerm.setEnabled(false); |
dateOuv.setEnabled(false); |
new Thread(new Runnable() { |
public void run() { |
try { |
clotureExercice(); |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
// show OK works fine |
Component comp = SwingUtilities.getRoot(ClotureSansAnouveauxPanel.this); |
JOptionPane.showMessageDialog(ClotureSansAnouveauxPanel.this, "Exercice clôturé", "Fin de la clôture", JOptionPane.INFORMATION_MESSAGE); |
if (comp != null) { |
((JFrame) comp).dispose(); |
} |
} |
}); |
} catch (Exception ex) { |
ExceptionHandler.handle("Erreur lors de la clôture", ex); |
} |
} |
}).start(); |
} |
}); |
// this.valider.setEnabled(isDateValid()); |
this.boxValid.addActionListener(new ActionListener() { |
@Override |
public void actionPerformed(ActionEvent e) { |
ClotureSansAnouveauxPanel.this.valider.setEnabled(isDateValid()); |
} |
}); |
this.annul.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent e) { |
((JFrame) SwingUtilities.getRoot(ClotureSansAnouveauxPanel.this)).dispose(); |
} |
}); |
} |
private boolean isDateValid() { |
// final Date d = (Date) this.rowExercice.getObject("DATE_FIN"); |
// return this.boxValid.isSelected() && (((!this.dateFerm.isEmpty()) && |
// (!this.dateOuv.isEmpty()) && (this.dateFerm.getValue().getTime() > |
// this.dateOuv.getValue().getTime()) |
// && (this.dateOuv.getValue().getTime() > d.getTime()))); |
return true; |
} |
private final SQLTable tablePrefCompte = this.base.getTable("PREFS_COMPTE"); |
private void clotureExercice() throws SQLException { |
final SQLRow rowPrefCompte = this.tablePrefCompte.getRow(2); |
final int id_Compte_Bilan_Ouverture; |
if (rowPrefCompte.getInt("ID_COMPTE_PCE_BILAN_O") <= 1) { |
id_Compte_Bilan_Ouverture = ComptePCESQLElement.getId("890"); |
} else { |
id_Compte_Bilan_Ouverture = rowPrefCompte.getInt("ID_COMPTE_PCE_BILAN_O"); |
} |
final int id_Compte_Bilan_Cloture; |
if (rowPrefCompte.getInt("ID_COMPTE_PCE_BILAN_F") <= 1) { |
id_Compte_Bilan_Cloture = ComptePCESQLElement.getId("891"); |
} else { |
id_Compte_Bilan_Cloture = rowPrefCompte.getInt("ID_COMPTE_PCE_BILAN_F"); |
} |
// /******************************************************************************************* |
// * Validation des écritures |
// ******************************************************************************************/ |
// EcritureSQLElement.validationEcrituresBefore((Date) |
// this.rowExercice.getObject("DATE_FIN"), true); |
SQLUtils.executeAtomic(this.tablePrefCompte.getDBSystemRoot().getDataSource(), new SQLUtils.SQLFactory<Object>() { |
@Override |
public Object create() throws SQLException { |
/******************************************************************************************* |
* Solde des comptes de gestion 6* et 7* (génération du résultat) |
******************************************************************************************/ |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
ClotureSansAnouveauxPanel.this.opEnCours.setText("En cours: solde des comptes 6 et 7"); |
} |
}); |
long time = new Date().getTime(); |
System.err.println("Start :: " + time); |
soldeCompte(false); |
/******************************************************************************************* |
* Solde des autres comptes (comptes de bilan) |
******************************************************************************************/ |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
ClotureSansAnouveauxPanel.this.opEnCours.setText("En cours: solde des comptes autres que 6 et 7"); |
ClotureSansAnouveauxPanel.this.bar.setValue(1); |
} |
}); |
soldeCompte(true); |
long time2 = new Date().getTime(); |
System.err.println("Stop :: " + time2); |
System.err.println("Time :: " + (time2 - time)); |
/******************************************************************************************* |
* Reouverture des comptes de bilan |
******************************************************************************************/ |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
ClotureSansAnouveauxPanel.this.opEnCours.setText("En cours: report des à nouveaux"); |
ClotureSansAnouveauxPanel.this.bar.setValue(2); |
} |
}); |
// transfert du compte bilan fermeture vers le compte bilan ouverture |
SQLTable ecritureTable = ClotureSansAnouveauxPanel.this.base.getTable("ECRITURE"); |
SQLTable compteTable = ClotureSansAnouveauxPanel.this.base.getTable("COMPTE_PCE"); |
SQLSelect sel = new SQLSelect(ClotureSansAnouveauxPanel.this.base); |
sel.addSelect(compteTable.getKey()); |
sel.addSelect(compteTable.getField("NUMERO")); |
sel.addSelect(compteTable.getField("NOM")); |
sel.addSelect(ecritureTable.getField("DEBIT"), "SUM"); |
sel.addSelect(ecritureTable.getField("CREDIT"), "SUM"); |
Where w = new Where(ecritureTable.getField("ID_COMPTE_PCE"), "=", id_Compte_Bilan_Cloture); |
w = w.and(new Where(ecritureTable.getField("ID_COMPTE_PCE"), "=", compteTable.getKey())); |
sel.setWhere(w); |
String req = sel.asString() + " GROUP BY \"COMPTE_PCE\".\"ID\", \"COMPTE_PCE\".\"NUMERO\", \"COMPTE_PCE\".\"NOM\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
System.out.println(req); |
Object ob = ClotureSansAnouveauxPanel.this.base.getDataSource().execute(req, new ArrayListHandler()); |
List myList = (List) ob; |
if (myList.size() != 0) { |
GenerationMvtVirement gen = new GenerationMvtVirement(1, id_Compte_Bilan_Cloture, 0, 0, "Fermeture du compte ", ClotureSansAnouveauxPanel.this.dateFerm.getDate(), |
JournalSQLElement.OD, "Fermeture des comptes"); |
for (int i = 0; i < myList.size(); i++) { |
Object[] objTmp = (Object[]) myList.get(i); |
Compte cptTmp = new Compte(((Number) objTmp[0]).intValue(), objTmp[1].toString(), objTmp[2].toString(), "", ((Number) objTmp[3]).longValue(), ((Number) objTmp[4]).longValue()); |
// vecteurCompte.add(cptTmp); |
long solde = cptTmp.getTotalDebit() - cptTmp.getTotalCredit(); |
if (solde != 0) { |
if (solde > 0) { |
gen.setValues(cptTmp.getId(), id_Compte_Bilan_Cloture, 0, Math.abs(solde), "Fermeture du compte " + cptTmp.getNumero(), |
ClotureSansAnouveauxPanel.this.dateFerm.getDate(), JournalSQLElement.OD, false); |
} else { |
gen.setValues(cptTmp.getId(), id_Compte_Bilan_Cloture, Math.abs(solde), 0, "Fermeture du compte " + cptTmp.getNumero(), |
ClotureSansAnouveauxPanel.this.dateFerm.getDate(), JournalSQLElement.OD, false); |
} |
gen.genereMouvement(); |
} |
} |
} |
/******************************************************************************************* |
* Validation des écritures de clotures |
******************************************************************************************/ |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
ClotureSansAnouveauxPanel.this.opEnCours.setText("En cours: validation des écritures de l'exercice"); |
ClotureSansAnouveauxPanel.this.bar.setValue(3); |
} |
}); |
EcritureSQLElement.validationEcrituresBefore((Date) ClotureSansAnouveauxPanel.this.dateFerm.getDate(), true); |
// // A nouveaux |
// Object[] compteAnouveau = ClotureSansAnouveauxPanel.this.mRAN.keySet().toArray(); |
// GenerationMvtVirement genAnouveaux = new |
// GenerationMvtVirement(id_Compte_Bilan_Ouverture, 1, 0, 0, "A nouveaux", |
// ClotureSansAnouveauxPanel.this.dateOuv.getValue(), JournalSQLElement.OD, |
// "A nouveaux"); |
// for (int i = 0; i < ClotureSansAnouveauxPanel.this.mRAN.keySet().size(); i++) { |
// |
// long solde = |
// ClotureSansAnouveauxPanel.this.mRAN.get(compteAnouveau[i]).longValue(); |
// |
// // if (solde != 0) { |
// if (solde > 0) { |
// genAnouveaux.setValues(id_Compte_Bilan_Ouverture, |
// Integer.parseInt(compteAnouveau[i].toString()), 0, Math.abs(solde), "A nouveaux", |
// ClotureSansAnouveauxPanel.this.dateOuv.getValue(), |
// JournalSQLElement.OD, false); |
// } else { |
// genAnouveaux.setValues(id_Compte_Bilan_Ouverture, |
// Integer.parseInt(compteAnouveau[i].toString()), Math.abs(solde), 0, "A nouveaux", |
// ClotureSansAnouveauxPanel.this.dateOuv.getValue(), |
// JournalSQLElement.OD, false); |
// } |
// genAnouveaux.genereMouvement(); |
// // } |
// } |
// |
// // Fixé la nouvel date de l'exercice |
// SQLRowValues valsExercice = new |
// SQLRowValues(ClotureSansAnouveauxPanel.this.exercice); |
// valsExercice.put("CLOTURE", Boolean.TRUE); |
// valsExercice.update(ClotureSansAnouveauxPanel.this.rowExercice.getID()); |
// |
// // Creation d'un nouvel exercice |
// valsExercice.put("CLOTURE", Boolean.FALSE); |
// valsExercice.put("DATE_DEB", new |
// java.sql.Date(ClotureSansAnouveauxPanel.this.dateOuv.getValue().getTime())); |
// valsExercice.put("DATE_FIN", new |
// java.sql.Date(ClotureSansAnouveauxPanel.this.dateFerm.getValue().getTime())); |
// valsExercice.put("ID_SOCIETE_COMMON", |
// ClotureSansAnouveauxPanel.this.rowSociete.getID()); |
// SQLRow rowNewEx = valsExercice.insert(); |
// |
// // mise a jour de l'exercice de la societe |
// SQLRowValues rowValsSociete = new |
// SQLRowValues(ClotureSansAnouveauxPanel.this.societe); |
// rowValsSociete.put("ID_EXERCICE_COMMON", rowNewEx.getID()); |
// rowValsSociete.update(ClotureSansAnouveauxPanel.this.rowSociete.getID()); |
// // Recharge les informations de la societe pour pointer sur le nouvel exercice |
// ComptaPropsConfiguration.getInstanceCompta().getRowSociete().fetchValues(); |
// SwingUtilities.invokeLater(new Runnable() { |
// public void run() { |
// ClotureSansAnouveauxPanel.this.bar.setValue(4); |
// ClotureSansAnouveauxPanel.this.opEnCours.setText("Etat: clôture terminée"); |
// } |
// }); |
return null; |
} |
}); |
} |
private void soldeCompte(boolean compteBilan) throws SQLException { |
String typeCompte; |
int compteDest; |
SQLRow rowPrefCompte = this.tablePrefCompte.getRow(2); |
if (compteBilan) { |
typeCompte = "^[^6-8].*$"; |
compteDest = rowPrefCompte.getInt("ID_COMPTE_PCE_BILAN_F"); |
if (compteDest <= 1) { |
compteDest = ComptePCESQLElement.getId("891", "Bilan de clôture"); |
} |
} else { |
SommeCompte s = new SommeCompte(); |
long solde6 = s.soldeCompte(6, 6, true, this.dateOuv.getDate(), this.dateFerm.getDate()); |
long solde7 = s.soldeCompte(7, 7, true, this.dateOuv.getDate(), this.dateFerm.getDate()); |
long resultat = -solde7 - solde6; |
System.err.println("Solde Résultat :::: " + solde7 + " __ " + solde6 + "__" + (solde7 - solde6)); |
typeCompte = "^(6|7).*$"; |
if (resultat > 0) { |
compteDest = rowPrefCompte.getInt("ID_COMPTE_PCE_RESULTAT"); |
} else { |
compteDest = rowPrefCompte.getInt("ID_COMPTE_PCE_RESULTAT_PERTE"); |
} |
if (compteDest <= 1) { |
if (resultat > 0) { |
compteDest = ComptePCESQLElement.getId("120", "Résultat de l'exercice (bénéfice)"); |
} else { |
compteDest = ComptePCESQLElement.getId("129", "Résultat de l'exercice (perte)"); |
} |
} |
} |
// on récupére les comptes avec leurs totaux |
SQLTable ecritureTable = this.base.getTable("ECRITURE"); |
SQLTable compteTable = this.base.getTable("COMPTE_PCE"); |
SQLSelect sel = new SQLSelect(this.base); |
sel.addSelect(compteTable.getKey()); |
sel.addSelect(compteTable.getField("NUMERO")); |
sel.addSelect(compteTable.getField("NOM")); |
sel.addSelect(ecritureTable.getField("DEBIT"), "SUM"); |
sel.addSelect(ecritureTable.getField("CREDIT"), "SUM"); |
Where w = new Where(ecritureTable.getField("ID_COMPTE_PCE"), "=", compteTable.getKey()); |
String function = "REGEXP"; |
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) { |
// function = "SIMILAR TO"; |
// typeCompte = typeCompte.replace(".*", "%"); |
function = "~"; |
} |
Where w2 = new Where(compteTable.getField("NUMERO"), function, typeCompte); |
Where w3 = new Where(ecritureTable.getField("DATE"), "<=", this.dateFerm.getDate()); |
sel.setWhere(w.and(w2).and(w3)); |
String req = sel.asString() + " GROUP BY \"COMPTE_PCE\".\"ID\", \"COMPTE_PCE\".\"NUMERO\", \"COMPTE_PCE\".\"NOM\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
System.err.println(req); |
Object ob = this.base.getDataSource().execute(req, new ArrayListHandler()); |
List myList = (List) ob; |
if (myList != null && myList.size() != 0) { |
GenerationMvtVirement genFerm = new GenerationMvtVirement(1, compteDest, 0, 0, "Fermeture du compte ", this.dateFerm.getDate(), JournalSQLElement.OD, "Fermeture des comptes"); |
for (int i = 0; i < myList.size(); i++) { |
Object[] objTmp = (Object[]) myList.get(i); |
Compte cptTmp = new Compte(((Number) objTmp[0]).intValue(), objTmp[1].toString(), objTmp[2].toString(), "", ((Number) objTmp[3]).longValue(), ((Number) objTmp[4]).longValue()); |
long solde = cptTmp.getTotalDebit() - cptTmp.getTotalCredit(); |
// if (solde != 0) { |
if (compteBilan) { |
this.mRAN.put(objTmp[0], Long.valueOf(solde)); |
} |
if (solde > 0) { |
genFerm.setValues(cptTmp.getId(), compteDest, 0, Math.abs(solde), "Fermeture du compte " + cptTmp.getNumero(), this.dateFerm.getDate(), JournalSQLElement.OD, false); |
} else { |
genFerm.setValues(cptTmp.getId(), compteDest, Math.abs(solde), 0, "Fermeture du compte " + cptTmp.getNumero(), this.dateFerm.getDate(), JournalSQLElement.OD, false); |
} |
genFerm.genereMouvement(); |
} |
// } |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ComptePayePreferencePanel.java |
---|
22,6 → 22,7 |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.request.SQLFieldTranslator; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.TitledSeparator; |
import org.openconcerto.ui.preferences.DefaultPreferencePanel; |
32,7 → 33,9 |
import java.sql.SQLException; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.SwingUtilities; |
public class ComptePayePreferencePanel extends DefaultPreferencePanel { |
private ISQLCompteSelector selCompteAcompte, selCompteAcompteReglement, selCompteRemunPers; |
124,7 → 127,14 |
this.rowPrefCompteVals.put("ID_COMPTE_PCE_PAYE", this.selCompteRemunPers.getValue()); |
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/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); |
} |
}); |
buttonClose.addActionListener(new ActionListener() { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieKmItemTable.java |
---|
93,16 → 93,19 |
final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE")); |
list.add(tableElementNomEcriture); |
// |
boolean kd = false; |
this.debit = new SQLTableElement(tableElement.getField("DEBIT"), Long.class, this.deviseCellEditor); |
list.add(this.debit); |
this.credit = new SQLTableElement(tableElement.getField("CREDIT"), Long.class, this.deviseCellEditor); |
list.add(this.credit); |
if (!DefaultNXProps.getInstance().getBooleanValue("HideAnalytique")) { |
if (!kd && !DefaultNXProps.getInstance().getBooleanValue("HideAnalytique")) { |
final AnalytiqueItemTable analytiqueAssocTable = new AnalytiqueItemTable(true); |
SQLTableElement eltPourcentAnalytique = new SQLTableElement(tableElement.getField("ANALYTIQUE"), String.class, |
new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable)); |
new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable)) { |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7")); |
}; |
}; |
list.add(eltPourcentAnalytique); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImportEcriturePanel.java |
---|
169,7 → 169,7 |
} |
} catch (Exception e) { |
if (e.getMessage().toLowerCase().contains("file format")) { |
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("file format")) { |
JOptionPane.showMessageDialog(ImportEcriturePanel.this, "Format de fichier non pris en charge"); |
} else { |
ExceptionHandler.handle(frame, "Erreur lors de la lecture du fichier " + fileToImport.getAbsolutePath(), e); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalItemTable.java |
---|
68,6 → 68,7 |
import javax.swing.JPanel; |
import javax.swing.JPopupMenu; |
import javax.swing.JScrollPane; |
import javax.swing.JTextField; |
import javax.swing.SwingConstants; |
import javax.swing.SwingUtilities; |
import javax.swing.ToolTipManager; |
94,7 → 95,7 |
private final JCheckBox boxAutoInsert; |
private boolean hideAnalytique = false; |
public SaisieJournalItemTable(final SQLRowValues defaultRowVals, JCheckBox boxAutoInsert) { |
public SaisieJournalItemTable(final SQLRowValues defaultRowVals, JCheckBox boxAutoInsert, final JTextField textField) { |
setLayout(new GridBagLayout()); |
this.boxAutoInsert = boxAutoInsert; |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
146,7 → 147,7 |
@Override |
public void actionPerformed(ActionEvent e) { |
montantValid(defaultRowVals, true); |
montantValid(defaultRowVals, true, textField); |
} |
}); |
final MultiLineTableCellEditor multiLineTableCellEditor = new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable); |
258,7 → 259,7 |
@Override |
public void keyPressed(KeyEvent e) { |
if (e.getKeyCode() == KeyEvent.VK_ENTER) { |
montantValid(defaultRowVals, false); |
montantValid(defaultRowVals, false, textField); |
} |
} |
}; |
472,7 → 473,7 |
return Tuple2.create(c.getTime(), lib); |
} |
public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique) { |
public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique, final JTextField textPiece) { |
System.err.println("Enter"); |
final SQLRowValues vals = SaisieJournalItemTable.this.table.getSelectedRowValues(); |
final int selectedRow = SaisieJournalItemTable.this.table.getSelectedRow(); |
483,7 → 484,7 |
if (SaisieJournalItemTable.this.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) { |
JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!"); |
} else { |
createSaisie(defaultRowVals); |
createSaisie(defaultRowVals, textPiece); |
} |
} else { |
if (!fromAnalytique && !hideAnalytique && vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) { |
517,11 → 518,12 |
} |
public synchronized void createSaisie(final SQLRowValues defaultRowVals) { |
public synchronized void createSaisie(final SQLRowValues defaultRowVals, JTextField pieceText) { |
Tuple2<Date, String> t = getDateAndLabelFromSaisie(); |
final Date d = t.get0(); |
final String lib = t.get1(); |
String pieceLabel = pieceText.getText(); |
final String lib = pieceLabel == null || pieceLabel.trim().length() == 0 ? t.get1() : pieceLabel; |
// Create saisieKM |
SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM")); |
536,12 → 538,17 |
table.updateField("ID_SAISIE_KM", id); |
table.clear(); |
GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id); |
gen.genereMouvement(); |
int idMvt = gen.genereMouvement(); |
// maj de l'id du mouvement correspondant |
SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM")); |
rowValsKMMvt.put("ID_MOUVEMENT", new Integer(idMvt)); |
rowValsKMMvt.update(id); |
defaultRowVals.put("NOM_PIECE", ""); |
defaultRowVals.put("NOM_ECRITURE", ""); |
table.getRowValuesTableModel().addNewRow(); |
pieceText.setText(""); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
/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/GrandLivrePanel.java |
---|
30,6 → 30,7 |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.users.rights.UserRightsManager; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.GestionDevise; |
import org.openconcerto.utils.TableSorter; |
42,7 → 43,6 |
import java.awt.event.MouseAdapter; |
import java.awt.event.MouseEvent; |
import java.util.List; |
import java.util.concurrent.ExecutionException; |
import javax.swing.AbstractAction; |
import javax.swing.BorderFactory; |
49,6 → 49,7 |
import javax.swing.JButton; |
import javax.swing.JFrame; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.JPopupMenu; |
import javax.swing.JScrollPane; |
111,7 → 112,7 |
// On recupere les differentes classes |
List<ClasseCompte> liste = ClasseCompte.getClasseCompte(); |
if (liste.size() != 0) { |
if (!liste.isEmpty()) { |
for (int k = 0; k < liste.size(); k++) { |
final ClasseCompte ccTmp = liste.get(k); |
119,9 → 120,7 |
new SwingWorker<JPanel, Object>() { |
@Override |
protected JPanel doInBackground() throws Exception { |
// TODO Auto-generated method stub |
return initClassePanel(ccTmp); |
} |
@Override |
129,9 → 128,7 |
JPanel initClassePanel; |
try { |
initClassePanel = get(); |
initClassePanel.setOpaque(false); |
final JScrollPane scrollPane = new JScrollPane(initClassePanel); |
scrollPane.setOpaque(false); |
scrollPane.setBorder(null); |
138,13 → 135,8 |
scrollPane.getViewport().setOpaque(false); |
// On créer les comptes de chaque classe |
GrandLivrePanel.this.tabbedClasse.addTab(ccTmp.getNom(), scrollPane); |
} catch (InterruptedException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} catch (ExecutionException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} catch (Exception e) { |
ExceptionHandler.handle("erreur " + ccTmp.getNom(), e); |
} |
fireLoading(false); |
super.done(); |
195,9 → 187,7 |
String function = "REGEXP"; |
String match = cc.getTypeNumeroCompte(); |
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) { |
// function = "SIMILAR TO"; |
function = "~"; |
// match = cc.getTypeNumeroCompte().replace(".*", "%"); |
} |
Where w = new Where(compteTable.getField("NUMERO"), function, match); |
219,12 → 209,11 |
JLabel labelTotalClasse = new JLabel(); |
labelTotalClasse.setOpaque(false); |
if (myList.size() != 0) { |
if (!myList.isEmpty()) { |
/*************************************************************************************** |
* Création des Panels de chaque compte |
**************************************************************************************/ |
// c.weighty = 1; |
for (int i = 0; i < myList.size(); i++) { |
Object[] objTmp = (Object[]) myList.get(i); |
285,7 → 274,6 |
// Total du Compte |
JLabel labelCompteDebit = new JLabel("Total Debit : " + GestionDevise.currencyToString(compte.getTotalDebit())); |
JLabel labelCompteCredit = new JLabel(" Credit : " + GestionDevise.currencyToString(compte.getTotalCredit())); |
// labelCompte.setFont(new Font(labelCompte.getFont().getFontName(), Font.BOLD, 12)); |
labelCompteDebit.setHorizontalAlignment(SwingUtilities.LEFT); |
labelCompteCredit.setHorizontalAlignment(SwingUtilities.LEFT); |
305,18 → 293,18 |
public void actionPerformed(ActionEvent e) { |
System.err.println(this.isShow); |
// Afficher la JTable du compte |
if (!this.isShow) { |
// if (this.scroll == null) { |
System.err.println(compte); |
JTable tableCpt = createJTableCompte(compte); |
if (tableCpt == null) { |
JOptionPane.showMessageDialog(GrandLivrePanel.this, "Aucune écriture"); |
return; |
} else { |
this.scroll = new JScrollPane(tableCpt); |
// calcul de la taille du JScrollPane |
Dimension d; |
System.err.println(tableCpt); |
if (tableCpt.getPreferredSize().height > 200) { |
d = new Dimension(this.scroll.getPreferredSize().width, 200); |
} else { |
330,20 → 318,14 |
c.fill = GridBagConstraints.HORIZONTAL; |
c.anchor = GridBagConstraints.NORTHWEST; |
panelCompte.add(this.scroll, c); |
/* |
* } else { this.scroll.setVisible(true); } |
*/ |
} |
} else { |
// if (this.scroll != null) { |
if (this.scroll != null) { |
panelCompte.remove(this.scroll); |
System.out.println("Hide scrollPane"); |
// this.scroll.setVisible(false); |
// this.scroll.repaint(); |
} |
panelCompte.repaint(); |
panelCompte.revalidate(); |
// } |
} |
this.isShow = !this.isShow; |
376,7 → 358,7 |
// Gestion de la souris sur la JTable |
tableTmp.addMouseListener(new MouseAdapter() { |
@Override |
public void mousePressed(final MouseEvent mE) { |
if (mE.getButton() == MouseEvent.BUTTON3) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/AnalytiqueItemTable.java |
---|
13,6 → 13,7 |
package org.openconcerto.erp.core.finance.accounting.ui; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.core.common.ui.DeviseCellEditor; |
import org.openconcerto.erp.core.common.ui.RowValuesMultiLineEditTable; |
import org.openconcerto.sql.Configuration; |
151,6 → 152,7 |
@Override |
public void tableChanged(TableModelEvent e) { |
long totalReparti = 0; |
// TODO Gestion répartition multi axe |
if (totalArepartir != 0) { |
for (int i = 0; i < model.getRowCount(); i++) { |
totalReparti += model.getRowValuesAt(i).getLong("MONTANT"); |
158,10 → 160,11 |
getDefaultRowValues().put("POURCENT", new BigDecimal(totalReparti).divide(new BigDecimal(totalArepartir), DecimalUtils.HIGH_PRECISION).setScale(6, RoundingMode.HALF_UP)); |
getDefaultRowValues().put("MONTANT", totalArepartir - totalReparti); |
} |
buttonValider.setEnabled(totalReparti == totalArepartir); |
} else { |
buttonValider.setEnabled(true); |
} |
} |
}); |
final RowValuesMultiLineEditTable multiTable = (RowValuesMultiLineEditTable) this.table; |
buttonValider.addActionListener(new ActionListener() { |
/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/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/SuppressionEcrituresPanel.java |
---|
22,7 → 22,6 |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.warning.JLabelWarning; |
import org.openconcerto.utils.ExceptionHandler; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
60,7 → 59,7 |
// TODO afficher les numeros de mouvement implique |
int[] idS = getMouvement(rowMvt.getInt("ID_PIECE")); |
if (idS == null) { |
ExceptionHandler.handle("Aucun mouvement associé à la piéce n°" + ((rowMvt != null) ? rowMvt.getInt("ID_PIECE") : "mouvement nul")); |
JOptionPane.showMessageDialog(null, "Aucun mouvement associé à la piéce n°" + ((rowMvt != null) ? rowMvt.getInt("ID_PIECE") : "mouvement nul")); |
} else { |
StringBuffer s = new StringBuffer(); |
s.append("Elle est composée par les mouvements : ("); |
115,19 → 114,19 |
SQLBase b = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
SQLTable tableMvt = b.getTable("MOUVEMENT"); |
SQLSelect sel = new SQLSelect(b); |
SQLSelect sel = new SQLSelect(); |
sel.addSelect(tableMvt.getField("NUMERO")); |
sel.setWhere(tableMvt.getField("ID_PIECE"), "=", idPiece); |
List l = (List) b.getDataSource().execute(sel.asString(), new ArrayListHandler()); |
if (l.size() > 0) { |
if (!l.isEmpty()) { |
idS = new int[l.size()]; |
} |
for (int i = 0; i < l.size(); i++) { |
Object[] tmp = (Object[]) l.get(i); |
idS[i] = Integer.parseInt(tmp[0].toString()); |
idS[i] = ((Number) tmp[0]).intValue(); |
} |
return idS; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteGestCommPreferencePanel.java |
---|
24,6 → 24,7 |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.request.SQLFieldTranslator; |
import org.openconcerto.sql.sqlobject.ElementComboBox; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.TitledSeparator; |
36,7 → 37,9 |
import javax.swing.JCheckBox; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.SwingUtilities; |
public class CompteGestCommPreferencePanel extends DefaultPreferencePanel { |
338,7 → 341,14 |
DefaultNXProps.getInstance().setProperty("HideAnalytique", String.valueOf(this.checkHideAnalytique.isSelected())); |
DefaultNXProps.getInstance().store(); |
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/model/CurrencyConverter.java |
---|
22,6 → 22,8 |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.utils.DecimalUtils; |
import org.openconcerto.utils.Tuple2; |
import org.openconcerto.utils.Tuple3; |
import java.math.BigDecimal; |
import java.util.ArrayList; |
28,13 → 30,15 |
import java.util.Arrays; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
import java.util.TimeZone; |
public class CurrencyConverter { |
private String companyCurrencyCode; |
private final DBRoot root; |
private boolean useCache = false; |
private String baseCurrencyCode; |
public CurrencyConverter(DBRoot rootSociete, String companyCurrencyCode, String baseCurrencyCode) { |
59,6 → 63,10 |
return baseCurrencyCode; |
} |
public void setUseCache(boolean useCache) { |
this.useCache = useCache; |
} |
/** |
* Converter an amount to an other currency |
*/ |
73,6 → 81,14 |
return convert(amount, from, to, date, false); |
} |
Map<Tuple3<String, String, Date>, Tuple2<BigDecimal, BigDecimal>> cacheBiased = new HashMap<Tuple3<String, String, Date>, Tuple2<BigDecimal, BigDecimal>>(); |
Map<Tuple3<String, String, Date>, Tuple2<BigDecimal, BigDecimal>> cacheNotBiased = new HashMap<Tuple3<String, String, Date>, Tuple2<BigDecimal, BigDecimal>>(); |
public void clearCache() { |
cacheBiased.clear(); |
cacheNotBiased.clear(); |
} |
/** |
* Converter an amount to an other currency at a precise date |
*/ |
82,6 → 98,27 |
return amount; |
} |
if (amount.signum() == 0) { |
return BigDecimal.ZERO; |
} |
BigDecimal r1 = null; |
BigDecimal r2 = null; |
if (useCache) { |
Tuple3<String, String, Date> key = Tuple3.create(from, to, date); |
if (useBiased && cacheBiased.containsKey(key)) { |
Tuple2<BigDecimal, BigDecimal> value = cacheBiased.get(key); |
r1 = value.get0(); |
r2 = value.get1(); |
} else if (!useBiased && cacheNotBiased.containsKey(key)) { |
Tuple2<BigDecimal, BigDecimal> value = cacheNotBiased.get(key); |
r1 = value.get0(); |
r2 = value.get1(); |
} |
} |
if (r1 == null || r2 == null) { |
// Clean date |
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); |
c.setTimeInMillis(date.getTime()); |
94,39 → 131,17 |
// Get conversion info |
final List<SQLRow> rowsFrom = getRates(from, d); |
final List<SQLRow> rowsTo = getRates(to, d); |
BigDecimal r1 = null; |
BigDecimal r2 = null; |
// Récupération des taux par défaut dans DEVISE si aucun taux dans l'historique |
List<SQLRow> rowsDevise = new ArrayList<SQLRow>(); |
if (rowsTo.isEmpty() || rowsFrom.isEmpty()) { |
SQLSelect sel = new SQLSelect(); |
sel.addSelectStar(root.findTable("DEVISE")); |
rowsDevise.addAll(SQLRowListRSH.execute(sel)); |
} |
if (rowsTo.isEmpty()) { |
for (SQLRow sqlRow : rowsDevise) { |
if (sqlRow.getString("CODE").equalsIgnoreCase(to)) { |
r2 = (useBiased ? sqlRow.getBigDecimal("TAUX_COMMERCIAL") : sqlRow.getBigDecimal("TAUX")); |
} |
} |
} |
if (rowsFrom.isEmpty()) { |
for (SQLRow sqlRow : rowsDevise) { |
if (sqlRow.getString("CODE").equalsIgnoreCase(from)) { |
r1 = (useBiased ? sqlRow.getBigDecimal("TAUX_COMMERCIAL") : sqlRow.getBigDecimal("TAUX")); |
} |
} |
} |
List<SQLRow> rows = new ArrayList<SQLRow>(); |
rows.addAll(rowsTo); |
rows.addAll(rowsFrom); |
// Pour le taux réel, on récupére celui de la veille |
for (SQLRow sqlRow : rows) { |
if (sqlRow.getString("DST").equals(from)) { |
if (useBiased) { |
if (r1 == null) { |
r1 = sqlRow.getBigDecimal("TAUX_COMMERCIAL"); |
} |
} else { |
r1 = sqlRow.getBigDecimal("TAUX"); |
} |
133,7 → 148,9 |
} |
if (sqlRow.getString("DST").equals(to)) { |
if (useBiased) { |
if (r2 == null) { |
r2 = sqlRow.getBigDecimal("TAUX_COMMERCIAL"); |
} |
} else { |
r2 = sqlRow.getBigDecimal("TAUX"); |
} |
145,12 → 162,47 |
if (to.equals(this.baseCurrencyCode)) { |
r2 = BigDecimal.ONE; |
} |
if (r1 == null || r2 == null) { |
// Récupération des taux par défaut dans DEVISE si aucun taux dans l'historique |
List<SQLRow> rowsDevise = new ArrayList<SQLRow>(); |
if (rowsTo.isEmpty() || rowsFrom.isEmpty()) { |
SQLSelect sel = new SQLSelect(); |
sel.addSelectStar(root.findTable("DEVISE")); |
rowsDevise.addAll(SQLRowListRSH.execute(sel)); |
} |
if (r2 == null) { |
for (SQLRow sqlRow : rowsDevise) { |
if (sqlRow.getString("CODE").equalsIgnoreCase(to)) { |
r2 = (useBiased ? sqlRow.getBigDecimal("TAUX_COMMERCIAL") : sqlRow.getBigDecimal("TAUX")); |
} |
} |
} |
if (r1 == null) { |
for (SQLRow sqlRow : rowsDevise) { |
if (sqlRow.getString("CODE").equalsIgnoreCase(from)) { |
r1 = (useBiased ? sqlRow.getBigDecimal("TAUX_COMMERCIAL") : sqlRow.getBigDecimal("TAUX")); |
} |
} |
} |
} |
} |
if (r1 == null) { |
throw new IllegalStateException("No conversion rate for " + from); |
} |
if (r2 == null) { |
throw new IllegalStateException("No conversion rate for " + to); |
} |
if (useCache) { |
Tuple3<String, String, Date> key = Tuple3.create(from, to, date); |
if (useBiased) { |
cacheBiased.put(key, Tuple2.create(r1, r2)); |
} else { |
cacheNotBiased.put(key, Tuple2.create(r1, r2)); |
} |
} |
final BigDecimal result = amount.multiply(r2, DecimalUtils.HIGH_PRECISION).divide(r1, DecimalUtils.HIGH_PRECISION); |
return result; |
} |
164,6 → 216,7 |
w = w.and(new Where(t.getField("DATE"), "<= |