OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 174 → Rev 173

/trunk/OpenConcerto/.classpath
16,6 → 16,7
<classpathentry exported="true" kind="lib" path="lib/ognl-2.6.5.jar"/>
<classpathentry exported="true" kind="lib" path="lib/resolver.jar"/>
<classpathentry exported="true" kind="lib" path="lib/RXTXcomm.jar"/>
<classpathentry exported="true" kind="lib" path="lib/poi-3.8-beta3-20110606.jar"/>
<classpathentry kind="lib" path="lib/jcip-annotations.jar"/>
<classpathentry kind="lib" path="lib/fb-annotations-2.0.0.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-dbcp-1.4.jar"/>
43,6 → 44,5
<classpathentry kind="lib" path="lib/mysql-connector-java-5.1.40-bin.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="lib" path="lib/postgresql-42.2.2.jre7.jar"/>
<classpathentry kind="lib" path="lib/poi-3.17.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
/trunk/OpenConcerto/lib/jOpenDocument-1.4rc2.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/jOpenCalendar.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/jopendocument/link/OOConnexion.java
84,14 → 84,8
perms.add(new RuntimePermission("modifyThread"));
// needed by PrinterJob.getPrinterJob()
perms.add(new RuntimePermission("queuePrintJob"));
 
// ProcessBuilder.start() calls SecurityManager.checkExec() which requires
// absolute path (or execute on "<<ALL FILES>>")
 
// needed by OOConnexion.init() to find the port
perms.add(new FilePermission("/usr/bin/lsof", "execute"));
// macOS path
perms.add(new FilePermission("/usr/sbin/lsof", "execute"));
perms.add(new FilePermission("/bin/ps", "execute"));
perms.add(new FilePermission("C:/Windows/System32/tasklist.exe", "execute"));
perms.add(new RuntimePermission("getenv.*"));
/trunk/OpenConcerto/src/org/jopendocument/link/OOInstallation.java
102,14 → 102,10
rootPaths.addAll(Arrays.asList(loRootPaths));
rootPaths.addAll(Arrays.asList(ooRootPaths));
}
 
for (final String p : rootPaths) {
// On force à chercher dans le registre 64 bits sinon il va chercher dans le registre 32
// bits si os 64b et VM 32b
if (DesktopEnvironment.test("reg", "query", p, "/reg:64"))
if (DesktopEnvironment.test("reg", "query", p))
return p;
}
 
return null;
}
 
127,8 → 123,7
// all string values for the passed registry path
private static Map<String, String> getStringValues(final String path, final String option) throws IOException {
final Map<String, String> values = new HashMap<String, String>();
// On force /reg:64 (utile si on utilise une VM 32 avec un systeme 64 bits)
final String out = DesktopEnvironment.cmdSubstitution(Runtime.getRuntime().exec(new String[] { "reg", "query", path, option, "/reg:64" }));
final String out = DesktopEnvironment.cmdSubstitution(Runtime.getRuntime().exec(new String[] { "reg", "query", path, option }));
final Matcher matcher = stringValuePattern.matcher(out);
while (matcher.find()) {
values.put(matcher.group(1), matcher.group(2));
/trunk/OpenConcerto/src/org/openconcerto/openoffice/ODPackage.java
17,9 → 17,7
import static org.openconcerto.openoffice.ODPackage.RootElement.META;
import static org.openconcerto.openoffice.ODPackage.RootElement.STYLES;
 
import org.openconcerto.openoffice.spreadsheet.CellStyle;
import org.openconcerto.openoffice.spreadsheet.SpreadSheet;
import org.openconcerto.openoffice.style.data.DataStyle;
import org.openconcerto.openoffice.text.TextDocument;
import org.openconcerto.utils.CopyUtils;
import org.openconcerto.utils.ExceptionUtils;
50,7 → 48,6
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
60,7 → 57,6
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
73,7 → 69,6
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
 
382,7 → 377,6
private ODMeta meta;
private File file;
private ODDocument doc;
private Locale locale;
 
public ODPackage() {
this.files = new HashMap<String, ODPackageEntry>();
408,19 → 402,16
protected void processEntry(ZipEntry entry, InputStream in) throws IOException {
final String name = entry.getName();
final Object res;
out.reset();
StreamUtils.copy(in, out);
if (subdocNames.contains(name)) {
try {
final SAXBuilder builder = OOUtils.getBuilder();
// bytes are read fully first in order to be compatible
// with SAXParser like Piccolo
res = builder.build(new ByteArrayInputStream(out.toByteArray()));
res = OOUtils.getBuilder().build(in);
} catch (JDOMException e) {
// always correct
throw new IllegalStateException("parse error on " + name, e);
throw new IllegalStateException("parse error", e);
}
} else {
out.reset();
StreamUtils.copy(in, out);
res = out.toByteArray();
}
// we don't know yet the types
588,39 → 579,6
this.setContentType(newType);
}
 
public final void setLocale(Locale locale) {
this.locale = locale;
}
 
// http://help.libreoffice.org/Common/Selecting_the_Document_Language
// The document language is set by default-style/text-properties and is not used for formatting.
// The formatting used to fill cell content is set by the editor application not read from the
// document.
public final Locale getLocale() {
return this.locale == null ? Locale.getDefault() : this.locale;
}
 
public final String formatNumber(Number n, final CellStyle defaultStyle) {
return formatNumber(NumberFormat.getNumberInstance(getLocale()), n, defaultStyle);
}
 
public final String formatPercent(Number n, final CellStyle defaultStyle) {
return formatNumber(NumberFormat.getPercentInstance(getLocale()), n, defaultStyle);
}
 
public final String formatCurrency(Number n, final CellStyle defaultStyle) {
return formatNumber(NumberFormat.getCurrencyInstance(getLocale()), n, defaultStyle);
}
 
private final String formatNumber(NumberFormat format, Number n, final CellStyle defaultStyle) {
synchronized (format) {
final int decPlaces = DataStyle.getDecimalPlaces(defaultStyle);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(decPlaces);
return format.format(n);
}
}
 
/**
* Call {@link Validator#isValid()} on each XML subdocuments.
*
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/cellFormat.fods
File deleted
\ No newline at end of file
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/DateStyle.java
54,7 → 54,7
return !"long".equals(elem.getAttributeValue("style", elem.getNamespace("number")));
}
 
static final Locale getElementLocale(final Element elem) {
public static final Locale getLocale(final Element elem) {
final Locale res;
final String country = elem.getAttributeValue("country", elem.getNamespace());
final String lang = elem.getAttributeValue("language", elem.getNamespace());
61,7 → 61,7
if (lang != null) {
res = new Locale(lang, country == null ? "" : country);
} else {
res = null;
res = Locale.getDefault();
}
return res;
}
123,7 → 123,7
public String format(Object o, CellStyle defaultStyle, boolean lenient) {
final Date d = o instanceof Calendar ? ((Calendar) o).getTime() : (Date) o;
final Namespace numberNS = this.getElement().getNamespace();
final Locale styleLocale = this.getLocale();
final Locale styleLocale = getLocale(getElement());
final Calendar styleCalendar = Calendar.getInstance(styleLocale);
final StringBuilder res = new StringBuilder();
 
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/TimeStyle.java
69,7 → 69,7
final Namespace numberNS = this.getElement().getNamespace();
final StringBuilder sb = new StringBuilder();
 
final Locale styleLocale = this.getLocale();
final Locale styleLocale = DateStyle.getLocale(getElement());
final boolean truncate = StyleProperties.parseBoolean(getElement().getAttributeValue("truncate-on-overflow", numberNS), true);
@SuppressWarnings("unchecked")
final List<Element> children = this.getElement().getChildren();
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/BooleanStyle.java
66,7 → 66,7
public String format(Object o, CellStyle defaultStyle, boolean lenient) {
final Boolean b = (Boolean) o;
final Namespace numberNS = this.getElement().getNamespace();
final Locale styleLocale = this.getLocale();
final Locale styleLocale = DateStyle.getLocale(getElement());
final StringBuilder sb = new StringBuilder();
@SuppressWarnings("unchecked")
final List<Element> children = this.getElement().getChildren();
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/NumberStyle.java
18,6 → 18,7
import org.openconcerto.openoffice.ODValueType;
import org.openconcerto.openoffice.XMLVersion;
import org.openconcerto.openoffice.spreadsheet.CellStyle;
import org.openconcerto.openoffice.spreadsheet.MutableCell;
 
import java.util.Calendar;
import java.util.Date;
88,7 → 89,7
} else if (elem.getName().equals("fraction")) {
// TODO fractions
reportError("Fractions not supported", lenient);
sb.append(getPackage().formatNumber(n, defaultStyle));
sb.append(MutableCell.formatNumber(n, defaultStyle));
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/DataStyle.java
27,12 → 27,10
 
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
47,11 → 45,7
// from section 16.27 in v1.2-cs01-part1
public abstract class DataStyle extends Style {
private static final int DEFAULT_GROUPING_SIZE = new DecimalFormat().getGroupingSize();
// 15 as of LibreOffice 6, was 10 earlier
/**
* The default number of decimal digits if neither defined in the style nor in default-style.
*/
public static final int DEFAULT_DECIMAL_PLACES = Integer.parseInt(System.getProperty("openDocument.defaultDecimalPlaces", "15"));
public static final int DEFAULT_DECIMAL_PLACES = 10;
private static final Pattern QUOTE_PATRN = Pattern.compile("'", Pattern.LITERAL);
private static final Pattern EXP_PATTERN = Pattern.compile("E(\\d+)$");
 
91,7 → 85,8
super(clazz, version, elemName, baseName);
this.setElementNS(getVersion().getNS("number"));
// from 19.469 in v1.2-cs01-part1
this.getRefElementsMap().addAll("style:data-style-name",
this.getRefElementsMap().addAll(
"style:data-style-name",
Arrays.asList("presentation:date-time-decl", "style:style", "text:creation-date", "text:creation-time", "text:database-display", "text:date", "text:editing-duration",
"text:expression", "text:meta-field", "text:modification-date", "text:modification-time", "text:print-date", "text:print-time", "text:table-formula", "text:time",
"text:user-defined", "text:user-field-get", "text:user-field-input", "text:variable-get", "text:variable-input", "text:variable-set"));
181,15 → 176,6
throw new UnsupportedOperationException(msg);
}
 
public final Locale getLocale() {
return this.getLocale(this.getElement());
}
 
protected final Locale getLocale(final Element elem) {
final Locale res = DateStyle.getElementLocale(elem);
return res != null ? res : this.getPackage().getLocale();
}
 
protected final String formatNumberOrScientificNumber(final Element elem, final Number n, CellStyle defaultStyle) {
return this.formatNumberOrScientificNumber(elem, n, 1, defaultStyle);
}
257,9 → 243,7
numberSB.append('0');
}
 
final DecimalFormatSymbols symbols = new DecimalFormatSymbols(this.getLocale());
 
final DecimalFormat decFormat = new DecimalFormat(numberSB.toString(), symbols);
final DecimalFormat decFormat = new DecimalFormat(numberSB.toString());
// Java always use HALF_EVEN
decFormat.setRoundingMode(RoundingMode.HALF_UP);
decFormat.setGroupingUsed(grouping);
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/CurrencyStyle.java
63,7 → 63,7
if (elem.getTextTrim().length() > 0) {
sb.append(elem.getText());
} else {
sb.append(new DecimalFormatSymbols(this.getLocale(elem)).getCurrencySymbol());
sb.append(new DecimalFormatSymbols(DateStyle.getLocale(elem)).getCurrencySymbol());
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/cellFormat.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/openconcerto/openoffice/style/data/cellFormat.ods
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/src/org/openconcerto/openoffice/generation/view/BaseGenerationRapport.java
93,7 → 93,7
private JComboBox<FileAction> fileActionCombo;
 
private JList<GenerationTask> tasksView;
private final JLabel status;
private JLabel status;
 
// le groupe dans lequel doivent être toutes les thread de la génération
private final ThreadGroup thg;
100,7 → 100,7
 
public BaseGenerationRapport() throws JDOMException, IOException {
this.thg = new ThreadGroup(this + " thread group");
this.status = new JLabel();
this.uiInit();
this.setStatus("Inactif");
}
 
112,7 → 112,7
return null;
}
 
protected final void uiInit() throws JDOMException, IOException {
private void uiInit() throws JDOMException, IOException {
setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.ipadx = 40;
171,6 → 171,7
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
this.status = new JLabel();
this.add(this.status, c);
 
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/MutableCell.java
24,6 → 24,7
import org.openconcerto.openoffice.spreadsheet.CellStyle.StyleTableCellProperties;
import org.openconcerto.openoffice.style.data.BooleanStyle;
import org.openconcerto.openoffice.style.data.DataStyle;
import org.openconcerto.openoffice.style.data.DateStyle;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.TimeUtils;
import org.openconcerto.utils.TimeUtils.DurationNullsChanger;
62,7 → 63,31
static private final DateFormat TextPDateFormat = DateFormat.getDateInstance();
static private final DateFormat TextPTimeFormat = DateFormat.getTimeInstance();
static private final NumberFormat TextPMinuteSecondFormat = new DecimalFormat("00.###");
static private final NumberFormat TextPFloatFormat = DecimalFormat.getNumberInstance();
static private final NumberFormat TextPPercentFormat = DecimalFormat.getPercentInstance();
static private final NumberFormat TextPCurrencyFormat = DecimalFormat.getCurrencyInstance();
 
static public String formatNumber(Number n, final CellStyle defaultStyle) {
return formatNumber(TextPFloatFormat, n, defaultStyle);
}
 
static public String formatPercent(Number n, final CellStyle defaultStyle) {
return formatNumber(TextPPercentFormat, n, defaultStyle);
}
 
static public String formatCurrency(Number n, final CellStyle defaultStyle) {
return formatNumber(TextPCurrencyFormat, n, defaultStyle);
}
 
static private String formatNumber(NumberFormat format, Number n, final CellStyle defaultStyle) {
synchronized (format) {
final int decPlaces = DataStyle.getDecimalPlaces(defaultStyle);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(decPlaces);
return format.format(n);
}
}
 
static private boolean LO_MODE = true;
// no date part, all time part to zero
static private final DurationNullsChanger TIME_NULLS = new TimeUtils.DurationNullsBuilder(TimeUtils.EmptyFieldPolicy.SET_TO_ZERO).setToNull(TimeUtils.getDateFields()).build();
216,11 → 241,11
} else {
// either there were no format or formatting failed
if (vt == ODValueType.FLOAT) {
text = getODDocument().getPackage().formatNumber((Number) obj, getDefaultStyle());
text = formatNumber((Number) obj, getDefaultStyle());
} else if (vt == ODValueType.PERCENTAGE) {
text = getODDocument().getPackage().formatPercent((Number) obj, getDefaultStyle());
text = formatPercent((Number) obj, getDefaultStyle());
} else if (vt == ODValueType.CURRENCY) {
text = getODDocument().getPackage().formatCurrency((Number) obj, getDefaultStyle());
text = formatCurrency((Number) obj, getDefaultStyle());
} else if (vt == ODValueType.DATE) {
final Date d;
if (obj instanceof Calendar) {
237,15 → 262,16
text = TextPTimeFormat.format(((Calendar) obj).getTime());
}
} else if (vt == ODValueType.BOOLEAN) {
Locale l = null;
// LO do not use the the document language but the system language
// http://help.libreoffice.org/Common/Selecting_the_Document_Language
Locale l = Locale.getDefault();
// except of course if there's a data style
final CellStyle s = getStyle();
if (s != null) {
final DataStyle ds = s.getDataStyle();
if (ds != null)
l = ds.getLocale();
l = DateStyle.getLocale(ds.getElement());
}
if (l == null)
l = getODDocument().getPackage().getLocale();
text = BooleanStyle.toString((Boolean) obj, l, lenient);
} else if (vt == ODValueType.STRING) {
text = obj.toString();
/trunk/OpenConcerto/src/org/openconcerto/ui/ColorField.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/grid/GridListener.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/grid/DecoratedGridPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/grid/GridItem.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/grid/GridPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/grid/TwoYearsHeaderPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/state/AbstractStateManager.java
13,8 → 13,6
package org.openconcerto.ui.state;
 
import org.openconcerto.utils.FileUtils;
 
import java.io.File;
import java.io.IOException;
import java.security.AccessController;
85,7 → 83,10
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws IOException {
FileUtils.mkParentDirs(file);
if (file.getParentFile() != null && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
 
writeState(file);
return null;
}
/trunk/OpenConcerto/src/org/openconcerto/ui/touch/ScrollableList.java
62,8 → 62,7
 
private boolean hasScrolled;
 
private List<ListSelectionListener> selectionListeners = new ArrayList<>();
private List<ActionListener> actionListeners = new ArrayList<>();
private List<ListSelectionListener> selectionListeners = new ArrayList<ListSelectionListener>();
 
public ScrollableList(ListModel model) {
a = new ScrollAnimator(this);
203,7 → 202,6
} else {
scrollToOffset(targetOffset);
}
fireActionPerformed();
}
 
public void setSelectedIndex(int index) {
378,18 → 376,6
}
}
 
public void addActionListener(ActionListener listener) {
this.actionListeners.add(listener);
}
 
private void fireActionPerformed() {
int size = this.actionListeners.size();
for (int i = 0; i < size; i++) {
this.actionListeners.get(i).actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "click"));
}
 
}
 
@Override
public void contentsChanged(ListDataEvent e) {
this.offsetY = 0;
/trunk/OpenConcerto/src/org/openconcerto/ui/table/CloseTableHeaderRenderer.java
82,7 → 82,7
header.setReorderingAllowed(false);
this.editedTable = table;
this.editedColumn = column;
this.label.setText(String.valueOf(value));
this.label.setText(value.toString());
this.header.removeMouseListener(this);
this.header.addMouseListener(this);
return this;
/trunk/OpenConcerto/src/org/openconcerto/ui/table/IconTableCellRenderer.java
98,7 → 98,7
 
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null) {
// JTable$AccessibleJTable.getAccessibleChild()
// Bug remonté sur Linux
value = Integer.valueOf(0);
}
int val = ((Integer) value).intValue();
/trunk/OpenConcerto/src/org/openconcerto/ui/light/UserSearchItem.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/light/UserSearch.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/light/TableSearchParameter.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/light/TableSearchParameterType.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUIHTMLStrippedPanel.java
20,9 → 20,6
 
public class LightUIHTMLStrippedPanel extends LightUIPanel implements Transferable, HTMLable {
 
public LightUIHTMLStrippedPanel() {
}
 
public LightUIHTMLStrippedPanel(String id) {
super(id);
this.setType(LightUIElement.TYPE_RAW_HTML);
37,6 → 34,11
}
 
@Override
public LightUIElement clone() {
return new LightUIHTMLStrippedPanel(this);
}
 
@Override
public String getHTML() {
final StringBuilder b = new StringBuilder();
for (int i = 0; i < this.getChildrenCount(); i++) {
/trunk/OpenConcerto/src/org/openconcerto/ui/light/SearchContent.java
New file
0,0 → 1,81
/*
* 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.ui.light;
 
import org.openconcerto.utils.io.Transferable;
import net.minidev.json.JSONObject;
 
public class SearchContent implements Transferable {
 
private String column;
private String text;
private String type;
private String operator;
 
public SearchContent(final JSONObject json) {
this.fromJSON(json);
}
 
public String getColumn() {
return this.column;
}
 
public String getText() {
return this.text;
}
 
public String getType() {
return this.type;
}
 
public String getOperator() {
return this.operator;
}
 
@Override
public JSONObject toJSON() {
final JSONObject json = new JSONObject();
json.put("column", this.column);
json.put("text", this.text);
json.put("type", this.type);
json.put("operator", this.operator);
return json;
}
 
@Override
public void fromJSON(final JSONObject json) {
if (!json.containsKey("column") || !(json.get("column") instanceof String)) {
throw new IllegalArgumentException("value for 'column' not found or invalid");
}
if (!json.containsKey("text") || !(json.get("text") instanceof String)) {
throw new IllegalArgumentException("value for 'text' not found or invalid");
}
if (!json.containsKey("type") || !(json.get("type") instanceof String)) {
throw new IllegalArgumentException("value for 'type' not found or invalid");
}
if (json.containsKey("operator")) {
if (json.get("operator") != null) {
if (!(json.get("operator") instanceof String)) {
throw new IllegalArgumentException("value for 'operator' not found or invalid");
} else {
this.operator = (String) json.get("operator");
}
}
}
 
this.column = (String) json.get("column");
this.text = (String) json.get("text");
this.type = (String) json.get("type");
}
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/TableSpec.java
16,19 → 16,19
import org.openconcerto.utils.io.JSONConverter;
import org.openconcerto.utils.io.Transferable;
 
import java.util.ArrayList;
import java.util.List;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
 
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
 
public class TableSpec implements Transferable {
public class TableSpec implements Transferable, Externalizable {
private String id;
private ColumnsSpec columns;
private TableContent content;
private RowSelectionSpec selection;
private List<TableSearchParameter> searchParameters = new ArrayList<>();
private UserSearch search;
private SearchSpec search;
private Boolean variableColumnsCount = false;
 
public TableSpec() {
84,11 → 84,11
this.selection = selection;
}
 
public UserSearch getSearch() {
public SearchSpec getSearch() {
return this.search;
}
 
public void setSearch(final UserSearch search) {
public void setSearch(final SearchSpec search) {
this.search = search;
}
 
100,14 → 100,6
this.variableColumnsCount = variableColumnsCount;
}
 
public void addSearchParameter(TableSearchParameter p) {
this.searchParameters.add(p);
}
 
public void removeSearchParameter(TableSearchParameter p) {
this.searchParameters.remove(p);
}
 
@Override
public JSONObject toJSON() {
final JSONObject result = new JSONObject();
122,7 → 114,6
if (this.selection != null) {
result.put("selection", JSONConverter.getJSON(this.selection));
}
 
if (this.search != null) {
result.put("search", JSONConverter.getJSON(this.search));
}
130,30 → 121,23
result.put("variable-columns-count", JSONConverter.getJSON(true));
}
 
if (!this.searchParameters.isEmpty()) {
JSONArray a = new JSONArray();
for (TableSearchParameter p : this.searchParameters) {
a.add(p.toJSON());
}
result.put("search-params", a);
}
return result;
}
 
@Override
public void fromJSON(final JSONObject json) {
this.id = json.getAsString("id");
this.id = (String) JSONConverter.getParameterFromJSON(json, "id", String.class);
 
final JSONObject jsonColumns = JSONConverter.getParameterFromJSON(json, "columns", JSONObject.class);
final JSONObject jsonColumns = (JSONObject) JSONConverter.getParameterFromJSON(json, "columns", JSONObject.class);
if (jsonColumns != null) {
this.columns = new ColumnsSpec(jsonColumns);
}
 
final JSONObject jsonContent = JSONConverter.getParameterFromJSON(json, "content", JSONObject.class);
final JSONObject jsonContent = (JSONObject) JSONConverter.getParameterFromJSON(json, "content", JSONObject.class);
if (jsonContent != null) {
this.content = new TableContent(jsonContent);
}
final JSONObject jsonSelection = JSONConverter.getParameterFromJSON(json, "selection", JSONObject.class);
final JSONObject jsonSelection = (JSONObject) JSONConverter.getParameterFromJSON(json, "selection", JSONObject.class);
if (jsonSelection != null) {
this.selection = new RowSelectionSpec(jsonSelection);
} else {
160,22 → 144,39
throw new IllegalArgumentException("null selection");
}
 
final JSONObject jsonSearch = JSONConverter.getParameterFromJSON(json, "search", JSONObject.class);
final JSONObject jsonSearch = (JSONObject) JSONConverter.getParameterFromJSON(json, "search", JSONObject.class);
if (jsonSearch != null) {
this.search = new UserSearch(jsonSearch);
this.search = new SearchSpec(jsonSearch);
}
 
this.variableColumnsCount = JSONConverter.getParameterFromJSON(json, "variable-columns-count", Boolean.class);
this.searchParameters.clear();
if (json.containsKey("search-params")) {
final JSONArray array = (JSONArray) json.get("search-params");
for (Object o : array) {
final TableSearchParameter p = new TableSearchParameter();
p.fromJSON((JSONObject) o);
this.searchParameters.add(p);
this.variableColumnsCount = (Boolean) JSONConverter.getParameterFromJSON(json, "variable-columns-count", Boolean.class);
}
 
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(id);
this.columns.writeExternal(out);
this.content.writeExternal(out);
 
this.selection.writeExternal(out);
this.search.writeExternal(out);
 
out.writeBoolean(this.variableColumnsCount);
 
}
 
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id = in.readUTF();
this.columns = new ColumnsSpec();
this.columns.readExternal(in);
this.content = new TableContent();
this.content.readExternal(in);
this.selection = new RowSelectionSpec();
this.selection.readExternal(in);
this.search = new SearchSpec();
this.search.readExternal(in);
this.variableColumnsCount = in.readBoolean();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUITable.java
18,6 → 18,10
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
 
29,7 → 33,7
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
 
public class LightUITable extends LightUserControlContainer {
public class LightUITable extends LightUserControlContainer implements Externalizable {
 
public static final int DEFAULT_LINE_HEIGHT = 40;
 
45,7 → 49,7
private Boolean autoSelectFirstLine = true;
private TableSpec tableSpec = null;
 
private transient List<ActionListener> selectionListeners = new ArrayList<>();
private transient List<ActionListener> selectionListeners = new ArrayList<ActionListener>();
 
// Nombre de ligne à afficher par Row
private int linePerRow = 1;
77,8 → 81,10
 
final RowSelectionSpec selection = new RowSelectionSpec(this.getId());
final ColumnsSpec columnsSpec = new ColumnsSpec(this.getId(), new ArrayList<ColumnSpec>(), new ArrayList<String>(), new ArrayList<String>());
this.tableSpec = new TableSpec(this.getId(), selection, columnsSpec);
this.tableSpec.setContent(new TableContent(this.getId()));
final TableSpec tableSpec = new TableSpec(this.getId(), selection, columnsSpec);
tableSpec.setContent(new TableContent(this.getId()));
 
this.setTableSpec(tableSpec);
}
 
@Override
237,7 → 243,7
}
 
public final List<Row> getSelectedRows() {
final List<Row> selectedRows = new ArrayList<>();
final List<Row> selectedRows = new ArrayList<Row>();
 
if (this.getTableSpec().getSelection() != null) {
final List<Number> selectedIds = this.getSelectedIds();
368,7 → 374,7
}
 
public <T extends LightUIElement> List<T> findChildren(final Class<T> expectedClass, final boolean recursively) {
final List<T> result = new ArrayList<>();
final List<T> result = new ArrayList<T>();
 
if (this.hasRow()) {
final int size = this.getRowsCount();
376,7 → 382,6
final Row row = this.getRow(i);
final List<Object> rowValues = row.getValues();
for (final Object value : rowValues) {
if (value != null) {
if (recursively) {
if (value instanceof LightUIContainer) {
result.addAll(((LightUIContainer) value).findChildren(expectedClass, recursively));
389,7 → 394,6
}
}
}
}
} else {
System.out.println("LightUITable.getElementById() - No rows for table: " + this.getId());
}
423,7 → 427,7
final Document xmlConf = new Document();
 
final int columnSpecCount = columnsSpec.getColumnCount();
final List<String> visibleIds = new ArrayList<>();
final List<String> visibleIds = new ArrayList<String>();
for (int i = 0; i < columnSpecCount; i++) {
final ColumnSpec columnSpec = columnsSpec.getColumn(i);
final Element xmlColumn = this.createXmlColumn(columnSpec.getId(), columnSpec.getMaxWidth(), columnSpec.getMinWidth(), columnSpec.getWidth());
490,7 → 494,7
final Row row = this.getRow(i);
final List<Object> values = row.getValues();
for (final Object value : values) {
if (value instanceof LightUIElement) {
if (value != null && value instanceof LightUIElement) {
((LightUIElement) value).setReadOnly(readOnly);
}
}
522,9 → 526,9
 
for (int i = 0; i < size; i++) {
final Row row = this.getRow(i);
final JSONObject jsonLineContext = JSONConverter.getObjectFromJSON(jsonContext.get(i), JSONObject.class);
final JSONObject jsonLineContext = (JSONObject) JSONConverter.getObjectFromJSON(jsonContext.get(i), JSONObject.class);
final Number rowId = JSONConverter.getParameterFromJSON(jsonLineContext, "row.id", Number.class);
final String rowExtendId = JSONConverter.getParameterFromJSON(jsonLineContext, "row.extend.id", String.class);
final String rowExtendId = (String) JSONConverter.getParameterFromJSON(jsonLineContext, "row.extend.id", String.class);
if (NumberUtils.areNumericallyEqual(rowId, row.getId()) && (row.getExtendId() == null || (row.getExtendId() != null && rowExtendId.equals(row.getExtendId())))) {
if (row.isFillWidth()) {
if (!row.getValues().isEmpty() && row.getValues().get(0) instanceof LightUserControl) {
555,7 → 559,7
}
}
} else {
final List<Number> ids = new ArrayList<>(size);
final List<Number> ids = new ArrayList<Number>(size);
for (int j = 0; j < size; j++) {
ids.add(this.getRow(j).getId());
}
607,6 → 611,29
}
 
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
 
out.writeBoolean(dynamicLoad);
out.writeBoolean(allowSelection);
out.writeBoolean(allowMultiSelection);
out.writeBoolean(autoSelectFirstLine);
tableSpec.writeExternal(out);
 
}
 
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
this.dynamicLoad = in.readBoolean();
this.allowSelection = in.readBoolean();
this.allowMultiSelection = in.readBoolean();
this.autoSelectFirstLine = in.readBoolean();
tableSpec = new TableSpec();
tableSpec.readExternal(in);
}
 
@Override
public void destroy() {
super.destroy();
this.selectionListeners.clear();
/trunk/OpenConcerto/src/org/openconcerto/ui/light/SearchSpec.java
New file
0,0 → 1,93
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.ui.light;
 
import org.openconcerto.utils.io.JSONConverter;
import org.openconcerto.utils.io.Transferable;
 
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
 
import net.minidev.json.JSONArray;
import net.minidev.json.JSONAware;
import net.minidev.json.JSONObject;
 
public class SearchSpec implements Transferable, JSONAware, Externalizable {
private String tableId;
private List<SearchContent> content = new ArrayList<>();
 
public SearchSpec() {
// Serialization
}
 
public SearchSpec(final String tableId) {
this.tableId = tableId;
}
 
public SearchSpec(final JSONObject json) {
this.fromJSON(json);
}
 
public final String getTableId() {
return this.tableId;
}
 
public final List<SearchContent> getContent() {
return this.content;
}
 
@Override
public JSONObject toJSON() {
final JSONObject json = new JSONObject();
json.put("table-id", this.tableId);
json.put("content", JSONConverter.getJSON(this.content));
return json;
}
 
@Override
public void fromJSON(JSONObject json) {
this.tableId = (String) JSONConverter.getParameterFromJSON(json, "table-id", String.class);
final JSONArray jsonContent = (JSONArray) JSONConverter.getParameterFromJSON(json, "content", JSONArray.class);
if (jsonContent != null) {
this.content = new ArrayList<SearchContent>();
for (final Object o : jsonContent) {
this.content.add(new SearchContent((JSONObject) JSONConverter.getObjectFromJSON(o, JSONObject.class)));
}
}
}
 
/*
* JSONAware pour que le JSONArray.toString() fonctionne quand cet objet est dans un JSONArray
*/
@Override
public String toJSONString() {
return toJSON().toJSONString();
}
 
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(this.tableId);
out.writeObject(this.content);
}
 
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.tableId = in.readUTF();
this.content = (List<SearchContent>) in.readObject();
}
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/TableContent.java
16,6 → 16,10
import org.openconcerto.utils.io.JSONConverter;
import org.openconcerto.utils.io.Transferable;
 
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
 
22,7 → 26,7
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
 
public class TableContent implements Transferable {
public class TableContent implements Transferable, Externalizable {
private static final long serialVersionUID = 3648381615123520834L;
private String tableId;
private List<Row> rows;
96,7 → 100,7
* @return a copy of the list
*/
public final synchronized List<Row> getRows() {
return new ArrayList<>(this.rows);
return new ArrayList<Row>(this.rows);
}
 
@Override
118,7 → 122,7
this.tableId = JSONConverter.getParameterFromJSON(json, "table-id", String.class);
final JSONArray jsonRows = JSONConverter.getParameterFromJSON(json, "rows", JSONArray.class);
if (jsonRows != null) {
final List<Row> listRows = new ArrayList<>();
final List<Row> listRows = new ArrayList<Row>();
for (final Object o : jsonRows) {
listRows.add(new Row(JSONConverter.getObjectFromJSON(o, JSONObject.class)));
}
126,4 → 130,27
}
}
 
@Override
public synchronized void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(tableId);
out.writeInt(rows.size());
for (Row row : this.rows) {
row.writeExternal(out);
}
 
}
 
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
tableId = in.readUTF();
int size = in.readInt();
this.rows = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
final Row row = new Row();
row.readExternal(in);
this.rows.add(row);
}
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUIStrippedImageLine.java
42,6 → 42,11
}
 
@Override
public LightUIElement clone() {
return new LightUIStrippedImageLine(this);
}
 
@Override
protected void copy(LightUIElement element) {
super.copy(element);
 
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUITab.java
54,6 → 54,11
}
 
@Override
public LightUIElement clone() {
return new LightUITab(this);
}
 
@Override
public void copy(final LightUIElement element) {
if (!(element instanceof LightUITab)) {
throw new InvalidClassException(LightUITab.class.getName(), element.getClassName(), element.getId());
/trunk/OpenConcerto/src/org/openconcerto/ui/light/RowsBulk.java
13,9 → 13,6
package org.openconcerto.ui.light;
 
import org.openconcerto.utils.io.JSONAble;
import org.openconcerto.utils.io.JSONConverter;
 
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
24,6 → 21,8
import java.util.Collections;
import java.util.List;
 
import org.openconcerto.utils.io.JSONAble;
import org.openconcerto.utils.io.JSONConverter;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
 
144,7 → 143,7
this.total = JSONConverter.getParameterFromJSON(json, "total", Integer.class);
 
final JSONArray jsonRows = JSONConverter.getParameterFromJSON(json, "rows", JSONArray.class);
this.rows = new ArrayList<>();
this.rows = new ArrayList<Row>();
if (jsonRows != null) {
for (final Object o : jsonRows) {
this.rows.add(new Row(JSONConverter.getObjectFromJSON(o, JSONObject.class)));
154,6 → 153,6
 
@Override
public String toString() {
return this.rows.size() + " rows at offset " + this.offset + " (total:" + this.total + ") remove:" + this.remove;
return this.rows.size() + " rows at offset " + offset + " (total:" + total + ") remove:" + this.remove;
}
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUIFileUploadWithSelection.java
38,6 → 38,11
}
 
@Override
public LightUIElement clone() {
return new LightUIFileUploadWithSelection(this);
}
 
@Override
protected void copy(LightUIElement element) {
super.copy(element);
if (!(element instanceof LightUIFileUploadWithSelection)) {
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUIElement.java
200,7 → 200,7
}
 
private static long count = 0;
private static Object counterLock = new Object();
private static Integer counterLock = new Integer(123456);
 
private String getNextUUID() {
String result;
536,11 → 536,7
}
 
public void setId(final String id) {
if (id == null) {
throw new IllegalArgumentException("id cannot be null");
}
this.id = id;
 
}
 
public String getUUID() {
813,9 → 809,6
if (element == null) {
throw new IllegalArgumentException("Try to copy attributes of null element in " + this.getId());
}
System.err.println("LightUIElement.copy() " + element);
this.UUID = getNextUUID();
this.id = element.getId();
this.fontSize = element.fontSize;
this.gridHeight = element.gridHeight;
this.gridWidth = element.gridWidth;
873,7 → 866,7
 
@Override
public String toString() {
if (!this.destroyed) {
if (!destroyed) {
return super.toString() + " " + this.id;
} else {
return super.toString() + " " + this.id + " DESTROYED";
1019,9 → 1012,6
if (this.toolTip != null) {
result.put("tool-tip", this.toolTip);
}
if (this.UUID == null) {
throw new IllegalStateException("null UUID, id: " + this.id);
}
result.put("uuid", this.UUID);
if (this.value != null) {
result.put("value", this.value);
1055,9 → 1045,6
public void fromJSON(final JSONObject json) {
this.id = JSONConverter.getParameterFromJSON(json, "id", String.class);
this.UUID = JSONConverter.getParameterFromJSON(json, "uuid", String.class);
if (this.UUID == null) {
throw new IllegalArgumentException("null UUID, id : " + this.id);
}
this.displayPrecision = JSONConverter.getParameterFromJSON(json, "display-precision", String.class);
this.icon = JSONConverter.getParameterFromJSON(json, "icon", String.class);
this.label = JSONConverter.getParameterFromJSON(json, "label", String.class);
1122,7 → 1109,7
}
 
public boolean isDestroyed() {
return this.destroyed;
return destroyed;
}
 
@Override
1133,7 → 1120,7
}
out.writeUTF(this.id);
if (this.UUID == null) {
throw new IllegalStateException("null UUID, id : " + this.id);
throw new IllegalStateException("UUID");
}
out.writeUTF(this.UUID);
 
1236,9 → 1223,6
this.type = in.readInt();
this.id = in.readUTF();
this.UUID = in.readUTF();
if (this.UUID == null) {
throw new IllegalStateException("null UUID, id : " + this.id);
}
if (in.readBoolean()) {
this.label = in.readUTF();
}
/trunk/OpenConcerto/src/org/openconcerto/ui/light/LightUIFrame.java
62,16 → 62,10
super.destroy();
if (this.titlePanel != null) {
this.titlePanel.destroy();
this.titlePanel = null;
}
if (this.footerPanel != null) {
this.footerPanel.destroy();
this.footerPanel = null;
}
if (this.contentPanel != null) {
this.contentPanel.destroy();
this.contentPanel = null;
}
if (this.childrenFrame != null) {
for (LightUIFrame frame : childrenFrame) {
frame.destroy();
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/KeyTableCellRenderer.java
20,7 → 20,6
import org.openconcerto.sql.model.SQLTableEvent;
import org.openconcerto.sql.model.SQLTableEvent.Mode;
import org.openconcerto.sql.model.SQLTableModifiedListener;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.IComboSelectionItem;
 
import java.awt.Component;
38,18 → 37,13
private Object toSelect;
private boolean isLoading = false;
private final SQLElement el;
private final List<String> fields;
private JTable t;
static private final Map<SQLElement, Map<Integer, IComboSelectionItem>> cacheMap = new HashMap<SQLElement, Map<Integer, IComboSelectionItem>>();
 
public KeyTableCellRenderer(final SQLElement el) {
this(el, null);
}
 
public KeyTableCellRenderer(final SQLElement el, final List<String> fields) {
super();
this.el = el;
this.fields = fields;
 
if (cacheMap.get(this.el) == null) {
loadCacheAsynchronous();
}
113,9 → 107,7
Configuration.getInstance().getNonInteractiveSQLExecutor().execute(new Runnable() {
public void run() {
 
final ComboSQLRequest comboRequest = KeyTableCellRenderer.this.fields == null || KeyTableCellRenderer.this.fields.isEmpty() ? KeyTableCellRenderer.this.el.getComboRequest()
: KeyTableCellRenderer.this.el.createComboRequest(KeyTableCellRenderer.this.fields, null);
List<IComboSelectionItem> items = comboRequest.getComboItems();
List<IComboSelectionItem> items = KeyTableCellRenderer.this.el.getComboRequest().getComboItems();
final Map<Integer, IComboSelectionItem> m = new HashMap<Integer, IComboSelectionItem>();
for (IComboSelectionItem comboSelectionItem : items) {
m.put(comboSelectionItem.getId(), comboSelectionItem);
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/IListe.java
30,7 → 30,6
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.users.User;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.TableAllRights;
import org.openconcerto.sql.view.FileTransfertHandler;
import org.openconcerto.sql.view.IListener;
import org.openconcerto.sql.view.list.IListeAction.ButtonsBuilder;
147,8 → 146,6
public final class IListe extends JPanel {
 
static private final class LockAction extends RowAction {
private final boolean lock;
 
public LockAction(final boolean lock) {
super(new AbstractAction(TM.tr(lock ? "ilist.lockRows" : "ilist.unlockRows")) {
@Override
170,13 → 167,12
t.fireTableModified(fireID.intValue(), update.getFieldsNames());
}
}, false, true);
this.lock = lock;
}
 
@Override
public boolean enabledFor(IListeEvent evt) {
boolean hasRight = TableAllRights.currentUserHasRight(this.lock ? TableAllRights.USER_UI_LOCK_ROW : TableAllRights.USER_UI_UNLOCK_ROW, evt.getTable());
return !evt.getSelectedRows().isEmpty() && hasRight;
// TODO use right
return evt.getSelectedRows().size() > 0;
}
}
 
1208,7 → 1204,8
try {
res.add(getRow(i, clazz));
} catch (IndexOutOfBoundsException e) {
throw new IllegalStateException("The selected row at " + i
throw new IllegalStateException(
"The selected row at " + i
+ " is not in the model : it has been changed before Swing could update the selection. E.g. the DB was changed on mousePressed and Swing updated the selection on mouseReleased.",
e);
}
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/SQLTextComboTableCellEditor.java
34,7 → 34,6
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EventObject;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.AbstractCellEditor;
57,7 → 56,7
private IListFrame listFrame = null;
 
public SQLTextComboTableCellEditor(final SQLElement elt, final boolean addUndefined) {
this(elt, addUndefined, false,null);
this(elt, addUndefined, false);
}
 
/**
67,16 → 66,6
* @param chooseInListe possibilité de choisir via une IListe
*/
public SQLTextComboTableCellEditor(final SQLElement elt, final boolean addUndefined, boolean chooseInListe) {
this(elt, addUndefined, chooseInListe, null);
}
 
/**
*
* @param elt Element à afficher dans la combo
* @param addUndefined ajout de l'indéfini
* @param chooseInListe possibilité de choisir via une IListe
*/
public SQLTextComboTableCellEditor(final SQLElement elt, final boolean addUndefined, boolean chooseInListe, List<String> fieldsInCombo) {
super();
 
this.addUndefined = addUndefined;
88,7 → 77,7
this.comboBox.setBorder(new LineBorder(Color.black));
this.comboBox.getPulseComponents().iterator().next().setBorder(null);
 
ComboSQLRequest c = fieldsInCombo == null || fieldsInCombo.isEmpty() ? elt.getComboRequest(true) : elt.createComboRequest(fieldsInCombo, null);
ComboSQLRequest c = elt.getComboRequest(true);
this.comboBox.uiInit(c);
 
if (chooseInListe) {
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/RowValuesTableModel.java
20,7 → 20,6
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSyntax.ConstraintType;
import org.openconcerto.sql.model.SQLTable;
301,7 → 300,7
for (int i = 0; i < size; i++) {
final SQLRowValues r = rowsToCommmit.get(i);
r.put(r.getTable().getOrderField().getFieldName(), o.add(new BigDecimal(i + 1)));
final SQLRow row = r.getGraph().store(StoreMode.COMMIT).getStoredRow(r);
final SQLRow row = r.commit();
r.setID(row.getIDNumber());
}
} catch (SQLException e) {
/trunk/OpenConcerto/src/org/openconcerto/sql/mapping_en.xml
12,8 → 12,7
<FIELD name="ID_USER_RIGHT_COMMON" label="User rights" />
<FIELD name="MAIL" label="E-Mail" />
<FIELD name="DISABLED" label="Account disabled" />
<FIELD name="TEL" label="Phone" />
<FIELD name="COLOR" label="Color" />
<FIELD name="TEL" label="Phone" titlelabel="Phone" />
</element>
<element refid="sql.right">
<name base="right" />
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/IColorChooser.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/TableSearchColumnMatcher.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/TableSearchMatcher.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/CustomRowEditor.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/LightForeignRowValuesTableOffline.java
16,12 → 16,11
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.SQLTableModelLinesSourceOffline;
import org.openconcerto.ui.light.LightUIElement;
import org.openconcerto.ui.light.SearchSpec;
import org.openconcerto.ui.light.TableContent;
import org.openconcerto.ui.light.UserSearch;
 
import java.util.concurrent.Future;
 
32,19 → 31,14
private SQLField foreignField;
private Number parentRowId;
 
public LightForeignRowValuesTableOffline(final Configuration configuration, final Number userId, final String id, final ITableModel model, final SQLField foreignField) {
public LightForeignRowValuesTableOffline(final Configuration configuration, final Number userId, final String id, final ITableModel model, final SQLField foreignField, final Number parentRowId) {
super(configuration, userId, id, model);
 
this.foreignField = foreignField;
this.parentRowId = parentRowId;
this.init();
}
 
public void setParentRowId(Number parentRowId) {
this.parentRowId = parentRowId;
// FIXME : d'apres Sylvain, on pourrait ne pas a utiliser le ITableMobel car on veut du
// synchrone
this.getModel().getReq().getReq().setWhere(new Where(this.foreignField, "=", parentRowId));
}
 
public LightForeignRowValuesTableOffline(final LightForeignRowValuesTableOffline table) {
super(table);
 
76,7 → 70,7
}
 
@Override
public void doSearch(final Configuration configuration, final UserSearch searchSpec, final int offset) {
public void doSearch(final Configuration configuration, final SearchSpec searchSpec, final int offset) {
// TODO: Implement search in offline table
this.getModel().fireTableRowsInserted(0, Integer.MAX_VALUE);
}
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/GroupToLightUIConvertor.java
23,6 → 23,7
import org.openconcerto.ui.group.Group;
import org.openconcerto.ui.group.Item;
import org.openconcerto.ui.group.LayoutHints;
import org.openconcerto.ui.light.CustomEditorProvider;
import org.openconcerto.ui.light.LightUIAutoCompleteComboBox;
import org.openconcerto.ui.light.LightUICheckBox;
import org.openconcerto.ui.light.LightUIDate;
42,7 → 43,6
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class GroupToLightUIConvertor {
49,7 → 49,7
private final int maxColumnCount;
private PropsConfiguration configuration;
private FieldMapper mapper;
private Map<String, CustomRowEditor> customRowEditors = new HashMap<>();
private Map<String, CustomEditorProvider> customEditorProviders = new HashMap<String, CustomEditorProvider>();
 
public GroupToLightUIConvertor(PropsConfiguration conf) {
this(conf, 4);
73,15 → 73,6
}
 
final SQLElement sqlElement = this.configuration.getDirectory().getElement(defaultRow.getTable());
if (sqlElement == null) {
throw new IllegalArgumentException("not SQLElement found for default row table : " + defaultRow.getTable().getName());
}
if (sqlElement.getGroupForCreation() == null) {
throw new IllegalArgumentException("no group for creation defined in " + sqlElement.getClass().getName());
}
if (sqlElement.getGroupForModification() == null) {
throw new IllegalArgumentException("no group for creation defined in " + sqlElement.getClass().getName());
}
if (!sqlElement.getGroupForCreation().equals(group) && sqlElement.getGroupForModification().equals(group)) {
throw new IllegalArgumentException("This group isn't attached to this SQLElement, group ID: " + group.getId() + " element code: " + sqlElement.getCode());
}
322,14 → 313,11
}
 
private LightUIElement getCustomEditor(final String id) {
if (id == null) {
throw new IllegalArgumentException("null id");
}
final CustomRowEditor customEditorProvider = this.customRowEditors.get(id);
final CustomEditorProvider customEditorProvider = this.customEditorProviders.get(id);
if (customEditorProvider != null) {
final LightUIElement element = customEditorProvider.createUIElement();
final LightUIElement element = customEditorProvider.createUIElement(id);
if (element.getId() == null) {
throw new IllegalStateException("Null id for custom editor for id: " + id + " element : " + element);
throw new IllegalStateException("Null id for custom editor for id: " + id);
}
return element;
}
336,12 → 324,11
return null;
}
 
public void putCustomEditorProvider(final CustomRowEditor e) {
this.customRowEditors.put(e.getItemId(), e);
public void putCustomEditorProvider(final String id, final CustomEditorProvider provider) {
this.customEditorProviders.put(id, provider);
}
 
public void putAllCustomEditorProvider(final List<CustomRowEditor> editors) {
for (CustomRowEditor e : editors)
this.customRowEditors.put(e.getItemId(), e);
public void putAllCustomEditorProvider(final Map<String, CustomEditorProvider> map) {
this.customEditorProviders.putAll(map);
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/LightRowValuesTable.java
14,14 → 14,8
package org.openconcerto.sql.ui.light;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.FieldRef;
import org.openconcerto.sql.model.SQLFunctionField;
import org.openconcerto.sql.model.SQLFunctionField.SQLFunction;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.ListSQLLine;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
32,21 → 26,12
import org.openconcerto.ui.light.LightUIElement;
import org.openconcerto.ui.light.LightUITable;
import org.openconcerto.ui.light.Row;
import org.openconcerto.ui.light.TableSearchParameter;
import org.openconcerto.ui.light.TableSearchParameterType;
import org.openconcerto.ui.light.UserSearch;
import org.openconcerto.ui.light.UserSearchItem;
import org.openconcerto.ui.light.SearchSpec;
import org.openconcerto.utils.NumberUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
 
import javax.swing.SwingUtilities;
70,10 → 55,8
 
private transient ITransformer<SQLSelect, SQLSelect> orginTransformer;
 
private transient List<TableModelListener> tableModelListeners = new ArrayList<>();
private transient List<TableModelListener> tableModelListeners = new ArrayList<TableModelListener>();
 
private Map<TableSearchParameter, TableSearchMatcher> searchMap = new HashMap<>();
 
public LightRowValuesTable() {
// Serialization
}
89,74 → 72,6
if (model.getReq() instanceof SQLTableModelSourceOnline) {
final SQLTableModelSourceOnline source = (SQLTableModelSourceOnline) model.getReq();
this.orginTransformer = source.getReq().getSelectTransf();
 
List<SQLTableModelColumn> columns = model.getReq().getColumns();
// all
// TODO : traduire
TableSearchParameter tableSearchParameterAll = new TableSearchParameter("all", "Tous");
 
TableSearchMatcher m = new TableSearchMatcher() {
 
@Override
public boolean useMatch() {
return false;
}
 
@Override
public boolean match(SQLRowValues r, TableSearchParameterType type, String txt) {
return true;
}
 
@Override
public Where getWhere(SQLSelect sel, TableSearchParameterType type, String txt) {
final Set<FieldPath> fields = new HashSet<>();
for (SQLTableModelColumn col : columns) {
fields.addAll(col.getPaths());
}
final List<Where> wFields = new ArrayList<>(fields.size());
for (final FieldPath fpath : fields) {
if (fpath.getField().getType().getJavaType().equals(String.class)) {
final FieldRef fieldRef = sel.followFieldPath(fpath);
if (type.getType().equals(UserSearchItem.TYPE_CONTAINS)) {
final Where w = new Where(new SQLFunctionField(SQLFunction.LOWER, fieldRef), "LIKE", "%" + txt.toLowerCase() + "%");
wFields.add(w);
}
if (type.getType().equals(UserSearchItem.TYPE_STARTS_WITH)) {
final Where w = new Where(new SQLFunctionField(SQLFunction.LOWER, fieldRef), "LIKE", txt.toLowerCase() + "%");
wFields.add(w);
}
if (type.getType().equals(UserSearchItem.TYPE_IS)) {
final Where w = new Where(new SQLFunctionField(SQLFunction.LOWER, fieldRef), "LIKE", txt.toLowerCase());
wFields.add(w);
}
}
}
return Where.or(wFields);
}
 
@Override
public List<FieldPath> getAdditionnalFieldsToFetch() {
return Collections.emptyList();
}
};
tableSearchParameterAll.add(TableSearchParameterType.getContainsStringInstance(Locale.FRENCH));
tableSearchParameterAll.add(TableSearchParameterType.getIsStringInstance(Locale.FRENCH));
 
this.addSearchParameter(tableSearchParameterAll, m);
 
//
for (int i = 0; i < columns.size(); i++) {
SQLTableModelColumn col = columns.get(i);
TableSearchParameter tableSearchParameter = new TableSearchParameter("col" + i, col.getName());
// FIXME : locale à recuperer depuis le user
// TODO : mettre d'autres TableSearchParameterType en fonction du type de la colonne
tableSearchParameter.add(TableSearchParameterType.getContainsStringInstance(Locale.FRENCH));
tableSearchParameter.add(TableSearchParameterType.getIsStringInstance(Locale.FRENCH));
 
TableSearchMatcher tableSearchMatcher = new TableSearchColumnMatcher(col);
this.addSearchParameter(tableSearchParameter, tableSearchMatcher);
}
 
} else {
this.orginTransformer = null;
}
193,15 → 108,9
 
public final void addTableModelListener(final TableModelListener tableModelListener) {
this.tableModelListeners.add(tableModelListener);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LightRowValuesTable.this.model.addTableModelListener(tableModelListener);
this.model.addTableModelListener(tableModelListener);
}
});
 
}
 
public final void removeTableModelListener(final TableModelListener tableModelListener) {
this.tableModelListeners.remove(tableModelListener);
this.model.removeTableModelListener(tableModelListener);
361,26 → 270,8
}
 
// TODO: merge with OpenConcerto List search system
public abstract void doSearch(final Configuration configuration, final UserSearch searchSpec, final int offset);
public abstract void doSearch(final Configuration configuration, final SearchSpec searchSpec, final int offset);
 
public void addSearchParameter(TableSearchParameter tableSearchParameter, TableSearchMatcher tableSearchMatcher) {
this.searchMap.put(tableSearchParameter, tableSearchMatcher);
this.getTableSpec().addSearchParameter(tableSearchParameter);
}
 
protected TableSearchMatcher getSearchMatcher(String colId, String searchType) {
for (TableSearchParameter p : this.searchMap.keySet()) {
if (p.getId().equals(colId)) {
for (TableSearchParameterType t : p.getTypes()) {
if (t.getType().equals(searchType)) {
return this.searchMap.get(p);
}
}
}
}
return null;
}
 
@Override
public Row getRowById(Number rowId) {
for (int i = 0; i < this.model.getRowCount(); i++) {
423,10 → 314,9
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
 
final List<TableModelListener> listeners = LightRowValuesTable.this.tableModelListeners;
for (int i = listeners.size() - 1; i > -1; i--) {
LightRowValuesTable.this.removeTableModelListener(listeners.get(i));
final List<TableModelListener> tableModelListeners = LightRowValuesTable.this.tableModelListeners;
for (int i = tableModelListeners.size() - 1; i > -1; i--) {
LightRowValuesTable.this.removeTableModelListener(tableModelListeners.get(i));
}
}
});
435,6 → 325,5
}
 
this.clearRows();
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/LightEditFrame.java
41,8 → 41,6
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
 
147,18 → 145,19
 
final SQLElement sqlElement = configuration.getDirectory().getElement(this.sqlRow.getTable());
 
final List<CustomRowEditor> customRowEditors = sqlElement.getCustomRowEditors(configuration, sessionSecurityToken);
final Map<String, CustomEditorProvider> customEditors;
if (this.editMode.equals(EditMode.CREATION)) {
customEditors = sqlElement.getCustomEditorProviderForCreation(configuration, sessionSecurityToken);
} else {
customEditors = sqlElement.getCustomEditorProviderForModification(configuration, this.sqlRow, sessionSecurityToken);
}
 
final Map<String, CustomRowEditor> customEditors = new HashMap<>(customRowEditors.size());
for (CustomRowEditor e : customRowEditors) {
customEditors.put(e.getItemId(), e);
}
this.createRowValues(configuration, sqlElement, fieldMapper, this.group, customEditors);
this.setMetaData(userId);
}
 
protected final void createRowValues(final Configuration configuration, final SQLElement sqlElement, final FieldMapper fieldMapper, final Group group,
final Map<String, CustomRowEditor> customEditors) {
final protected void createRowValues(final Configuration configuration, final SQLElement sqlElement, final FieldMapper fieldMapper, final Group group,
final Map<String, CustomEditorProvider> customEditors) {
final int itemCount = group.getSize();
for (int i = 0; i < itemCount; i++) {
final Item item = group.getItem(i);
177,29 → 176,26
this.putValueFromUserControl(configuration, sqlElement, field, uiElement, customEditors);
}
} else {
final LightUIElement uiElement = this.findChildByID(item.getId(), LightUIElement.class);
if (uiElement == null) {
throw new IllegalArgumentException("Impossible to find UI Element with id: " + item.getId());
}
if (customEditors.containsKey(uiElement.getId())) {
final CustomRowEditor customEditor = customEditors.get(uiElement.getId());
customEditor.store(uiElement, this.sqlRow);
} else {
Log.get().warning("No field attached to " + item.getId());
}
}
}
}
}
 
protected final void putValueFromUserControl(final Configuration configuration, final SQLElement sqlElement, final SQLField sqlField, final LightUIElement uiElement,
final Map<String, CustomRowEditor> customEditors) {
final Map<String, CustomEditorProvider> customEditors) {
if (!uiElement.isNotSaved()) {
boolean useElementValue = true;
final Class<?> fieldType = sqlField.getType().getJavaType();
if (customEditors.containsKey(uiElement.getId())) {
final CustomRowEditor customEditor = customEditors.get(uiElement.getId());
customEditor.store(uiElement, this.sqlRow);
} else {
final CustomEditorProvider customEditor = customEditors.get(uiElement.getId());
if (customEditor instanceof SavableCustomEditorProvider) {
((SavableCustomEditorProvider) customEditor).save(this.sqlRow, sqlField, uiElement);
useElementValue = false;
}
}
 
if (useElementValue) {
final String fieldName = sqlField.getFieldName();
if (sqlField.isKey()) {
if (!(uiElement instanceof LightUIComboBox)) {
272,13 → 268,11
* @param row Element saved row
* @param customEditors List of custom editors used in element edit frame
*/
@Deprecated
public final void saveReferentRows(final Configuration configuration, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors, final String sessionSecurityToken) {
final public void saveReferentRows(final Configuration configuration, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors, final String sessionSecurityToken) {
this.saveReferentRows(configuration, this.group, parentSqlRow, customEditors, sessionSecurityToken);
}
 
@Deprecated
private final void saveReferentRows(final Configuration configuration, final Group group, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors,
final private void saveReferentRows(final Configuration configuration, final Group group, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors,
final String sessionSecurityToken) {
for (int i = 0; i < group.getSize(); i++) {
final Item item = group.getItem(i);
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/SavableCustomEditorProvider.java
New file
0,0 → 1,31
/*
* 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.sql.ui.light;
 
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.light.CustomEditorProvider;
import org.openconcerto.ui.light.LightUIElement;
 
public abstract class SavableCustomEditorProvider extends CustomEditorProvider {
 
public final void save(final SQLRowValues sqlRow, final SQLField sqlField, final LightUIElement uiElement) throws IllegalArgumentException, IllegalStateException {
if (sqlRow == null || sqlField == null) {
throw new IllegalStateException("Impossible to save this editor: " + uiElement.getId());
}
this._save(sqlRow, sqlField, uiElement);
}
 
protected abstract void _save(final SQLRowValues sqlRow, final SQLField sqlField, final LightUIElement uiElement) throws IllegalArgumentException, IllegalStateException;
}
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/LightRowValuesTableOnline.java
14,23 → 14,29
package org.openconcerto.sql.ui.light;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.Log;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.IFieldPath;
import org.openconcerto.sql.model.SQLFunctionField;
import org.openconcerto.sql.model.SQLFunctionField.SQLFunction;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.light.TableSearchParameterType;
import org.openconcerto.ui.light.UserSearch;
import org.openconcerto.ui.light.UserSearchItem;
import org.openconcerto.ui.light.SearchSpec;
import org.openconcerto.utils.cc.ITransformer;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
 
import javax.swing.SwingUtilities;
 
import net.minidev.json.JSONObject;
 
public class LightRowValuesTableOnline extends LightRowValuesTable {
42,6 → 48,7
 
public LightRowValuesTableOnline(final Configuration configuration, final Number userId, final String id, final ITableModel model) {
super(configuration, userId, id, model);
 
this.orginTransformer = ((SQLTableModelSourceOnline) model.getReq()).getReq().getSelectTransf();
}
 
48,6 → 55,7
// Clone constructor
public LightRowValuesTableOnline(final LightRowValuesTableOnline tableElement) {
super(tableElement);
 
this.orginTransformer = tableElement.orginTransformer;
}
 
58,31 → 66,19
}
 
@Override
public void doSearch(final Configuration configuration, final UserSearch searchSpec, final int offset) {
 
public void doSearch(final Configuration configuration, final SearchSpec searchSpec, final int offset) {
this.getTableSpec().setSearch(searchSpec);
 
this.setOffset(offset);
 
final SQLTableModelSource tableSource = this.getModel().getReq();
final SearchInfo sInfo = (searchSpec != null) ? new SearchInfo(searchSpec) : null;
 
final FutureTask<ListSQLRequest> f = new FutureTask<ListSQLRequest>(new Callable<ListSQLRequest>() {
@Override
public ListSQLRequest call() throws Exception {
final ListSQLRequest req = tableSource.getReq();
final List<UserSearchItem> content = new ArrayList<>();
if (searchSpec != null) {
content.addAll(searchSpec.getContent());
 
for (UserSearchItem item : content) {
// ex "col0"
String colId = item.getColumn();
// ex "contains"
String searchType = item.getType();
TableSearchMatcher m = LightRowValuesTableOnline.this.getSearchMatcher(colId, searchType);
if (m != null && m.getAdditionnalFieldsToFetch() != null) {
for (FieldPath p : m.getAdditionnalFieldsToFetch()) {
req.addToGraphToFetch(p.getPath(), Arrays.asList(p.getField().getFieldName()));
}
}
}
}
final List<SQLTableModelColumn> columns = tableSource.getColumns();
req.setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(final SQLSelect sel) {
89,30 → 85,60
if (LightRowValuesTableOnline.this.orginTransformer != null) {
LightRowValuesTableOnline.this.orginTransformer.transformChecked(sel);
}
if (searchSpec != null) {
//
final List<Where> wheres = new ArrayList<>();
for (UserSearchItem item : content) {
// ex "col0"
String colId = item.getColumn();
// ex "hello"
String userText = item.getText();
// ex "contains"
String searchType = item.getType();
TableSearchMatcher m = LightRowValuesTableOnline.this.getSearchMatcher(colId, searchType);
if (m != null) {
final Where where = m.getWhere(sel, new TableSearchParameterType(searchType), userText);
if (where != null) {
wheres.add(where);
setWhere(sel, sInfo, columns);
return sel;
}
} else {
Log.get().warning("no TableSearchMatcher for " + item);
});
return req;
}
});
 
// TODO: clean swing
SwingUtilities.invokeLater(f);
 
try {
final ListSQLRequest req = f.get();
 
// get values
long t4 = System.currentTimeMillis();
final List<SQLRowValues> rowValues = req.getValues();
final int size = rowValues.size();
long t5 = System.currentTimeMillis();
 
System.err.println("DefaultTableContentHandler.handle() getValues() :" + size + " : " + (t5 - t4) + " ms");
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
 
/**
* Apply filter on ListSQLRequest
*
* @param sel - The ListSQLRequest select
* @param sInfo - Search parameters
*/
private final void setWhere(final SQLSelect sel, final SearchInfo sInfo, final List<SQLTableModelColumn> cols) {
if (sInfo != null) {
final Set<IFieldPath> fields = new HashSet<>(cols.size() * 2);
for (final SQLTableModelColumn sqlTableModelColumn : cols) {
fields.addAll(sqlTableModelColumn.getPaths());
}
final List<Where> wheres = new ArrayList<>();
final List<Where> wFields = new ArrayList<>();
 
final List<String> texts = sInfo.getTexts();
for (String string : texts) {
wFields.clear();
for (final IFieldPath fpath : fields) {
if (fpath.getField().getType().getJavaType().equals(String.class)) {
final Where w = new Where(new SQLFunctionField(SQLFunction.LOWER, sel.followFieldPath(fpath)), "LIKE", "%" + string.toLowerCase() + "%");
wFields.add(w);
}
}
wheres.add(Where.or(wFields));
}
 
final Where w;
if (!wheres.isEmpty()) {
if (sel.getWhere() != null) {
w = Where.and(sel.getWhere(), Where.and(wheres));
} else {
121,10 → 147,4
sel.setWhere(w);
}
}
return sel;
}
});
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/SearchInfo.java
17,8 → 17,8
import org.openconcerto.sql.view.search.SearchList;
import org.openconcerto.sql.view.search.TextSearchSpec;
import org.openconcerto.sql.view.search.TextSearchSpec.Mode;
import org.openconcerto.ui.light.UserSearchItem;
import org.openconcerto.ui.light.UserSearch;
import org.openconcerto.ui.light.SearchContent;
import org.openconcerto.ui.light.SearchSpec;
 
import java.util.ArrayList;
import java.util.List;
28,10 → 28,10
private final SearchList list = new SearchList();
private final List<String> texts = new ArrayList<String>();
 
public SearchInfo(final UserSearch params) {
public SearchInfo(final SearchSpec params) {
int stop = params.getContent().size();
for (int i = 0; i < stop; i++) {
final UserSearchItem param = params.getContent().get(i);
final SearchContent param = params.getContent().get(i);
final String col = param.getColumn();
final String type = param.getType();
final String[] tTexts = param.getText().split(" ");
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/light/LightUIPanelFiller.java
15,7 → 15,6
 
import org.openconcerto.sql.Log;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.Constraint;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
32,9 → 31,6
 
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
/**
62,17 → 58,11
}
}
 
public void fillFromRow(final PropsConfiguration configuration, SQLElement element, final SQLRowAccessor row, String sessionSecurityToken) {
this.fillFromRow(this.panel, configuration, element, row, sessionSecurityToken);
public void fillFromRow(final PropsConfiguration configuration, final SQLRowAccessor row) {
this.fillFromRow(this.panel, configuration, row);
}
 
private void fillFromRow(final LightUIPanel panel, final PropsConfiguration configuration, SQLElement sqlElement, SQLRowAccessor sqlRow, String sessionSecurityToken) {
List<CustomRowEditor> editors = sqlElement.getCustomRowEditors(configuration, sessionSecurityToken);
Map<String, CustomRowEditor> mapEditor = new HashMap<>(editors.size());
for (CustomRowEditor e : editors) {
mapEditor.put(e.getItemId(), e);
}
 
private void fillFromRow(final LightUIPanel panel, final PropsConfiguration configuration, SQLRowAccessor sqlRow) {
final int panelChildCount = panel.getChildrenCount();
// Convert as sqlrow if possible to get all values from db
if (sqlRow.hasID()) {
83,10 → 73,6
final int lineChildCount = panelChild.getChildrenCount();
for (int j = 0; j < lineChildCount; j++) {
final LightUIElement element = panelChild.getChild(j);
if (mapEditor.containsKey(element.getId())) {
mapEditor.get(element.getId()).fillFrom(element, sqlRow);
} else {
 
final SQLField sqlField = configuration.getFieldMapper().getSQLFieldForItem(element.getId());
 
SQLRowAccessor sqlRowTmp = this.getSQLRowForField(sqlRow, sqlField);
129,7 → 115,7
element.setValue(JSONConverter.getJSON(date).toString());
}
} else if (type == LightUIElement.TYPE_PANEL) {
this.fillFromRow((LightUIPanel) element, configuration, sqlElement, sqlRowTmp, sessionSecurityToken);
this.fillFromRow((LightUIPanel) element, configuration, sqlRowTmp);
} else if (type == LightUIElement.TYPE_SLIDER) {
final Integer value = sqlRowTmp.getInt(sqlField.getName());
if (value != null) {
139,7 → 125,6
}
}
}
}
 
public SQLRowAccessor getSQLRowForField(final SQLRowAccessor sqlRow, final SQLField sqlField) {
SQLRowAccessor sqlRowResult = sqlRow;
/trunk/OpenConcerto/src/org/openconcerto/sql/mapping_fr.xml
2,23 → 2,21
<translations>
<element refid="sql.user">
<name base="utilisateur" nounClass="masculine" />
<FIELD name="NOM" label="Nom" />
<FIELD name="PRENOM" label="Prénom" />
<FIELD name="PASSWORD" label="Mot de passe" />
<FIELD name="NOM" label="Nom" titlelabel="Nom" />
<FIELD name="PRENOM" label="Prénom" titlelabel="Prénom" />
<FIELD name="PASSWORD" label="Mot de passe" titlelabel="Mot de passe" />
<FIELD name="PASSWORD_CONFIRM" label="Confirmation" />
<FIELD name="LOGIN" label="Identifiant" />
<FIELD name="SURNOM" label="Surnom" />
<FIELD name="LOGIN" label="Identifiant" titlelabel="Identifiant" />
<FIELD name="SURNOM" label="Surnom" titlelabel="Surnom" />
<FIELD name="ADMIN" label="Administrateur" titlelabel="Admin." />
<FIELD name="ID_USER_RIGHT_COMMON" label="Droits utilisateur" />
<FIELD name="ID_USER_RIGHT_COMMON" label="Droits utilisateur" titlelabel="Droits utilisateur" />
<FIELD name="MAIL" label="E-Mail" titlelabel="E-Mail" />
<FIELD name="COMPTE_NUMERO" label="N° compte comptable" />
<FIELD name="DISABLED" label="Compte désactivé" />
<FIELD name="TEL" label="Téléphone" />
<FIELD name="COLOR" label="Couleur" />
<FIELD name="TEL" label="Téléphone" titlelabel="Téléphone" />
</element>
<element refid="sql.right">
<name base="droit" nounClass="masculine" />
<FIELD name="CODE" label="Code" />
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="NOM" label="Nom" titlelabel="Nom du droit" />
<FIELD name="DESCRIPTION" label="Description" titlelabel="Desc." />
</element>
/trunk/OpenConcerto/src/org/openconcerto/sql/element/SQLElement.java
57,10 → 57,10
import org.openconcerto.sql.request.SQLCache;
import org.openconcerto.sql.request.SQLFieldTranslator;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.sql.ui.light.CustomRowEditor;
import org.openconcerto.sql.ui.light.GroupToLightUIConvertor;
import org.openconcerto.sql.ui.light.LightEditFrame;
import org.openconcerto.sql.ui.light.LightUIPanelFiller;
import org.openconcerto.sql.ui.light.SavableCustomEditorProvider;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
74,6 → 74,7
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.group.Group;
import org.openconcerto.ui.light.ComboValueConvertor;
import org.openconcerto.ui.light.CustomEditorProvider;
import org.openconcerto.ui.light.IntValueConvertor;
import org.openconcerto.ui.light.LightUIComboBox;
import org.openconcerto.ui.light.LightUIElement;
336,10 → 337,10
editFrame.createTitlePanel(this.getCreationFrameTitle());
} else if (editMode.equals(EditMode.MODIFICATION)) {
editFrame.createTitlePanel(this.getModificationFrameTitle(sqlRow));
new LightUIPanelFiller(editFrame.getContentPanel()).fillFromRow(configuration, this, sqlRow, sessionSecurityToken);
new LightUIPanelFiller(editFrame.getContentPanel()).fillFromRow(configuration, sqlRow);
} else if (editMode.equals(EditMode.READONLY)) {
editFrame.createTitlePanel(this.getReadOnlyFrameTitle(sqlRow));
new LightUIPanelFiller(editFrame.getContentPanel()).fillFromRow(configuration, this, sqlRow, sessionSecurityToken);
new LightUIPanelFiller(editFrame.getContentPanel()).fillFromRow(configuration, sqlRow);
}
 
this.setEditFrameModifiers(editFrame, sessionSecurityToken);
388,12 → 389,11
*/
public GroupToLightUIConvertor getGroupToLightUIConvertor(final PropsConfiguration configuration, final EditMode editMode, final SQLRowAccessor sqlRow, final String token) {
final GroupToLightUIConvertor convertor = new GroupToLightUIConvertor(configuration);
// if (editMode.equals(EditMode.CREATION)) {
convertor.putAllCustomEditorProvider(this.getCustomRowEditors(configuration, token));
// } else {
// convertor.putAllCustomEditorProvider(this.getCustomRowEditors(configuration, sqlRow,
// token));
// }
if (editMode.equals(EditMode.CREATION)) {
convertor.putAllCustomEditorProvider(this.getCustomEditorProviderForCreation(configuration, token));
} else {
convertor.putAllCustomEditorProvider(this.getCustomEditorProviderForModification(configuration, sqlRow, token));
}
return convertor;
}
 
418,55 → 418,76
public void setEditFrameModifiers(final LightEditFrame frame, final String sessionToken) {
}
 
public List<CustomRowEditor> getCustomRowEditors(final Configuration configuration, final String sessionToken) {
public final Map<String, CustomEditorProvider> getCustomEditorProviderForCreation(final Configuration configuration, final String sessionToken) {
final Map<String, CustomEditorProvider> map = this.getDefaultCustomEditorProvider(configuration, null, sessionToken);
map.putAll(this._getCustomEditorProviderForCreation(configuration, sessionToken));
return map;
}
 
public final Map<String, CustomEditorProvider> getCustomEditorProviderForModification(final Configuration configuration, final SQLRowAccessor sqlRow, final String sessionToken) {
final Map<String, CustomEditorProvider> map = this.getDefaultCustomEditorProvider(configuration, sqlRow, sessionToken);
map.putAll(this._getCustomEditorProviderForModification(configuration, sqlRow, sessionToken));
return map;
}
 
protected Map<String, CustomEditorProvider> _getCustomEditorProviderForCreation(final Configuration configuration, final String sessionToken) {
return new HashMap<String, CustomEditorProvider>();
}
 
protected Map<String, CustomEditorProvider> _getCustomEditorProviderForModification(final Configuration configuration, final SQLRowAccessor sqlRow, final String sessionToken) {
return new HashMap<String, CustomEditorProvider>();
}
 
protected Map<String, CustomEditorProvider> _getDefaultCustomEditorProvider(final Configuration configuration, final SQLRowAccessor sqlRow, final String sessionToken) {
return new HashMap<String, CustomEditorProvider>();
}
 
private final Map<String, CustomEditorProvider> getDefaultCustomEditorProvider(final Configuration configuration, final SQLRowAccessor sqlRow, final String sessionToken) {
final Map<String, ComboValueConvertor<?>> comboConvertors = this.getComboConvertors();
final List<CustomRowEditor> result = new ArrayList<>();
final Map<String, CustomEditorProvider> result = new HashMap<String, CustomEditorProvider>();
for (final Entry<String, ComboValueConvertor<?>> entry : comboConvertors.entrySet()) {
 
final String itemId = entry.getKey();
result.add(new CustomRowEditor(itemId) {
result.put(entry.getKey(), new SavableCustomEditorProvider() {
final ComboValueConvertor<?> convertor = entry.getValue();
 
@Override
public LightUIElement createUIElement() {
final LightUIComboBox uiCombo = new LightUIComboBox(getItemId());
public LightUIElement createUIElement(final String elementId) {
final LightUIComboBox uiCombo = new LightUIComboBox(elementId);
 
if (sqlRow == null) {
this.convertor.fillCombo(uiCombo, null);
return uiCombo;
}
 
@Override
public void fillFrom(LightUIElement uiElement, SQLRowAccessor sqlRow) {
final LightUIComboBox uiCombo = (LightUIComboBox) uiElement;
final SQLField field = configuration.getFieldMapper().getSQLFieldForItem(getItemId());
} else {
final SQLField field = configuration.getFieldMapper().getSQLFieldForItem(elementId);
if (this.convertor instanceof StringValueConvertor) {
((StringValueConvertor) this.convertor).fillCombo(uiCombo, sqlRow.getString(field.getFieldName()));
} else if (this.convertor instanceof IntValueConvertor) {
if (sqlRow.getObject(field.getFieldName()) != null) {
if (sqlRow.getObject(field.getFieldName()) == null) {
this.convertor.fillCombo(uiCombo, null);
} else {
((IntValueConvertor) this.convertor).fillCombo(uiCombo, sqlRow.getInt(field.getFieldName()));
}
}
 
}
return uiCombo;
}
 
@Override
public void store(LightUIElement uiElement, SQLRowValues sqlRow) {
final LightUIComboBox combobox = (LightUIComboBox) uiElement;
final String fieldName = configuration.getFieldMapper().getSQLFieldForItem(getItemId()).getName();
if (combobox.hasSelectedValue()) {
protected void _save(final SQLRowValues sqlRow, final SQLField sqlField, final LightUIElement uiElement) {
final LightUIComboBox combo = (LightUIComboBox) uiElement;
if (combo.hasSelectedValue()) {
if (this.convertor instanceof StringValueConvertor) {
sqlRow.put(fieldName, ((StringValueConvertor) this.convertor).getIdFromIndex(combobox.getSelectedValue().getId()));
sqlRow.put(sqlField.getName(), ((StringValueConvertor) this.convertor).getIdFromIndex(combo.getSelectedValue().getId()));
} else if (this.convertor instanceof IntValueConvertor) {
sqlRow.put(fieldName, combobox.getSelectedValue().getId());
sqlRow.put(sqlField.getName(), combo.getSelectedValue().getId());
} else {
throw new IllegalArgumentException("the save is not implemented for the class: " + this.convertor.getClass().getName() + " - ui id: " + getItemId());
throw new IllegalArgumentException("the save is not implemented for the class: " + this.convertor.getClass().getName() + " - ui element id: " + uiElement.getId());
}
} else {
sqlRow.put(fieldName, null);
sqlRow.put(sqlField.getName(), null);
}
 
}
});
}
result.putAll(this._getDefaultCustomEditorProvider(configuration, sqlRow, sessionToken));
return result;
}
 
/trunk/OpenConcerto/src/org/openconcerto/sql/element/BaseSQLComponent.java
434,13 → 434,7
if (!(this instanceof GroupSQLComponent)) {
 
for (final Entry<String, JComponent> e : this.getElement().getAdditionalFields().entrySet()) {
final SpecParser spec;
// FIXME Required à spécifier directement depuis le module
if (this.requiredNames != null && this.requiredNames.contains(e.getKey())) {
spec = new SpecParser(REQ, true);
} else {
spec = new SpecParser(null, true);
}
final SpecParser spec = new SpecParser(null, true);
final JComponent comp = e.getValue();
if (comp == null)
// infer component
732,6 → 726,7
return this.getRequest().setLastKnownDBVals(current, this.getRequest().fetchRow(current.getID(), ls));
}
 
 
@Override
public final void select(int id) {
// TODO in an executor outside of the EDT
/trunk/OpenConcerto/src/org/openconcerto/sql/element/SQLElementDirectory.java
202,55 → 202,10
* @return the corresponding SQLElement, or <code>null</code> if none can be found.
* @throws IllegalArgumentException if there's more than one match.
*/
public final <S extends SQLElement> S getElement(Class<S> clazz) {
return this.getElementOfClass(clazz, false);
public synchronized final <S extends SQLElement> S getElement(Class<S> clazz) {
return clazz.cast(this.getElement(getSoleTable(this.byClass, clazz)));
}
 
public final <S extends SQLElement> S getElementOfClass(Class<S> clazz, final boolean allowSubclass) {
final List<S> res = getElementsOfClass(clazz, allowSubclass);
if (res.size() > 1)
throw new IllegalArgumentException(clazz + " is not unique: " + res);
return res.isEmpty() ? null : res.get(0);
}
 
/**
* Search for SQLElement whose class is <code>clazz</code>.
*
* @param clazz the class.
* @param allowSubclass <code>true</code> to include {@link Class#isInstance(Object)
* subclasses}, <code>false</code> to only return exact match.
* @return the corresponding elements.
*/
public final <S extends SQLElement> List<S> getElementsOfClass(final Class<S> clazz, final boolean allowSubclass) {
final List<S> res;
synchronized (this) {
if (allowSubclass) {
res = new ArrayList<>();
for (final SQLElement elem : this.elements.values()) {
if (clazz.isInstance(elem))
res.add(clazz.cast(elem));
}
} else {
final Set<SQLTable> tables = this.byClass.get(clazz);
if (tables != null) {
res = new ArrayList<>(tables.size());
for (final SQLTable t : tables) {
res.add(clazz.cast(this.getElement(t)));
}
} else {
res = Collections.emptyList();
}
}
}
if (res.isEmpty()) {
return Collections.emptyList();
} else if (res.size() == 1) {
return Collections.singletonList(res.get(0));
} else {
return Collections.unmodifiableList(res);
}
}
 
public synchronized final SQLElement getElementForCode(String code) {
return this.getElement(getSoleTable(this.byCode, code));
}
/trunk/OpenConcerto/src/org/openconcerto/sql/element/GroupSQLComponent.java
64,8 → 64,8
 
private final Group group;
private final int columns = 2;
private final Map<String, JComponent> labels = new HashMap<>();
private final Map<String, JComponent> editors = new HashMap<>();
private final Map<String, JComponent> labels = new HashMap<String, JComponent>();
private final Map<String, JComponent> editors = new HashMap<String, JComponent>();
private String startTabAfter = null;
private boolean tabGroup;
private int tabDepth;
80,12 → 80,6
 
public GroupSQLComponent(final SQLElement element, final Group group) {
super(element);
if (element == null) {
throw new IllegalArgumentException("null SQLElement");
}
if (group == null) {
throw new IllegalArgumentException("null group (SQLElement : " + element + ")");
}
this.group = group;
this.hasAdditionnalFields = this.getElement().getAdditionalFields().size() > 0;
this.additionnalFieldsGroup = getAdditionalFieldsGroup(group.getDescendantGroups());
105,7 → 99,7
}
 
public void startTabGroupAfter(String id) {
this.startTabAfter = id;
startTabAfter = id;
}
 
@Override
161,8 → 155,7
c.gridx = 0;
c.weightx = 1;
c.gridwidth = 4;
JComponent comp = getLabel(id);
panel.add(comp, c);
panel.add(getLabel(id), c);
c.gridy++;
}
}
283,13 → 276,13
}
 
}
if (id.equals(this.startTabAfter)) {
if (this.tabGroup) {
if (id.equals(startTabAfter)) {
if (tabGroup) {
throw new IllegalArgumentException("ID " + id + " already set as tab");
}
this.tabGroup = true;
this.tabDepth = level;
this.pane = new JTabbedPane();
tabGroup = true;
tabDepth = level;
pane = new JTabbedPane();
c.gridx = 0;
c.gridy++;
c.weightx = 1;
296,7 → 289,7
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 4;
panel.add(this.pane, c);
panel.add(pane, c);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/sql/utils/SQLUtils.java
372,8 → 372,9
 
final long afterQueryInfo = System.nanoTime();
final long afterExecute, afterHandle;
final Statement stmt = conn.createStatement();
int count = 0;
try (final Statement stmt = conn.createStatement()){
try {
if (Thread.currentThread().isInterrupted())
throw new RTInterruptedException("Interrupted before executing : " + query);
stmt.execute(query);
391,6 → 392,8
stmt.getMoreResults();
}
afterHandle = System.nanoTime();
} finally {
stmt.close();
}
SQLRequestLog.log(query, "executeMultiple", conn, timeMs, time, afterCache, afterQueryInfo, afterExecute, afterHandle, System.nanoTime(), count);
return null;
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLUpdate.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLInsert.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLRequestLog.java
25,7 → 25,6
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DateFormat;
61,23 → 60,7
private static final String ACTIVER_LA_CAPTURE = "Enable monitoring";
private static final String DESACTIVER_LA_CAPTURE = "Disable monitoring";
private static Vector<SQLRequestLog> list = new Vector<SQLRequestLog>(500);
@GuardedBy("this")
private static boolean enabled;
 
public static synchronized void setEnabled(boolean enable) {
enabled = enable;
}
 
public static synchronized boolean toggleEnabled() {
final boolean newVal = !isEnabled();
setEnabled(newVal);
return newVal;
}
 
public static synchronized boolean isEnabled() {
return enabled;
}
 
private String query;
private String comment;
private long startAsMs;
102,6 → 85,10
return l == 0 ? "" : dformat.format(l / 1000000D) + " ms";
}
 
public static void setEnabled(boolean enable) {
enabled = enable;
}
 
public SQLRequestLog(String query, String comment, int connectionId, long starAtMs, String ex, boolean inSwing, long startTime, long afterCache, long afterQueryInfo, long afterExecute,
long afterHandle, long endTime, int count) {
this.query = query;
129,7 → 116,7
public static void log(String query, String comment, int connectionId, long starAtMs, long startTime, long afterCache, long afterQueryInfo, long afterExecute, long afterHandle, long endTime,
int count) {
 
if (isEnabled()) {
if (enabled) {
if (list.size() < 50000) {
final String ex = ExceptionUtils.getStackTrace(new Exception());
 
148,7 → 135,7
 
public static void log(PreparedStatement pStmt, String comment, long timeMs, long startTime, long afterCache, long afterQueryInfo, long afterExecute, long afterHandle, long endTime) {
// only call potentially expensive and/or exceptions throwing methods if necessary
if (isEnabled()) {
if (enabled) {
try {
log(pStmt.toString(), comment, pStmt.getConnection(), timeMs, startTime, afterCache, afterQueryInfo, afterExecute, afterHandle, endTime, 0);
} catch (Exception e) {
446,7 → 433,7
JPanel bar = new JPanel(new FlowLayout());
 
final JButton b0 = new JButton();
if (isEnabled()) {
if (enabled) {
b0.setText(DESACTIVER_LA_CAPTURE);
} else {
b0.setText(ACTIVER_LA_CAPTURE);
454,9 → 441,11
b0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!toggleEnabled()) {
if (enabled) {
enabled = false;
b0.setText(ACTIVER_LA_CAPTURE);
} else {
enabled = true;
b0.setText(DESACTIVER_LA_CAPTURE);
}
 
631,15 → 620,4
model.fireTableRowsUpdated(0, model.getRowCount() - 1);
}
}
 
public static void dump(PrintStream out) {
final DecimalFormat dformat = new DecimalFormat("##0.00");
for (SQLRequestLog log : list) {
out.print(dformat.format(log.getDurationTotalNano() / 1000000D) + " ms ");
out.print("\t");
out.print(log.getQuery());
out.println();
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLInjector.java
166,28 → 166,18
rowVals.put(field.getName(), value);
}
 
protected void transfertReference(SQLRowAccessor srcRow, SQLRowValues rowVals, final SQLTable tableElementDestination, String refField, String from, String to) {
protected void transfertReference(SQLRowAccessor srcRow, SQLRowValues rowVals, String from, String to) {
 
String label = rowVals.getString(to);
SQLPreferences prefs = SQLPreferences.getMemCached(srcRow.getTable().getDBRoot());
 
if (prefs.getBoolean("TransfertRef", true) || !to.equals("NOM")) {
if (label != null && label.trim().length() > 0) {
rowVals.put(to, label + ", " + srcRow.getString(from));
} else {
rowVals.put(to, srcRow.getString(from));
}
} else if (prefs.getBoolean("TransfertMultiRef", false)) {
SQLRowValues rowValsHeader = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(tableElementDestination));
// TODO taxe may be undefined set it to default
rowValsHeader.put("NOM", srcRow.getString(from));
rowValsHeader.put(refField, rowVals);
}
 
}
 
protected void transfertNumberReference(SQLRowAccessor srcRow, SQLRowValues rowVals, final SQLTable tableElementDestination, String refField) {
SQLPreferences prefs = SQLPreferences.getMemCached(srcRow.getTable().getDBRoot());
SQLPreferences prefs = new SQLPreferences(srcRow.getTable().getDBRoot());
 
if (prefs.getBoolean("TransfertRef", true)) {
String label = rowVals.getString("NOM");
422,7 → 412,7
* register manually a transfer, use with caution
*
* @throws SQLException
*/
* */
public void addTransfert(int idFrom, int idTo) throws SQLException {
final SQLTable tableTransfert = getSource().getTable(getTableTranferName());
final SQLRowValues rowTransfer = new SQLRowValues(tableTransfert);
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLRowValues.java
1006,7 → 1006,7
}
 
// TODO support java.time.LocalDateTime in Java 8
public static <T, U> U convert(final Class<T> source, final Object value, final Class<U> dest) {
static private <T, U> U convert(final Class<T> source, final Object value, final Class<U> dest) {
final ValueConvertor<T, U> conv = ValueConvertorFactory.find(source, dest);
if (conv == null)
throw new IllegalArgumentException("No convertor to " + dest + " from " + source);
2447,6 → 2447,7
return insert(t, sql, ReturnMode.NO_FIELDS).getCount();
}
 
// if scalar is null primary keys aren't fetched
private static final Insertion<?> insert(final SQLTable t, final String sql, final ReturnMode mode) throws SQLException {
return new Inserter(t).insert(sql, mode, true);
}
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLBackgroundTableCacheItem.java
28,11 → 28,6
public SQLBackgroundTableCacheItem(final SQLTable t, final int second) {
this.table = t;
this.timeout = second;
 
if (second == -1) {
reloadFromDB();
}
 
this.table.addTableModifiedListener(new SQLTableModifiedListener() {
 
@Override
49,20 → 44,16
this.enableReloadIfTableModified = enableReloadIfTableModified;
}
 
@SuppressWarnings("unchecked")
public synchronized void reloadFromDbIfNeeded() {
final long delta = System.currentTimeMillis() - this.lastReload;
if (this.timeout >= 0 && delta / 1000 > this.timeout) {
reloadFromDB();
}
}
 
@SuppressWarnings("unchecked")
private void reloadFromDB() {
if (delta / 1000 > this.timeout) {
final SQLSelect sel = new SQLSelect();
sel.addSelectStar(this.table);
this.rows = Collections.unmodifiableList((List<SQLRow>) this.table.getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, this.table)));
this.lastReload = System.currentTimeMillis();
}
}
 
public synchronized SQLRow getFirstRowContains(final int value, final SQLField field) {
for (SQLRow r : this.rows) {
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLBackgroundTableCache.java
19,7 → 19,7
 
public class SQLBackgroundTableCache {
private static SQLBackgroundTableCache instance;
private Map<SQLTable, SQLBackgroundTableCacheItem> list = new HashMap<>();
private Map<SQLTable, SQLBackgroundTableCacheItem> list = new HashMap<SQLTable, SQLBackgroundTableCacheItem>();
 
/**
* @param args
90,8 → 90,7
item.reloadFromDbIfNeeded();
} else {
System.err.println("SQLBackgroundTableCache.getCacheForTable() WARNING " + t.getName() + " is not registered (use add to register)");
// Start cache without autorefresh for Caisse offline
this.add(t, -1);
this.add(t, 0);
item = this.list.get(t);
item.reloadFromDbIfNeeded();
}
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLTable.java
122,7 → 122,7
};
 
@SuppressWarnings("unchecked")
public static final Map<String, Number> getUndefIDs(final SQLSchema schema) {
private static final Map<String, Number> getUndefIDs(final SQLSchema schema) {
if (!UNDEFINED_IDs.containsKey(schema)) {
final Map<String, Number> r;
if (schema.contains(undefTable)) {
556,10 → 556,7
return undef.intValue();
}
} else if ("inDB".equals(policy)) {
return SQLRow.NONEXISTANT_ID;
// FIXME : BUG A INVESTIGUER DANS LA CREATION DE MODULE throw new
// throw new IllegalStateException("Not in " + new SQLName(this.getDBRoot().getName(),
// undefTable) + " : " + this.getName());
throw new IllegalStateException("Not in " + new SQLName(this.getDBRoot().getName(), undefTable) + " : " + this.getName());
} else if (policy != null && !"nonexistant".equals(policy)) {
final int res = Integer.parseInt(policy);
if (res < SQLRow.MIN_VALID_ID)
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLDataSource.java
16,13 → 16,11
import org.openconcerto.sql.Log;
import org.openconcerto.sql.State;
import org.openconcerto.sql.request.SQLCache;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ExceptionUtils;
import org.openconcerto.utils.RTInterruptedException;
import org.openconcerto.utils.ThreadFactory;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cache.CacheResult;
import org.openconcerto.utils.cache.ICacheSupport;
 
50,8 → 48,6
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
 
import org.apache.commons.dbcp.AbandonedConfig;
997,66 → 993,7
return res;
}
 
private static final Tuple2<Long, int[]> NO_QUERIES_RES = Tuple2.create(0l, new int[0]);
 
/**
* Execute multiple queries in batch.
*
* @param queries what to execute.
* @param atomic <code>true</code> if all queries should be executed in a transaction.
* @return the total update count (&lt; 0 if unknown), followed by the individual update counts.
* @throws SQLException if an error occurs.
* @see Statement#executeBatch()
*/
public final Tuple2<Long, int[]> executeBatch(final List<String> queries, final boolean atomic) throws SQLException {
if (queries.isEmpty())
return NO_QUERIES_RES;
final long timeMs = System.currentTimeMillis();
final long time = System.nanoTime();
final long afterCache = time;
final AtomicLong afterQueryInfo = new AtomicLong();
final AtomicLong afterExecute = new AtomicLong();
final AtomicReference<Connection> conn = new AtomicReference<>();
final ConnectionHandlerNoSetup<int[], SQLException> handler = new ConnectionHandlerNoSetup<int[], SQLException>() {
@Override
public int[] handle(SQLDataSource ds) throws SQLException {
afterQueryInfo.set(System.nanoTime());
conn.set(ds.getConnection());
final int[] res;
try (final Statement stmt = conn.get().createStatement()) {
for (final String s : queries) {
stmt.addBatch(s);
}
if (Thread.currentThread().isInterrupted())
throw new RTInterruptedException("Interrupted before executing : " + queries);
res = stmt.executeBatch();
}
afterExecute.set(System.nanoTime());
return res;
}
};
final int[] res = atomic ? SQLUtils.executeAtomic(this, handler) : this.useConnection(handler);
long totalCount = 0;
int i = 0;
for (final int count : res) {
if (count == Statement.SUCCESS_NO_INFO) {
totalCount = -1;
break;
} else {
if (count < 0)
throw new SQLException("Invalid count (" + count + ") for query " + i + " : " + queries.get(i));
totalCount += count;
}
i++;
}
if (SQLRequestLog.isEnabled()) {
final long afterHandle = System.nanoTime();
SQLRequestLog.log(queries.toString(), "executeBatch", conn.get(), timeMs, time, afterCache, afterQueryInfo.get(), afterExecute.get(), afterHandle, afterHandle, (int) totalCount);
}
return Tuple2.create(totalCount, res);
}
 
/**
* Try to execute a {@link #getValidationQuery() simple query} on the database server. This
* method even works when the pool is exhausted.
*
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLRowListRSH.java
19,12 → 19,10
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
 
import org.apache.commons.dbutils.ResultSetHandler;
 
39,18 → 37,16
// ATTN doesn't check that the types of columns are coherent with the types of the fields
public RSH(final SQLTable t, final List<String> names) {
this(Tuple2.create(t, names));
// null are OK (they're ignored)
final List<String> unknown = names.stream().filter(n -> n != null && !t.getFieldsName().contains(n)).collect(Collectors.toList());
if (!unknown.isEmpty())
throw new IllegalArgumentException("Not all names are fields of " + t + " : " + unknown);
if (!t.getFieldsName().containsAll(names))
throw new IllegalArgumentException("Not all names are fields of " + t + " : " + names);
}
 
private RSH(final Tuple2<SQLTable, List<String>> names) {
private RSH(Tuple2<SQLTable, List<String>> names) {
this.names = names;
}
 
@Override
public List<SQLRow> handle(final ResultSet rs) throws SQLException {
public List<SQLRow> handle(ResultSet rs) throws SQLException {
// since the result will be cached, disallow its modification (e.g.avoid
// ConcurrentModificationException)
return Collections.unmodifiableList(SQLRow.createListFromRS(this.names.get0(), rs, this.names.get1()));
62,7 → 58,7
}
 
@Override
public boolean equals(final Object obj) {
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
82,7 → 78,7
return t;
}
 
static Tuple2<SQLTable, List<String>> getIndexes(final SQLSelect sel, final TableRef passedTable, final boolean findTable) {
static Tuple2<SQLTable, List<String>> getIndexes(SQLSelect sel, final TableRef passedTable, final boolean findTable) {
final List<FieldRef> selectFields = sel.getSelectFields();
final int size = selectFields.size();
if (size == 0)
128,7 → 124,6
* @return a handler creating a list of {@link SQLRow}.
* @deprecated use {@link SQLSelectHandlerBuilder}
*/
@Deprecated
static public ResultSetHandler createFromSelect(final SQLSelect sel) {
return create(getIndexes(sel, null, true));
}
142,7 → 137,6
* @return a handler creating a list of {@link SQLRow}.
* @deprecated use {@link SQLSelectHandlerBuilder}
*/
@Deprecated
static public ResultSetHandler createFromSelect(final SQLSelect sel, final TableRef t) {
return create(getIndexes(sel, t, false));
}
151,20 → 145,6
return new RSH(names);
}
 
static public List<SQLRow> fetch(final SQLTable t, final Collection<? extends Number> ids) throws IllegalArgumentException {
return fetch(t, ids, null);
}
 
static public List<SQLRow> fetch(final SQLTable t, final Collection<? extends Number> ids, final Collection<String> fields) throws IllegalArgumentException {
final SQLSelect sel = new SQLSelect();
if (fields == null)
sel.addSelectStar(t);
else
sel.addAllSelect(t, fields);
sel.setWhere(new Where(t.getKey(), ids));
return execute(sel);
}
 
/**
* Execute the passed select and return rows. NOTE if there's more than one table in the query
* {@link #execute(SQLSelect, TableRef)} must be used.
215,18 → 195,17
private final SQLTable t;
private final boolean tableOnly;
 
public SQLRowListRSH(final SQLTable t) {
public SQLRowListRSH(SQLTable t) {
this(t, false);
}
 
public SQLRowListRSH(final SQLTable t, final boolean tableOnly) {
public SQLRowListRSH(SQLTable t, final boolean tableOnly) {
super();
this.t = t;
this.tableOnly = tableOnly;
}
 
@Override
public List<SQLRow> handle(final ResultSet rs) throws SQLException {
public Object handle(ResultSet rs) throws SQLException {
return SQLRow.createListFromRS(this.t, rs, this.tableOnly);
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/users/User.java
15,8 → 15,6
 
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.awt.Color;
 
import net.jcip.annotations.Immutable;
 
@Immutable
24,7 → 22,6
private final int id;
private final String name, firstName, nickName;
private final Boolean active;
private final Color color;
 
public User(final SQLRowAccessor r) {
this.id = r.getID();
36,12 → 33,7
} else {
this.active = null;
}
if (r.contains("COLOR")) {
this.color = new Color(r.getInt("COLOR"));
} else {
this.color = null;
}
}
 
public String getName() {
return this.name;
71,8 → 63,4
public boolean isActive() {
return this.active;
}
 
public Color getColor() {
return this.color;
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/users/rights/SQLTableRightEditor.java
13,7 → 13,6
package org.openconcerto.sql.users.rights;
 
import org.openconcerto.sql.Log;
import org.openconcerto.sql.TM;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
28,6 → 27,7
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
 
import javax.swing.JComponent;
import javax.swing.JTextField;
41,12 → 41,15
 
@Override
public JComponent getRightEditor(final String right, final DBRoot root, final SQLElementDirectory directory, final JTextField fieldObject) {
final ISearchableCombo<SQLTableComboItem> comboMenu = new ISearchableCombo<>();
final DefaultIMutableListModel<SQLTableComboItem> comboItems = new DefaultIMutableListModel<>();
final List<SQLTableComboItem> result = new ArrayList<>();
final ISearchableCombo<SQLTableComboItem> comboMenu = new ISearchableCombo<SQLTableComboItem>();
DefaultIMutableListModel<SQLTableComboItem> comboItems = new DefaultIMutableListModel<SQLTableComboItem>();
Set<SQLTable> set = root.getTables();
 
List<SQLTableComboItem> result = new ArrayList<SQLTableComboItem>(set.size());
result.add(SQLTableComboItem.createFromTable(null));
for (SQLElement elt : directory.getElements()) {
result.add(SQLTableComboItem.create(elt.getTable(), elt));
for (SQLTable table : set) {
final SQLElement elt = directory.getElement(table);
result.add(SQLTableComboItem.create(table, elt));
}
comboItems.addAll(result);
comboMenu.initCache(comboItems);
54,7 → 57,7
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
final SQLTableComboItem selectedItem = comboMenu.getSelectedItem();
final SQLTableComboItem selectedItem = (SQLTableComboItem) comboMenu.getSelectedItem();
if (selectedItem != null) {
fieldObject.setText(selectedItem.getValue());
}
69,28 → 72,22
RightEditorManager.getInstance().register(code, editor);
}
 
public static class SQLTableComboItem {
static public class SQLTableComboItem {
 
public static SQLTableComboItem create(final SQLTable t, final SQLElement elt) {
static public SQLTableComboItem create(final SQLTable t, final SQLElement elt) {
assert elt == null || elt.getTable() == t;
return elt != null ? createFromElement(elt) : createFromTable(t);
}
 
public static SQLTableComboItem createFromElement(final SQLElement elt) {
String variant = elt.getName().getVariant(Grammar.SINGULAR);
if (variant.contains("_")) {
// quick patch for not translated tables
Log.get().warning(elt.getName() + " not translated");
variant = variant.replace('_', ' ').toLowerCase();
static public SQLTableComboItem createFromElement(final SQLElement elt) {
return new SQLTableComboItem(elt.getTable(), elt.getName().getVariant(Grammar.SINGULAR));
}
return new SQLTableComboItem(elt.getTable(), variant);
}
 
public static SQLTableComboItem createFromTable(final SQLTable t) {
return new SQLTableComboItem(t, t == null ? TM.tr("rights.allTables") : t.getName().toLowerCase().replace('_', ' '));
static public SQLTableComboItem createFromTable(final SQLTable t) {
return new SQLTableComboItem(t, t == null ? TM.tr("rights.allTables") : t.getName());
}
 
public static SQLTableComboItem createFromString(final String s, final DBRoot r, final SQLElementDirectory dir) {
static public SQLTableComboItem createFromString(final String s, final DBRoot r, final SQLElementDirectory dir) {
if (s == null)
return createFromTable(null);
final SQLName n = SQLName.parse(s);
99,7 → 96,7
final SQLTable t = r.findTable(n.getName());
if (t == null)
// allow to use unknown table (e.g. not yet created)
return new SQLTableComboItem(s, n.getName().toLowerCase().replace('_', ' '));
return new SQLTableComboItem(s, n.getName());
else
return create(t, dir.getElement(t));
}
/trunk/OpenConcerto/src/org/openconcerto/sql/users/rights/TableAllRights.java
31,11 → 31,9
public static final String ADD_ROW_TABLE = "INSERT_ROW";
public static final String VIEW_ROW_TABLE = "SELECT_ROW";
public static final String SAVE_ROW_TABLE = "SAVE_ROW";
public static final String USER_UI_LOCK_ROW = "LIST_UI_LOCK_ROWS";
public static final String USER_UI_UNLOCK_ROW = "LIST_UI_UNLOCK_ROWS";
 
public static final List<String> getCodes() {
return Arrays.asList(CODE, CODE_MODIF, DELETE_ROW_TABLE, MODIFY_ROW_TABLE, ADD_ROW_TABLE, VIEW_ROW_TABLE, SAVE_ROW_TABLE, USER_UI_UNLOCK_ROW, USER_UI_LOCK_ROW);
return Arrays.asList(CODE, CODE_MODIF, DELETE_ROW_TABLE, MODIFY_ROW_TABLE, ADD_ROW_TABLE, VIEW_ROW_TABLE, SAVE_ROW_TABLE);
}
 
public static RightTuple createRight(final SQLTable t, final boolean b) {
121,8 → 119,6
res.add(new RightTuple(DELETE_ROW_TABLE, object, haveRight));
res.add(new RightTuple(MODIFY_ROW_TABLE, object, haveRight));
res.add(new RightTuple(ADD_ROW_TABLE, object, haveRight));
res.add(new RightTuple(USER_UI_LOCK_ROW, object, haveRight));
res.add(new RightTuple(USER_UI_UNLOCK_ROW, object, haveRight));
if (getCode() == CODE)
res.add(new RightTuple(VIEW_ROW_TABLE, object, haveRight));
return res;
/trunk/OpenConcerto/src/org/openconcerto/sql/users/UserCommonSQLElement.java
28,7 → 28,6
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.itemview.SimpleRowItemView;
import org.openconcerto.sql.ui.IColorChooser;
import org.openconcerto.sql.ui.Login;
import org.openconcerto.sql.view.QuickAssignPanel;
import org.openconcerto.sql.view.list.ITableModel;
221,7 → 220,8
// Login
c.gridx = 0;
c.insets = new Insets(2, 2, 1, 2);
final JLabel labelLogin = new JLabel(getLabelFor("LOGIN"), SwingConstants.RIGHT);
final JLabel labelLogin = new JLabel(getLabelFor("LOGIN"));
labelLogin.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelLogin, c);
final JTextField textLogin = new JTextField();
c.gridx++;
242,7 → 242,8
c.gridx = 0;
c.weightx = 0;
c.insets = new Insets(2, 2, 1, 2);
final JLabel labelPass = new JLabel(getLabelFor("PASSWORD"), SwingConstants.RIGHT);
final JLabel labelPass = new JLabel(getLabelFor("PASSWORD"));
labelPass.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelPass, c);
this.passField = new JPasswordField(15);
c.gridx++;
253,7 → 254,8
// Confirmation password
c.gridx++;
c.weightx = 0;
final JLabel labelConfirmationPass = new JLabel(getLabelFor("PASSWORD_CONFIRM"), SwingConstants.RIGHT);
final JLabel labelConfirmationPass = new JLabel(getLabelFor("PASSWORD_CONFIRM"));
labelConfirmationPass.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelConfirmationPass, c);
this.passFieldConfirm = new JPasswordField(15);
c.gridx++;
265,7 → 267,8
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel labelNom = new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT);
final JLabel labelNom = new JLabel(getLabelFor("NOM"));
labelNom.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNom, c);
final JTextField textNom = new JTextField();
c.gridx++;
275,7 → 278,8
// Prenom
c.gridx++;
c.weightx = 0;
final JLabel labelPrenom = new JLabel(getLabelFor("PRENOM"), SwingConstants.RIGHT);
final JLabel labelPrenom = new JLabel(getLabelFor("PRENOM"));
labelPrenom.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelPrenom, c);
final JTextField textPrenom = new JTextField();
c.gridx++;
286,7 → 290,8
c.gridx = 0;
c.gridy++;
c.weightx = 0;
final JLabel labelSurnom = new JLabel(getLabelFor("SURNOM"), SwingConstants.RIGHT);
final JLabel labelSurnom = new JLabel(getLabelFor("SURNOM"));
labelSurnom.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelSurnom, c);
final JTextField textSurnom = new JTextField();
c.gridx++;
308,7 → 313,8
c.weightx = 0;
 
if (getTable().contains("MAIL")) {
final JLabel labelMail = new JLabel(getLabelFor("MAIL"), SwingConstants.RIGHT);
final JLabel labelMail = new JLabel(getLabelFor("MAIL"));
labelMail.setHorizontalAlignment(SwingConstants.RIGHT);
c.anchor = GridBagConstraints.NORTHWEST;
this.add(labelMail, c);
c.gridx++;
319,7 → 325,6
this.add(textMail, c);
this.addView(textMail, "MAIL");
}
 
if (getTable().contains("OUT")) {
c.gridx++;
final JCheckBox boxOut = new JCheckBox(getLabelFor("OUT"));
340,24 → 345,9
}
}
c.gridy++;
 
if (getTable().contains("COMPTE_NUMERO")) {
final JLabel labelMail = new JLabel(getLabelFor("COMPTE_NUMERO"));
labelMail.setHorizontalAlignment(SwingConstants.RIGHT);
c.anchor = GridBagConstraints.NORTHWEST;
this.add(labelMail, c);
c.gridx++;
final JTextField textMail = new JTextField();
c.gridwidth = 1;
c.weightx = 1;
c.gridy++;
this.add(textMail, c);
this.addView(textMail, "COMPTE_NUMERO");
}
 
if (getTable().contains("TEL")) {
c.gridx = 0;
final JLabel labelTel = new JLabel(getLabelFor("TEL"), SwingConstants.RIGHT);
final JLabel labelTel = new JLabel(getLabelFor("TEL"));
c.gridwidth = 1;
c.weightx = 0;
this.add(labelTel, c);
375,20 → 365,6
this.add(boxCalUser, c);
this.addView(boxCalUser, "CALENDAR_USER");
}
if (getTable().contains("COLOR")) {
c.gridy++;
c.gridx = 0;
final JLabel labelTel = new JLabel(getLabelFor("COLOR"), SwingConstants.RIGHT);
c.gridwidth = 1;
c.weightx = 0;
this.add(labelTel, c);
final IColorChooser colorChooser = new IColorChooser(getLabelFor("COLOR"));
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(colorChooser, c);
this.addView(colorChooser, "COLOR");
}
 
final boolean gestionHoraire = false;
if (Configuration.getInstance().getAppName().startsWith("OpenConcerto") && gestionHoraire) {
/trunk/OpenConcerto/src/org/openconcerto/utils/ooxml/XLSXStyle.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/ooxml/XLSXFormat.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/ooxml/XLSXSheet.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/ooxml/XLSXDocument.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/NetUtils.java
22,17 → 22,11
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
public class NetUtils {
 
131,10 → 125,6
}
};
 
public static final String getHTTPContent(String address) {
return getHTTPContent(address, false);
}
 
public static final String getHTTPContent(String address, final boolean dontVerify) {
String content = "";
OutputStream out = null;
177,23 → 167,4
 
return content;
}
 
// Create a trust manager that does not validate certificate chains
static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
 
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
 
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
 
static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
final SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
return sc;
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/StringUtils.java
28,7 → 28,6
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
821,13 → 820,4
}
return b.toString();
}
 
public static final Matcher findFirstContaining(final String s, final Pattern... patterns) {
for (final Pattern p : patterns) {
final Matcher matcher = p.matcher(s);
if (matcher.find())
return matcher;
}
return null;
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/sync/SimpleSyncClient.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/sync/HashWriter.java
13,8 → 13,6
package org.openconcerto.utils.sync;
 
import org.openconcerto.utils.MessageDigestUtils;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
40,8 → 38,8
}
final DataOutputStream bOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
bOut.writeInt((int) this.in.length());
final MessageDigest hashSum = MessageDigestUtils.getSHA256();
final MessageDigest md5 = MessageDigestUtils.getMD5();
final MessageDigest hashSum = MessageDigest.getInstance("SHA-256");
final MessageDigest md5 = MessageDigest.getInstance("MD5");
fb = new BufferedInputStream(new FileInputStream(in));
final RollingChecksum32 r32 = new RollingChecksum32();
final byte[] buffer = new byte[BLOCK_SIZE];
76,8 → 74,8
}
}
 
public static byte[] getHash(File f) throws IOException {
final MessageDigest hashSum = MessageDigestUtils.getSHA256();
public static byte[] getHash(File f) throws Exception {
final MessageDigest hashSum = MessageDigest.getInstance("SHA-256");
FileInputStream fIn = null;
try {
fIn = new FileInputStream(f);
125,15 → 123,4
return true;
}
 
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
 
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TranslationManager.java
25,17 → 25,16
import java.util.Map;
import java.util.ResourceBundle.Control;
 
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
 
@ThreadSafe
public class TranslationManager {
private static final Locale FALLBACK_LOCALE = Locale.ENGLISH;
65,7 → 64,7
@GuardedBy("classes")
private Locale locale;
 
private final Object trMutex = new Object();
private final Object trMutex = new String("translations mutex");
@GuardedBy("trMutex")
private Map<String, String> menuTranslation;
@GuardedBy("trMutex")
74,7 → 73,7
private Map<String, String> actionTranslation;
 
private TranslationManager() {
this.classes = new ArrayList<>();
this.classes = new ArrayList<Class<?>>();
}
 
public void addTranslationStreamFromClass(Class<?> c) {
165,10 → 164,10
 
private void loadAllTranslation() {
synchronized (this.trMutex) {
this.menuTranslation = new HashMap<>();
this.itemTranslation = new HashMap<>();
this.actionTranslation = new HashMap<>();
if (this.classes.isEmpty()) {
this.menuTranslation = new HashMap<String, String>();
this.itemTranslation = new HashMap<String, String>();
this.actionTranslation = new HashMap<String, String>();
if (this.classes.size() == 0) {
Log.get().warning("TranslationManager has no resources to load (" + this.getLocale() + ")");
}
for (Class<?> c : this.classes) {
183,7 → 182,7
// return all existing (e.g fr_CA only specify differences with fr)
private List<InputStream> findStream(final Locale locale, final Class<?> c, final boolean rootLast) {
final Control cntrl = CONTROL;
final List<InputStream> res = new ArrayList<>();
final List<InputStream> res = new ArrayList<InputStream>();
final String baseName = c.getPackage().getName() + "." + BASENAME;
 
// test emptiness to not mix languages
204,7 → 203,7
// we want more specific translations to replace general ones, i.e. root Locale first
for (final InputStream input : findStream(l, c, false)) {
// create new instances to check if there's no duplicates in each resource
final Map<String, String> menuTranslation = new HashMap<>(), itemTranslation = new HashMap<>(), actionTranslation = new HashMap<>();
final Map<String, String> menuTranslation = new HashMap<String, String>(), itemTranslation = new HashMap<String, String>(), actionTranslation = new HashMap<String, String>();
loadTranslation(input, menuTranslation, itemTranslation, actionTranslation);
// on the other hand, it's OK for one resource to override another
this.menuTranslation.putAll(menuTranslation);
215,14 → 214,10
return translationLoaded;
}
 
private static void loadTranslation(final InputStream input, final Map<String, String> menuTranslation, final Map<String, String> itemTranslation, final Map<String, String> actionTranslation) {
// FIXME : l'implementation de Java est lente
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl : 60 ms!
// On pourrait passer à 1ms avec Piccolo...
static private void loadTranslation(final InputStream input, final Map<String, String> menuTranslation, final Map<String, String> itemTranslation, final Map<String, String> actionTranslation) {
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
 
try {
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(input);
// Menus
244,7 → 239,7
}
}
 
private static void loadTranslation(final Document doc, final String tagName, final Map<String, String> m) {
static private void loadTranslation(final Document doc, final String tagName, final Map<String, String> m) {
final NodeList menuChildren = doc.getElementsByTagName(tagName);
final int size = menuChildren.getLength();
for (int i = 0; i < size; i++) {
/trunk/OpenConcerto/src/org/openconcerto/utils/CollectionMap2.java
122,9 → 122,6
 
// ** copy constructors
 
// ATTN getDelegate() is not in CollectionMap2Itf, so if one copies an unmodifiableMap() this
// constructor won't be used and the delegate will be the default HashMap (even if the source
// used a LinkedHashMap).
public CollectionMap2(final CollectionMap2<K, C, ? extends V> m) {
this(CopyUtils.copy(m.getDelegate()), m);
}
/trunk/OpenConcerto/src/org/openconcerto/utils/TableSorter.java
348,12 → 348,8
* @return the corresponding index in the model.
*/
public int modelIndex(int viewIndex) {
try {
return getViewToModel()[viewIndex].modelIndex;
} catch (Exception e) {
throw new IllegalStateException(this + " couldn't get model index for view index " + viewIndex + " with " + this.getTableModel().getRowCount() + " row(s) in our model", e);
}
}
 
private int[] getModelToView() {
if (!SwingUtilities.isEventDispatchThread()) {
434,11 → 430,6
this.supp.removePropertyChangeListener(l);
}
 
@Override
public String toString() {
return this.getClass().getSimpleName() + " on " + this.getTableModel();
}
 
// Helper classes
 
private class Row implements Comparable<Row> {
/trunk/OpenConcerto/src/org/openconcerto/utils/FileUtils.java
695,7 → 695,6
* @see StreamUtils#createXMLWriter(java.io.OutputStream)
*/
public static BufferedWriter createXMLWriter(final File f) throws IOException {
FileUtils.mkParentDirs(f);
final FileOutputStream outs = new FileOutputStream(f);
try {
return StreamUtils.createXMLWriter(outs);
/trunk/OpenConcerto/src/org/openconcerto/utils/text/CSVReader.java
29,6 → 29,7
 
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
247,4 → 248,11
br.close();
}
 
public static void main(String[] args) throws IOException {
CSVReader reader = new CSVReader(new FileReader("n:\\Sans nom 1.csv"));
String[] s = reader.readNext();
for (int i = 0; i < s.length; i++) {
System.err.println("CSVReader.main() :" + i + " : " + s[i]);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/ProductInfo.java
14,9 → 14,6
package org.openconcerto.utils;
 
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
 
160,12 → 157,6
return this.getProperty(VERSION);
}
 
public final void store(final Path p) throws IOException {
try (final OutputStream out = Files.newOutputStream(p)) {
this.getProps().store(out, this.getClass().getName());
}
}
 
@Override
public String toString() {
return this.getClass().getSimpleName() + " for " + getName() + " " + getVersion();
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/IExnFactory.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/Cookies.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/IFactory.java
13,9 → 13,8
package org.openconcerto.utils.cc;
 
public interface IFactory<E> extends IExnFactory<E, RuntimeException> {
public interface IFactory<E> {
 
@Override
public abstract E createChecked();
 
}
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/CustomEquals.java
19,10 → 19,7
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
import java.util.Set;
import java.util.function.BiPredicate;
 
/**
* Allow to create a proxy object which uses a {@link HashingStrategy}.
106,28 → 103,6
return CompareUtils.equals(sA, sB);
}
 
static public final <S, T1 extends S> int indexOf(final List<T1> s1, final S o, final HashingStrategy<S> s) {
return indexOf(s1, o, s::equals);
}
 
static public final <S, T1 extends S> int indexOf(final List<T1> s1, final S o, final BiPredicate<S, S> s) {
if (s1 instanceof RandomAccess) {
final int stop = s1.size();
for (int i = 0; i < stop; i++) {
if (s.test(s1.get(i), o))
return i;
}
} else {
final ListIterator<T1> listIter = s1.listIterator();
while (listIter.hasNext()) {
final T1 item = listIter.next();
if (s.test(item, o))
return listIter.previousIndex();
}
}
return -1;
}
 
static public class ProxyFull<S, E extends S> implements ProxyItf<E> {
 
static public final <S, E extends S> Set<ProxyFull<S, E>> createSet(final HashingStrategy<S> strategy, final Collection<E> coll) {
217,12 → 192,7
else
return this.strategy.equals(this.getDelegate(), delegate2);
}
 
@Override
public String toString() {
return this.getClass().getSimpleName() + " using strategy " + this.getStrategy() + " for " + this.getDelegate();
}
}
 
/**
* A proxy object which uses a {@link HashingStrategy}.
/trunk/OpenConcerto/src/org/openconcerto/utils/CollectionUtils.java
18,7 → 18,6
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.cc.IdentityHashSet;
import org.openconcerto.utils.cc.IdentitySet;
import org.openconcerto.utils.cc.LinkedIdentitySet;
import org.openconcerto.utils.cc.Transformer;
 
import java.io.Serializable;
644,16 → 643,14
return collector;
}
 
@SuppressWarnings("unchecked")
public static <T> Collection<T> subtract(final Collection<T> a, final Collection<? extends T> b) {
final Collection<T> res = a instanceof IdentitySet ? new LinkedIdentitySet<>(a) : new ArrayList<>(a);
for (Iterator<? extends T> it = b.iterator(); it.hasNext();) {
res.remove(it.next());
return org.apache.commons.collections.CollectionUtils.subtract(a, b);
}
return res;
}
 
@SuppressWarnings("unchecked")
public static <T> Collection<T> substract(final Collection<T> a, final Collection<? extends T> b) {
return subtract(a, b);
return org.apache.commons.collections.CollectionUtils.subtract(a, b);
}
 
public static final <T> T coalesce(T o1, T o2) {
938,11 → 935,10
* @param <K> type of key.
* @param <V> type of value.
* @param keys the keys of the map.
* @return a new ordered map.
* @return a new map, if <code>keys</code> is a {@link List} it will be ordered.
*/
public static <K, V> Map<K, V> createMap(Collection<? extends K> keys) {
// there's no way to tell if a Collection is ordered, so always use ordered map.
return fillMap(new LinkedHashMap<K, V>(keys.size()), keys);
return fillMap(keys instanceof List ? new LinkedHashMap<K, V>(keys.size()) : new HashMap<K, V>(keys.size()), keys);
}
 
/**
/trunk/OpenConcerto/src/org/openconcerto/xml/FastXMLProperties.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/xml/XMLDecoderJDOM.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/xml/AbstractXMLDecoder.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/xml/XMLUtils.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/xml/XMLDecoderStAX.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/xml/XMLCodecUtils.java
13,6 → 13,11
package org.openconcerto.xml;
 
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.cache.CacheResult;
import org.openconcerto.utils.cache.ICache;
import org.openconcerto.utils.cc.ExnTransformer;
 
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
30,8 → 35,11
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
39,6 → 47,7
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;
import java.util.Stack;
 
import org.jdom2.Element;
import org.jdom2.JDOMException;
53,6 → 62,9
 
private static final String END_DECL = "?>";
 
private static final ICache<Object, Method, Object> cache = new ICache<Object, Method, Object>(60, -1, "methods for " + XMLCodecUtils.class);
private static final ICache<Object, Constructor<?>, Object> cacheCtor = new ICache<Object, Constructor<?>, Object>(60, -1, "constructors for " + XMLCodecUtils.class);
 
// the same as XMLEncoder
private static final Charset CS = Charset.forName("UTF-8");
 
73,9 → 85,6
}
};
 
public static final XMLDecoderJDOM XML_DECODER_JDOM = new XMLDecoderJDOM();
public static final XMLDecoderStAX XML_DECODER_STAX = new XMLDecoderStAX();
 
/**
* Register a {@link PersistenceDelegate} for the passed class. This method tries to set
* <code>del</code> as the default for any subsequent {@link Encoder}, but with the current JRE
121,46 → 130,7
return res;
}
 
public static final String encodeAsArray(final Map<?, ?> m) {
return encodeAsArray(m, new StringBuilder(1024)).toString();
}
 
/**
* Encode a map as an array. Useful since parsing an array is faster than parsing a map.
*
* @param m the map to encode.
* @param sb where to encode.
* @return <code>sb</code>.
* @see AbstractXMLDecoder#decodeFromArray(Object, Class, Class)
*/
public static final StringBuilder encodeAsArray(final Map<?, ?> m, final StringBuilder sb) {
final Object[] array = new Object[m.size() * 2];
int i = 0;
for (final Entry<?, ?> e : m.entrySet()) {
array[i++] = e.getKey();
array[i++] = e.getValue();
}
assert i == array.length;
return encodeSimple(array, sb);
}
 
public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass) {
return decodeFromArray(array, keyClass, valueClass, null);
}
 
public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass, Map<K, V> m) {
final int l = array.length;
if (m == null)
m = new HashMap<K, V>((int) (l / 2 / 0.8f) + 1, 0.8f);
for (int i = 0; i < l; i += 2) {
final K key = keyClass.cast(array[i]);
final V value = valueClass.cast(array[i + 1]);
m.put(key, value);
}
return m;
}
 
/**
* Encodes an object using {@link XMLEncoder}, stripping the XML declaration.
*
* @param o the object to encode.
183,14 → 153,10
*/
public static final String encodeSimple(Object o) {
final StringBuilder sb = new StringBuilder(256);
return encodeSimple(o, sb).toString();
}
 
public static final StringBuilder encodeSimple(final Object o, final StringBuilder sb) {
sb.append("<java version=\"1.6.0\" class=\"java.beans.XMLDecoder\">");
encodeSimpleRec(o, sb);
sb.append("</java>");
return sb;
return sb.toString();
}
 
private static final void createElemEscaped(final String elemName, final Object o, final StringBuilder sb) {
395,9 → 361,287
* @return the decoded object.
*/
public static final Object decode1(Element javaElem) {
return XML_DECODER_JDOM.decode1(javaElem);
final Element elem = (Element) javaElem.getChildren().get(0);
try {
return eval(elem, new Stack<Object>(), new HashMap<String, Object>());
} catch (Exception e) {
throw new IllegalStateException("error decoding " + JDOM2Utils.output(javaElem), e);
}
}
 
private static final Object eval(Element elem, Stack<Object> context, final Map<String, Object> ids)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
final String n = elem.getName();
// Ordered from real world scenario
// string : 80k
// void : 53k
// int : 18k
// object : 9k
// null : 6k
if (n.equals("string")) {
return elem.getText();
} else if (n.equals("void") || n.equals("object")) {
final String idref = elem.getAttributeValue("idref");
if (idref != null) {
if (!ids.containsKey(idref))
throw new IllegalStateException("id '" + idref + "' wasn't defined");
return ids.get(idref);
}
final String id = elem.getAttributeValue("id");
final String targetClass = elem.getAttributeValue("class");
final Object target = targetClass == null ? context.peek() : Class.forName(targetClass);
final String propAttr = elem.getAttributeValue("property");
final String indexAttr = elem.getAttributeValue("index");
final String methodAttr = elem.getAttributeValue("method");
 
// statement or expression
final Object res = evalContainer(elem, context, ids, new ExnTransformer<List<Object>, Object, Exception>() {
@Override
public Object transformChecked(List<Object> args) throws Exception {
// call the statement
final Object res;
 
if (propAttr != null) {
final String methodName = (args.size() == 0 ? "get" : "set") + StringUtils.firstUp(propAttr);
res = invoke(target, methodName, args);
} else if (indexAttr != null) {
final String methodName;
if (target instanceof List) {
methodName = args.size() == 0 ? "get" : "set";
// get(index) or set(index, value)
args.add(0, Integer.valueOf(indexAttr));
res = invoke(target, methodName, args);
} else if (target.getClass().isArray()) {
final Class<?> componentType = target.getClass().getComponentType();
// in Array there's set(array, int index, Object value) or
// setPrimitive(array, int index, primitive value)
methodName = (args.size() == 0 ? "get" : "set") + (componentType.isPrimitive() ? StringUtils.firstUp(componentType.getSimpleName()) : "");
args.add(0, target);
args.add(1, Integer.valueOf(indexAttr));
res = invoke(Array.class, methodName, args);
} else
throw new IllegalStateException("use index with neither List nor array: " + target);
} else if (methodAttr != null) {
res = invoke(target, methodAttr, args);
} else
res = getCtor((Class<?>) target, args).newInstance(args.toArray());
return res;
}
});
// not very functional but it works
if (id != null)
ids.put(id, res);
return res;
} else if (n.equals("int")) {
return Integer.valueOf(elem.getText());
} else if (n.equals("null")) {
return null;
} else if (n.equals("boolean")) {
return Boolean.valueOf(elem.getText());
} else if (n.equals("byte")) {
return Byte.valueOf(elem.getText());
} else if (n.equals("char")) {
return Character.valueOf(elem.getText().charAt(0));
} else if (n.equals("short")) {
return Short.valueOf(elem.getText());
} else if (n.equals("long")) {
return Long.valueOf(elem.getText());
} else if (n.equals("float")) {
return Float.valueOf(elem.getText());
} else if (n.equals("double")) {
return Double.valueOf(elem.getText());
} else if (n.equals("array")) {
final String classAttr = elem.getAttributeValue("class");
final String lengthAttr = elem.getAttributeValue("length");
 
final Class<?> componentClass = parseClassName(classAttr);
if (lengthAttr != null) {
context.push(Array.newInstance(componentClass, Integer.parseInt(lengthAttr)));
for (final Object child : elem.getChildren()) {
eval((Element) child, context, ids);
}
return context.pop();
} else {
return evalContainer(elem, context, ids, new ExnTransformer<List<Object>, Object, RuntimeException>() {
@Override
public Object transformChecked(List<Object> args) {
final Object res = Array.newInstance(componentClass, args.size());
for (int j = 0; j < args.size(); j++) {
Array.set(res, j, args.get(j));
}
return res;
}
});
}
} else if (n.equals("class")) {
return Class.forName(elem.getText());
} else
throw new UnsupportedOperationException("doesn't yet support " + n);
}
 
private static final Object evalContainer(final Element parent, Stack<Object> context, final Map<String, Object> ids, final ExnTransformer<List<Object>, Object, ? extends Exception> transf)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
final List<Object> args = new ArrayList<Object>();
final List<?> children = parent.getChildren();
int i = 0;
boolean noVoid = true;
final int size = children.size();
while (i < size && noVoid) {
final Element child = (Element) children.get(i);
if (child.getName().equals("void"))
noVoid = false;
else {
args.add(eval(child, context, ids));
i++;
}
}
 
// call the statement
final Object res = transf.transformCheckedWithExn(args, false, InvocationTargetException.class, InstantiationException.class, IllegalAccessException.class);
 
context.push(res);
 
// now call the voids
while (i < children.size()) {
final Element child = (Element) children.get(i);
eval(child, context, ids);
i++;
}
return context.pop();
}
 
private static final Object invoke(final Object target, String methodName, final List<Object> args) throws IllegalAccessException, InvocationTargetException {
// <object class="Cell" method="createEmpty" >
// for static methods the target is already a class
final Class clazz = target instanceof Class ? (Class) target : target.getClass();
final Method m = getMethod(clazz, methodName, args);
return m.invoke(target, args.toArray());
}
 
private static final Method getMethod(Class<?> clazz, String name, List<Object> actualArgs) {
final List<Class<?>> actualClasses = objectsToClasses(actualArgs);
final List<Object> key = new ArrayList<Object>(3);
key.add(clazz);
key.add(name);
key.add(actualClasses);
 
final CacheResult<Method> cacheRes = cache.check(key);
if (cacheRes.getState() == CacheResult.State.VALID)
return cacheRes.getRes();
 
final Method res = findMethod(clazz, name, actualClasses);
cache.put(key, res);
return res;
}
 
private static final Constructor getCtor(Class<?> clazz, List<Object> actualArgs) {
final List<Class<?>> actualClasses = objectsToClasses(actualArgs);
final List<Object> key = new ArrayList<Object>(3);
key.add(clazz);
key.add(actualClasses);
 
final CacheResult<Constructor<?>> cacheRes = cacheCtor.check(key);
if (cacheRes.getState() == CacheResult.State.VALID)
return cacheRes.getRes();
 
final Constructor res = findCtor(clazz, actualClasses);
cacheCtor.put(key, res);
return res;
}
 
private static final List<Class<?>> objectsToClasses(List<Object> actualArgs) {
final List<Class<?>> actualClasses = new ArrayList<Class<?>>(actualArgs.size());
for (final Object actualArg : actualArgs)
actualClasses.add(actualArg == null ? null : actualArg.getClass());
return actualClasses;
}
 
// TODO return the most specific matching method instead of the first one
// (handle both Sub/Superclass and primitive/object type)
private static final Method findMethod(Class<?> clazz, String name, List<Class<?>> actualArgs) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && callableWith(m.getParameterTypes(), actualArgs)) {
return m;
}
}
return null;
}
 
// TODO see findMethod()
private static final Constructor findCtor(Class<?> clazz, List<Class<?>> actualArgs) {
for (final Constructor m : clazz.getConstructors()) {
if (callableWith(m.getParameterTypes(), actualArgs)) {
return m;
}
}
return null;
}
 
private static final boolean callableWith(Class<?>[] formalArgs, List<Class<?>> actualArgs) {
if (formalArgs.length != actualArgs.size())
return false;
int i = 0;
for (final Class<?> argClass : formalArgs) {
final Class<?> actualArg = actualArgs.get(i);
// null match everything
if (actualArg != null && !argClass.isAssignableFrom(actualArg) && argClass != getPrimitive(actualArg))
return false;
i++;
}
 
return true;
}
 
private static Class<?> getPrimitive(Class<?> argClass) {
if (argClass == Boolean.class)
return Boolean.TYPE;
else if (argClass == Character.class)
return Character.TYPE;
else if (argClass == Byte.class)
return Byte.TYPE;
else if (argClass == Short.class)
return Short.TYPE;
else if (argClass == Integer.class)
return Integer.TYPE;
else if (argClass == Long.class)
return Long.TYPE;
else if (argClass == Float.class)
return Float.TYPE;
else if (argClass == Double.class)
return Double.TYPE;
else
return null;
}
 
private static final Map<String, Class> primitiveNames = new HashMap<String, Class>();
 
static {
primitiveNames.put("boolean", boolean.class);
primitiveNames.put("byte", byte.class);
primitiveNames.put("char", char.class);
primitiveNames.put("short", short.class);
primitiveNames.put("int", int.class);
primitiveNames.put("long", long.class);
primitiveNames.put("float", float.class);
primitiveNames.put("double", double.class);
}
 
/**
* Parse class names (including primitive).
*
* @param className a class name, eg "java.lang.String" or "int".
* @return the matching class, eg java.lang.String.class or Integer.TYPE.
* @throws ClassNotFoundException if the passed name doesn't exist.
*/
private static Class<?> parseClassName(String className) throws ClassNotFoundException {
final Class<?> primitive = primitiveNames.get(className);
if (primitive != null)
return primitive;
else
return Class.forName(className);
}
 
private XMLCodecUtils() {
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/stat/action/ReportingCommercialAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeSQLElement.java
21,7 → 21,6
import org.openconcerto.erp.core.supplychain.receipt.component.BonReceptionSQLComponent;
import org.openconcerto.erp.generationDoc.gestcomm.CommandeXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
34,7 → 33,6
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.sql.view.list.IListe;
52,8 → 50,6
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
71,57 → 67,11
transfertBR(selectedRows);
}
 
}, true, "supplychain.order.create.receipt");
}, false, "supplychain.order.create.receipt");
 
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(bonAction);
 
PredicateRowAction actionsTRFA = new PredicateRowAction(new AbstractAction("Transfert vers facture fournisseur") {
public void actionPerformed(ActionEvent e) {
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
SwingWorker<Boolean, Object> worker = new SwingWorker<Boolean, Object>() {
@Override
protected Boolean doInBackground() throws Exception {
 
boolean b = TransfertBaseSQLComponent.isAlreadyAllTransfert(selectedRows, getTable(), getTable().getTable("FACTURE_FOURNISSEUR"), "T_HT", "T_HT");
 
if (b) {
String label = "Attention ";
if (selectedRows.size() > 1) {
label += " les " + getPluralName() + " ont déjà été transféré!";
} else {
label += getSingularName() + " a déjà été transféré!";
}
label += "\n Voulez vous continuer?";
 
int ans = JOptionPane.showConfirmDialog(null, label, "Transfert " + getSingularName(), JOptionPane.YES_NO_OPTION);
if (ans == JOptionPane.NO_OPTION) {
return Boolean.FALSE;
}
}
 
return Boolean.TRUE;
 
}
 
@Override
protected void done() {
try {
Boolean b = get();
if (b) {
TransfertBaseSQLComponent.openTransfertFrame(selectedRows, "FACTURE_FOURNISSEUR");
}
} catch (Exception e) {
ExceptionHandler.handle("Erreur lors du transfert des " + getPluralName() + "!", e);
}
}
};
worker.execute();
}
}, false);
actionsTRFA.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(actionsTRFA);
 
// Transfert vers facture
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
157,13 → 107,9
l.add("NOM");
l.add("DATE");
l.add("ID_FOURNISSEUR");
l.add("ID_COMMERCIAL");
l.add("T_HT");
l.add("T_TTC");
Boolean useCommandeEnCours = SQLPreferences.getMemCached(getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.COMMANDE_FOURNISSEUR_EN_COURS, false);
if (useCommandeEnCours) {
l.add("EN_COURS");
}
l.add("INFOS");
return l;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/EtatDemandeAchatItemSQLElement.java
17,9 → 17,9
package org.openconcerto.erp.core.supplychain.order.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.IColorChooser;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.ui.IColorChooser;
import org.openconcerto.utils.ListMap;
 
import java.util.ArrayList;
68,7 → 68,7
return new UISQLComponent(this) {
public void addViews() {
this.addRequiredSQLObject(new JTextField(), "NOM", "left");
this.addRequiredSQLObject(new IColorChooser("Couleur"), "COLOR", "right");
this.addRequiredSQLObject(new IColorChooser(), "COLOR", "right");
}
};
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/FactureFournisseurSQLElement.java
19,23 → 19,15
import org.openconcerto.erp.generationDoc.gestcomm.FactureFournisseurXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLRowAccessor;
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.ListMap;
 
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;
 
public class FactureFournisseurSQLElement extends ComptaSQLConfElement {
 
public FactureFournisseurSQLElement() {
49,22 → 41,7
actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionAttachment);
}
RowAction actionClone = new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
 
EditFrame editFrame = new EditFrame(FactureFournisseurSQLElement.this, EditPanel.CREATION);
 
((FactureFournisseurSQLComponent) editFrame.getSQLComponent()).loadFactureExistante(IListe.get(e).getSelectedId());
editFrame.setVisible(true);
}
}, true, "supplychain.invoice.clone") {
public boolean enabledFor(IListeEvent evt) {
List<? extends SQLRowAccessor> l = evt.getSelectedRows();
return (l != null && l.size() == 1);
}
};
getRowActions().add(actionClone);
}
 
@Override
public Set<String> getReadOnlyFields() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandeAchatItemSQLElement.java
25,7 → 25,6
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLInjector;
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;
93,6 → 92,7
 
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowValues> rows = IListe.get(e).getSelectedRows();
StyleSQLElement styleElt = getDirectory().getElement(StyleSQLElement.class);
int idNormal = styleElt.getAllStyleByName().get("Normal");
 
99,10 → 99,9
SQLRowValues rowVals = new SQLRowValues(getTable().getTable("DEMANDE_PRIX"));
rowVals.put("DATE", new Date());
SQLInjector inj = SQLInjector.getInjector(getTable(), getTable().getTable("DEMANDE_PRIX_ELEMENT"));
 
final List<SQLRow> rows = SQLRowListRSH.fetch(IListe.get(e).getRequest().getPrimaryTable(), IListe.get(e).getSelection().getSelectedIDs());
 
for (SQLRow row : rows) {
for (SQLRowValues sqlRowValues : rows) {
SQLRow row = sqlRowValues.asRow();
row.fetchValues();
rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
rowValsCmdElt.put("ID_STYLE", idNormal);
153,6 → 152,7
 
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowValues> rows = IListe.get(e).getSelectedRows();
StyleSQLElement styleElt = getDirectory().getElement(StyleSQLElement.class);
int idNormal = styleElt.getAllStyleByName().get("Normal");
 
159,8 → 159,9
SQLRowValues rowVals = new SQLRowValues(getTable().getTable("COMMANDE"));
rowVals.put("DATE", new Date());
SQLInjector inj = SQLInjector.getInjector(getTable(), getTable().getTable("COMMANDE_ELEMENT"));
final List<SQLRow> rows = SQLRowListRSH.fetch(IListe.get(e).getRequest().getPrimaryTable(), IListe.get(e).getSelection().getSelectedIDs());
for (SQLRow row : rows) {
for (SQLRowValues sqlRowValues : rows) {
SQLRow row = sqlRowValues.asRow();
row.fetchValues();
rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
rowValsCmdElt.put("ID_STYLE", idNormal);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesAction.java
14,11 → 14,9
package org.openconcerto.erp.core.supplychain.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
27,17 → 25,13
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.PercentTableCellRenderer;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
 
import java.awt.GridBagConstraints;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
import javax.swing.Action;
53,135 → 47,28
 
final SQLElement elementCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE");
final SQLTableModelSourceOnline tableSource = elementCmd.getTableSource(true);
BaseSQLTableModelColumn colAvancementR = new BaseSQLTableModelColumn("Avancement réception", BigDecimal.class) {
BaseSQLTableModelColumn colAvancement = new BaseSQLTableModelColumn("Avancement réception", BigDecimal.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
return getAvancementLFromBR(r);
return getAvancement(r);
}
 
@Override
public Set<FieldPath> getPaths() {
final Path p = new PathBuilder(elementCmd.getTable()).addTable("COMMANDE_ELEMENT").build();
return CollectionUtils.createSet(new FieldPath(p, "RECU_FORCED"), new FieldPath(p, "RECU"), new FieldPath(p, "QTE_RECUE"), new FieldPath(p, "PA_HT"), new FieldPath(p, "ID_ARTICLE"),
new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"));
final Path p = new PathBuilder(elementCmd.getTable()).addTable("TR_COMMANDE").addTable("BON_RECEPTION").build();
return CollectionUtils.createSet(new FieldPath(p, "TOTAL_HT"));
}
};
tableSource.getColumns().add(colAvancementR);
colAvancementR.setRenderer(new PercentTableCellRenderer());
 
BaseSQLTableModelColumn colAvancement = new BaseSQLTableModelColumn("Avancement facturation", BigDecimal.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
return getAvancementFact(r);
}
 
@Override
public Set<FieldPath> getPaths() {
final Path p = new PathBuilder(elementCmd.getTable()).addTable("TR_COMMANDE").addTable("SAISIE_ACHAT").build();
final Path p2 = new PathBuilder(elementCmd.getTable()).addTable("TR_COMMANDE").addTable("FACTURE_FOURNISSEUR").build();
 
final Path pBr = new PathBuilder(elementCmd.getTable()).addTable("TR_COMMANDE").addTable("BON_RECEPTION").build();
final Path trBr = pBr.add(elementCmd.getTable().getTable("TR_BON_RECEPTION"));
final Path pFact2 = trBr.addTable("FACTURE_FOURNISSEUR");
final Path pAchat2 = trBr.addTable("SAISIE_ACHAT");
return CollectionUtils.createSet(new FieldPath(p, "MONTANT_HT"), new FieldPath(p2, "T_HT"), new FieldPath(pAchat2, "MONTANT_HT"), new FieldPath(pFact2, "T_HT"));
}
};
tableSource.getColumns().add(colAvancement);
colAvancement.setRenderer(new PercentTableCellRenderer());
 
final ListeAddPanel panel = new ListeAddPanel(elementCmd, new IListe(tableSource));
// Date panel
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(panel.getListe(), elementCmd.getTable().getField("DATE"));
final IListFrame frame = new IListFrame(new ListeAddPanel(elementCmd, new IListe(tableSource)));
 
IListFilterDatePanel datePanel = new IListFilterDatePanel(map, IListFilterDatePanel.getDefaultMap());
GridBagConstraints c = new DefaultGridBagConstraints();
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
c.gridy = 4;
c.anchor = GridBagConstraints.CENTER;
c.weighty = 0;
datePanel.setFilterOnDefault();
panel.add(datePanel, c);
final IListFrame frame = new IListFrame(panel);
 
return frame;
}
 
private BigDecimal getAvancementLFromBR(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("COMMANDE_ELEMENT"));
BigDecimal totalQte = BigDecimal.ZERO;
BigDecimal totalQteL = BigDecimal.ZERO;
for (SQLRowAccessor row : rows) {
BigDecimal qte = row.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(row.getInt("QTE")));
// On ne prend en compte que les articles ou les lignes différentes de 0
if (!row.isForeignEmpty("ID_ARTICLE") || row.getBigDecimal("PA_HT").signum() != 0) {
totalQte = totalQte.add(qte);
if (row.getBoolean("RECU_FORCED") || row.getBoolean("RECU")) {
totalQteL = totalQteL.add(qte);
} else if (row.getBigDecimal("QTE_RECUE") != null) {
final BigDecimal qteLivree = row.getBigDecimal("QTE_RECUE");
if (qteLivree != null) {
totalQteL = totalQteL.add(qteLivree);
}
}
}
}
if (totalQte.signum() != 0) {
return totalQteL.divide(totalQte, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
} else {
return BigDecimal.ONE.movePointRight(2);
}
}
 
BigDecimal bigDecimal100 = new BigDecimal(100.0);
 
private BigDecimal getAvancementFact(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_COMMANDE"));
long totalFact = 0;
long total = r.getLong("T_HT");
for (SQLRowAccessor row : rows) {
if (!row.isForeignEmpty("ID_FACTURE_FOURNISSEUR")) {
SQLRowAccessor rowFact = row.getForeign("ID_FACTURE_FOURNISSEUR");
Long l = rowFact.getLong("T_HT");
totalFact += l;
}
if (!row.isForeignEmpty("ID_SAISIE_ACHAT")) {
SQLRowAccessor rowFact = row.getForeign("ID_SAISIE_ACHAT");
Long l = rowFact.getLong("MONTANT_HT");
totalFact += l;
}
 
if (!row.isForeignEmpty("ID_BON_RECEPTION")) {
Collection<? extends SQLRowAccessor> rowsBr = row.getForeign("ID_BON_RECEPTION").getReferentRows(r.getTable().getTable("TR_BON_RECEPTION"));
for (SQLRowAccessor rowTrBr : rowsBr) {
if (!rowTrBr.isForeignEmpty("ID_FACTURE_FOURNISSEUR")) {
SQLRowAccessor rowFact = rowTrBr.getForeign("ID_FACTURE_FOURNISSEUR");
Long l = rowFact.getLong("T_HT");
totalFact += l;
}
if (!rowTrBr.isForeignEmpty("ID_SAISIE_ACHAT")) {
SQLRowAccessor rowFact = rowTrBr.getForeign("ID_SAISIE_ACHAT");
Long l = rowFact.getLong("MONTANT_HT");
totalFact += l;
}
 
}
}
}
 
if (total > 0) {
return this.bigDecimal100.min(new BigDecimal(totalFact).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP));
} else {
return BigDecimal.ONE.movePointRight(2);
}
}
 
private BigDecimal getAvancement(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_COMMANDE"));
long totalFact = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/FactureFournisseurSQLComponent.java
59,9 → 59,6
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.JLabel;
import javax.swing.JPanel;
68,7 → 65,6
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
106,7 → 102,7
 
int idModeRegl = rowFourn.getInt("ID_MODE_REGLEMENT");
if (idModeRegl > 1 && FactureFournisseurSQLComponent.this.eltModeRegl != null && getMode() == Mode.INSERTION) {
SQLElement sqlEltModeRegl = getElement().getDirectory().getElement("MODE_REGLEMENT");
SQLElement sqlEltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
SQLRow rowModeRegl = sqlEltModeRegl.getTable().getRow(idModeRegl);
SQLRowValues rowVals = rowModeRegl.createUpdateRow();
rowVals.clearPrimaryKeys();
128,15 → 124,6
return this.fourn;
}
 
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<>(1);
if (getTable().contains("ID_TYPE_CMD")) {
s.add("ID_TYPE_CMD");
}
return s;
}
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
493,10 → 480,10
ElementComboBox comboTaxePort = new ElementComboBox();
DeviseField textRemiseHT = new DeviseField();
 
if (getTable().contains("PORT_HT")) {
addSQLObject(textPortHT, "PORT_HT");
final JPanel panelPoids = new JPanel(new GridBagLayout());
GridBagConstraints cPort = new DefaultGridBagConstraints();
if (getTable().contains("PORT_HT")) {
addSQLObject(textPortHT, "PORT_HT");
cPort.gridx = 0;
cPort.weightx = 0;
panelPoids.add(new JLabel(getLabelFor("PORT_HT")), cPort);
575,49 → 562,6
final TotalPanel totalTTC = new TotalPanel(this.table, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, null, null,
(getTable().contains("ID_TAXE_PORT") ? comboTaxePort : null), null);
 
if (getTable().contains("TVA_ADJUSTMENT")) {
final JTextField textTvaAdujs = new JTextField(15);
 
JLabel labelTvaAdujst = new JLabel(getLabelFor("TVA_ADJUSTMENT"));
labelTvaAdujst.setHorizontalAlignment(SwingConstants.RIGHT);
 
cPort.gridx = 0;
cPort.gridy++;
panelPoids.add(labelTvaAdujst, cPort);
cPort.gridx++;
panelPoids.add(textTvaAdujs, cPort);
addView(textTvaAdujs, "TVA_ADJUSTMENT");
totalTTC.setTextFixTVA(textTvaAdujs);
textTvaAdujs.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update(final DocumentEvent e) {
final String text = textTvaAdujs.getText();
if (text != null && text.trim().length() > 0) {
if (!text.trim().equals("-")) {
BigDecimal tvaFix = new BigDecimal(text);
if (tvaFix.abs().compareTo(new BigDecimal(0.05)) > 0) {
final String limitedFix;
if (tvaFix.signum() > 0) {
limitedFix = tvaFix.min(new BigDecimal(0.05)).toString();
} else {
limitedFix = tvaFix.max(new BigDecimal(-0.05)).toString();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
 
textTvaAdujs.setText(limitedFix);
}
});
}
}
}
totalTTC.updateTotal();
}
});
DefaultGridBagConstraints.lockMinimumSize(textTvaAdujs);
}
 
c.gridx++;
c.gridy--;
c.gridwidth = GridBagConstraints.REMAINDER;
914,48 → 858,4
 
}
 
public void loadFactureExistante(int idFacture) {
 
SQLElement fact = getElement();
SQLElement factElt = getElement().getDirectory().getElement("FACTURE_FOURNISSEUR_ELEMENT");
 
// On duplique la facture
if (idFacture > 1) {
SQLRow row = fact.getTable().getRow(idFacture);
SQLRowValues rowVals = new SQLRowValues(fact.getTable());
rowVals.put("ID_FOURNISSEUR", row.getInt("ID_FOURNISSEUR"));
// if (getTable().contains("ID_NUMEROTATION_AUTO")) {
// rowVals.put("NUMERO",
// NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new
// Date(), row.getForeign("ID_NUMEROTATION_AUTO")));
// } else {
// rowVals.put("NUMERO",
// NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new
// Date()));
// }
rowVals.put("NOM", row.getObject("NOM"));
this.select(rowVals);
}
 
// On duplique les elements de facture
List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
 
if (myListItem.size() != 0) {
this.table.getModel().clearRows();
 
for (SQLRow rowElt : myListItem) {
 
SQLRowValues rowVals = rowElt.createUpdateRow();
rowVals.clearPrimaryKeys();
this.table.getModel().addRow(rowVals);
int rowIndex = this.table.getModel().getRowCount() - 1;
this.table.getModel().fireTableModelModified(rowIndex);
}
} else {
this.table.getModel().clearRows();
}
this.table.getModel().fireTableDataChanged();
this.table.repaint();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
31,7 → 31,6
import org.openconcerto.erp.generationDoc.gestcomm.CommandeXmlSheet;
import org.openconcerto.erp.panel.PanelOOSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.DefaultElementSQLObject;
48,11 → 47,9
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.AutoHideListener;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FormLayouter;
64,7 → 61,6
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.ui.preferences.DefaultProps;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.Color;
import java.awt.GridBagConstraints;
74,9 → 70,7
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
115,17 → 109,6
return this.fourn;
}
 
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<>(4);
if (getTable().contains("ID_TYPE_CMD")) {
s.add("ID_TYPE_CMD");
s.add("DA1");
s.add("ID_POLE_PRODUIT");
}
return s;
}
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
201,9 → 184,7
} else {
table.setRowCatComptable(null);
}
if (getTable().contains("OFFRE_COM")) {
((SQLTextCombo) getView("OFFRE_COM").getComp()).setValue(rowF.getString("RESPONSABLE"));
}
 
} else {
table.setRowCatComptable(null);
}
210,9 → 191,7
}
});
 
Boolean useCommandeEnCours = SQLPreferences.getMemCached(getElement().getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.COMMANDE_FOURNISSEUR_EN_COURS, false);
 
if (!getTable().getFieldsName().contains("LIVRER") && useCommandeEnCours) {
if (!getTable().getFieldsName().contains("LIVRER")) {
// Commande en cours
JCheckBox boxEnCours = new JCheckBox(getLabelFor("EN_COURS"));
c.gridx += 2;
1025,27 → 1004,6
stockUpdater.update();
}
 
@Override
public synchronized ValidState getValidState() {
if (getTable().contains("ID_TYPE_CMD") && getTable().contains("ID_AFFAIRE") && getTable().getTable("COMMANDE_ELEMENT").contains("ID_AFFAIRE")) {
SQLRequestComboBox boxAff = (SQLRequestComboBox) getView("ID_AFFAIRE").getComp();
final SQLRow selectedAff = boxAff.getSelectedRow();
if (selectedAff == null || selectedAff.isUndefined()) {
RowValuesTableModel tableRow = this.table.getRowValuesTable().getRowValuesTableModel();
 
for (int i = 0; i < tableRow.getRowCount(); i++) {
SQLRowValues rowVals = tableRow.getRowValuesAt(i);
if (rowVals.getInt("QTE") != 0 && (rowVals.getObject("ID_AFFAIRE") == null || rowVals.isForeignEmpty("ID_AFFAIRE"))) {
return ValidState.create(false, "Aucune affaire globale sélectionnée et une ligne avec une quantité > 0 n'est pas affectée à une affaire!");
}
}
} else {
ValidState.create(false, "Aucune affaire globale sélectionnée!");
}
}
return super.getValidState();
}
 
public void setDefaults() {
this.resetValue();
this.numeroUniqueCommande.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/action/ListeDesBonsReceptionsAction.java
94,8 → 94,6
return frame;
}
 
private BigDecimal bigDecimal100 = new BigDecimal(100);
 
private BigDecimal getAvancement(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_BON_RECEPTION"));
long totalFact = 0;
108,7 → 106,7
}
}
if (total > 0) {
return this.bigDecimal100.min(new BigDecimal(totalFact).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP));
return new BigDecimal(totalFact).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
} else {
return BigDecimal.ONE.movePointRight(2);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
60,14 → 60,11
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
94,15 → 91,6
}
 
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<>(1);
if (getTable().contains("ID_TYPE_CMD")) {
s.add("ID_TYPE_CMD");
}
return s;
}
 
@Override
protected SQLRowValues createDefaults() {
this.tableBonItem.getModel().clearRows();
this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
640,8 → 628,6
}
}
int count = this.tableBonItem.getModel().getRowCount();
int receipt = 0;
 
for (int i = 0; i < count; i++) {
SQLRowValues r = this.tableBonItem.getModel().getRowValuesAt(i);
SQLRowValues rowTR = map.get(r.getForeignID("ID_ARTICLE"));
648,28 → 634,14
if (rowTR != null && !rowTR.isUndefined()) {
if (r.getInt("QTE") > 0) {
if (NumberUtils.areNumericallyEqual(r.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || r.getInt("QTE") > 1) {
int value = r.getInt("QTE") - rowTR.getInt("QTE");
if ((value <= 0)) {
receipt++;
}
 
this.tableBonItem.getModel().putValue(Math.max(0, value), i, "QTE");
this.tableBonItem.getModel().putValue(r.getInt("QTE") - rowTR.getInt("QTE"), i, "QTE");
} else {
BigDecimal subtract = r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE"));
if (subtract.signum() <= 0) {
receipt++;
this.tableBonItem.getModel().putValue(r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE")), i, "QTE_UNITAIRE");
}
this.tableBonItem.getModel().putValue(subtract.max(BigDecimal.ZERO), i, "QTE_UNITAIRE");
}
} else {
receipt++;
}
}
}
if (receipt == count) {
JOptionPane.showMessageDialog(null, "Attention tous les articles ont déjà été réceptionné!");
}
}
 
@Override
public void update() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionSQLElement.java
27,7 → 27,6
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
36,7 → 35,6
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.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
 
import java.awt.event.ActionEvent;
47,8 → 45,6
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
59,46 → 55,8
 
PredicateRowAction actionsTRFA = new PredicateRowAction(new AbstractAction("Transfert vers facture fournisseur") {
public void actionPerformed(ActionEvent e) {
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
SwingWorker<Boolean, Object> worker = new SwingWorker<Boolean, Object>() {
@Override
protected Boolean doInBackground() throws Exception {
 
boolean b = TransfertBaseSQLComponent.isAlreadyAllTransfert(selectedRows, getTable(), getTable().getTable("FACTURE_FOURNISSEUR"), "TOTAL_HT", "T_HT");
 
if (b) {
String label = "Attention ";
if (selectedRows.size() > 1) {
label += " les " + getPluralName() + " ont déjà été transféré!";
} else {
label += getSingularName() + " a déjà été transféré!";
TransfertBaseSQLComponent.openTransfertFrame(IListe.get(e).getSelectedRows(), "FACTURE_FOURNISSEUR");
}
label += "\n Voulez vous continuer?";
 
int ans = JOptionPane.showConfirmDialog(null, label, "Transfert " + getSingularName(), JOptionPane.YES_NO_OPTION);
if (ans == JOptionPane.NO_OPTION) {
return Boolean.FALSE;
}
}
 
return Boolean.TRUE;
 
}
 
@Override
protected void done() {
try {
Boolean b = get();
if (b) {
TransfertBaseSQLComponent.openTransfertFrame(selectedRows, "FACTURE_FOURNISSEUR");
}
} catch (Exception e) {
ExceptionHandler.handle("Erreur lors du transfert des " + getPluralName() + "!", e);
}
}
};
worker.execute();
}
}, true);
actionsTRFA.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
 
127,7 → 85,6
protected List<String> getListFields() {
final List<String> l = new ArrayList<>(5);
l.add("NUMERO");
l.add("NOM");
l.add("DATE");
l.add("ID_FOURNISSEUR");
l.add("TOTAL_HT");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/DepotStockSQLElement.java
14,27 → 14,16
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.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.Where;
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.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.ListMap;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
44,22 → 33,7
 
public DepotStockSQLElement() {
super("DEPOT_STOCK", "un dépôt", "dépôts");
 
PredicateRowAction actionStock = new PredicateRowAction(new AbstractAction("Voir le détails du stock") {
 
@Override
public void actionPerformed(ActionEvent e) {
SQLRowAccessor selRow = IListe.get(e).getSelectedRow();
final SQLElement elementStock = getDirectory().getElement("STOCK");
IListFrame frame = new IListFrame(
new ListeViewPanel(elementStock, new IListe(elementStock.createTableSource(new Where(elementStock.getTable().getField("ID_DEPOT_STOCK"), "=", selRow.getID())))));
FrameUtil.showPacked(frame);
 
}
}, true);
actionStock.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionStock);
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItemsUpdater.java
25,8 → 25,6
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTableEvent;
import org.openconcerto.sql.model.SQLTableEvent.Mode;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.DecimalUtils;
156,13 → 154,12
for (String s : requests) {
handlers.add(null);
}
// FIXME FIRE TABLE CHANGED TO UPDATE ILISTE ??
try {
SQLUtils.executeAtomic(stockTable.getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
SQLUtils.executeMultiple(stockTable.getDBSystemRoot(), requests, handlers);
// FIXME FIRE ONLY CHANGED ROWS
stockTable.fire(new SQLTableEvent(stockTable, SQLRow.NONEXISTANT_ID, Mode.ROW_UPDATED));
return null;
}
});
267,6 → 264,35
SQLUtils.executeMultiple(table.getDBSystemRoot(), multipleRequests, handlers);
}
 
private void fillProductComponent(List<ProductComponent> productComponents, int qte, int index, int level) {
if (level > 0) {
for (int i = index; i < items.size(); i++) {
SQLRowAccessor r = items.get(i);
 
if (!r.getTable().contains("NIVEAU") || r.getInt("NIVEAU") >= level) {
// On ne calcul pas les stocks pour les éléments ayant des fils (le mouvement de
// stock
// des fils impactera les stocks automatiquement)
if (r.getTable().contains("NIVEAU")) {
if (i + 1 < items.size()) {
SQLRowAccessor rNext = items.get(i + 1);
if (rNext.getInt("NIVEAU") > r.getInt("NIVEAU")) {
fillProductComponent(productComponents, qte * r.getInt("QTE"), i + 1, rNext.getInt("NIVEAU"));
continue;
}
}
}
if ((!r.getTable().contains("NIVEAU") || r.getInt("NIVEAU") == level) && !r.isForeignEmpty("ID_ARTICLE") && r.getForeign("ID_ARTICLE") != null) {
productComponents.add(ProductComponent.createFrom(r, qte, r));
}
} else if (r.getInt("NIVEAU") < level) {
// BREAK si on sort de l'article composé
break;
}
}
}
}
 
/**
* Récupére les stocks associés aux articles non composés (inclus les fils des nomenclatures) et
* les met à jour
279,10 → 305,9
 
String mvtStockTableQuoted = rowSource.getTable().getTable("MOUVEMENT_STOCK").getSQLName().quote();
 
ProductHelper helper = new ProductHelper(rowSource.getTable().getDBRoot());
// Liste des éléments à mettre à jour
List<ProductComponent> productComponents = new ArrayList<ProductComponent>();
helper.fillProductComponent(this.items, productComponents, 1, 0, 1);
fillProductComponent(productComponents, 1, 0, 1);
// for (int i = 0; i < items.size(); i++) {
// SQLRowAccessor r = items.get(i);
//
302,6 → 327,7
// }
 
// Liste des articles non composés à mettre à jour (avec les fils des nomenclatures)
ProductHelper helper = new ProductHelper(rowSource.getTable().getDBRoot());
List<ProductComponent> boms = helper.getChildWithQtyFrom(productComponents);
 
for (ProductComponent productComp : boms) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockSQLElement.java
20,7 → 20,6
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
101,7 → 100,7
@Override
public ListMap<String, String> getShowAs() {
if (getTable().contains("ID_DEPOT_STOCK")) {
return ListMap.singleton(null, "QTE_TH", "QTE_REEL", "QTE_MIN", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE", "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");
}
135,15 → 134,8
if (rowValsSource.getForeign("ID_DEPOT_STOCK") != null && !rowValsSource.isForeignEmpty("ID_DEPOT_STOCK")) {
idDepot = rowValsSource.getForeignID("ID_DEPOT_STOCK");
} else {
SQLRowAccessor rowValsArt = rowValsSource.getForeign("ID_ARTICLE");
if (rowValsArt.getObject("ID_DEPOT_STOCK") == null) {
rowValsArt = rowValsArt.asRow();
((SQLRow) rowValsArt).fetchValues();
System.err.println("REFETCH ARTICLE");
Thread.dumpStack();
idDepot = rowValsSource.getForeign("ID_ARTICLE").getForeignID("ID_DEPOT_STOCK");
}
idDepot = rowValsArt.getForeignID("ID_DEPOT_STOCK");
}
SQLTable stockTable = rowValsSource.getTable().getTable("STOCK");
SQLRowValues putRowValuesStock = new SQLRowValues(stockTable);
putRowValuesStock.putNulls(stockTable.getTable().getFieldsName());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
16,12 → 16,10
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
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.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
52,7 → 50,6
import java.util.List;
import java.util.Map.Entry;
 
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
public class MouvementStockSQLElement extends ComptaSQLConfElement {
249,10 → 246,10
}
 
public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise) {
createCommandeF(col, rowDevise, "");
createCommandeF(col, rowDevise, "", true);
}
 
public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise, final String ref) {
public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise, final String ref, final boolean useCommandeEnCours) {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("This method must be called outside of EDT");
}
259,7 → 256,6
if (col.size() > 0) {
 
final SQLElement commande = Configuration.getInstance().getDirectory().getElement("COMMANDE");
Boolean useCommandeEnCours = SQLPreferences.getMemCached(commande.getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.COMMANDE_FOURNISSEUR_EN_COURS, false);
for (final Entry<SQLRow, List<SQLRowValues>> e : col.entrySet()) {
final SQLRow fournisseur = e.getKey();
// On regarde si il existe une commande en cours existante
328,23 → 324,9
}
}
if (rowValsMatch != null) {
 
int qte = rowValsMatch.getInt("QTE");
BigDecimal qteUV = rowValsMatch.getBigDecimal("QTE_UNITAIRE");
 
if (rowValsMatch.getObject("ID_UNITE_VENTE") != null && rowValsMatch.getForeignID("ID_UNITE_VENTE") != UniteVenteArticleSQLElement.A_LA_PIECE) {
qteUV = qteUV.multiply(new BigDecimal(qte));
int qteElt = rowValsElt.getInt("QTE");
BigDecimal qteUVElt = rowValsElt.getBigDecimal("QTE_UNITAIRE");
qteUV = qteUV.add(qteUVElt.multiply(new BigDecimal(qteElt)));
qte = 1;
final int qte = rowValsMatch.getInt("QTE");
model.putValue(qte + rowValsElt.getInt("QTE"), index, "QTE");
} else {
qte += rowValsElt.getInt("QTE");
}
 
model.putValue(qte, index, "QTE");
model.putValue(qteUV, index, "QTE_UNITAIRE");
} 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");
360,16 → 342,9
 
}
});
}
} else {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
JOptionPane.showMessageDialog(null, "Aucune commande à passer", "Commande fournisseur", JOptionPane.INFORMATION_MESSAGE);
}
 
});
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ComptaContactSQLElement.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ContactSQLElement.java
New file
0,0 → 1,56
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.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;
 
public class ContactSQLElement extends ContactSQLElementBase {
 
static public class ContactFournisseurSQLElement extends ContactSQLElement {
public ContactFournisseurSQLElement() {
super("CONTACT_FOURNISSEUR");
}
}
 
static public class ContactAdministratifSQLElement extends ContactSQLElement {
public ContactAdministratifSQLElement() {
super("CONTACT_ADMINISTRATIF");
}
}
 
public ContactSQLElement() {
this("CONTACT");
 
}
 
protected ContactSQLElement(String tableName) {
super(tableName);
PredicateRowAction action = new PredicateRowAction(new AbstractAction() {
 
@Override
public void actionPerformed(ActionEvent e) {
sendMail(IListe.get(e).getSelectedRows());
 
}
}, true, "customerrelationship.customer.email.send");
action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(action);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerSQLComponent.java
17,7 → 17,6
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseClientItemTable;
import org.openconcerto.erp.core.sales.product.element.ClientCodeArticleTable;
import org.openconcerto.erp.core.sales.product.ui.CustomerProductQtyPriceListTable;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
76,7 → 75,6
private ContactItemTable table;
private ClientCodeArticleTable tableCustomProduct;
private AdresseClientItemTable adresseTable = new AdresseClientItemTable();
 
private SQLTable contactTable = Configuration.getInstance().getDirectory().getElement("CONTACT").getTable();
private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
private final JUniqueTextField code = new JUniqueTextField(20) {
90,7 → 88,6
}
};
 
private CustomerProductQtyPriceListTable clienTarifTable = new CustomerProductQtyPriceListTable();
private SQLRowValues defaultContactRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(this.contactTable));
private JCheckBox checkAdrLivraison, checkAdrFacturation;
 
170,8 → 167,6
return this.table;
} else if (id.equals("customerrelationship.customer.customproduct")) {
return this.tableCustomProduct;
} else if (id.equals("customerrelationship.customer.customtarif")) {
return this.clienTarifTable;
} else if (id.equals("customerrelationship.customer.addresses")) {
return createAdressesComponent();
} else if (id.equals("NOM")) {
248,7 → 243,6
super.update();
final int selectedID = getSelectedID();
this.table.updateField("ID_CLIENT", selectedID);
this.clienTarifTable.updateField("ID_CLIENT", selectedID);
this.tableCustomProduct.updateField("ID_CLIENT", selectedID);
this.adresseTable.updateField("ID_CLIENT", selectedID);
}
260,7 → 254,6
this.checkAdrFacturation.setSelected(r == null || !r.getFields().contains("ID_ADRESSE_F") || r.isForeignEmpty("ID_ADRESSE_F"));
if (r != null) {
this.table.insertFrom("ID_CLIENT", r.asRowValues());
this.clienTarifTable.insertFrom("ID_CLIENT", r.asRowValues());
this.tableCustomProduct.insertFrom("ID_CLIENT", r.asRowValues());
this.adresseTable.insertFrom("ID_CLIENT", r.asRowValues());
}
301,7 → 294,6
id = super.insert(order);
this.table.updateField("ID_CLIENT", id);
this.tableCustomProduct.updateField("ID_CLIENT", id);
this.clienTarifTable.updateField("ID_CLIENT", id);
this.adresseTable.updateField("ID_CLIENT", id);
if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass()).equalsIgnoreCase(this.code.getText().trim())) {
SQLRowValues rowVals = new SQLRowValues(this.tableNum);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerGroup.java
94,9 → 94,6
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));
this.add(gCustomProduct);
final Group gCustomRemiseProduct = new Group("customerrelationship.customer.customtarif", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gCustomRemiseProduct.addItem("customerrelationship.customer.customtarif", new LayoutHints(true, true, true, true, true, true, true, true));
this.add(gCustomRemiseProduct);
 
this.add(gState);
final Group gInfo = new Group("customerrelationship.customer.info", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
22,19 → 22,14
import org.openconcerto.ql.QLPrinter;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.EmailComposer;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Font;
42,7 → 37,6
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
 
186,28 → 180,6
return l;
}
 
@Override
protected void _initTableSource(SQLTableModelSource res) {
super._initTableSource(res);
 
res.getColumns().add(new BaseSQLTableModelColumn(getDirectory().getTranslator().getLabelFor(getTable().getField("CATEGORIES")), String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
return r.getString("CATEGORIES");
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
return CollectionUtils.createSet(new FieldPath(p, "CATEGORIES"));
 
}
});
 
}
 
/*
* (non-Javadoc)
*
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/ReportingCommercialPDF.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/ReportingCommercialItem.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/ReportingCommercial.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/ReportingCommercialCreator.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/ReportingCommercialPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesContactsAction.java
15,7 → 15,7
 
import org.openconcerto.erp.action.CreateIListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.customer.element.ComptaContactSQLElement.ContactSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.element.ContactSQLElement;
 
public class ListeDesContactsAction extends CreateIListFrameAbstractAction<ContactSQLElement> {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesClientsAction.java
15,8 → 15,9
 
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.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.view.IListFrame;
25,12 → 26,10
 
import javax.swing.JTable;
 
public class ListeDesClientsAction extends CreateIListFrameAbstractAction<SQLElement> {
public class ListeDesClientsAction extends CreateIListFrameAbstractAction<ClientNormalSQLElement> {
 
public ListeDesClientsAction(final ComptaPropsConfiguration conf) {
// handle CustomerSQLElement/ClientSocieteSQLElement (or even a module replacing the
// default element)
super(conf, conf.getDirectory().getElement(conf.getRootSociete().getTable("CLIENT")));
super(conf, CustomerSQLElement.class);
}
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/ui/CategorieComptableChoiceUI.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateSQLComponent.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateSQLElement.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateGroup.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/ValueListener.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplate.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/action/ListeDesModelesEmailAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/ui/ListeDesChequesAEncaisserPanel.java
18,7 → 18,6
import org.openconcerto.erp.rights.ComptaTotalUserRight;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.users.rights.UserRightsManager;
54,10 → 53,10
 
@Override
protected JTextComponent createLabelText() {
if (this.fieldLabel == null) {
if (fieldLabel == null) {
this.fieldLabel = new JTextField();
}
return this.fieldLabel;
return fieldLabel;
}
 
@Override
67,16 → 66,18
@Override
public void actionPerformed(ActionEvent e) {
final String s = text.getText();
SQLRowValues rowValsDepot = new SQLRowValues(ListeDesChequesAEncaisserPanel.this.element.getTable().getTable("DEPOT_CHEQUE"));
SQLRowValues rowValsDepot = new SQLRowValues(element.getTable().getTable("DEPOT_CHEQUE"));
rowValsDepot.put("DATE", dateDepot.getValue());
rowValsDepot.put("NOM", ListeDesChequesAEncaisserPanel.this.fieldLabel.getText());
rowValsDepot.put("NOM", fieldLabel.getText());
final SQLRow selectedBanque = banqueSelect.getSelectedRow();
if (selectedBanque != null) {
rowValsDepot.put("ID_" + selectedBanque.getTable().getName(), selectedBanque.getID());
}
final List<SQLRow> chq = SQLRowListRSH.fetch(getListe().getRequest().getPrimaryTable(), getListe().getSelection().getSelectedIDs());
for (SQLRow rowChq : chq) {
SQLRowValues rowValsDepotElt = new SQLRowValues(ListeDesChequesAEncaisserPanel.this.element.getTable().getTable("DEPOT_CHEQUE_ELEMENT"));
List<SQLRowValues> chq = getListe().getSelectedRows();
for (SQLRowValues sqlRowValues : chq) {
SQLRow rowChq = sqlRowValues.asRow();
rowChq.fetchValues();
SQLRowValues rowValsDepotElt = new SQLRowValues(element.getTable().getTable("DEPOT_CHEQUE_ELEMENT"));
rowValsDepotElt.put("ID_DEPOT_CHEQUE", rowValsDepot);
if (rowChq.getObject("ID_CLIENT") != null && !rowChq.isForeignEmpty("ID_CLIENT")) {
rowValsDepotElt.put("ID_CLIENT", rowChq.getForeignID("ID_CLIENT"));
95,7 → 96,7
rowValsDepotElt.put("NUMERO", (rowChq.getObject("NUMERO") == null ? "" : rowChq.getObject("NUMERO")));
rowValsDepotElt.put("MONTANT", rowChq.getObject("MONTANT"));
}
EditFrame frame = new EditFrame(ListeDesChequesAEncaisserPanel.this.element.getDirectory().getElement("DEPOT_CHEQUE"), EditMode.CREATION);
EditFrame frame = new EditFrame(element.getDirectory().getElement("DEPOT_CHEQUE"), EditMode.CREATION);
frame.getSQLComponent().select(rowValsDepot);
frame.setVisible(true);
text.setText("");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/component/EncaisserMontantSQLComponent.java
16,9 → 16,11
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.EncaisserMontantSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.payment.ui.EncaisseMontantTable;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
31,6 → 33,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
38,6 → 41,7
import org.openconcerto.ui.warning.JLabelWarning;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.GridBagConstraints;
51,6 → 55,7
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
178,6 → 183,7
 
this.addSQLObject(this.nom, "NOM");
 
 
this.addSQLObject(new ElementComboBox(), "ID_COMPTE_PCE_TIERS");
this.addSQLObject(new JTextField(), "TIERS");
DefaultGridBagConstraints.lockMinimumSize(this.montant);
299,17 → 305,64
public int insert(SQLRow order) {
 
int id = super.insert(order);
try {
this.table.updateField("ID_ENCAISSER_MONTANT", id);
 
System.out.println("Génération des ecritures du reglement");
SQLRow row = getTable().getRow(id);
String s = row.getString("NOM");
SQLRow rowModeRegl = row.getForeignRow("ID_MODE_REGLEMENT");
SQLRow rowTypeRegl = rowModeRegl.getForeignRow("ID_TYPE_REGLEMENT");
 
try {
((EncaisserMontantSQLElement) getElement()).regleFacture(row);
// Compte Client
SQLRow clientRow = row.getForeignRow("ID_CLIENT");
 
String label = "Règlement vente " + ((s == null) ? "" : s) + " (" + rowTypeRegl.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
long montant = row.getLong("MONTANT");
PrixTTC ttc = new PrixTTC(montant);
 
List<SQLRow> l = row.getReferentRows(Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT_ELEMENT").getTable());
if (l.isEmpty()) {
JOptionPane.showMessageDialog(null, "Un problème a été rencontré lors de l'encaissement! \n Les écritures comptables non pu être générer!");
System.err.println("Liste des échéances vides pour l'encaissement ID " + id);
Thread.dumpStack();
}
new GenerationReglementVenteNG(label, clientRow, ttc, row.getDate("DATE").getTime(), rowModeRegl, row, l.get(0).getForeignRow("ID_MOUVEMENT_ECHEANCE"), false, false,
row.getString("TIERS"), row.getForeign("ID_COMPTE_PCE_TIERS"));
 
// Mise a jour du montant de l'echeance
boolean supplement = false;
 
if (!row.getBoolean("ACOMPTE")) {
// On marque les echeances comme reglees
for (SQLRow sqlRow : l) {
 
final SQLRow rowEch = sqlRow.getForeignRow("ID_ECHEANCE_CLIENT");
SQLRowValues rowValsEch = rowEch.createEmptyUpdateRow();
if (sqlRow.getLong("MONTANT_REGLE") >= sqlRow.getLong("MONTANT_A_REGLER")) {
rowValsEch.put("REGLE", Boolean.TRUE);
if (sqlRow.getLong("MONTANT_REGLE") > sqlRow.getLong("MONTANT_A_REGLER")) {
supplement = true;
}
}
rowValsEch.put("MONTANT", Long.valueOf(rowEch.getLong("MONTANT") - sqlRow.getLong("MONTANT_REGLE")));
 
rowValsEch.update();
// this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
// getTable().fireTableModified(rowEch.getID());
}
}
// si le montant réglé est supérieur, on crée une facture de complément
if (supplement) {
SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
EditFrame f = new EditFrame(elt, EditFrame.CREATION);
SaisieVenteFactureSQLComponent comp = (SaisieVenteFactureSQLComponent) f.getSQLComponent();
comp.setComplement(true);
f.setVisible(true);
}
} catch (Exception e) {
ExceptionHandler.handle("Erreur de génération des écritures", e);
ExceptionHandler.handle("Erreur lors de la génération des ecritures du reglement", e);
}
 
return id;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ChequeAEncaisserSQLElement.java
100,13 → 100,9
l.add("DATE_VENTE");
l.add(getMinDateFieldName());
l.add("ID_CLIENT");
final ShowAs showAs = new ShowAs(getTable().getDBRoot());
if (getTable().contains("ID_BANQUE")) {
l.add("ID_BANQUE");
showAs.show(getTable().getForeignTable("ID_BANQUE"), "NOM");
}
l.add("MONTANT");
 
final ShowAs showAs = new ShowAs(getTable().getDBRoot());
 
final SQLTable mvtT = getTable().getForeignTable("ID_MOUVEMENT");
showAs.show(mvtT, "ID_PIECE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/EncaisserMontantSQLElement.java
17,13 → 17,9
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.payment.component.EncaisserMontantSQLComponent;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.TreesOfSQLRows;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRow;
36,7 → 32,6
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.preferences.SQLPreferences;
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;
44,7 → 39,6
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
 
import java.awt.event.ActionEvent;
import java.sql.SQLException;
57,8 → 51,6
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
public class EncaisserMontantSQLElement extends ComptaSQLConfElement {
 
172,77 → 164,7
super.archive(trees, cutLinks);
}
 
public void regleFacture(SQLRow row) throws Exception {
 
System.out.println("Génération des ecritures du reglement");
String s = row.getString("NOM");
SQLRow rowModeRegl = row.getForeignRow("ID_MODE_REGLEMENT");
SQLRow rowTypeRegl = rowModeRegl.getForeignRow("ID_TYPE_REGLEMENT");
 
// Compte Client
SQLRow clientRow = row.getForeignRow("ID_CLIENT");
 
String label = "Règlement vente " + ((s == null) ? "" : s) + " (" + rowTypeRegl.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
long montant = row.getLong("MONTANT");
PrixTTC ttc = new PrixTTC(montant);
 
List<SQLRow> l = row.getReferentRows(row.getTable().getTable("ENCAISSER_MONTANT_ELEMENT"));
if (l.isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
JOptionPane.showMessageDialog(null, "Un problème a été rencontré lors de l'encaissement! \n Les écritures comptables non pu être générer!");
}
});
System.err.println("Liste des échéances vides pour l'encaissement ID " + row.getID());
Thread.dumpStack();
return;
}
new GenerationReglementVenteNG(label, clientRow, ttc, row.getDate("DATE").getTime(), rowModeRegl, row, l.get(0).getForeignRow("ID_MOUVEMENT_ECHEANCE"), false, false, row.getString("TIERS"),
row.getForeign("ID_COMPTE_PCE_TIERS"));
 
// Mise a jour du montant de l'echeance
boolean supplement = false;
 
if (!row.getBoolean("ACOMPTE")) {
// On marque les echeances comme reglees
for (SQLRow sqlRow : l) {
 
final SQLRow rowEch = sqlRow.getForeignRow("ID_ECHEANCE_CLIENT");
SQLRowValues rowValsEch = rowEch.createEmptyUpdateRow();
if (sqlRow.getLong("MONTANT_REGLE") >= sqlRow.getLong("MONTANT_A_REGLER")) {
rowValsEch.put("REGLE", Boolean.TRUE);
if (sqlRow.getLong("MONTANT_REGLE") > sqlRow.getLong("MONTANT_A_REGLER")) {
supplement = true;
}
}
rowValsEch.put("MONTANT", Long.valueOf(rowEch.getLong("MONTANT") - sqlRow.getLong("MONTANT_REGLE")));
 
rowValsEch.update();
// this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
// getTable().fireTableModified(rowEch.getID());
}
}
// si le montant réglé est supérieur, on crée une facture de complément
if (supplement) {
SQLElement elt = getDirectory().getElement("SAISIE_VENTE_FACTURE");
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
 
EditFrame f = new EditFrame(elt, EditFrame.CREATION);
SaisieVenteFactureSQLComponent comp = (SaisieVenteFactureSQLComponent) f.getSQLComponent();
comp.setComplement(true);
f.setVisible(true);
}
});
}
 
}
 
@Override
protected String createCodeSuffix() {
return ".category";
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/EcritureSQLElement.java
65,6 → 65,8
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
78,6 → 80,7
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
150,11 → 153,6
return "ID_MOUVEMENT";
}
 
@Override
public boolean isPrivate() {
return false;
}
 
// Impossible de modifier si validée
// FIXME impossible de saisir une écriture avant la date de debut d'exercice --> de saisir de
// document de gest comm
198,9 → 196,67
}
 
public void consultationCompte(SQLRowAccessor rowCpt) {
final ListeDesEcrituresPanel panel = new ListeDesEcrituresPanel();
final ConsultationCompteFrame f = new ConsultationCompteFrame(panel, rowCpt);
final ConsultationCompteFrame f = new ConsultationCompteFrame(new ListeDesEcrituresPanel(), "Consultation compte n°" + rowCpt.getString("NUMERO") + " " + rowCpt.getString("NOM"));
 
f.getPanel().getListe().getJTable().addMouseListener(new MouseAdapter() {
 
public void mousePressed(final MouseEvent mE) {
 
if (mE.getButton() == MouseEvent.BUTTON3) {
JPopupMenu menuDroit = new JPopupMenu();
 
menuDroit.add(new AbstractAction("Voir les ecritures du journal") {
 
public void actionPerformed(ActionEvent e) {
int id = f.getPanel().getListe().idFromIndex(f.getPanel().getListe().getJTable().rowAtPoint(mE.getPoint()));
// int id = f.getPanel().getListe().getSelectedId();
 
SQLTable ecrTable = getTable().getTable("ECRITURE");
 
System.err.println("Ecritures ID ::: " + id);
SQLRow rowEcr = ecrTable.getRow(id);
 
System.err.println("Ecritures ID ::: " + id + " --> ID_JOURNAL = " + rowEcr.getInt("ID_JOURNAL"));
 
ConsultationCompteFrame f2 = new ConsultationCompteFrame(new ListeDesEcrituresPanel(),
"Consultation du journal " + getTable().getTable("JOURNAL").getRow(rowEcr.getInt("ID_JOURNAL")).getString("NOM"));
 
Where w = new Where(ecrTable.getField("ID_JOURNAL"), "=", rowEcr.getInt("ID_JOURNAL"));
 
f2.getPanel().getListe().getRequest().setWhere(w);
f2.getPanel().getListe().setModificationAllowed(false);
f2.pack();
f2.setVisible(true);
}
});
 
menuDroit.add(new AbstractAction("Voir la source") {
 
public void actionPerformed(ActionEvent e) {
 
// int id = f.getPanel().getListe().getSelectedId();
int id = f.getPanel().getListe().idFromIndex(f.getPanel().getListe().getJTable().rowAtPoint(mE.getPoint()));
System.err.println("ID COMPTE SELECTED " + id);
SQLRow rowEcr = getTable().getTable("ECRITURE").getRow(id);
 
System.out.println("MOUVEMENT VALIDE ------------->>>>>>>>>>>>>> " + MouvementSQLElement.isEditable(rowEcr.getInt("ID_MOUVEMENT")));
 
MouvementSQLElement.showSource(rowEcr.getInt("ID_MOUVEMENT"));
 
System.out.println("Mouvement Numero : " + rowEcr.getInt("ID_MOUVEMENT"));
}
});
 
menuDroit.show(mE.getComponent(), mE.getX(), mE.getY());
}
}
});
 
SQLTable ecrTable = getTable().getTable("ECRITURE");
 
Where w = new Where(ecrTable.getField("ID_COMPTE_PCE"), "=", rowCpt.getID());
f.getPanel().getListe().getRequest().setWhere(w);
 
f.getPanel().getListe().setModificationAllowed(false);
f.pack();
f.setVisible(true);
640,9 → 696,7
 
// on archive le mouvement
if (dropMvt) {
 
SQLElement elt = getDirectory().getElement(tableMvt);
 
SQLElement elt = Configuration.getInstance().getDirectory().getElement(tableMvt);
try {
elt.archive(idMvt);
} catch (SQLException e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AssociationAnalytiqueSQLElement.java
16,8 → 16,6
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElementLink.LinkType;
import org.openconcerto.sql.element.SQLElementLinksSetup;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.graph.Path;
46,14 → 44,6
this.setAction("ID_SAISIE_KM_ELEMENT", ReferenceAction.CASCADE);
}
 
@Override
protected void setupLinks(SQLElementLinksSetup links) {
super.setupLinks(links);
if (getTable().contains("ID_ECRITURE")) {
links.get("ID_ECRITURE").setType(LinkType.ASSOCIATION);
}
}
 
protected List<String> getListFields() {
final List<String> list = new ArrayList<String>(2);
list.add("ID_ECRITURE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033A.java
499,9 → 499,9
// 120 -SommeSolde( 100, 103* )-SommeSolde( 108, 109* )
// Racine = "101, 104, 108"
// S120=-10...101-108-104
long v120 = -this.sommeCompte.sommeCompteFils("101", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("102", this.dateDebut, this.dateFin)
- this.sommeCompte.sommeCompteFils("103", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("108", this.dateDebut, this.dateFin)
- this.sommeCompte.sommeCompteFils("104", this.dateDebut, this.dateFin) + this.sommeCompte.soldeCompteCrediteur(109, 109, true, this.dateDebut, this.dateFin);
long v120 = -this.sommeCompte.sommeCompteFils("101", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("103", this.dateDebut, this.dateFin)
- this.sommeCompte.sommeCompteFils("108", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("104", this.dateDebut, this.dateFin)
+ this.sommeCompte.soldeCompteCrediteur(109, 109, true, this.dateDebut, this.dateFin);
this.m.put("PASSIF3.15", GestionDevise.currencyToString(v120, false));
 
// 121
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033B.java
215,7 → 215,7
* VARIATION DE STOCK
******************************************************************************************/
// 240 SommeSolde( 6030, 6036* )
long v240 = this.sommeCompte.soldeCompte(6031, 6036, true, this.dateDeb, this.dateFin);
long v240 = this.sommeCompte.soldeCompte(6031, 6032, true, this.dateDeb, this.dateFin);
this.m.put("CHARGES3.11", GestionDevise.currencyToString(v240, false));
 
// 213
264,7 → 264,7
******************************************************************************************/
// 250 SommeSolde( 640, 644* )+SommeSolde( 648, 649* )
long v250 = this.sommeCompte.soldeCompte(644, 644, true, this.dateDeb, this.dateFin) + this.sommeCompte.soldeCompte(648, 649, true, this.dateDeb, this.dateFin)
+ this.sommeCompte.soldeCompte(641, 641, true, this.dateDeb, this.dateFin)+ this.sommeCompte.soldeCompte(642, 642, true, this.dateDeb, this.dateFin);
+ this.sommeCompte.soldeCompte(641, 641, true, this.dateDeb, this.dateFin);
this.m.put("CHARGES3.14", GestionDevise.currencyToString(v250, false));
 
// 220
352,7 → 352,7
* PRODUITS FINANCIERS
******************************************************************************************/
// 280 -SommeSolde( 760, 769* )-SommeSolde( 786, 786* )-SommeSolde( 796, 796* )
long v280 = -this.sommeCompte.soldeCompte(760, 768, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(786, 786, true, this.dateDeb, this.dateFin)
long v280 = -this.sommeCompte.soldeCompte(761, 768, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(786, 786, true, this.dateDeb, this.dateFin)
- this.sommeCompte.soldeCompte(796, 796, true, this.dateDeb, this.dateFin);
this.m.put("PCHARGES3.21", GestionDevise.currencyToString(v280, false));
 
369,7 → 369,7
* PRODUITS EXCEPTIONNELS
******************************************************************************************/
// 290 -SommeSolde( 77, 77* )-SommeSolde( 787, 789* )-SommeSolde( 797, 799* )
long v290 = -this.sommeCompte.soldeCompte(770, 772, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(775, 778, true, this.dateDeb, this.dateFin)
long v290 = -this.sommeCompte.soldeCompte(771, 772, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(775, 778, true, this.dateDeb, this.dateFin)
- this.sommeCompte.soldeCompte(787, 787, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(797, 797, true, this.dateDeb, this.dateFin);
this.m.put("PCHARGES3.22", GestionDevise.currencyToString(v290, false));
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheetXML.java
179,8 → 179,47
@Override
public SQLSelect transformChecked(SQLSelect sel) {
 
Where w = getWhere(lCompteSolde);
Where w = (new Where(tableEcriture.getField("DATE"), GrandLivreSheetXML.this.dateDu, GrandLivreSheetXML.this.dateAu));
 
if (GrandLivreSheetXML.this.compteDeb.equals(GrandLivreSheetXML.this.compteEnd)) {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "=", GrandLivreSheetXML.this.compteDeb));
} else {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), (Object) GrandLivreSheetXML.this.compteDeb, (Object) GrandLivreSheetXML.this.compteEnd));
}
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
w = w.and(new Where(tableEcriture.getField("ID_MOUVEMENT"), "=", tableMvt.getField("ID")));
 
if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
w = w.and(new Where(tableEcriture.getField("DATE_LETTRAGE"), "<=", GrandLivreSheetXML.this.dateAu));
} else if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODENONLETTREE_PERIODE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
Where wSTTC = new Where(tableEcriture.getField("DATE_LETTRAGE"), "<>", o);
wSTTC = wSTTC.and(new Where(tableEcriture.getField("DATE_LETTRAGE"), ">", GrandLivreSheetXML.this.dateAu));
 
w2 = w2.or(wSTTC);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
} else if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODENONLETTREE_ALL) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
}
 
if (GrandLivreSheetXML.this.excludeCompteSolde) {
System.err.println("Exclude compte");
 
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), lCompteSolde).not());
}
w = w.and(new Where(tableEcriture.getField("NOM"), "NOT LIKE", "Fermeture du compte%"));
 
if (!UserRightsManager.getCurrentUserRights().haveRight(ComptaUserRight.ACCES_NOT_RESCTRICTED_TO_411)) {
// TODO Show Restricted acces in UI
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "LIKE", "411%"));
}
 
sel.setWhere(w);
sel.addFieldOrder(tableEcriture.getField("COMPTE_NUMERO"));
sel.addFieldOrder(tableEcriture.getField("DATE"));
528,8 → 567,36
sel.addSelect(tableEcriture.getField("DEBIT"), "SUM");
sel.addSelect(tableEcriture.getField("CREDIT"), "SUM");
 
Where w = getWhere(null);
Where w;
if (this.compteDeb.equals(this.compteEnd)) {
w = new Where(tableCompte.getField("NUMERO"), "=", this.compteDeb);
} else {
w = new Where(tableCompte.getField("NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd);
}
 
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), "=", tableCompte.getField("ID")));
 
if (this.cumul) {
w = w.and(new Where(tableEcriture.getField("DATE"), "<=", this.dateAu));
} else {
w = w.and(new Where(tableEcriture.getField("DATE"), this.dateDu, this.dateAu));
}
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
if (this.lettrage == GrandLivreSheet.MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
} else if (this.lettrage == GrandLivreSheet.MODENONLETTREE_ALL) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
 
} else if (this.lettrage == GrandLivreSheet.MODENONLETTREE_PERIODE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
}
 
sel.setWhere(w);
 
String req = sel.asString() + " GROUP BY \"COMPTE_PCE\".\"ID\"";
556,52 → 623,6
return list;
}
 
private Where getWhere(final List<Integer> lCompteSolde) {
Where w = (new Where(tableEcriture.getField("DATE"), GrandLivreSheetXML.this.dateDu, GrandLivreSheetXML.this.dateAu));
 
if (GrandLivreSheetXML.this.compteDeb.equals(GrandLivreSheetXML.this.compteEnd)) {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "=", GrandLivreSheetXML.this.compteDeb));
} else {
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), (Object) GrandLivreSheetXML.this.compteDeb, (Object) GrandLivreSheetXML.this.compteEnd));
}
w = w.and(new Where(tableEcriture.getField("ID_JOURNAL"), "!=", idJrnlExclude));
w = w.and(new Where(tableEcriture.getField("ID_MOUVEMENT"), "=", tableMvt.getField("ID")));
 
if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODELETTREE) {
Object o = null;
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "<>", o));
w = w.and(new Where(tableEcriture.getField("LETTRAGE"), "!=", ""));
w = w.and(new Where(tableEcriture.getField("DATE_LETTRAGE"), "<=", GrandLivreSheetXML.this.dateAu));
} else if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODENONLETTREE_PERIODE) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
Where wSTTC = new Where(tableEcriture.getField("DATE_LETTRAGE"), "<>", o);
wSTTC = wSTTC.and(new Where(tableEcriture.getField("DATE_LETTRAGE"), ">", GrandLivreSheetXML.this.dateAu));
 
w2 = w2.or(wSTTC);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
} else if (GrandLivreSheetXML.this.lettrage == GrandLivreSheet.MODENONLETTREE_ALL) {
Object o = null;
Where w2 = new Where(tableEcriture.getField("LETTRAGE"), "=", o);
w = w.and(w2.or(new Where(tableEcriture.getField("LETTRAGE"), "=", "")));
}
 
if (GrandLivreSheetXML.this.excludeCompteSolde) {
System.err.println("Exclude compte");
 
if (lCompteSolde != null) {
w = w.and(new Where(tableEcriture.getField("ID_COMPTE_PCE"), lCompteSolde).not());
}
}
w = w.and(new Where(tableEcriture.getField("NOM"), "NOT LIKE", "Fermeture du compte%"));
 
if (!UserRightsManager.getCurrentUserRights().haveRight(ComptaUserRight.ACCES_NOT_RESCTRICTED_TO_411)) {
// TODO Show Restricted acces in UI
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "LIKE", "411%"));
}
return w;
}
 
/**
* @param d date limite des cumuls
* @return Map<Integer id compte, Long solde(debit-credit)>
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ComptaPrefTreeNode.java
31,6 → 31,7
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.erp.preferences.GestionPieceCommercialePanel;
import org.openconcerto.erp.preferences.ImpressionGestCommPreferencePanel;
import org.openconcerto.erp.preferences.MailRelancePreferencePanel;
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
import org.openconcerto.erp.preferences.NumerotationPreferencePanel;
import org.openconcerto.erp.preferences.PayPalPreferencePanel;
118,6 → 119,7
nsGlobale.add(new PrefTreeNode(GenerationDocGlobalPreferencePanel.class, "Génération des Documents", new String[] { "documents" }));
nsGlobale.add(new PrefTreeNode(GestionClientPreferencePanel.class, "Gestion des clients", new String[] { "client", "service" }));
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" });
160,6 → 162,7
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.getRunningModules().values()) {
for (final Entry<Boolean, List<ModulePreferencePanelDesc>> e : module.getPrefDescriptorsByLocation(moduleManager.getRoot()).entrySet()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteCloturePreferencePanel.java
133,7 → 133,7
this.rowPrefCompteVals.put("ID_COMPTE_PCE_BILAN_O", this.selCompteOuverture.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_BILAN_F", this.selCompteFermeture.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_RESULTAT", this.selCompteResultat.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_RESULTAT_PERTE", this.selCompteResultatPerte.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_RESULTAT_PERTE", this.selCompteResultat.getValue());
this.rowPrefCompteVals.put("ID_JOURNAL_AN", this.selJournal.getValue());
this.rowPrefCompteVals.put("CREATE_NUL_SOLDE_ECR", this.boxCompteSolde.isSelected());
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ListeDesEcrituresPanel.java
13,10 → 13,6
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.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
26,7 → 22,6
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Date;
 
import javax.swing.BorderFactory;
import javax.swing.JLabel;
59,18 → 54,9
c.fill = GridBagConstraints.BOTH;
this.add(this.panelEcritures, c);
 
SQLRow rowExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON").getRow(ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getInt("ID_EXERCICE_COMMON"));
 
final IListFilterDatePanel comp = new IListFilterDatePanel(this.panelEcritures.getListe(), this.panelEcritures.getListe().getSource().getElem().getTable().getField("DATE"),
IListFilterDatePanel.getDefaultMap());
comp.setDateDu((Date) rowExercice.getObject("DATE_DEB"));
c.weightx = 1;
c.gridy++;
this.add(comp, c);
 
/* Panel Legende */
c.gridwidth = 1;
c.gridy++;
c.gridy = GridBagConstraints.RELATIVE;
this.panelLegende = new JPanel();
this.panelLegende.setLayout(new GridBagLayout());
this.panelLegende.setBorder(BorderFactory.createTitledBorder("Légende"));
81,7 → 67,6
panelValide.add(new JLabel("Ecritures validées"));
panelValide.setBackground(Color.WHITE);
// panelValide.setBorder(BorderFactory.createLineBorder(Color.BLACK));
c.gridy++;
this.panelLegende.add(panelValide, c);
 
JPanel panelNonValide = new JPanel();
89,7 → 74,6
panelNonValide.add(new JLabel("Ecritures non validées"));
panelNonValide.setBackground(ListEcritureRenderer.getCouleurEcritureNonValide());
// panelNonValide.setBorder(BorderFactory.createLineBorder(Color.BLACK));
c.gridy++;
this.panelLegende.add(panelNonValide, c);
 
JPanel panelNonValideToDay = new JPanel();
97,10 → 81,9
panelNonValideToDay.add(new JLabel("Ecritures non validées du jour"));
panelNonValideToDay.setBackground(ListEcritureRenderer.getCouleurEcritureToDay());
// panelNonValideToDay.setBorder(BorderFactory.createLineBorder(Color.BLACK));
c.gridy++;
this.panelLegende.add(panelNonValideToDay, c);
 
c.gridy = 2;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.insets = new Insets(2, 2, 1, 2);
108,7 → 91,7
 
/* Panel Total */
c.gridx = 0;
// c.gridy = 0;
c.gridy = 0;
this.panelTotal = new JPanel();
this.panelTotal.setLayout(new GridBagLayout());
this.panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
142,7 → 125,7
c.gridx++;
this.panelTotal.add(this.montantSolde, c);
 
c.gridy = 2;
c.gridy = 1;
c.gridx = 1;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ConsultationCompteFrame.java
15,32 → 15,20
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.State;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.state.WindowStateManager;
 
import java.awt.DisplayMode;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
 
public class ConsultationCompteFrame extends JFrame {
// panel contenant la liste des ecritures
private final ListPanelEcritures panelEcritures;
49,13 → 37,12
 
private String titre;
 
private int indexID;
 
public ConsultationCompteFrame(ListeDesEcrituresPanel panel, SQLRowAccessor rowCpt) {
public ConsultationCompteFrame(ListeDesEcrituresPanel panel, String titre) {
super();
this.panel = panel;
this.panelEcritures = panel.getListPanelEcritures();
this.titre = "Consultation compte n°" + rowCpt.getString("NUMERO") + " " + rowCpt.getString("NOM");
this.titre = titre;
 
// rafraichir le titre à chaque changement de la liste
this.panelEcritures.getListe().addListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
76,74 → 63,8
}
});
}
 
SQLTable ecrTable = rowCpt.getTable().getTable("ECRITURE");
 
final int id = rowCpt.getID();
Where w = new Where(ecrTable.getField("ID_COMPTE_PCE"), "=", id);
getPanel().getListe().getRequest().setWhere(w);
 
final SQLTable cptTable = ecrTable.getForeignTable("ID_COMPTE_PCE");
List<SQLRow> rowsCpt = new ArrayList<SQLRow>(SQLBackgroundTableCache.getInstance().getCacheForTable(cptTable).getRows());
Collections.sort(rowsCpt, new Comparator<SQLRow>() {
@Override
public int compare(SQLRow o1, SQLRow o2) {
 
return o1.getString("NUMERO").compareTo(o2.getString("NUMERO"));
}
});
final List<Integer> idsCpt = new ArrayList<>();
for (SQLRow sqlRow : rowsCpt) {
idsCpt.add(sqlRow.getID());
}
this.indexID = idsCpt.indexOf(rowCpt.getID());
 
final PredicateRowAction prec = new PredicateRowAction(new AbstractAction("Précédent") {
 
@Override
public void actionPerformed(ActionEvent e) {
 
if (indexID > 0) {
int newCptId = idsCpt.get(indexID - 1);
Where w = new Where(ecrTable.getField("ID_COMPTE_PCE"), "=", newCptId);
getPanel().getListe().getRequest().setWhere(w);
SQLRow rowCptNew = SQLBackgroundTableCache.getInstance().getCacheForTable(cptTable).getRowFromId(newCptId);
setTitle("Consultation compte n°" + rowCptNew.getString("NUMERO") + " " + rowCptNew.getString("NOM"));
indexID--;
}
 
}
}, true, false);
prec.setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE));
panel.getListPanelEcritures().getListe().addIListeAction(prec);
 
final PredicateRowAction suivant = new PredicateRowAction(new AbstractAction("Suivant") {
 
@Override
public void actionPerformed(ActionEvent e) {
 
if (indexID < idsCpt.size() - 1) {
int newCptId = idsCpt.get(indexID + 1);
Where w = new Where(ecrTable.getField("ID_COMPTE_PCE"), "=", newCptId);
getPanel().getListe().getRequest().setWhere(w);
SQLRow rowCptNew = SQLBackgroundTableCache.getInstance().getCacheForTable(cptTable).getRowFromId(newCptId);
setTitle("Consultation compte n°" + rowCptNew.getString("NUMERO") + " " + rowCptNew.getString("NOM"));
indexID++;
}
 
}
}, true, false);
suivant.setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE));
panel.getListPanelEcritures().getListe().addIListeAction(suivant);
 
}
 
@Override
public void setTitle(String title) {
this.titre = title;
super.setTitle(title);
}
 
private String getPlural(String s, int nb) {
return nb + " " + s + (nb > 1 ? "s" : "");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteGestCommPreferencePanel.java
15,7 → 15,6
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.erp.preferences.DefaultNXProps;
46,7 → 45,7
 
private ISQLCompteSelector selCompteTVAIntraComm, selCompteFourn, selCompteAchat, selCompteValeurEncaissement, selCompteAvanceClient, selCompteClient, selCompteVenteProduits,
selCompteVenteService, selCompteTVACol, selCompteTVADed, selCompteTVAImmo, selCompteAchatIntra, selCompteFactor, selComptePortSoumis, selComptePortNonSoumis;
private ElementComboBox selJrnlFactor, selJrnlValEnc;
private ElementComboBox selJrnlFactor;
private final static SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
private SQLRowValues rowPrefCompteVals = new SQLRowValues(tablePrefCompte);
175,17 → 174,6
this.selCompteValeurEncaissement.init();
this.add(this.selCompteValeurEncaissement, c);
 
// Journal
c.gridy++;
c.weightx = 0;
c.gridx = 0;
this.add(new JLabel("Journal dépôt chèque"), c);
c.weightx = 1;
c.gridx++;
this.selJrnlValEnc = new ElementComboBox();
this.selJrnlValEnc.init(Configuration.getInstance().getDirectory().getElement("JOURNAL"));
this.add(this.selJrnlValEnc, c);
 
// Compte vente produits
c.gridy++;
c.weightx = 0;
337,10 → 325,6
this.rowPrefCompteVals.put("ID_COMPTE_PCE_FACTOR", this.selCompteFactor.getValue());
final int selectedId = this.selJrnlFactor.getSelectedId();
this.rowPrefCompteVals.put("ID_JOURNAL_FACTOR", (selectedId > 1) ? selectedId : 1);
 
final int selectedIdEnc = this.selJrnlValEnc.getSelectedId();
this.rowPrefCompteVals.put("ID_JOURNAL_VALEUR_ENCAISSEMENT", (selectedIdEnc > 1) ? selectedIdEnc : 1);
 
this.rowPrefCompteVals.put("ID_COMPTE_PCE_FOURNISSEUR", this.selCompteFourn.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_CLIENT", this.selCompteClient.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_AVANCE_CLIENT", this.selCompteAvanceClient.getValue());
404,7 → 388,6
this.selCompteFactor.setValue(value);
 
this.selJrnlFactor.setValue(GenerationMvtSaisieVenteFacture.journal);
this.selJrnlValEnc.setValue(JournalSQLElement.BANQUES);
 
// Fournisseurs
compte = ComptePCESQLElement.getComptePceDefault("Fournisseurs");
472,22 → 455,14
setComboValues(selCompteVenteService, "ID_COMPTE_PCE_VENTE_SERVICE", "VentesServices");
setComboValues(selCompteFactor, "ID_COMPTE_PCE_FACTOR", "Factor");
 
{
// Journal Factor
int value = (this.rowPrefCompteVals.getObject("ID_JOURNAL_FACTOR") == null ? 1 : this.rowPrefCompteVals.getInt("ID_JOURNAL_FACTOR"));
if (value <= 1) {
 
value = GenerationMvtSaisieVenteFacture.journal;
}
this.selJrnlFactor.setValue(value);
}
{
// Journal Val enc
int value = (this.rowPrefCompteVals.getObject("ID_JOURNAL_VALEUR_ENCAISSEMENT") == null ? 1 : this.rowPrefCompteVals.getInt("ID_JOURNAL_VALEUR_ENCAISSEMENT"));
if (value <= 1) {
value = JournalSQLElement.BANQUES;
}
this.selJrnlValEnc.setValue(value);
}
 
setComboValues(selCompteFourn, "ID_COMPTE_PCE_FOURNISSEUR", "Fournisseurs");
setComboValues(selCompteClient, "ID_COMPTE_PCE_CLIENT", "Clients");
setComboValues(selCompteAvanceClient, "ID_COMPTE_PCE_AVANCE_CLIENT", "AvanceClients");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/EcritureGrandLivreRenderer.java
40,16 → 40,23
}
 
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
 
TableCellRendererUtils.setBackgroundColor(this, table, isSelected);
 
if (!isSelected) {
 
Ecriture ecrTmp = ((ConsultCompteModel) this.model.getTableModel()).getEcritures().get(this.model.viewIndex(row));
 
if (!ecrTmp.getValide()) {
// this.setForeground(couleurEcritureValide);
Date dateEcr = ecrTmp.getDate();
Date dateToDay = new Date();
 
if ((dateEcr.getDate() == dateToDay.getDate()) && (dateEcr.getMonth() == dateToDay.getMonth()) && (dateEcr.getYear() == dateToDay.getYear())) {
// System.out.println("ToDay :: " + dateToDay + " Ecr ::: " + dateEcr);
 
this.setBackground(couleurEcritureToDay);
} else {
this.setBackground(couleurEcritureValide);
56,13 → 63,14
}
}
}
if (value != null) {
 
if (value instanceof Date) {
this.setText(dateFormat.format((Date) value));
} else if (value.getClass() == Long.class) {
}
if (value.getClass() == Long.class) {
this.setText(GestionDevise.currencyToString(((Long) value).longValue()));
}
}
 
return this;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalItemTable.java
21,7 → 21,6
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.TM;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
37,7 → 36,6
import org.openconcerto.sql.view.list.TextTableCellEditorWithCompletion;
import org.openconcerto.sql.view.list.ValidStateChecker;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JComponentUtils;
import org.openconcerto.ui.RangedIntegerTableCellEditor;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.GestionDevise;
47,7 → 45,6
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
57,7 → 54,6
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
66,7 → 62,6
 
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
300,21 → 295,10
 
TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table);
 
JButton buttonClone = new JButton(TM.tr("duplicateLine"));
buttonClone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
cloneLine(table.getSelectedRow());
}
});
buttonClone.setEnabled(false);
c.gridx++;
JComponentUtils.setMinimumWidth(buttonClone, 95);
this.controlPanel = new RowValuesTableControlPanel(this.table);
controlPanel.setButtonAjouterEnabled(false);
this.add(controlPanel, c);
 
this.controlPanel = new RowValuesTableControlPanel(this.table, Arrays.asList(buttonClone));
this.controlPanel.setVisibleButtonClone(false);
this.controlPanel.setButtonAjouterEnabled(false);
this.add(this.controlPanel, c);
 
c.gridy++;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
704,26 → 688,4
public void mouseExited(final MouseEvent e) {
}
 
private void cloneLine(int row) {
if (row < 0) {
System.err.println("RowValuesTableControlPanel.cloneLine() wrong selected line, index = " + row);
Thread.dumpStack();
return;
}
SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row);
 
SQLRowValues rowValsBis = rowVals.deepCopy();
rowValsBis.clearPrimaryKeys();
rowValsBis.put(rowValsBis.getTable().getOrderField().getName(), null);
 
this.table.getRowValuesTableModel().getSQLElement().clearPrivateFields(rowValsBis);
rowValsBis.putEmptyLink("ID_ECRITURE");
for (String elt : this.table.getClearCloneTableElement()) {
if (rowValsBis.getTable().getFieldsName().contains(elt)) {
rowValsBis.putEmptyLink(elt);
}
}
 
this.table.getRowValuesTableModel().addRow(rowValsBis);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieKmItemTable.java
20,7 → 20,6
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.TM;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
39,16 → 38,13
import org.openconcerto.sql.view.list.TextTableCellEditorWithCompletion;
import org.openconcerto.sql.view.list.ValidStateChecker;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JComponentUtils;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
55,7 → 51,6
import java.util.Vector;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
148,7 → 143,7
@Override
public ValidState getValidState(Object o) {
if (o != null) {
return this.elt.getCompteNumeroValidState(o.toString());
return elt.getCompteNumeroValidState(o.toString());
}
return super.getValidState(o);
}
166,19 → 161,8
m2.setWhere(w);
 
TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table);
JButton buttonClone = new JButton(TM.tr("duplicateLine"));
buttonClone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
cloneLine(table.getSelectedRow());
}
});
buttonClone.setEnabled(false);
c.gridx++;
JComponentUtils.setMinimumWidth(buttonClone, 95);
 
RowValuesTableControlPanel rowValuesTableControlPanel = new RowValuesTableControlPanel(this.table, Arrays.asList(buttonClone));
rowValuesTableControlPanel.setVisibleButtonClone(false);
this.add(rowValuesTableControlPanel, c);
this.add(new RowValuesTableControlPanel(this.table), c);
 
c.gridy++;
c.fill = GridBagConstraints.BOTH;
238,29 → 222,6
 
}
 
private void cloneLine(int row) {
if (row < 0) {
System.err.println("RowValuesTableControlPanel.cloneLine() wrong selected line, index = " + row);
Thread.dumpStack();
return;
}
SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row);
 
SQLRowValues rowValsBis = rowVals.deepCopy();
rowValsBis.clearPrimaryKeys();
rowValsBis.put(rowValsBis.getTable().getOrderField().getName(), null);
 
this.table.getRowValuesTableModel().getSQLElement().clearPrivateFields(rowValsBis);
rowValsBis.putEmptyLink("ID_ECRITURE");
for (String elt : this.table.getClearCloneTableElement()) {
if (rowValsBis.getTable().getFieldsName().contains(elt)) {
rowValsBis.putEmptyLink(elt);
}
}
 
this.table.getRowValuesTableModel().addRow(rowValsBis);
}
 
/**
* Remplit la RowValuesTable avec les ecritures du mouvement
*
373,11 → 334,11
assert SwingUtilities.isEventDispatchThread();
if (text == null)
return;
RowValuesTableModel model = this.table.getRowValuesTableModel();
RowValuesTableModel model = table.getRowValuesTableModel();
int size = model.getRowCount();
for (int i = 0; i < size; i++) {
SQLRowValues r = model.getRowValuesAt(i);
if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").equals(previousText)) {
if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").trim().equals(previousText)) {
r.put("NOM_ECRITURE", text);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/SalarieSQLElement.java
15,7 → 15,6
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.element.ContactItemTable;
import org.openconcerto.erp.core.edm.AttachmentAction;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.ElementSQLObject;
26,17 → 25,15
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.UndefinedRowValuesCache;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanelListener;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.EditPanelListener;
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.FormLayouter;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.warning.JLabelWarning;
import org.openconcerto.utils.checks.ValidState;
49,11 → 46,9
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
99,7 → 94,6
try {
rowInfosAncien.createEmptyUpdateRow().put("ID_SALARIE", rowSelected.getID()).commit();
rowSelected.createEmptyUpdateRow().put("ID_INFOS_SALARIE_PAYE", id).commit();
infosPayeElement.getTable().getRow(id).createEmptyUpdateRow().put("ID_SALARIE", rowSelected.getID()).commit();
} catch (SQLException e) {
e.printStackTrace();
}
147,7 → 141,7
return new BaseSQLComponent(this) {
private final JLabel warningCodeSalLabel = new JLabelWarning();
private final JTextField textCode = new JTextField();
ContactItemTable tableContact = new ContactItemTable(UndefinedRowValuesCache.getInstance().getDefaultRowValues(getTable().getTable("CONTACT_SALARIE")));
 
private JTabbedPane tabbedPane;
private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
 
212,18 → 206,6
}
});
 
// User
final JLabel labelUser = new JLabel(getLabelFor("ID_USER_COMMON"));
final ElementComboBox comboUser = new ElementComboBox(false, 50);
c.gridx = 0;
c.gridy++;
this.add(labelUser, c);
c.gridx++;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
this.add(comboUser, c);
this.addView(comboUser, "ID_USER_COMMON");
 
/***********************************************************************************
* TABBED PANE
**********************************************************************************/
236,18 → 218,6
scrollEtatCivil.setBorder(null);
this.tabbedPane.add("Etat Civil", scrollEtatCivil);
 
// Contact
JPanel panelContact = new JPanel(new GridBagLayout());
DefaultGridBagConstraints cContact = new DefaultGridBagConstraints();
cContact.weighty = 1;
cContact.weightx = 1;
cContact.fill = GridBagConstraints.BOTH;
 
panelContact.add(tableContact, cContact);
JScrollPane scrollContact = new JScrollPane(panelContact);
scrollContact.setBorder(null);
this.tabbedPane.add("Contacts", scrollContact);
 
// Règlement de la paye
this.addView("ID_REGLEMENT_PAYE", REQ + ";" + DEC + ";" + SEP);
ElementSQLObject eltReglPaye = (ElementSQLObject) this.getView("ID_REGLEMENT_PAYE");
316,18 → 286,7
this.tabbedPane.add("Cumuls et variables de la période", new JScrollPane(panelAllCumul));
// this.tabbedPane.setEnabledAt(this.tabbedPane.getTabCount() - 1, false);
 
Map<String, JComponent> additionalFields = getElement().getAdditionalFields();
if (additionalFields != null && additionalFields.size() > 0) {
// Champ Module
c.gridx = 0;
c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();
this.setAdditionalFieldsPanel(new FormLayouter(addP, 2));
this.tabbedPane.add("Compléments", new JScrollPane(addP));
}
 
c.gridy++;
c.gridx = 0;
c.weighty = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
376,19 → 335,15
* }
*/
checkCode();
if (r != null) {
this.tableContact.insertFrom("ID_SALARIE", r.asRowValues());
}
}
 
public void update() {
 
super.update();
 
SQLTable tableFichePaye = getTable().getBase().getTable("FICHE_PAYE");
SQLRowValues rowVals = new SQLRowValues(tableFichePaye);
rowVals.put("ID_SALARIE",
 
getSelectedID());
rowVals.put("ID_SALARIE", getSelectedID());
SQLRow row = getTable().getRow(getSelectedID());
try {
rowVals.update(row.getInt("ID_FICHE_PAYE"));
395,7 → 350,6
} catch (SQLException e) {
e.printStackTrace();
}
this.tableContact.updateField("ID_SALARIE", getSelectedID());
}
 
public int insert(SQLRow order) {
433,10 → 387,9
e.printStackTrace();
}
}
this.tableContact.updateField("ID_SALARIE", id);
 
return id;
}
 
};
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ContratSalarieSQLElement.java
113,20 → 113,6
c.weightx = 1;
this.add(selCodeCatSocio, c);
JLabel complPCSLabel = new JLabel(getLabelFor("COMPLEMENT_PCS"));
complPCSLabel.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField complPCS = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(complPCSLabel, c);
c.gridx++;
c.weightx = 1;
this.add(complPCS, c);
addView(complPCS,"COMPLEMENT_PCS");
 
// Contrat de travail
JLabel labelContratTravail = new JLabel(getLabelFor("ID_CODE_CONTRAT_TRAVAIL"));
labelContratTravail.setHorizontalAlignment(SwingConstants.RIGHT);
239,91 → 225,87
this.add(selFF, c);
this.addSQLObject(selFF, "ID_CONTRAT_MOTIF_RECOURS");
 
// Code Arrco, agirc retirés du contrat et ajoutés dans les caisses de cotisations
 
// Code UGRR
JLabel labelCodeUGRR = new JLabel(getLabelFor("CODE_IRC_UGRR"));
labelCodeUGRR.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textCodeUGRR = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelCodeUGRR, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textCodeUGRR, c);
addView(textCodeUGRR, "CODE_IRC_UGRR");
 
// JLabel labelCodeUGRR = new JLabel(getLabelFor("CODE_IRC_UGRR"));
// labelCodeUGRR.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textCodeUGRR = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelCodeUGRR, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textCodeUGRR, c);
// addView(textCodeUGRR, "CODE_IRC_UGRR");
//
// JLabel labelNumUGRR = new JLabel(getLabelFor("NUMERO_RATTACHEMENT_UGRR"));
// labelNumUGRR.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textNumUGRR = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelNumUGRR, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textNumUGRR, c);
// addView(textNumUGRR, "NUMERO_RATTACHEMENT_UGRR");
//
// // Code UGRC
// JLabel labelCodeUGRC = new JLabel(getLabelFor("CODE_IRC_UGRC"));
// labelCodeUGRC.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textCodeUGRC = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelCodeUGRC, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textCodeUGRC, c);
// addView(textCodeUGRC, "CODE_IRC_UGRC");
//
// JLabel labelNumUGRC = new JLabel(getLabelFor("NUMERO_RATTACHEMENT_UGRC"));
// labelNumUGRC.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textNumUGRC = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelNumUGRC, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textNumUGRC, c);
// addView(textNumUGRC, "NUMERO_RATTACHEMENT_UGRC");
//
// // Retraite
// JLabel labelCodeRetraite = new JLabel(getLabelFor("CODE_IRC_RETRAITE"));
// labelCodeRetraite.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textCodeRetraite = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelCodeRetraite, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textCodeRetraite, c);
// addView(textCodeRetraite, "CODE_IRC_RETRAITE");
//
// JLabel labelNumRetraite = new
// JLabel(getLabelFor("NUMERO_RATTACHEMENT_RETRAITE"));
// labelNumRetraite.setHorizontalAlignment(SwingConstants.RIGHT);
// JTextField textNumRetraite = new JTextField();
// c.gridy++;
// c.gridx = 0;
// c.weightx = 0;
// this.add(labelNumRetraite, c);
// c.gridx++;
// c.weighty = 1;
// c.weightx = 1;
// this.add(textNumRetraite, c);
// addView(textNumRetraite, "NUMERO_RATTACHEMENT_RETRAITE");
JLabel labelNumUGRR = new JLabel(getLabelFor("NUMERO_RATTACHEMENT_UGRR"));
labelNumUGRR.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textNumUGRR = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelNumUGRR, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textNumUGRR, c);
addView(textNumUGRR, "NUMERO_RATTACHEMENT_UGRR");
 
// Code UGRC
JLabel labelCodeUGRC = new JLabel(getLabelFor("CODE_IRC_UGRC"));
labelCodeUGRC.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textCodeUGRC = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelCodeUGRC, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textCodeUGRC, c);
addView(textCodeUGRC, "CODE_IRC_UGRC");
 
JLabel labelNumUGRC = new JLabel(getLabelFor("NUMERO_RATTACHEMENT_UGRC"));
labelNumUGRC.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textNumUGRC = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelNumUGRC, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textNumUGRC, c);
addView(textNumUGRC, "NUMERO_RATTACHEMENT_UGRC");
 
// Retraite
JLabel labelCodeRetraite = new JLabel(getLabelFor("CODE_IRC_RETRAITE"));
labelCodeRetraite.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textCodeRetraite = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelCodeRetraite, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textCodeRetraite, c);
addView(textCodeRetraite, "CODE_IRC_RETRAITE");
 
JLabel labelNumRetraite = new JLabel(getLabelFor("NUMERO_RATTACHEMENT_RETRAITE"));
labelNumRetraite.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textNumRetraite = new JTextField();
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(labelNumRetraite, c);
c.gridx++;
c.weighty = 1;
c.weightx = 1;
this.add(textNumRetraite, c);
addView(textNumRetraite, "NUMERO_RATTACHEMENT_RETRAITE");
 
// JLabel labelCodeRegimeRetraite = new
// JLabel(getLabelFor("CODE_REGIME_RETRAITE_DSN"));
// labelCodeRegimeRetraite.setHorizontalAlignment(SwingConstants.RIGHT);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/InfosSalariePayeSQLElement.java
442,19 → 442,6
panelBase.add(sectionAT, c);
addView(sectionAT, "CODE_SECTION_AT");
 
if (getTable().contains("DUREE_FORFAIT")) {
JLabel labelForfait = new JLabel(getLabelFor("DUREE_FORFAIT"));
labelForfait.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField forfait = new JTextField();
c.gridx++;
c.weightx = 0;
panelBase.add(labelForfait, c);
c.gridx++;
c.weightx = 1;
panelBase.add(forfait, c);
addView(forfait, "DUREE_FORFAIT");
}
 
c.gridy = 5;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ReglementPayeSQLElement.java
97,7 → 97,7
JLabel labelNomBq = new JLabel(getLabelFor("NOM_BANQUE"));
labelNomBq.setHorizontalAlignment(SwingConstants.RIGHT);
SQLTextCombo textNomBq = new SQLTextCombo();
c.weightx = 0;
 
panelBanque.add(labelNomBq, c);
c.gridx++;
c.weightx = 1;
104,32 → 104,6
panelBanque.add(textNomBq, c);
c.weightx = 0;
 
// IBAN
JLabel labelIBAN = new JLabel(getLabelFor("IBAN"));
labelIBAN.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textIBAN = new JTextField();
 
c.gridy++;
c.gridx = 0;
c.weightx = 0;
panelBanque.add(labelIBAN, c);
c.gridx++;
c.weightx = 1;
panelBanque.add(textIBAN, c);
 
// BIC
JLabel labelBIC = new JLabel(getLabelFor("BIC"));
labelBIC.setHorizontalAlignment(SwingConstants.RIGHT);
JTextField textBIC = new JTextField();
 
c.gridy++;
c.gridx = 0;
c.weightx = 0;
panelBanque.add(labelBIC, c);
c.gridx++;
c.weightx = 1;
panelBanque.add(textBIC, c);
 
// RIB
JLabel labelRIB = new JLabel(getLabelFor("RIB"));
labelRIB.setHorizontalAlignment(SwingConstants.RIGHT);
179,13 → 153,11
c.gridy++;
panelReglement.add(radioLe, c);
c.gridx++;
c.weightx = 1;
panelReglement.add(textLe, c);
textLe.setText("31");
c.gridx++;
c.weightx = 0;
c.weightx = 1;
panelReglement.add(labelDu, c);
c.weightx = 1;
 
c.gridy++;
c.gridx = 0;
238,7 → 210,6
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.weightx = 0;
panelCompta.add(labelCompteSal, c);
c.gridx++;
c.weightx = 1;
254,8 → 225,6
 
this.addSQLObject(textNomBq, "NOM_BANQUE");
this.addSQLObject(textRIB, "RIB");
this.addSQLObject(textIBAN, "IBAN");
this.addSQLObject(textBIC, "BIC");
this.addRequiredSQLObject(typeRegl, "ID_MODE_REGLEMENT_PAYE");
this.addRequiredSQLObject(textLe, "LE");
this.addRequiredSQLObject(compteSal, "ID_COMPTE_PCE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/FichePayeSheetXML.java
198,36 → 198,10
ligneSimplifiee.put("MONTANT_SAL_DED", montantSalBulletinSimpl.add(montantSalLigne));
ligneSimplifiee.put("MONTANT_PAT", montantPatBulletinSimpl.add(montantPatLigne));
}
 
BigDecimal tauxPatBulletinSimpl = BigDecimal.ZERO;
BigDecimal tauxSalBulletinSimpl = BigDecimal.ZERO;
if (ligneSimplifiee.getBigDecimal("TAUX_SAL") != null) {
tauxSalBulletinSimpl = ligneSimplifiee.getBigDecimal("TAUX_SAL");
}
if (ligneSimplifiee.getBigDecimal("TAUX_PAT") != null) {
tauxPatBulletinSimpl = ligneSimplifiee.getBigDecimal("TAUX_PAT");
}
 
BigDecimal tauxPatLigne = BigDecimal.ZERO;
BigDecimal tauxSalLigne = BigDecimal.ZERO;
if (sqlRowAccessor.getBigDecimal("TAUX_SAL") != null) {
tauxSalLigne = sqlRowAccessor.getBigDecimal("TAUX_SAL");
}
if (sqlRowAccessor.getBigDecimal("TAUX_PAT") != null) {
tauxPatLigne = sqlRowAccessor.getBigDecimal("TAUX_PAT");
}
 
if (tauxSalLigne.signum() > 0) {
ligneSimplifiee.put("TAUX_SAL", tauxSalBulletinSimpl.add(tauxSalLigne));
}
 
if (tauxPatLigne.signum() > 0) {
ligneSimplifiee.put("TAUX_PAT", tauxPatBulletinSimpl.add(tauxPatLigne));
}
}
}
}
 
private StyleSQLElement eltStyle = Configuration.getInstance().getDirectory().getElement(StyleSQLElement.class);
 
private Map<String, SQLRowValues> initCotisations(boolean cadre, List<SQLRowAccessor> resultCotis) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/ui/EditionFichePayePanel.java
165,7 → 165,7
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
buttonValid.setEnabled(dateDeb.getValue() != null && dateFin.getValue() != null && dateDeb.getValue().compareTo(dateFin.getValue()) <= 0);
buttonValid.setEnabled(dateDeb.getValue() != null && dateFin.getValue() != null && dateDeb.getValue().before(dateFin.getValue()));
model.setDateLimit(dateDeb.getValue());
}
};
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/EtatCivilSQLElement.java
293,7 → 293,7
c.gridwidth = 1;
c.weightx = 1;
JTextField fieldNTT = new JTextField();
panelSituation.add(fieldNTT, c);
panelSituation.add(fieldCNPS, c);
c.weightx = 0;
c.gridwidth = 1;
addView(fieldNTT, "NTT");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/POSConfiguration.java
30,7 → 30,6
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles.HashMode;
import org.openconcerto.erp.core.sales.pos.model.RegisterLogEntry.ReceiptEntry;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.erp.core.sales.pos.model.TicketLine;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
42,12 → 41,10
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
58,6 → 55,7
import org.openconcerto.utils.BaseDirs;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Pair;
import org.openconcerto.utils.i18n.TranslationManager;
 
import java.io.File;
71,11 → 69,9
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Logger;
 
import javax.swing.JOptionPane;
122,8 → 118,6
private String LCDLine1 = "Bienvenue";
private String LCDLine2 = "ILM Informatique";
 
private boolean askPostalCode = false;
 
public static POSConfiguration createInstance() throws JDOMException, IOException {
POSConfiguration res = new POSConfiguration(getConfigFile(new File(".")));
res.loadConfiguration();
261,8 → 255,8
System.exit(2);
}
 
NouvelleConnexionAction.initCache(conf, -1);
TaxeCache.getCache();
NouvelleConnexionAction.initCache(conf);
 
return conf;
}
 
323,23 → 317,14
throw new IllegalArgumentException("Size mismatch");
 
final int defaultIDClient = getClientCaisse().getID();
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
SQLElement elt = directory.getElement("TICKET_CAISSE");
SQLElement eltFact = directory.getElement("SAISIE_VENTE_FACTURE_ELEMENT");
SQLElement eltEnc = directory.getElement("ENCAISSER_MONTANT");
SQLElement eltMode = directory.getElement("MODE_REGLEMENT");
SQLElement eltArticle = directory.getElement("ARTICLE");
SQLElement elt = Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE");
SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
SQLElement eltEnc = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
SQLElement eltMode = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
final SQLDataSource ds = elt.getTable().getDBSystemRoot().getDataSource();
int imported = 0;
 
//
final SQLSelect selUniteVente = new SQLSelect();
selUniteVente.addSelectStar(directory.getElement("UNITE_VENTE").getTable());
final Map<String, Integer> mapUniteVenteName = new HashMap<>();
for (SQLRow row : SQLRowListRSH.execute(selUniteVente)) {
mapUniteVenteName.put(row.getString("CODE"), row.getID());
}
 
final Iterator<ReceiptEntry> entriesIter = entries == null ? null : entries.iterator();
for (Ticket ticket : tickets) {
SQLSelect sel = new SQLSelect();
362,9 → 347,6
rowVals.put("NUMERO", ticket.getCode());
rowVals.put("DATE", ticket.getCreationDate());
rowVals.put("ID_CAISSE", getPosID());
if (elt.getTable().contains("CODE_POSTAL")) {
rowVals.put("CODE_POSTAL", ticket.getCodePostal());
}
if (entry != null) {
rowVals.put("FILE_HASH", entry.getFileHash());
rowVals.put("FILE_HASH_PREVIOUS", ticket.getPreviousHash());
382,24 → 364,17
calc.setServiceActive(bServiceActive != null && bServiceActive);
 
// Articles
for (TicketItem item : ticket.getItems()) {
for (Pair<Article, Integer> item : ticket.getArticles()) {
SQLRowValues rowValsElt = new SQLRowValues(eltFact.getTable());
final Article article = item.getArticle();
final BigDecimal nb = item.getQty();
if (article.getSalesUnit() == null) {
rowValsElt.put("QTE", nb.intValue());
} else {
rowValsElt.put("QTE", 1);
rowValsElt.put("QTE_UNITAIRE", nb);
}
final Article article = item.getFirst();
final Integer nb = item.getSecond();
rowValsElt.put("QTE", nb);
rowValsElt.put("PV_HT", article.getPriceWithoutTax());
Float tauxFromId = TaxeCache.getCache().getTauxFromId(article.getIdTaxe());
BigDecimal tauxTVA = BigDecimal.valueOf(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
BigDecimal tauxTVA = new BigDecimal(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
 
final BigDecimal valueHT = article.getPriceWithoutTax().multiply(nb, DecimalUtils.HIGH_PRECISION);
if (article.getSalesUnit() != null) {
rowValsElt.put("ID_UNITE_VENTE", mapUniteVenteName.get(article.getSalesUnit()));
}
final BigDecimal valueHT = article.getPriceWithoutTax().multiply(new BigDecimal(nb), DecimalUtils.HIGH_PRECISION);
 
rowValsElt.put("T_PV_HT", valueHT);
rowValsElt.put("T_PV_TTC", valueHT.multiply(tauxTVA, DecimalUtils.HIGH_PRECISION));
rowValsElt.put("ID_TAXE", article.getIdTaxe());
474,7 → 449,7
false);
}
if (totalEnc > longValueTotal) {
final SQLTable table = directory.getElement("TYPE_REGLEMENT").getTable();
final SQLTable table = Configuration.getInstance().getDirectory().getElement("TYPE_REGLEMENT").getTable();
int idComptePceCaisse = table.getRow(TypeReglementSQLElement.ESPECE).getInt("ID_COMPTE_PCE_CLIENT");
if (idComptePceCaisse == table.getUndefinedID()) {
idComptePceCaisse = ComptePCESQLElement.getId(ComptePCESQLElement.getComptePceDefault("VenteEspece"));
545,13 → 520,15
stockUpdater.update();
}
 
public List<Ticket> allTickets() throws IOException {
public List<Ticket> allTickets() {
final List<Ticket> l = new ArrayList<Ticket>();
for (final File f : ReceiptCode.getReceiptsToImport(getPosID())) {
// old receipts have no hash files
final Ticket ticket = Ticket.parseFile(f, HashMode.NOT_REQUIRED);
if (ticket != null) {
l.add(ticket);
}
}
return l;
}
 
588,8 → 565,6
setCompanyID(Integer.valueOf(rootElement.getAttributeValue("societeID", "42")));
setPosID(Integer.valueOf(rootElement.getAttributeValue("caisseID", "2")));
setScanDelay(Integer.valueOf(rootElement.getAttributeValue("scanDelay", "80")));
setAskPostalCode(rootElement.getAttributeValue("askPostalCode", "false").equals("true"));
 
// screen
final List<Element> children = rootElement.getChildren("screen");
if (children != null) {
632,7 → 607,7
}
// ticket printers
final List<Element> printers = rootElement.getChildren("ticketPrinter");
if (!printers.isEmpty()) {
if (printers.size() > 0) {
configureTicketPrinter(this.ticketPrinterConf1, printers.get(0));
}
if (printers.size() > 1) {
674,7 → 649,6
configElement.setAttribute("societeID", String.valueOf(this.companyID));
configElement.setAttribute("caisseID", String.valueOf(this.posID));
configElement.setAttribute("scanDelay", String.valueOf(this.scanDelay));
configElement.setAttribute("askPostalCode", this.askPostalCode ? "true" : "false");
doc.addContent(configElement);
// screen size
final Element screenElement = new Element("screen");
825,12 → 799,4
public String getLCDType() {
return this.LCDType;
}
 
public boolean askPostalCode() {
return this.askPostalCode;
}
 
public void setAskPostalCode(boolean askPostalCode) {
this.askPostalCode = askPostalCode;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/TicketCaisseSQLElement.java
30,7 → 30,6
static public final String UNARCHIVED_WHERE = SQLBase.quoteIdentifier("ARCHIVE") + " = " + 0;
static public final String DATE_WHERE = UNARCHIVED_WHERE + " and " + SQLBase.quoteIdentifier("FILE_HASH") + " is not null";
 
// needed until H2 databases are upgraded to use JS code
static public final class UniqueNumber_PartialUniqueTrigger extends PartialUniqueTrigger {
public UniqueNumber_PartialUniqueTrigger() {
super(Arrays.asList("NUMERO"), UNARCHIVED_WHERE);
37,7 → 36,6
}
}
 
// needed until H2 databases are upgraded to use JS code
static public final class UniqueDate_PartialUniqueTrigger extends PartialUniqueTrigger {
public UniqueDate_PartialUniqueTrigger() {
super(Arrays.asList("ID_CAISSE", "DATE"), DATE_WHERE);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PostalCodeEditorPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSearchPanel.java
17,7 → 17,6
import org.openconcerto.erp.core.sales.pos.model.Categorie;
import org.openconcerto.ui.touch.ScrollableList;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
25,6 → 24,7
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
39,6 → 39,7
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
45,7 → 46,7
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
public class ArticleSearchPanel extends JPanel implements CaisseListener {
public class ArticleSearchPanel extends JPanel implements ListSelectionListener, CaisseListener {
private final ScrollableList list;
private final CaisseControler controler;
private final JTextField textField = new JTextField();
56,23 → 57,14
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
final FilteredListModel model = new FilteredListModel();
final Font f1;
final Font f2;
 
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
f1 = new Font("Arial", Font.PLAIN, 21);
f2 = new Font("Arial", Font.PLAIN, 14);
} else {
f1 = new Font("Arial", Font.PLAIN, 24);
f2 = new Font("Arial", Font.PLAIN, 16);
}
 
setBackground(new Color(230, 230, 230));
this.list = new ScrollableList(model) {
final Font f1 = new Font("Arial", Font.PLAIN, 24);
final Font f2 = new Font("Arial", Font.PLAIN, 16);
setBackground(CaissePanel.LIGHT_BLUE);
list = new ScrollableList(model) {
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.LIGHT_GRAY);
g.setColor(CaissePanel.LIGHT_BLUE);
g.drawLine(0, 0, 0, this.getHeight());
}
 
96,12 → 88,12
public void mouseReleased(MouseEvent event) {
if ((event.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) {
final Object obj = getSelectedValue();
if (obj instanceof Article) {
if (obj != null && obj instanceof Article) {
Article product = (Article) obj;
Categorie.toggleFavoriteState(product);
controler.saveFavoriteProductsIds(Categorie.getFavoriteProducts());
model.setFilter(ArticleSearchPanel.this.textField.getText());
ArticleSearchPanel.this.list.scrollToOffset(0);
model.setFilter(textField.getText());
list.scrollToOffset(0);
}
} else {
super.mouseReleased(event);
132,7 → 124,7
bar.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
ArticleSearchPanel.this.list.scrollToOffset(0);
list.scrollToOffset(0);
}
});
 
143,34 → 135,29
// List
c.weighty = 1;
c.gridy++;
this.list.setBackground(new Color(240, 240, 240));
this.add(this.list, c);
 
this.add(list, c);
// Separator
c.weighty = 0;
c.gridy++;
this.add(new JSeparator(JSeparator.HORIZONTAL), c);
 
JPanel pBottom = new JPanel();
pBottom.setOpaque(true);
pBottom.setBackground(CaissePanel.DARK_BLUE);
pBottom.setLayout(new BorderLayout(3, 3));
 
// Icon and text
 
c.weighty = 0;
c.gridy++;
c.insets = new Insets(3, 3, 3, 3);
final JLabel label = new JLabel(new ImageIcon(this.getClass().getResource("search.png")));
c.gridwidth = 1;
c.weightx = 0;
this.add(label, c);
 
pBottom.add(label, BorderLayout.WEST);
pBottom.setBorder(BorderFactory.createLineBorder(CaissePanel.DARK_BLUE, 3));
this.textField.setBorder(BorderFactory.createLineBorder(CaissePanel.DARK_BLUE, 1));
this.textField.setFont(f1);
 
this.textField.setFont(f1);
pBottom.add(this.textField, BorderLayout.CENTER);
c.gridy++;
textField.setBorder(BorderFactory.createLineBorder(CaissePanel.DARK_BLUE, 1));
textField.setFont(f1);
c.weightx = 1;
c.gridwidth = 2;
this.add(pBottom, c);
c.gridx++;
 
this.textField.getDocument().addDocumentListener(new DocumentListener() {
textField.setFont(f1);
this.add(textField, c);
textField.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
184,50 → 171,40
 
@Override
public void changedUpdate(DocumentEvent e) {
model.setFilter(ArticleSearchPanel.this.textField.getText());
model.setFilter(textField.getText());
controler.setArticleSelected(null);
}
});
this.list.addListSelectionListener(new ListSelectionListener() {
list.addListSelectionListener(this);
 
list.addMouseListener(new MouseAdapter() {
@Override
public void valueChanged(ListSelectionEvent e) {
Object sel = ArticleSearchPanel.this.list.getSelectedValue();
if (sel != null && !e.getValueIsAdjusting()) {
if (sel instanceof Article) {
public void mouseClicked(MouseEvent e) {
int nb = e.getClickCount();
if (nb > 1) {
Object sel = list.getSelectedValue();
if (sel != null) {
Article article = (Article) sel;
controler.incrementArticle(article);
controler.setArticleSelected(article);
 
}
}
 
}
});
}
 
this.list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Object sel = ArticleSearchPanel.this.list.getSelectedValue();
if (sel != null) {
int nb = e.getClickCount();
if (nb == 1) {
public void valueChanged(ListSelectionEvent e) {
Object sel = list.getSelectedValue();
if (sel != null && !e.getValueIsAdjusting()) {
if (sel instanceof Article) {
Article article = (Article) sel;
controler.setArticleSelected(article);
controler.addArticle(article);
}
} else if (nb > 1) {
Article article = (Article) sel;
controler.incrementArticle(article);
controler.setArticleSelected(article);
}
}
 
}
});
 
}
 
public void paintCategorie(final Font f, Font f2, Graphics g, Categorie c, boolean isSelected, int posY, int cellWidth, int cellHeight) {
g.setFont(f);
 
271,7 → 248,7
if (c.getParent() == null) {
return null;
}
String storedString = this.categoryCache.get(c);
String storedString = categoryCache.get(c);
if (storedString != null) {
return storedString;
}
296,28 → 273,28
parent = c.getParent();
 
}
this.categoryCache.put(c, s);
categoryCache.put(c, s);
return s;
}
 
@Override
public void caisseStateChanged() {
final Article articleSelected = this.controler.getArticleSelected();
final Article articleSelected = controler.getArticleSelected();
System.err.println("ArticleSearchPanel.caisseStateChanged() article selected : " + articleSelected);
if (articleSelected == null) {
this.list.clearSelection();
list.clearSelection();
return;
}
Object selectedValue = null;
try {
selectedValue = this.list.getSelectedValue();
selectedValue = list.getSelectedValue();
} catch (Exception e) {
e.printStackTrace();
}
if (selectedValue == null || !articleSelected.equals(selectedValue)) {
boolean found = this.list.setSelectedValue(articleSelected, true);
boolean found = list.setSelectedValue(articleSelected, true);
if (!found) {
this.list.clearSelection();
list.clearSelection();
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PriceEditorPanel.java
15,7 → 15,6
 
import org.openconcerto.erp.core.common.ui.NumericTextField;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
 
import java.awt.Color;
import java.awt.GridBagConstraints;
33,7 → 32,7
import javax.swing.event.DocumentListener;
 
public class PriceEditorPanel extends JPanel {
private final transient TicketItem item;
private final transient Article article;
private final POSLabel labelPrice;
private final POSRadioButton rHT;
private final POSRadioButton rTTC;
45,8 → 44,8
private final NumericTextField discountTextField;
private final NumericKeypadPanel keyPad;
 
public PriceEditorPanel(final CaisseFrame caisseFrame, final TicketItem item) {
this.item = item;
public PriceEditorPanel(final CaisseFrame caisseFrame, final Article article) {
this.article = article;
this.setBackground(Color.WHITE);
this.setOpaque(true);
this.setLayout(new GridBagLayout());
65,59 → 64,59
// Line 2
c.gridy++;
c.gridwidth = 1;
this.rTTC = new POSRadioButton("prix TTC");
this.rTTC.setSelected(true);
rTTC = new POSRadioButton("prix TTC");
rTTC.setSelected(true);
c.weightx = 0;
this.add(this.rTTC, c);
this.ttcTextField = new NumericTextField();
this.ttcTextField.setFont(title.getFont());
this.ttcTextField.setValue(item.getArticle().getPriceWithTax());
this.ttcTextField.requestFocusInWindow();
this.add(rTTC, c);
ttcTextField = new NumericTextField();
ttcTextField.setFont(title.getFont());
ttcTextField.setValue(article.getPriceWithTax());
ttcTextField.requestFocusInWindow();
c.gridx++;
c.weightx = 1;
this.add(this.ttcTextField, c);
this.add(ttcTextField, c);
// Line 3
c.gridy++;
this.rHT = new POSRadioButton("prix HT");
rHT = new POSRadioButton("prix HT");
c.gridx = 0;
c.weightx = 0;
this.add(this.rHT, c);
this.htTextField = new NumericTextField();
this.htTextField.setValue(item.getArticle().getPriceWithoutTax());
this.htTextField.setFont(title.getFont());
this.add(rHT, c);
htTextField = new NumericTextField();
htTextField.setValue(article.getPriceWithoutTax());
htTextField.setFont(title.getFont());
c.gridx++;
c.weightx = 1;
this.add(this.htTextField, c);
this.add(htTextField, c);
// Line 4
c.gridy++;
this.rDiscountPercent = new POSRadioButton("remise en %");
rDiscountPercent = new POSRadioButton("remise en %");
c.gridx = 0;
c.weightx = 0;
this.add(this.rDiscountPercent, c);
this.discountPercentTextField = new NumericTextField();
this.discountPercentTextField.setValue(BigDecimal.ZERO);
this.discountPercentTextField.setFont(title.getFont());
this.add(rDiscountPercent, c);
discountPercentTextField = new NumericTextField();
discountPercentTextField.setValue(BigDecimal.ZERO);
discountPercentTextField.setFont(title.getFont());
c.gridx++;
c.weightx = 1;
this.add(this.discountPercentTextField, c);
this.add(discountPercentTextField, c);
// Line 5
this.rDiscount = new POSRadioButton("remise HT");
rDiscount = new POSRadioButton("remise HT");
c.gridx = 0;
c.weightx = 0;
c.gridy++;
this.add(this.rDiscount, c);
this.discountTextField = new NumericTextField();
this.discountTextField.setValue(BigDecimal.ZERO);
this.discountTextField.setFont(title.getFont());
this.add(rDiscount, c);
discountTextField = new NumericTextField();
discountTextField.setValue(BigDecimal.ZERO);
discountTextField.setFont(title.getFont());
c.gridx++;
c.weightx = 1;
this.add(this.discountTextField, c);
this.add(discountTextField, c);
 
final ButtonGroup group = new ButtonGroup();
group.add(this.rHT);
group.add(this.rTTC);
group.add(this.rDiscountPercent);
group.add(this.rDiscount);
group.add(rHT);
group.add(rTTC);
group.add(rDiscountPercent);
group.add(rDiscount);
//
//
c.gridy++;
124,14 → 123,13
c.gridx = 0;
c.gridwidth = 2;
final POSLabel labelPriceOld = new POSLabel("Ancien Prix : ");
labelPriceOld.setText(
"Ancien Prix : " + TicketCellRenderer.toString(item.getArticle().getPriceWithTax()) + "€ TTC, " + TicketCellRenderer.toString(item.getArticle().getPriceWithoutTax()) + "€ HT");
labelPriceOld.setText("Ancien Prix : " + TicketCellRenderer.toString(article.getPriceWithTax()) + "€ TTC, " + TicketCellRenderer.toString(article.getPriceWithoutTax()) + "€ HT");
this.add(labelPriceOld, c);
 
c.gridy++;
c.gridx = 0;
this.labelPrice = new POSLabel("Nouveau Prix : ");
this.add(this.labelPrice, c);
labelPrice = new POSLabel("Nouveau Prix : ");
this.add(labelPrice, c);
 
c.gridy++;
c.gridx = 0;
148,7 → 146,7
 
@Override
public void actionPerformed(ActionEvent e) {
caisseFrame.getControler().setArticleHT(item, getHTFromUI());
caisseFrame.getControler().setArticleHT(article, getHTFromUI());
caisseFrame.showCaisse();
}
});
170,10 → 168,10
c.insets = new Insets(20, 20, 30, 20);
// Line 1
c.gridheight = 5;
this.keyPad = new NumericKeypadPanel(this.ttcTextField);
this.add(this.keyPad, c);
keyPad = new NumericKeypadPanel(ttcTextField);
this.add(keyPad, c);
 
updatePrice(item.getArticle().getPriceWithoutTax());
updatePrice(article.getPriceWithoutTax());
updateTextFields();
//
final ActionListener listenerRadio = new ActionListener() {
228,11 → 226,11
if (this.rHT.isSelected()) {
r = this.htTextField.getValue();
} else if (this.rTTC.isSelected()) {
r = Article.computePriceWithoutTax(this.ttcTextField.getValue(), this.item.getArticle().getIdTaxe());
r = Article.computePriceWithoutTax(this.ttcTextField.getValue(), this.article.getIdTaxe());
} else if (this.rDiscountPercent.isSelected()) {
r = this.item.getArticle().getPriceWithoutTax().subtract(this.item.getArticle().getPriceWithoutTax().multiply(this.discountPercentTextField.getValue().divide(new BigDecimal(100))));
r = this.article.getPriceWithoutTax().subtract(this.article.getPriceWithoutTax().multiply(this.discountPercentTextField.getValue().divide(new BigDecimal(100))));
} else if (this.rDiscount.isSelected()) {
r = this.item.getArticle().getPriceWithoutTax().subtract(this.discountTextField.getValue());
r = this.article.getPriceWithoutTax().subtract(this.discountTextField.getValue());
}
} catch (Exception e) {
e.printStackTrace();
239,30 → 237,30
}
if (r == null) {
// fallback if something wrong
r = this.item.getArticle().getPriceWithoutTax();
r = this.article.getPriceWithoutTax();
}
return r;
}
 
private void updatePrice(BigDecimal ht) {
BigDecimal ttc = Article.computePriceWithTax(ht, this.item.getArticle().getIdTaxe());
this.labelPrice.setText("Nouveau Prix : " + TicketCellRenderer.toString(ttc) + "€ TTC, " + TicketCellRenderer.toString(ht) + "€ HT");
BigDecimal ttc = Article.computePriceWithTax(ht, this.article.getIdTaxe());
labelPrice.setText("Nouveau Prix : " + TicketCellRenderer.toString(ttc) + "€ TTC, " + TicketCellRenderer.toString(ht) + "€ HT");
}
 
private void updateTextFields() {
this.invalidate();
this.htTextField.setVisible(false);
this.ttcTextField.setVisible(false);
this.discountPercentTextField.setVisible(false);
this.discountTextField.setVisible(false);
if (this.rHT.isSelected()) {
enableTextField(this.htTextField);
} else if (this.rTTC.isSelected()) {
enableTextField(this.ttcTextField);
} else if (this.rDiscountPercent.isSelected()) {
enableTextField(this.discountPercentTextField);
} else if (this.rDiscount.isSelected()) {
enableTextField(this.discountTextField);
htTextField.setVisible(false);
ttcTextField.setVisible(false);
discountPercentTextField.setVisible(false);
discountTextField.setVisible(false);
if (rHT.isSelected()) {
enableTextField(htTextField);
} else if (rTTC.isSelected()) {
enableTextField(ttcTextField);
} else if (rDiscountPercent.isSelected()) {
enableTextField(discountPercentTextField);
} else if (rDiscount.isSelected()) {
enableTextField(discountTextField);
}
this.validate();
repaint();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseControler.java
27,10 → 27,10
import org.openconcerto.erp.core.sales.pos.model.RegisterLogEntry.ReceiptEntry;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.Pair;
import org.openconcerto.utils.StringUtils;
 
import java.awt.event.KeyEvent;
59,7 → 59,7
private Paiement paiementSelected;
private Ticket t;
private Client client = Client.NONE;
private List<CaisseListener> listeners = new ArrayList<>();
private List<CaisseListener> listeners = new ArrayList<CaisseListener>();
 
private final BarcodeReader r;
private Paiement p1 = new Paiement(Paiement.ESPECES);
67,7 → 67,6
private Paiement p3 = new Paiement(Paiement.CHEQUE);
private final CaisseFrame caisseFrame;
private final POSDisplay lcd;
private TicketItem ticketItemSelected;
 
public CaisseControler(CaisseFrame caisseFrame) throws ParseException, JDOMException, IOException {
this.caisseFrame = caisseFrame;
96,9 → 95,9
this.r.start();
this.r.addBarcodeListener(this);
if (posConf.getLCDType().equals("serial")) {
this.lcd = new ESCSerialDisplay(posConf.getLCDPort());
lcd = new ESCSerialDisplay(posConf.getLCDPort());
} else {
this.lcd = new PrinterPOSDisplay(posConf.getLCDPort());
lcd = new PrinterPOSDisplay(posConf.getLCDPort());
}
this.setLCDDefaultDisplay(0);
}
120,7 → 119,7
}
 
void setArticleSelected(Article a) {
if (a != this.articleSelected) {
if (a != articleSelected) {
this.articleSelected = a;
this.paiementSelected = null;
fire();
130,7 → 129,6
void setPaiementSelected(Paiement p) {
this.paiementSelected = p;
this.articleSelected = null;
this.ticketItemSelected = null;
fire();
}
 
161,13 → 159,9
}
 
public Client getClient() {
return this.client;
return client;
}
 
public void setCodePostal(String codePostal) {
this.t.setCodePostal(codePostal);
}
 
// Articles
public void addArticle(Article a) {
this.t.addArticle(a);
231,20 → 225,20
 
//
 
public List<TicketItem> getItems() {
return this.t.getItems();
public List<Pair<Article, Integer>> getItems() {
return this.t.getArticles();
}
 
public BigDecimal getItemCount(Article article) {
public int getItemCount(Article article) {
return this.t.getItemCount(article);
}
 
public void clearArticle(Article article) {
this.t.clearArticle(article);
this.setTicketItemSelected(null);
this.setArticleSelected(null);
}
 
public void setArticleCount(Article article, BigDecimal count) {
public void setArticleCount(Article article, int count) {
this.t.setArticleCount(article, count);
this.setArticleSelected(null);
}
264,10 → 258,15
} else if (code.equalsIgnoreCase("annuler")) {
if (this.articleSelected != null) {
this.clearArticle(this.articleSelected);
} else if (this.paiementSelected != null) {
 
} else {
if (this.paiementSelected != null) {
this.paiementSelected.setMontantInCents(0);
// setPaiementSelected(null);
fire();
}
 
}
} else if (code.equalsIgnoreCase("valider")) {
 
} else if (code.equalsIgnoreCase("facture")) {
285,7 → 284,7
Ticket t = Ticket.getTicketFromCode(code, this.caisseFrame.getFiles());
if (t != null) {
System.err.println("CaisseControler.barcodeRead() barcode : " + code + " : receipt found :" + t.getNumber());
this.caisseFrame.showTickets(t);
caisseFrame.showTickets(t);
}
}
}
326,7 → 325,7
 
@Override
public void keyReceived(KeyEvent ee) {
// nothing
 
}
 
public static String getCents(int cents) {
338,7 → 337,9
}
 
public static String getEuros(int cents) {
return String.valueOf(cents / 100);
String s = String.valueOf(cents / 100);
 
return s;
}
 
public Ticket saveAndClearTicket(final RegisterFiles files, final SQLElementDirectory dir) throws IOException, SQLException {
348,16 → 349,16
final String fileHash = this.t.save(files, dir);
final Ticket res = this.t;
final int newIndex = this.t.getNumber() + 1;
this.t = new Ticket(getPOSConf().getPosID(), newIndex, fileHash);
this.p1 = new Paiement(Paiement.ESPECES);
this.p2 = new Paiement(Paiement.CB);
this.p3 = new Paiement(Paiement.CHEQUE);
t = new Ticket(getPOSConf().getPosID(), newIndex, fileHash);
p1 = new Paiement(Paiement.ESPECES);
p2 = new Paiement(Paiement.CB);
p3 = new Paiement(Paiement.CHEQUE);
this.t.addPaiement(this.p1);
this.t.addPaiement(this.p2);
this.t.addPaiement(this.p3);
this.setPaiementSelected(null);
this.setArticleSelected(null);
this.client = Client.NONE;
client = Client.NONE;
return res;
}
 
376,7 → 377,7
}
 
public void switchListMode() {
this.caisseFrame.mainPanel.switchListMode();
caisseFrame.mainPanel.switchListMode();
 
}
 
385,7 → 386,7
@Override
public void run() {
try {
CaisseControler.this.lcd.setMessage(line1, line2);
lcd.setMessage(line1, line2);
} catch (Exception e) {
e.printStackTrace();
}
392,22 → 393,17
}
};
final Timer timer = new Timer("LCD : " + line1, true);
timer.schedule(task, delay * 1000L);
timer.schedule(task, delay * 1000);
 
}
 
public void setLCDDefaultDisplay(int delay) {
if (this.t.getTotalInCents() > 0) {
if (t.getTotalInCents() > 0) {
int count = 0;
final List<TicketItem> articles = this.t.getItems();
for (TicketItem pair : articles) {
Article a = pair.getArticle();
if (a.getSalesUnit() == null) {
count += pair.getQty().intValue();
} else {
count++;
final List<Pair<Article, Integer>> articles = t.getArticles();
for (Pair<Article, Integer> pair : articles) {
count += pair.getSecond();
}
}
String line1;
if (count == 1) {
line1 = "1 article";
414,7 → 410,7
} else {
line1 = count + " articles";
}
int cents = this.t.getTotalInCents();
int cents = t.getTotalInCents();
setLCD(line1, "Total : " + TicketCellRenderer.centsToString(cents), delay);
} else {
setLCD(getPOSConf().getLCDLine1(), getPOSConf().getLCDLine2(), delay);
425,7 → 421,7
 
final String creditCardPort = getPOSConf().getCreditCardPort();
if (creditCardPort != null && creditCardPort.trim().length() > 2) {
final Thread thread = new Thread(new Runnable() {
final Thread t = new Thread(new Runnable() {
 
@Override
public void run() {
442,22 → 438,33
}
}
});
thread.setDaemon(true);
thread.start();
t.setDaemon(true);
t.start();
 
}
 
}
 
public void setArticleHT(TicketItem item, BigDecimal ht) {
final Article newArticle = new Article(item.getArticle());
newArticle.updatePriceWithoutTax(ht);
item.setArticle(newArticle);
public void setArticleHT(Article article, BigDecimal ht) {
Article existingArticle = null;
final List<Pair<Article, Integer>> articles = t.getArticles();
for (Pair<Article, Integer> pair : articles) {
final Article a = pair.getFirst();
if (a.getId() == article.getId()) {
if (article.getPriceWithoutTax().doubleValue() == a.getPriceWithoutTax().doubleValue()) {
existingArticle = a;
break;
}
}
}
if (existingArticle != null) {
existingArticle.updatePriceWithoutTax(ht);
fire();
}
}
 
public void openPriceEditor(TicketItem item) {
this.caisseFrame.showPriceEditor(item, this);
public void openPriceEditor(Article article) {
caisseFrame.showPriceEditor(article, this);
}
 
public void enableBarcodeReader() {
469,7 → 476,7
}
 
public boolean isTicketValid() {
return (!this.t.getItems().isEmpty()) && ((this.getTotal() >= 0 && this.getPaidTotal() >= this.getTotal()) || (this.getTotal() < 0 && this.getPaidTotal() == this.getTotal()));
return (!this.t.getArticles().isEmpty()) && ((this.getTotal() >= 0 && this.getPaidTotal() >= this.getTotal()) || (this.getTotal() < 0 && this.getPaidTotal() == this.getTotal()));
}
 
public Set<Integer> loadFavoriteProductsIds() {
508,43 → 515,4
}
}
 
public void setTicketItemSelected(TicketItem item) {
this.ticketItemSelected = item;
if (item == null) {
this.articleSelected = null;
} else {
this.articleSelected = item.getArticle();
this.paiementSelected = null;
}
fire();
 
}
 
public TicketItem getTicketItemSelected() {
return this.ticketItemSelected;
}
 
public void removeTicketItem(TicketItem item) {
this.t.removeTicketItem(item);
this.setTicketItemSelected(null);
}
 
public void cancel(Ticket ticket) {
this.t.clear();
// Annulation du ticket
for (TicketItem a : ticket.getItems()) {
final Article article = a.getArticle();
TicketItem item = new TicketItem(article, a.getQty().multiply(new BigDecimal(-1)));
this.t.addItem(item);
}
for (Paiement p : ticket.getPaiements()) {
final Paiement paiement = new Paiement(p.getType());
paiement.setMontantInCents(-1 * p.getMontantInCents());
this.t.addPaiement(paiement);
}
 
this.caisseFrame.showCaisse();
fire();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/RegisterSummary.java
23,7 → 23,6
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
57,7 → 56,7
 
public abstract String getLabel();
 
protected abstract List<Ticket> getReceipts() throws ParseException, IOException;
protected abstract List<Ticket> getReceipts() throws ParseException;
 
@Override
public void print(TicketPrinter prt, int ticketWidth) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketPanel.java
17,8 → 17,8
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.Pair;
 
import java.awt.Color;
import java.awt.Dimension;
45,27 → 45,27
 
public class TicketPanel extends JPanel implements CaisseListener {
 
private final DateFormat df = new SimpleDateFormat("' le' d MMMM à H:mm");
static private final DateFormat DF = new SimpleDateFormat("' le' EEEE d MMMM à H:mm:ss");
 
private final Image bg;
private final ListModel<TicketItem> dataModel;
private final List<ListDataListener> listeners = new ArrayList<>();
private final JLabel lTotal = new JLabel("", SwingConstants.RIGHT);
private final JLabel lNumero = new JLabel("", SwingConstants.LEFT);
 
private final ListModel dataModel;
private final List<ListDataListener> listeners = new ArrayList<ListDataListener>();
JLabel lTotal = new JLabel("", SwingConstants.RIGHT);
JLabel lNumero = new JLabel("", SwingConstants.LEFT);
private final CaisseControler controler;
 
private final ScrollableList list;
private int xOffset = 0;
 
TicketPanel(final CaisseControler controler) {
this.controler = controler;
this.controler.addCaisseListener(this);
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
this.xOffset = -24;
}
 
this.setOpaque(false);
this.bg = new ImageIcon(TicketPanel.class.getResource("ticket.png")).getImage();
this.setLayout(null);
 
this.dataModel = new ListModel<TicketItem>() {
this.dataModel = new ListModel() {
 
@Override
public void addListDataListener(final ListDataListener l) {
73,7 → 73,7
}
 
@Override
public TicketItem getElementAt(final int index) {
public Object getElementAt(final int index) {
return controler.getItems().get(index);
}
 
95,22 → 95,22
@Override
public void paintCell(final Graphics g, final Object value, final int index, final boolean isSelected, final int posY) {
g.translate(0, posY);
this.renderer.paint(g, TicketPanel.this.list, (TicketItem) value, index, isSelected);
this.renderer.paint(g, TicketPanel.this.list, value, index, isSelected);
g.translate(0, -posY);
}
};
this.list.setOpaque(false);
this.list.setSize(315, 450);
this.list.setSize(276, 450);
this.list.setFixedCellHeight(40);
this.list.setLocation(30 + this.xOffset, 18);
this.list.setLocation(68, 18);
this.add(this.list);
 
this.lTotal.setSize(276 - 10, 32);
this.lTotal.setLocation(68 + this.xOffset, 500 - 32);
this.lTotal.setLocation(68, 500 - 32);
this.lTotal.setFont(new Font("Arial", Font.BOLD, 18));
this.add(this.lTotal);
this.lNumero.setSize(276 - 10, 32);
this.lNumero.setLocation(68 + this.xOffset, 500);
this.lNumero.setLocation(68, 500);
this.lNumero.setForeground(Color.DARK_GRAY);
this.lNumero.setFont(new Font("Arial", Font.BOLD, 12));
this.add(this.lNumero);
122,13 → 122,12
if (!e.getValueIsAdjusting()) {
final Object selectedValue = TicketPanel.this.list.getSelectedValue();
if (selectedValue != null) {
TicketItem item = (TicketItem) selectedValue;
controler.setTicketItemSelected(item);
final Article a = ((Pair<Article, Integer>) selectedValue).getFirst();
controler.setArticleSelected(a);
// If the category of the selected article does not match the current
// category of the categories list,
// then the corresponding article is not selected.
controler.setTicketItemSelected(item); // Dirty fix : use two refresh
 
controler.setArticleSelected(a); // Dirty fix : use two refresh
}
}
 
139,28 → 138,19
 
@Override
protected void paintComponent(final Graphics g) {
g.drawImage(this.bg, this.xOffset, 0, null);
g.drawImage(this.bg, 0, 0, null);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
try {
final RegisterState registerState = this.controler.getCaisseFrame().getFiles().getLastLog().getRegisterState();
 
// Display caisse and Vendor ID
final String infoCaisseVendeur = "Caisse " + this.controler.getPOSConf().getPosID() + " Vendeur " + this.controler.getPOSConf().getUserID();
final String infoCaisse = (registerState.getStatus() == Status.OPEN ? "Ouverte" : "Fermée") + registerState.formatDate(this.df);
String InfoCaisseVendeur = "Caisse " + this.controler.getPOSConf().getPosID() + " Vendeur " + this.controler.getPOSConf().getUserID();
g.setColor(new Color(230, 230, 230));
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
g.setFont(getFont().deriveFont(16.0f));
} else {
g.setFont(getFont().deriveFont(14.0f));
}
int w1 = g.getFontMetrics().stringWidth(infoCaisseVendeur);
int w2 = g.getFontMetrics().stringWidth(infoCaisse);
g.setFont(getFont().deriveFont(28.0f));
g.drawString(InfoCaisseVendeur, 20, this.getHeight() - 50);
 
int x = 330 - Math.max(w1, w2) + this.xOffset;
g.drawString(infoCaisseVendeur, x, this.getHeight() - 40);
g.setColor(Color.LIGHT_GRAY);
 
g.drawString(infoCaisse, x, this.getHeight() - 25);
g.setFont(getFont().deriveFont(18.0f));
final RegisterState registerState = this.controler.getCaisseFrame().getFiles().getLastLog().getRegisterState();
g.drawString("Caisse " + (registerState.getStatus() == Status.OPEN ? "ouverte" : "fermée") + registerState.formatDate(DF), 20, this.getHeight() - 25);
} catch (Exception e) {
POSConfiguration.getLogger().log(Level.WARNING, "Couldn't find register state", e);
}
167,28 → 157,14
super.paintComponent(g);
}
 
int getMinWidth() {
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
return 330;
}
return 480;
}
 
int getMaxHeight() {
if (this.controler.getPOSConf().getScreenHeight() < 1000) {
return 550;
}
return 707;
}
 
@Override
public Dimension getMinimumSize() {
return new Dimension(getMinWidth(), 550);
return new Dimension(480, 550);
}
 
@Override
public Dimension getPreferredSize() {
return new Dimension(getMinWidth(), getMaxHeight());
return new Dimension(480, 707);
}
 
public void fire() {
213,7 → 189,7
}
try {
// Deja selectionné
if (this.list.getSelectedValue() != null && articleSelected.equals(((TicketItem) this.list.getSelectedValue()).getArticle())) {
if (this.list.getSelectedValue() != null && articleSelected != null && articleSelected.equals(((Pair<Article, Integer>) this.list.getSelectedValue()).getFirst())) {
return;
}
} catch (final Exception e) {
220,14 → 196,16
e.printStackTrace();
}
 
if (articleSelected != null) {
 
for (int i = 0; i < this.dataModel.getSize(); i++) {
final TicketItem item = this.dataModel.getElementAt(i);
if (item.getArticle().equals(articleSelected)) {
final Pair<Article, Integer> item = (Pair<Article, Integer>) this.dataModel.getElementAt(i);
if (item.getFirst().equals(articleSelected)) {
this.list.setSelectedValue(item, true);
break;
}
}
 
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketCellRenderer.java
14,8 → 14,8
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.Pair;
 
import java.awt.Color;
import java.awt.Component;
35,11 → 35,12
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
 
public class TicketCellRenderer implements ListCellRenderer<TicketItem> {
public class TicketCellRenderer implements ListCellRenderer {
 
@Override
public Component getListCellRendererComponent(JList<? extends TicketItem> list, TicketItem item, int index, boolean isSelected, boolean cellHasFocus) {
 
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
@SuppressWarnings("unchecked")
Pair<Article, Integer> item = (Pair<Article, Integer>) value;
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
47,12 → 48,12
 
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 5, 5, 5);
final JLabel l1 = new JLabel(item.getArticle().toString(), SwingConstants.RIGHT);
final JLabel l1 = new JLabel(item.getSecond().toString(), SwingConstants.RIGHT);
 
p.add(l1, c);
c.gridx++;
c.weightx = 1;
Article article = item.getArticle();
Article article = item.getFirst();
final JLabel l2 = new JLabel(article.getName().toUpperCase(), SwingConstants.LEFT);
p.add(l2, c);
c.gridx++;
81,7 → 82,9
return p;
}
 
public void paint(Graphics g, ScrollableList list, TicketItem item, int index, boolean isSelected) {
public void paint(Graphics g, ScrollableList list, Object value, int index, boolean isSelected) {
@SuppressWarnings("unchecked")
final Pair<Article, Integer> item = (Pair<Article, Integer>) value;
 
if (isSelected) {
g.setColor(new Color(232, 242, 254));
94,34 → 97,20
g.setFont(new Font("Arial", Font.PLAIN, 16));
final int height = g.getFontMetrics().getMaxAscent() + g.getFontMetrics().getMaxDescent() + inset;
 
System.err.println("TicketCellRenderer.paint()" + item);
 
Article article = item.getArticle();
final BigDecimal qty = item.getQty();
String s1 = qty.toString();
if (article.getSalesUnit() != null) {
s1 = qty.toString() + article.getSalesUnit();
}
final String s1 = item.getSecond().toString();
g.drawString(s1, inset, height);
final int width1 = (int) g.getFontMetrics().getStringBounds("1999kg ", g).getWidth() + inset * 2;
final int width1 = (int) g.getFontMetrics().getStringBounds("999 ", g).getWidth() + inset * 2;
 
String s2 = article.getName().toUpperCase().trim();
 
final int maxLength = 15;
Article article = item.getFirst();
String s2 = article.getName().toUpperCase();
final int maxLength = 13;
if (s2.length() > maxLength)
s2 = s2.substring(0, maxLength + 1) + '…';
g.drawString(s2, width1 + inset, height);
 
final String s3 = centsToString(article.getPriceWithTax().multiply(qty).movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue()) + "€";
final int width3 = (int) g.getFontMetrics().getStringBounds(s3, g).getWidth() + +inset;
g.drawString(s3, list.getWidth() - width3, height - 4);
 
g.setFont(g.getFont().deriveFont(12f));
final String s4 = qty.toPlainString() + " x " + centsToString(article.getPriceWithTax().movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue());
 
final int width4 = (int) g.getFontMetrics().getStringBounds(s4, g).getWidth() + +inset;
g.drawString(s4, list.getWidth() - width4, height + 11);
 
final String s3 = centsToString(article.getPriceWithTax().movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue());
final int width3 = (int) g.getFontMetrics().getStringBounds(s3, g).getWidth() + inset * 2;
g.drawString(s3, list.getWidth() - width3, height);
}
 
public static String centsToString(int cents) {
136,5 → 125,4
public static String toString(final BigDecimal p) {
return centsToString(p.movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PaiementPanel.java
15,7 → 15,6
 
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
 
import java.awt.Color;
import java.awt.Dimension;
27,7 → 26,6
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
import java.math.BigDecimal;
import java.util.List;
 
import javax.swing.JOptionPane;
68,16 → 66,14
 
@Override
public void paint(Graphics g) {
 
Graphics2D g2 = (Graphics2D) g;
g.setColor(new Color(250, 250, 250));
g.fillRect(0, 0, this.getWidth(), this.getHeight());
 
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.LIGHT_GRAY);
g.drawLine(0, 0, 0, this.getHeight());
int y = PAYMENT_POS_Y;
for (Paiement p : this.controller.getPaiements()) {
for (Paiement p : controller.getPaiements()) {
if (p.getType() == Paiement.CB) {
drawMontant(g, "CB", p, 242 - 15, y, true);
} else if (p.getType() == Paiement.CHEQUE) {
113,7 → 109,6
 
drawCalculator(g);
super.paint(g);
 
}
 
private void drawKey(Graphics2D g2, String string, int col, int row, int w, int h, Color color) {
142,7 → 137,7
Graphics2D g2 = (Graphics2D) g;
 
// LCD
if (this.controller.getArticleSelected() != null || this.controller.getPaiementSelected() != null) {
if (controller.getArticleSelected() != null || controller.getPaiementSelected() != null) {
g.setColor(new Color(232, 242, 254));
} else {
g.setColor(new Color(240, 240, 240));
152,10 → 147,10
int y = this.getHeight() - this.calcHeight - 10;
g.setFont(new Font("Arial", Font.PLAIN, 32));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
final Article article = this.controller.getArticleSelected();
final Article article = controller.getArticleSelected();
g.setColor(Color.DARK_GRAY);
if (article != null) {
String string = this.calculatorValue;
String string = calculatorValue;
g.setFont(g.getFont().deriveFont(52f));
Rectangle2D r1 = g.getFontMetrics().getStringBounds(string, g2);
g.drawString(string, (int) (260 - r1.getWidth()), y);
163,9 → 158,9
g.drawString("Quantité", 10, 460 + y);
 
} else {
final Paiement paiement = this.controller.getPaiementSelected();
final Paiement paiement = controller.getPaiementSelected();
if (paiement != null) {
String string = this.calculatorValue;
String string = calculatorValue;
g.setFont(g.getFont().deriveFont(52f));
Rectangle2D r1 = g.getFontMetrics().getStringBounds(string, g2);
g.drawString(string, (int) (260 - r1.getWidth()), y);
184,7 → 179,7
}
}
g.setFont(g.getFont().deriveFont(14f));
g.drawString("" + this.mode, 10, y - 20);
g.drawString("" + mode, 10, y - 20);
}
 
private char getToucheFrom(int x, int y) {
304,23 → 299,23
 
@Override
public Dimension getPreferredSize() {
return new Dimension(this.calcWidth, 768);
return new Dimension(calcWidth, 768);
}
 
public Dimension getMinimumSize() {
return new Dimension(this.calcWidth, 768);
return new Dimension(calcWidth, 768);
}
 
@Override
public void caisseStateChanged() {
if (this.controller.getArticleSelected() != null) {
if (controller.getArticleSelected() != null) {
initCaisseArticle();
} else if (this.controller.getPaiementSelected() != null) {
} else if (controller.getPaiementSelected() != null) {
initCaissePaiement();
}
// Add / Remove solde if needed
boolean soldeIsShown = false;
for (Paiement p : this.controller.getPaiements()) {
for (Paiement p : controller.getPaiements()) {
if (p.getType() == Paiement.SOLDE) {
soldeIsShown = true;
break;
327,19 → 322,19
}
}
 
if (this.controller.isClientDefined()) {
if (!soldeIsShown && this.controller.getClient().getSolde().signum() == 1) {
if (controller.isClientDefined()) {
if (!soldeIsShown && controller.getClient().getSolde().signum() == 1) {
// add
this.controller.addPaiement(new Paiement(Paiement.SOLDE));
controller.addPaiement(new Paiement(Paiement.SOLDE));
}
} else {
if (soldeIsShown) {
// remove
final List<Paiement> paiements = this.controller.getPaiements();
final List<Paiement> paiements = controller.getPaiements();
for (int i = 0; i < paiements.size(); i++) {
final Paiement p = paiements.get(i);
if (p.getType() == Paiement.SOLDE) {
this.controller.getPaiements().remove(i);
controller.getPaiements().remove(i);
break;
}
}
350,19 → 345,15
}
 
private void initCaisseArticle() {
if (this.controller.getTicketItemSelected() != null) {
this.calculatorValue = this.controller.getTicketItemSelected().getQty().toPlainString();
} else {
this.calculatorValue = "";
calculatorValue = String.valueOf(controller.getItemCount(controller.getArticleSelected()));
init = true;
mode = ' ';
}
this.init = true;
this.mode = ' ';
}
 
private void initCaissePaiement() {
this.calculatorValue = TicketCellRenderer.centsToString(this.controller.getPaiementSelected().getMontantInCents());
this.init = true;
this.mode = ' ';
calculatorValue = TicketCellRenderer.centsToString(controller.getPaiementSelected().getMontantInCents());
init = true;
mode = ' ';
}
 
@Override
393,32 → 384,32
} else {
Paiement p = getPaiementFrom(e.getY());
if (p != null) {
if (e.getX() > this.getWidth() - 68 && p.getType() != Paiement.ESPECES && this.controller.canAddPaiement(p.getType())) {
if (e.getX() > this.getWidth() - 68 && p.getType() != Paiement.ESPECES && controller.canAddPaiement(p.getType())) {
p = new Paiement(p.getType());
this.controller.addPaiement(p);
controller.addPaiement(p);
}
this.controller.autoFillPaiement(p);
controller.autoFillPaiement(p);
this.calculatorValue = TicketCellRenderer.centsToString(p.getMontantInCents());
if (p.getType() == Paiement.ESPECES) {
try {
this.controller.openDrawer();
controller.openDrawer();
} catch (Throwable ex) {
JOptionPane.showMessageDialog(PaiementPanel.this, "Ouverture du tiroir caisse impossible");
}
} else if (p.getType() == Paiement.CB) {
this.controller.sendCBRequest(p);
controller.sendCBRequest(p);
}
 
}
this.controller.setPaiementSelected(p);
controller.setPaiementSelected(p);
}
}
 
public void lcdPressed() {
System.err.println("PaiementPanel.lcdPressed()");
final TicketItem articleSelected = this.controller.getTicketItemSelected();
final Article articleSelected = controller.getArticleSelected();
if (articleSelected != null) {
this.controller.openPriceEditor(articleSelected);
controller.openPriceEditor(articleSelected);
}
repaint();
 
428,10 → 419,10
System.out.println("Handle: " + c);
if (c == '?')
return;
final TicketItem article = this.controller.getTicketItemSelected();
final Article article = controller.getArticleSelected();
 
if (c == '+' || c == '-' || c == '*') {
this.mode = c;
mode = c;
 
repaint();
return;
441,71 → 432,66
// Changement de quantité
if (c == 'c' || c == '/') {
System.out.println("Clear quantité");
this.mode = ' ';
this.controller.removeTicketItem(article);
mode = ' ';
controller.clearArticle(article);
} else if (c == '=' || c == '\n') {
if (!this.init) {
BigDecimal v = new BigDecimal(this.calculatorValue);
if (this.mode == ' ') {
article.setQty(v);
} else if (this.mode == '+') {
article.setQty(article.getQty().add(v));
} else if (this.mode == '-') {
article.setQty(article.getQty().subtract(v));
} else if (this.mode == '*') {
article.setQty(article.getQty().multiply(v));
if (!init) {
int v = Integer.parseInt(calculatorValue);
if (mode == ' ') {
controller.setArticleCount(article, v);
} else if (mode == '+') {
controller.setArticleCount(article, controller.getItemCount(article) + v);
} else if (mode == '-') {
controller.setArticleCount(article, controller.getItemCount(article) - v);
} else if (mode == '*') {
controller.setArticleCount(article, controller.getItemCount(article) * v);
}
// Reselect to fire a refresh
this.controller.setTicketItemSelected(article);
}
initCaisseArticle();
} else if (Character.isDigit(c)) {
if (this.init) {
this.calculatorValue = "";
this.init = false;
if (init) {
calculatorValue = "";
init = false;
}
if (this.calculatorValue.length() < 8) {
this.calculatorValue += c;
if (calculatorValue.length() < 8) {
calculatorValue += c;
}
}
if (article.getArticle().getSalesUnit() != null && c == '.' && (this.calculatorValue.indexOf('.') < 0)) {
this.calculatorValue += ".";
}
 
} else {
final Paiement paiement = this.controller.getPaiementSelected();
final Paiement paiement = controller.getPaiementSelected();
if (paiement != null) {
// Changement de paiement
if (c == 'c' || c == '/') {
System.out.println("Clear paiement");
this.mode = ' ';
this.controller.clearPaiement(paiement);
} else if (c == '.' && (this.calculatorValue.indexOf('.') < 0)) {
this.calculatorValue += ".";
mode = ' ';
controller.clearPaiement(paiement);
} else if (c == '.' && (calculatorValue.indexOf('.') < 0)) {
calculatorValue += ".";
} else if (c == '=' || c == '\n') {
if (!this.init) {
if (!init) {
int v = getCentsFrom(this.calculatorValue);
if (this.mode == ' ') {
this.controller.setPaiementValue(paiement, v);
} else if (this.mode == '+') {
this.controller.setPaiementValue(paiement, paiement.getMontantInCents() + v);
} else if (this.mode == '-') {
this.controller.setPaiementValue(paiement, paiement.getMontantInCents() - v);
} else if (this.mode == '*') {
this.controller.setPaiementValue(paiement, paiement.getMontantInCents() * v);
if (mode == ' ') {
controller.setPaiementValue(paiement, v);
} else if (mode == '+') {
controller.setPaiementValue(paiement, paiement.getMontantInCents() + v);
} else if (mode == '-') {
controller.setPaiementValue(paiement, paiement.getMontantInCents() - v);
} else if (mode == '*') {
controller.setPaiementValue(paiement, paiement.getMontantInCents() * v);
}
}
initCaissePaiement();
this.controller.setPaiementSelected(null);
controller.setPaiementSelected(null);
} else if (Character.isDigit(c)) {
if (this.init) {
this.calculatorValue = "";
this.init = false;
if (init) {
calculatorValue = "";
init = false;
}
if (this.calculatorValue.length() < 9) {
int i = this.calculatorValue.indexOf('.');
if (i < 0 || (this.calculatorValue.length() - i < 3)) {
this.calculatorValue += c;
if (calculatorValue.length() < 9) {
int i = calculatorValue.indexOf('.');
if (i < 0 || (calculatorValue.length() - i < 3)) {
calculatorValue += c;
}
}
}
548,8 → 534,8
 
private Paiement getPaiementFrom(int y) {
int index = (y - PAYMENT_POS_Y) / PAYMENT_LINE_HEIGHT;
if (index < this.controller.getPaiements().size() && index >= 0) {
return this.controller.getPaiements().get(index);
if (index < controller.getPaiements().size() && index >= 0) {
return controller.getPaiements().get(index);
}
return null;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseFrame.java
16,6 → 16,7
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Client;
import org.openconcerto.erp.core.sales.pos.model.DBState;
import org.openconcerto.erp.core.sales.pos.model.ReceiptCode;
25,7 → 26,6
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.RemoteShell;
225,6 → 225,11
public void run() {
 
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
try {
CaisseFrame f = new CaisseFrame(posConf, conf, registerFiles, registerDB);
f.setUndecorated(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
243,9 → 248,9
}
System.out.println("Affichage de l'interface");
f.setVisible(true);
if (screenSize.getWidth() < 1024 || screenSize.getHeight() < 720) {
if (screenSize.getWidth() < 1280 || screenSize.getHeight() < 720) {
JOptionPane.showMessageDialog(f,
"La résolution de votre écran est trop faible.\nLa largeur doit être au minium de 1024 pixels.\nLa hauteur doit être au minium de 720 pixels.");
"La résolution de votre écran est trop faible.\nLa largeur doit être au minium de 1280 pixels.\nLa hauteur doit être au minium de 720 pixels.");
}
} catch (Throwable e) {
// Catch throwable to be able to see NoClassDefFound and other hard issues
510,11 → 515,11
this.repaint();
}
 
public void showPriceEditor(TicketItem item, CaisseControler caisseControler) {
public void showPriceEditor(Article article, CaisseControler caisseControler) {
getControler().disableBarcodeReader();
System.out.println("CaisseFrame.showPriceEditor()");
this.invalidate();
final PriceEditorPanel panel = new PriceEditorPanel(this, item);
final PriceEditorPanel panel = new PriceEditorPanel(this, article);
 
final POSGlassPane glassPane2 = new POSGlassPane(panel, (getWidth() - panel.getPreferredSize().width) / 2, 100) {
@Override
580,16 → 585,4
this.validate();
this.repaint();
}
 
public void showPostalCodeFrame(CaissePanel caissePanel) {
System.out.println("CaisseFrame.showPostalCodeFrame()");
this.invalidate();
final PostalCodeEditorPanel panel = new PostalCodeEditorPanel(this, caissePanel);
final POSGlassPane glassPane2 = new POSGlassPane(panel, (getWidth() - panel.getPreferredSize().width) / 2, 100);
this.setGlassPane(glassPane2);
this.getGlassPane().setVisible(true);
this.validate();
this.repaint();
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ListeDesTicketsPanel.java
16,6 → 16,7
import org.openconcerto.erp.core.sales.pos.TicketPrinterConfiguration;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
22,6 → 23,7
import org.openconcerto.ui.DefaultListModel;
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Pair;
 
import java.awt.Color;
import java.awt.Component;
109,7 → 111,7
}
 
@Override
protected final List<Ticket> getReceipts() throws ParseException, IOException {
protected final List<Ticket> getReceipts() throws ParseException {
return this.getLog().parseReceipts();
}
 
158,22 → 160,22
try {
final RegisterLog lastLog = this.frame.getFiles().getLastLog();
final List<Ticket> receipts = lastLog.parseReceipts();
this.ticketLlistModel = new DefaultListModel();
this.ticketLlistModel.addElement(new X(lastLog, receipts));
this.ticketLlistModel.addElement(new XLite(lastLog, receipts));
ticketLlistModel = new DefaultListModel();
ticketLlistModel.addElement(new X(lastLog, receipts));
ticketLlistModel.addElement(new XLite(lastLog, receipts));
final Date previousDate = lastLog.getFirstRegisterEvent().getPreviousDate();
if (previousDate != null) {
final Calendar cal = Calendar.getInstance();
cal.setTime(previousDate);
this.ticketLlistModel.addElement(new Z(this.frame.getFiles(), cal));
ticketLlistModel.addElement(new Z(this.frame.getFiles(), cal));
}
this.ticketLlistModel.addAll(receipts);
ticketLlistModel.addAll(receipts);
 
} catch (Exception exn) {
ExceptionHandler.handle(this.frame, "Impossible de charger les tickets", exn);
}
final Font f = new Font(ARIAL_FONT, Font.PLAIN, 24);
this.ticketList = new ScrollableList(this.ticketLlistModel) {
ticketList = new ScrollableList(ticketLlistModel) {
@Override
public void paintCell(Graphics g, Object object, int index, boolean isSelected, int posY) {
g.setFont(f);
209,25 → 211,24
}
}
};
this.add(this.ticketList, c);
this.add(ticketList, c);
// Ticket
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0;
c.gridx++;
c.gridheight = 1;
c.insets = new Insets(10, 10, 10, 10);
this.ticketP = new TextAreaTicketPrinter();
ticketP = new TextAreaTicketPrinter();
 
JScrollPane scrollPane = new JScrollPane(this.ticketP);
JScrollPane scrollPane = new JScrollPane(ticketP);
scrollPane.setPreferredSize(new Dimension(400, 200));
scrollPane.setMinimumSize(new Dimension(400, 200));
this.add(scrollPane, c);
 
this.ticketList.addListSelectionListener(new ListSelectionListener() {
ticketList.addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
Object selectedValue = ListeDesTicketsPanel.this.ticketList.getSelectedValue();
Object selectedValue = ticketList.getSelectedValue();
setSelectedTicket(selectedValue);
}
});
238,8 → 239,8
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
final Font font = new Font(ARIAL_FONT, Font.PLAIN, 46);
this.l = new JList(new String[] { "Imprimer", "Annuler le ticket" });
this.l.setCellRenderer(new ListCellRenderer() {
l = new JList(new String[] { "Imprimer", "Annuler" });
l.setCellRenderer(new ListCellRenderer() {
 
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
258,11 → 259,11
}
 
});
this.l.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.l.getSelectionModel().addListSelectionListener(this);
l.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
l.getSelectionModel().addListSelectionListener(this);
 
this.l.setFixedCellHeight(100);
this.add(this.l, c);
l.setFixedCellHeight(160);
this.add(l, c);
 
setFont(new Font(ARIAL_FONT, Font.BOLD, 24));
 
271,7 → 272,7
 
@Override
public void actionPerformed(ActionEvent e) {
ListeDesTicketsPanel.this.frame.showCaisse();
frame.showCaisse();
 
}
});
283,25 → 284,30
if (e.getValueIsAdjusting()) {
return;
}
Object selectedValue = this.ticketList.getSelectedValue();
int selectedIndex = this.l.getSelectedIndex();
Object selectedValue = ticketList.getSelectedValue();
int selectedIndex = l.getSelectedIndex();
if (selectedIndex == 0 && selectedValue != null) {
this.frame.getPOSConf().printOnceOnFirstPrinter(((Printable) selectedValue));
} else if (selectedIndex == 1 && selectedValue != null && selectedValue instanceof Ticket) {
} else if (selectedIndex == 1 && selectedValue != null) {
// Annulation du ticket
Ticket t = (Ticket) selectedValue;
this.frame.getControler().cancel(t);
 
for (Pair<Article, Integer> a : t.getArticles()) {
frame.getControler().addArticle(a.getFirst());
frame.getControler().setArticleCount(a.getFirst(), -a.getSecond());
frame.getControler().setArticleHT(a.getFirst(), a.getFirst().getPriceWithoutTax());
}
this.l.clearSelection();
frame.showCaisse();
}
l.clearSelection();
}
 
public void setSelectedTicket(Object selectedValue) {
this.ticketP.clear();
ticketP.clear();
if (selectedValue != null) {
this.frame.getPOSConf().print(((Printable) selectedValue), new TicketPrinterConfiguration() {
@Override
public TicketPrinter createTicketPrinter() {
return ListeDesTicketsPanel.this.ticketP;
return ticketP;
}
 
@Override
315,11 → 321,11
}
});
try {
this.ticketP.printBuffer();
ticketP.printBuffer();
} catch (Exception e1) {
e1.printStackTrace();
}
}
this.ticketList.setSelectedValue(selectedValue, true);
ticketList.setSelectedValue(selectedValue, true);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSelector.java
36,7 → 36,7
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
public class ArticleSelector extends JPanel implements CaisseListener {
public class ArticleSelector extends JPanel implements ListSelectionListener, CaisseListener {
private ArticleModel model;
private ScrollableList list;
private StatusBar comp;
52,34 → 52,28
c.gridy = 0;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
this.comp = new StatusBar();
this.comp.setLayout(new FlowLayout(FlowLayout.LEFT));
this.comp.setTitle("Articles");
comp = new StatusBar();
comp.setLayout(new FlowLayout(FlowLayout.LEFT));
comp.setTitle("Articles");
final POSButton bSwitch = new POSButton("-");
bSwitch.setForeground(Color.WHITE);
bSwitch.setBackground(CaissePanel.DARK_BLUE);
this.comp.add(bSwitch);
this.add(this.comp, c);
comp.add(bSwitch);
this.add(comp, c);
 
c.weighty = 1;
c.gridy++;
this.model = new ArticleModel();
this.model.setCategorie(null);
model = new ArticleModel();
model.setCategorie(null);
 
final Font f;
if (controller.getPOSConf().getScreenWidth() < 1280) {
f = new Font("Arial", Font.PLAIN, 18);
} else {
f = new Font("Arial", Font.PLAIN, 21);
}
 
this.list = new ScrollableList(this.model) {
final Font f = new Font("Arial", Font.PLAIN, 21);
list = new ScrollableList(model) {
int maxStringWidth = 0;
 
@Override
public void paint(Graphics g) {
 
if (this.maxStringWidth == 0) {
if (maxStringWidth == 0) {
g.setFont(f);
int w = this.getWidth();
int priceWidth = (int) g.getFontMetrics(f).getStringBounds(getPrice(BigDecimal.valueOf(999)), g).getWidth();
91,7 → 85,8
str += "a";
} while (strW < maxW);
 
this.maxStringWidth = Math.max(1, str.length() - 1);
maxStringWidth = Math.max(1, str.length() - 1);
System.out.println(w + " " + priceWidth + " " + maxStringWidth);
 
}
super.paint(g);
102,39 → 97,24
@Override
public void paintCell(Graphics g, Object object, int index, boolean isSelected, int posY) {
Article article = (Article) object;
paintArticle(f, g, article, isSelected, posY, this.getWidth(), this.getCellHeight(), this.maxStringWidth, getLeftMargin());
paintArticle(f, g, article, isSelected, posY, this.getWidth(), this.getCellHeight(), maxStringWidth, getLeftMargin());
 
}
};
 
this.list.setFixedCellHeight(64);
this.list.setOpaque(true);
this.add(this.list, c);
this.list.addListSelectionListener(new ListSelectionListener() {
list.setFixedCellHeight(64);
list.setOpaque(true);
this.add(list, c);
list.addListSelectionListener(this);
 
list.addMouseListener(new MouseAdapter() {
@Override
public void valueChanged(ListSelectionEvent e) {
Object sel = ArticleSelector.this.list.getSelectedValue();
if (sel != null && !e.getValueIsAdjusting()) {
Article article = (Article) sel;
controller.setArticleSelected(article);
}
 
}
});
 
this.list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
 
Object sel = ArticleSelector.this.list.getSelectedValue();
int nb = e.getClickCount();
if (nb > 1) {
Object sel = list.getSelectedValue();
if (sel != null) {
int nb = e.getClickCount();
if (nb == 1) {
Article article = (Article) sel;
controller.addArticle(article);
} else if (nb > 1) {
Article article = (Article) sel;
controller.incrementArticle(article);
controller.setArticleSelected(article);
}
150,14 → 130,24
 
}
});
this.comp.addMouseListener(new MouseAdapter() {
comp.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
ArticleSelector.this.list.scrollToOffset(0);
list.scrollToOffset(0);
}
});
}
 
@Override
public void valueChanged(ListSelectionEvent e) {
Object sel = list.getSelectedValue();
if (sel != null && !e.getValueIsAdjusting()) {
Article article = (Article) sel;
controller.setArticleSelected(article);
controller.addArticle(article);
}
}
 
public ArticleModel getModel() {
return this.model;
}
165,22 → 155,22
@Override
public void caisseStateChanged() {
 
final Article articleSelected = this.controller.getArticleSelected();
final Article articleSelected = controller.getArticleSelected();
if (articleSelected == null) {
this.list.clearSelection();
list.clearSelection();
return;
}
 
Object selectedValue = null;
try {
selectedValue = this.list.getSelectedValue();
selectedValue = list.getSelectedValue();
} catch (Exception e) {
e.printStackTrace();
}
if (!articleSelected.equals(selectedValue)) {
Categorie c = articleSelected.getCategorie();
this.model.setCategorie(c);
this.list.setSelectedValue(articleSelected, true);
model.setCategorie(c);
list.setSelectedValue(articleSelected, true);
}
 
}
236,35 → 226,10
g.drawString(label, leftMargin, posY + 26);
g.drawString(label2, leftMargin, posY + 52);
}
 
if (isSelected) {
g.setColor(new Color(232, 242, 254));
} else {
g.setColor(Color.WHITE);
}
g.fillRect(cellWidth - wEuro - 12, posY + 1, wEuro + 12, cellHeight - 2);
 
// Price
if (isSelected) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.GRAY);
}
if (article.getSalesUnit() != null) {
String unit = "/" + article.getSalesUnit();
int wUnit = (int) g.getFontMetrics().getStringBounds(unit, g).getWidth();
g.drawString(euro, cellWidth - 5 - wEuro, posY + 28);
g.drawString(unit, cellWidth - 5 - wUnit, posY + 50);
} else {
g.drawString(euro, cellWidth - 5 - wEuro, posY + 39);
}
 
}
 
public int getLeftMargin() {
if (this.controller.getPOSConf().getScreenWidth() < 1280) {
return 3;
}
return 10;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
20,10 → 20,7
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTable.VirtualFields;
64,7 → 61,7
private ArticleSelectorPanel articleSelectorPanel;
private ArticleSearchPanel articleSearchPanel;
 
private JPanel selector;
private JPanel articleSelector;
 
public CaissePanel(final CaisseFrame caisseFrame) throws Exception {
final SQLElementDirectory dir = caisseFrame.getConf().getDirectory();
73,36 → 70,40
this.setBackground(Color.WHITE);
this.setOpaque(isOpaque());
GridBagConstraints c = new GridBagConstraints();
 
// Column 1
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
 
this.controler = new CaisseControler(caisseFrame);
 
c.fill = GridBagConstraints.HORIZONTAL;
this.st = createStatusBar(caisseFrame);
 
this.add(this.st, c);
 
TicketPanel t = new TicketPanel(this.controler);
// fillExampleArticle();
loadArticles(dir);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.weighty = 1;
c.gridwidth = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
c.fill = GridBagConstraints.NONE;
this.add(t, c);
// Column 2
 
c.fill = GridBagConstraints.BOTH;
c.gridx++;
c.gridy = 0;
c.weightx = 1;
c.gridy--;
c.gridheight = 2;
this.articleSelectorPanel = new ArticleSelectorPanel(this.controler);
this.articleSearchPanel = new ArticleSearchPanel(this.controler);
this.selector = this.articleSelectorPanel;
this.add(this.selector, c);
// Column 3
articleSelectorPanel = new ArticleSelectorPanel(this.controler);
articleSearchPanel = new ArticleSearchPanel(this.controler);
articleSelector = articleSelectorPanel;
this.add(articleSelector, c);
 
c.gridx++;
c.weightx = 0;
this.add(new PaiementPanel(this.controler), c);
113,11 → 114,7
final StatusBar s = new StatusBar();
s.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
c.insets = new Insets(0, 2, 0, 2);
} else {
c.insets = new Insets(0, 10, 0, 10);
}
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
202,17 → 199,11
}
 
private void loadArticles(final SQLElementDirectory dir) {
final SQLSelect selUniteVente = new SQLSelect();
selUniteVente.addSelectStar(dir.getElement("UNITE_VENTE").getTable());
final Map<Integer, String> mapUniteVenteName = new HashMap<>();
for (SQLRow row : SQLRowListRSH.execute(selUniteVente)) {
mapUniteVenteName.put(row.getID(), row.getString("CODE"));
}
 
final Set<Integer> favoriteProductsIds = this.controler.loadFavoriteProductsIds();
final Set<Integer> favoriteProductsIds = controler.loadFavoriteProductsIds();
final List<Article> favoriteProducts = new ArrayList<>();
 
final Map<Integer, Categorie> categoriesMap = new HashMap<>();
final Map<Integer, Categorie> categoriesMap = new HashMap<Integer, Categorie>();
 
SQLElement eltFam = dir.getElement("FAMILLE_ARTICLE");
SQLElement eltArticle = dir.getElement("ARTICLE");
238,7 → 229,7
final SQLSelect selArticle = new SQLSelect();
final SQLTable tableArticle = eltArticle.getTable();
selArticle.addAllSelect(tableArticle.getFields(VirtualFields.PRIMARY_KEY.union(VirtualFields.ARCHIVE)));
selArticle.addAllSelect(tableArticle, Arrays.asList("ID_FAMILLE_ARTICLE", "NOM", "CODE", "CODE_BARRE", "ID_TAXE", "PV_HT", "PV_TTC", "ADDITIONAL_TICKET_COPY", "ID_UNITE_VENTE"));
selArticle.addAllSelect(tableArticle, Arrays.asList("ID_FAMILLE_ARTICLE", "NOM", "CODE", "CODE_BARRE", "ID_TAXE", "PV_HT", "PV_TTC", "ADDITIONAL_TICKET_COPY"));
selArticle.setWhere(new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE).and(new Where(tableArticle.getField("MASQUE_CAISSE"), "=", Boolean.FALSE)));
 
final Categorie cUnclassified = new Categorie("Non classés", true);
261,9 → 252,6
a.setPriceWithoutTax(row.getBigDecimal("PV_HT"));
a.setPriceWithTax(row.getBigDecimal("PV_TTC"));
a.setAdditionalCopyRequested(row.getBoolean("ADDITIONAL_TICKET_COPY"));
if (row.getInt("ID_UNITE_VENTE") != 2) {
a.setSalesUnit(mapUniteVenteName.get(row.getInt("ID_UNITE_VENTE")));
}
final Integer idProduct = a.getId();
if (favoriteProductsIds.contains(idProduct)) {
favoriteProducts.add(a);
272,39 → 260,8
}
}
Categorie.setFavoriteProducts(favoriteProducts);
initCacheArticleMap(dir);
}
 
private static Map<Integer, SQLRowAccessor> cacheArticle = new HashMap<>();
 
public static SQLRowAccessor getArticleRowValuesFromCache(int id) {
return cacheArticle.get(id);
}
 
private void initCacheArticleMap(final SQLElementDirectory dir) {
final SQLTable tableArt = dir.getElement("ARTICLE").getTable();
SQLRowValues rowValsArt = new SQLRowValues(tableArt);
rowValsArt.putNulls(tableArt.getFieldsName());
final SQLTable tableArtCatComptable = dir.getElement("ARTICLE_CATEGORIE_COMPTABLE").getTable();
SQLRowValues rowValsArtCatComptable = new SQLRowValues(tableArtCatComptable);
rowValsArtCatComptable.putNulls(tableArtCatComptable.getFieldsName());
rowValsArtCatComptable.put("ID_ARTICLE", rowValsArt);
final SQLRowValues rowValsCaCompt = rowValsArtCatComptable.putRowValues("ID_CATEGORIE_COMPTABLE");
rowValsCaCompt.putNulls(rowValsCaCompt.getTable().getFieldsName());
 
final SQLRowValues rowValsFam = rowValsArt.putRowValues("ID_FAMILLE_ARTICLE");
rowValsFam.putNulls(rowValsFam.getTable().getFieldsName());
final SQLRowValues rowValuesFamP = rowValsFam.putRowValues("ID_FAMILLE_ARTICLE_PERE");
rowValuesFamP.putNulls(rowValuesFamP.getTable().getFieldsName());
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsArt);
List<SQLRowValues> res = fetcher.fetch();
for (SQLRowValues sqlRowValues : res) {
cacheArticle.put(sqlRowValues.getID(), sqlRowValues);
}
 
}
 
@Override
public void paint(Graphics g) {
System.err.println("CaissePanel.paint()" + this.getWidth() + " x " + this.getHeight());
322,12 → 279,9
g.drawString("Solde : " + new DecimalFormat("#0.00").format(this.controler.getClient().getSolde()), 20, 120);
 
}
int xPos = 300;
if (this.controler.getPOSConf().getScreenWidth() < 1280) {
xPos = 270;
}
 
// Prix
int x = xPos;
int x = 300;
int y = 110;
String euros;
String cents;
349,7 → 303,7
g.drawString(cents, x + (int) r.getWidth(), y);
// Paiement
y += 40;
x = xPos;
x = 300;
final int paye = this.controler.getPaidTotal();
euros = CaisseControler.getEuros(paye) + ".";
cents = CaisseControler.getCents(paye);
373,7 → 327,7
final boolean minimalHeight = this.getHeight() < 750;
if (!minimalHeight) {
y += 40;
x = xPos;
x = 300;
} else {
x = 140;
}
418,16 → 372,15
 
public void switchListMode() {
 
GridBagConstraints c = ((GridBagLayout) this.getLayout()).getConstraints(this.selector);
this.remove(this.selector);
GridBagConstraints c = ((GridBagLayout) this.getLayout()).getConstraints(articleSelector);
this.remove(articleSelector);
 
if (this.selector == this.articleSearchPanel) {
this.selector = this.articleSelectorPanel;
if (articleSelector == this.articleSearchPanel) {
articleSelector = this.articleSelectorPanel;
} else {
this.selector = this.articleSearchPanel;
articleSelector = this.articleSearchPanel;
}
System.err.println("CaissePanel.switchListMode()" + this.selector.getMinimumSize() + " " + this.selector.getPreferredSize() + " " + this.selector.getMaximumSize());
this.add(this.selector, c);
this.add(articleSelector, c);
this.validate();
this.repaint();
 
434,36 → 387,6
}
 
public CaisseControler getControler() {
return this.controler;
return controler;
}
 
public void validateTicket(final CaisseFrame caisseFrame) {
final Ticket savedReceipt;
try {
savedReceipt = CaissePanel.this.controler.saveAndClearTicket(caisseFrame.getFiles(), caisseFrame.getConf().getDirectory());
} catch (DifferentDayException ex) {
JOptionPane.showMessageDialog(CaissePanel.this, "Impossible de laisser la caisse ouverte plusieurs jours. Veuillez la clôturer pour pouvoir faire de nouveaux tickets.", "Erreur",
JOptionPane.ERROR_MESSAGE);
return;
} catch (Throwable ex) {
ExceptionHandler.handle(CaissePanel.this, "Erreur de sauvegarde des informations du ticket", ex);
return;
}
if (savedReceipt != null) {
// Valider
CaissePanel.this.controler.setLCD("Impression de", "votre ticket...", 0);
try {
caisseFrame.getPOSConf().print(savedReceipt, (savedReceipt.isAdditionnalCopyRequested() ? 1 : 0));
} catch (UnsatisfiedLinkError ex) {
JOptionPane.showMessageDialog(CaissePanel.this, "Erreur de configuration de la liaison à l'imprimante");
} catch (Throwable ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(CaissePanel.this, "Erreur d'impression du ticket");
}
 
CaissePanel.this.controler.setLCDDefaultDisplay(2);
} else {
System.err.println("CaissePanel.validateTicket() ticket non sauvé");
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TextAreaTicketPanel.java
23,10 → 23,7
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.DecimalUtils;
 
36,9 → 33,7
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JButton;
import javax.swing.JPanel;
82,7 → 77,6
}
 
private Ticket createTicket(SQLRow row) {
// TODO merger ce code avec CaissepPanel.loadArticles si possible
final Ticket t;
try {
t = new Ticket(new ReceiptCode(row.getString("NUMERO")), row.getDate("DATE"), row.getString("FILE_HASH_PREVIOUS"));
90,8 → 84,7
throw new IllegalStateException("Couldn't parse " + row, e);
}
 
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
SQLElement eltEncaisser = directory.getElement("ENCAISSER_MONTANT");
SQLElement eltEncaisser = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
List<SQLRow> l = row.getReferentRows(eltEncaisser.getTable());
for (SQLRow row2 : l) {
long montant = row2.getLong("MONTANT");
113,35 → 106,20
t.addPaiement(p);
}
 
SQLElement eltArticle = directory.getElement("SAISIE_VENTE_FACTURE_ELEMENT");
 
final SQLSelect selUniteVente = new SQLSelect();
selUniteVente.addSelectStar(directory.getElement("UNITE_VENTE").getTable());
final Map<Integer, String> mapUniteVenteName = new HashMap<>();
for (SQLRow rowUniteVente : SQLRowListRSH.execute(selUniteVente)) {
mapUniteVenteName.put(rowUniteVente.getID(), rowUniteVente.getString("CODE"));
}
 
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
List<SQLRow> l2 = row.getReferentRows(eltArticle.getTable());
Categorie c = new Categorie("");
for (SQLRow row2 : l2) {
Article a = new Article(c, row2.getString("NOM"), row2.getInt("ID_ARTICLE"));
if (row2.getInt("ID_UNITE_VENTE") != 2) {
a.setSalesUnit(mapUniteVenteName.get(row2.getInt("ID_UNITE_VENTE")));
}
BigDecimal ht = (BigDecimal) row2.getObject("PV_HT");
a.setPriceWithoutTax(ht);
int idTaxe = row2.getInt("ID_TAXE");
float tva = TaxeCache.getCache().getTauxFromId(idTaxe);
a.setPriceWithTax(ht.multiply(BigDecimal.valueOf(1.0 + (tva / 100.0D)), DecimalUtils.HIGH_PRECISION));
a.setPriceWithTax(ht.multiply(new BigDecimal(1.0 + (tva / 100.0D)), DecimalUtils.HIGH_PRECISION));
a.setIdTaxe(idTaxe);
t.addArticle(a);
if (a.getSalesUnit() == null) {
t.setArticleCount(a, new BigDecimal(row2.getInt("QTE")));
} else {
t.setArticleCount(a, row2.getBigDecimal("QTE_UNITAIRE"));
t.setArticleCount(a, row2.getInt("QTE"));
}
}
 
return t;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CategorieSelector.java
85,10 → 85,6
 
}
super.paint(g);
 
g.setColor(Color.LIGHT_GRAY);
g.drawLine(0, 0, 0, this.getHeight());
 
}
 
private int getLeftMargin() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSelectorPanel.java
13,6 → 13,7
package org.openconcerto.erp.core.sales.pos.ui;
 
 
import java.awt.GridLayout;
 
import javax.swing.JPanel;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/TicketItem.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterFiles.java
78,10 → 78,6
public static final String STRUCT_VERSION_2013 = "v20131206";
public static final String STRUCT_VERSION = "v20171220";
 
private static final String PREVIOUS_SUBDIR = "previous";
private static final String CURRENT_SUBDIR = "current";
private static final String STAGING_SUBDIR = "staging";
 
private static final String LOG_FILENAME = "log.xml";
static final String HASH_SUFFIX = ".hash";
private static final String LOG_HASH_FILENAME = LOG_FILENAME + HASH_SUFFIX;
337,7 → 333,7
}
 
private final Path getDayDirToUse(final Path dayDir) throws IOException {
for (final Path subdir : new Path[] { dayDir.resolve(CURRENT_SUBDIR), dayDir.resolve(PREVIOUS_SUBDIR) }) {
for (final Path subdir : new Path[] { dayDir.resolve("current"), dayDir.resolve("previous") }) {
if (Files.exists(subdir)) {
final ValidState validity = getDayDirValidity(subdir);
if (validity.isValid())
417,9 → 413,9
if (dayDirToUse != null)
throw new IllegalStateException(cal.getTime() + " already open");
 
final Path stagingDir = dayDir.resolve(STAGING_SUBDIR);
final Path currentDir = stagingDir.resolveSibling(CURRENT_SUBDIR);
final Path prevDir = stagingDir.resolveSibling(PREVIOUS_SUBDIR);
final Path stagingDir = dayDir.resolve("staging");
final Path currentDir = stagingDir.resolveSibling("current");
final Path prevDir = stagingDir.resolveSibling("previous");
FileUtils.rm_R(stagingDir);
FileUtils.rm_R(currentDir);
FileUtils.rm_R(prevDir);
429,20 → 425,7
rootElem.addContent(new RegisterLogEntry.RegisterEntry(EventType.REGISTER_OPENING, cal.getTime(), userID, input.getPosID(), lastLocalHash, prevDate).toXML());
save(new Document(rootElem), stagingDir.resolve(LOG_FILENAME));
 
for (int i = 0; i < 5; i++) {
try {
Files.move(stagingDir, currentDir, StandardCopyOption.ATOMIC_MOVE);
break;
} catch (Exception e) {
e.printStackTrace();
try {
// Retry 5 times, because can fail under Windows
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
 
POSConfiguration.getLogger().log(Level.INFO, "Finished opening of FS state for register {0}", registerDB);
 
471,9 → 454,9
 
// e.g. 2017/12/21/current/
final Path toUse = lastLog.getLogFile().getParent();
final Path stagingDir = toUse.resolveSibling(STAGING_SUBDIR);
final Path currentDir = stagingDir.resolveSibling(CURRENT_SUBDIR);
final Path prevDir = stagingDir.resolveSibling(PREVIOUS_SUBDIR);
final Path stagingDir = toUse.resolveSibling("staging");
final Path currentDir = stagingDir.resolveSibling("current");
final Path prevDir = stagingDir.resolveSibling("previous");
 
FileUtils.rm_R(stagingDir);
FileUtils.copyDirectory(toUse, stagingDir, input.useHardLinks, StandardCopyOption.COPY_ATTRIBUTES);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterDB.java
42,7 → 42,6
import org.openconcerto.utils.TimeUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
219,7 → 218,7
 
// TODO monthly and yearly closures
 
public final DBState close(final POSConfiguration posConf, final RegisterLog log) throws SQLException, ParseException, IOException {
public final DBState close(final POSConfiguration posConf, final RegisterLog log) throws SQLException, ParseException {
final List<ReceiptEntry> receiptEvents = log.getReceiptEvents();
final RegisterEntry closureEntry = log.getLastRegisterEvent();
if (closureEntry.getType() != EventType.REGISTER_CLOSURE)
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Article.java
31,8 → 31,6
private String barCode = "empty barcode";
private String code = "";
private final int id;
// unité de vente (null si à la pièce)
private String salesUnit;
private static Map<String, Article> codes = new HashMap<String, Article>();
 
public Article(Categorie s1, String string, int id) {
50,12 → 48,11
this.priceHT = a.priceHT;
this.barCode = a.barCode;
this.id = a.id;
this.salesUnit = a.salesUnit;
this.s.addArticle(this);
}
 
public boolean isAdditionalCopyRequested() {
return this.additionalCopyRequested;
return additionalCopyRequested;
}
 
public void setAdditionalCopyRequested(boolean additionalCopyRequested) {
117,7 → 114,7
 
@Override
public String toString() {
return "Article:" + this.name + " " + this.priceTTC + " cents" + "(HT:" + this.priceHT + ") " + getSalesUnit();
return "Article:" + this.name + " " + this.priceTTC + " cents" + "(HT:" + priceHT + ")";
}
 
public static Article getArticleFromBarcode(String code) {
142,20 → 139,12
}
 
public static BigDecimal computePriceWithTax(BigDecimal ht, int idTaxe) {
final BigDecimal tax = BigDecimal.valueOf(TaxeCache.getCache().getTauxFromId(idTaxe)).movePointLeft(2).add(BigDecimal.ONE);
final BigDecimal tax = new BigDecimal(TaxeCache.getCache().getTauxFromId(idTaxe)).movePointLeft(2).add(BigDecimal.ONE);
return ht.multiply(tax).setScale(2, RoundingMode.HALF_UP);
}
 
public static BigDecimal computePriceWithoutTax(BigDecimal ttc, int idTaxe) {
final BigDecimal tax = BigDecimal.valueOf(TaxeCache.getCache().getTauxFromId(idTaxe)).movePointLeft(2).add(BigDecimal.ONE);
final BigDecimal tax = new BigDecimal(TaxeCache.getCache().getTauxFromId(idTaxe)).movePointLeft(2).add(BigDecimal.ONE);
return ttc.divide(tax, DecimalUtils.HIGH_PRECISION).setScale(6, RoundingMode.HALF_UP);
}
 
public void setSalesUnit(String name) {
this.salesUnit = name;
}
 
public String getSalesUnit() {
return this.salesUnit;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Ticket.java
24,7 → 24,6
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles.HashMode;
import org.openconcerto.erp.core.sales.pos.ui.CaissePanel;
import org.openconcerto.erp.core.sales.pos.ui.TicketCellRenderer;
import org.openconcerto.erp.generationEcritures.GenerationEcritures;
import org.openconcerto.erp.generationEcritures.GenerationMvtVirement;
31,8 → 30,6
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
39,6 → 36,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.Pair;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.XMLDateFormat;
 
68,14 → 66,14
private static final XMLDateFormat DATE_FMT = new XMLDateFormat();
 
// Propre a ticket
private final List<Paiement> paiements = new ArrayList<>();
private final List<TicketItem> items = new ArrayList<>();
private final List<Paiement> paiements = new ArrayList<Paiement>();
private final List<Pair<Article, Integer>> items = new ArrayList<Pair<Article, Integer>>();
private Calendar creationCal;
private Client client = Client.NONE;
private final int number;
private final String previousHash;
private boolean additionnalCopyRequested = false;
private String codePostal = "";
 
// Propre à la caisse
private final int caisseNumber;
 
96,15 → 94,6
}
}
 
public String getCodePostal() {
return this.codePostal;
}
 
public void setCodePostal(String codePostal) {
this.codePostal = codePostal;
 
}
 
public void setClient(final Client client) {
this.client = client;
}
113,11 → 102,15
return this.client;
}
 
public static Ticket parseFile(final File file) throws IOException {
public static Ticket parseFile(final File file) {
return parseFile(file, HashMode.REQUIRED);
}
 
public static Ticket parseFile(final File file, final HashMode hashMode) throws IOException {
public static Ticket parseFile(final File file, final HashMode hashMode) {
if (!file.exists()) {
return null;
}
 
try {
// XML Reading
 
138,12 → 131,10
final Ticket t = new Ticket(receiptCode, c, root.getAttributeValue("previousHash"));
t.setClient(new Client(Integer.parseInt(client), "", BigDecimal.ZERO));
 
t.setCodePostal(root.getAttributeValue("codePostal", ""));
 
// article
final List<Element> children = root.getChildren("article");
for (final Element element : children) {
final BigDecimal qte = new BigDecimal(element.getAttributeValue("qte"));
final int qte = Integer.parseInt(element.getAttributeValue("qte"));
final BigDecimal prix_unitaire_cents_ht = new BigDecimal(element.getAttributeValue("prixHT"));
final int idTaxe = Integer.parseInt(element.getAttributeValue("idTaxe"));
final BigDecimal prix_unitaire_cents = new BigDecimal(element.getAttributeValue("prix"));
151,7 → 142,6
final String name = element.getValue();
final String codebarre = element.getAttributeValue("codebarre");
final String codeArt = element.getAttributeValue("code");
final String salesUnit = element.getAttributeValue("unit");
final Categorie cat = new Categorie(categorie);
 
final String valueID = element.getAttributeValue("id");
163,8 → 153,7
art.setPriceWithoutTax(prix_unitaire_cents_ht);
art.setIdTaxe(idTaxe);
art.setBarCode(codebarre);
art.setSalesUnit(salesUnit);
final TicketItem line = new TicketItem(art, qte);
final Pair<Article, Integer> line = new Pair<Article, Integer>(art, qte);
t.items.add(line);
 
}
192,10 → 181,10
}
 
return t;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("Couldn't parse " + file, e);
} catch (final Exception e) {
System.err.println("Error with ticket : " + file + " : " + e.getMessage());
e.printStackTrace();
return null;
}
}
 
222,13 → 211,6
return this.previousHash;
}
 
public void clear() {
this.client = Client.NONE;
this.codePostal = "";
this.paiements.clear();
 
}
 
public final ReceiptCode getReceiptCode() {
// TODO replace our fields by one ReceiptCode
return new ReceiptCode(this.getCaisseNumber(), this.getCreationCal(), this.getNumber());
270,24 → 252,19
topLevel.setAttribute("previousHash", this.getPreviousHash());
topLevel.setAttribute("creationDate", DATE_FMT.format(c.getTime()));
topLevel.setAttribute("clientID", String.valueOf(this.client.getId()));
topLevel.setAttribute("codePostal", this.codePostal);
// Articles
for (final TicketItem item : this.items) {
for (final Pair<Article, Integer> item : this.items) {
final Element e = new Element("article");
e.setAttribute("qte", String.valueOf(item.getQty()));
e.setAttribute("qte", String.valueOf(item.getSecond()));
// Prix unitaire
final Article article = item.getArticle();
e.setAttribute("prix", String.valueOf(article.getPriceWithTax()));
e.setAttribute("prixHT", String.valueOf(article.getPriceWithoutTax()));
e.setAttribute("idTaxe", String.valueOf(article.getIdTaxe()));
e.setAttribute("categorie", article.getCategorie().getName());
e.setAttribute("codebarre", article.getBarCode());
e.setAttribute("code", article.getCode());
e.setAttribute("id", String.valueOf(article.getId()));
if (article.getSalesUnit() != null) {
e.setAttribute("unit", article.getSalesUnit());
}
e.setText(article.getName());
e.setAttribute("prix", String.valueOf(item.getFirst().getPriceWithTax()));
e.setAttribute("prixHT", String.valueOf(item.getFirst().getPriceWithoutTax()));
e.setAttribute("idTaxe", String.valueOf(item.getFirst().getIdTaxe()));
e.setAttribute("categorie", item.getFirst().getCategorie().getName());
e.setAttribute("codebarre", item.getFirst().getBarCode());
e.setAttribute("code", item.getFirst().getCode());
e.setAttribute("id", String.valueOf(item.getFirst().getId()));
e.setText(item.getFirst().getName());
topLevel.addContent(e);
}
// Paiements
383,13 → 360,13
final SimpleDateFormat df = new SimpleDateFormat("EEEE d MMMM yyyy à HH:mm", Locale.FRENCH);
prt.addToBuffer(DefaultTicketPrinter.formatCenter(maxWidth, "Le " + df.format(getCreationDate())));
prt.addToBuffer("");
List<TicketItem> itemsToPrint = new ArrayList<>(this.items);
Collections.sort(itemsToPrint, new Comparator<TicketItem>() {
List<Pair<Article, Integer>> itemsToPrint = new ArrayList<>(this.items);
Collections.sort(itemsToPrint, new Comparator<Pair<Article, Integer>>() {
 
@Override
public int compare(TicketItem o1, TicketItem o2) {
final Article p1 = o1.getArticle();
final Article p2 = o2.getArticle();
public int compare(Pair<Article, Integer> o1, Pair<Article, Integer> o2) {
final Article p1 = o1.getFirst();
final Article p2 = o2.getFirst();
final Categorie c1 = p1.getCategorie();
final Categorie c2 = p2.getCategorie();
if (c1.equals(c2)) {
407,9 → 384,8
}
});
Categorie currentCategorie = null;
for (final TicketItem item : this.items) {
final Article article = item.getArticle();
System.err.println("Ticket.print()" + item);
for (final Pair<Article, Integer> item : this.items) {
final Article article = item.getFirst();
if (currentCategorie == null || !currentCategorie.getName().equals(article.getCategorie().getName())) {
// Print category name, except for unknown
currentCategorie = article.getCategorie();
417,29 → 393,20
prt.addToBuffer(currentCategorie.getName(), TicketPrinter.BOLD);
}
}
final BigDecimal nb = item.getQty();
final Integer nb = item.getSecond();
final Float tauxFromId = TaxeCache.getCache().getTauxFromId(article.getIdTaxe());
final BigDecimal tauxTVA = BigDecimal.valueOf(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
final BigDecimal tauxTVA = new BigDecimal(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
final BigDecimal unitPrice = article.getPriceWithoutTax().multiply(tauxTVA, DecimalUtils.HIGH_PRECISION);
final BigDecimal multiply = article.getPriceWithoutTax().multiply(nb, DecimalUtils.HIGH_PRECISION).multiply(tauxTVA, DecimalUtils.HIGH_PRECISION);
final BigDecimal multiply = article.getPriceWithoutTax().multiply(new BigDecimal(nb), DecimalUtils.HIGH_PRECISION).multiply(tauxTVA, DecimalUtils.HIGH_PRECISION);
 
String qtyString = DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, String.valueOf(nb));
final String priceUnformated = TicketCellRenderer.centsToString(multiply.movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue());
final String priceString = DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, priceUnformated);
final String qtyString = DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, String.valueOf(nb));
final String priceString = DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, TicketCellRenderer.centsToString(multiply.movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue()));
String unitPriceString = "";
if (article.getSalesUnit() == null) {
if (nb.intValue() != 1) {
if (nb != 1) {
unitPriceString = DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, TicketCellRenderer.centsToString(unitPrice.movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue()));
}
} else {
unitPriceString = DefaultTicketPrinter.formatRight(MAX_PRICE_WIDTH, "");
if (nb.signum() >= 0) {
qtyString = DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, "1");
} else {
qtyString = DefaultTicketPrinter.formatRight(MAX_QTE_WIDTH, "-1");
}
}
if (article.getCode() != null && !article.getCode().isEmpty() && !article.getCode().equalsIgnoreCase(article.getName())) {
 
if (article.getCode() != null && !article.getCode().isEmpty()) {
// 2 lines
final String codeString = DefaultTicketPrinter.formatLeft(maxWidth - 2 - MAX_PRICE_WIDTH - MAX_QTE_WIDTH - 1 - unitPriceString.length(), article.getCode());
prt.addToBuffer(qtyString + " " + codeString + " " + unitPriceString + " " + priceString);
450,11 → 417,8
final String nameString = DefaultTicketPrinter.formatLeft(maxWidth - 2 - MAX_PRICE_WIDTH - MAX_QTE_WIDTH - 1 - unitPriceString.length(), article.getName());
prt.addToBuffer(qtyString + " " + nameString + " " + unitPriceString + " " + priceString);
}
if (article.getSalesUnit() != null) {
prt.addToBuffer(
" (" + nb.abs() + " " + article.getSalesUnit() + " x " + TicketCellRenderer.centsToString(unitPrice.movePointRight(2).setScale(0, RoundingMode.HALF_UP).intValue()) + ")");
 
}
}
 
final StringBuilder spacer = new StringBuilder();
for (int i = 0; i <= MAX_QTE_WIDTH; i++) {
496,20 → 460,16
type = "Remboursement ";
}
if (paiement.getType() == Paiement.CB) {
type += "CB";
type = "CB";
} else if (paiement.getType() == Paiement.CHEQUE) {
type += "par chèque";
type = "par chèque";
} else if (paiement.getType() == Paiement.ESPECES) {
type += "en espèces";
type = "en espèces";
} else if (paiement.getType() == Paiement.SOLDE) {
type += "depuis solde";
type = "depuis solde";
}
if (montantInCents > 0) {
type += " de " + TicketCellRenderer.centsToString(montantInCents);
} else {
type += " de " + TicketCellRenderer.centsToString(-montantInCents);
}
if (Math.abs(montantInCents) > 100) {
if (montantInCents > 100) {
type += " euros";
} else {
type += " euro";
521,7 → 481,7
if (getTotalInCents() < getPaidTotal()) {
final int montantInCents = getPaidTotal() - getTotalInCents();
String type = "Rendu : " + TicketCellRenderer.centsToString(montantInCents);
if (Math.abs(montantInCents) > 100) {
if (montantInCents > 100) {
type += " euros";
} else {
type += " euro";
565,25 → 525,23
}
 
public boolean isAdditionnalCopyRequested() {
return this.additionnalCopyRequested;
return additionnalCopyRequested;
}
 
public void addArticle(final Article a) {
System.err.println("Ticket.addArticle()" + a);
boolean alreadyExist = false;
if (a.isAdditionalCopyRequested()) {
this.additionnalCopyRequested = true;
}
if (a.getSalesUnit() == null) {
for (final TicketItem line : this.items) {
if (line.getArticle().equals(a)) {
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(a)) {
alreadyExist = true;
break;
}
}
}
 
if (!alreadyExist) {
final TicketItem line = new TicketItem(new Article(a), BigDecimal.ONE);
final Pair<Article, Integer> line = new Pair<Article, Integer>(new Article(a), 1);
this.items.add(line);
}
 
590,29 → 548,21
}
 
public void incrementArticle(final Article a) {
System.err.println("Ticket.incrementArticle()" + a.getName());
 
boolean alreadyExist = false;
if (a.getSalesUnit() == null) {
for (final TicketItem line : this.items) {
if (line.getArticle().equals(a)) {
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(a)) {
alreadyExist = true;
line.setQty(line.getQty().add(BigDecimal.ONE));
line.setSecond(line.getSecond() + 1);
break;
}
}
}
if (!alreadyExist) {
final TicketItem line = new TicketItem(a, BigDecimal.ONE);
final Pair<Article, Integer> line = new Pair<Article, Integer>(a, 1);
this.items.add(line);
}
 
}
 
public void addItem(TicketItem item) {
this.items.add(item);
}
 
public List<Paiement> getPaiements() {
return this.paiements;
}
631,19 → 581,14
calc.setServiceActive(bServiceActive != null && bServiceActive);
final int size = this.items.size();
for (int i = 0; i < size; i++) {
final TicketItem line = this.items.get(i);
final BigDecimal count = line.getQty();
final Article art = line.getArticle();
final Pair<Article, Integer> line = this.items.get(i);
final int count = line.getSecond();
final Article art = line.getFirst();
final SQLRowValues rowVals = new SQLRowValues(tableElt);
rowVals.put("T_PV_HT", art.getPriceWithoutTax().multiply(count));
if (art.getSalesUnit() != null) {
rowVals.put("QTE_UNITAIRE", count);
rowVals.put("QTE", BigDecimal.ONE);
} else {
rowVals.put("QTE", count.intValue());
}
rowVals.put("T_PV_HT", art.getPriceWithoutTax().multiply(new BigDecimal(count)));
rowVals.put("QTE", count);
rowVals.put("ID_TAXE", art.getIdTaxe());
calc.addLine(rowVals, CaissePanel.getArticleRowValuesFromCache(art.getId()), i, false);
calc.addLine(rowVals, tableArticle.getRow(art.getId()), i, false);
 
}
calc.checkResult();
650,14 → 595,14
return calc;
}
 
public List<TicketItem> getItems() {
public List<Pair<Article, Integer>> getArticles() {
return this.items;
}
 
public void clearArticle(final Article article) {
TicketItem toRemove = null;
for (final TicketItem line : this.items) {
if (line.getArticle().equals(article)) {
Pair<Article, Integer> toRemove = null;
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(article)) {
toRemove = line;
break;
}
667,46 → 612,32
}
}
 
public void removeTicketItem(TicketItem item) {
TicketItem toRemove = null;
for (final TicketItem line : this.items) {
if (line.equals(item)) {
toRemove = line;
break;
}
}
if (toRemove != null) {
this.items.remove(toRemove);
}
 
}
 
public void setArticleCount(final Article article, final BigDecimal count) {
public void setArticleCount(final Article article, final int count) {
// TODO Allow only if annulation?
// if (count <= 0) {
// this.clearArticle(article);
// return;
// }
TicketItem toModify = null;
for (final TicketItem line : this.items) {
if (line.getArticle().equals(article)) {
Pair<Article, Integer> toModify = null;
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(article)) {
toModify = line;
break;
}
}
if (toModify != null) {
toModify.setQty(count);
toModify.setSecond(count);
}
 
}
 
public BigDecimal getItemCount(final Article article) {
for (final TicketItem line : this.items) {
if (line.getArticle().equals(article)) {
return line.getQty();
public int getItemCount(final Article article) {
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(article)) {
return line.getSecond();
}
}
return BigDecimal.ZERO;
return 0;
}
 
public int getPaidTotal() {
718,14 → 649,14
}
 
public void removeArticle(final Article a) {
TicketItem lineToDelete = null;
for (final TicketItem line : this.items) {
if (line.getArticle().equals(a)) {
final BigDecimal count = line.getQty().add(BigDecimal.ONE);
if (count.signum() <= 0) {
Pair<Article, Integer> lineToDelete = null;
for (final Pair<Article, Integer> line : this.items) {
if (line.getFirst().equals(a)) {
final int count = line.getSecond() + 1;
if (count <= 0) {
lineToDelete = line;
}
line.setQty(count);
line.setSecond(count);
break;
}
}
820,5 → 751,4
 
getReceiptCode().markDeleted();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/ReceiptCode.java
229,6 → 229,10
return this.dayIndex;
}
 
public final String getCodePrefix() {
return this.code.substring(0, this.code.length() - INDEX_FORMAT.getMinimumIntegerDigits());
}
 
public final String getCode() {
return this.code;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterLog.java
163,9 → 163,8
*
* @return the list of current receipts in this.
* @throws ParseException if an entry couldn't be parsed.
* @throws IOException if the receipts couldn't be parsed.
*/
public final List<Ticket> parseReceipts() throws ParseException, IOException {
public final List<Ticket> parseReceipts() throws ParseException {
final List<Ticket> receipts = new ArrayList<>();
final Path toUse = this.getLogFile().getParent();
final List<ReceiptEntry> receiptEvents = this.getReceiptEvents();
173,13 → 172,7
int index = 1;
for (final ReceiptEntry receiptEntry : receiptEvents) {
final Path receiptFile = toUse.resolve(receiptEntry.getCode().getFileName());
final Ticket receipt;
try {
receipt = Ticket.parseFile(receiptFile.toFile(), HashMode.equalTo(receiptEntry.getFileHash()));
} catch (Exception e) {
throw new IOException("Couldn't parse file of " + receiptEntry + " : " + receiptFile, e);
}
assert receipt != null;
final Ticket receipt = Ticket.parseFile(receiptFile.toFile(), HashMode.equalTo(receiptEntry.getFileHash()));
if (!receipt.getCode().equals(receiptEntry.getCodeString()))
throw new IllegalStateException("Code mismatch");
if (!CompareUtils.equals(lastHash, receipt.getPreviousHash()))
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/element/BonDeLivraisonItemSQLElement.java
37,7 → 37,6
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("ID_BON_DE_LIVRAISON");
l.add("CODE");
l.add("NOM");
l.add("PA_HT");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/element/BonDeLivraisonSQLElement.java
77,10 → 77,6
final List<String> l = new ArrayList<>();
l.add("NUMERO");
l.add("DATE");
if(getTable().contains("ID_COMMERCIAL")) {
l.add("ID_COMMERCIAL");
}
l.add("ID_CLIENT");
DefaultProps props = DefaultNXProps.getInstance();
Boolean b = props.getBooleanValue("ArticleShowPoids");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/ui/BonDeLivraisonItemTable.java
617,7 → 617,6
if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
completionField.add("ID_ECO_CONTRIBUTION");
}
completionField.add("POURCENT_REMISE");
completionField.add("ID_UNITE_VENTE");
completionField.add("QTE_UNITAIRE");
completionField.add("PA_HT");
654,13 → 653,11
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field, rowDest, true);
if (res == null) {
res = super.getValueFrom(row, field, rowDest);
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
if (field.equals("POURCENT_REMISE")) {
return getRemiseClient(row);
}
return res;
}
};
m.fill("NOM", "NOM");
m.fill("ID", "ID_ARTICLE");
746,13 → 743,11
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field, rowDest, true);
if (res == null) {
res = super.getValueFrom(row, field, rowDest);
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
if (field.equals("POURCENT_REMISE")) {
return getRemiseClient(row);
}
return res;
}
};
m2.fill("CODE", "CODE");
m2.fill("ID", "ID_ARTICLE");
769,13 → 764,11
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field, rowDest, true);
if (res == null) {
res = super.getValueFrom(row, field, rowDest);
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
if (field.equals("POURCENT_REMISE")) {
return getRemiseClient(row);
}
return res;
}
};
m3.fill("CODE", "CODE");
m3.fill("NOM", "NOM");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/component/BonDeLivraisonSQLComponent.java
22,7 → 22,6
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
41,7 → 40,6
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
52,8 → 50,6
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.sqlobject.SQLTextCombo;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
109,7 → 105,6
private final JDate date = new JDate(true);
private final boolean displayDpt;
private final ElementComboBox comboDpt = new ElementComboBox();
private ElementComboBox comboCommercial;
 
public BonDeLivraisonSQLComponent() {
super(Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON"));
130,13 → 125,6
if (rowVals == null) {
rowVals = new SQLRowValues(getTable());
}
SQLElement eltComm = getElement().getForeignElement("ID_COMMERCIAL");
int idUser = UserManager.getInstance().getCurrentUser().getId();
SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
 
if (rowsComm != null) {
rowVals.put("ID_COMMERCIAL", rowsComm.getID());
}
if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
rowVals.put("CREATE_VIRTUAL_STOCK", Boolean.TRUE);
}
319,23 → 307,6
}
});
}
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
// cat spe
final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
catUI.addToUI(this, c);
catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = catUI.getCombo().getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
tableBonItem.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
} else {
tableBonItem.setRowCatComptable(null);
}
}
});
}
if (getTable().contains("SPEC_LIVRAISON")) {
// Date livraison
c.gridx++;
391,37 → 362,14
} else {
tableBonItem.setRowCatComptable(null);
}
if (!isFilling()) {
tableBonItem.setClient(rowClient, true);
}
 
} else {
comboContact.getRequest().setWhere(Where.FALSE);
tableBonItem.setRowCatComptable(null);
if (!isFilling()) {
tableBonItem.setClient(null, true);
}
// DevisSQLComponent.this.table.setTarif(null, false);
}
}
});
 
// Commercial
JLabel labelCommercial = new JLabel(getLabelFor("ID_COMMERCIAL"));
labelCommercial.setHorizontalAlignment(SwingConstants.RIGHT);
 
c.gridx++;
c.weightx = 0;
this.add(labelCommercial, c);
 
this.comboCommercial = new ElementComboBox(false, 25);
this.comboCommercial.setListIconVisible(false);
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
this.add(this.comboCommercial, c);
addRequiredSQLObject(this.comboCommercial, "ID_COMMERCIAL");
 
}
 
final ElementComboBox boxTarif = new ElementComboBox();
497,23 → 445,7
tableBonItem.setTarif(selectedRow, !isFilling());
}
});
 
if (getTable().contains("SERVI_PAR")) {
// Commercial
JLabel labelServi = new JLabel("Servi par");
labelServi.setHorizontalAlignment(SwingConstants.RIGHT);
c.gridx++;
c.weightx = 0;
this.add(labelServi, c);
 
SQLTextCombo comboServiPar = new SQLTextCombo();
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
this.add(comboServiPar, c);
addRequiredSQLObject(comboServiPar, "SERVI_PAR");
}
}
 
if (getTable().contains("A_ATTENTION")) {
// Date livraison
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/component/AvoirClientSQLComponent.java
27,7 → 27,6
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
194,9 → 193,6
boxTarif.setValue(foreignRow.getID());
}
}
if (!isFilling()) {
AvoirClientSQLComponent.this.table.setClient(row, true);
}
 
} else {
table.setRowCatComptable(null);
427,25 → 423,7
}
});
}
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
// cat spe
final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
catUI.addToUI(this, c);
catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = catUI.getCombo().getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
table.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
} else {
table.setRowCatComptable(null);
}
}
});
 
}
 
final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
 
// Contact
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesElementsACommanderClientAction.java
18,7 → 18,6
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.sales.order.element.CommandeClientElementSQLElement;
import org.openconcerto.erp.core.sales.product.ui.QteAcommanderRenderer;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.element.SQLElement;
125,17 → 124,14
protected Object show_(SQLRowAccessor r) {
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
 
if (foreign != null && !foreign.isUndefined()) {
if (foreign.getBoolean("GESTION_STOCK")) {
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_REEL");
}
}
return 0F;
}
return null;
}
 
@Override
public Set<FieldPath> getPaths() {
154,16 → 150,13
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
if (foreign.getBoolean("GESTION_STOCK")) {
 
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_TH");
}
}
return 0F;
}
return null;
}
 
@Override
public Set<FieldPath> getPaths() {
182,16 → 175,13
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
if (foreign.getBoolean("GESTION_STOCK")) {
 
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
return foreign2.getFloat("QTE_MIN");
}
}
return 0F;
}
return null;
}
 
@Override
public Set<FieldPath> getPaths() {
210,8 → 200,6
 
final SQLRowAccessor foreign = r.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined()) {
if (foreign.getBoolean("GESTION_STOCK")) {
 
SQLRowAccessor foreign2 = StockSQLElement.getStockFetched(r);
if (foreign2 != null && !foreign2.isUndefined()) {
float qteMin = foreign2.getFloat("QTE_MIN");
218,13 → 206,10
float manque = foreign2.getFloat("QTE_TH") - qteMin;
if (manque < 0) {
return -manque;
} else {
return 0f;
}
}
}
}
return r.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(r.getInt("QTE"))).floatValue();
return 0F;
 
}
 
237,7 → 222,7
}
};
tableSource.getColumns().add(colSug);
colSug.setRenderer(new QteAcommanderRenderer());
// colLiv2.setRenderer(new PercentTableCellRenderer());
 
return tableSource;
}
329,7 → 314,7
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
eltCmd.transfertCommande(selectedRows);
eltCmd.createCommandeF(selectedRows);
}
}, true);
predicateACtion.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/component/CommandeClientSQLComponent.java
23,7 → 23,6
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI;
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.order.ui.CommandeClientItemTable;
256,16 → 255,8
// }
// table.setTarif(foreignRow, true);
}
if (!isFilling()) {
table.setClient(row, true);
}
 
} else {
if (!isFilling()) {
table.setClient(null, true);
}
}
}
 
}
});
402,24 → 393,6
});
}
 
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
// cat spe
final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
catUI.addToUI(this, c);
catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
int wantedID = catUI.getCombo().getWantedID();
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
table.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
} else {
table.setRowCatComptable(null);
}
}
});
}
 
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ORDER_PACKAGING_MANAGEMENT, true)) {
// Emballage
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientSQLElement.java
22,9 → 22,7
import org.openconcerto.erp.core.sales.order.component.CommandeClientSQLComponent;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.order.ui.EtatCommandeClient;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
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.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
38,6 → 36,7
import org.openconcerto.sql.element.TreesOfSQLRows;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
580,68 → 579,43
public void transfertCommande(int commandeID, boolean useCommandeEnCours) {
 
SQLElement elt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
SQLTable tableCmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT").getTable();
SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
SQLRow rowCmd = getTable().getRow(commandeID);
List<SQLRow> rows = rowCmd.getReferentRows(elt.getTable());
transfertEltToCommandeF(rows);
}
 
public void transfertEltToCommandeF(List<? extends SQLRowAccessor> rowsItems) {
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
ProductHelper helper = new ProductHelper(getTable().getDBRoot());
List<ProductComponent> productComp = new ArrayList<>();
helper.fillProductComponent(rowsItems, productComp, 1, 0, 1);
 
List<ProductComponent> leafItems = helper.getChildWithQtyFrom(productComp);
 
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
final Set<Integer> stockChecked = new HashSet<Integer>();
for (ProductComponent comp : leafItems) {
SQLRowAccessor rowArticleFind = comp.getProduct();
 
SQLRow row = rowArticleFind.asRow();
SQLRowAccessor rowStock = comp.getStock();
int value = 0;
if (row.getBoolean("GESTION_STOCK") && !stockChecked.contains(rowStock.getID())) {
stockChecked.add(rowStock.getID());
 
value = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
} else if (!row.getBoolean("GESTION_STOCK")) {
value = comp.getQty().intValue();
for (SQLRow sqlRow : rows) {
// on récupére l'article qui lui correspond
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (SQLField field : eltArticle.getTable().getFields()) {
if (sqlRow.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field.getName(), sqlRow.getObject(field.getName()));
}
if (value > 0) {
 
SQLInjector inj = SQLInjector.getInjector(row.getTable(), row.getTable().getTable("COMMANDE_ELEMENT"));
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(row));
 
int qte = 1;
BigDecimal qteUV = BigDecimal.ONE;
 
if (row.getObject("ID_UNITE_VENTE") != null && row.getForeignID("ID_UNITE_VENTE") != UniteVenteArticleSQLElement.A_LA_PIECE) {
qteUV = comp.getQty();
} else {
qte = comp.getQty().setScale(0, RoundingMode.HALF_UP).intValue();
}
 
rowValsElt.put("QTE", qte);
rowValsElt.put("QTE_UNITAIRE", qteUV);
 
int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
if (rowArticleFind != null && !rowArticleFind.isUndefined()) {
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC", ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)),
DecimalUtils.HIGH_PRECISION));
// rowValsElt.put("ID_DEVISE",
// rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
map.add(rowArticleFind.getForeign("ID_FOURNISSEUR").asRow(), rowValsElt);
rowValsElt.put("T_PA_TTC",
((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)), DecimalUtils.HIGH_PRECISION));
final SQLRow foreignRow = rowArticleFind.getForeignRow("ID_FOURNISSEUR");
if (foreignRow != null && !foreignRow.isUndefined()) {
rowValsElt.put("ID_DEVISE", foreignRow.getForeignID("ID_DEVISE"));
} else {
rowValsElt.put("ID_DEVISE", rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
}
map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
}
 
}
MouvementStockSQLElement.createCommandeF(map, null, "");
MouvementStockSQLElement.createCommandeF(map, rowCmd.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"), rowCmd.getString("NUMERO") + " - " + rowCmd.getString("NOM"), useCommandeEnCours);
}
});
}
 
/**
* Transfert en BL
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientElementSQLElement.java
16,11 → 16,11
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.UISQLComponent;
66,9 → 66,16
 
@Override
public void actionPerformed(ActionEvent e) {
final List<SQLRow> rows = SQLRowListRSH.fetch(IListe.get(e).getRequest().getPrimaryTable(), IListe.get(e).getSelection().getSelectedIDs());
((CommandeClientSQLElement) getForeignElement("ID_COMMANDE_CLIENT")).transfertEltToCommandeF(rows);
final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
 
createCommandeF(selectedRows);
}
});
}
 
}, true);
rowAction.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
207,7 → 214,6
l.add("NOM");
l.add("ID_COMMANDE_CLIENT");
l.add("ID_ARTICLE");
l.add("ID_DEPOT_STOCK");
l.add("PA_HT");
l.add("PV_HT");
l.add("T_PA_HT");
228,11 → 234,6
*/
public void transfertCommande(List<SQLRowValues> commandeClientEltsRows) {
 
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
 
SQLTable tableCmdElt = getDirectory().getElement("COMMANDE_ELEMENT").getTable();
SQLElement eltArticle = getDirectory().getElement("ARTICLE");
 
239,26 → 240,10
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
List<String> fields2copy = Arrays.asList("CODE", "NOM", "VALEUR_METRIQUE_1", "VALEUR_METRIQUE_2", "VALEUR_METRIQUE_3");
 
Set<Integer> artAdded = new HashSet<Integer>();
// Set<Integer> art = new HashSet<Integer>();
for (SQLRowValues sqlRow : commandeClientEltsRows) {
boolean article = false;
if (sqlRow.getTable().getName().equalsIgnoreCase("ARTICLE")) {
article = true;
}
 
// renderer sur liste des ar
 
// if()
 
/// rowValsElt.put("QTE", sqlRow.getObject("QTE"));
SQLRowAccessor rowArticleFind;
SQLRowValues rowArticle;
int qte = 1;
BigDecimal qteUV = BigDecimal.ONE;
boolean gestionStock = true;
if (!article) {
// on récupére l'article qui lui correspond
rowArticle = new SQLRowValues(eltArticle.getTable());
SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
for (String field : fields2copy) {
// if (sqlRow.getTable().getFieldsName().contains(field.getName())) {
rowArticle.put(field, sqlRow.asRow().getObject(field));
266,43 → 251,54
}
 
int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
rowArticleFind = eltArticle.getTable().getRow(idArticle);
SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
if (rowArticleFind != null && !rowArticleFind.isUndefined()) {
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
 
gestionStock = rowArticleFind.getBoolean("GESTION_STOCK");
if (!gestionStock) {
qte = sqlRow.getInt("QTE");
qteUV = sqlRow.getBigDecimal("QTE_UNITAIRE");
// if()
 
if (sqlRow.getObject("ID_UNITE_VENTE") != null && sqlRow.getForeignID("ID_UNITE_VENTE") != UniteVenteArticleSQLElement.A_LA_PIECE) {
qteUV = qteUV.multiply(new BigDecimal(qte));
qte = 1;
rowValsElt.put("QTE", sqlRow.getObject("QTE"));
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC",
((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)), DecimalUtils.HIGH_PRECISION));
// rowValsElt.put("ID_DEVISE",
// rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
}
} else {
if (rowArticle.getForeign("ID_STOCK") != null && !rowArticle.isForeignEmpty("ID_STOCK")) {
SQLRowAccessor rowStock = rowArticle.getForeign("ID_STOCK");
qte = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
 
}
// TODO
MouvementStockSQLElement.createCommandeF(map, null, "", false);
}
} else {
rowArticleFind = sqlRow;
rowArticle = sqlRow;
if (rowArticle.getForeign("ID_STOCK") != null && !rowArticle.isForeignEmpty("ID_STOCK")) {
SQLRowAccessor rowStock = rowArticle.getForeign("ID_STOCK");
qte = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
}
}
if (rowArticleFind != null && !rowArticleFind.isUndefined() && (!gestionStock || !artAdded.contains(rowArticleFind.getID()))) {
 
artAdded.add(rowArticleFind.getID());
public void createCommandeF(final List<? extends SQLRowAccessor> rowsItems) {
 
SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind.asRow()));
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
@Override
public void run() {
final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
final Set<Integer> stockChecked = new HashSet<Integer>();
for (SQLRowAccessor rowItem : rowsItems) {
if (rowItem.getObject("ID_ARTICLE") != null && !rowItem.isForeignEmpty("ID_ARTICLE")) {
SQLRowAccessor rowArticleFind = rowItem.getForeign("ID_ARTICLE");
 
rowValsElt.put("QTE", qte);
rowValsElt.put("QTE_UNITAIRE", qteUV);
SQLRow row = rowArticleFind.asRow();
SQLRowAccessor rowStock = StockSQLElement.getStock(rowItem);
if (!stockChecked.contains(rowStock.getID())) {
stockChecked.add(rowStock.getID());
 
int value = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
 
if (value > 0) {
 
SQLInjector inj = SQLInjector.getInjector(row.getTable(), row.getTable().getTable("COMMANDE_ELEMENT"));
SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(row));
 
rowValsElt.put("QTE", value);
rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
rowValsElt.put("T_PA_TTC", ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)),
309,13 → 305,15
DecimalUtils.HIGH_PRECISION));
// rowValsElt.put("ID_DEVISE",
// rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
map.add(rowArticleFind.asRow().getForeignRow("ID_FOURNISSEUR"), rowValsElt);
map.add(rowArticleFind.getForeign("ID_FOURNISSEUR").asRow(), rowValsElt);
}
}
 
MouvementStockSQLElement.createCommandeF(map, null, "");
}
}
MouvementStockSQLElement.createCommandeF(map, null, "", false);
}
});
 
}
 
protected List<String> getComboFields() {
340,7 → 338,7
res.putCollection("ID_COMMANDE_CLIENT", "NUMERO", "DATE", "DATE_LIVRAISON_PREV", "ID_CLIENT");
 
if (getTable().contains("ID_ARTICLE")) {
res.putCollection("ID_ARTICLE", "GESTION_STOCK", "ID_FAMILLE_ARTICLE", "ID_FOURNISSEUR");
res.putCollection("ID_ARTICLE", "ID_FAMILLE_ARTICLE", "ID_FOURNISSEUR");
}
res.putCollection(null, "NOM");
return res;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/EcheanceClientSQLElement.java
18,11 → 18,7
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.core.customerrelationship.customer.element.RelanceSQLElement;
import org.openconcerto.erp.core.customerrelationship.mail.EmailTemplate;
import org.openconcerto.erp.core.customerrelationship.mail.ValueListener;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.EncaisserMontantSQLElement;
import org.openconcerto.erp.core.sales.invoice.action.ImportReglementSage;
import org.openconcerto.erp.core.sales.invoice.report.MailRelanceCreator;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.rights.ComptaUserRight;
30,25 → 26,18
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Link;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
60,15 → 49,11
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.EmailComposer;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.SwingThreadUtils;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.ListMap;
 
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
77,7 → 62,6
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
87,6 → 71,7
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
public class EcheanceClientSQLElement extends ComptaSQLConfElement {
 
126,90 → 111,16
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Envoyer un mail de relance") {
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Envoyer un mail") {
 
@Override
public void actionPerformed(ActionEvent e) {
final IListe iListe = IListe.get(e);
if (iListe.getSelectedRows().isEmpty()) {
int result = JOptionPane.showConfirmDialog(iListe,
"Souhaitez vous envoyer un email de relance pour toutes les factures\ndont l'échéance est dépassée?\nLes relances ne seront pas envoyées si les factures ont déjà  une relance de moins d'un mois. ",
"Relance automatique", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
EmailTemplate.askTemplate(iListe, getTable().getDBRoot(), new ValueListener() {
public void actionPerformed(ActionEvent arg0) {
 
@Override
public void valueSelected(Object value) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
EmailTemplate template = (EmailTemplate) value;
final SQLTable table = getTable();
final SQLRowValues v = new SQLRowValues(table);
v.putNulls(table.getFieldsName());
Where w = new Where(table.getField("REGLE"), "=", false);
w = w.and(new Where(table.getField("REG_COMPTA"), "=", false));
final Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
w = w.and(new Where(table.getField("DATE_LAST_RELANCE"), ">", c.getTime()));
w = w.and(new Where(table.getField("DATE"), "<=", Calendar.getInstance().getTime()));
List<SQLRowValues> rowValues = SQLRowValuesListFetcher.create(v).fetch(w);
if (rowValues.isEmpty()) {
JOptionPane.showMessageDialog(iListe, "Aucune relance à  envoyer.");
} else {
for (SQLRowValues row : rowValues) {
sendMail(row.asRow(), template);
SQLRow row = IListe.get(arg0).fetchSelectedRow();
sendMail(row);
}
}
} catch (Exception e) {
ExceptionHandler.handle("erreur lors de l'envoi", e);
}
 
}
});
t.setDaemon(true);
t.setName("email relance");
t.start();
 
}
});
 
}
 
} else {
final SQLTable primaryTable = iListe.getRequest().getPrimaryTable();
final List<Integer> selectedIDs = iListe.getSelection().getSelectedIDs();
EmailTemplate.askTemplate(iListe, getTable().getDBRoot(), new ValueListener() {
 
@Override
public void valueSelected(Object value) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
EmailTemplate template = (EmailTemplate) value;
final List<SQLRow> rows = SQLRowListRSH.fetch(primaryTable, selectedIDs);
for (SQLRow row : rows) {
sendMail(row, template);
}
} catch (Exception e) {
ExceptionHandler.handle("erreur lors de l'envoi", e);
}
 
}
});
t.setDaemon(true);
t.setName("email relance selection");
t.start();
 
}
});
 
}
}
}, true);
action.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
}, false);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
 
232,7 → 143,6
}
}
}, false) {
 
@Override
public boolean enabledFor(List<SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
274,7 → 184,6
}
}
}, false) {
 
@Override
public boolean enabledFor(List<SQLRowValues> selection) {
if (selection != null && selection.size() == 1) {
284,63 → 193,24
return true;
}
}
 
};
getRowActions().add(actionRegul);
}
 
RowAction actionImport = new RowAction(new AbstractAction("Importer") {
 
public void actionPerformed(ActionEvent e) {
 
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource());
final FileDialog fd = new FileDialog(frame, "Import XML des réglements Sage", FileDialog.LOAD);
if (fd.getFile() != null) {
try {
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(final SQLDataSource ds) throws SQLException, IOException {
 
ImportReglementSage sageImporter = new ImportReglementSage(getDirectory().getElement(EncaisserMontantSQLElement.class));
try {
sageImporter.importFromFile(new File(fd.getDirectory(), fd.getFile()));
} catch (Exception e) {
e.printStackTrace();
new SQLException(e);
}
return null;
}
 
});
JOptionPane.showMessageDialog(null, "Import des paiements terminés!");
} catch (IOException exn) {
ExceptionHandler.handle(frame, "Erreur lors de la lecture du fichier", exn);
} catch (SQLException exn) {
ExceptionHandler.handle(frame, "Erreur lors de l'insertion des paiements dans la base", exn);
}
 
}
fd.setVisible(true);
}
}, true) {
@Override
public boolean enabledFor(List<SQLRowValues> selection) {
return true;
}
};
getRowActions().add(actionImport);
private void sendMail(final SQLRow row) {
 
}
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
 
if (row != null) {
 
private void sendMail(final SQLRow row, EmailTemplate template) throws Exception {
 
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
 
int idMvtSource = MouvementSQLElement.getSourceId(row.getInt("ID_MOUVEMENT"));
SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
 
if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
// this.relancer.setEnabled(false);
return;
}
int idFact = rowMvtSource.getInt("IDSOURCE");
372,12 → 242,16
}
final String adresseMail = mail;
 
MailRelanceCreator creator = new MailRelanceCreator(template, row);
final String references = creator.getObject();
final String text = creator.getValue();
MailRelanceCreator creator = new MailRelanceCreator();
final String references = creator.getObject(row);
final String text = creator.getValue(row);
 
final Thread t = new Thread() {
@Override
public void run() {
 
final File f;
 
try {
f = sheet.getOrCreatePDFDocumentFile(true);
 
EmailComposer.getInstance().compose(adresseMail, references, text, f.getAbsoluteFile());
392,7 → 266,7
rowValsR.put("MONTANT", row.getObject("MONTANT"));
rowValsR.put("INFOS", "Email");
rowValsR.put("ID_ECHEANCE_CLIENT", row.getID());
 
try {
rowValsR.insert();
 
SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
413,8 → 287,26
 
rowValsEch.update(row.getID());
 
} catch (SQLException e) {
 
e.printStackTrace();
}
} catch (IOException exn) {
exn.printStackTrace();
} catch (InterruptedException exn) {
exn.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
 
}
};
 
t.start();
}
}
 
@Override
public ListMap<String, String> getShowAs() {
ListMap<String, String> map = new ListMap<String, String>();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/MailRelanceCreator.java
14,10 → 14,11
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.customerrelationship.mail.EmailTemplate;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.preferences.MailRelancePreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.GestionDevise;
 
29,18 → 30,10
 
public class MailRelanceCreator {
 
private final EmailTemplate template;
private final SQLRow rowEcheance;
private final Map<String, String> map;
SQLRow rowEcheance;
 
public MailRelanceCreator(EmailTemplate template, SQLRow row) {
if (template == null) {
template = new EmailTemplate("defautl", getDefaultObject(), getDefaultValue(), true, "dd/MM/yyyy");
}
this.template = template;
this.rowEcheance = row;
public MailRelanceCreator() {
 
this.map = getMapValues();
}
 
public String getDefaultObject() {
57,14 → 50,9
return value;
}
 
private Map<String, String> getMapValues() {
String datePattern = this.template.getDateFormat();
if (datePattern == null || datePattern.trim().isEmpty()) {
datePattern = "dd/MM/yyyy";
}
public Map<String, String> getMapValues(SQLRow rowEch, String datePattern) {
final Map<String, String> map = new HashMap<String, String>();
 
final Map<String, String> map = new HashMap<>();
 
final SQLRow rowSoc = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
final SQLRow rowSocAdresse = rowSoc.getForeignRow("ID_ADRESSE_COMMON");
SQLRow rowUser = rowSoc.getTable().getDBRoot().findTable("USER_COMMON").getRow(UserManager.getUser().getId());
96,7 → 84,7
map.put("SocieteVille", ville);
 
SQLRow rowClient;
final SQLRow clientRowNX = this.rowEcheance.getForeignRow("ID_CLIENT");
final SQLRow clientRowNX = rowEch.getForeignRow("ID_CLIENT");
rowClient = clientRowNX;
SQLRow rowAdresse = rowClient.getForeignRow("ID_ADRESSE");
if (!clientRowNX.isForeignEmpty("ID_ADRESSE_F")) {
130,13 → 118,13
DateFormat dateFormat = new SimpleDateFormat(datePattern);
map.put("RelanceDate", dateFormat.format(d));
 
SQLRow rowFacture = this.rowEcheance.getForeignRow("ID_SAISIE_VENTE_FACTURE");
SQLRow rowFacture = rowEch.getForeignRow("ID_SAISIE_VENTE_FACTURE");
 
 
// Infos facture
Long lTotal = (Long) rowFacture.getObject("T_TTC");
Long lRestant = (Long) this.rowEcheance.getObject("MONTANT");
Long lVerse = Long.valueOf(lTotal.longValue() - lRestant.longValue());
Long lRestant = (Long) rowEch.getObject("MONTANT");
Long lVerse = new Long(lTotal.longValue() - lRestant.longValue());
map.put("FactureNumero", rowFacture.getString("NUMERO"));
map.put("FactureReference", rowFacture.getString("NOM"));
map.put("FactureTotal", GestionDevise.currencyToString(lTotal.longValue(), true));
148,22 → 136,30
SQLRow modeRegRow = rowFacture.getForeignRow("ID_MODE_REGLEMENT");
Date dateEch = ModeDeReglementSQLElement.calculDate(modeRegRow.getInt("AJOURS"), modeRegRow.getInt("LENJOUR"), dFacture);
map.put("FactureDateEcheance", dateFormat.format(dateEch));
map.put("message", "");
 
return map;
}
 
public String getObject() {
return fill(this.template.getTitle());
public String getObject(SQLRow rowEch) {
SQLPreferences prefs = new SQLPreferences(rowEch.getTable().getDBRoot());
String object = prefs.get(MailRelancePreferencePanel.MAIL_RELANCE_OBJET, getDefaultObject());
String date = prefs.get(MailRelancePreferencePanel.MAIL_RELANCE_DATE_PATTERN, "dd/MM/yyyy");
return fill(rowEch, date, object);
}
 
public String getValue() {
return fill(this.template.getText());
public String getValue(SQLRow rowEch) {
SQLPreferences prefs = new SQLPreferences(rowEch.getTable().getDBRoot());
String value = prefs.get(MailRelancePreferencePanel.MAIL_RELANCE, getDefaultValue());
String date = prefs.get(MailRelancePreferencePanel.MAIL_RELANCE_DATE_PATTERN, "dd/MM/yyyy");
return fill(rowEch, date, value);
}
 
private String fill(String string) {
private String fill(SQLRow rowEch, String datePattern, String string) {
 
Map<String, String> map = getMapValues(rowEch, datePattern);
String result = string;
for (String key : this.map.keySet()) {
result = result.replace("{" + key + "}", this.map.get(key));
for (String key : map.keySet()) {
result = result.replace("{" + key + "}", map.get(key));
}
return result;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/report/ReportingStockXmlSheet.java
13,6 → 13,7
package org.openconcerto.erp.core.sales.invoice.report;
 
import org.openconcerto.erp.core.sales.invoice.report.ReportingVenteXmlSheet.Line;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
36,6 → 37,8
import java.util.Map;
import java.util.TreeMap;
 
import javax.swing.JProgressBar;
 
public class ReportingStockXmlSheet extends AbstractListeSheetXml {
 
private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
122,12 → 125,11
Float qte = vals.getForeign("ID_STOCK").getFloat("QTE_REEL");
BigDecimal ha = BigDecimal.ZERO;
if (qte > 0) {
final BigDecimal puHA = vals.getBigDecimal("PA_HT");
ha = puHA.multiply(new BigDecimal(qte));
ha = vals.getBigDecimal("PA_HT").multiply(new BigDecimal(qte));
 
int idFamille = vals.getForeignID("ID_FAMILLE_ARTICLE");
SQLRow rowF = mapF.get(idFamille);
Line lineArt = new Line(vals.getString("NOM"), vals.getString("CODE"), puHA, ha, qte);
Line lineArt = new Line(vals.getString("NOM"), vals.getString("CODE"), ha, qte);
 
// Init des lines familles
 
223,18 → 225,13
 
class Line {
final private String nomArt, codeArt;
private BigDecimal totalHA, puHA;
private BigDecimal totalHA;
private Float qte;
 
public Line(String nomArt, String codeArt, BigDecimal totalHA, Float qte) {
this(nomArt, codeArt, BigDecimal.ZERO, totalHA, qte);
}
 
public Line(String nomArt, String codeArt, BigDecimal puHA, BigDecimal totalHA, Float qte) {
this.nomArt = nomArt;
this.codeArt = codeArt;
this.totalHA = totalHA;
this.puHA = puHA;
this.qte = qte;
}
 
246,10 → 243,6
return codeArt;
}
 
public BigDecimal getPuHA() {
return puHA;
}
 
public String getNomArt() {
return nomArt;
}
270,7 → 263,6
m.put("CODE", getCodeArt());
m.put("NOM", getNomArt());
m.put("QTE", getQte());
m.put("PU_HA", getPuHA());
m.put("TOTAL_HA", getTotalHA());
return m;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ImportReglementSageAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ImportReglementSage.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/GenListeVentePanel.java
31,8 → 31,6
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
import javax.swing.JButton;
111,40 → 109,16
sel.addSelectStar(tableFact);
sel.setDistinct(true);
sel.setWhere(new Where(tableFact.getField("DATE"), GenListeVentePanel.this.du.getDate(), GenListeVentePanel.this.au.getDate()));
List<SQLRow> l = new ArrayList((List<SQLRow>) dataSource.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableFact)));
Collections.sort(l, new Comparator<SQLRow>() {
@Override
public int compare(SQLRow o1, SQLRow o2) {
int dateComp = o1.getDate("DATE&quo