OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 66 → Rev 67

/trunk/OpenConcerto/.classpath
11,7 → 11,6
<classpathentry exported="true" kind="lib" path="lib/commons-pool-1.5.5.jar"/>
<classpathentry exported="true" kind="lib" path="lib/forms-1.0.5.jar"/>
<classpathentry exported="true" kind="lib" path="lib/ganymed-ssh2-build250.jar"/>
<classpathentry exported="true" kind="lib" path="lib/h2-1.2.138.jar"/>
<classpathentry exported="true" kind="lib" path="lib/iText-2.1.5.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jakarta-oro-2.0.8.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jaxen-1.1.jar"/>
30,5 → 29,6
<classpathentry kind="lib" path="lib/jcip-annotations.jar"/>
<classpathentry kind="lib" path="lib/fb-annotations-2.0.0.jar"/>
<classpathentry kind="lib" path="lib/jOpenDocument-1.3b2.jar"/>
<classpathentry kind="lib" path="lib/h2-1.3.168.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
/trunk/OpenConcerto/lib/h2-1.2.138.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/h2-1.3.168.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/h2-1.3.168.jar
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/src/org/jopenchart/piechart/PieChartWithSeparatedLabels.java
New file
0,0 → 1,98
package org.jopenchart.piechart;
 
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
 
import org.jopenchart.DataModel1D;
 
public class PieChartWithSeparatedLabels extends PieChart {
 
public void renderPlot(Graphics2D g) {
 
g.setColor(Color.RED);
 
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int xCenter = getCenterX();
int yCenter = getCenterY();
 
DataModel1D model1 = (DataModel1D) this.getDataModel();
double total = getTotalValue().doubleValue();
 
double space = 0.0D;
 
int stop = model1.getSize();
computeColorsAndSpaces();
 
int maxSpace = (int) spaces[0];
 
int height2 = Math.min(xCenter, yCenter) - maxSpace - this.getMaxLabelHeight(g) / 2 - 2;
int width2 = height2;
int posX = (getCenterX() - width2);
int squareSize = this.getMaxLabelHeight(g);
if (posX < this.getMaxLabelWidth(g) + 4 * squareSize) {
posX = this.getMaxLabelWidth(g) + 4 * squareSize;
}
int posY = (getCenterY() - width2);
 
double ratio = 360 / total;
double startAngle = 0D;
for (int i = 0; i < stop; i++) {
Number n = model1.getValueAt(i);
if (n == null) {
continue;
}
int angle = (int) Math.round(n.doubleValue() * ratio);
double moveAngle = startAngle - angle / 2D;
double angleRadian = ((moveAngle) * Math.PI * 2) / 360;
 
double current_space = spaces[i];
int x = posX + width2 / 2 + (int) ((Math.cos(angleRadian)) * current_space);
int y = posY + height2 / 2 + (int) ((-Math.sin(angleRadian)) * current_space);
 
g.setColor(colors[i]);
g.setStroke(new BasicStroke(width2 - this.innerWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 12.0f, null, 10.0f));
g.drawArc(x, y, width2, height2, (int) Math.round(startAngle), -angle);
 
g.setStroke(new BasicStroke());
if (i < labels.size()) {
final String label = labels.get(i).getLabel();
 
int xLabel = squareSize * 2;
int yLabel = (int) (i * (squareSize * 1.5f) + squareSize / 2);
g.fillRect(squareSize / 2, yLabel, squareSize, squareSize);
 
g.setColor(Color.GRAY);
 
g.drawString(label, xLabel, (int) (yLabel + squareSize * 0.8f));
}
startAngle -= angle;
 
}
 
if (this.getSeparatorColor() != null) {
startAngle = 0D;
g.setStroke(new BasicStroke(2f));
g.setColor(this.getSeparatorColor());
 
for (int i = 0; i < stop; i++) {
Number n = model1.getValueAt(i);
if (n == null) {
continue;
}
int angle = (int) Math.round(n.doubleValue() * ratio);
 
double angleRadian = ((startAngle) * Math.PI * 2) / 360;
double current_space = spaces[i];
 
int x2 = posX + width2 + (int) ((Math.cos(angleRadian)) * (width2 + current_space + 2));
int y2 = posY + height2 + (int) ((-Math.sin(angleRadian)) * (height2 + current_space + 2));
g.drawLine(posX + width2, posY + height2, x2, y2);
startAngle -= angle;
}
}
 
}
 
}
/trunk/OpenConcerto/src/org/jopenchart/piechart/PieChart.java
7,7 → 7,9
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.jopenchart.Chart;
import org.jopenchart.DataModel1D;
14,16 → 16,21
import org.jopenchart.Label;
 
public class PieChart extends Chart {
private final List<Label> labels = new ArrayList<Label>();
protected final List<Label> labels = new ArrayList<Label>();
 
private Color separatorColor = Color.WHITE;
 
private int innerWidth;
protected int innerWidth;
 
private int innerHeight;
 
private Color innerColor;
protected Color innerColor;
protected Map<Label, Color> colorMap = new HashMap<Label, Color>();
 
protected Color[] colors;
 
protected double[] spaces;
 
public void setData(List<Number> data) {
DataModel1D m = new DataModel1D();
m.addAll(data);
55,26 → 62,9
DataModel1D model1 = (DataModel1D) this.getDataModel();
double total = getTotalValue().doubleValue();
 
double space = 0.0D;
 
int stop = model1.getSize();
Color[] colors = new Color[stop];
double[] spaces = new double[stop];
Color origine = this.getColor(0);
 
double mR = origine.getRed();
double mV = origine.getGreen();
double mB = origine.getBlue();
double dR = (255D - origine.getRed()) / stop;
double dV = (255D - origine.getGreen()) / stop;
double dB = (255D - origine.getBlue()) / stop;
for (int i = 0; i < stop; i++) {
colors[i] = new Color((int) mR, (int) mV, (int) mB);
mR += dR;
mV += dV;
mB += dB;
spaces[i] = space;
}
computeColorsAndSpaces();
// spaces[0] = 10;
int maxSpace = (int) spaces[0];
 
81,9 → 71,7
int height2 = Math.min(xCenter, yCenter) - maxSpace - this.getMaxLabelHeight(g) / 2 - 2;
int width2 = height2;// Math.min(xCenter, yCenter) - maxSpace;
int posX = (getCenterX() - width2);
int posY = (getCenterY() - width2);// +
// this.getMaxLabelHeight(g);
// g.drawRect(0, 0, posX, posY);
int posY = (getCenterY() - width2);
double ratio = 360 / total;
double startAngle = 0D;
for (int i = 0; i < stop; i++) {
183,12 → 171,46
 
}
 
private int getLabelWidth(Graphics2D g, String label) {
protected void computeColorsAndSpaces() {
double space = 0;
DataModel1D model1 = (DataModel1D) this.getDataModel();
int stop = model1.getSize();
colors = new Color[stop];
spaces = new double[stop];
Color origine = this.getColor(0);
 
double mR = origine.getRed();
double mV = origine.getGreen();
double mB = origine.getBlue();
double dR = (255D - origine.getRed()) / stop;
double dV = (255D - origine.getGreen()) / stop;
double dB = (255D - origine.getBlue()) / stop;
for (int i = 0; i < stop; i++) {
colors[i] = new Color((int) mR, (int) mV, (int) mB);
mR += dR;
mV += dV;
mB += dB;
spaces[i] = space;
}
// Apply user colors
for (int i = 0; i < stop; i++) {
if (i < labels.size()) {
final Label label = labels.get(i);
final Color color = colorMap.get(label);
if (color != null) {
colors[i] = color;
}
}
 
}
}
 
protected int getLabelWidth(Graphics2D g, String label) {
int w = (int) g.getFontMetrics().getStringBounds(label, g).getWidth();
return w;
}
 
private Number getTotalValue() {
protected Number getTotalValue() {
DataModel1D model1 = (DataModel1D) this.getDataModel();
double total = 0D;
for (int i = 0; i < model1.getSize(); i++) {
199,11 → 221,11
return total;
}
 
private int getCenterY() {
protected int getCenterY() {
return this.getChartRectangle().height / 2;
}
 
private int getCenterX() {
protected int getCenterX() {
return this.getChartRectangle().width / 2;
}
 
250,7 → 272,7
return separatorColor;
}
 
private int getMaxLabelHeight(Graphics2D g) {
protected int getMaxLabelHeight(Graphics2D g) {
int max = 0;
for (Label label : this.labels) {
int w = (int) g.getFontMetrics().getStringBounds(label.getLabel(), g).getHeight();
276,6 → 298,11
this.labels.add(label);
}
 
public void addLabel(Label label, Color red) {
colorMap.put(label, red);
this.labels.add(label);
}
 
public void setInnerDimension(int width, int height) {
this.innerWidth = width;
this.innerHeight = height;
/trunk/OpenConcerto/src/org/jopenchart/LeftAxis.java
2,6 → 2,7
 
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.List;
 
public class LeftAxis extends Axis {
 
15,6 → 16,17
}
 
public void render(Graphics2D g) {
List<AxisLabel> l = this.getLabels();
Number max = 0;
for (AxisLabel axisLabel : l) {
Number value = axisLabel.getValue();
if (value != null && value.doubleValue() > max.doubleValue()) {
max = value;
}
}
 
double ratioy = (double) this.getHeight() / max.doubleValue();
 
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
double dy = (double) this.getHeight() / (this.getLabels().size() - 1);
double y = this.getHeight() + this.getY();
21,12 → 33,17
for (AxisLabel label : this.getLabels()) {
g.setColor(this.getColor());
 
g.drawLine(this.getX() + this.getWidth() - getMarkerLenght() - 1, (int) y, this.getX() + this.getWidth() - 1, (int) y);
int minXValue = 0;
int y1 = (int) y;
if (max.intValue() > 0)
y1 = getY() + getHeight() - (int) ((label.getValue().doubleValue() - minXValue) * ratioy);
 
g.drawLine(this.getX() + this.getWidth() - getMarkerLenght() - 1, (int) y1, this.getX() + this.getWidth() - 1, (int) y1);
int labelH = (int) g.getFontMetrics().getStringBounds(label.getLabel(), g).getHeight() / 2 - 1;
int labelW = (int) g.getFontMetrics().getStringBounds(label.getLabel(), g).getWidth();
 
g.setColor(label.getColor());
g.drawString(label.getLabel(), this.getX() + this.getWidth() - this.getMarkerLenght() - labelW - 2, labelH + (int) y);
g.drawString(label.getLabel(), this.getX() + this.getWidth() - this.getMarkerLenght() - labelW - 2, labelH + (int) y1);
 
y -= dy;
}
34,5 → 51,4
g.drawLine(this.getX() + this.getWidth() - 1, this.getY(), this.getX() + this.getWidth() - 1, this.getY() + this.getHeight());
 
}
 
}
/trunk/OpenConcerto/src/org/jopenchart/linechart/LineChart.java
39,10 → 39,12
 
private List<ShapeMarker> markers = new ArrayList<ShapeMarker>();
 
private Stroke defaultStroke = new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
 
public LineChart() {
 
left = new LeftAxis();
bottom = new BottomAxis();
bottom = new BottomAxis(true);
gridStroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[] { 5, 3 }, 0);
 
}
49,10 → 51,14
 
public Stroke getStroke(int index) {
if (index >= lineStrokes.size())
return new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
return defaultStroke;
return lineStrokes.get(index);
}
 
public void setDefaultLineStroke(Stroke s) {
this.defaultStroke = s;
}
 
public DataModelMultiple getDataModel() {
return (DataModelMultiple) this.model;
}
106,7 → 112,7
}
 
public void setBottomAxis(Axis axis) {
bottom = new BottomAxis(axis);
bottom = new BottomAxis(axis, true);
 
}
 
/trunk/OpenConcerto/src/org/jopenchart/BottomAxis.java
5,13 → 5,17
 
public class BottomAxis extends Axis {
 
public BottomAxis(Axis a) {
boolean leftAlign;
 
public BottomAxis(Axis a, boolean leftAlign) {
super("x");
this.addLabels(a.getLabels());
this.leftAlign = leftAlign;
}
 
public BottomAxis() {
public BottomAxis(boolean leftAlign) {
super("x");
this.leftAlign = leftAlign;
}
 
public void render(Graphics2D g) {
27,12 → 31,13
} else {
x = i * dx;
}
g.drawLine((int) x, getY(), (int) x, getY() + getMarkerLenght());
int alignment = (this.leftAlign ? getX() : 0);
g.drawLine(alignment + (int) x, getY(), alignment + (int) x, getY() + getMarkerLenght());
int labelH = g.getFontMetrics().getAscent();
double labelW = (int) g.getFontMetrics().getStringBounds(label.getLabel(), g).getWidth() / 2 - 1;
// Label
g.setColor(label.getColor());
g.drawString(label.getLabel(), (int) (x - labelW), labelH + getY() + getMarkerLenght() + getMarkerSpacing());
g.drawString(label.getLabel(), alignment + (int) (x - labelW), labelH + getY() + getMarkerLenght() + getMarkerSpacing());
 
}
g.setColor(this.getColor());
/trunk/OpenConcerto/src/org/jopenchart/sample/devguide/PieChartSample.java
1,5 → 1,6
package org.jopenchart.sample.devguide;
 
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
 
8,6 → 9,7
import org.jopenchart.ChartPanel;
import org.jopenchart.Label;
import org.jopenchart.piechart.PieChart;
import org.jopenchart.piechart.PieChartWithSeparatedLabels;
 
public class PieChartSample {
/**
14,8 → 16,8
* @param args
*/
public static void main(String[] args) {
chart1();
chart2();
chart3();
// chart2();
}
 
private static void chart1() {
58,4 → 60,35
f.setLocation(0, 200);
f.setVisible(true);
}
 
private static void chart3() {
PieChartWithSeparatedLabels c = new PieChartWithSeparatedLabels();
c.addLabel(new Label("AAAAAA"), Color.red);
c.addLabel(new Label("BBBB"));
c.addLabel(new Label("CCCCCCCCCCCCCCCCCCCCCCCCCCCC"));
c.addLabel(new Label("D"));
c.addLabel(new Label("EEE"));
c.addLabel(new Label("FFF"));
c.addLabel(new Label("GG"));
c.addLabel(new Label("HHH"));
c.setDimension(new Dimension(400, 200));
 
ArrayList<Number> l = new ArrayList<Number>();
l.add(100);
l.add(50);
l.add(10);
l.add(5);
l.add(2);
l.add(2);
l.add(2);
l.add(2);
c.setData(l);
ChartPanel panel = new ChartPanel(c);
JFrame f = new JFrame("Test");
f.setContentPane(panel);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocation(0, 200);
f.setVisible(true);
}
}
/trunk/OpenConcerto/src/org/jopenchart/Axis.java
143,4 → 143,8
 
}
 
public void setMarkerLenght(int markerLenght) {
this.markerLenght = markerLenght;
}
 
}
/trunk/OpenConcerto/src/org/jopenchart/barchart/VerticalBarChart.java
12,7 → 12,7
public class VerticalBarChart extends BarChart {
public VerticalBarChart() {
left = new LeftAxis();
bottom = new BottomAxis();
bottom = new BottomAxis(false);
}
 
public void setLeftAxis(Axis axis) {
22,7 → 22,7
}
 
public void setBottomAxis(Axis axis) {
this.bottom = new BottomAxis(axis);
this.bottom = new BottomAxis(axis, false);
this.bottom.setChart(this);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/ITreeSelection.java
16,15 → 16,19
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTableListener;
import org.openconcerto.sql.model.UndefinedRowValuesCache;
import org.openconcerto.sql.request.SQLRowItemView;
import org.openconcerto.sql.sqlobject.itemview.RowItemViewComponent;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.valuewrapper.ValueWrapper;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.SwingWorker2;
import org.openconcerto.utils.checks.EmptyListener;
import org.openconcerto.utils.checks.EmptyObject;
import org.openconcerto.utils.checks.EmptyObjectHelper;
40,6 → 44,7
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
 
import javax.swing.AbstractAction;
import javax.swing.JComponent;
53,7 → 58,6
import javax.swing.tree.TreeSelectionModel;
 
import org.apache.commons.collections.Predicate;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
// TODO Drag'n drop des nodes
public class ITreeSelection extends JTree implements MouseListener, EmptyObject, ValueWrapper<Integer>, RowItemViewComponent {
101,13 → 105,12
if (this.element == null) {
this.rootNode = new ITreeSelectionNode(null);
} else {
SQLRow row = this.element.getTable().getRow(element.getTable().getUndefinedID());
SQLRowValues row = UndefinedRowValuesCache.getInstance().getDefaultRowValues(element.getTable());
this.rootNode = new ITreeSelectionNode(row);
}
this.model = new DefaultTreeModel(this.rootNode);
this.setModel(this.model);
loadTree();
this.expandRow(0);
setTableListener();
this.addMouseListener(this);
}
330,21 → 333,37
 
private void loadTree() {
 
SQLTable table = this.element.getTable();
SQLSelect sel = new SQLSelect(table.getBase());
SwingWorker2<List<SQLRow>, Object> worker = new SwingWorker2<List<SQLRow>, Object>() {
@Override
protected List<SQLRow> doInBackground() throws Exception {
SQLTable table = element.getTable();
SQLSelect sel = new SQLSelect();
sel.addSelectStar(table);
 
sel.addSelect(table.getKey());
sel.addSelect(table.getField("ID_" + table.getName() + "_PERE"));
return SQLRowListRSH.execute(sel);
}
 
List l = (List) table.getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
 
@Override
protected void done() {
List<SQLRow> l;
try {
l = get();
if (l != null) {
for (int i = 0; i < l.size(); i++) {
Object[] tmp = (Object[]) l.get(i);
addNewNode(((Number) tmp[0]).intValue(), ((Number) tmp[1]).intValue());
SQLRow row = l.get(i);
addNewNode(row, row.getInt("ID_" + element.getTable().getName() + "_PERE"));
}
expandRow(0);
}
} catch (InterruptedException e) {
ExceptionHandler.handle("", e);
} catch (ExecutionException e) {
ExceptionHandler.handle("", e);
}
}
};
worker.execute();
}
 
/**
* Ajoute une famille dans l'arbre
352,14 → 371,13
* @param id
* @param idPere
*/
private void addNewNode(int id, int idPere) {
SQLTable table = this.element.getTable();
private void addNewNode(SQLRow row, int idPere) {
 
ITreeSelectionNode nodePere = this.mapNode.get(Integer.valueOf(idPere));
SQLRow row = table.getRow(id);
ITreeSelectionNode newNode = new ITreeSelectionNode(row);
this.mapNode.put(Integer.valueOf(id), newNode);
this.mapNode.put(row.getID(), newNode);
 
if (id > 1) {
if (row != null && !row.isUndefined()) {
if (nodePere != null && idPere > 1) {
addNode(newNode, nodePere);
} else {
444,7 → 462,7
SQLRow row = table.getRow(id);
int idPere = row.getInt("ID_" + element.getTable().getName() + "_PERE");
 
addNewNode(id, idPere);
addNewNode(row, idPere);
}
 
public void rowDeleted(SQLTable table, int id) {
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/ITreeSelectionNode.java
16,6 → 16,7
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.util.List;
 
23,9 → 24,9
 
public class ITreeSelectionNode extends DefaultMutableTreeNode {
 
SQLRow row;
SQLRowAccessor row;
 
public ITreeSelectionNode(SQLRow row) {
public ITreeSelectionNode(SQLRowAccessor row) {
super();
this.row = row;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/ListeFastPrintFrame.java
180,6 → 180,7
ListeFastPrintFrame.this.operation.setText("Impression du document " + bSheet.getGeneratedFile());
}
});
 
bSheet.fastPrintDocument(copies);
final int progress = ++i;
SwingUtilities.invokeLater(new Runnable() {
199,7 → 200,7
}
});
}
});
}, "Impressions multiple");
this.thread.start();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/UserExitPanel.java
15,6 → 15,7
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.preferences.BackupNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.utils.BackupPanel;
130,6 → 131,7
 
private void closeGNx() {
UserExit.closeAllWindows(null);
ModuleManager.tearDown();
ComptaPropsConfiguration.closeOOConnexion();
// ((JFrame) SwingUtilities.getRoot(UserExitingPanel.this)).dispose();
if (Gestion.pgFrameStart != null) {
233,6 → 235,7
public void run() {
try {
// 5 s d'attente
// TODO make ModuleManager.install() atomic
Thread.sleep(5 * 1000);
System.err.println("Warning: Forcing exit");
Frame[] l = Frame.getFrames();
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/ChargementCreationSocietePanel.java
16,6 → 16,8
import org.openconcerto.erp.utils.ActionDB;
import org.openconcerto.erp.utils.StatusListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSchema;
29,7 → 31,6
import java.awt.GridBagLayout;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
112,64 → 113,46
private void importationPlanComptable(int id, int typePCG) {
 
SQLRow rowSociete = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON").getRow(id);
// SQLBase base = Configuration.getInstance().getBase();
 
// FIXME by Sylvain comme on a deja accede à la base, les nouvelles tables non pas étaient
// FIXME by Sylvain comme on a déjà accede à la base, les nouvelles tables n'ont pas été
// rechargées
SQLSchema baseNewSociete = Configuration.getInstance().getBase().getSchema(rowSociete.getString("DATABASE_NAME"));
final SQLSchema baseNewSociete = Configuration.getInstance().getBase().getSchema(rowSociete.getString("DATABASE_NAME"));
 
SQLTable tableComptePCG = baseNewSociete.getTable("COMPTE_PCG");
SQLSelect sel = new SQLSelect(baseNewSociete.getBase());
final SQLSelect sel = new SQLSelect();
sel.addSelect(tableComptePCG.getField("NUMERO"));
sel.addSelect(tableComptePCG.getField("NOM"));
sel.addSelect(tableComptePCG.getField("INFOS"));
 
// StringBuffer req = new StringBuffer("SELECT NUMERO, NOM, INFOS FROM \"" +
// rowSociete.getString("DATABASE_NAME") + "\".COMPTE_PCG WHERE ID > 1 AND ARCHIVE = 0 AND
// ");
 
if (typePCG == 0) {
sel.setWhere(new Where(tableComptePCG.getField("ID_TYPE_COMPTE_PCG_BASE"), "!=", 1));
} else {
if (typePCG == 1) {
} else if (typePCG == 1) {
sel.setWhere(new Where(tableComptePCG.getField("ID_TYPE_COMPTE_PCG_AB"), "!=", 1));
}
}
List tmpCpt = baseNewSociete.getBase().getDataSource().execute(sel.asString());
 
try {
baseNewSociete.getBase().getDataSource().useConnection(new ConnectionHandlerNoSetup<Object, SQLException>() {
 
@Override
public Object handle(SQLDataSource ds) throws SQLException, SQLException {
String insert = "INSERT INTO \"" + baseNewSociete.getName() + "\".\"COMPTE_PCE\" (\"NUMERO\", \"NOM\", \"INFOS\") VALUES (?, ?, ?)";
PreparedStatement stmt = baseNewSociete.getBase().getDataSource().getNewConnection().prepareStatement(insert);
 
PreparedStatement stmt = ds.getConnection().prepareStatement(insert);
List tmpCpt = baseNewSociete.getBase().getDataSource().execute(sel.asString());
for (int i = 0; i < tmpCpt.size(); i++) {
Map tmp = (HashMap) tmpCpt.get(i);
 
// StringBuffer insert = new StringBuffer("INSERT INTO \"" +
// baseNewSociete.getName() + "\".\"COMPTE_PCE\" (\"NUMERO\", \"NOM\", \"INFOS\")
// VALUES (");
 
Map tmp = (Map) tmpCpt.get(i);
String numero = (tmp.get("NUMERO") == null) ? "" : tmp.get("NUMERO").toString();
stmt.setString(1, numero);
 
// insert.append(SQLSelect.quoteString(numero)/* "'" + numero.replaceAll("'",
// "\\\\'") + "'"*/+", ");
 
String nom = (tmp.get("NOM") == null) ? "" : tmp.get("NOM").toString();
stmt.setString(2, nom);
// insert.append("'" + nom.replaceAll("'", "\\\\'") + "', ");
 
String infos = (tmp.get("INFOS") == null) ? "" : tmp.get("INFOS").toString();
// insert.append("'" + infos.replaceAll("'", "\\\\'") + "') ");
stmt.setString(3, infos);
 
// Statement state =
// baseNewSociete.getBase().getDataSource().getConnection().createStatement();
// stmt.addBatch();
stmt.executeUpdate();
// state.executeUpdate(insert.toString());
 
}
// stmt.executeUpdate();
return null;
}
});
 
} catch (SQLException e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/PanelOOSQLComponent.java
46,7 → 46,7
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
this.setOpaque(false);
SQLPreferences prefs = new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete());
SQLPreferences prefs = SQLPreferences.getMemCached(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete());
if (prefs.getBoolean(GenerationDocGlobalPreferencePanel.MULTIMOD, false)) {
 
if (comp.getElement().getTable().getFieldsName().contains("ID_MODELE")) {
/trunk/OpenConcerto/src/org/openconcerto/erp/panel/compta/ExportRelationExpertPanel.java
16,10 → 16,17
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
40,6 → 47,7
import java.util.List;
 
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
56,31 → 64,34
private JButton buttonClose = new JButton("Fermer");
private JFileChooser fileChooser = new JFileChooser();
private JTextField textDestination = new JTextField();
private ElementComboBox boxJournal = new ElementComboBox(true);
private JCheckBox boxExport = new JCheckBox("Seulement les nouvelles ecritures");
 
public ExportRelationExpertPanel() {
super(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.CENTER;
 
this.add(new JLabelBold("Export des écritures comptables"), c);
 
// Fichier de destination
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.weightx = 0;
this.add(new JLabel("Fichier de destination"), c);
JPanel panelFichier = new JPanel(new GridBagLayout());
GridBagConstraints cFic = new DefaultGridBagConstraints();
panelFichier.add(new JLabel("Dossier de destination"), cFic);
cFic.gridx++;
cFic.weightx = 1;
panelFichier.add(textDestination, cFic);
 
c.gridx++;
c.weightx = 1;
this.add(textDestination, c);
final JButton buttonChoose = new JButton("...");
cFic.gridx++;
cFic.weightx = 0;
cFic.fill = GridBagConstraints.NONE;
panelFichier.add(buttonChoose, cFic);
 
final JButton buttonChoose = new JButton("...");
c.gridx++;
c.weightx = 0;
this.add(buttonChoose, c);
buttonGen.setEnabled(false);
this.textDestination.setEditable(false);
 
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
buttonChoose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
92,13 → 103,19
buttonGen.setEnabled(answer == JFileChooser.APPROVE_OPTION);
}
});
 
c.gridy++;
c.weightx = 1;
this.add(panelFichier, c);
 
c.gridx = 0;
c.gridwidth = 1;
c.gridy++;
c.anchor = GridBagConstraints.WEST;
this.add(new JLabel("du"), c);
c.anchor = GridBagConstraints.EAST;
this.add(new JLabel("Période du"), c);
 
c.gridx++;
c.anchor = GridBagConstraints.WEST;
this.du = new JDate(true);
this.add(this.du, c);
 
109,16 → 126,39
this.au = new JDate(true);
this.add(this.au, c);
 
boxExport.setSelected(true);
c.gridy++;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(boxExport, c);
 
JPanel panelButton = new JPanel();
SQLElement elt = Configuration.getInstance().getDirectory().getElement(JournalSQLElement.class);
ComboSQLRequest comboRequest = elt.getComboRequest(true);
comboRequest.setUndefLabel("Tous");
boxJournal.init(elt, comboRequest);
c.gridy++;
c.gridx = 0;
c.weightx = 0;
c.gridwidth = 1;
this.add(new JLabel("Ecritures du journal"), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
boxJournal.setValue(JournalSQLElement.VENTES);
this.add(boxJournal, c);
 
c.gridy++;
c.weightx = 1;
c.gridx = 0;
c.gridwidth = 1;
final JPanel panelButton = new JPanel();
panelButton.add(this.buttonGen);
panelButton.add(this.buttonClose);
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
c.anchor = GridBagConstraints.SOUTHEAST;
c.weightx = 0;
c.weighty = 1;
this.add(panelButton, c);
this.buttonGen.addActionListener(this);
this.buttonClose.addActionListener(this);
129,22 → 169,26
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.buttonGen) {
File fOut = fileChooser.getSelectedFile();
Date toDay = new Date();
DateFormat format = new SimpleDateFormat("ddMMyyyy_HHMMSS");
File fOut = new File(fileChooser.getSelectedFile(), "ExportOpenConcerto_" + format.format(toDay) + ".xls");
try {
BufferedOutputStream bufOut = new BufferedOutputStream(new FileOutputStream(fOut.getAbsolutePath() + ".xls"));
BufferedOutputStream bufOut = new BufferedOutputStream(new FileOutputStream(fOut.getAbsolutePath()));
 
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
SQLSelect sel = new SQLSelect(base);
SQLSelect sel = new SQLSelect();
 
SQLTable tableEcriture = base.getTable("ECRITURE");
SQLTable tableMouvement = base.getTable("MOUVEMENT");
SQLTable tableCompte = base.getTable("COMPTE_PCE");
SQLTable tableJrnl = base.getTable("JOURNAL");
SQLTable tablePiece = base.getTable("PIECE");
 
sel.addSelect(tableEcriture.getField("NOM"));
sel.addJoin("LEFT", tableEcriture.getField("ID_COMPTE_PCE"));
sel.addJoin("LEFT", tableEcriture.getField("ID_MOUVEMENT"));
sel.addJoin("LEFT", tableEcriture.getField("ID_JOURNAL"));
sel.addJoin("LEFT", tableMouvement.getField("ID_PIECE"));
sel.addSelect(tableMouvement.getField("NUMERO"));
sel.addSelect(tableCompte.getField("NUMERO"));
sel.addSelect(tableEcriture.getField("DATE"));
151,9 → 195,28
sel.addSelect(tableEcriture.getField("DEBIT"));
sel.addSelect(tableEcriture.getField("CREDIT"));
sel.addSelect(tableJrnl.getField("CODE"));
if (tableEcriture.contains("CODE_CLIENT")) {
final SQLField fieldCodeClient = tableEcriture.getField("CODE_CLIENT");
sel.addSelect(fieldCodeClient);
}
sel.addSelect(tablePiece.getField("NOM"));
 
sel.setWhere(new Where(tableEcriture.getField("DATE"), this.du.getDate(), this.au.getDate()).and(new Where(tableEcriture.getField("ID_JOURNAL"), "=", JournalSQLElement.VENTES)));
sel.addFieldOrder(tableEcriture.getField("ID_MOUVEMENT"));
sel.addFieldOrder(tableCompte.getField("NUMERO"));
Where w = new Where(tableEcriture.getField("DATE"), this.du.getDate(), this.au.getDate());
 
if (boxJournal.getSelectedId() != SQLRow.NONEXISTANT_ID) {
Where wJ = new Where(tableEcriture.getField("ID_JOURNAL"), "=", boxJournal.getSelectedId());
w = w.and(wJ);
}
 
if (boxExport.isSelected()) {
Where wJ = new Where(tableEcriture.getField("DATE_EXPORT"), "IS", (Object) null);
w = w.and(wJ);
}
 
sel.setWhere(w);
 
List l = (List) base.getDataSource().execute(sel.asString(), new ArrayListHandler());
System.err.println(sel.asString());
if (l != null) {
192,6 → 255,24
line.append(GestionDevise.currencyToString(credit.longValue()));
line.append('\t');
line.append('E');
 
int z = 7;
final boolean containsCodeClient = tableEcriture.contains("CODE_CLIENT");
if (containsCodeClient) {
// Code Client
String codeClient = "";
if (tmp[z] != null) {
codeClient = tmp[z].toString().trim();
}
line.append('\t');
line.append(codeClient);
z++;
}
 
// Piece
line.append('\t');
line.append(tmp[z].toString().trim());
 
line.append('\r');
line.append('\n');
bufOut.write(line.toString().getBytes());
199,6 → 280,22
}
 
bufOut.close();
 
DBRoot root = Configuration.getInstance().getRoot();
SQLTable tableEcr = root.findTable("ECRITURE");
UpdateBuilder update = new UpdateBuilder(tableEcr);
 
SQLField field = tableEcr.getField("DATE_EXPORT");
update.set("DATE_EXPORT", field.getType().toString(toDay));
if (!boxExport.isSelected()) {
Where wJ = new Where(tableEcriture.getField("DATE_EXPORT"), "IS", (Object) null);
w = w.and(wJ);
}
update.setWhere(w);
String req2 = update.asString();
System.err.println(req2);
root.getDBSystemRoot().getDataSource().execute(req2);
 
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
207,5 → 304,4
}
((JFrame) SwingUtilities.getRoot(this)).dispose();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/model/MouseSheetXmlListeListener.java
44,14 → 44,6
 
private Class<? extends AbstractSheetXml> clazz;
protected IListe liste;
private String fastPrintString = "Impression rapide";
private String printString = "Impression ...";
private String printAllString = "Imprimer les documents";
private String previewString = "Voir le document";
private String showString = "Modifier le document avec OpenOffice";
private String generateString = "Générer le document";
private String mailPDFString = "Envoyer le document PDF par email";
private String mailString = "Envoyer le document par email";
 
private boolean previewIsVisible = true;
private boolean showIsVisible = true;
239,38 → 231,18
return null;
}
 
public void setGenerateString(String generateString) {
this.generateString = generateString;
}
 
public void setPreviewString(String previewString) {
this.previewString = previewString;
}
 
public void setShowString(String showString) {
this.showString = showString;
}
 
public void setFastPrintString(String printString) {
this.fastPrintString = printString;
}
 
public void setprintString(String printString) {
this.printString = printString;
}
 
public List<RowAction> getRowActions() {
List<RowAction> l = new ArrayList<RowAction>();
 
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
if (this.showIsVisible) {
RowAction action = new RowAction(new AbstractAction(this.showString) {
RowAction action = new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
System.err.println("");
createAbstractSheet(IListe.get(ev).getSelectedRow()).openDocument(false);
}
 
}, this.previewHeader) {
}, this.previewHeader, "document.modify") {
@Override
public boolean enabledFor(IListeEvent evt) {
 
283,7 → 255,7
}
} else {
if (this.previewIsVisible) {
l.add(new RowAction(new AbstractAction(this.previewString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
try {
createAbstractSheet(IListe.get(ev).getSelectedRow()).showPreviewDocument();
292,7 → 264,7
}
}
 
}, this.previewHeader) {
}, this.previewHeader, "document.preview") {
 
@Override
public boolean enabledFor(IListeEvent evt) {
314,11 → 286,11
if (Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
 
if (this.showIsVisible) {
l.add(new RowAction(new AbstractAction(this.showString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(IListe.get(ev).getSelectedRow()).openDocument(false);
}
}, this.showHeader) {
}, this.showHeader, "document.modify") {
@Override
public boolean enabledFor(IListeEvent evt) {
return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1 && createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
329,12 → 301,12
 
if (this.printIsVisible) {
 
l.add(new RowAction(new AbstractAction(this.fastPrintString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(IListe.get(ev).getSelectedRow()).fastPrintDocument();
}
 
}, this.printHeader) {
}, this.printHeader, "document.quickprint") {
 
@Override
public boolean enabledFor(IListeEvent evt) {
342,11 → 314,11
}
});
 
l.add(new RowAction(new AbstractAction(this.printString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
createAbstractSheet(IListe.get(ev).getSelectedRow()).printDocument();
}
}, false) {
}, false, "document.print") {
@Override
public boolean enabledFor(IListeEvent evt) {
return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1 && createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
353,7 → 325,7
}
});
 
PredicateRowAction rowAction = new PredicateRowAction(new AbstractAction(this.printAllString) {
PredicateRowAction rowAction = new PredicateRowAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
List<SQLRowAccessor> list = IListe.get(e).getSelectedRows();
360,7 → 332,7
ListeFastPrintFrame frame = new ListeFastPrintFrame(list, clazz);
frame.setVisible(true);
}
}, this.previewHeader);
}, this.previewHeader, "document.print.all");
rowAction.setPredicate(IListeEvent.createSelectionCountPredicate(2, Integer.MAX_VALUE));
 
l.add(rowAction);
369,11 → 341,11
 
if (this.showIsVisible) {
 
l.add(new RowAction(new AbstractAction(this.mailPDFString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
sendMail(createAbstractSheet(IListe.get(ev).getSelectedRow()), true);
}
}, false) {
}, false, "document.pdf.send.email") {
@Override
public boolean enabledFor(IListeEvent evt) {
return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1 && createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
380,11 → 352,11
}
});
 
l.add(new RowAction(new AbstractAction(this.mailString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
sendMail(createAbstractSheet(IListe.get(ev).getSelectedRow()), false);
}
}, false) {
}, false, "document.send.email") {
@Override
public boolean enabledFor(IListeEvent evt) {
return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1 && createAbstractSheet(evt.getSelectedRow().asRow()).getGeneratedFile().exists();
393,7 → 365,7
 
}
if (this.generateIsVisible) {
l.add(new RowAction(new AbstractAction(this.generateString) {
l.add(new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
 
final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).getSelectedRow());
400,7 → 372,7
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(true, false, true);
}
}, this.generateHeader) {
}, this.generateHeader, "document.create") {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return selection != null && selection.size() == 1;
418,7 → 390,7
* @return
*/
public RowAction getDefaultRowAction() {
return new RowAction(new AbstractAction(this.generateString) {
return new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).getSelectedRow().asRow());
try {
428,7 → 400,7
ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", exn);
}
}
}, false, false) {
}, false, false, "document.create") {
@Override
public boolean enabledFor(List<SQLRowAccessor> selection) {
return selection != null && selection.size() == 1;
/trunk/OpenConcerto/src/org/openconcerto/erp/model/ISQLCompteSelector.java
52,6 → 52,12
this.addButtonVisible = addButtonVisible;
}
 
JButton selectCompte = new JButton("Sélection Compte");
 
public void setSelectButtonEnabled(boolean b) {
this.selectCompte.setEnabled(b);
}
 
@Override
protected void uiLayout() {
super.uiLayout();
63,7 → 69,6
c.gridx = GridBagConstraints.EAST;
 
// TODO use the standard list button or at least disable when we're disabled
JButton selectCompte = new JButton("Sélection Compte");
this.add(selectCompte, c);
 
// if only digits assume we're looking for a hierarchical account number, otherwise perform
/trunk/OpenConcerto/src/org/openconcerto/erp/utils/FileUtility.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/utils/ActionDB.java
19,7 → 19,6
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.changer.correct.FixSerial;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.DBStructureItemDB;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLDataSource;
33,16 → 32,10
import org.openconcerto.sql.utils.SQLCreateRoot;
import org.openconcerto.utils.ExceptionHandler;
 
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
 
149,216 → 142,6
}
}
 
/**
* Affiche si il y a des différences entre les tables de base et baseDefault
*
* @param base
* @param baseDefault
*/
public static void compareDB(int base, int baseDefault) {
 
try {
if (Configuration.getInstance() == null) {
Configuration.setInstance(ComptaPropsConfiguration.create());
}
Configuration instance = Configuration.getInstance();
SQLTable tableSociete = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON");
 
String baseName = tableSociete.getRow(base).getString("DATABASE_NAME");
String baseDefaultName = tableSociete.getRow(baseDefault).getString("DATABASE_NAME");
 
instance.getBase().getDBSystemRoot().mapAllRoots();
try {
Set<String> s = new HashSet<String>();
s.add(baseName);
s.add(baseDefaultName);
instance.getBase().fetchTables(s);
} catch (SQLException e) {
throw new IllegalStateException("could not access societe base", e);
}
// instance.getBase().getDBRoot(baseName);
// instance.getBase().getDBRoot(baseDefaultName);
System.err.println("baseName" + baseName);
System.err.println("baseDefault" + baseDefaultName);
instance.getSystemRoot().prependToRootPath("Common");
instance.getSystemRoot().prependToRootPath(baseName);
instance.getSystemRoot().prependToRootPath(baseDefaultName);
 
SQLSchema baseSQL = instance.getBase().getSchema(baseName);
SQLSchema baseSQLDefault = instance.getBase().getSchema(baseDefaultName);
 
DatabaseMetaData dbMetaDataSociete = baseSQL.getBase().getDataSource().getConnection().getMetaData();
DatabaseMetaData dbMetaDataSocieteDefault = baseSQLDefault.getBase().getDataSource().getConnection().getMetaData();
 
Map<String, Map<String, SQLField>> mapTableSociete = new HashMap<String, Map<String, SQLField>>();
Map<String, Map<String, SQLField>> mapTableSocieteDefault = new HashMap<String, Map<String, SQLField>>();
 
ResultSet rs = dbMetaDataSociete.getTables("", baseSQL.getName(), "%", null);
 
System.err.println("Start");
 
while (rs.next()) {
// System.err.println(rs.getString("TABLE_NAME") + ", TYPE ::" +
// rs.getString("TABLE_TYPE"));
 
if (rs.getString("TABLE_TYPE") != null && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
Map<String, SQLField> m = new HashMap<String, SQLField>();
baseSQL.getTableNames();
Set<SQLField> s = baseSQL.getTable(rs.getString("TABLE_NAME")).getFields();
for (SQLField field : s) {
m.put(field.getName(), field);
}
mapTableSociete.put(rs.getString("TABLE_NAME"), m);
}
}
rs.close();
 
rs = dbMetaDataSocieteDefault.getTables("", baseSQLDefault.getName(), "%", null);
 
while (rs.next()) {
// System.err.println(rs.getString("TABLE_NAME") + ", TYPE ::" +
// rs.getString("TABLE_TYPE"));
if (rs.getString("TABLE_TYPE") != null && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
Map<String, SQLField> m = new HashMap<String, SQLField>();
Set<SQLField> s = baseSQLDefault.getTable(rs.getString("TABLE_NAME")).getFields();
for (SQLField field : s) {
m.put(field.getName(), field);
}
mapTableSocieteDefault.put(rs.getString("TABLE_NAME"), m);
}
}
rs.close();
 
System.err.println("Test 1 " + mapTableSociete.keySet().size());
// On verifie que toutes les tables de la societe sont contenues dans la base default
for (String tableName : mapTableSociete.keySet()) {
 
if (!mapTableSocieteDefault.containsKey(tableName)) {
System.err.println("!! **** La table " + tableName + " n'est pas dans la base " + baseDefault);
 
} else {
Map<String, SQLField> mSoc = mapTableSociete.get(tableName);
Map<String, SQLField> mDef = mapTableSocieteDefault.get(tableName);
if (mSoc.keySet().containsAll(mDef.keySet())) {
if (mSoc.keySet().size() == mDef.keySet().size()) {
System.err.println("Table " + tableName + " --- OK");
compareTypeField(mSoc, mDef);
} else {
if (mSoc.keySet().size() > mDef.keySet().size()) {
for (String fieldName : mDef.keySet()) {
mSoc.remove(fieldName);
}
System.err.println("!! **** Difference Table " + tableName);
System.err.println(tableSociete.getRow(baseDefault).getString("DATABASE_NAME") + " Set Column " + mSoc);
System.err.println(getAlterTable(mSoc, tableSociete.getRow(baseDefault).getString("DATABASE_NAME"), tableName));
} else {
 
}
}
} else {
// System.err.println("!! **** Difference Table " + tableName);
// System.err.println(tableSociete.getRow(base).getString("DATABASE_NAME") +
// " Set Column " + mapTableSociete.get(tableName));
// System.err.println(tableSociete.getRow(baseDefault).getString("DATABASE_NAME")
// + " Set Column " + mapTableSocieteDefault.get(tableName));
for (String fieldName : mSoc.keySet()) {
mDef.remove(fieldName);
}
System.err.println("!! **** Difference Table " + tableName);
System.err.println(tableSociete.getRow(base).getString("DATABASE_NAME") + " Set Column " + mDef);
System.err.println(getAlterTable(mDef, tableSociete.getRow(base).getString("DATABASE_NAME"), tableName));
}
}
}
 
System.err.println("Test 2 " + mapTableSocieteDefault.keySet().size());
// On verifie que toutes les tables de la base default sont contenues dans la base
// societe
for (Iterator i = mapTableSocieteDefault.keySet().iterator(); i.hasNext();) {
Object tableName = i.next();
if (!mapTableSociete.containsKey(tableName)) {
System.err.println("!! **** La table " + tableName + " n'est pas dans la base " + baseDefault);
}
}
 
SQLSchema schem = instance.getBase().getSchema("Common");
 
} catch (SQLException e) {
e.printStackTrace();
}
}
 
private static String getAlterTable(Map<String, SQLField> m, String baseName, String tableName) {
StringBuffer buf = new StringBuffer();
for (String s : m.keySet()) {
SQLField field = m.get(s);
buf.append("ALTER TABLE \"" + baseName + "\".\"" + tableName + "\" ADD COLUMN ");
buf.append("\"" + field.getName() + "\" ");
buf.append(getType(field));
buf.append(";\n");
}
 
return buf.toString();
}
 
private static String getType(SQLField field) {
String columnName = field.getName();
String columnType = field.getType().getTypeName();
StringBuffer result = new StringBuffer();
// NULL OR NOT NULL
// field.getType().getSize();
// String nullable = tableMetaData.getString("IS_NULLABLE");
String nullString = "NULL";
DBStructureItemDB db = field.getDB();
// if ("NO".equalsIgnoreCase(nullable)) {
// nullString = "NOT NULL";
// }
 
// DEFAULT
Object defaultValueO = field.getDefaultValue();
String defaultValue = (defaultValueO == null) ? null : defaultValueO.toString();
String defaultValueString = "";
if (defaultValue != null) {
defaultValueString = " default " + defaultValue;
}
 
int columnSize = field.getType().getSize();
Integer decimalDigit = (Integer) field.getMetadata("DECIMAL_DIGITS");
String stringColumnSize = "";
if (Integer.valueOf(columnSize).intValue() > 0) {
stringColumnSize = " (" + columnSize;
 
if (decimalDigit != null && Integer.valueOf(decimalDigit).intValue() > 0) {
stringColumnSize += ", " + decimalDigit;
}
 
stringColumnSize += ")";
}
 
if ((columnType.trim().equalsIgnoreCase("character varying") || columnType.trim().equalsIgnoreCase("varchar") || columnType.trim().equalsIgnoreCase("numeric"))
&& stringColumnSize.length() > 0) {
result.append(" " + columnType + stringColumnSize + " ");
result.append(defaultValueString);
} else {
result.append(" " + columnType + " ");
result.append(defaultValueString);
}
return result.toString();
}
 
private static void compareTypeField(Map fieldsDefault, Map fields) {
for (Iterator i = fieldsDefault.keySet().iterator(); i.hasNext();) {
 
Object o = i.next();
SQLField field = (SQLField) fieldsDefault.get(o);
SQLField fieldDefault = (SQLField) fields.get(o);
 
if (field != null && fieldDefault != null && field.getType() != fieldDefault.getType()) {
System.err.println("---------> Type different Table " + field.getTable() + " -- Field " + field.getName());
}
}
}
 
private static void updateMultiBase() {
// Calcul automatique du ht des saisies de vente avec facture
 
495,83 → 278,10
 
}
 
public static void fixUserCommon(int base) {
 
if (Configuration.getInstance() == null) {
Configuration.setInstance(ComptaPropsConfiguration.create());
}
Configuration instance = Configuration.getInstance();
SQLTable tableSociete = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON");
 
String baseName = tableSociete.getRow(base).getString("DATABASE_NAME");
 
instance.getBase().getDBSystemRoot().mapAllRoots();
try {
Set<String> s = new HashSet<String>();
s.add(baseName);
instance.getBase().fetchTables(s);
} catch (SQLException e) {
throw new IllegalStateException("could not access societe base", e);
}
 
System.err.println("baseName" + baseName);
instance.getSystemRoot().prependToRootPath("Common");
instance.getSystemRoot().prependToRootPath(baseName);
 
SQLSchema baseSQL = instance.getBase().getSchema(baseName);
 
DatabaseMetaData dbMetaDataSociete;
try {
dbMetaDataSociete = baseSQL.getBase().getDataSource().getConnection().getMetaData();
 
String[] type = new String[1];
type[0] = "TABLE";
ResultSet rs = dbMetaDataSociete.getTables("", baseSQL.getName(), "%", null);
 
System.err.println("Start " + rs.getFetchSize());
int i = 0;
while (rs.next()) {
 
if (rs.getString("TABLE_TYPE") != null && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
// System.err.println("FIND TABLE");
// baseSQL.getTableNames();
final SQLTable table = baseSQL.getTable(rs.getString("TABLE_NAME"));
Set<SQLField> s = table.getFields();
for (SQLField field : s) {
if (field.getName().equalsIgnoreCase("ID_USER_COMMON_CREATE") || field.getName().equalsIgnoreCase("ID_USER_COMMON_MODIFY")) {
Object o = field.getDefaultValue();
if (o == null || (o instanceof Integer && ((Integer) o) == 0)
 
) {
System.err.println("Bad default on " + field);
baseSQL.getBase()
.execute(
"ALTER TABLE \"" + field.getTable().getSchema().getName() + "\".\"" + field.getTable().getName() + "\" ALTER COLUMN \"" + field.getName()
+ "\" SET DEFAULT 1;");
 
baseSQL.getBase().execute(
"UPDATE \"" + field.getTable().getSchema().getName() + "\".\"" + field.getTable().getName() + "\" SET \"" + field.getName() + "\"=1 WHERE \"" + field.getName()
+ "\"=0 OR \"" + field.getName() + "\" IS NULL;");
}
 
}
}
}
// System.err.println(i++ + " " + rs.getString("TABLE_TYPE"));
}
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
public static void main(String[] args) {
// updateMultiBase();
// compareDB(41, 1);
 
fixUserCommon(41);
 
// try {
// patchSequences(new
// PropsConfiguration(ActionDB.class.getResourceAsStream("changeBase.properties"),
/trunk/OpenConcerto/src/org/openconcerto/erp/graph/MargeDayDataModel.java
18,9 → 18,12
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.NumberUtils;
import org.openconcerto.utils.RTInterruptedException;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
 
87,26 → 90,27
final Where w2 = new Where(tableSaisieVenteFElt.getField("ID_SAISIE_VENTE_FACTURE"), "=", tableSaisieVenteF.getKey());
sel.setWhere(w.and(w2));
 
long total = 0;
BigDecimal total = BigDecimal.ZERO;
Object[] o = tableSaisieVenteF.getBase().getDataSource().executeA1(sel.asString());
if (o != null && o[0] != null && o[1] != null && (Long.valueOf(o[0].toString()) != 0 || Long.valueOf(o[1].toString()) != 0)) {
long ha = Long.valueOf(o[0].toString());
long vt = Long.valueOf(o[1].toString());
total = vt - ha;
if (o != null) {
BigDecimal pa = (BigDecimal) o[0];
BigDecimal pv = (BigDecimal) o[1];
if (pa != null && pv != null && (!NumberUtils.areNumericallyEqual(pa, BigDecimal.ZERO) || !NumberUtils.areNumericallyEqual(pv, BigDecimal.ZERO))) {
total = pv.subtract(pa);
}
}
 
final float value = total / 100;
 
if (value > chart.getHigherRange().floatValue()) {
long euros = (long) value;
String currencyToString = GestionDevise.currencyToString(euros * 100, true);
chart.getLeftAxis().getLabels().get(2).setLabel(currencyToString.substring(0, currencyToString.length() - 3) + " €");
currencyToString = GestionDevise.currencyToString(euros * 100 / 2, true);
chart.getLeftAxis().getLabels().get(1).setLabel(currencyToString.substring(0, currencyToString.length() - 3) + " €");
chart.setHigherRange(value);
if (total.doubleValue() > chart.getHigherRange().doubleValue()) {
// String currencyToString = GestionDevise.currencyToString(euros * 100,
// true);
chart.getLeftAxis().getLabels().get(2).setLabel(total.setScale(0, RoundingMode.HALF_UP).toString() + " €");
// currencyToString = GestionDevise.currencyToString(euros * 100 / 2,
// true);
chart.getLeftAxis().getLabels().get(1).setLabel(total.divide(new BigDecimal(2), MathContext.DECIMAL128).setScale(0, RoundingMode.HALF_UP) + " €");
chart.setHigherRange(total);
}
if (((int) value) != 0) {
MargeDayDataModel.this.setValueAt(i, value);
if (total.compareTo(BigDecimal.ZERO) != 0) {
MargeDayDataModel.this.setValueAt(i, total);
fireDataModelChanged();
Thread.sleep(20);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/graph/MargeDataModel.java
18,9 → 18,14
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.NumberUtils;
import org.openconcerto.utils.RTInterruptedException;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
 
81,22 → 86,25
final Where w2 = new Where(tableSaisieVenteFElt.getField("ID_SAISIE_VENTE_FACTURE"), "=", tableSaisieVenteF.getKey());
sel.setWhere(w.and(w2));
 
long total = 0;
BigDecimal total = BigDecimal.ZERO;
Object[] o = tableSaisieVenteF.getBase().getDataSource().executeA1(sel.asString());
if (o != null && o[0] != null && o[1] != null && (Long.valueOf(o[0].toString()) != 0 || Long.valueOf(o[1].toString()) != 0)) {
long ha = Long.valueOf(o[0].toString());
long vt = Long.valueOf(o[1].toString());
total = vt - ha;
if (o != null) {
BigDecimal pa = (BigDecimal) o[0];
BigDecimal pv = (BigDecimal) o[1];
if (pa != null && pv != null && (!NumberUtils.areNumericallyEqual(pa, BigDecimal.ZERO) || !NumberUtils.areNumericallyEqual(pv, BigDecimal.ZERO))) {
total = pv.subtract(pa);
}
}
 
final float value = total / 100;
final double value = total.doubleValue();
 
if (value > chart.getHigherRange().floatValue()) {
long euros = (long) value;
String currencyToString = GestionDevise.currencyToString(euros * 100, true);
chart.getLeftAxis().getLabels().get(2).setLabel(currencyToString.substring(0, currencyToString.length() - 3) + " €");
currencyToString = GestionDevise.currencyToString(euros * 100 / 2, true);
chart.getLeftAxis().getLabels().get(1).setLabel(currencyToString.substring(0, currencyToString.length() - 3) + " €");
if (value > chart.getHigherRange().doubleValue()) {
 
// String currencyToString = GestionDevise.currencyToString(euros * 100,
// true);
chart.getLeftAxis().getLabels().get(2).setLabel(total.setScale(0, RoundingMode.HALF_UP).toString() + " €");
 
chart.getLeftAxis().getLabels().get(1).setLabel(total.divide(new BigDecimal(2), MathContext.DECIMAL128).setScale(0, RoundingMode.HALF_UP) + " €");
chart.setHigherRange(value);
}
if (((int) value) != 0) {
/trunk/OpenConcerto/src/org/openconcerto/erp/graph/GraphArticleMargePanel.java
17,6 → 17,8
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
39,7 → 41,11
sel.addSelect(tableVFElement.getField("PV_HT"));
sel.addSelect(tableVFElement.getField("QTE"), "SUM");
 
final List<Object[]> rowsArticle = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(
final List<Object[]> rowsArticle = (List<Object[]>) Configuration
.getInstance()
.getBase()
.getDataSource()
.execute(
sel.asString() + " GROUP BY \"SAISIE_VENTE_FACTURE_ELEMENT\".\"" + field + "\"" + ",\"SAISIE_VENTE_FACTURE_ELEMENT\".\"PA_HT\"" + ",\"SAISIE_VENTE_FACTURE_ELEMENT\".\"PV_HT\"",
new ArrayListHandler());
 
47,23 → 53,29
@Override
public int compare(Object[] o1, Object[] o2) {
 
long marge1 = (Integer.parseInt(o1[2].toString()) - Integer.parseInt(o1[1].toString())) * Integer.parseInt(o1[3].toString());
long marge2 = (Integer.parseInt(o2[2].toString()) - Integer.parseInt(o2[1].toString())) * Integer.parseInt(o2[3].toString());
return (int) (marge2 - marge1);
BigDecimal pa1 = (BigDecimal) o1[1];
BigDecimal pv1 = (BigDecimal) o1[2];
BigDecimal qte1 = new BigDecimal(o1[3].toString());
 
BigDecimal pa2 = (BigDecimal) o2[1];
BigDecimal pv2 = (BigDecimal) o2[2];
BigDecimal qte2 = new BigDecimal(o2[3].toString());
 
BigDecimal marge1 = pv1.subtract(pa1).multiply(qte1, MathContext.DECIMAL128);
BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, MathContext.DECIMAL128);
return marge1.compareTo(marge2);
}
});
 
int rowCount = 0;
for (Object[] objects : rowsArticle) {
int value = Integer.parseInt(objects[1].toString());
rowCount += value;
}
 
for (int i = 0; i < 10 && i < rowsArticle.size(); i++) {
Object[] o = rowsArticle.get(i);
double value = (Long.parseLong(o[2].toString()) - Long.parseLong(o[1].toString())) * Integer.parseInt(o[3].toString()) / 100.0;
BigDecimal pa2 = (BigDecimal) o[1];
BigDecimal pv2 = (BigDecimal) o[2];
BigDecimal qte2 = new BigDecimal(o[3].toString());
BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, MathContext.DECIMAL128);
 
final String string = o[0].toString();
values.add(value);
values.add(marge2);
labels.add(string);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GestionArticleGlobalPreferencePanel.java
28,6 → 28,8
public static String UNITE_VENTE = "UniteVenteActive";
public static String USE_CREATED_ARTICLE = "UseCreatedArticle";
public static String CREATE_ARTICLE_AUTO = "CreateArticleAuto";
public static String TVA_LINE = "TVALigne";
public static String SUPPLIER_PRODUCT_CODE = "SupplierProductCode";
 
public GestionArticleGlobalPreferencePanel() {
super("Gestion des articles", null);
36,6 → 38,11
 
@Override
protected void addViews() {
 
PrefView<Boolean> viewAchat = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Gérer les codes articles fournisseurs", SUPPLIER_PRODUCT_CODE);
viewAchat.setDefaultValue(Boolean.FALSE);
this.addView(viewAchat);
 
PrefView<Boolean> view = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Gérer les sorties de stock avec les factures et non les bons de livraison", STOCK_FACT);
view.setDefaultValue(Boolean.TRUE);
this.addView(view);
51,5 → 58,10
PrefView<Boolean> view4 = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Créer automatiquement les articles (si il n'y a aucune correspondance CODE, DESIGNATION)", CREATE_ARTICLE_AUTO);
view4.setDefaultValue(Boolean.TRUE);
this.addView(view4);
 
// FIXME Patch pour arfang
PrefView<Boolean> view5 = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Calculer la TVA par ligne", TVA_LINE);
view5.setDefaultValue(Boolean.FALSE);
this.addView(view5);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/translation_fr.xml
New file
0,0 → 1,199
<translation lang="fr">
<!-- File -->
<menu id="menu.file" label="Fichier" />
<menu id="backup" label="Sauvegarde" />
<menu id="export.accounting" label="Export relation expert" />
<menu id="modules" label="Modules" />
<menu id="preferences" label="Préférences" />
<menu id="quit" label="Quitter" />
<!-- Creation -->
<menu id="menu.create" label="Saisie" />
<menu id="accounting" label="Comptabilité" />
<menu id="accounting.entry.create" label="Ecritures comptables" />
<menu id="customer" label="Clients" />
<menu id="customer.quote.create" label="Devis" />
<menu id="customer.letter.create" label="Courrier" />
<menu id="customer.proposal.create" label="Proposition" />
<menu id="project.create" label="Affaire" />
<menu id="appointment.create" label="Fiche de rendez-vous" />
<menu id="mission.create" label="Ordre de mission" />
<menu id="mission.notice.create" label="Avis d'intervention" />
<menu id="customer.delivery.create" label="Bon de livraison" />
<menu id="customer.order.create" label="Commande" />
<menu id="pos.sale.create" label="Vente comptoir" />
<menu id="customer.invoice.create" label="Facture" />
<menu id="kd.invoice.create" label="Facture CTC" />
<menu id="customer.credit.create" label="Facture d'avoir" />
<menu id="supplier" label="Fournisseur" />
<menu id="supplier.order.create" label="Commande fournisseur" />
<menu id="supplier.receipt.create" label="Bon de réception" />
<menu id="supplier.purchase.create" label="Achat fournisseur" />
<menu id="supplier.credit.create" label="Avoir fournisseur" />
<menu id="stock.io.create" label="Mouvement de stock" />
 
<!-- List -->
<menu id="menu.list" label="Gestion" />
<menu id="menu.list.customer" label="Gestion des clients" />
<menu id="customer.list" label="Liste des clients" />
<menu id="contact.list" label="Liste des contacts" />
<menu id="customer.history" label="Historique des clients" />
<menu id="customer.quote.list" label="Liste des devis" />
<menu id="customer.proposal.list" label="Liste des propositions" />
<menu id="customer.proposal.item.list" label="Liste des éléments de proposition" />
<menu id="menu.list.mission" label="Missions" />
<menu id="project.list" label="Liste des affaires" />
<menu id="mission.list" label="Liste des missions" />
<menu id="appointment.list" label="Liste des rendez-vous" />
<menu id="appointment.unplanned.list" label="" />
<menu id="appointment.notvalidated.list" label="" />
<menu id="mission.order.list" label="" />
<menu id="mission.notice.list" label="" />
<menu id="customer.order.list" label="Liste des commmandes" />
<menu id="customer.delivery.list" label="Liste des bons de livraison" />
<menu id="sales.list" label="Liste des ventes" />
<menu id="customer.invoice.list" label="Liste des factures" />
<menu id="payment.factoring.create" label="" />
<menu id="payment.factoring.list" label="" />
<menu id="customer.credit.list" label="Liste des avoirs" />
<menu id="menu.list.supplier" label="Fournisseurs" />
<menu id="supplier.list" label="Liste des fournisseurs" />
<menu id="supplier.contact.list" label="Liste des contact fournisseur" />
<menu id="supplier.history" label="Historique des fournisseurs" />
<menu id="supplier.order.list" label="Liste des commandes fournisseur" />
<menu id="supplier.receipt.list" label="Liste des bons de réception" />
<menu id="supplier.purchase.list" label="Liste des saisies d'achat" />
<menu id="supplier.credit.list" label="Liste des avoirs fournisseur" />
<menu id="product.list" label="Liste des articles" />
<menu id="product.reference.list" label="Liste des références" />
<menu id="stock.io.list" label="Listes des mouvements de stock" />
<menu id="menu.list.pos" label="Point de vente" />
<menu id="pos.receipt.list" label="Liste des tickets de caisse" />
<menu id="pos.sales.report" label="Liste des ventes en caisse" />
<menu id="sales.report" label="" />
<!-- Accounting -->
<menu id="menu.accounting" label="Etats" />
<menu id="accounting.balance" label="Balance" />
<menu id="accounting.client.balance" label="Balance agée" />
<menu id="accounting.analytical.result" label="Compte de résultat analytique" />
<menu id="accounting.ledger" label="Journaux" />
<menu id="accounting.general.ledger" label="Grand livre" />
<menu id="accounting.entries.ledger" label="Liste des écritures" />
<menu id="accounting.entries.list" label="Liste des écritures par classe" />
<menu id="menu.accounting.closing" label="Clôture" />
<menu id="accounting.validating" label="Validation des écritures" />
<menu id="accounting.closing" label="Assistant de clôture" />
<!-- Documents -->
<menu id="menu.report" label="Déclaration" />
<menu id="accounting.vat.report" label="Déclaration de TVA" />
<menu id="accounting.costs.report" label="Etat des charges" />
<menu id="accounting.balance.report" label="Compte de résultat et bilan" />
<menu id="employe.social.report" label="Déclaration N4DS" />
<!-- Stats -->
<menu id="menu.stats" label="Statistique" />
<menu id="sales.graph" label="Evolution du chiffre d'affaires" />
<menu id="sales.margin.graph" label="Evolution des marges" />
<menu id="sales.list.report" label="Journal des ventes" />
<menu id="sales.product.graph" label="Articles les plus vendus" />
<menu id="sales.product.margin.graph" label="Articles les plus rentables" />
<menu id="sales.list.graph" label="Etat des ventes" />
<!-- Payment -->
<menu id="menu.payment" label="Paiement" />
<menu id="payment.checking.create" label="Pointage manuel par compte" />
<menu id="payment.reconciliation.create" label="Lettrage manuel par compte" />
<menu id="menu.payment.customer" label="Clients" />
<menu id="customer.invoice.unpaid.list" label="Factures clients non payées" />
<menu id="customer.dept.list" label="Liste des débiteurs" />
<menu id="customer.payment.list" label="Liste des encaissements" />
<menu id="customer.payment.followup.list" label="Liste des relances" />
<menu id="customer.payment.check.pending.list" label="Chèques des clients" />
<menu id="customer.payment.check.pending.create" label="Chèques à encaisser" />
<menu id="customer.credit.check.list" label="Chèques d'avoir" />
<menu id="customer.credit.check.create" label="Chèques d'avoir à décaisser" />
<menu id="menu.payment.supplier" label="Fournisseurs" />
<menu id="supplier.invoice.unpaid.list" label="Factures fournisseurs impayées" />
<menu id="supplier.bill.list" label="Liste des traites et virements aux fournisseurs" />
<menu id="supplier.payment.check.list" label="Chèques aux fournisseurs" />
<menu id="supplier.payment.check.pending.list" label="Chèques à décaisser" />
<!-- Payroll -->
<menu id="menu.payroll" label="Paye" />
<menu id="payroll.list.report.print" label="Livre de paye" />
<menu id="payroll.profile.list" label="Liste des profils de paye" />
<menu id="payroll.history" label="Liste des fiches de paye" />
<menu id="payroll.create" label="Edition des fiches de paye" />
<menu id="payroll.deposit.create" label="Acompte sur salaire" />
<menu id="employee.list" label="Liste des salariés" />
<menu id="payroll.section" label="Liste des rubriques de paye" />
<menu id="payroll.variable" label="Liste des variables et plafonds" />
<menu id="payroll.closing" label="Clôture mensuelle" />
<!-- Organization -->
<menu id="menu.organization" label="Structure" />
<menu id="accounting.chart" label="Plan comptable de l'entreprise" />
<menu id="accounting.journal" label="Gestion des journaux comptables" />
<menu id="user.list" label="Liste des utilisateurs" />
<menu id="user.right.list" label="Gestion des droits" />
<menu id="user.task.right" label="Autorisations liées aux tâches" />
<menu id="salesman.list" label="Liste des commerciaux" />
<menu id="pos.list" label="Liste des caisses" />
<menu id="secretary.list" label="Liste des secrétaires" />
<menu id="auditor.list" label="Liste des vérificateurs" />
<menu id="index.list" label="Liste des indices" />
<menu id="enterprise.list" label="Liste des sociétés" />
<menu id="divison.list" label="" />
<menu id="divison.bank.list" label="" />
<menu id="enterprise.create" label="Nouvelle société" />
<menu id="mission.sample.list" label="" />
<menu id="mission.code.list" label="" />
<menu id="department.list" label="" />
<!-- Test -->
<menu id="menu.test" label="En test" />
<!-- Help -->
<menu id="menu.help" label="Aide" />
<menu id="information" label="Informations" />
<menu id="tips" label="Astuces" />
<!-- Quote -->
<action id="sales.quote.accept" label="Marquer comme accepté" />
<action id="sales.quote.refuse" label="Marquer comme refusé" />
<action id="sales.quote.create.invoice" label="Transfert vers facture" />
<action id="sales.quote.create.supplier.order" label="Transférer en commande" />
<action id="sales.quote.clone" label="Créer à partir de" />
<action id="sales.quote.create.customer.order" label="Transfert vers commande client" />
<action id="sales.quote.accept.create.customer.order" label="Marquer comme accepté et Transfert en commande client" />
<!-- Customer -->
<action id="customerrelationship.customer.label.print" label="Imprimer l'étiquette client" />
<action id="customerrelationship.customer.info.create" label="Créer la fiche client" />
<action id="customerrelationship.customer.email.send" label="Envoyer un email" />
<!-- Matching -->
<action id="financing.accouning.entries.source.show" label="Voir la source" />
<action id="financing.accouning.entries.match" label="Lettrer" />
<action id="financing.accouning.entries.unmatch" label="Délettrer" />
<!-- Invoice -->
<action id="sales.invoice.purchase.update" label="Mettre à jour le total achat" />
<action id="sales.invoice.comment.add" label="Ajouter un commentaire" />
<action id="sales.invoice.create.delivery" label="Transférer en bon de livraison" />
<action id="sales.invoice.create.credit" label="Transférer en avoir" />
<action id="sales.invoice.clone" label="Créer à partir de" />
<action id="sales.invoice.info.show" label="Détails client" />
<action id="sales.invoice.create.supplier.order" label="Transférer en commande" />
<action id="sales.shipment.create.invoice" label="Transfert en facture" />
 
<!-- Document -->
<action id="document.quickprint" label="Impression rapide" />
<action id="document.print" label="Impression..." />
<action id="document.print.all" label="Imprimer les documents" />
<action id="document.preview" label="Voir le document" />
<action id="document.modify" label="Modifier le document avec OpenOffice" />
<action id="document.create" label="Générer le document" />
<action id="document.pdf.send.email" label="Envoyer le document PDF par email" />
<action id="document.send.email" label="Envoyer le document par email" />
 
<!-- Supplier order -->
<action id="supplychain.order.create.purchase" label="Transfert vers saisie achat" />
<action id="supplychain.order.create.receipt" label="Transfert vers bon de réception" />
 
<!-- Customer order -->
<action id="sales.order.create.deliverynote" label="Transfert vers bon de livraison" />
<action id="sales.order.create.invoice" label="Transfert vers facture" />
<action id="sales.order.create.supplier.order" label="Transfert vers commande fournisseur" />
 
 
</translation>
/trunk/OpenConcerto/src/org/openconcerto/erp/config/Gestion.java
15,8 → 15,6
 
import org.openconcerto.erp.action.NouvelleConnexionAction;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.quote.ui.DevisItemTable;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.panel.PostgreSQLFrame;
import org.openconcerto.erp.panel.UserExitPanel;
30,7 → 28,6
import org.openconcerto.sql.model.SQLRequestLog;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.view.ListeModifyPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.ui.FrameUtil;
42,7 → 39,6
 
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.SplashScreen;
import java.awt.Toolkit;
133,7 → 129,6
System.setProperty("sun.java2d.pmoffscreen", "false");
 
System.setProperty("org.openconcerto.editpanel.noborder", "true");
System.setProperty("org.openconcerto.editpanel.noborder", "true");
System.setProperty("org.openconcerto.sql.editpanel.endAdd", "true");
System.setProperty("org.openconcerto.sql.listPanel.deafEditPanel", "true");
System.setProperty("org.openconcerto.ui.addComboButton", "true");
145,7 → 140,6
System.setProperty("org.openconcerto.ui.removeSwapSearchCheckBox", "true");
 
if (System.getProperty("org.openconcerto.oo.useODSViewer") == null) {
 
System.setProperty("org.openconcerto.oo.useODSViewer", "true");
}
 
214,6 → 208,8
try {
// ensure consistent state
conf.getSystemRoot().getGraph();
// Prefetch undefined
conf.getRoot().getTables().iterator().next().getUndefinedID();
} catch (Exception e) {
System.out.println("Init phase 1 error:" + (System.currentTimeMillis() - t4) + "ms");
ExceptionHandler.die("Erreur de connexion à la base de données", e);
401,10 → 397,10
e.printStackTrace();
}
try {
Enumeration e = NetworkInterface.getNetworkInterfaces();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e.nextElement();
Enumeration e2 = ni.getInetAddresses();
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ip = (InetAddress) e2.nextElement();
final String iip = ip.toString().replace('/', ' ').trim();
421,36 → 417,6
 
public static PostgreSQLFrame pgFrameStart = null;
 
private static void testModifyRowValuesTable() {
 
JFrame f = new JFrame();
f.getContentPane().setLayout(new GridLayout(1, 1));
 
f.getContentPane().add(new ListeModifyPanel(new DevisSQLElement()));
f.pack();
f.setSize(800, 600);
 
// f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 
}
 
private static void testRowValuesTable() {
 
JFrame f = new JFrame();
f.getContentPane().setLayout(new GridLayout(1, 1));
 
f.getContentPane().add(new DevisItemTable());
f.pack();
f.setSize(800, 600);
 
// f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 
}
 
private static JDialog frameExit = null;
 
static void askForExit() {
/trunk/OpenConcerto/src/org/openconcerto/erp/config/mappingCompta.xml
109,7 → 109,10
<FIELD name="QTE_ACHAT" label="Quantité multiple d'achat à respecter"
titlelabel="Quantité multiple d'achat à respecter" />
<FIELD name="CODE_BARRE" label="Code barres" titlelabel="Code barres" />
<FIELD name="ID_FOURNISSEUR" label="Fournisseur" titlelabel="Fournisseur" />
<FIELD name="INFOS" label="Informations complémentaires"
titlelabel="Informations complémentaires" />
<FIELD name="ID_FOURNISSEUR" label="Fournisseur principal"
titlelabel="Fournisseur principal" />
<FIELD name="GESTION_STOCK" label="Gérer le stock" titlelabel="Gérer le stock" />
<FIELD name="CODE_DOUANIER" label="Code douanier" titlelabel="Code douanier" />
<FIELD name="ID_PAYS" label="Pays d'origine" titlelabel="Pays d'origine" />
147,6 → 150,10
<FIELD name="PRIX_FINAL_TTC" label="Prix client final ttc"
titlelabel="Prix client final ttc" />
<FIELD name="ID_ECOTAXE" label="Ecotaxe" titlelabel="Ecotaxe" />
<FIELD name="ID_COMPTE_PCE" label="Compte spécifique de vente"
titlelabel="Compte spécifique de vente" />
<FIELD name="ID_COMPTE_PCE_ACHAT" label="Compte spécifique d'achat"
titlelabel="Compte spécifique d'achat" />
</TABLE>
 
<TABLE name="ARTICLE_TARIF">
310,6 → 317,8
</TABLE>
 
<TABLE name="AVOIR_FOURNISSEUR">
<FIELD name="INFOS" label="Informations complémentaires"
titlelabel="Informations complémentaires" />
<FIELD name="NOM" label="Libellé" titlelabel="Libellé" />
<FIELD name="DATE" label="Date" titlelabel="Date" />
<FIELD name="SOLDE" label="Soldé" titlelabel="Soldé" />
370,6 → 379,8
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="ID_CODE_FOURNISSEUR" label="Code fournisseur"
titlelabel="Code fournisseur" />
<FIELD name="DESCRIPTIF" label="Descriptif" titlelabel="Descriptif" />
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="NOM" label="Libellé" titlelabel="Libellé" />
630,6 → 641,13
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="NOM" label="Libellé" titlelabel="Libellé" />
</TABLE>
 
<TABLE name="CODE_FOURNISSEUR">
<FIELD name="CODE" label="Code" titlelabel="Code" />
<FIELD name="ID_FOURNISSEUR" label="Fournisseur" titlelabel="Fournisseur" />
</TABLE>
 
 
<TABLE name="CODE_MISSION">
<FIELD name="CONTROLE_TECHNIQUE" label="Mission controle technique"
titlelabel="Mission controle technique" />
764,6 → 782,8
 
<TABLE name="COMMANDE_ELEMENT">
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_CODE_FOURNISSEUR" label="Code Fournisseur"
titlelabel="Code Fournisseur" />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
<FIELD name="ID_DEVISE" label="Devise" titlelabel="Devise" />
800,6 → 820,7
<FIELD name="T_PV_HT" label="Total Vt HT" titlelabel="Total Vt HT" />
<FIELD name="T_PA_TTC" label="Total Ha TTC" titlelabel="Total Ha TTC" />
<FIELD name="T_PA_HT" label="Total Ha HT" titlelabel="Total Ha HT" />
<FIELD name="POURCENT_REMISE" label="% Remise" titlelabel="% Remise" />
<FIELD name="T_POIDS" label="Poids total" titlelabel="Poids total" />
<FIELD name="ID_MODE_VENTE_ARTICLE" label="Mode de vente"
titlelabel="Mode de vente" />
866,6 → 887,8
<FIELD name="T_POIDS" label="Poids total" titlelabel="Poids total" />
<FIELD name="ID_MODE_VENTE_ARTICLE" label="Mode de vente"
titlelabel="Mode de vente" />
 
<FIELD name="POURCENT_ACOMPTE" label="% Acompte" titlelabel="% Acompte" />
</TABLE>
 
<TABLE name="COMMERCIAL">
1045,7 → 1068,7
titlelabel="Régularisation en comptabilité" />
<FIELD name="DATE_LAST_RELANCE" label="Date de derniere relance"
titlelabel="Date de derniere relance" />
<FIELD name="MONTANT" label="Montant TTC" titlelabel="Montant TTC" />
<FIELD name="MONTANT" label="Montant TTC dû" titlelabel="Montant TTC dû" />
</TABLE>
<TABLE name="ECHEANCE_FOURNISSEUR">
<FIELD name="REGLE" label="Réglé" titlelabel="Réglé" />
1148,6 → 1171,10
<FIELD name="NOM" label="Famille" titlelabel="Famille" />
<FIELD name="ID_FAMILLE_ARTICLE_PERE" label="Sous Famille de"
titlelabel="Sous Famille de" />
<FIELD name="ID_COMPTE_PCE" label="Compte spécifique de vente"
titlelabel="Compte spécifique de vente" />
<FIELD name="ID_COMPTE_PCE_ACHAT" label="Compte spécifique d'achat"
titlelabel="Compte spécifique d'achat" />
</TABLE>
 
<TABLE name="FICHE_PAYE">
1814,6 → 1841,7
titlelabel="Gestion automatique du compte de service" />
</TABLE>
<TABLE name="SAISIE_VENTE_FACTURE_ELEMENT">
<FIELD name="POURCENT_ACOMPTE" label="% Acompte" titlelabel="% Acompte" />
<FIELD name="QTE_UNITAIRE" label="Qté U.V." titlelabel="Qté U.V." />
<FIELD name="ID_UNITE_VENTE" label="Unité de vente" titlelabel="Unité de vente" />
<FIELD name="ID_ARTICLE" label="Article" titlelabel="Article" />
/trunk/OpenConcerto/src/org/openconcerto/erp/config/Log.java
New file
0,0 → 1,27
/*
* 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.config;
 
import java.util.logging.Logger;
 
/**
* Logger for OpenConcerto
*/
public class Log {
private static final Logger L = Logger.getLogger("openconcerto.erp");
 
public static Logger get() {
return L;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/InstallationPanel.java
13,8 → 13,9
package org.openconcerto.erp.config;
 
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.erp.modules.ModuleReference;
import org.openconcerto.sql.changer.convert.AddFK;
import org.openconcerto.sql.changer.correct.CorrectOrder;
import org.openconcerto.sql.changer.correct.FixSerial;
54,6 → 55,7
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
118,7 → 120,8
// FixUnbounded varchar
fixUnboundedVarchar(conf.getRoot());
 
// FIXME DROP CONSTRAINT UNIQUE ORDRE ON CONTACT_FOURNISSEUR
// FIXME DROP CONSTRAINT UNIQUE ORDRE ON
// CONTACT_FOURNISSEUR
 
// Mise à jour des taux
final SQLTable table = conf.getRoot().getTable("VARIABLE_PAYE");
179,7 → 182,8
});
final String[] type = new String[] { "Avoir client", "AVOIR_CLIENT", "Avoir", "Bon de livraison", "BON_DE_LIVRAISON", "BonLivraison", "Commande Client",
"COMMANDE_CLIENT", "CommandeClient", "Devis", "DEVIS", "Devis", "Facture", "SAISIE_VENTE_FACTURE", "VenteFacture" };
// ('FR', 'Français', 1.000), ('EN', 'Anglais', 2.000)
// ('FR', 'Français', 1.000), ('EN',
// 'Anglais', 2.000)
final List<String> values = new ArrayList<String>();
final SQLBase base = table.getDBRoot().getBase();
 
198,7 → 202,8
}
}
 
// ///////////// updateSocieteTable(conf.getRoot());
SQLTable.setUndefID(conf.getRoot().getSchema(), "DEVISE", 1);
SQLTable.setUndefID(conf.getRoot().getSchema(), "TYPE_MODELE", 1);
 
// we need to upgrade all roots
// ///////////////////////////
219,6 → 224,7
for (final String childName : childrenNames) {
System.out.println("InstallationPanel.InstallationPanel() UPDATE SCHEMA " + childName);
final int barValue = i;
 
SwingUtilities.invokeLater(new Runnable() {
 
@Override
263,6 → 269,7
throw new SQLException(e);
}
updateToV1Dot2(root);
updateToV1Dot3(root);
return null;
}
});
374,7 → 381,8
// @Override
// public void actionPerformed(ActionEvent e) {
// JFileChooser choose = new JFileChooser();
// if (choose.showOpenDialog(InstallationPanel.this) == JFileChooser.APPROVE_OPTION) {
// if (choose.showOpenDialog(InstallationPanel.this) ==
// JFileChooser.APPROVE_OPTION) {
// chemin.setText(choose.getSelectedFile().getAbsolutePath());
// }
// }
408,7 → 416,8
// input.close();
//
// try {
// final SQLServer sqlServer = finderPanel.getServerConfig().createSQLServer();
// final SQLServer sqlServer =
// finderPanel.getServerConfig().createSQLServer();
// Number n = (Number)
// sqlServer.getBase("postgres").getDataSource().executeScalar("select COUNT(*) from pg_database WHERE datname='OpenConcerto'");
// if (n.intValue() > 0) {
422,7 → 431,8
//
// sqlServer.getBase("postgres").getDataSource().execute("ALTER DATABASE \"OpenConcerto\" OWNER TO openconcerto;");
//
// SQLUtils.executeScript(sql.toString(), sqlServer.getSystemRoot("OpenConcerto"));
// SQLUtils.executeScript(sql.toString(),
// sqlServer.getSystemRoot("OpenConcerto"));
// sqlServer.destroy();
// JOptionPane.showMessageDialog(InstallationPanel.this,
// "Création de la base OpenConerto terminée.");
630,8 → 640,164
}
root.refetch();
}
 
}
 
private void updateToV1Dot3(final DBRoot root) throws SQLException {
final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
// Article
{
SQLTable tableProduct = root.getTable("ARTICLE");
boolean alterTableProduct = false;
AlterTable t = new AlterTable(tableProduct);
if (!tableProduct.getFieldsName().contains("ID_COMPTE_PCE")) {
t.addForeignColumn("ID_COMPTE_PCE", root.getTable("COMPTE_PCE"));
alterTableProduct = true;
}
if (!tableProduct.getFieldsName().contains("ID_COMPTE_PCE_ACHAT")) {
t.addForeignColumn("ID_COMPTE_PCE_ACHAT", root.getTable("COMPTE_PCE"));
alterTableProduct = true;
}
if (alterTableProduct) {
try {
ds.execute(t.asString());
tableProduct.getSchema().updateVersion();
tableProduct.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ARTICLE", ex);
}
}
}
 
// Famille Article
{
SQLTable tableArticleFamily = root.getTable("FAMILLE_ARTICLE");
boolean alterArticleFamily = false;
AlterTable t = new AlterTable(tableArticleFamily);
if (!tableArticleFamily.getFieldsName().contains("ID_COMPTE_PCE")) {
t.addForeignColumn("ID_COMPTE_PCE", root.getTable("COMPTE_PCE"));
alterArticleFamily = true;
}
if (!tableArticleFamily.getFieldsName().contains("ID_COMPTE_PCE_ACHAT")) {
t.addForeignColumn("ID_COMPTE_PCE_ACHAT", root.getTable("COMPTE_PCE"));
alterArticleFamily = true;
}
if (alterArticleFamily) {
try {
ds.execute(t.asString());
tableArticleFamily.getSchema().updateVersion();
tableArticleFamily.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table FAMILLE_ARTICLE", ex);
}
}
}
 
// ECRITURE
{
SQLTable tableRecords = root.getTable("ECRITURE");
boolean alterRecords = false;
AlterTable t = new AlterTable(tableRecords);
if (!tableRecords.getFieldsName().contains("DATE_EXPORT")) {
t.addColumn("DATE_EXPORT", "date");
alterRecords = true;
}
 
if (!tableRecords.getFieldsName().contains("CODE_CLIENT")) {
t.addVarCharColumn("CODE_CLIENT", 256);
alterRecords = true;
}
if (alterRecords) {
try {
ds.execute(t.asString());
tableRecords.getSchema().updateVersion();
tableRecords.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ECRITURE", ex);
}
}
}
addInfoField(root, ds, "AVOIR_FOURNISSEUR");
addInfoField(root, ds, "AVOIR_CLIENT");
 
boolean refetchRoot = false;
if (!root.contains("CODE_FOURNISSEUR")) {
 
SQLCreateTable createCode = new SQLCreateTable(root, "CODE_FOURNISSEUR");
createCode.addVarCharColumn("CODE", 256);
createCode.addForeignColumn("FOURNISSEUR");
createCode.addForeignColumn("ARTICLE");
try {
ds.execute(createCode.asString());
insertUndef(createCode);
root.getSchema().updateVersion();
refetchRoot = true;
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table CODE_FOURNISSEUR", ex);
}
 
}
 
// Chargement des tables fraichement créées
if (refetchRoot)
root.refetch();
 
addSupplierCode(root, ds, "BON_RECEPTION_ELEMENT");
addSupplierCode(root, ds, "COMMANDE_ELEMENT");
 
// Undefined
SQLTable.setUndefID(root.getSchema(), "ARTICLE_DESIGNATION", 1);
SQLTable.setUndefID(root.getSchema(), "ARTICLE_TARIF", 1);
SQLTable.setUndefID(root.getSchema(), "CODE_STATUT_CAT_CONV", 1);
SQLTable.setUndefID(root.getSchema(), "CONTACT_ADMINISTRATIF", 1);
SQLTable.setUndefID(root.getSchema(), "CONTACT_FOURNISSEUR", 1);
 
SQLTable.setUndefID(root.getSchema(), "LANGUE", 1);
SQLTable.setUndefID(root.getSchema(), "MODELE", 1);
SQLTable.setUndefID(root.getSchema(), "OBJECTIF_COMMERCIAL", 1);
SQLTable.setUndefID(root.getSchema(), "TARIF", 1);
 
SQLTable.setUndefID(root.getSchema(), "UNITE_VENTE", 1);
}
 
private void addInfoField(final DBRoot root, final SQLDataSource ds, String tableName) {
SQLTable tableBL = root.getTable(tableName);
boolean alterBL = false;
AlterTable t = new AlterTable(tableBL);
if (!tableBL.getFieldsName().contains("INFOS")) {
t.addVarCharColumn("INFOS", 1024);
alterBL = true;
}
if (alterBL) {
try {
ds.execute(t.asString());
tableBL.getSchema().updateVersion();
tableBL.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table AVOIR FOURNISSEUR", ex);
}
}
}
 
private void addSupplierCode(final DBRoot root, final SQLDataSource ds, String tableName) {
SQLTable tableBL = root.getTable(tableName);
boolean alterBL = false;
AlterTable t = new AlterTable(tableBL);
if (!tableBL.contains("ID_CODE_FOURNISSEUR")) {
t.addForeignColumn("ID_CODE_FOURNISSEUR", root.getTable("CODE_FOURNISSEUR"));
alterBL = true;
}
if (alterBL) {
try {
ds.execute(t.asString());
tableBL.getSchema().updateVersion();
tableBL.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table " + tableName, ex);
}
}
}
 
private void updateToV1Dot2(final DBRoot root) throws SQLException {
// bigint -> int ID_METRIQUE BON_DE_LIVRAISON_ELEMENT
final SQLTable tableLivraisonElement = root.getTable("BON_DE_LIVRAISON_ELEMENT");
667,10 → 833,24
SQLRowValues rowVals = new SQLRowValues(tableEtatDevis);
rowVals.put("NOM", "En cours de rédaction");
rowVals.commit();
 
}
 
SQLRowValues rowValsOrdre = new SQLRowValues(tableEtatDevis);
rowValsOrdre.put("ORDRE", new BigDecimal(1.505));
rowValsOrdre.update(EtatDevisSQLElement.EN_ATTENTE);
 
rowValsOrdre.put("ORDRE", new BigDecimal(2.505));
rowValsOrdre.update(EtatDevisSQLElement.ACCEPTE);
 
rowValsOrdre.put("ORDRE", new BigDecimal(3.505));
rowValsOrdre.update(EtatDevisSQLElement.REFUSE);
 
rowValsOrdre.put("ORDRE", new BigDecimal(3.505));
rowValsOrdre.update(EtatDevisSQLElement.EN_COURS);
 
// Ajout de la TVA à 0
SQLSelect selTVA = new SQLSelect(root.getBase());
SQLSelect selTVA = new SQLSelect();
SQLTable tableTaxe = root.getTable("TAXE");
selTVA.addSelect(tableTaxe.getKey(), "COUNT");
selTVA.setWhere(new Where(tableTaxe.getField("TAUX"), "=", 0));
850,7 → 1030,7
ds.execute(createLangue.asString());
insertUndef(createLangue);
tableDevis.getSchema().updateVersion();
root.refetch(createLangue.getName());
root.refetchTable(createLangue.getName());
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table LANGUE", ex);
}
923,7 → 1103,7
ds.execute(createTarif.asString());
insertUndef(createTarif);
tableDevis.getSchema().updateVersion();
root.refetch(createTarif.getName());
root.refetchTable(createTarif.getName());
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de la création de la table TARIF", ex);
}
1036,6 → 1216,9
SQLTable tableCommande = root.getTable("COMMANDE");
addDeviseHAField(tableCommande, root);
 
patchFieldElt1Dot3(root.getTable("ARTICLE"), root);
patchFieldElt1Dot3(root.getTable("ARTICLE_TARIF"), root);
 
if (!tableCommande.getFieldsName().contains("ID_ADRESSE")) {
AlterTable alterCmd = new AlterTable(tableCommande);
alterCmd.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE", true));
1391,7 → 1574,41
 
}
 
private void patchFieldElt1Dot3(SQLTable table, DBRoot root) {
 
List<String> cols = Arrays.asList("PV_HT", "PA_DEVISE_T", "T_PV_HT", "T_PA_TTC", "T_PA_HT", "PA_HT", "T_PV_TTC", "PRIX_METRIQUE_HA_2", "PRIX_METRIQUE_HA_1", "PRIX_METRIQUE_HA_3",
"PRIX_METRIQUE_VT_2", "PRIX_METRIQUE_VT_1", "PRIX_METRIQUE_VT_3", "MARGE_HT", "PA_DEVISE", "PV_U_DEVISE", "PV_T_DEVISE", "PV_TTC");
 
if (table.getField("PV_HT").getType().getDecimalDigits() == 0) {
AlterTable t = new AlterTable(table);
UpdateBuilder builder = new UpdateBuilder(table);
for (String field : cols) {
if (table.contains(field)) {
builder.set(field, table.getField(field).getSQLName().getRest().quote() + "/100");
if (field.contains("TTC")) {
t.alterColumn(field, EnumSet.allOf(Properties.class), "numeric(16,2)", "0", false);
} else {
t.alterColumn(field, EnumSet.allOf(Properties.class), "numeric(16,6)", "0", false);
}
}
}
 
try {
table.getBase().getDataSource().execute(t.asString());
table.getSchema().updateVersion();
table.fetchFields();
} catch (SQLException ex) {
throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
}
 
String req2 = builder.asString();
root.getDBSystemRoot().getDataSource().execute(req2);
}
 
}
 
private void addHAElementField(SQLTable table, DBRoot root) throws SQLException {
 
boolean alter = false;
AlterTable t = new AlterTable(table);
if (!table.getFieldsName().contains("QTE_ACHAT")) {
1424,6 → 1641,11
alter = true;
}
 
// if (!table.getFieldsName().contains("POURCENT_REMISE")) {
// t.addColumn("POURCENT_REMISE", "numeric(16,2) DEFAULT 0");
// alter = true;
// }
 
if (alter) {
try {
table.getBase().getDataSource().execute(t.asString());
1433,7 → 1655,7
throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
}
}
 
patchFieldElt1Dot3(table, root);
}
 
private void addModeleField(SQLTable table, DBRoot root) throws SQLException {
1551,6 → 1773,7
throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
}
}
patchFieldElt1Dot3(table, root);
}
 
private void updateSocieteSchema(final DBRoot root) throws IOException, Exception {
1571,7 → 1794,8
// 1. root.refetch() clears the graph
// 2. we add some foreign field (the graph is still null)
// 3. we use a method that needs the graph
// 4. the graph is created and throws an exception when it wants to use the new field not in
// 4. the graph is created and throws an exception when it wants to use
// the new field not in
// the structure
sysRoot.getGraph();
 
1632,9 → 1856,10
}
}
 
SQLSelect sel2 = new SQLSelect(tableReglmt.getBase());
SQLSelect sel2 = new SQLSelect();
sel2.addSelect(tableReglmt.getKey());
sel2.setWhere(new Where(tableReglmt.getField("NOM"), "=", "CESU"));
@SuppressWarnings("unchecked")
List<Number> l2 = (List<Number>) ds.executeCol(sel2.asString());
if (l2.size() == 0) {
SQLRowValues rowVals = new SQLRowValues(tableReglmt);
1686,10 → 1911,10
//
final ModuleManager instance = new ModuleManager();
instance.setRoot(root);
final Set<String> modulesIds = instance.getDBInstalledModules().keySet();
final List<ModuleReference> refs = instance.getRemoteInstalledModules();
final Set<String> allUsedTable = new HashSet<String>();
for (String id : modulesIds) {
Set<String> tableNames = instance.getCreatedItems(id).get0();
for (ModuleReference ref : refs) {
Set<String> tableNames = instance.getCreatedTables(ref);
allUsedTable.addAll(tableNames);
}
System.out.println("Tables used by modules:" + allUsedTable);
1777,7 → 2002,7
Map<SQLTable, Set<Number>> ids = getIdsForTables(extTables);
 
//
SQLSelect s = new SQLSelect(root.getBase(), true);
SQLSelect s = new SQLSelect(true);
if (table.getPrimaryKeys().size() != 1) {
return;
}
1825,7 → 2050,7
 
private Set<Number> getIdsForTable(SQLTable table) {
final DBRoot dbRoot = table.getDBRoot();
SQLSelect s = new SQLSelect(dbRoot.getBase(), true);
SQLSelect s = new SQLSelect(true);
s.addSelect(table.getKey());
List<Number> result = dbRoot.getDBSystemRoot().getDataSource().executeCol(s.asString());
return new HashSet<Number>(result);
1894,7 → 2119,7
if (table == null) {
throw new IllegalArgumentException("null table");
}
SQLSelect sel = new SQLSelect(table.getBase());
SQLSelect sel = new SQLSelect();
sel.addSelectStar(table);
sel.setWhere(new Where(table.getField("NOM"), "=", var));
List<SQLRow> l = (List<SQLRow>) table.getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ServerFinderConfig.java
20,6 → 20,9
import org.openconcerto.utils.cc.IClosure;
 
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
211,8 → 214,14
@Override
public void executeChecked(DBSystemRoot input) {
// don't map all the database
input.setRootToMap(root);
final List<String> asList = new ArrayList<String>(2);
if (!root.equals("Common")) {
asList.add("Common");
}
asList.add(root);
input.setRootsToMap(asList);
 
}
}, null);
 
return server;
264,7 → 273,7
@Override
public String toString() {
return this.getType() + ":" + this.getIp() + ":" + this.getPort() + " file:" + this.getFile() + " " + this.getOpenconcertoLogin() + "/" + this.getOpenconcertoPassword() + " ["
+ this.getDbLogin() + "/" + this.getDbPassword() + "]";
+ this.getDbLogin() + "/" + this.getDbPassword() + "] systemRoot:" + systemRoot;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/translation_en.xml
New file
0,0 → 1,153
<translation lang="fr">
<!-- File -->
<menu id="menu.file" label="File" />
<menu id="backup" label="Backup" />
<menu id="export.accounting" label="Export accounting" />
<menu id="modules" label="Modules" />
<menu id="preferences" label="Preferences" />
<menu id="quit" label="Exit" />
<!-- Creation -->
<menu id="menu.create" label="Create" />
<menu id="accounting" label="Accounting" />
<menu id="accounting.entry.create" label="Accounting entries" />
<menu id="customer" label="Customers" />
<menu id="customer.quote.create" label="Quote" />
<menu id="customer.letter.create" label="Letter" />
<menu id="customer.proposal.create" label="Proposal" />
<menu id="project.create" label="Project" />
<menu id="appointment.create" label="Appointment" />
<menu id="mission.create" label="Mission" />
<menu id="mission.notice.create" label="Mission notice" />
<menu id="customer.delivery.create" label="Delivery" />
<menu id="customer.order.create" label="Order" />
<menu id="pos.sale.create" label="Sale (POS)" />
<menu id="customer.invoice.create" label="Invoice" />
<menu id="kd.invoice.create" label="Invoice" />
<menu id="customer.credit.create" label="Credit note" />
<menu id="supplier" label="Supplier" />
<menu id="supplier.order.create" label="Supplier order" />
<menu id="supplier.receipt.create" label="Supplier receipt" />
<menu id="supplier.purchase.create" label="Supplier purchase" />
<menu id="supplier.credit.create" label="Supplier credit" />
<menu id="stock.io.create" label="Stock" />
 
<!-- List -->
<menu id="menu.list" label="Mamagement" />
<menu id="menu.list.customer" label="CRM" />
<menu id="customer.list" label="Customer" />
<menu id="contact.list" label="Contacts" />
<menu id="customer.history" label="Customer history" />
<menu id="customer.quote.list" label="Quotes" />
<menu id="customer.proposal.list" label="Proposals" />
<menu id="customer.proposal.item.list" label="Proposal items" />
<menu id="menu.list.mission" label="Missions" />
<menu id="project.list" label="Projects" />
<menu id="mission.list" label="Missions" />
<menu id="appointment.list" label="Appointments" />
<menu id="appointment.unplanned.list" label="" />
<menu id="appointment.notvalidated.list" label="" />
<menu id="mission.order.list" label="" />
<menu id="mission.notice.list" label="" />
<menu id="customer.order.list" label="Orders" />
<menu id="customer.delivery.list" label="Deliveries" />
<menu id="sales.list" label="Sales" />
<menu id="customer.invoice.list" label="Invoices" />
<menu id="payment.factoring.create" label="" />
<menu id="payment.factoring.list" label="" />
<menu id="customer.credit.list" label="Credits" />
<menu id="menu.list.supplier" label="Supplier" />
<menu id="supplier.list" label="Suppliers" />
<menu id="supplier.contact.list" label="Supplier contacta" />
<menu id="supplier.history" label="Supplier history" />
<menu id="supplier.order.list" label="Supplier orders" />
<menu id="supplier.receipt.list" label="Supplier receipts" />
<menu id="supplier.purchase.list" label="Purchases" />
<menu id="supplier.credit.list" label="Supplier credits" />
<menu id="product.list" label="Product list" />
<menu id="product.reference.list" label="Reference list" />
<menu id="stock.io.list" label="Stock movements" />
<menu id="menu.list.pos" label="Point of sales" />
<menu id="pos.receipt.list" label="Receipts (POS)" />
<menu id="pos.sales.report" label="Sales (POS)" />
<menu id="sales.report" label="" />
<!-- Accounting -->
<menu id="menu.accounting" label="Accounting" />
<menu id="accounting.balance" label="Balance" />
<menu id="accounting.client.balance" label="Customer balance" />
<menu id="accounting.analytical.result" label="Anatycal result" />
<menu id="accounting.ledger" label="Ledger" />
<menu id="accounting.general.ledger" label="General ledger" />
<menu id="accounting.entries.ledger" label="Ledger entries" />
<menu id="accounting.entries.list" label="List of ledger entries" />
<menu id="menu.accounting.closing" label="Closing" />
<menu id="accounting.validating" label="Validating" />
<menu id="accounting.closing" label="Closing" />
<!-- Documents -->
<menu id="menu.report" label="Reporting" />
<menu id="accounting.vat.report" label="VAT report" />
<menu id="accounting.costs.report" label="Costs report" />
<menu id="accounting.balance.report" label="Balance report" />
<menu id="employe.social.report" label="Social report" />
<!-- Stats -->
<menu id="menu.stats" label="Statistics" />
<menu id="sales.graph" label="Sales" />
<menu id="sales.margin.graph" label="Margins" />
<menu id="sales.list.report" label="Sales report" />
<menu id="sales.product.graph" label="Products" />
<menu id="sales.product.margin.graph" label="Product pargin" />
<menu id="sales.list.graph" label="Sales lists" />
<!-- Payment -->
<menu id="menu.payment" label="Payment" />
<menu id="payment.checking.create" label="Payment checking" />
<menu id="payment.reconciliation.create" label="Reconciliation" />
<menu id="menu.payment.customer" label="Customer" />
<menu id="customer.invoice.unpaid.list" label="Unpaid invoices" />
<menu id="customer.dept.list" label="Customer depts" />
<menu id="customer.payment.list" label="Payments" />
<menu id="customer.payment.followup.list" label="Followup" />
<menu id="customer.payment.check.pending.list" label="Customer checks" />
<menu id="customer.payment.check.pending.create" label="Pending checks" />
<menu id="customer.credit.check.list" label="Credit checks" />
<menu id="customer.credit.check.create" label="Pending credit checks" />
<menu id="menu.payment.supplier" label="Supplier" />
<menu id="supplier.invoice.unpaid.list" label="Unpaid supplier invoices" />
<menu id="supplier.bill.list" label="Supplier bills" />
<menu id="supplier.payment.check.list" label="Supplier checks" />
<menu id="supplier.payment.check.pending.list" label="Pending checks to suppliers" />
<!-- Payroll -->
<menu id="menu.payroll" label="Paye" />
<menu id="payroll.list.report.print" label="Apyroll report" />
<menu id="payroll.profile.list" label="Profiles" />
<menu id="payroll.history" label="History" />
<menu id="payroll.create" label="Payroll" />
<menu id="payroll.deposit.create" label="Deposit" />
<menu id="employee.list" label="Employees" />
<menu id="payroll.section" label="Sections" />
<menu id="payroll.variable" label="Variables" />
<menu id="payroll.closing" label="Monthly closing" />
<!-- Organization -->
<menu id="menu.organization" label="Structure" />
<menu id="accounting.chart" label="Accounting chart" />
<menu id="accounting.journal" label="Acounting journals" />
<menu id="user.list" label="Users" />
<menu id="user.right.list" label="User rights" />
<menu id="user.task.right" label="Task rigths" />
<menu id="salesman.list" label="Salemen" />
<menu id="pos.list" label="Points of sales" />
<menu id="secretary.list" label="Secretaries" />
<menu id="auditor.list" label="Auditors" />
<menu id="index.list" label="Indexes" />
<menu id="enterprise.list" label="Enterprises" />
<menu id="divison.list" label="" />
<menu id="divison.bank.list" label="" />
<menu id="enterprise.create" label="New enterprise" />
<menu id="mission.sample.list" label="" />
<menu id="mission.code.list" label="" />
<menu id="department.list" label="" />
<!-- Help -->
<menu id="menu.test" label="Tests" />
<!-- Help -->
<menu id="menu.help" label="Help" />
<menu id="information" label="About" />
<menu id="tips" label="Tips" />
</translation>
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ComptaPropsConfiguration.java
129,6 → 129,7
import org.openconcerto.erp.core.supplychain.order.element.SaisieAchatSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionElementSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.element.CodeFournisseurSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
import org.openconcerto.erp.core.supplychain.supplier.element.EcheanceFournisseurSQLElement;
135,10 → 136,17
import org.openconcerto.erp.core.supplychain.supplier.element.FournisseurSQLElement;
import org.openconcerto.erp.generationDoc.element.ModeleSQLElement;
import org.openconcerto.erp.generationDoc.element.TypeModeleSQLElement;
import org.openconcerto.erp.generationDoc.provider.AdresseFullClientValueProvider;
import org.openconcerto.erp.generationDoc.provider.AdresseRueClientValueProvider;
import org.openconcerto.erp.generationDoc.provider.AdresseVilleCPClientValueProvider;
import org.openconcerto.erp.generationDoc.provider.AdresseVilleClientValueProvider;
import org.openconcerto.erp.generationDoc.provider.AdresseVilleNomClientValueProvider;
import org.openconcerto.erp.generationDoc.provider.PrixUnitaireRemiseProvider;
import org.openconcerto.erp.generationDoc.provider.QteTotalProvider;
import org.openconcerto.erp.generationDoc.provider.UserCreateInitialsValueProvider;
import org.openconcerto.erp.generationDoc.provider.UserCurrentInitialsValueProvider;
import org.openconcerto.erp.generationDoc.provider.UserModifyInitialsValueProvider;
import org.openconcerto.erp.generationEcritures.provider.SalesInvoiceAccountingRecordsProvider;
import org.openconcerto.erp.injector.AchatAvoirSQLInjector;
import org.openconcerto.erp.injector.ArticleCommandeEltSQLInjector;
import org.openconcerto.erp.injector.BonFactureSQLInjector;
271,7 → 279,7
}
}
 
static File getConfFile() {
public static File getConfFile() {
return getConfFile(APP_NAME);
}
 
390,15 → 398,26
// ATTN this works because this is executed last (i.e. if you put this in a superclass
// this won't work since e.g. app.name won't have its correct value)
this.setupLogging("logs");
registerAccountingProvider();
registerCellValueProvider();
UserRightsManager.getInstance().register(new ComptaTotalUserRight());
}
 
private void registerAccountingProvider() {
SalesInvoiceAccountingRecordsProvider.register();
}
 
private void registerCellValueProvider() {
UserCreateInitialsValueProvider.register();
UserModifyInitialsValueProvider.register();
UserCurrentInitialsValueProvider.register();
PrixUnitaireRemiseProvider.register();
AdresseRueClientValueProvider.register();
AdresseVilleClientValueProvider.register();
AdresseVilleCPClientValueProvider.register();
AdresseVilleNomClientValueProvider.register();
AdresseFullClientValueProvider.register();
QteTotalProvider.register();
}
 
@Override
642,7 → 661,7
dir.addSQLElement(new CourrierClientSQLElement());
 
dir.addSQLElement(new ClassementConventionnelSQLElement());
 
dir.addSQLElement(CodeFournisseurSQLElement.class);
dir.addSQLElement(new CommandeSQLElement());
dir.addSQLElement(new CommandeElementSQLElement());
dir.addSQLElement(new CommandeClientSQLElement());
790,7 → 809,7
private void setSocieteShowAs() {
final ShowAs showAs = this.getShowAs();
showAs.setRoot(getRootSociete());
showAs.show("ARTICLE", "NOM");
showAs.show("ARTICLE", "NOM", "ID_FAMILLE_ARTICLE");
showAs.show("ACTIVITE", "CODE_ACTIVITE");
showAs.show("ADRESSE", SQLRow.toList("RUE,VILLE"));
final DBRoot root = this.getRootSociete();
917,6 → 936,8
}
}
TemplateNXProps.getInstance();
// Prefetch undefined
rootSociete.getTables().iterator().next().getUndefinedID();
}
 
private void setMapper() {
/trunk/OpenConcerto/src/org/openconcerto/erp/config/MainFrame.java
14,106 → 14,10
package org.openconcerto.erp.config;
 
import org.openconcerto.erp.action.AboutAction;
import org.openconcerto.erp.action.AstuceAction;
import org.openconcerto.erp.action.GestionDroitsAction;
import org.openconcerto.erp.action.NouvelleSocieteAction;
import org.openconcerto.erp.action.PreferencesAction;
import org.openconcerto.erp.action.SauvegardeBaseAction;
import org.openconcerto.erp.action.TaskAdminAction;
import org.openconcerto.erp.action.list.ListeDesSocietesCommonsAction;
import org.openconcerto.erp.action.list.ListeDesUsersCommonAction;
import org.openconcerto.erp.core.common.ui.StatusPanel;
import org.openconcerto.erp.core.customerrelationship.customer.action.ListeDesClientsAction;
import org.openconcerto.erp.core.customerrelationship.customer.action.ListeDesContactsAction;
import org.openconcerto.erp.core.customerrelationship.customer.action.NouvelHistoriqueListeClientAction;
import org.openconcerto.erp.core.customerrelationship.mail.action.ListeDesCourriersClientsAction;
import org.openconcerto.erp.core.customerrelationship.mail.action.NouveauCourrierClientAction;
import org.openconcerto.erp.core.finance.accounting.action.CompteResultatBilanAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatBalanceAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatChargeAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatGrandLivreAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatJournauxAction;
import org.openconcerto.erp.core.finance.accounting.action.ExportRelationExpertAction;
import org.openconcerto.erp.core.finance.accounting.action.GenerePointageAction;
import org.openconcerto.erp.core.finance.accounting.action.GestionPlanComptableEAction;
import org.openconcerto.erp.core.finance.accounting.action.ImpressionLivrePayeAction;
import org.openconcerto.erp.core.finance.accounting.action.ListeDesEcrituresAction;
import org.openconcerto.erp.core.finance.accounting.action.ListeEcritureParClasseAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauClotureAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauJournalAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauLettrageAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauPointageAction;
import org.openconcerto.erp.core.finance.accounting.action.NouvelleValidationAction;
import org.openconcerto.erp.core.finance.accounting.action.ResultatAnalytiqueAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesAEncaisserAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesAvoirAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesFournisseursAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesEncaissementsAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesReferencesAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesRelancesAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesTraitesFournisseursAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauDecaissementChequeAvoirAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauListeDesChequesADecaisserAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauListeDesChequesAEncaisserAction;
import org.openconcerto.erp.core.finance.tax.action.DeclarationTVAAction;
import org.openconcerto.erp.core.humanresources.ListeDesContactsAdministratif;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesCommerciauxAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSalariesAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSecretairesAction;
import org.openconcerto.erp.core.humanresources.employe.action.N4DSAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ClotureMensuellePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.EditionFichePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesProfilsPayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesRubriquesDePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesVariablesPayes;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelAcompteAction;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelHistoriqueFichePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelleSaisieKmAction;
import org.openconcerto.erp.core.reports.stat.action.EvolutionCAAction;
import org.openconcerto.erp.core.reports.stat.action.EvolutionMargeAction;
import org.openconcerto.erp.core.reports.stat.action.VenteArticleGraphAction;
import org.openconcerto.erp.core.reports.stat.action.VenteArticleMargeGraphAction;
import org.openconcerto.erp.core.sales.credit.action.ListeDesAvoirsClientsAction;
import org.openconcerto.erp.core.sales.credit.action.NouveauAvoirClientAction;
import org.openconcerto.erp.core.sales.invoice.action.EtatVenteAction;
import org.openconcerto.erp.core.sales.invoice.action.GenListeVenteAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDebiteursAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDesElementsFactureAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDesVentesAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeSaisieVenteFactureAction;
import org.openconcerto.erp.core.sales.invoice.action.ListesFacturesClientsImpayeesAction;
import org.openconcerto.erp.core.sales.invoice.action.NouveauSaisieVenteComptoirAction;
import org.openconcerto.erp.core.sales.invoice.action.NouveauSaisieVenteFactureAction;
import org.openconcerto.erp.core.sales.order.action.NouvelleCommandeClientAction;
import org.openconcerto.erp.core.sales.pos.action.ListeDesCaissesTicketAction;
import org.openconcerto.erp.core.sales.pos.action.ListeDesTicketsAction;
import org.openconcerto.erp.core.sales.product.action.FamilleArticleAction;
import org.openconcerto.erp.core.sales.product.action.ListeDesArticlesAction;
import org.openconcerto.erp.core.sales.quote.action.ListeDesDevisAction;
import org.openconcerto.erp.core.sales.quote.action.ListeDesElementsPropositionsAction;
import org.openconcerto.erp.core.sales.quote.action.NouveauDevisAction;
import org.openconcerto.erp.core.sales.quote.action.NouvellePropositionAction;
import org.openconcerto.erp.core.sales.shipment.action.ListeDesBonsDeLivraisonAction;
import org.openconcerto.erp.core.sales.shipment.action.NouveauBonLivraisonAction;
import org.openconcerto.erp.core.supplychain.credit.action.ListeDesAvoirsFournisseurAction;
import org.openconcerto.erp.core.supplychain.credit.action.NouvelAvoirFournisseurAction;
import org.openconcerto.erp.core.supplychain.order.action.ListeDesCommandesAction;
import org.openconcerto.erp.core.supplychain.order.action.ListeDesCommandesClientAction;
import org.openconcerto.erp.core.supplychain.order.action.ListeSaisieAchatAction;
import org.openconcerto.erp.core.supplychain.order.action.NouveauSaisieAchatAction;
import org.openconcerto.erp.core.supplychain.order.action.NouvelleCommandeAction;
import org.openconcerto.erp.core.supplychain.receipt.action.ListeDesBonsReceptionsAction;
import org.openconcerto.erp.core.supplychain.receipt.action.NouveauBonReceptionAction;
import org.openconcerto.erp.core.supplychain.stock.action.ListeDesMouvementsStockAction;
import org.openconcerto.erp.core.supplychain.stock.action.NouvelleSaisieMouvementStockAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListeDesContactsFournisseursAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListeDesFournisseursAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListesFacturesFournImpayeesAction;
import org.openconcerto.erp.core.supplychain.supplier.action.NouvelHistoriqueListeFournAction;
import org.openconcerto.erp.modules.ModuleFrame;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.erp.rights.NXRights;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.LockAdminUserRight;
123,6 → 27,8
import org.openconcerto.ui.AutoHideTabbedPane;
import org.openconcerto.ui.MenuUtils;
import org.openconcerto.ui.SwingThreadUtils;
import org.openconcerto.ui.group.Group;
import org.openconcerto.ui.group.Item;
import org.openconcerto.ui.state.WindowStateManager;
import org.openconcerto.utils.JImage;
import org.openconcerto.utils.OSXAdapter;
148,6 → 54,7
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
 
public class MainFrame extends JFrame {
214,7 → 121,7
super();
 
this.setIconImage(new ImageIcon(this.getClass().getResource("frameicon.png")).getImage());
this.setJMenuBar(Gestion.isMinimalMode() ? createMinimalMenu() : createMenu());
 
Container co = this.getContentPane();
co.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
279,7 → 186,7
new NewsUpdater(this.image);
}
 
private final JMenuBar createMinimalMenu() {
public final JMenuBar createMinimalMenu() {
final JMenuBar res = new JMenuBar();
final JMenu fileMenu = new JMenu(FILE_MENU);
fileMenu.add(new SauvegardeBaseAction());
307,321 → 214,116
return res;
}
 
private final JMenuBar createMenu() {
JMenuBar result = new JMenuBar();
 
JMenu menu;
 
Boolean bModeVenteComptoir = DefaultNXProps.getInstance().getBooleanValue("ArticleVenteComptoir", true);
 
// Fichier
menu = new JMenu(FILE_MENU);
 
// FIXME Probleme AliasedTable --> flush showAs, ...
// item = new JMenuItem(new NouvelleConnexionAction());
// menu.add(item);
 
// Boolean bSauvegarde =
// UserManager.getInstance().getCurrentUser().getRights().haveRight("BACKUP");
// if (bSauvegarde) {
 
// item = new JMenuItem("Sauvegarde"); // eSauvegarde
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
final ComptaPropsConfiguration configuration = (ComptaPropsConfiguration) Configuration.getInstance();
 
menu.add(new SauvegardeBaseAction());
menu.add(new ExportRelationExpertAction());
 
// if (rights.haveRight(NXRights.LOCK_MENU_TEST.getCode())) {
// menu.add(new GenerateEcrFactAction());
// menu.add(new ImportCielDataAction());
// }
 
menu.add(new JMenuItem(new AbstractAction("Modules") {
@Override
public void actionPerformed(ActionEvent e) {
final ModuleFrame frame = new ModuleFrame();
frame.setMinimumSize(new Dimension(480, 640));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public final JMenuBar createMenu() {
final JMenuBar result = new JMenuBar();
final Group g = MenuManager.getInstance().getGroup();
for (int i = 0; i < g.getSize(); i++) {
final Item item = g.getItem(i);
result.add(createJMenuFrom(item));
}
}));
 
if (!Gestion.MAC_OS_X) {
menu.add(new JMenuItem(new PreferencesAction()));
menu.add(new JMenuItem(new AbstractAction("Quitter") {
@Override
public void actionPerformed(ActionEvent e) {
quit();
return result;
}
}));
}
result.add(menu);
 
// Saisie
result.add(getCreateMenu(bModeVenteComptoir, rights, configuration));
 
// Gestion
result.add(getListeMenu(bModeVenteComptoir, rights, configuration));
 
// Etats
menu = getStateMenu();
 
if (rights.haveRight(ComptaUserRight.MENU)) {
result.add(menu);
private JMenu createJMenuFrom(final Item item) {
final String id = item.getId();
String name = MenuManager.getInstance().getLabelForId(id);
String menuLabel = name;
if (name == null || name.trim().isEmpty()) {
menuLabel = id;
}
 
menu = getDeclarationMenu();
if (rights.haveRight(ComptaUserRight.MENU)) {
result.add(menu);
final JMenu m = new JMenu(menuLabel);
if (name == null || name.trim().isEmpty()) {
m.setForeground(new Color(200, 65, 20));
}
 
// Stat
menu = getStatMenu(configuration);
 
if (rights.haveRight(NXRights.ACCES_MENU_STAT.getCode())) {
result.add(menu);
if (item instanceof Group) {
final Group g = (Group) item;
for (int i = 0; i < g.getSize(); i++) {
final Item child = g.getItem(i);
final List<JMenuItem> menuItems = createJMenuItemsFrom(child);
if (child.getLocalHint().isSeparated() && m.getMenuComponentCount() > 0) {
m.addSeparator();
}
 
// Paiement
menu = getPaiementMenu(rights);
result.add(menu);
 
// Paye
menu = getPayrollMenu();
 
if (rights.haveRight(NXRights.LOCK_MENU_PAYE.getCode())) {
result.add(menu);
for (JMenuItem jMenuItem : menuItems) {
m.add(jMenuItem);
}
 
// Structure
menu = getStructureMenu(rights, configuration);
 
if (rights.haveRight(NXRights.ACCES_MENU_STRUCTURE.getCode())) {
result.add(menu);
}
// Aide
menu = new JMenu(HELP_MENU);
menu.add(new JMenuItem(AboutAction.getInstance()));
menu.add(new JMenuItem(new AstuceAction()));
} else {
 
result.add(menu);
return result;
m.add(createJMenuItemForId(id));
}
 
public JMenu getPayrollMenu() {
JMenu menu;
menu = new JMenu(PAYROLL_MENU);
 
menu.add(new ImpressionLivrePayeAction());
menu.add(new ListeDesProfilsPayeAction());
menu.add(new NouvelHistoriqueFichePayeAction());
menu.add(new EditionFichePayeAction());
menu.add(new NouvelAcompteAction());
menu.add(new ListeDesSalariesAction());
menu.add(new JSeparator());
menu.add(new ListeDesRubriquesDePayeAction());
menu.add(new ListeDesVariablesPayes());
menu.add(new JSeparator());
menu.add(new ClotureMensuellePayeAction());
return menu;
return m;
}
 
public JMenu getStructureMenu(final UserRights rights, final ComptaPropsConfiguration configuration) {
JMenu menu;
menu = new JMenu(STRUCTURE_MENU);
 
if (rights.haveRight(ComptaUserRight.MENU)) {
 
menu.add(new GestionPlanComptableEAction());
menu.add(new NouveauJournalAction());
menu.add(new JSeparator());
 
private List<JMenuItem> createJMenuItemsFrom(Item item) {
List<JMenuItem> result = new ArrayList<JMenuItem>();
final String id = item.getId();
String name = MenuManager.getInstance().getLabelForId(id);
String menuLabel = name;
if (name == null || name.trim().isEmpty()) {
menuLabel = id;
}
 
if (rights.haveRight(LockAdminUserRight.LOCK_MENU_ADMIN)) {
menu.add(new JMenuItem(new ListeDesUsersCommonAction()));
menu.add(new JMenuItem(new GestionDroitsAction()));
menu.add(new JMenuItem(new TaskAdminAction()));
menu.add(new JSeparator());
if (item instanceof Group) {
Group g = (Group) item;
JMenu m = null;
if (g.getLocalHint().showLabel()) {
m = new JMenu(menuLabel);
if (name == null || name.trim().isEmpty()) {
m.setForeground(new Color(20, 65, 200));
}
 
menu.add(new ListeDesContactsAdministratif());
menu.add(new ListeDesCommerciauxAction());
menu.add(new JSeparator());
menu.add(new ListeDesCaissesTicketAction());
 
menu.add(new JSeparator());
 
menu.add(new ListeDesSocietesCommonsAction());
 
menu.add(new NouvelleSocieteAction());
 
return menu;
result.add(m);
}
 
public JMenu getPaiementMenu(final UserRights rights) {
JMenu menu;
menu = new JMenu(PAYMENT_MENU);
 
if (rights.haveRight(ComptaUserRight.MENU) || rights.haveRight(ComptaUserRight.POINTAGE_LETTRAGE)) {
menu.add(new NouveauPointageAction());
menu.add(new NouveauLettrageAction());
menu.add(new JSeparator());
if (g.getLocalHint().isSeparated() && !g.getLocalHint().showLabel()) {
// result.add(null);
}
 
if (rights.haveRight(NXRights.GESTION_ENCAISSEMENT.getCode())) {
menu.add(new ListesFacturesClientsImpayeesAction());
menu.add(new ListeDebiteursAction());
menu.add(new ListeDesEncaissementsAction());
menu.add(new ListeDesRelancesAction());
menu.add(new JSeparator());
menu.add(new ListeDesChequesAEncaisserAction());
menu.add(new NouveauListeDesChequesAEncaisserAction());
menu.add(new JSeparator());
menu.add(new ListeDesChequesAvoirAction());
menu.add(new NouveauDecaissementChequeAvoirAction());
menu.add(new JSeparator());
for (int i = 0; i < g.getSize(); i++) {
final Item child = g.getItem(i);
final List<JMenuItem> menuItems = createJMenuItemsFrom(child);
for (JMenuItem jMenuItem : menuItems) {
if (m == null) {
result.add(jMenuItem);
} else {
if (child.getLocalHint().isSeparated()) {
m.addSeparator();
}
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
menu.add(new ListesFacturesFournImpayeesAction());
menu.add(new ListeDesTraitesFournisseursAction());
menu.add(new ListeDesChequesFournisseursAction());
menu.add(new NouveauListeDesChequesADecaisserAction());
m.add(jMenuItem);
}
return menu;
}
 
public JMenu getStatMenu(final ComptaPropsConfiguration configuration) {
JMenu menu;
menu = new JMenu(STATS_MENU);
 
 
menu.add(new EvolutionCAAction());
 
menu.add(new EvolutionMargeAction());
menu.addSeparator();
menu.add(new GenListeVenteAction());
menu.add(new VenteArticleGraphAction());
menu.add(new VenteArticleMargeGraphAction());
menu.add(new EtatVenteAction());
return menu;
}
 
public JMenu getDeclarationMenu() {
JMenu menu;
menu = new JMenu(DECLARATION_MENU);
 
menu.add(new DeclarationTVAAction());
menu.add(new JSeparator());
menu.add(new EtatChargeAction());
menu.add(new CompteResultatBilanAction());
menu.add(new N4DSAction());
return menu;
} else {
result.add(createJMenuItemForId(id));
}
 
public JMenu getStateMenu() {
JMenu menu;
menu = new JMenu(STATE_MENU);
 
menu.add(new EtatBalanceAction());
menu.add(new org.openconcerto.erp.core.finance.accounting.action.BalanceAgeeAction());
menu.add(new EtatJournauxAction());
menu.add(new EtatGrandLivreAction());
menu.add(new ListeDesEcrituresAction());
menu.add(new ListeEcritureParClasseAction());
menu.add(new JSeparator());
menu.add(new NouvelleValidationAction());
menu.add(new JMenuItem(new NouveauClotureAction()));
return menu;
return result;
}
 
public JMenu getListeMenu(Boolean bModeVenteComptoir, final UserRights rights, final ComptaPropsConfiguration configuration) {
JMenu menu;
menu = new JMenu(LIST_MENU);
 
menu.add(new ListeDesClientsAction());
menu.add(new ListeDesContactsAction());
 
if (rights.haveRight(NXRights.ACCES_HISTORIQUE.getCode())) {
menu.add(new NouvelHistoriqueListeClientAction());
public JMenuItem createJMenuItemForId(final String id) {
final String name = MenuManager.getInstance().getLabelForId(id);
String menuLabel = name;
if (name == null || name.trim().isEmpty()) {
menuLabel = id;
}
final JMenuItem menuItem = new JMenuItem(menuLabel);
Action actionForId = MenuManager.getInstance().getActionForId(id);
if (actionForId == null) {
actionForId = new AbstractAction(name) {
 
 
menu.add(new JSeparator());
 
menu.add(new ListeDesDevisAction());
 
 
menu.add(new ListeDesCommandesClientAction());
menu.add(new ListeDesBonsDeLivraisonAction());
 
boolean useListDesVentesAction = bModeVenteComptoir;
if (useListDesVentesAction) {
menu.add(new ListeDesVentesAction());
 
} else {
 
menu.add(new ListeSaisieVenteFactureAction());
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(MainFrame.this, "No action for " + id);
}
 
menu.add(new ListeDesAvoirsClientsAction());
 
menu.add(new JSeparator());
menu.add(new ListeDesFournisseursAction());
menu.add(new ListeDesContactsFournisseursAction());
menu.add(new NouvelHistoriqueListeFournAction());
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
menu.add(new ListeDesCommandesAction());
menu.add(new ListeDesBonsReceptionsAction());
menu.add(new ListeSaisieAchatAction());
menu.add(new ListeDesAvoirsFournisseurAction());
};
menuItem.setForeground(new Color(200, 65, 95));
}
 
menu.add(new JSeparator());
menu.add(new ListeDesArticlesAction());
menu.add(new ListeDesMouvementsStockAction());
 
menu.add(new JSeparator());
menu.add(new ListeDesTicketsAction());
return menu;
if (name == null || name.trim().isEmpty()) {
menuItem.setForeground(new Color(20, 65, 200));
}
 
public JMenu getCreateMenu(Boolean bModeVenteComptoir, final UserRights rights, final ComptaPropsConfiguration configuration) {
 
JMenu menu = new JMenu(CREATE_MENU);
 
if (rights.haveRight(ComptaUserRight.MENU)) {
menu.add(new NouvelleSaisieKmAction());
menu.add(new JSeparator());
actionForId.putValue(Action.NAME, menuLabel);
menuItem.setAction(actionForId);
return menuItem;
}
 
menu.add(new NouveauDevisAction());
 
 
menu.add(new JSeparator());
 
menu.add(new NouveauBonLivraisonAction());
menu.add(new NouvelleCommandeClientAction());
if (bModeVenteComptoir && rights.haveRight("VENTE_COMPTOIR")) {
menu.add(new NouveauSaisieVenteComptoirAction());
}
menu.add(new NouveauSaisieVenteFactureAction());
 
menu.add(new NouveauAvoirClientAction());
 
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
 
menu.add(new JSeparator());
menu.add(new NouvelleCommandeAction());
menu.add(new NouveauBonReceptionAction());
menu.add(new NouveauSaisieAchatAction());
menu.add(new NouvelAvoirFournisseurAction());
menu.add(new NouvelleSaisieMouvementStockAction());
}
return menu;
}
 
public JMenuItem addMenuItem(final Action action, final String... path) {
return this.addMenuItem(action, Arrays.asList(path));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/MenuManager.java
New file
0,0 → 1,52
/*
* 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.config;
 
import org.openconcerto.ui.group.Group;
import org.openconcerto.utils.i18n.TranslationManager;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.Action;
 
public class MenuManager {
private static final MenuManager instance = new MenuManager();
 
public static final MenuManager getInstance() {
return instance;
}
 
private Group group = new Group("menu.main");
private Map<String, Action> actions = new HashMap<String, Action>();
 
 
public Group getGroup() {
return group;
}
 
public void registerAction(String id, Action a) {
actions.put(id, a);
}
 
public Action getActionForId(String id) {
return this.actions.get(id);
}
 
public String getLabelForId(String id) {
return TranslationManager.getInstance().getTranslationForMenu(id);
}
 
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/DefaultMenuConfiguration.java
New file
0,0 → 1,629
/*
* 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.config;
 
import org.openconcerto.erp.action.AboutAction;
import org.openconcerto.erp.action.AstuceAction;
import org.openconcerto.erp.action.GestionDroitsAction;
import org.openconcerto.erp.action.NouvelleSocieteAction;
import org.openconcerto.erp.action.PreferencesAction;
import org.openconcerto.erp.action.SauvegardeBaseAction;
import org.openconcerto.erp.action.TaskAdminAction;
import org.openconcerto.erp.action.list.ListeDesSocietesCommonsAction;
import org.openconcerto.erp.action.list.ListeDesUsersCommonAction;
import org.openconcerto.erp.core.customerrelationship.customer.action.ListeDesClientsAction;
import org.openconcerto.erp.core.customerrelationship.customer.action.ListeDesContactsAction;
import org.openconcerto.erp.core.customerrelationship.customer.action.NouvelHistoriqueListeClientAction;
import org.openconcerto.erp.core.customerrelationship.mail.action.ListeDesCourriersClientsAction;
import org.openconcerto.erp.core.finance.accounting.action.BalanceAgeeAction;
import org.openconcerto.erp.core.finance.accounting.action.CompteResultatBilanAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatBalanceAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatChargeAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatGrandLivreAction;
import org.openconcerto.erp.core.finance.accounting.action.EtatJournauxAction;
import org.openconcerto.erp.core.finance.accounting.action.ExportRelationExpertAction;
import org.openconcerto.erp.core.finance.accounting.action.GenerePointageAction;
import org.openconcerto.erp.core.finance.accounting.action.GestionPlanComptableEAction;
import org.openconcerto.erp.core.finance.accounting.action.ImpressionLivrePayeAction;
import org.openconcerto.erp.core.finance.accounting.action.ListeDesEcrituresAction;
import org.openconcerto.erp.core.finance.accounting.action.ListeEcritureParClasseAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauClotureAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauJournalAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauLettrageAction;
import org.openconcerto.erp.core.finance.accounting.action.NouveauPointageAction;
import org.openconcerto.erp.core.finance.accounting.action.NouvelleValidationAction;
import org.openconcerto.erp.core.finance.accounting.action.ResultatAnalytiqueAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesAEncaisserAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesAvoirAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesChequesFournisseursAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesEncaissementsAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesReferencesAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesRelancesAction;
import org.openconcerto.erp.core.finance.payment.action.ListeDesTraitesFournisseursAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauDecaissementChequeAvoirAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauListeDesChequesADecaisserAction;
import org.openconcerto.erp.core.finance.payment.action.NouveauListeDesChequesAEncaisserAction;
import org.openconcerto.erp.core.finance.tax.action.DeclarationTVAAction;
import org.openconcerto.erp.core.humanresources.ListeDesContactsAdministratif;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesCommerciauxAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSalariesAction;
import org.openconcerto.erp.core.humanresources.employe.action.ListeDesSecretairesAction;
import org.openconcerto.erp.core.humanresources.employe.action.N4DSAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ClotureMensuellePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.EditionFichePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesProfilsPayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesRubriquesDePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.ListeDesVariablesPayes;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelAcompteAction;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelHistoriqueFichePayeAction;
import org.openconcerto.erp.core.humanresources.payroll.action.NouvelleSaisieKmAction;
import org.openconcerto.erp.core.reports.stat.action.EvolutionCAAction;
import org.openconcerto.erp.core.reports.stat.action.EvolutionMargeAction;
import org.openconcerto.erp.core.reports.stat.action.VenteArticleGraphAction;
import org.openconcerto.erp.core.reports.stat.action.VenteArticleMargeGraphAction;
import org.openconcerto.erp.core.sales.credit.action.ListeDesAvoirsClientsAction;
import org.openconcerto.erp.core.sales.credit.action.NouveauAvoirClientAction;
import org.openconcerto.erp.core.sales.invoice.action.EtatVenteAction;
import org.openconcerto.erp.core.sales.invoice.action.GenListeVenteAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDebiteursAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDesElementsFactureAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeDesVentesAction;
import org.openconcerto.erp.core.sales.invoice.action.ListeSaisieVenteFactureAction;
import org.openconcerto.erp.core.sales.invoice.action.ListesFacturesClientsImpayeesAction;
import org.openconcerto.erp.core.sales.invoice.action.NouveauSaisieVenteComptoirAction;
import org.openconcerto.erp.core.sales.invoice.action.NouveauSaisieVenteFactureAction;
import org.openconcerto.erp.core.sales.order.action.ListeDesCommandesClientAction;
import org.openconcerto.erp.core.sales.order.action.NouvelleCommandeClientAction;
import org.openconcerto.erp.core.sales.pos.action.ListeDesCaissesTicketAction;
import org.openconcerto.erp.core.sales.pos.action.ListeDesTicketsAction;
import org.openconcerto.erp.core.sales.product.action.FamilleArticleAction;
import org.openconcerto.erp.core.sales.product.action.ListeDesArticlesAction;
import org.openconcerto.erp.core.sales.quote.action.ListeDesDevisAction;
import org.openconcerto.erp.core.sales.quote.action.ListeDesElementsPropositionsAction;
import org.openconcerto.erp.core.sales.quote.action.NouveauDevisAction;
import org.openconcerto.erp.core.sales.shipment.action.ListeDesBonsDeLivraisonAction;
import org.openconcerto.erp.core.sales.shipment.action.NouveauBonLivraisonAction;
import org.openconcerto.erp.core.supplychain.credit.action.ListeDesAvoirsFournisseurAction;
import org.openconcerto.erp.core.supplychain.credit.action.NouvelAvoirFournisseurAction;
import org.openconcerto.erp.core.supplychain.order.action.ListeDesCommandesAction;
import org.openconcerto.erp.core.supplychain.order.action.ListeSaisieAchatAction;
import org.openconcerto.erp.core.supplychain.order.action.NouveauSaisieAchatAction;
import org.openconcerto.erp.core.supplychain.order.action.NouvelleCommandeAction;
import org.openconcerto.erp.core.supplychain.receipt.action.ListeDesBonsReceptionsAction;
import org.openconcerto.erp.core.supplychain.receipt.action.NouveauBonReceptionAction;
import org.openconcerto.erp.core.supplychain.stock.action.ListeDesMouvementsStockAction;
import org.openconcerto.erp.core.supplychain.stock.action.NouvelleSaisieMouvementStockAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListeDesContactsFournisseursAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListeDesFournisseursAction;
import org.openconcerto.erp.core.supplychain.supplier.action.ListesFacturesFournImpayeesAction;
import org.openconcerto.erp.core.supplychain.supplier.action.NouvelHistoriqueListeFournAction;
import org.openconcerto.erp.modules.ModuleFrame;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.erp.rights.NXRights;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.LockAdminUserRight;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.ui.group.Group;
import org.openconcerto.ui.group.LayoutHints;
 
import java.awt.Dimension;
import java.awt.event.ActionEvent;
 
import javax.swing.AbstractAction;
 
public class DefaultMenuConfiguration {
public void registerMenuTranslations() {
 
}
 
public void createMenuGroup() {
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
 
Group mGroup = MenuManager.getInstance().getGroup();
mGroup.add(createFilesMenuGroup());
mGroup.add(createCreationMenuGroup());
mGroup.add(createListMenuGroup());
if (rights.haveRight(ComptaUserRight.MENU)) {
mGroup.add(createAccountingMenuGroup());
mGroup.add(createStatsDocumentsGroup());
}
if (rights.haveRight(NXRights.ACCES_MENU_STAT.getCode())) {
mGroup.add(createStatsMenuGroup());
}
mGroup.add(createPaymentMenuGroup());
if (rights.haveRight(NXRights.LOCK_MENU_PAYE.getCode())) {
mGroup.add(createPayrollMenuGroup());
}
if (rights.haveRight(NXRights.ACCES_MENU_STRUCTURE.getCode())) {
mGroup.add(createOrganizationMenuGroup());
}
mGroup.add(createHelpMenuGroup());
if (rights.haveRight(NXRights.LOCK_MENU_TEST.getCode())) {
mGroup.add(createTestMenuGroup());
}
 
}
 
public void registerMenuActions() {
registerFilesMenuActions();
registerCreationMenuActions();
registerListMenuActions();
registerAccountingMenuActions();
registerStatsDocumentsActions();
registerStatsMenuActions();
registerPaymentMenuActions();
registerPayrollMenuActions();
registerOrganizationMenuActions();
registerHelpMenuActions();
registerHelpTestActions();
}
 
/**
* Groups
*/
private Group createFilesMenuGroup() {
Group group = new Group("menu.file");
group.addItem("backup");
group.addItem("export.accounting");
group.addItem("modules");
group.addItem("preferences");
group.addItem("quit");
return group;
}
 
private Group createCreationMenuGroup() {
final Group group = new Group("menu.create");
final Boolean bModeVenteComptoir = DefaultNXProps.getInstance().getBooleanValue("ArticleVenteComptoir", true);
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
final Group accountingGroup = new Group("accounting");
if (rights.haveRight(ComptaUserRight.MENU)) {
accountingGroup.addItem("accounting.entry.create");
}
group.add(accountingGroup);
 
final Group customerGroup = new Group("customer", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
customerGroup.addItem("customer.quote.create");
customerGroup.addItem("customer.delivery.create");
customerGroup.addItem("customer.order.create");
if (bModeVenteComptoir && rights.haveRight("VENTE_COMPTOIR")) {
customerGroup.addItem("pos.sale.create");
}
customerGroup.addItem("customer.invoice.create");
 
customerGroup.addItem("customer.credit.create");
group.add(customerGroup);
 
final Group supplierGroup = new Group("supplier", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
group.add(supplierGroup);
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
supplierGroup.addItem("supplier.order.create");
supplierGroup.addItem("supplier.receipt.create");
supplierGroup.addItem("supplier.purchase.create");
supplierGroup.addItem("supplier.credit.create");
group.addItem("stock.io.create");
}
 
return group;
}
 
private Group createHelpMenuGroup() {
final Group group = new Group("menu.help");
group.addItem("information");
group.addItem("tips");
return group;
}
 
private Group createOrganizationMenuGroup() {
final Group group = new Group("menu.organization");
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
 
if (rights.haveRight(ComptaUserRight.MENU)) {
final Group gAccounting = new Group("menu.organization.accounting", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gAccounting.addItem("accounting.chart");
gAccounting.addItem("accounting.journal");
group.add(gAccounting);
}
 
if (rights.haveRight(LockAdminUserRight.LOCK_MENU_ADMIN)) {
final Group gUser = new Group("menu.organization.user", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gUser.addItem("user.list");
gUser.addItem("user.right.list");
gUser.addItem("user.task.right");
group.add(gUser);
}
 
group.addItem("contact.list");
group.addItem("salesman.list");
 
final Group gPos = new Group("menu.organization.pos", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gPos.addItem("pos.list");
group.add(gPos);
 
 
group.addItem("enterprise.list");
 
group.addItem("enterprise.create");
return group;
}
 
private Group createPayrollMenuGroup() {
final Group group = new Group("menu.payroll");
group.addItem("payroll.list.report.print");
group.addItem("payroll.profile.list");
group.addItem("payroll.history");
group.addItem("payroll.create");
group.addItem("payroll.deposit.create");
group.addItem("employee.list");
final Group groupConfig = new Group("menu.payroll.config", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
groupConfig.addItem("payroll.section");
groupConfig.addItem("payroll.variable");
group.add(groupConfig);
group.addItem("payroll.closing");
return group;
}
 
private Group createPaymentMenuGroup() {
final Group group = new Group("menu.payment");
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
 
if (rights.haveRight(ComptaUserRight.MENU) || rights.haveRight(ComptaUserRight.POINTAGE_LETTRAGE)) {
group.addItem("payment.checking.create");
group.addItem("payment.reconciliation.create");
}
 
if (rights.haveRight(NXRights.GESTION_ENCAISSEMENT.getCode())) {
Group gCustomer = new Group("menu.payment.customer");
gCustomer.addItem("customer.invoice.unpaid.list");
gCustomer.addItem("customer.dept.list");
gCustomer.addItem("customer.payment.list");
gCustomer.addItem("customer.payment.followup.list");
gCustomer.addItem("customer.payment.check.pending.list");
gCustomer.addItem("customer.payment.check.pending.create");
gCustomer.addItem("customer.credit.check.list");
gCustomer.addItem("customer.credit.check.create");
group.add(gCustomer);
}
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
Group gSupplier = new Group("menu.payment.supplier");
gSupplier.addItem("supplier.invoice.unpaid.list");
gSupplier.addItem("supplier.bill.list");
gSupplier.addItem("supplier.payment.check.list");
gSupplier.addItem("supplier.payment.check.pending.list");
group.add(gSupplier);
}
return group;
}
 
private Group createStatsMenuGroup() {
final Group group = new Group("menu.stats");
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
 
group.addItem("sales.graph");
 
group.addItem("sales.margin.graph");
 
group.addItem("sales.list.report");
group.addItem("sales.product.graph");
group.addItem("sales.product.margin.graph");
group.addItem("sales.list.graph");
return group;
}
 
private Group createStatsDocumentsGroup() {
final Group group = new Group("menu.report");
group.addItem("accounting.vat.report");
group.addItem("accounting.costs.report");
group.addItem("accounting.balance.report");
group.addItem("employe.social.report");
return group;
}
 
private Group createAccountingMenuGroup() {
final Group group = new Group("menu.accounting");
group.addItem("accounting.balance");
group.addItem("accounting.client.balance");
group.addItem("accounting.ledger");
group.addItem("accounting.general.ledger");
group.addItem("accounting.entries.ledger");
group.addItem("accounting.entries.list");
final Group gClosing = new Group("menu.accounting.closing", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gClosing.addItem("accounting.validating");
gClosing.addItem("accounting.closing");
group.add(gClosing);
return group;
}
 
private Group createListMenuGroup() {
final Group group = new Group("menu.list");
 
final Boolean bModeVenteComptoir = DefaultNXProps.getInstance().getBooleanValue("ArticleVenteComptoir", true);
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
 
Group gCustomer = new Group("menu.list.customer", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gCustomer.addItem("customer.list");
gCustomer.addItem("contact.list");
 
if (rights.haveRight(NXRights.ACCES_HISTORIQUE.getCode())) {
gCustomer.addItem("customer.history");
}
 
 
gCustomer.addItem("customer.quote.list");
 
 
gCustomer.addItem("customer.order.list");
gCustomer.addItem("customer.delivery.list");
group.add(gCustomer);
 
boolean useListDesVentesAction = bModeVenteComptoir;
if (useListDesVentesAction) {
gCustomer.addItem("sales.list");
 
} else {
 
gCustomer.addItem("customer.invoice.list");
}
 
gCustomer.addItem("customer.credit.list");
 
final Group gSupplier = new Group("menu.list.supplier", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gSupplier.addItem("supplier.list");
gSupplier.addItem("supplier.contact.list");
gSupplier.addItem("supplier.history");
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
gSupplier.addItem("supplier.order.list");
gSupplier.addItem("supplier.receipt.list");
gSupplier.addItem("supplier.purchase.list");
gSupplier.addItem("supplier.credit.list");
}
group.add(gSupplier);
 
final Group gProduct = new Group("menu.list.product", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gProduct.addItem("product.list");
gProduct.addItem("stock.io.list");
group.add(gProduct);
 
final Group gPos = new Group("menu.list.pos", LayoutHints.DEFAULT_NOLABEL_SEPARATED_GROUP_HINTS);
gPos.addItem("pos.receipt.list");
group.add(gPos);
return group;
}
 
private Group createTestMenuGroup() {
final Group group = new Group("menu.test");
return group;
}
 
/**
* Actions
* */
private void registerFilesMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
mManager.registerAction("backup", new SauvegardeBaseAction());
mManager.registerAction("export.accounting", new ExportRelationExpertAction());
mManager.registerAction("modules", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
final ModuleFrame frame = new ModuleFrame();
frame.setMinimumSize(new Dimension(480, 640));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
if (!Gestion.MAC_OS_X) {
mManager.registerAction("preferences", new PreferencesAction());
mManager.registerAction("quit", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
MainFrame.getInstance().quit();
}
});
}
}
 
private void registerCreationMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
final Boolean bModeVenteComptoir = DefaultNXProps.getInstance().getBooleanValue("ArticleVenteComptoir", true);
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
 
if (rights.haveRight(ComptaUserRight.MENU)) {
mManager.registerAction("accounting.entry.create", new NouvelleSaisieKmAction());
}
 
mManager.registerAction("customer.quote.create", new NouveauDevisAction());
 
mManager.registerAction("customer.delivery.create", new NouveauBonLivraisonAction());
mManager.registerAction("customer.order.create", new NouvelleCommandeClientAction());
if (bModeVenteComptoir && rights.haveRight("VENTE_COMPTOIR")) {
mManager.registerAction("pos.sale.create", new NouveauSaisieVenteComptoirAction());
}
mManager.registerAction("customer.invoice.create", new NouveauSaisieVenteFactureAction());
 
mManager.registerAction("customer.credit.create", new NouveauAvoirClientAction());
 
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
 
mManager.registerAction("supplier.order.create", new NouvelleCommandeAction());
mManager.registerAction("supplier.receipt.create", new NouveauBonReceptionAction());
mManager.registerAction("supplier.purchase.create", new NouveauSaisieAchatAction());
mManager.registerAction("supplier.credit.create", new NouvelAvoirFournisseurAction());
mManager.registerAction("stock.io.create", new NouvelleSaisieMouvementStockAction());
}
 
}
 
private void registerListMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
final Boolean bModeVenteComptoir = DefaultNXProps.getInstance().getBooleanValue("ArticleVenteComptoir", true);
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
 
mManager.registerAction("customer.list", new ListeDesClientsAction());
mManager.registerAction("contact.list", new ListeDesContactsAction());
 
if (rights.haveRight(NXRights.ACCES_HISTORIQUE.getCode())) {
mManager.registerAction("customer.history", new NouvelHistoriqueListeClientAction());
}
 
 
mManager.registerAction("customer.quote.list", new ListeDesDevisAction());
 
 
mManager.registerAction("customer.order.list", new ListeDesCommandesClientAction());
mManager.registerAction("customer.delivery.list", new ListeDesBonsDeLivraisonAction());
 
boolean useListDesVentesAction = bModeVenteComptoir;
if (useListDesVentesAction) {
mManager.registerAction("sales.list", new ListeDesVentesAction());
 
} else {
 
mManager.registerAction("customer.invoice.list", new ListeSaisieVenteFactureAction());
}
 
mManager.registerAction("customer.credit.list", new ListeDesAvoirsClientsAction());
 
mManager.registerAction("supplier.list", new ListeDesFournisseursAction());
mManager.registerAction("supplier.contact.list", new ListeDesContactsFournisseursAction());
mManager.registerAction("supplier.history", new NouvelHistoriqueListeFournAction());
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
mManager.registerAction("supplier.order.list", new ListeDesCommandesAction());
mManager.registerAction("supplier.receipt.list", new ListeDesBonsReceptionsAction());
mManager.registerAction("supplier.purchase.list", new ListeSaisieAchatAction());
mManager.registerAction("supplier.credit.list", new ListeDesAvoirsFournisseurAction());
}
 
mManager.registerAction("product.list", new ListeDesArticlesAction());
mManager.registerAction("stock.io.list", new ListeDesMouvementsStockAction());
 
mManager.registerAction("pos.receipt.list", new ListeDesTicketsAction());
 
}
 
private void registerAccountingMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
mManager.registerAction("accounting.balance", new EtatBalanceAction());
mManager.registerAction("accounting.client.balance", new BalanceAgeeAction());
mManager.registerAction("accounting.ledger", new EtatJournauxAction());
mManager.registerAction("accounting.general.ledger", new EtatGrandLivreAction());
mManager.registerAction("accounting.entries.ledger", new ListeDesEcrituresAction());
mManager.registerAction("accounting.entries.list", new ListeEcritureParClasseAction());
mManager.registerAction("accounting.validating", new NouvelleValidationAction());
mManager.registerAction("accounting.closing", new NouveauClotureAction());
}
 
private void registerStatsDocumentsActions() {
final MenuManager mManager = MenuManager.getInstance();
mManager.registerAction("accounting.vat.report", new DeclarationTVAAction());
mManager.registerAction("accounting.costs.report", new EtatChargeAction());
mManager.registerAction("accounting.balance.report", new CompteResultatBilanAction());
mManager.registerAction("employe.social.report", new N4DSAction());
}
 
private void registerStatsMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
 
mManager.registerAction("sales.graph", new EvolutionCAAction());
 
mManager.registerAction("sales.margin.graph", new EvolutionMargeAction());
 
mManager.registerAction("sales.list.report", new GenListeVenteAction());
mManager.registerAction("sales.product.graph", new VenteArticleGraphAction());
mManager.registerAction("sales.product.margin.graph", new VenteArticleMargeGraphAction());
mManager.registerAction("sales.list.graph", new EtatVenteAction());
 
}
 
private void registerPaymentMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
 
if (rights.haveRight(ComptaUserRight.MENU) || rights.haveRight(ComptaUserRight.POINTAGE_LETTRAGE)) {
mManager.registerAction("payment.checking.create", new NouveauPointageAction());
mManager.registerAction("payment.reconciliation.create", new NouveauLettrageAction());
}
 
if (rights.haveRight(NXRights.GESTION_ENCAISSEMENT.getCode())) {
mManager.registerAction("customer.invoice.unpaid.list", new ListesFacturesClientsImpayeesAction());
mManager.registerAction("customer.dept.list", new ListeDebiteursAction());
mManager.registerAction("customer.payment.list", new ListeDesEncaissementsAction());
mManager.registerAction("customer.payment.followup.list", new ListeDesRelancesAction());
mManager.registerAction("customer.payment.check.pending.list", new ListeDesChequesAEncaisserAction());
mManager.registerAction("customer.payment.check.pending.create", new NouveauListeDesChequesAEncaisserAction());
mManager.registerAction("customer.credit.check.list", new ListeDesChequesAvoirAction());
mManager.registerAction("customer.credit.check.create", new NouveauDecaissementChequeAvoirAction());
}
if (rights.haveRight(NXRights.LOCK_MENU_ACHAT.getCode())) {
mManager.registerAction("supplier.invoice.unpaid.list", new ListesFacturesFournImpayeesAction());
mManager.registerAction("supplier.bill.list", new ListeDesTraitesFournisseursAction());
mManager.registerAction("supplier.payment.check.list", new ListeDesChequesFournisseursAction());
mManager.registerAction("supplier.payment.check.pending.list", new NouveauListeDesChequesADecaisserAction());
}
 
}
 
private void registerPayrollMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
mManager.registerAction("payroll.list.report.print", new ImpressionLivrePayeAction());
mManager.registerAction("payroll.profile.list", new ListeDesProfilsPayeAction());
mManager.registerAction("payroll.history", new NouvelHistoriqueFichePayeAction());
mManager.registerAction("payroll.create", new EditionFichePayeAction());
mManager.registerAction("payroll.deposit.create", new NouvelAcompteAction());
mManager.registerAction("employee.list", new ListeDesSalariesAction());
mManager.registerAction("payroll.section", new ListeDesRubriquesDePayeAction());
mManager.registerAction("payroll.variable", new ListeDesVariablesPayes());
mManager.registerAction("payroll.closing", new ClotureMensuellePayeAction());
 
}
 
private void registerOrganizationMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
final UserRights rights = UserManager.getInstance().getCurrentUser().getRights();
final ComptaPropsConfiguration configuration = ComptaPropsConfiguration.getInstanceCompta();
if (rights.haveRight(ComptaUserRight.MENU)) {
mManager.registerAction("accounting.chart", new GestionPlanComptableEAction());
mManager.registerAction("accounting.journal", new NouveauJournalAction());
}
 
if (rights.haveRight(LockAdminUserRight.LOCK_MENU_ADMIN)) {
mManager.registerAction("user.list", new ListeDesUsersCommonAction());
mManager.registerAction("user.right.list", new GestionDroitsAction());
mManager.registerAction("user.task.right", new TaskAdminAction());
}
 
mManager.registerAction("contact.list", new ListeDesContactsAdministratif());
mManager.registerAction("salesman.list", new ListeDesCommerciauxAction());
mManager.registerAction("pos.list", new ListeDesCaissesTicketAction());
 
 
mManager.registerAction("enterprise.list", new ListeDesSocietesCommonsAction());
 
mManager.registerAction("enterprise.create", new NouvelleSocieteAction());
}
 
private void registerHelpMenuActions() {
final MenuManager mManager = MenuManager.getInstance();
mManager.registerAction("information", AboutAction.getInstance());
mManager.registerAction("tips", new AstuceAction());
}
 
private void registerHelpTestActions() {
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/InstalledModulesPanel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/InstalledModuleTableModel.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleFactory.java
194,7 → 194,7
}
 
public final Preferences getPreferences(final boolean local, final DBRoot root) {
final Preferences rootPrefs = local ? Preferences.userRoot() : new SQLPreferences(root);
final Preferences rootPrefs = local ? Preferences.userRoot() : SQLPreferences.getMemCached(root);
// ID is a package name, transform to path to avoid bumping into the size limit
return rootPrefs.node(ModulePreferencePanel.getAppPrefPath() + this.getID().replace('.', '/'));
}
203,4 → 203,8
public String toString() {
return getClass().getSimpleName() + " " + getID() + " (" + getMajorVersion() + "." + getMinorVersion() + ")";
}
 
public ModuleReference getReference() {
return new ModuleReference(this.id, this.version);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleTableModel.java
29,23 → 29,23
 
static private final int CB_INDEX = 0;
 
private final IFactory<? extends Collection<ModuleFactory>> rowSource;
private List<ModuleFactory> list;
private final Set<ModuleFactory> selection;
private final IFactory<? extends Collection<ModuleReference>> rowSource;
private List<ModuleReference> list;
private final Set<ModuleReference> selection;
 
public ModuleTableModel(IFactory<? extends Collection<ModuleFactory>> rowSource) {
public ModuleTableModel(IFactory<? extends Collection<ModuleReference>> rowSource) {
this.rowSource = rowSource;
this.selection = new HashSet<ModuleFactory>();
this.selection = new HashSet<ModuleReference>();
this.reload();
}
 
public final void reload() {
this.list = new ArrayList<ModuleFactory>(this.rowSource.createChecked());
this.list = new ArrayList<ModuleReference>(this.rowSource.createChecked());
// sort alphabetically
Collections.sort(this.list, new Comparator<ModuleFactory>() {
Collections.sort(this.list, new Comparator<ModuleReference>() {
@Override
public int compare(ModuleFactory o1, ModuleFactory o2) {
return o1.getID().compareTo(o2.getID());
public int compare(ModuleReference o1, ModuleReference o2) {
return o1.getId().compareTo(o2.getId());
}
});
this.selection.retainAll(this.list);
52,7 → 52,7
this.fireTableDataChanged();
}
 
public final Collection<ModuleFactory> getCheckedRows() {
public final Set<ModuleReference> getCheckedRows() {
return Collections.unmodifiableSet(this.selection);
}
 
66,7 → 66,7
return this.list.size();
}
 
protected final ModuleFactory getFactory(int i) {
protected final ModuleReference getModuleReference(int i) {
return this.list.get(i);
}
 
87,10 → 87,14
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final ModuleFactory f = this.getFactory(rowIndex);
final ModuleReference f = this.getModuleReference(rowIndex);
if (columnIndex == 1) {
try {
return f.getName();
final ModuleFactory moduleFactory = ModuleManager.getInstance().getFactories().get(f.getId());
if (moduleFactory != null) {
return moduleFactory.getName();
}
return f.getId();
} catch (Exception e) {
return e.getMessage();
}
111,9 → 115,9
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (columnIndex == CB_INDEX) {
if ((Boolean) value)
this.selection.add(this.getFactory(rowIndex));
this.selection.add(this.getModuleReference(rowIndex));
else
this.selection.remove(this.getFactory(rowIndex));
this.selection.remove(this.getModuleReference(rowIndex));
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AvailableModuleTableModel.java
22,17 → 22,18
 
public class AvailableModuleTableModel extends ModuleTableModel {
 
static private IFactory<Set<ModuleFactory>> getNonInstalled() {
return new IFactory<Set<ModuleFactory>>() {
static private IFactory<Set<ModuleReference>> getNonInstalled() {
return new IFactory<Set<ModuleReference>>() {
@Override
public Set<ModuleFactory> createChecked() {
public Set<ModuleReference> createChecked() {
final ModuleManager mngr = ModuleManager.getInstance();
return CollectionUtils.select(mngr.getFactories().values(), new IPredicate<ModuleFactory>() {
 
return CollectionUtils.select(mngr.getAllKnownModuleReference(), new IPredicate<ModuleReference>() {
@Override
public boolean evaluateChecked(ModuleFactory input) {
return !mngr.isModuleInstalledLocally(input.getID());
public boolean evaluateChecked(ModuleReference input) {
return !mngr.isModuleInstalledLocally(input) && !mngr.isModuleInstalledOnServer(input);
}
}, new HashSet<ModuleFactory>());
}, new HashSet<ModuleReference>());
}
};
}
43,7 → 44,7
 
@Override
public int getColumnCount() {
return 4;
return 5;
}
 
@Override
50,6 → 51,8
public String getColumnName(int column) {
if (column == 3) {
return "Description";
} else if (column == 4) {
return "Information";
}
return super.getColumnName(column);
}
56,9 → 59,17
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final ModuleReference moduleReference = this.getModuleReference(rowIndex);
if (columnIndex == 3) {
return this.getFactory(rowIndex).getDescription();
final ModuleFactory f = ModuleManager.getInstance().getFactories().get(moduleReference);
if (f != null) {
return f.getDescription();
} else {
return "";
}
} else if (columnIndex == 4) {
return ModuleManager.getInstance().getInfo(moduleReference);
}
return super.getValueAt(rowIndex, columnIndex);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ServerInstalledModulesPanel.java
New file
0,0 → 1,238
/*
* 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.modules;
 
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.IFactory;
 
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
 
public class ServerInstalledModulesPanel extends JPanel {
 
private final ServerInstalledModuleTableModel tm;
private ModuleFrame moduleFrame;
 
ServerInstalledModulesPanel(final ModuleFrame moduleFrame) {
this.moduleFrame = moduleFrame;
this.setOpaque(false);
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
// Toolbar
c.weightx = 0;
c.weighty = 0;
 
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
final JButton activateButton = new JButton(new LocalInstallAction());
activateButton.setOpaque(false);
this.add(activateButton, c);
c.gridx++;
final JButton desactivateButton = new JButton(new UninstallAction());
desactivateButton.setOpaque(false);
this.add(desactivateButton, c);
 
// Rows
 
final IFactory<List<ModuleReference>> rowSource = new IFactory<List<ModuleReference>>() {
@Override
public List<ModuleReference> createChecked() {
return ModuleManager.getInstance().getRemoteInstalledModules();
}
};
 
this.tm = new ServerInstalledModuleTableModel(rowSource);
final JTable t = new JTable(this.tm);
t.setShowGrid(false);
t.setShowVerticalLines(false);
t.setFocusable(false);
t.setRowSelectionAllowed(false);
t.setColumnSelectionAllowed(false);
t.setCellSelectionEnabled(false);
t.getColumnModel().getColumn(0).setMinWidth(24);
t.getColumnModel().getColumn(0).setPreferredWidth(24);
t.getColumnModel().getColumn(0).setMaxWidth(24);
t.getColumnModel().getColumn(0).setResizable(false);
t.getColumnModel().getColumn(1).setMinWidth(148);
// Version
t.getColumnModel().getColumn(2).setMinWidth(48);
t.getColumnModel().getColumn(2).setMaxWidth(48);
// Etat
t.getColumnModel().getColumn(3).setMinWidth(80);
t.getColumnModel().getColumn(3).setPreferredWidth(148);
t.getColumnModel().getColumn(3).setCellRenderer(new DefaultTableCellRenderer() {
 
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
ModuleReference ref = (ModuleReference) tm.getModuleReferenceAt(row);
if (!ModuleManager.getInstance().isModuleInstalledLocally(ref) && ModuleManager.getInstance().isModuleRequiredLocally(ref)) {
c.setBackground(Color.ORANGE);
c.setForeground(Color.BLACK);
} else {
c.setBackground(table.getBackground());
c.setForeground(table.getForeground());
}
return c;
}
});
// Installation
t.getColumnModel().getColumn(4).setMinWidth(80);
t.getColumnModel().getColumn(4).setPreferredWidth(80);
// Info
t.getColumnModel().getColumn(5).setMinWidth(160);
t.getColumnModel().getColumn(5).setPreferredWidth(128);
t.getTableHeader().setReorderingAllowed(false);
// allow InstalledModuleTableModel to be gc'd
t.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (!e.getChanged().isDisplayable()) {
t.setModel(new DefaultTableModel());
} else if (t.getModel() != ServerInstalledModulesPanel.this.tm) {
t.setModel(ServerInstalledModulesPanel.this.tm);
}
}
}
});
 
final JScrollPane scroll = new JScrollPane(t);
c.gridx = 0;
c.gridy++;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
 
this.add(scroll, c);
 
ModuleManager.getInstance().dump(System.err);
}
 
public final void reload() {
this.tm.reload();
}
 
private final class LocalInstallAction extends AbstractAction {
LocalInstallAction() {
super("Installer sur le poste");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final Set<ModuleReference> checkedRows = ServerInstalledModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(ServerInstalledModulesPanel.this, "Aucune ligne cochée");
return;
}
// Modules are already installed on server
try {
ModuleManager.getInstance().installModulesLocally(checkedRows);
} catch (Exception e) {
ExceptionHandler.handle(ServerInstalledModulesPanel.this, "Impossible d'installer les modules sur le poste", e);
}
reload();
}
}
 
private final class UninstallAction extends AbstractAction {
 
public UninstallAction() {
super("Désinstaller du serveur");
 
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final Collection<ModuleReference> checkedRows = ServerInstalledModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(ServerInstalledModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final ModuleManager mngr = ModuleManager.getInstance();
final int answer = JOptionPane.showConfirmDialog(ServerInstalledModulesPanel.this,
"Êtes-vous sûr de vouloir désinstaller ces modules ?\nToutes les données seront irrémédiablement effacées.", "Désinstallation de modules", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (answer == JOptionPane.NO_OPTION)
return;
 
try {
final Set<String> ids = new HashSet<String>();
for (final ModuleReference f : checkedRows) {
ids.add(f.getId());
}
final Collection<String> dependentModules = mngr.getDependentModulesRecursively(ids);
if (!dependentModules.isEmpty()) {
final int selectAnswer = JOptionPane.showConfirmDialog(ServerInstalledModulesPanel.this, "Des modules non sélectionnés ont besoin de la sélection : " + dependentModules
+ ".\nVoulez-vous également désinstaller ces modules ?", "Désinstallation de modules", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (selectAnswer == JOptionPane.NO_OPTION)
return;
}
 
final boolean force = (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0;
 
final JDialog dialog = AvailableModulesPanel.displayDialog(ServerInstalledModulesPanel.this,
"Désinstallation " + AvailableModulesPanel.MODULE_FMT.format(new Object[] { checkedRows.size() }));
new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
// Uninstall on server and locally
mngr.uninstall(ids, true, force, false);
return null;
}
 
protected void done() {
try {
this.get();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ServerInstalledModulesPanel.this, "Impossible de désinstaller les modules");
}
moduleFrame.reload();
dialog.dispose();
}
}.execute();
} catch (Exception e) {
ExceptionHandler.handle(ServerInstalledModulesPanel.this, "Impossible de trouver les modules à désinstaller", e);
}
 
// only need to reload us
reload();
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleManager.java
13,8 → 13,10
package org.openconcerto.erp.modules;
 
import org.openconcerto.erp.config.Log;
import org.openconcerto.erp.config.MainFrame;
import org.openconcerto.sql.Configuration;
 
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
24,20 → 26,13
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSyntax;
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.DirectedEdge;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.utils.AlterTable;
import org.openconcerto.sql.utils.ChangeTable;
import org.openconcerto.sql.utils.DropTable;
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
import org.openconcerto.sql.view.list.RowAction;
55,6 → 50,7
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
69,6 → 65,7
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
93,20 → 90,37
@ThreadSafe
public class ModuleManager {
 
/**
* Rules:
*
* To start a module: the module MUST be locally installed AND the module version MUST match the
* locally intalled version
*
* To install a module locally: the module MUST be installed on server AND the module version
* MUST match the server intalled version
*
* Required modules MUST be started
*
* */
 
private static final Logger L = Logger.getLogger(ModuleManager.class.getPackage().getName());
private static final Executor exec = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory(ModuleManager.class.getSimpleName()
+ " executor thread ", Boolean.TRUE));
@GuardedBy("ModuleManager.class")
private static ExecutorService exec = null;
 
private static synchronized final Executor getExec() {
if (exec == null)
exec = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory(ModuleManager.class.getSimpleName()
// not daemon since install() is not atomic
+ " executor thread ", false));
return exec;
}
 
private static final int MIN_VERSION = 0;
private static final String MODULE_COLNAME = "MODULE_NAME";
private static final String MODULE_VERSION_COLNAME = "MODULE_VERSION";
private static final String TABLE_COLNAME = "TABLE";
private static final String FIELD_COLNAME = "FIELD";
private static final String ISKEY_COLNAME = "KEY";
// Don't use String literals for the synchronized blocks
private static final String FWK_MODULE_TABLENAME = new String("FWK_MODULE_METADATA");
 
private static final String fileMutex = new String("modules");
@GuardedBy("ModuleManager.class")
private static ModuleManager instance = null;
private boolean setupDone = false;
 
public static synchronized ModuleManager getInstance() {
if (instance == null)
114,6 → 128,13
return instance;
}
 
public static synchronized void tearDown() {
if (exec != null) {
exec.shutdown();
exec = null;
}
}
 
private static String getMDVariant(ModuleFactory f) {
return f.getID();
}
125,6 → 146,8
// we synchronize the whole install/start and stop/uninstall
@GuardedBy("this")
private final Map<String, AbstractModule> runningModules;
private final List<ModuleReference> missingModules;
private final Map<ModuleReference, String> infos;
// in fact it is also already guarded by "this"
@GuardedBy("modulesElements")
private final Map<String, Collection<SQLElement>> modulesElements;
140,10 → 163,19
private DBRoot root;
@GuardedBy("this")
private Configuration conf;
private Set<ModuleReference> knownModuleReferences = new HashSet<ModuleReference>();
 
private ServerModuleManager remoteModuleManager;
private List<ModuleReference> modulesInstalledOnServer;
private List<ModuleReference> modulesRequiredLocally;
 
public ModuleManager() {
 
//
this.factories = new HashMap<String, ModuleFactory>();
this.runningModules = new HashMap<String, AbstractModule>();
this.missingModules = new ArrayList<ModuleReference>();
this.infos = new HashMap<ModuleReference, String>();
this.dependencyGraph = new SimpleDirectedGraph<ModuleFactory, DirectedEdge<ModuleFactory>>(new EdgeFactory<ModuleFactory, DirectedEdge<ModuleFactory>>() {
@Override
public DirectedEdge<ModuleFactory> createEdge(ModuleFactory sourceVertex, ModuleFactory targetVertex) {
155,8 → 187,13
 
this.root = null;
this.conf = null;
 
}
 
public synchronized final DBRoot getRoot() {
return this.root;
}
 
// *** factories (thread-safe)
 
public final int addFactories(final File dir) {
208,6 → 245,7
private final String addFactory(final ModuleFactory f, final boolean start, final boolean persistent) {
synchronized (this.factories) {
final ModuleFactory prev = this.factories.put(f.getID(), f);
this.knownModuleReferences.add(new ModuleReference(f.getID(), f.getVersion()));
if (prev != null)
L.info("Changing the factory for " + f.getID() + "\nfrom\t" + prev + "\nto\t" + f);
}
231,13 → 269,16
}
}
 
/**
* Get the factory associated to a module id
*
* @return null if no associated factory
* */
private ModuleFactory getFactory(final String id) {
final ModuleFactory res;
synchronized (this.factories) {
res = this.factories.get(id);
}
if (res == null)
throw new IllegalArgumentException("No factory for " + id);
return res;
}
 
253,7 → 294,7
* @param factory the factory to test.
* @return <code>true</code> if the factory can create modules.
*/
public final boolean canFactoryCreate(final ModuleFactory factory) {
private final boolean canFactoryCreate(final ModuleFactory factory) {
return canFactoryCreate(factory, new LinkedHashMap<ModuleFactory, Boolean>());
}
 
290,7 → 331,7
MainFrame.invoke(new Runnable() {
@Override
public void run() {
exec.execute(new Runnable() {
getExec().execute(new Runnable() {
@Override
public void run() {
c.executeChecked(ModuleManager.this);
305,58 → 346,105
// be archived along its parent)
private void registerRequiredModules() throws Exception {
final List<String> modulesToStart = new ArrayList<String>();
final List<ModuleReference> toUpgrade = new ArrayList<ModuleReference>();
missingModules.clear();
boolean areRequiredModulesOk = true;
try {
final Map<String, ModuleFactory> factories = this.getFactories();
for (final Entry<String, ModuleVersion> e : this.getDBInstalledModules().entrySet()) {
final String moduleID = e.getKey();
// modules that just add non-key fields are not required
if (this.areElementsNeeded(moduleID)) {
final List<ModuleReference> required = this.modulesRequiredLocally;
 
this.knownModuleReferences.addAll(required);
for (final ModuleReference ref : required) {
final String moduleID = ref.getId();
System.err.println("ModuleManager: registering required module: " + ref);
final ModuleFactory moduleFactory = factories.get(moduleID);
final String error;
if (moduleFactory == null)
error = "Module '" + moduleID + "' non disponible.";
else if (!moduleFactory.getVersion().equals(e.getValue()))
error = "Mauvaise version pour '" + moduleID + "'. La version " + moduleFactory.getVersion() + " est disponible mais " + e.getValue() + " est requise.";
// check canCreate() after since it's more efficient
else
error = null;
if (error != null) {
// TODO open GUI to resolve the issue
throw new Exception(error);
if (moduleFactory == null) {
System.err.println("ModuleManager: error registering required modules: no factory found for " + ref.getId());
// Error: Missing factory
missingModules.add(ref);
areRequiredModulesOk = false;
this.infos.put(ref, moduleID + " " + ref.getVersion() + " manquant");
} else if (moduleFactory.getVersion().compareTo(ref.getVersion()) < 0) {
System.err.println("ModuleManager: error registering required modules: " + ref.getId() + " " + ref.getVersion() + ": factory too old " + moduleFactory.getVersion());
// Error: Factory too old
for (ModuleReference moduleReference : knownModuleReferences) {
if (moduleReference.getId().equals(ref.getId())) {
setInfo(moduleReference, "version " + ref.getVersion() + " requise");
}
}
areRequiredModulesOk = false;
 
} else if (moduleFactory.getVersion().compareTo(ref.getVersion()) > 0) {
// Error: Installed module too old
System.err.println("ModuleManager: error registering required modules: " + ref.getId() + " " + ref.getVersion() + ": server must be updated (" + moduleFactory.getVersion() + ")");
 
for (ModuleReference moduleReference : knownModuleReferences) {
if (moduleReference.getId().equals(ref.getId())) {
setInfo(moduleReference, "mise à jour du serveur en " + moduleFactory.getVersion() + " requise");
}
}
toUpgrade.add(ref);
areRequiredModulesOk = false;
} else {
modulesToStart.add(moduleID);
 
}
}
}
} catch (Exception e) {
throw new Exception("Impossible de déterminer les modules requis", e);
}
 
if (!areRequiredModulesOk) {
 
System.err.println("ModuleManager: error found on required modules");
dump(System.err);
throw new Exception("Impossible de d'activer les modules requis");
}
final Tuple2<Map<String, AbstractModule>, Set<String>> modules = this.createModules(modulesToStart, false, true);
if (modules.get1().size() > 0)
throw new Exception("Impossible de créer les modules " + modules.get1());
final Set<String> notStarted = modules.get1();
if (notStarted.size() > 0) {
for (String id : notStarted) {
System.err.println("ModuleManager: cannot start required module: " + id);
}
throw new Exception("Impossible de créer les modules requis: " + notStarted);
}
for (final AbstractModule m : modules.get0().values())
this.registerSQLElements(m);
}
 
private void setInfo(ModuleReference moduleReference, String string) {
String s = this.infos.get(moduleReference);
if (s == null || s.length() == 0) {
this.infos.put(moduleReference, string);
} else {
this.infos.put(moduleReference, s + ", " + string);
}
}
 
/**
* Allow to access certain methods without a full {@link #setup(DBRoot, Configuration)}. If
* setup() is subsequently called it must be passed the same root instance.
*
* @param root the root.
* @throws SQLException
* @throws IllegalStateException if already set.
* @see #getDBInstalledModules()
* @see #getCreatedItems(String)
*/
public synchronized final void setRoot(final DBRoot root) {
public synchronized final void setRoot(final DBRoot root) throws SQLException {
if (this.root != root) {
if (this.root != null)
throw new IllegalStateException("Root already set");
this.root = root;
// Server
this.remoteModuleManager = new ServerModuleManager();
this.remoteModuleManager.setRoot(root);
this.reloadServerState();
}
}
 
public synchronized final boolean isSetup() {
return this.getRoot() != null && this.getConf() != null;
return setupDone;
}
 
/**
373,7 → 461,6
throw new IllegalStateException("Already setup");
// modulesElements can be non empty, if a previous setup() failed
assert this.runningModules.isEmpty() && this.modulesComponents.isEmpty() : "Modules cannot start without root & conf";
final DBRoot currentRoot = this.getRoot();
this.setRoot(root);
this.conf = conf;
try {
380,11 → 467,10
this.registerRequiredModules();
} catch (Exception e) {
// allow setup() to be called again
this.root = currentRoot;
this.conf = null;
throw e;
}
assert this.runningModules.isEmpty() && this.modulesComponents.isEmpty() : "registerRequiredModules() should not start modules";
setupDone = true;
}
 
// Preferences is thread-safe
406,9 → 492,16
}
 
protected final Preferences getRequiredIDsPrefs() {
return new SQLPreferences(getRoot()).node("modules/required");
return SQLPreferences.getMemCached(getRoot()).node("modules/required");
}
 
protected final boolean isModuleInstalledLocally(ModuleReference ref) {
final ModuleVersion version = getModuleVersionInstalledLocally(ref.getId());
if (version == null)
return false;
return version.equals(ref.getVersion());
}
 
protected final boolean isModuleInstalledLocally(String id) {
return getLocalVersionFile(id).exists();
}
428,74 → 521,49
}
}
 
public final Collection<String> getModulesInstalledLocally() {
return getModulesVersionInstalledLocally().keySet();
}
 
public final Map<String, ModuleVersion> getModulesVersionInstalledLocally() {
public final List<ModuleReference> getModulesInstalledLocally() {
synchronized (fileMutex) {
final File dir = getLocalDirectory();
if (!dir.isDirectory())
return Collections.emptyMap();
final Map<String, ModuleVersion> res = new HashMap<String, ModuleVersion>();
if (dir == null || !dir.isDirectory())
return Collections.emptyList();
final List<ModuleReference> res = new ArrayList<ModuleReference>();
for (final File d : dir.listFiles()) {
final String id = d.getName();
final ModuleVersion version = getModuleVersionInstalledLocally(id);
if (version != null)
res.put(id, version);
if (version != null) {
res.add(new ModuleReference(id, version));
}
}
return res;
}
}
 
private void setModuleInstalledLocally(ModuleFactory f, boolean b) {
private void setModuleInstalledLocally(ModuleReference f) {
try {
synchronized (fileMutex) {
if (b) {
 
final ModuleVersion vers = f.getVersion();
if (vers.getMerged() < MIN_VERSION)
throw new IllegalStateException("Invalid version : " + vers);
final File versionFile = getLocalVersionFile(f.getID());
final File versionFile = getLocalVersionFile(f.getId());
FileUtils.mkdir_p(versionFile.getParentFile());
FileUtils.write(String.valueOf(vers.getMerged()), versionFile);
} else {
// perhaps add a parameter to only remove the versionFile
FileUtils.rm_R(getLocalDirectory(f.getID()));
 
}
}
} catch (IOException e) {
throw new IllegalStateException("Couldn't change installed status of " + f, e);
}
}
 
private SQLTable getInstalledTable(final DBRoot r) throws SQLException {
synchronized (FWK_MODULE_TABLENAME) {
if (!r.contains(FWK_MODULE_TABLENAME)) {
// store :
// - currently installed module (TABLE_COLNAME & FIELD_COLNAME are null)
// - created tables (FIELD_COLNAME is null)
// - created fields (and whether they are keys)
final SQLCreateTable createTable = new SQLCreateTable(r, FWK_MODULE_TABLENAME);
createTable.setPlain(true);
createTable.addColumn(SQLSyntax.ID_NAME, createTable.getSyntax().getPrimaryIDDefinition());
createTable.addVarCharColumn(MODULE_COLNAME, 128);
createTable.addColumn(TABLE_COLNAME, "varchar(128) NULL");
createTable.addColumn(FIELD_COLNAME, "varchar(128) NULL");
createTable.addColumn(ISKEY_COLNAME, "boolean NULL");
createTable.addColumn(MODULE_VERSION_COLNAME, "bigint NOT NULL");
 
createTable.addUniqueConstraint("uniqModule", Arrays.asList(MODULE_COLNAME, TABLE_COLNAME, FIELD_COLNAME));
 
r.createTable(createTable);
private void removeModuleInstalledLocally(String id) {
try {
// perhaps add a parameter to only remove the versionFile
FileUtils.rm_R(getLocalDirectory(id));
} catch (IOException e) {
throw new IllegalStateException("Couldn't change installed status of " + id, e);
}
}
return r.getTable(FWK_MODULE_TABLENAME);
}
 
public synchronized final DBRoot getRoot() {
return this.root;
}
 
private SQLDataSource getDS() {
return getRoot().getDBSystemRoot().getDataSource();
}
520,148 → 588,76
return new File(this.getLocalDirectory(id), "version");
}
 
public final ModuleVersion getDBInstalledModuleVersion(final String id) throws SQLException {
return getDBInstalledModules(id).get(id);
protected synchronized final boolean isModuleInstalledLocallyOrInDB(String id) throws SQLException {
return this.isModuleInstalledLocally(id) || this.remoteModuleManager.isModuleInstalled(id);
}
 
public final Map<String, ModuleVersion> getDBInstalledModules() throws SQLException {
return getDBInstalledModules(null);
}
private void installOnServer(final Collection<AbstractModule> modules) throws Exception {
final List<ModuleReference> dbInstalledModules = getRemoteInstalledModules();
for (final AbstractModule module : modules) {
 
private final Map<String, ModuleVersion> getDBInstalledModules(final String id) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final SQLSelect sel = new SQLSelect(installedTable.getBase()).addSelectStar(installedTable);
sel.setWhere(Where.isNull(installedTable.getField(TABLE_COLNAME)).and(Where.isNull(installedTable.getField(FIELD_COLNAME))));
if (id != null)
sel.andWhere(new Where(installedTable.getField(MODULE_COLNAME), "=", id));
final Map<String, ModuleVersion> res = new HashMap<String, ModuleVersion>();
for (final SQLRow r : SQLRowListRSH.execute(sel)) {
res.put(r.getString(MODULE_COLNAME), new ModuleVersion(r.getLong(MODULE_VERSION_COLNAME)));
assert !isModuleRunning(module.getFactory().getID());
assert Thread.holdsLock(this);
final ModuleFactory factory = module.getFactory();
final ModuleVersion localVersion = getModuleVersionInstalledLocally(factory.getID());
ModuleVersion version = null;
for (ModuleReference moduleReference : dbInstalledModules) {
if (moduleReference.getId().equals(module.getFactory().getID())) {
version = moduleReference.getVersion();
break;
}
return res;
}
final ModuleVersion lastInstalledVersion = version;
final ModuleVersion moduleVersion = module.getFactory().getVersion();
if (lastInstalledVersion != null && moduleVersion.compareTo(lastInstalledVersion) < 0)
throw new IllegalArgumentException("Module older than the one installed in the DB : " + moduleVersion + " < " + lastInstalledVersion);
if (!moduleVersion.equals(lastInstalledVersion)) {
 
private void setDBInstalledModule(ModuleFactory f, boolean b) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", f.getID());
final Where noItemsW = Where.isNull(installedTable.getField(TABLE_COLNAME)).and(Where.isNull(installedTable.getField(FIELD_COLNAME)));
final Where w = idW.and(noItemsW);
if (b) {
final SQLSelect sel = new SQLSelect(installedTable.getBase());
sel.addSelect(installedTable.getKey());
sel.setWhere(w);
final Number id = (Number) installedTable.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
final SQLRowValues vals = new SQLRowValues(installedTable);
vals.put(MODULE_VERSION_COLNAME, f.getVersion().getMerged());
if (id != null) {
vals.setID(id);
vals.update();
} else {
vals.put(MODULE_COLNAME, f.getID());
vals.put(TABLE_COLNAME, null);
vals.put(FIELD_COLNAME, null);
vals.insert();
try {
SQLUtils.executeAtomic(getDS(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
final String fId = factory.getID();
final DBContext ctxt = new DBContext(localVersion, getRoot(), lastInstalledVersion, remoteModuleManager.getCreatedTables(fId), remoteModuleManager.getCreatedItems(fId));
// configure DB install
module.install(ctxt);
// install in DB
ctxt.execute();
remoteModuleManager.updateModuleFields(factory.getReference(), ctxt);
return null;
}
} else {
installedTable.getDBSystemRoot().getDataSource().execute("DELETE FROM " + installedTable.getSQLName().quote() + " WHERE " + w.getClause());
});
} catch (Exception e) {
// install did not complete successfully
if (getRoot().getServer().getSQLSystem() == SQLSystem.MYSQL)
L.warning("MySQL cannot rollback DDL statements");
throw e;
}
}
 
protected synchronized final boolean isModuleInstalledLocallyOrInDB(String id) throws SQLException {
return this.isModuleInstalledLocally(id) || getDBInstalledModuleVersion(id) != null;
}
 
public final Tuple2<Set<String>, Set<SQLName>> getCreatedItems(final String id) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final SQLSelect sel = new SQLSelect(installedTable.getBase());
sel.addSelect(installedTable.getKey());
sel.addSelect(installedTable.getField(TABLE_COLNAME));
sel.addSelect(installedTable.getField(FIELD_COLNAME));
sel.setWhere(new Where(installedTable.getField(MODULE_COLNAME), "=", id).and(Where.isNotNull(installedTable.getField(TABLE_COLNAME))));
final Set<String> tables = new HashSet<String>();
final Set<SQLName> fields = new HashSet<SQLName>();
for (final SQLRow r : SQLRowListRSH.execute(sel)) {
final String tableName = r.getString(TABLE_COLNAME);
final String fieldName = r.getString(FIELD_COLNAME);
if (fieldName == null)
tables.add(tableName);
else
fields.add(new SQLName(tableName, fieldName));
}
return Tuple2.create(tables, fields);
}
 
private void updateModuleFields(ModuleFactory factory, final DBContext ctxt) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", factory.getID());
// removed items
{
final List<Where> dropWheres = new ArrayList<Where>();
for (final String dropped : ctxt.getRemovedTables()) {
dropWheres.add(new Where(installedTable.getField(TABLE_COLNAME), "=", dropped));
}
for (final SQLName dropped : ctxt.getRemovedFieldsFromExistingTables()) {
dropWheres.add(new Where(installedTable.getField(TABLE_COLNAME), "=", dropped.getItem(0)).and(new Where(installedTable.getField(FIELD_COLNAME), "=", dropped.getItem(1))));
}
if (dropWheres.size() > 0)
installedTable.getDBSystemRoot().getDataSource().execute("DELETE FROM " + installedTable.getSQLName().quote() + " WHERE " + Where.or(dropWheres).and(idW).getClause());
}
// added items
{
final SQLRowValues vals = new SQLRowValues(installedTable);
vals.put(MODULE_VERSION_COLNAME, factory.getVersion().getMerged());
vals.put(MODULE_COLNAME, factory.getID());
for (final String added : ctxt.getAddedTables()) {
vals.put(TABLE_COLNAME, added).put(FIELD_COLNAME, null).insert();
final SQLTable t = ctxt.getRoot().findTable(added);
for (final SQLField field : t.getFields()) {
vals.put(TABLE_COLNAME, added).put(FIELD_COLNAME, field.getName()).put(ISKEY_COLNAME, field.isKey()).insert();
}
vals.remove(ISKEY_COLNAME);
}
for (final SQLName added : ctxt.getAddedFieldsToExistingTables()) {
final SQLTable t = ctxt.getRoot().findTable(added.getItem(0));
final SQLField field = t.getField(added.getItem(1));
vals.put(TABLE_COLNAME, t.getName()).put(FIELD_COLNAME, field.getName()).put(ISKEY_COLNAME, field.isKey()).insert();
}
vals.remove(ISKEY_COLNAME);
}
// Always put true, even if getCreatedItems() is empty, since for now we can't be sure that
// the module didn't insert rows or otherwise changed the DB (MAYBE change SQLDataSource to
// hand out connections with read only user for a new ThreadGroup, or even no connections at
// all). If we could assert that the module didn't access at all the DB, we could add an
// option so that the module can declare not accessing the DB and install() would know that
// the DB version of the module is null. This could be beneficial since different users
// could install different version of modules that only change the UI.
setDBInstalledModule(factory, true);
}
 
private void removeModuleFields(ModuleFactory f) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", f.getID());
installedTable.getDBSystemRoot().getDataSource()
.execute("DELETE FROM " + installedTable.getSQLName().quote() + " WHERE " + Where.isNotNull(installedTable.getField(TABLE_COLNAME)).and(idW).getClause());
setDBInstalledModule(f, false);
}
private void instalLocally(final Collection<AbstractModule> modules) throws Exception {
final List<ModuleReference> dbInstalledModules = getRemoteInstalledModules();
for (final AbstractModule module : modules) {
 
// true if the module has created a table or a key
private final boolean areElementsNeeded(final String id) throws SQLException {
final SQLTable installedTable = getInstalledTable(getRoot());
final SQLSelect sel = new SQLSelect(installedTable.getBase());
sel.addRawSelect("COUNT(*) > 0", null);
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", id);
final Where tableCreated = Where.isNotNull(installedTable.getField(TABLE_COLNAME)).and(Where.isNull(installedTable.getField(FIELD_COLNAME)));
final Where keyCreated = Where.isNotNull(installedTable.getField(FIELD_COLNAME)).and(new Where(installedTable.getField(ISKEY_COLNAME), "=", Boolean.TRUE));
sel.setWhere(idW.and(tableCreated.or(keyCreated)));
return (Boolean) installedTable.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
}
 
private void install(final AbstractModule module) throws Exception {
assert !isModuleRunning(module.getFactory().getID());
assert Thread.holdsLock(this);
final ModuleFactory factory = module.getFactory();
final ModuleVersion localVersion = getModuleVersionInstalledLocally(factory.getID());
final ModuleVersion lastInstalledVersion = getDBInstalledModuleVersion(factory.getID());
ModuleVersion version = null;
for (ModuleReference moduleReference : dbInstalledModules) {
if (moduleReference.getId().equals(module.getFactory().getID())) {
version = moduleReference.getVersion();
break;
}
}
final ModuleVersion lastInstalledVersion = version;
final ModuleVersion moduleVersion = module.getFactory().getVersion();
System.err.println("Module: " + module.getFactory().getID() + " Module:" + moduleVersion + " Local:" + localVersion + " Remote:" + lastInstalledVersion);
if (lastInstalledVersion != null && moduleVersion.compareTo(lastInstalledVersion) < 0)
throw new IllegalArgumentException("Module older than the one installed in the DB : " + moduleVersion + " < " + lastInstalledVersion);
if (localVersion != null && moduleVersion.compareTo(localVersion) < 0)
670,11 → 666,14
// local
final File localDir = getLocalDirectory(factory.getID());
// There are 2 choices to handle the update of files :
// 1. copy dir to a new one and pass it to DBContext, then either rename it to dir or
// 1. copy dir to a new one and pass it to DBContext, then either rename it to dir
// or
// rename it failed
// 2. copy dir to a backup, pass dir to DBContext, then either remove backup or rename
// 2. copy dir to a backup, pass dir to DBContext, then either remove backup or
// rename
// it to dir
// Choice 2 is simpler since the module deals with the same directory in both install()
// Choice 2 is simpler since the module deals with the same directory in both
// install()
// and start()
final File backupDir;
// check if we need a backup
688,25 → 687,15
}
assert localDir.exists();
try {
SQLUtils.executeAtomic(getDS(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
final Tuple2<Set<String>, Set<SQLName>> alreadyCreatedItems = getCreatedItems(factory.getID());
final DBContext ctxt = new DBContext(localDir, localVersion, getRoot(), lastInstalledVersion, alreadyCreatedItems.get0(), alreadyCreatedItems.get1());
// install local
 
final LocalContext ctxt = new LocalContext(localVersion, localDir, lastInstalledVersion);
// local install
module.install(ctxt);
if (!localDir.exists())
throw new IOException("Modules shouldn't remove their directory");
// install in DB
ctxt.execute();
updateModuleFields(factory, ctxt);
return null;
}
});
setModuleInstalledLocally(factory.getReference());
} catch (Exception e) {
// install did not complete successfully
if (getRoot().getServer().getSQLSystem() == SQLSystem.MYSQL)
L.warning("MySQL cannot rollback DDL statements");
 
// keep failed install files and restore previous files
final File failed = FileUtils.addSuffix(localDir, ".failed");
if (failed.exists() && !FileUtils.rmR(failed))
725,11 → 714,13
assert localDir.exists();
if (backupDir != null)
FileUtils.rm_R(backupDir);
setModuleInstalledLocally(factory, true);
 
}
assert moduleVersion.equals(getModuleVersionInstalledLocally(factory.getID())) && moduleVersion.equals(getDBInstalledModuleVersion(factory.getID()));
 
}
 
}
 
private void registerSQLElements(final AbstractModule module) {
final String id = module.getFactory().getID();
synchronized (this.modulesElements) {
756,12 → 747,12
}
}
 
private void setupComponents(final AbstractModule module, final Tuple2<Set<String>, Set<SQLName>> alreadyCreatedItems) throws SQLException {
private void setupComponents(final AbstractModule module, Set<String> alreadyCreatedTables, Set<SQLName> alreadyCreatedItems) throws SQLException {
assert SwingUtilities.isEventDispatchThread();
final String id = module.getFactory().getID();
if (!this.modulesComponents.containsKey(id)) {
final SQLElementDirectory dir = getDirectory();
final ComponentsContext ctxt = new ComponentsContext(dir, getRoot(), alreadyCreatedItems.get0(), alreadyCreatedItems.get1());
final ComponentsContext ctxt = new ComponentsContext(dir, getRoot(), alreadyCreatedTables, alreadyCreatedItems);
module.setupComponents(ctxt);
this.modulesComponents.put(id, ctxt);
}
768,9 → 759,26
}
 
public final void startRequiredModules() throws Exception {
startModules(Arrays.asList(getRequiredIDsPrefs().keys()));
List<ModuleReference> refs = this.remoteModuleManager.getRequiredModules();
 
// Auto install required modules
final List<ModuleReference> modulesToAutoInstall = new ArrayList<ModuleReference>();
for (ModuleReference moduleReference : refs) {
if (!isModuleInstalledLocally(moduleReference)) {
Log.get().warning("Required module " + moduleReference + " will be automatically installed locally");
modulesToAutoInstall.add(moduleReference);
}
}
if (!modulesToAutoInstall.isEmpty()) {
Log.get().warning("Starting installing locally missing modules");
installModulesLocally(modulesToAutoInstall);
}
 
Log.get().info("starting required modules");
startModules(ModuleReference.getIds(refs));
Log.get().info("starting required modules, done");
}
 
/**
* Start modules that were deemed persistent.
*
789,7 → 797,7
 
public final boolean startModule(final String id, final boolean persistent) throws Exception {
final Set<String> res = startModules(Collections.singleton(id), persistent);
return res.isEmpty();
return !res.isEmpty();
}
 
/**
831,6 → 839,9
synchronized (this.factories) {
for (final String id : ids) {
final ModuleFactory f = getFactory(id);
if (f == null) {
throw new IllegalArgumentException("No factory for module " + id);
}
if (!canFactoryCreate(f, map)) {
cannotCreate.add(id);
}
838,9 → 849,12
}
for (final ModuleFactory useableFactory : map.keySet()) {
final String id = useableFactory.getID();
if (inSetup || !this.runningModules.containsKey(id))
modules.put(id, useableFactory.createModule(Collections.unmodifiableMap(modules)));
if (inSetup || !this.runningModules.containsKey(id)) {
System.err.println("ModuleManager.createModules():from factory " + id);
final AbstractModule createdModule = useableFactory.createModule(Collections.unmodifiableMap(modules));
modules.put(id, createdModule);
}
}
// only keep modules created by this method
if (!inSetup)
modules.keySet().removeAll(this.runningModules.keySet());
847,18 → 861,20
 
if (start) {
final Collection<AbstractModule> toStart = modules.values();
for (final AbstractModule module : toStart)
installAndRegister(module);
 
register(toStart);
 
for (final AbstractModule module : toStart) {
final ModuleFactory f = module.getFactory();
final String id = f.getID();
System.err.println("ModuleManager.createModules():from factory, starting " + id);
try {
// do the request here instead of in the EDT in setupComponents()
assert !this.runningModules.containsKey(id) : "Doing a request for nothing";
final Tuple2<Set<String>, Set<SQLName>> createdItems = getCreatedItems(id);
 
// execute right away if possible, allowing the caller to handle any exceptions
if (SwingUtilities.isEventDispatchThread()) {
startModule(module, createdItems);
startModule(module, remoteModuleManager.getCreatedTables(id), remoteModuleManager.getCreatedItems(id));
} else {
// keep the for outside to avoid halting the EDT too long
SwingUtilities.invokeLater(new Runnable() {
865,7 → 881,7
@Override
public void run() {
try {
startModule(module, createdItems);
startModule(module, remoteModuleManager.getCreatedTables(id), remoteModuleManager.getCreatedItems(id));
} catch (Exception e) {
ExceptionHandler.handle(MainFrame.getInstance(), "Unable to start " + f, e);
}
891,15 → 907,12
return Tuple2.create(modules, cannotCreate);
}
 
private final void installAndRegister(final AbstractModule module) throws Exception {
private final void register(final Collection<AbstractModule> modules) throws Exception {
assert Thread.holdsLock(this);
assert !isModuleRunning(module.getFactory().getID());
 
// Register
for (AbstractModule module : modules) {
try {
install(module);
} catch (Exception e) {
throw new Exception("Couldn't install module " + module, e);
}
try {
final Set<SQLTable> tablesWithMD;
final String mdVariant = getMDVariant(module.getFactory());
final InputStream labels = module.getClass().getResourceAsStream("labels.xml");
916,16 → 929,24
this.registerSQLElements(module);
// insert just loaded labels into the search path
for (final SQLTable tableWithDoc : tablesWithMD) {
this.getDirectory().getElement(tableWithDoc).addToMDPath(mdVariant);
final SQLElement sqlElem = this.getDirectory().getElement(tableWithDoc);
if (sqlElem == null)
throw new IllegalStateException("Missing element for table with metadata : " + tableWithDoc);
sqlElem.addToMDPath(mdVariant);
}
} catch (Exception e) {
throw new Exception("Couldn't register module " + module, e);
}
}
}
 
private final void startModule(final AbstractModule module, final Tuple2<Set<String>, Set<SQLName>> createdItems) throws Exception {
private final void startModule(final AbstractModule module, Set<String> alreadyCreatedTables, Set<SQLName> alreadyCreatedItems) throws Exception {
assert SwingUtilities.isEventDispatchThread();
this.setupComponents(module, createdItems);
if (alreadyCreatedTables == null)
throw new IllegalArgumentException("null created tables");
if (alreadyCreatedItems == null)
throw new IllegalArgumentException("null created items");
this.setupComponents(module, alreadyCreatedTables, alreadyCreatedItems);
module.start();
}
 
1035,24 → 1056,10
}
}
 
private final List<String> getDBDependentModules(final String id) throws Exception {
final Set<String> tables = getCreatedItems(id).get0();
if (tables.size() == 0)
return Collections.emptyList();
 
final SQLTable installedTable = getInstalledTable(getRoot());
final SQLSelect sel = new SQLSelect(installedTable.getBase());
sel.addSelect(installedTable.getField(MODULE_COLNAME));
sel.setWhere(new Where(installedTable.getField(MODULE_COLNAME), "!=", id).and(new Where(installedTable.getField(TABLE_COLNAME), tables)));
@SuppressWarnings("unchecked")
final List<String> res = installedTable.getDBSystemRoot().getDataSource().executeCol(sel.asString());
return res;
}
 
// modules needing us are the ones currently started + the ones installed in the database
// that need one of our fields
private synchronized final Collection<String> getDependentModules(final String id) throws Exception {
final Set<String> depModules = new HashSet<String>(getDBDependentModules(id));
final Set<String> depModules = new HashSet<String>(remoteModuleManager.getDBDependentModules(id));
final AbstractModule runningModule = this.runningModules.get(id);
if (runningModule != null) {
for (final DirectedEdge<ModuleFactory> e : new ArrayList<DirectedEdge<ModuleFactory>>(this.dependencyGraph.incomingEdgesOf(runningModule.getFactory()))) {
1075,6 → 1082,7
for (final String depModule : getDependentModules(id)) {
res.add(depModule);
// the graph has no cycle, so we don't need to protected against infinite loop
 
res.addAll(this.getDependentModulesRecursively(depModule));
}
Collections.reverse(res);
1086,6 → 1094,7
final LinkedHashSet<String> depModules = new LinkedHashSet<String>();
for (final String id : ids) {
if (!depModules.contains(id)) {
 
depModules.addAll(getDependentModulesRecursively(id));
// even without this line the result could still contain some of ids if it contained
// a module and one of its dependencies
1108,34 → 1117,36
return res;
}
 
public synchronized final Collection<String> uninstall(final Set<String> ids, final boolean recurse) throws Exception {
/**
* Uninstall all version of some modules
* */
public synchronized final Collection<String> uninstall(final Set<String> ids, final boolean recurse, boolean force, boolean localOnly) throws Exception {
final Set<String> res;
try {
if (!recurse) {
final LinkedHashSet<String> depModules = getAllOrderedDependentModulesRecursively(ids);
final Collection<String> depModulesNotRequested = CollectionUtils.substract(depModules, ids);
if (!depModulesNotRequested.isEmpty())
throw new IllegalStateException("Dependent modules not uninstalled : " + depModulesNotRequested);
// limit the number of requests
final Map<String, ModuleVersion> dbVersions = this.getDBInstalledModules();
for (final String id : depModules)
this.uninstallUnsafe(id, dbVersions);
this.uninstallUnsafe(depModules, force, localOnly);
res = depModules;
} else {
res = new HashSet<String>();
for (final String id : ids) {
if (!res.contains(id))
res.addAll(this.uninstall(id, recurse));
res.addAll(this.uninstall(id, recurse, force, localOnly));
}
}
assert (recurse && res.containsAll(ids)) || (!recurse && res.equals(ids));
} catch (Throwable t) {
throw new IllegalStateException(t);
} finally {
reloadServerState();
}
return res;
}
 
public final void uninstall(final String id) throws Exception {
this.uninstall(id, false);
}
 
public synchronized final Collection<String> uninstall(final String id, final boolean recurse) throws Exception {
private synchronized final Collection<String> uninstall(final String id, final boolean recurse, boolean force, boolean localOnly) throws Exception {
// even if it wasn't installed locally we might want to uninstall it from the DB
if (!this.isModuleInstalledLocallyOrInDB(id))
return Collections.emptySet();
1145,7 → 1156,7
if (depModules.size() > 0) {
if (recurse) {
for (final String depModule : depModules) {
res.addAll(uninstall(depModule, recurse));
res.addAll(uninstall(depModule, recurse, force, localOnly));
}
} else {
throw new IllegalStateException("Dependent modules not uninstalled : " + depModules);
1152,24 → 1163,32
}
}
 
uninstallUnsafe(id, null);
uninstallUnsafe(Arrays.asList(id), force, localOnly);
res.add(id);
return res;
}
 
// dbVersions parameter to avoid requests to the DB
private void uninstallUnsafe(final String id, Map<String, ModuleVersion> dbVersions) throws SQLException, Exception {
if (dbVersions == null)
dbVersions = this.getDBInstalledModules();
private void uninstallUnsafe(Collection<String> ids, final boolean force, final boolean localOnly) throws SQLException, Exception {
List<ModuleReference> dbrefs = getRemoteInstalledModules();
for (final String id : ids) {
 
final ModuleFactory moduleFactory = getFactory(id);
if (!force) {
 
if (moduleFactory == null)
throw new IllegalStateException("No factory for : " + id);
 
final ModuleVersion localVersion = this.getModuleVersionInstalledLocally(id);
final ModuleVersion dbVersion = dbVersions.get(id);
final ModuleVersion dbVersion = ModuleReference.getVersion(dbrefs, id);
 
if (localVersion != null && !moduleFactory.getVersion().equals(localVersion))
throw new IllegalStateException("Local version not equal : " + localVersion);
if (dbVersion != null && !moduleFactory.getVersion().equals(dbVersion))
if (!localOnly && dbVersion != null && !moduleFactory.getVersion().equals(dbVersion))
throw new IllegalStateException("DB version not equal : " + dbVersion);
 
}
final AbstractModule module;
if (moduleFactory != null) {
if (!this.isModuleRunning(id)) {
module = this.createModules(Collections.singleton(id), false, false).get0().get(id);
} else {
1176,31 → 1195,51
module = this.runningModules.get(id);
this.stopModule(id, true);
}
} else {
module = null;
}
 
SQLUtils.executeAtomic(getDS(), new SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
final DBRoot root = getRoot();
if (module != null) {
if (!localOnly) {
module.uninstall(root);
}
unregisterSQLElements(module);
setModuleInstalledLocally(module.getFactory(), false);
}
 
removeModuleInstalledLocally(id);
 
if (!localOnly) {
// uninstall from DB
final Tuple2<Set<String>, Set<SQLName>> createdItems = getCreatedItems(id);
final List<ChangeTable<?>> l = new ArrayList<ChangeTable<?>>();
final Set<String> tableNames = createdItems.get0();
for (final SQLName field : createdItems.get1()) {
final Set<String> tableNames = remoteModuleManager.getCreatedTables(id);
for (final SQLName field : remoteModuleManager.getCreatedItems(id)) {
try {
// Can throw exception if table is already removed
final SQLField f = root.getDesc(field, SQLField.class);
// dropped by DROP TABLE
if (!tableNames.contains(f.getTable().getName())) {
// cascade needed since the module might have created constraints
// cascade needed since the module might have created
// constraints
// (e.g. on H2 a foreign column cannot be dropped)
l.add(new AlterTable(f.getTable()).dropColumnCascade(f.getName()));
}
} catch (Throwable e) {
if (!force) {
throw new RuntimeException(e);
}
}
}
for (final String table : tableNames) {
l.add(new DropTable(root.getTable(table)));
final SQLTable tableToDrop = root.getTable(table);
if (force && tableToDrop == null) {
continue;
}
l.add(new DropTable(tableToDrop));
}
if (l.size() > 0) {
for (final String s : ChangeTable.cat(l, root.getName()))
root.getDBSystemRoot().getDataSource().execute(s);
1208,9 → 1247,126
root.refetch();
}
 
removeModuleFields(module.getFactory());
remoteModuleManager.removeModule(id);
}
 
return null;
}
});
}
}
 
public String getInfo(ModuleReference ref) {
String s = this.infos.get(ref);
if (s != null)
return s;
return "";
}
 
public Set<ModuleReference> getAllKnownModuleReference() {
return knownModuleReferences;
}
 
public void dump(PrintStream out) {
out.println("Module Manager:" + this.missingModules.size() + " missing modules");
for (ModuleReference ref : this.missingModules) {
out.println("Missing module: " + ref);
}
for (ModuleReference ref : this.knownModuleReferences) {
ModuleFactory f = this.getFactory(ref.getId());
if (f == null) {
out.println("No factory for module: " + ref);
}
}
out.println("Running modules:");
for (ModuleReference ref : this.knownModuleReferences) {
if (isModuleRunning(ref.getId())) {
out.println(ref);
}
}
out.println("Not running modules:");
for (ModuleReference ref : this.knownModuleReferences) {
if (!isModuleRunning(ref.getId())) {
out.println(ref);
}
}
out.println("Locally installed modules:");
for (ModuleReference ref : getModulesInstalledLocally()) {
out.println(ref);
}
out.println("Remote installed modules:");
try {
for (ModuleReference ref : getRemoteInstalledModules()) {
out.println(ref);
}
} catch (Exception e) {
out.println("Unable to get DB installed modules: " + e.getMessage());
}
out.println("Required modules:");
try {
for (ModuleReference ref : this.modulesRequiredLocally) {
out.println(ref);
}
} catch (Exception e) {
out.println("Unable to get required modules: " + e.getMessage());
}
}
 
public synchronized List<ModuleReference> getRemoteInstalledModules() {
return modulesInstalledOnServer;
}
 
private synchronized void reloadServerState() {
try {
modulesInstalledOnServer = this.remoteModuleManager.getDBInstalledModules();
modulesRequiredLocally = this.remoteModuleManager.getRequiredModules();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
 
/**
* Install some modules on server
*
* @throws Exception if one module cannot be installed
* */
public synchronized void installModulesOnServer(Set<ModuleReference> refs) throws Exception {
final Map<String, AbstractModule> alreadyCreated = new LinkedHashMap<String, AbstractModule>(this.runningModules);
 
List<AbstractModule> modules = new ArrayList<AbstractModule>();
for (ModuleReference moduleReference : refs) {
ModuleFactory m = this.getFactory(moduleReference.getId());
AbstractModule module = m.createModule(alreadyCreated);
modules.add(module);
}
 
installOnServer(modules);
reloadServerState();
}
 
public synchronized void installModulesLocally(Collection<ModuleReference> refs) throws Exception {
final Map<String, AbstractModule> alreadyCreated = new LinkedHashMap<String, AbstractModule>(this.runningModules);
 
List<AbstractModule> modules = new ArrayList<AbstractModule>();
for (ModuleReference moduleReference : refs) {
ModuleFactory m = this.getFactory(moduleReference.getId());
AbstractModule module = m.createModule(alreadyCreated);
modules.add(module);
}
 
instalLocally(modules);
 
}
 
public synchronized boolean isModuleInstalledOnServer(ModuleReference reference) {
return modulesInstalledOnServer.contains(reference);
}
 
public synchronized boolean isModuleRequiredLocally(ModuleReference reference) {
return modulesRequiredLocally.contains(reference);
}
 
public Set<String> getCreatedTables(ModuleReference reference) {
return this.remoteModuleManager.getCreatedTables(reference.getId());
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AvailableModulesPanel.java
20,6 → 20,7
import org.openconcerto.utils.FileUtils;
 
import java.awt.Dialog.ModalityType;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
27,7 → 28,7
import java.io.IOException;
import java.text.ChoiceFormat;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
67,12 → 68,27
}
 
private final AvailableModuleTableModel tm;
private final ModuleFrame moduleFrame;
 
AvailableModulesPanel(final ModuleFrame moduleFrame) {
this.moduleFrame = moduleFrame;
this.setOpaque(false);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
// Toolbar
c.weightx = 0;
c.weighty = 0;
 
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
final JButton startButton = new JButton(new InstallAction());
startButton.setOpaque(false);
this.add(startButton, c);
c.gridx++;
final JButton importButton = new JButton(new ImportAction());
importButton.setOpaque(false);
this.add(importButton, c);
 
// Left Column
this.tm = new AvailableModuleTableModel();
JTable t = new JTable(this.tm);
87,8 → 103,10
t.getColumnModel().getColumn(0).setMaxWidth(24);
t.getColumnModel().getColumn(0).setResizable(false);
t.getColumnModel().getColumn(1).setMinWidth(100);
// Version
t.getColumnModel().getColumn(2).setMinWidth(48);
t.getColumnModel().getColumn(2).setPreferredWidth(48);
t.getColumnModel().getColumn(2).setMaxWidth(48);
 
t.getColumnModel().getColumn(3).setMinWidth(48);
t.getColumnModel().getColumn(3).setPreferredWidth(200);
t.getTableHeader().setReorderingAllowed(false);
95,61 → 113,23
JScrollPane scroll = new JScrollPane(t);
c.weighty = 1;
c.weightx = 1;
c.gridheight = 4;
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
 
c.fill = GridBagConstraints.BOTH;
this.add(scroll, c);
// Right column
c.weightx = 0;
c.weighty = 0;
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.gridheight = 1;
final JButton activateButton = new JButton(new AbstractAction("Installer") {
@Override
public void actionPerformed(ActionEvent evt) {
final Collection<ModuleFactory> checkedRows = AvailableModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final JDialog dialog = displayDialog(AvailableModulesPanel.this, "Installation " + MODULE_FMT.format(new Object[] { checkedRows.size() }));
final ModuleManager mngr = ModuleManager.getInstance();
new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
for (final ModuleFactory f : checkedRows) {
mngr.startModule(f.getID(), true);
}
return null;
}
this.setTransferHandler(new AbstractFileTransfertHandler() {
 
@Override
protected void done() {
try {
this.get();
} catch (Exception e) {
ExceptionHandler.handle(AvailableModulesPanel.this, "Impossible de démarrer les modules", e);
public void handleFile(File f) {
installModule(f);
}
// some might have started
moduleFrame.reload();
dialog.dispose();
});
}
}.execute();
}
});
activateButton.setOpaque(false);
this.add(activateButton, c);
 
JPanel space = new JPanel();
space.setOpaque(false);
c.weighty = 1;
c.gridy++;
this.add(space, c);
this.setTransferHandler(new AbstractFileTransfertHandler() {
 
@Override
public void handleFile(File f) {
protected void installModule(File f) {
if (!f.getName().endsWith(".jar")) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'installer le module. Le fichier n'est pas un module.");
return;
156,6 → 136,10
}
File dir = new File("Modules");
dir.mkdir();
if (!dir.exists()) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Impossible d'installer le module.\nLe dossier ne peut pas être créer:\n" + dir.getAbsolutePath());
return;
}
File out = null;
if (dir.canWrite()) {
try {
184,10 → 168,69
});
 
}
});
}
 
public void reload() {
this.tm.reload();
}
 
private final class InstallAction extends AbstractAction {
 
InstallAction() {
super("Installer");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final Set<ModuleReference> checkedRows = AvailableModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(AvailableModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final JDialog dialog = displayDialog(AvailableModulesPanel.this, "Installation " + MODULE_FMT.format(new Object[] { checkedRows.size() }));
final ModuleManager mngr = ModuleManager.getInstance();
new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
 
mngr.installModulesOnServer(checkedRows);
return null;
}
 
@Override
protected void done() {
try {
this.get();
int r = JOptionPane.showConfirmDialog(AvailableModulesPanel.this, "Installation sur le serveur reussie.\nVoulez-vous également installer les modules sur le poste?");
if (r == JOptionPane.OK_OPTION) {
mngr.installModulesLocally(checkedRows);
}
} catch (Exception e) {
ExceptionHandler.handle(AvailableModulesPanel.this, "Impossible d'installer les modules", e);
}
// some might have started
moduleFrame.reload();
dialog.dispose();
}
}.execute();
}
}
 
private final class ImportAction extends AbstractAction {
 
ImportAction() {
super("Importer");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
FileDialog fileDialog = new FileDialog(moduleFrame, "Module à importer", FileDialog.LOAD);
fileDialog.setVisible(true);
if (fileDialog.getFile() != null) {
installModule(new File(fileDialog.getFile()));
}
 
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/LocalInstalledModuleTableModel.java
New file
0,0 → 1,140
/*
* 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.modules;
 
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.IFactory;
 
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
 
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class LocalInstalledModuleTableModel extends ModuleTableModel {
 
static private final int STATE_INDEX = 3;
static private final int REQUIRED_INDEX = 4;
static private final int INFO_INDEX = 5;
static private final int LAST_INDEX = INFO_INDEX;
private final Preferences prefs;
private Set<String> requiredIDs;
private final PreferenceChangeListener pcl;
 
public LocalInstalledModuleTableModel(IFactory<? extends Collection<ModuleReference>> rowSource) {
super(rowSource);
this.requiredIDs = null;
this.prefs = ModuleManager.getInstance().getRequiredIDsPrefs();
this.pcl = new PreferenceChangeListener() {
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
final Set<String> ids = LocalInstalledModuleTableModel.this.requiredIDs;
if (evt.getNewValue() == null)
ids.remove(evt.getKey());
else
ids.add(evt.getKey());
fireTableChanged(new TableModelEvent(LocalInstalledModuleTableModel.this, 0, getRowCount() - 1, REQUIRED_INDEX));
assert fetchRequiredIDs().equals(ids);
}
};
}
 
protected final Preferences getPrefs() {
return this.prefs;
}
 
@Override
public void addTableModelListener(TableModelListener l) {
final boolean hadListeners = hasListeners();
super.addTableModelListener(l);
if (!hadListeners && hasListeners()) {
this.getPrefs().addPreferenceChangeListener(this.pcl);
}
}
 
private final boolean hasListeners() {
return this.listenerList.getListenerCount() > 0;
}
 
@Override
public synchronized void removeTableModelListener(TableModelListener l) {
final boolean hadListeners = hasListeners();
super.removeTableModelListener(l);
if (hadListeners && !hasListeners()) {
this.getPrefs().removePreferenceChangeListener(this.pcl);
}
}
 
private Set<String> fetchRequiredIDs() {
try {
return new HashSet<String>(Arrays.asList(this.getPrefs().keys()));
} catch (BackingStoreException e) {
ExceptionHandler.handle("Impossible de déterminer les modules requis", e);
return null;
}
}
 
private boolean isRequiredByUser(final String id) {
if (this.requiredIDs == null)
this.requiredIDs = this.fetchRequiredIDs();
return this.requiredIDs == null ? false : this.requiredIDs.contains(id);
}
 
@Override
public int getColumnCount() {
return LAST_INDEX + 1;
}
 
@Override
public String getColumnName(int column) {
if (column == STATE_INDEX) {
return "Etat";
} else if (column == REQUIRED_INDEX) {
return "Démarrage";
} else if (column == INFO_INDEX) {
return "Information";
} else {
return super.getColumnName(column);
}
}
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final ModuleReference f = this.getModuleReference(rowIndex);
if (columnIndex == STATE_INDEX) {
return ModuleManager.getInstance().isModuleRunning(f.getId()) ? "Démarré" : "Arrêté";
} else if (columnIndex == REQUIRED_INDEX) {
return (this.isRequiredByUser(f.getId()) || ModuleManager.getInstance().isModuleRequiredLocally(f)) ? "Obligatoire" : "Facultatif";
} else if (columnIndex == INFO_INDEX) {
return ModuleManager.getInstance().getInfo(f);
} else {
return super.getValueAt(rowIndex, columnIndex);
}
}
 
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == STATE_INDEX || columnIndex == REQUIRED_INDEX) {
return String.class;
} else {
return super.getColumnClass(columnIndex);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/DBContext.java
24,7 → 24,6
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.cc.IClosure;
 
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
41,7 → 40,7
*/
public final class DBContext {
 
private final File dir;
 
private final ModuleVersion localVersion;
private final ModuleVersion lastInstalledVersion;
private final DBRoot root;
53,9 → 52,8
private final Set<String> tables;
private final CollectionMap<String, SQLField> fields;
 
DBContext(final File dir, final ModuleVersion localVersion, final DBRoot root, final ModuleVersion dbVersion, final Set<String> tables, final Set<SQLName> fields) {
super();
this.dir = dir;
DBContext(final ModuleVersion localVersion, final DBRoot root, final ModuleVersion dbVersion, final Set<String> tables, final Set<SQLName> fields) {
 
this.localVersion = localVersion;
this.lastInstalledVersion = dbVersion;
this.root = root;
70,9 → 68,6
this.dm = new ArrayList<IClosure<? super DBRoot>>();
}
 
public final File getLocalDirectory() {
return this.dir;
}
 
public final ModuleVersion getLocalVersion() {
return this.localVersion;
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleVersion.java
82,6 → 82,6
 
@Override
public String toString() {
return "v" + this.getMajor() + "." + this.getMinor();
return this.getMajor() + "." + this.getMinor();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/LocalModuleManager.java
New file
0,0 → 1,18
/*
* 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.modules;
 
public class LocalModuleManager {
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/LocalContext.java
New file
0,0 → 1,40
/*
* 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.modules;
 
import java.io.File;
 
public class LocalContext {
private final File dir;
private final ModuleVersion localVersion;
private final ModuleVersion dbVersion;
 
public LocalContext(final ModuleVersion localVersion, File dir, final ModuleVersion dbVersion) {
this.localVersion = localVersion;
this.dir = dir;
this.dbVersion = dbVersion;
}
 
public final File getLocalDirectory() {
return this.dir;
}
 
public final ModuleVersion getLocalVersion() {
return localVersion;
}
 
public ModuleVersion getLastInstalledVersion() {
return dbVersion;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleFrame.java
26,8 → 26,9
import javax.swing.JTabbedPane;
 
public class ModuleFrame extends JFrame {
private final InstalledModulesPanel tab1;
private final AvailableModulesPanel tab2;
private final LocalInstalledModulesPanel tab1;
private final ServerInstalledModulesPanel tab2;
private final AvailableModulesPanel tab3;
 
public ModuleFrame() {
this.setTitle("Modules");
36,10 → 37,12
p.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
final JTabbedPane tabbedPane = new JTabbedPane();
this.tab1 = new InstalledModulesPanel(this);
tabbedPane.addTab("Modules installés", this.tab1);
this.tab2 = new AvailableModulesPanel(this);
tabbedPane.addTab("Modules disponibles", this.tab2);
this.tab1 = new LocalInstalledModulesPanel(this);
tabbedPane.addTab("Modules installés sur le poste", this.tab1);
this.tab2 = new ServerInstalledModulesPanel(this);
tabbedPane.addTab("Modules installés sur le serveur", this.tab2);
this.tab3 = new AvailableModulesPanel(this);
tabbedPane.addTab("Modules disponibles", this.tab3);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
62,5 → 65,6
public void reload() {
this.tab1.reload();
this.tab2.reload();
this.tab3.reload();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/LocalInstalledModulesPanel.java
New file
0,0 → 1,264
/*
* 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.modules;
 
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.IFactory;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
 
public class LocalInstalledModulesPanel extends JPanel {
 
private final LocalInstalledModuleTableModel tm;
final ModuleFrame moduleFrame;
 
LocalInstalledModulesPanel(final ModuleFrame moduleFrame) {
this.moduleFrame = moduleFrame;
 
final IFactory<List<ModuleReference>> rowSource = new IFactory<List<ModuleReference>>() {
@Override
public List<ModuleReference> createChecked() {
 
final ModuleManager mngr = ModuleManager.getInstance();
Set<ModuleReference> moduleRefs = new HashSet<ModuleReference>();
moduleRefs.addAll(mngr.getModulesInstalledLocally());
 
return new ArrayList<ModuleReference>(moduleRefs);
}
};
 
this.tm = new LocalInstalledModuleTableModel(rowSource);
 
this.setOpaque(false);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
// Toolbar
c.weightx = 0;
c.weighty = 0;
 
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
final JButton startButton = new JButton(new StartAction());
startButton.setOpaque(false);
this.add(startButton, c);
c.gridx++;
final JButton stopButton = new JButton(new StopAction());
stopButton.setOpaque(false);
this.add(stopButton, c);
c.gridx++;
final JButton uninstallButton = new JButton(new UninstallAction());
uninstallButton.setOpaque(false);
this.add(uninstallButton, c);
// Rows
 
final JTable t = new JTable(this.tm);
t.setShowGrid(false);
t.setShowVerticalLines(false);
t.setFocusable(false);
t.setRowSelectionAllowed(false);
t.setColumnSelectionAllowed(false);
t.setCellSelectionEnabled(false);
t.getColumnModel().getColumn(0).setMinWidth(24);
t.getColumnModel().getColumn(0).setPreferredWidth(24);
t.getColumnModel().getColumn(0).setMaxWidth(24);
t.getColumnModel().getColumn(0).setResizable(false);
t.getColumnModel().getColumn(1).setMinWidth(148);
// Version
t.getColumnModel().getColumn(2).setMinWidth(48);
t.getColumnModel().getColumn(2).setMaxWidth(48);
// Etat
t.getColumnModel().getColumn(3).setMinWidth(48);
t.getColumnModel().getColumn(3).setPreferredWidth(48);
t.getColumnModel().getColumn(3).setMaxWidth(200);
//
t.getColumnModel().getColumn(4).setMinWidth(80);
t.getColumnModel().getColumn(4).setPreferredWidth(80);
t.getColumnModel().getColumn(5).setMinWidth(128);
t.getColumnModel().getColumn(5).setPreferredWidth(128);
t.getTableHeader().setReorderingAllowed(false);
// allow InstalledModuleTableModel to be gc'd
t.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (!e.getChanged().isDisplayable()) {
t.setModel(new DefaultTableModel());
} else if (t.getModel() != LocalInstalledModulesPanel.this.tm) {
t.setModel(LocalInstalledModulesPanel.this.tm);
}
}
}
});
 
final JScrollPane scroll = new JScrollPane(t);
c.weighty = 1;
c.weightx = 1;
c.gridx = 0;
c.gridy++;
c.gridwidth = 3;
c.fill = GridBagConstraints.BOTH;
this.add(scroll, c);
 
ModuleManager.getInstance().dump(System.err);
}
 
public final void reload() {
this.tm.reload();
}
 
private final class StartAction extends AbstractAction {
private final Preferences reqPrefs;
 
public StartAction() {
super("Démarrer");
this.reqPrefs = tm.getPrefs();
this.putValue(Action.SHORT_DESCRIPTION, "Démarrer le(s) module(s), maintenir CTRL pour rendre obligatoire le démarrage");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final ModuleManager mngr = ModuleManager.getInstance();
final Collection<ModuleReference> checkedRows = LocalInstalledModulesPanel.this.tm.getCheckedRows();
try {
for (final ModuleReference f : checkedRows) {
mngr.startModule(f.getId(), true);
// on Ubuntu ALT-Click is used to move windows
final boolean changeRequired = (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0;
if (changeRequired) {
this.reqPrefs.put(f.getId(), "");
}
}
this.reqPrefs.sync();
} catch (Exception e) {
JOptionPane.showMessageDialog(LocalInstalledModulesPanel.this, "Impossible d'activer les modules");
}
// only need to reload us
reload();
}
}
 
private final class StopAction extends AbstractAction {
private final Preferences reqPrefs;
 
public StopAction() {
super("Arrêter");
this.reqPrefs = tm.getPrefs();
this.putValue(Action.SHORT_DESCRIPTION, "Arrête le(s) module(s), maintenir CTRL pour rendre facultatif le démarrage");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final ModuleManager mngr = ModuleManager.getInstance();
final Collection<ModuleReference> checkedRows = LocalInstalledModulesPanel.this.tm.getCheckedRows();
try {
for (final ModuleReference f : checkedRows) {
mngr.stopModuleRecursively(f.getId());
// on Ubuntu ALT-Click is used to move windows
final boolean changeRequired = (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0;
if (changeRequired) {
this.reqPrefs.remove(f.getId());
}
}
this.reqPrefs.sync();
} catch (Exception e) {
JOptionPane.showMessageDialog(LocalInstalledModulesPanel.this, "Impossible de désactiver les modules");
}
// only need to reload us
reload();
}
}
 
private final class UninstallAction extends AbstractAction {
UninstallAction() {
super("Désinstaller du poste");
}
 
@Override
public void actionPerformed(ActionEvent evt) {
final Collection<ModuleReference> checkedRows = LocalInstalledModulesPanel.this.tm.getCheckedRows();
if (checkedRows.isEmpty()) {
JOptionPane.showMessageDialog(LocalInstalledModulesPanel.this, "Aucune ligne cochée");
return;
}
 
final ModuleManager mngr = ModuleManager.getInstance();
final int answer = JOptionPane.showConfirmDialog(LocalInstalledModulesPanel.this,
"Êtes-vous sûr de vouloir désinstaller ces modules sur ce poste?\nToutes les données locales seront irrémédiablement effacées.", "Désinstallation de modules",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (answer == JOptionPane.NO_OPTION)
return;
 
try {
final Set<String> ids = new HashSet<String>();
for (final ModuleReference f : checkedRows) {
ids.add(f.getId());
}
final Collection<String> dependentModules = mngr.getDependentModulesRecursively(ids);
if (!dependentModules.isEmpty()) {
final int selectAnswer = JOptionPane.showConfirmDialog(LocalInstalledModulesPanel.this, "Des modules non sélectionnés ont besoin de la sélection : " + dependentModules
+ ".\nVoulez-vous également désinstaller ces modules ?", "Désinstallation de modules", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (selectAnswer == JOptionPane.NO_OPTION)
return;
}
final boolean force = (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0;
 
final JDialog dialog = AvailableModulesPanel.displayDialog(LocalInstalledModulesPanel.this,
"Désinstallation " + AvailableModulesPanel.MODULE_FMT.format(new Object[] { checkedRows.size() }));
new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
// Local uninstall
mngr.uninstall(ids, true, force, true);
return null;
}
 
protected void done() {
try {
this.get();
} catch (Exception e) {
ExceptionHandler.handle(LocalInstalledModulesPanel.this, "Impossible de désinstaller les modules", e);
}
moduleFrame.reload();
dialog.dispose();
}
}.execute();
} catch (Exception e) {
ExceptionHandler.handle(LocalInstalledModulesPanel.this, "Impossible de trouver les modules à désinstaller", e);
}
}
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleReference.java
New file
0,0 → 1,74
/*
* 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.modules;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
 
public class ModuleReference {
private final String id;
private final ModuleVersion version;
 
public ModuleReference(String id, ModuleVersion version) {
this.id = id;
this.version = version;
}
 
public String getId() {
return id;
}
 
public ModuleVersion getVersion() {
return version;
}
 
@Override
public String toString() {
return this.id + " " + this.version;
}
 
@Override
public int hashCode() {
return this.version.hashCode() + id.hashCode();
}
 
@Override
public boolean equals(Object obj) {
if (obj instanceof ModuleReference) {
final ModuleReference ref = (ModuleReference) obj;
return ref.id.equals(id) && ref.version.equals(version);
}
return super.equals(obj);
}
 
public static ModuleVersion getVersion(List<ModuleReference> refs, String id) {
for (ModuleReference moduleReference : refs) {
if (moduleReference.getId().equals(id)) {
return moduleReference.getVersion();
}
}
return null;
}
 
public static List<String> getIds(List<ModuleReference> refs) {
final List<String> ids = new ArrayList<String>();
for (ModuleReference moduleReference : refs) {
if (!ids.contains(moduleReference.getId())) {
ids.add(moduleReference.getId());
}
}
return ids;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ServerInstalledModuleTableModel.java
New file
0,0 → 1,130
/*
* 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.modules;
 
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.IFactory;
 
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
 
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class ServerInstalledModuleTableModel extends ModuleTableModel {
 
static private final int STATE_INDEX = 3;
static private final int REQUIRED_INDEX = 4;
static private final int INFO_INDEX = 5;
static private final int LAST_INDEX = INFO_INDEX;
private final Preferences prefs;
private Set<String> requiredIDs;
private final PreferenceChangeListener pcl;
 
public ServerInstalledModuleTableModel(IFactory<? extends Collection<ModuleReference>> rowSource) {
super(rowSource);
this.requiredIDs = null;
this.prefs = ModuleManager.getInstance().getRequiredIDsPrefs();
this.pcl = new PreferenceChangeListener() {
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
final Set<String> ids = ServerInstalledModuleTableModel.this.requiredIDs;
if (evt.getNewValue() == null)
ids.remove(evt.getKey());
else
ids.add(evt.getKey());
fireTableChanged(new TableModelEvent(ServerInstalledModuleTableModel.this, 0, getRowCount() - 1, REQUIRED_INDEX));
 
}
};
}
 
protected final Preferences getPrefs() {
return this.prefs;
}
 
@Override
public void addTableModelListener(TableModelListener l) {
final boolean hadListeners = hasListeners();
super.addTableModelListener(l);
if (!hadListeners && hasListeners()) {
this.getPrefs().addPreferenceChangeListener(this.pcl);
}
}
 
private final boolean hasListeners() {
return this.listenerList.getListenerCount() > 0;
}
 
@Override
public synchronized void removeTableModelListener(TableModelListener l) {
final boolean hadListeners = hasListeners();
super.removeTableModelListener(l);
if (hadListeners && !hasListeners()) {
this.getPrefs().removePreferenceChangeListener(this.pcl);
}
}
 
@Override
public int getColumnCount() {
return LAST_INDEX + 1;
}
 
@Override
public String getColumnName(int column) {
if (column == STATE_INDEX) {
return "Etat";
} else if (column == REQUIRED_INDEX) {
return "Installation locale";
} else if (column == INFO_INDEX) {
return "Information";
} else {
return super.getColumnName(column);
}
}
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final ModuleReference f = this.getModuleReference(rowIndex);
if (columnIndex == STATE_INDEX) {
return ModuleManager.getInstance().isModuleInstalledLocally(f) ? "Installé sur le poste" : "Non installé sur le poste";
} else if (columnIndex == REQUIRED_INDEX) {
return ModuleManager.getInstance().isModuleRequiredLocally(f) ? "Obligatoire" : "Facultative";
} else if (columnIndex == INFO_INDEX) {
return ModuleManager.getInstance().getInfo(f);
} else {
return super.getValueAt(rowIndex, columnIndex);
}
}
 
public ModuleReference getModuleReferenceAt(int rowIndex) {
final ModuleReference f = this.getModuleReference(rowIndex);
return f;
}
 
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == STATE_INDEX || columnIndex == REQUIRED_INDEX) {
return String.class;
} else {
return super.getColumnClass(columnIndex);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ServerModuleManager.java
New file
0,0 → 1,315
/*
* 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.modules;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSyntax;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.utils.SQLCreateTable;
 
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.SwingUtilities;
 
public class ServerModuleManager {
private static final String MODULE_COLNAME = "MODULE_NAME";
private static final String MODULE_VERSION_COLNAME = "MODULE_VERSION";
private static final String TABLE_COLNAME = "TABLE";
private static final String FIELD_COLNAME = "FIELD";
private static final String ISKEY_COLNAME = "KEY";
// Don't use String literals for the synchronized blocks
private static final String FWK_MODULE_TABLENAME = new String("FWK_MODULE_METADATA");
private DBRoot root;
 
private ArrayList<ModuleReference> installedModules;
private ArrayList<ModuleReference> requiredModules;
private Map<String, Set<String>> mapCreatedTables = new HashMap<String, Set<String>>();
private Map<String, Set<SQLName>> mapCreatedItems = new HashMap<String, Set<SQLName>>();
 
// TODO use transactions
 
synchronized final DBRoot getRoot() {
return this.root;
}
 
synchronized void setRoot(DBRoot root) throws SQLException {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalAccessError("Cannot be called in EDT");
}
this.root = root;
reload();
 
}
 
synchronized void reload() throws SQLException {
final SQLRowValues graph = new SQLRowValues(getModuleMetadataTable());
graph.put(SQLSyntax.ID_NAME, null);
graph.put(MODULE_COLNAME, null);
graph.put(TABLE_COLNAME, null);
graph.put(FIELD_COLNAME, null);
graph.put(ISKEY_COLNAME, null);
graph.put(MODULE_VERSION_COLNAME, null);
 
final SQLRowValuesListFetcher fetcher = new SQLRowValuesListFetcher(graph);
final List<SQLRowValues> values = fetcher.fetch();
 
final HashSet<ModuleReference> installedSet = new HashSet<ModuleReference>();
final HashSet<ModuleReference> requiredSet = new HashSet<ModuleReference>();
this.mapCreatedTables = new HashMap<String, Set<String>>();
this.mapCreatedItems = new HashMap<String, Set<SQLName>>();
 
for (SQLRowValues row : values) {
final String id = row.getString(MODULE_COLNAME);
final Long version = row.getLong(MODULE_VERSION_COLNAME);
 
if (id != null && version != null) {
final String table = row.getString(TABLE_COLNAME);
final ModuleReference ref = new ModuleReference(id, new ModuleVersion(version));
installedSet.add(ref);
 
Set<String> tables = this.mapCreatedTables.get(id);
if (tables == null) {
tables = new HashSet<String>();
this.mapCreatedTables.put(id, tables);
}
final String field = row.getString(FIELD_COLNAME);
 
if (table != null && (field == null || field.isEmpty())) {
tables.add(table);
requiredSet.add(ref);
}
 
Set<SQLName> items = this.mapCreatedItems.get(id);
if (items == null) {
items = new HashSet<SQLName>();
this.mapCreatedItems.put(id, items);
}
if (field != null) {
items.add(new SQLName(table, field));
}
 
}
}
installedModules = new ArrayList<ModuleReference>(installedSet);
requiredModules = new ArrayList<ModuleReference>(requiredSet);
 
}
 
synchronized void updateModuleFields(ModuleReference ref, final DBContext ctxt) throws SQLException {
if (ref == null) {
throw new IllegalArgumentException("null ModuleReference");
}
if (ref.getId() == null) {
throw new IllegalArgumentException("null module id");
}
if (ref.getId().trim().isEmpty()) {
throw new IllegalArgumentException("empty module id");
}
if (ref.getVersion() == null) {
throw new IllegalArgumentException("null module id");
}
if (ctxt == null) {
throw new IllegalArgumentException("null DBContext");
}
System.err.println("RemoteModuleManager: update module fields: " + ref);
final SQLTable installedTable = getModuleMetadataTable();
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", ref.getId());
// removed items
{
final List<Where> dropWheres = new ArrayList<Where>();
for (final String dropped : ctxt.getRemovedTables()) {
dropWheres.add(new Where(installedTable.getField(TABLE_COLNAME), "=", dropped));
}
for (final SQLName dropped : ctxt.getRemovedFieldsFromExistingTables()) {
dropWheres.add(new Where(installedTable.getField(TABLE_COLNAME), "=", dropped.getItem(0)).and(new Where(installedTable.getField(FIELD_COLNAME), "=", dropped.getItem(1))));
}
if (dropWheres.size() > 0)
installedTable.getDBSystemRoot().getDataSource().execute("DELETE FROM " + installedTable.getSQLName().quote() + " WHERE " + Where.or(dropWheres).and(idW).getClause());
}
// added items
{
final SQLRowValues vals = new SQLRowValues(installedTable);
vals.put(MODULE_VERSION_COLNAME, ref.getVersion().getMerged());
vals.put(MODULE_COLNAME, ref.getId());
for (final String added : ctxt.getAddedTables()) {
vals.put(TABLE_COLNAME, added).put(FIELD_COLNAME, null).insert();
final SQLTable t = ctxt.getRoot().findTable(added);
for (final SQLField field : t.getFields()) {
vals.put(TABLE_COLNAME, added).put(FIELD_COLNAME, field.getName()).put(ISKEY_COLNAME, field.isKey()).insert();
}
vals.remove(ISKEY_COLNAME);
}
for (final SQLName added : ctxt.getAddedFieldsToExistingTables()) {
final SQLTable t = ctxt.getRoot().findTable(added.getItem(0));
final SQLField field = t.getField(added.getItem(1));
vals.put(TABLE_COLNAME, t.getName()).put(FIELD_COLNAME, field.getName()).put(ISKEY_COLNAME, field.isKey()).insert();
}
vals.remove(ISKEY_COLNAME);
vals.insert();
}
 
// Always put true, even if getCreatedItems() is empty, since for now we can't be sure that
// the module didn't insert rows or otherwise changed the DB (MAYBE change SQLDataSource to
// hand out connections with read only user for a new ThreadGroup, or even no connections at
// all). If we could assert that the module didn't access at all the DB, we could add an
// option so that the module can declare not accessing the DB and install() would know that
// the DB version of the module is null. This could be beneficial since different users
// could install different version of modules that only change the UI.
setDBInstalledModule(ref);
 
}
 
/**
*
* @return null if module not installed
* */
synchronized List<String> getDBDependentModules(final String id) throws Exception {
if (!isModuleInstalled(id)) {
return null;
}
final Set<String> tables = getCreatedTables(id);
if (tables.size() == 0) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<String>();
for (final ModuleReference ref : this.getDBInstalledModules()) {
final String mId = ref.getId();
if (!mId.equals(id)) {
for (String mTableName : getCreatedTables(mId)) {
if (tables.contains(mTableName)) {
result.add(mId);
}
}
 
}
}
return result;
}
 
synchronized Set<String> getCreatedTables(String id) {
final Set<String> set = this.mapCreatedTables.get(id);
if (set == null)
return Collections.emptySet();
return set;
}
 
synchronized Set<SQLName> getCreatedItems(String id) {
final Set<SQLName> set = this.mapCreatedItems.get(id);
if (set == null)
return Collections.emptySet();
return set;
}
 
/**
* Get required modules
* */
synchronized final List<ModuleReference> getRequiredModules() {
return requiredModules;
}
 
/**
* Get installed modules
* */
synchronized final List<ModuleReference> getDBInstalledModules() throws SQLException {
return installedModules;
}
 
synchronized boolean isModuleInstalled(String id) {
boolean result = false;
for (ModuleReference ref : this.installedModules) {
if (ref.getId().equals(id)) {
return true;
}
}
return result;
}
 
synchronized void removeModule(String id) throws SQLException {
System.err.println("RemoteModuleManager: remove module: " + id);
final SQLTable installedTable = getModuleMetadataTable();
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", id);
installedTable.getDBSystemRoot().getDataSource().execute("DELETE FROM " + installedTable.getSQLName().quote() + " WHERE " + idW.getClause());
reload();
}
 
private SQLTable getModuleMetadataTable() throws SQLException {
final DBRoot r = this.getRoot();
synchronized (FWK_MODULE_TABLENAME) {
if (!r.contains(FWK_MODULE_TABLENAME)) {
// store :
// - currently installed module (TABLE_COLNAME & FIELD_COLNAME are null)
// - created tables (FIELD_COLNAME is null)
// - created fields (and whether they are keys)
final SQLCreateTable createTable = new SQLCreateTable(r, FWK_MODULE_TABLENAME);
createTable.setPlain(true);
createTable.addColumn(SQLSyntax.ID_NAME, createTable.getSyntax().getPrimaryIDDefinition());
createTable.addVarCharColumn(MODULE_COLNAME, 128);
createTable.addColumn(TABLE_COLNAME, "varchar(128) NULL");
createTable.addColumn(FIELD_COLNAME, "varchar(128) NULL");
createTable.addColumn(ISKEY_COLNAME, "boolean NULL");
createTable.addColumn(MODULE_VERSION_COLNAME, "bigint NOT NULL");
createTable.addUniqueConstraint("uniqModule", Arrays.asList(MODULE_COLNAME, TABLE_COLNAME, FIELD_COLNAME));
r.createTable(createTable);
}
}
return r.getTable(FWK_MODULE_TABLENAME);
}
 
private void setDBInstalledModule(ModuleReference ref) throws SQLException {
System.err.println("RemoteModuleManager: set installed module: " + ref.getId() + " " + ref.getVersion());
final SQLTable installedTable = getModuleMetadataTable();
final Where idW = new Where(installedTable.getField(MODULE_COLNAME), "=", ref.getId());
final Where noItemsW = Where.isNull(installedTable.getField(TABLE_COLNAME)).and(Where.isNull(installedTable.getField(FIELD_COLNAME)));
final Where w = idW.and(noItemsW);
 
final SQLSelect sel = new SQLSelect();
sel.addSelect(installedTable.getKey());
sel.setWhere(w);
final Number id = (Number) installedTable.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
final SQLRowValues vals = new SQLRowValues(installedTable);
vals.put(MODULE_VERSION_COLNAME, ref.getVersion().getMerged());
if (id != null) {
vals.setID(id);
vals.update();
} else {
vals.put(MODULE_COLNAME, ref.getId());
vals.put(TABLE_COLNAME, null);
vals.put(FIELD_COLNAME, null);
vals.insert();
}
 
// Update fields to module version
final UpdateBuilder update = new UpdateBuilder(installedTable);
update.set(MODULE_VERSION_COLNAME, String.valueOf(ref.getVersion().getMerged()));
update.setWhere(new Where(installedTable.getField(MODULE_COLNAME), "=", ref.getId()));
installedTable.getDBSystemRoot().getDataSource().execute(update.asString());
 
reload();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/AbstractModule.java
78,6 → 78,17
}
 
/**
* Should create permanent items. NOTE: all files created in
* {@link LocalContext#getLocalDirectory()} will be deleted automatically, i.e. no action is
* necessary in {@link #uninstall(DBRoot)}.
*
* @param ctxt to create database objects.
*/
protected void install(LocalContext ctxt) {
 
}
 
/**
* Should add elements for the tables of this module. It's also the place to
* {@link SQLElement#setAction(String, SQLElement.ReferenceAction) set actions} for foreign keys
* of this module. NOTE: this method is called as long as the module is installed in the
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateFrameAbstractAction.java
42,9 → 42,14
final JFrame frame = createFrame();
frame.setIconImages(Gestion.getFrameIcon());
 
WindowStateManager stateManager = new WindowStateManager(frame, new File(Configuration.getInstance().getConfDir(), "Configuration" + File.separator + "Frame" + File.separator
+ this.getValue(Action.NAME).toString() + ".xml"), true);
 
final Object name = this.getValue(Action.NAME);
WindowStateManager stateManager = null;
if (name != null) {
stateManager = new WindowStateManager(frame, new File(Configuration.getInstance().getConfDir(), "Configuration" + File.separator + "Frame" + File.separator + name.toString() + ".xml"),
true);
} else {
System.err.println("Warning: no action name for action " + this + ", unable to use a window state manager.");
}
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
 
53,7 → 58,7
int h = Math.min(d.height - 100, frame.getHeight());
frame.setMinimumSize(new Dimension(w, h));
frame.setLocationRelativeTo(null);
if (mustLoadState) {
if (mustLoadState && stateManager != null) {
stateManager.loadState();
}
FrameUtil.show(frame);
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction_en.properties
New file
0,0 → 1,6
adminLogin = Administrator
loginLabel=Username
passwordLabel=Password
companyLabel=Company
saveCheckBox=Remember my password
buttonConnect=Log in
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction.java
15,6 → 15,7
 
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.DefaultMenuConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.config.MainFrame;
import org.openconcerto.erp.core.common.ui.PanelFrame;
22,6 → 23,7
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.humanresources.payroll.element.CaisseCotisationSQLElement;
import org.openconcerto.erp.element.objet.ClasseCompte;
import org.openconcerto.erp.modules.ModuleFrame;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.panel.ComptaTipsFrame;
import org.openconcerto.erp.utils.NXDatabaseAccessor;
52,8 → 54,10
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.JImage;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.i18n.TranslationManager;
 
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
61,7 → 65,9
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
 
75,13 → 81,15
import javax.swing.UIManager;
 
public class NouvelleConnexionAction extends CreateFrameAbstractAction {
private ConnexionPanel connexionPanel;
// Module configuration frame used when something goes wrong
private ModuleFrame fMod;
 
public NouvelleConnexionAction() {
super();
this.putValue(Action.NAME, "Changer d'utilisateur");
}
 
private ConnexionPanel connexionPanel;
 
public JFrame createFrame() {
// needed as done() must come after us
assert SwingUtilities.isEventDispatchThread();
93,6 → 101,9
 
public void run() {
try {
TranslationManager.getInstance().addTranslationStreamFromClass(MainFrame.class);
TranslationManager.getInstance().setLocale(UserProps.getInstance().getLocale());
 
final Boolean booleanValue = UserProps.getInstance().getBooleanValue("HideTips");
if (!booleanValue) {
SwingUtilities.invokeLater(new Runnable() {
117,23 → 128,22
}
}
comptaPropsConfiguration.setUpSocieteDataBaseConnexion(selectedSociete);
 
// finish filling the configuration before going any further, otherwise the
// SQLElementDirectory is not coherent
try {
ModuleManager.getInstance().setup(comptaPropsConfiguration.getRootSociete(), comptaPropsConfiguration);
} catch (Exception e) {
// not OK to continue without required elements
ExceptionHandler.die("Impossible de démarrer les modules requis", e);
}
 
try {
// create table if necessary
SQLPreferences.getPrefTable(comptaPropsConfiguration.getRootSociete());
SQLPreferences.startMemCached(comptaPropsConfiguration.getRootSociete());
} catch (Exception e) {
// don't die now, we might not need them
ExceptionHandler.handle("Impossible d'accéder aux préférences", e);
}
// finish filling the configuration before going any further, otherwise the
// SQLElementDirectory is not coherent
try {
ModuleManager.getInstance().setup(comptaPropsConfiguration.getRootSociete(), comptaPropsConfiguration);
} catch (Throwable e) {
// not OK to continue without required elements
openEmergencyModuleManager("Impossible de configurer les modules requis", e);
}
 
 
SwingUtilities.invokeLater(new Runnable() {
143,11 → 153,16
// frame
 
StatusPanel.getInstance().fireStatusChanged();
final JFrame f = new MainFrame();
final MainFrame f = new MainFrame();
String version = comptaPropsConfiguration.getVersion();
final String socTitle = comptaPropsConfiguration.getRowSociete() == null ? "" : ", [Société " + comptaPropsConfiguration.getRowSociete().getString("NOM") + "]";
f.setTitle(comptaPropsConfiguration.getAppName() + " " + version + socTitle);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// Init menus
DefaultMenuConfiguration mConfiguration = new DefaultMenuConfiguration();
mConfiguration.createMenuGroup();
mConfiguration.registerMenuActions();
f.setJMenuBar(Gestion.isMinimalMode() ? f.createMinimalMenu() : f.createMenu());
 
}
});
154,8 → 169,11
final FutureTask<?> showMainFrame = new FutureTask<Object>(new Runnable() {
@Override
public void run() {
FrameUtil.show(MainFrame.getInstance());
if (ModuleManager.getInstance().isSetup()) {
final MainFrame mainFrame = MainFrame.getInstance();
FrameUtil.show(mainFrame);
}
}
}, null);
ModuleManager.getInstance().invoke(new IClosure<ModuleManager>() {
@Override
164,24 → 182,12
// visible menu bar)
try {
input.startRequiredModules();
} catch (Exception exn) {
// by definition we cannot continue without required modules
ExceptionHandler.die("Impossible de démarrer les modules requis", exn);
}
try {
input.startPreviouslyRunningModules();
SwingUtilities.invokeLater(showMainFrame);
} catch (Exception exn) {
// OK to start the application without all modules started
// but don't continue right away otherwise connexion panel will be
// closed and the popup with it
try {
ExceptionHandler.handle(NouvelleConnexionAction.this.connexionPanel, "Impossible de démarrer les modules", exn).getDialogFuture().get();
} catch (Exception e) {
e.printStackTrace();
openEmergencyModuleManager("Impossible de démarrer les modules requis", exn);
}
}
 
SwingUtilities.invokeLater(showMainFrame);
}
});
initCache();
195,7 → 201,7
private void fixEcriture() {
// FIXME Bug archive ecriture (ecriture non archivé ayant un id_mouvement=1)
SQLElement elt = Configuration.getInstance().getDirectory().getElement("ECRITURE");
SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
SQLSelect sel = new SQLSelect();
sel.addSelect(elt.getTable().getKey());
 
Where w = new Where(elt.getTable().getField("ID_MOUVEMENT"), "=", 1);
242,6 → 248,8
this.connexionPanel = ConnexionPanel.create(r, image, !Gestion.isMinimalMode());
if (this.connexionPanel == null)
return null;
this.connexionPanel.initLocalization(getClass().getName(),
Arrays.asList(Locale.FRANCE, Locale.CANADA_FRENCH, new Locale("fr", "CH"), new Locale("fr", "BE"), Locale.UK, Locale.CANADA, Locale.US, Locale.GERMANY, new Locale("de", "CH")));
 
p.add(this.connexionPanel, c);
final PanelFrame panelFrame = new PanelFrame(p, "Connexion");
275,22 → 283,25
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMMERCIAL"), 600);
 
SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TYPE_REGLEMENT"), 1000);
SQLBackgroundTableCache.getInstance().startCacheWatcher();
 
TaxeCache.getCache();
 
final UndefinedRowValuesCache UndefCache = UndefinedRowValuesCache.getInstance();
// TODO: 1 request to rules them all?
UndefCache.getDefaultRowValues(baseSociete.getTable("DEVIS"));
UndefCache.getDefaultRowValues(baseSociete.getTable("ETAT_DEVIS"));
UndefCache.getDefaultRowValues(baseSociete.getTable("ADRESSE"));
UndefCache.getDefaultRowValues(baseSociete.getTable("DEVIS_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("CONTACT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("SAISIE_KM_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("BON_DE_LIVRAISON_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("COMMANDE_CLIENT_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("AVOIR_CLIENT_ELEMENT"));
UndefCache.getDefaultRowValues(baseSociete.getTable("BON_RECEPTION_ELEMENT"));
 
final UndefinedRowValuesCache undefCache = UndefinedRowValuesCache.getInstance();
final List<SQLTable> tablesToCache = new ArrayList<SQLTable>();
tablesToCache.add(baseSociete.getTable("DEVIS"));
tablesToCache.add(baseSociete.getTable("ETAT_DEVIS"));
tablesToCache.add(baseSociete.getTable("FAMILLE_ARTICLE"));
tablesToCache.add(baseSociete.getTable("ADRESSE"));
tablesToCache.add(baseSociete.getTable("DEVIS_ELEMENT"));
tablesToCache.add(baseSociete.getTable("CONTACT"));
tablesToCache.add(baseSociete.getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
tablesToCache.add(baseSociete.getTable("SAISIE_KM_ELEMENT"));
tablesToCache.add(baseSociete.getTable("BON_DE_LIVRAISON_ELEMENT"));
tablesToCache.add(baseSociete.getTable("COMMANDE_CLIENT_ELEMENT"));
tablesToCache.add(baseSociete.getTable("AVOIR_CLIENT_ELEMENT"));
tablesToCache.add(baseSociete.getTable("BON_RECEPTION_ELEMENT"));
undefCache.preload(tablesToCache);
}
 
};
308,4 → 319,24
}
}
 
private void openEmergencyModuleManager(final String str, Throwable e) {
System.err.println("The following exception is preventing a normal startup:");
e.printStackTrace();
System.err.println("Opening the module manager in order to resolve the issue.");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (fMod == null) {
fMod = new ModuleFrame();
fMod.pack();
fMod.setMinimumSize(new Dimension(480, 640));
fMod.setLocationRelativeTo(null);
fMod.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fMod.setTitle(str);
fMod.setVisible(true);
}
}
});
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction_fr.properties
New file
0,0 → 1,6
adminLogin = Administrateur
loginLabel=Identifiant
passwordLabel=Mot de passe
companyLabel=Société
saveCheckBox=Mémoriser le mot de passe
buttonConnect=Connexion
/trunk/OpenConcerto/src/org/openconcerto/erp/action/SauvegardeBaseAction.java
90,7 → 90,7
 
frame.setIconImages(Gestion.getFrameIcon());
frame.setAlwaysOnTop(true);
frame.setVisible(true);
 
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction_de.properties
New file
0,0 → 1,6
adminLogin = Administrator
loginLabel=Benutzename
passwordLabel=Passwort
companyLabel=Kompanie
saveCheckBox=Passwort vergessen
buttonConnect=Ammelden
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/ArticleCommandeEltSQLInjector.java
29,6 → 29,9
public ArticleCommandeEltSQLInjector(final DBRoot root) {
super(articleTable, commandeEltTable);
createDefaultMap();
if (commandeEltTable.contains("ID_ARTICLE")) {
map(articleTable.getKey(), commandeEltTable.getField("ID_ARTICLE"));
}
if (articleTable.getFieldsName().contains("ID_DEVISE")) {
remove(articleTable.getField("ID_DEVISE"), commandeEltTable.getField("ID_DEVISE"));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeCliCommandeSQLInjector.java
25,5 → 25,6
final SQLTable tableCommande = getDestination();
mapDefaultValues(tableCommande.getField("SOURCE"), tableCommandeCli.getName());
map(tableCommandeCli.getKey(), tableCommande.getField("IDSOURCE"));
map(tableCommandeCli.getField("NOM"), tableCommande.getField("NOM"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLElement.java
64,18 → 64,16
for (Attribute attr : attrs) {
context.put(attr.getName(), attr.getValue());
}
return provider.getValue(context);
}
res = provider.getValue(context);
} else
 
if (type.equalsIgnoreCase("TotalHTTable")) {
return getTotalHTTable(row);
}
 
if (type.equalsIgnoreCase("DateEcheance")) {
res = getTotalHTTable(row);
} else if (type.equalsIgnoreCase("DateEcheance")) {
int idModeReglement = row.getInt("ID_MODE_REGLEMENT");
Date d = (Date) row.getObject("DATE");
return getDateEcheance(idModeReglement, d, this.elt.getAttributeValue("datePattern"));
}
res = getDateEcheance(idModeReglement, d, this.elt.getAttributeValue("datePattern"));
} else {
 
final List<Element> eltFields = this.elt.getChildren("field");
 
97,6 → 95,26
res = field.getValue();
}
}
}
 
// Liste des valeurs à ne pas afficher
List<String> listOfExcludedValues = null;
 
List<Element> excludeValue = this.elt.getChildren("exclude");
if (excludeValue != null && excludeValue.size() > 0) {
 
listOfExcludedValues = new ArrayList<String>();
 
for (Element element : excludeValue) {
String attributeValue = element.getAttributeValue("value");
listOfExcludedValues.add(attributeValue);
}
}
 
if (res != null && listOfExcludedValues != null && listOfExcludedValues.contains(res.toString())) {
res = null;
}
 
return res;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseClientProvider.java
New file
0,0 → 1,55
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider;
 
public abstract class AdresseClientProvider implements SpreadSheetCellValueProvider {
 
public static int ADRESSE_FACTURATION = 1;
public static int ADRESSE_LIVRAISON = 2;
 
@Override
public abstract Object getValue(SpreadSheetCellValueContext context);
 
public SQLRowAccessor getAdresse(SQLRowAccessor r, int type) {
 
// Adresse spécifique
if (r.getTable().contains("ID_ADRESSE")) {
SQLRowAccessor rAdr = r.getForeign("ID_ADRESSE");
if (rAdr != null && !rAdr.isUndefined()) {
return rAdr;
}
}
 
// Adresse Facturation
SQLRowAccessor rCli = r.getForeign("ID_CLIENT");
String field;
if (type == ADRESSE_FACTURATION) {
field = "ID_ADRESSE_F";
} else {
field = "ID_ADRESSE_L";
}
SQLRowAccessor rAdr = rCli.getForeign(field);
if (rAdr != null && !rAdr.isUndefined()) {
return rAdr;
}
 
return rCli.getForeign("ID_ADRESSE");
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseFullClientValueProvider.java
New file
0,0 → 1,54
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class AdresseFullClientValueProvider extends AdresseClientProvider {
 
private int type;
 
public AdresseFullClientValueProvider(int type) {
this.type = type;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor r = getAdresse(context.getRow(), this.type);
Ville v = Ville.getVilleFromVilleEtCode(r.getString("VILLE"));
String result = r.getString("RUE");
if (v != null) {
result += "\n" + v.getCodepostal();
result += " ";
result += v.getName();
if (r.getBoolean("HAS_CEDEX")) {
result += " Cedex";
String cedex = r.getString("CEDEX");
if (cedex != null && cedex.trim().length() > 0) {
result += " " + cedex;
}
}
}
 
return result;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("address.customer.invoice.full", new AdresseFullClientValueProvider(ADRESSE_FACTURATION));
SpreadSheetCellValueProviderManager.put("address.customer.shipment.full", new AdresseFullClientValueProvider(ADRESSE_LIVRAISON));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseVilleNomClientValueProvider.java
New file
0,0 → 1,52
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class AdresseVilleNomClientValueProvider extends AdresseClientProvider {
 
private int type;
 
public AdresseVilleNomClientValueProvider(int type) {
this.type = type;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor r = getAdresse(context.getRow(), this.type);
Ville v = Ville.getVilleFromVilleEtCode(r.getString("VILLE"));
String result = null;
if (v != null) {
result = v.getName();
if (r.getBoolean("HAS_CEDEX")) {
result += " Cedex";
String cedex = r.getString("CEDEX");
if (cedex != null && cedex.trim().length() > 0) {
result += " " + cedex;
}
}
}
 
return result;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("address.customer.invoice.country.name", new AdresseVilleNomClientValueProvider(ADRESSE_FACTURATION));
SpreadSheetCellValueProviderManager.put("address.customer.shipment.country.name", new AdresseVilleNomClientValueProvider(ADRESSE_LIVRAISON));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/PrixUnitaireRemiseProvider.java
25,10 → 25,14
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
final Long pv = row.getLong("PV_HT");
final BigDecimal pv = row.getBigDecimal("PV_HT");
final BigDecimal remise = (BigDecimal) row.getObject("POURCENT_REMISE");
BigDecimal result = BigDecimal.ONE.subtract(remise.movePointLeft(2)).multiply(new BigDecimal(pv), MathContext.DECIMAL128);
result = result.movePointLeft(2);
BigDecimal acompte = BigDecimal.ONE;
if (row.getTable().contains("POURCENT_ACOMPTE")) {
acompte = ((BigDecimal) row.getObject("POURCENT_ACOMPTE")).movePointLeft(2);
}
BigDecimal result = BigDecimal.ONE.subtract(remise.movePointLeft(2)).multiply(pv, MathContext.DECIMAL128).multiply(acompte, MathContext.DECIMAL128);
 
return result;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/QteTotalProvider.java
New file
0,0 → 1,45
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.math.BigDecimal;
 
public class QteTotalProvider implements SpreadSheetCellValueProvider {
 
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
int qte = row.getInt("QTE");
BigDecimal qteUV = row.getBigDecimal("QTE_UNITAIRE");
 
BigDecimal result = qteUV.multiply(new BigDecimal(qte));
 
BigDecimal pv = row.getBigDecimal("PV_HT");
 
if (pv.compareTo(BigDecimal.ZERO) == 0) {
return null;
} else {
return result;
}
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("supplychain.element.qte", new QteTotalProvider());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseRueClientValueProvider.java
New file
0,0 → 1,37
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
 
public class AdresseRueClientValueProvider extends AdresseClientProvider {
 
private int type;
 
public AdresseRueClientValueProvider(int type) {
this.type = type;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
return getAdresse(context.getRow(), this.type).getString("RUE");
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("address.customer.invoice.address", new AdresseRueClientValueProvider(ADRESSE_FACTURATION));
SpreadSheetCellValueProviderManager.put("address.customer.shipment.address", new AdresseRueClientValueProvider(ADRESSE_LIVRAISON));
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseVilleClientValueProvider.java
New file
0,0 → 1,54
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class AdresseVilleClientValueProvider extends AdresseClientProvider {
 
private int type;
 
public AdresseVilleClientValueProvider(int type) {
this.type = type;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor r = getAdresse(context.getRow(), this.type);
Ville v = Ville.getVilleFromVilleEtCode(r.getString("VILLE"));
String result = null;
if (v != null) {
result = v.getCodepostal();
result += " ";
result += v.getName();
if (r.getBoolean("HAS_CEDEX")) {
result += " Cedex";
String cedex = r.getString("CEDEX");
if (cedex != null && cedex.trim().length() > 0) {
result += " " + cedex;
}
}
}
 
return result;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("address.customer.invoice.country", new AdresseVilleClientValueProvider(ADRESSE_FACTURATION));
SpreadSheetCellValueProviderManager.put("address.customer.shipment.country", new AdresseVilleClientValueProvider(ADRESSE_LIVRAISON));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/AdresseVilleCPClientValueProvider.java
New file
0,0 → 1,45
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.map.model.Ville;
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class AdresseVilleCPClientValueProvider extends AdresseClientProvider {
 
private int type;
 
public AdresseVilleCPClientValueProvider(int type) {
this.type = type;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor r = getAdresse(context.getRow(), this.type);
Ville v = Ville.getVilleFromVilleEtCode(r.getString("VILLE"));
String result = null;
if (v != null) {
result = v.getCodepostal();
}
 
return result;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("address.customer.invoice.country.code", new AdresseVilleCPClientValueProvider(ADRESSE_FACTURATION));
SpreadSheetCellValueProviderManager.put("address.customer.shipment.country.code", new AdresseVilleCPClientValueProvider(ADRESSE_LIVRAISON));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLTableField.java
70,10 → 70,8
for (Attribute attr : attrs) {
context.put(attr.getName(), attr.getValue());
}
return provider.getValue(context);
}
 
if (this.type.equalsIgnoreCase("LineReference")) {
value = provider.getValue(context);
} else if (this.type.equalsIgnoreCase("LineReference")) {
return idRef;
} else if (this.type.equalsIgnoreCase("DescriptifArticle")) {
value = getDescriptifArticle(this.row);
92,6 → 90,24
}
}
 
// Liste des valeurs à ne pas afficher
List<String> listOfExcludedValues = null;
 
List<Element> excludeValue = this.elt.getChildren("exclude");
if (excludeValue != null && excludeValue.size() > 0) {
 
listOfExcludedValues = new ArrayList<String>();
 
for (Element element : excludeValue) {
String attributeValue = element.getAttributeValue("value");
listOfExcludedValues.add(attributeValue);
}
}
 
if (value != null && listOfExcludedValues != null && listOfExcludedValues.contains(value.toString())) {
value = null;
}
 
return value;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractJOOReportsSheet.java
84,6 → 84,10
return result.toString();
}
 
public abstract String getDefaultTemplateID();
 
public abstract String getDefaultLocationProperty();
 
protected void init(String year, String templateId, String attributePrinter) {
this.year = year;
this.templateId = templateId;
110,7 → 114,7
 
String fileName = getFileName();
final InputStream fileTemplate = TemplateManager.getInstance().getTemplate(this.templateId);
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(this.templateId);
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(getDefaultTemplateID());
File fileOutOO = getDocumentFile();
if (fileOutOO.exists() && overwrite) {
if (this.askOverwriting) {
147,7 → 151,7
final Component doc = ooConnexion.loadDocument(fileOutOO, !show);
 
if (this.savePDF()) {
File pdfOutputDir = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(templateId);
File pdfOutputDir = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(getDefaultTemplateID());
doc.saveToPDF(new File(pdfOutputDir, fileName + ".pdf"), "writer_pdf_Export");
}
if (print) {
198,7 → 202,7
}
 
private File getDocumentFile() {
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(templateId);
File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(getDefaultTemplateID());
return new File(outputDir, getFileName() + ".odt");
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
162,6 → 162,27
 
@Override
public void run() {
createPDF(generatedFile, pdfFile, doc, getStoragePath());
 
}
 
}, "convert and upload to pdf");
 
t.setDaemon(true);
t.start();
if (exportPDFSynch) {
t.join();
}
}
}
 
} catch (Exception e) {
e.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
}
}
 
public static void createPDF(final File generatedFile, final File pdfFile, final OpenDocument doc, String storagePath) {
try {
SheetUtils.convert2PDF(doc, pdfFile);
 
174,45 → 195,29
try {
storageEngine.connect();
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(pdfFile));
final String path = getStoragePath();
final String path = storagePath;
storageEngine.store(inStream, path, pdfFile.getName(), true);
inStream.close();
storageEngine.disconnect();
} catch (IOException e) {
ExceptionHandler.handle("Impossible de sauvegarder le PDF");
ExceptionHandler.handle("Impossible de sauvegarder le PDF", e);
}
if (storageEngine instanceof CloudStorageEngine) {
try {
storageEngine.connect();
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(generatedFile));
final String path = getStoragePath();
final String path = storagePath;
storageEngine.store(inStream, path, generatedFile.getName(), true);
inStream.close();
storageEngine.disconnect();
} catch (IOException e) {
ExceptionHandler.handle("Impossible de sauvegarder le fichier généré");
ExceptionHandler.handle("Impossible de sauvegarder le fichier généré", e);
}
}
}
}
 
}
}, "convert and upload to pdf");
 
t.setDaemon(true);
t.start();
if (exportPDFSynch) {
t.join();
}
}
}
 
} catch (Exception e) {
e.printStackTrace();
ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
}
}
 
public abstract String getDefaultTemplateId();
 
/**
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/PointageXmlSheet.java
37,14 → 37,12
 
public static final String TEMPLATE_ID = "Pointage";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
private Map<Integer, List<Map<String, Object>>> listAllSheetValues;
private Map<Integer, Map<Integer, String>> styleAllSheetValues;
private Map<Integer, Map<String, Object>> mapAllSheetValues;
private Calendar c = Calendar.getInstance();
private Date date = new Date();
private final long MILLIS_IN_HOUR = 3600000;
 
public PointageXmlSheet(int mois, int year) {
super();
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.mapAllSheetValues = new HashMap<Integer, Map<String, Object>>();
this.c.set(Calendar.DAY_OF_MONTH, 1);
58,7 → 56,15
}
 
@Override
protected String getStoragePathP() {
return "Pointage";
}
 
@Override
public String getName() {
if (this.date == null) {
this.date = new Date();
}
return "Pointage" + this.date;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/FicheRelanceSheet.java
33,11 → 33,16
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
public FicheRelanceSheet(SQLRow row) {
super(row);
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.row = row;
}
 
@Override
protected String getStoragePathP() {
return "Relance";
}
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
62,9 → 67,14
 
}
 
Date d;
 
@Override
public String getName() {
return "FicheRelance" + new Date().getTime();
if (d == null) {
d = new Date();
}
return "FicheRelance" + d.getTime();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/CourrierClientSheet.java
40,6 → 40,16
init(year, "Courrier.odt", "CourrierPrinter");
}
 
@Override
public String getDefaultTemplateID() {
return TEMPLATE_ID;
}
 
@Override
public String getDefaultLocationProperty() {
return TEMPLATE_PROPERTY_NAME;
}
 
/**
* @return une Map contenant les valeurs à remplacer dans la template
*/
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/RelanceSheet.java
35,6 → 35,16
 
public static final String TEMPLATE_PROPERTY_NAME = "LocationRelance";
 
@Override
public String getDefaultTemplateID() {
return TEMPLATE_ID;
}
 
@Override
public String getDefaultLocationProperty() {
return TEMPLATE_PROPERTY_NAME;
}
 
/**
* @return une Map contenant les valeurs à remplacer dans la template
*/
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/ReleveChequeSheet.java
47,6 → 47,11
public static final String TEMPLATE_ID = "ReleveCheque";
public static final String TEMPLATE_PROPERTY_NAME = "LocationReleveChequeCli";
 
@Override
protected String getStoragePathP() {
return "Releve Cheque";
}
 
public ReleveChequeSheet(List<Integer> listeIds, Date date, boolean apercu) {
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.date = date;
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/EtatVentesXmlSheet.java
20,12 → 20,11
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.AliasedField;
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
 
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
57,6 → 56,7
private Timestamp du, au;
 
public EtatVentesXmlSheet(Date du, Date au) {
super();
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
final Calendar c1 = Calendar.getInstance();
c1.setTime(du);
80,9 → 80,19
}
 
@Override
protected String getStoragePathP() {
return "Etat Ventes";
}
 
Date d;
 
@Override
public String getName() {
return "EtatVentes" + new Date().getTime();
if (d == null) {
d = new Date();
}
return "EtatVentes" + d.getTime();
}
 
protected void createListeValues() {
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
156,7 → 166,7
Number ha = (Number) sqlRow[3];
Number ht = (Number) sqlRow[4];
Number ttc = (Number) sqlRow[5];
ArticleVendu a = new ArticleVendu(code, nom, qteVendu.intValue(), ht.longValue(), ha.longValue(), ttc.longValue());
ArticleVendu a = new ArticleVendu(code, nom, qteVendu.intValue(), (BigDecimal) ht, (BigDecimal) ha, (BigDecimal) ttc);
map.put(code + "##" + nom, a);
}
 
169,8 → 179,8
// Liste des valeurs de la feuille OO
ArrayList<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>(listeIds.size());
 
long totalTPAInCents = 0;
long totalTPVTTCInCents = 0;
BigDecimal totalTPA = BigDecimal.ZERO;
BigDecimal totalTPVTTC = BigDecimal.ZERO;
 
for (Object[] obj : listeIds) {
Map<String, Object> mValues = new HashMap<String, Object>();
182,14 → 192,14
mValues.put("CODE", code);
mValues.put("NOM", nom);
mValues.put("QTE", a.qte);
mValues.put("T_PA", (a.ha / 100.0D));
mValues.put("T_PV_HT", (a.ht / 100.0D));
mValues.put("T_PV_TTC", (a.ttc / 100.0D));
mValues.put("T_PA", a.ha);
mValues.put("T_PV_HT", a.ht);
mValues.put("T_PV_TTC", a.ttc);
mValues.put("NB_CHEQUE", obj[2]);
mValues.put("NB_CB", obj[3]);
mValues.put("NB_ESPECES", obj[4]);
totalTPAInCents += a.ha;
totalTPVTTCInCents += a.ttc;
totalTPA = totalTPA.add(a.ha);
totalTPVTTC = totalTPVTTC.add(a.ttc);
listValues.add(mValues);
System.out.println("EtatVentesXmlSheet.createListeValues():" + listValues);
}
275,7 → 285,7
listValuesAchat.add(mValues);
}
 
totalTPVTTCInCents += totalVCInCents;
totalTPVTTC = totalTPVTTC.add(new BigDecimal(totalVCInCents).movePointLeft(2));
 
// Récapitulatif
Map<String, Object> valuesE = this.mapAllSheetValues.get(2);
319,12 → 329,12
valuesAchat.put("TOTAL", totalAchatInCents / 100f);
valuesE.put("TOTAL_HA", totalAchatInCents / 100f);
valuesE.put("TOTAL", totalEInCents / 100f);
valuesE.put("TOTAL_VT", totalTPVTTCInCents / 100f);
valuesE.put("TOTAL_VT", totalTPVTTC);
values.put("TOTAL", totalVCInCents / 100f);
values.put("TOTAL_MARGE", (totalTPVTTCInCents - totalTPAInCents) / 100f);
valuesE.put("TOTAL_GLOBAL", (totalTPVTTCInCents + totalAchatInCents) / 100f);
values.put("TOTAL_PA", totalTPAInCents / 100f);
values.put("TOTAL_PV_TTC", totalTPVTTCInCents / 100f);
values.put("TOTAL_MARGE", totalTPVTTC.subtract(totalTPA));
valuesE.put("TOTAL_GLOBAL", totalTPVTTC.add(new BigDecimal(totalAchatInCents).movePointLeft(2)));
values.put("TOTAL_PA", totalTPA);
values.put("TOTAL_PV_TTC", totalTPVTTC);
 
String periode = "Période Du " + DATE_FORMAT.format(this.du) + " au " + DATE_FORMAT.format(this.au);
values.put("DATE", periode);
346,9 → 356,9
class ArticleVendu {
public String code, nom;
public int qte;
public long ht, ha, ttc;
public BigDecimal ht, ha, ttc;
 
public ArticleVendu(String code, String nom, int qte, long ht, long ha, long ttc) {
public ArticleVendu(String code, String nom, int qte, BigDecimal ht, BigDecimal ha, BigDecimal ttc) {
this.code = code;
this.nom = nom;
this.qte = qte;
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLField.java
148,10 → 148,16
 
// Devise en Long transformée en double
if (typeComp.equalsIgnoreCase("Devise")) {
long result = Math.round(calcul(o, o2, this.op).doubleValue());
return Double.valueOf(GestionDevise.currencyToString(result, false));
 
BigDecimal result = calcul(o, o2, this.op);
if (o instanceof Long) {
long resultLong = Math.round(result.doubleValue());
return Double.valueOf(GestionDevise.currencyToString(resultLong, false));
} else {
return result;
}
}
}
 
return calcul(o, o2, this.op);
 
303,7 → 309,11
}
}
}
if (result instanceof Long) {
return new Double(GestionDevise.currencyToString(prix.longValue(), false));
} else {
return result;
}
} else if (typeComp.equalsIgnoreCase("globalAcompte")) {
Long prix = (Long) result;
int pourcent = this.row.getInt("POURCENT_ACOMPTE");
575,27 → 585,38
return ville.getCodepostal();
}
 
private static Number calcul(Object o1, Object o2, String op) {
private static BigDecimal calcul(Object o1, Object o2, String op) {
 
double d1 = (o1 == null) ? 0 : Double.parseDouble(o1.toString());
double d2 = (o2 == null) ? 0 : Double.parseDouble(o2.toString());
BigDecimal d1;
if (o1 != null && o1 instanceof BigDecimal) {
d1 = (BigDecimal) o1;
} else {
d1 = (o1 == null) ? BigDecimal.ZERO : new BigDecimal(o1.toString());
}
 
BigDecimal d2;
if (o2 != null && o2 instanceof BigDecimal) {
d2 = (BigDecimal) o2;
} else {
d2 = (o2 == null) ? BigDecimal.ZERO : new BigDecimal(o2.toString());
}
 
if (op.equalsIgnoreCase("+")) {
return d1 + d2;
return d1.add(d2);
} else {
if (op.equalsIgnoreCase("-")) {
return d1 - d2;
return d1.subtract(d2);
} else {
if (op.equalsIgnoreCase("*")) {
return d1 * d2;
return d1.multiply(d2);
} else {
if (op.equalsIgnoreCase("/") && d2 != 0) {
return d1 / d2;
if (op.equalsIgnoreCase("/") && d2.compareTo(BigDecimal.ZERO) != 0) {
return d1.divide(d2);
}
}
}
}
return 0;
return BigDecimal.ZERO;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
35,6 → 35,8
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
349,16 → 351,16
numeroRef++;
if (!cache && rowElt.getTable().getFieldRaw("ID_TAXE") != null) {
SQLRowAccessor rowTaxe = getForeignRow(rowElt, rowElt.getTable().getField("ID_TAXE"));
long ht = 0;
BigDecimal ht = BigDecimal.ZERO;
if (rowElt.getTable().getFieldRaw("T_PV_HT") != null) {
ht = rowElt.getLong("T_PV_HT");
ht = (BigDecimal) rowElt.getObject("T_PV_HT");
}
 
if (taxe.get(rowTaxe) != null) {
 
final Object object = taxe.get(rowTaxe).get("MONTANT_HT");
long montant = (object == null) ? 0 : (Long) object;
taxe.get(rowTaxe).put("MONTANT_HT", montant + ht);
BigDecimal montant = (object == null) ? BigDecimal.ZERO : (BigDecimal) object;
taxe.get(rowTaxe).put("MONTANT_HT", montant.add(ht));
} else {
Map<String, Object> m = new HashMap<String, Object>();
m.put("MONTANT_HT", ht);
543,7 → 545,9
} else {
Object value = m.get(name);
if (name.equalsIgnoreCase("MONTANT_TVA")) {
value = Math.round(((Long) m.get("MONTANT_HT") * rowTaxe.getFloat("TAUX") / 100.0));
// value = Math.round(((Long) m.get("MONTANT_HT") * rowTaxe.getFloat("TAUX")
// / 100.0));
value = ((BigDecimal) m.get("MONTANT_HT")).multiply(new BigDecimal(rowTaxe.getFloat("TAUX")), MathContext.DECIMAL128).movePointLeft(2);
} else if (name.equalsIgnoreCase("NOM")) {
value = rowTaxe.getString("NOM");
// TODO prefix et suffix
556,10 → 560,10
value = value + suffix;
}
}
if (typeComp != null && typeComp.equalsIgnoreCase("Devise")) {
 
value = Double.valueOf(GestionDevise.currencyToString((Long) value, false));
}
// if (typeComp != null && typeComp.equalsIgnoreCase("Devise")) {
// if (value != null && value instanceof Long)
// value = Double.valueOf(GestionDevise.currencyToString((Long) value, false));
// }
fill(test ? "A1" : loc, value, sheet, false, null, null, test, false);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractListeSheetXml.java
90,7 → 90,7
protected abstract void createListeValues();
 
@Override
public String getStoragePathP() {
protected String getStoragePathP() {
return StringUtils.firstUp(elt.getPluralName());
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/provider/AccountingRecordsProvider.java
New file
0,0 → 1,26
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationEcritures.provider;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
 
import java.util.Map;
 
public interface AccountingRecordsProvider {
 
public void putLabel(SQLRowAccessor rowSource, Map<String, Object> values);
 
public void putPieceLabel(SQLRowAccessor rowSource, SQLRowValues rowValsPiece);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/provider/SalesInvoiceAccountingRecordsProvider.java
New file
0,0 → 1,45
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationEcritures.provider;
 
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
 
import java.util.Map;
 
public class SalesInvoiceAccountingRecordsProvider implements AccountingRecordsProvider {
 
@Override
public void putPieceLabel(SQLRowAccessor rowSource, SQLRowValues rowValsPiece) {
rowValsPiece.put("NOM", rowSource.getString("NUMERO"));
}
 
@Override
public void putLabel(SQLRowAccessor rowSource, Map<String, Object> values) {
String nom = "";
Boolean acompte = rowSource.getBoolean("ACOMPTE");
if (acompte != null && acompte) {
nom = "Fact. acompte client" + rowSource.getObject("NUMERO").toString();
} else {
nom = "Fact. vente " + rowSource.getObject("NUMERO").toString();
}
values.put("NOM", nom);
}
 
public static void register() {
AccountingRecordsProviderManager.put(GenerationMvtSaisieVenteFacture.ID, new SalesInvoiceAccountingRecordsProvider());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/provider/AccountingRecordsProviderManager.java
New file
0,0 → 1,39
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationEcritures.provider;
 
import java.util.HashMap;
import java.util.Map;
 
public class AccountingRecordsProviderManager {
private final static AccountingRecordsProviderManager instance = new AccountingRecordsProviderManager();
private final Map<String, AccountingRecordsProvider> map = new HashMap<String, AccountingRecordsProvider>();
 
public static void put(String id, AccountingRecordsProvider provider) {
instance.putProvider(id, provider);
}
 
public static AccountingRecordsProvider get(String id) {
return instance.getProvider(id);
}
 
private synchronized void putProvider(String id, AccountingRecordsProvider provider) {
map.put(id, provider);
}
 
private synchronized AccountingRecordsProvider getProvider(String id) {
return map.get(id);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtTicketCaisse.java
13,13 → 13,17
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLTable;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import java.util.concurrent.Callable;
 
64,6 → 68,8
public Integer call() throws Exception {
SQLRow clientRow = GenerationMvtTicketCaisse.this.rowTicket.getForeignRow("ID_CLIENT");
 
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(((Long) GenerationMvtTicketCaisse.this.rowTicket.getObject("TOTAL_TTC")).longValue());
PrixHT prixTVA = new PrixHT(((Long) GenerationMvtTicketCaisse.this.rowTicket.getObject("TOTAL_TVA")).longValue());
84,71 → 90,35
GenerationMvtTicketCaisse.this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(GenerationMvtTicketCaisse.this.idMvt));
}
 
TotalCalculator calc = getValuesFromElement(rowTicket, rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"), BigDecimal.ZERO, null, null);
long ttcLongValue = calc.getTotalTTC().movePointRight(2).longValue();
 
// compte Vente Produits
final long produitHT = prixHT.getLongValue();
if (produitHT >= 0) {
 
if (produitHT > 0) {
 
int idCompteVenteProduit = 1;
if (idCompteVenteProduit <= 1) {
idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
if (idCompteVenteProduit <= 1) {
try {
idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
} catch (Exception e) {
e.printStackTrace();
}
}
}
 
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteProduit));
for (SQLRowAccessor row : calc.getMapHt().keySet()) {
long b = calc.getMapHt().get(row).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (b != 0) {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(produitHT));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(b));
ajoutEcriture();
}
 
}
 
// compte TVA
if (prixTVA.getLongValue() > 0) {
int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
if (idCompteTVA <= 1) {
try {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
} catch (Exception e) {
e.printStackTrace();
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(GenerationMvtTicketCaisse.this.rowTicket, GenerationMvtTicketCaisse.this.rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"),
true, prixHT, 0);
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
if (l != null && l > 0) {
// FIXME
int idCpt = i;
if (idCpt <= 1) {
idCpt = idCompteTVA;
}
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
Map<SQLRowAccessor, BigDecimal> tvaMap = calc.getMapHtTVA();
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(l));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", longValue);
ajoutEcriture();
allTaxe += l;
}
}
if (allTaxe < prixTVA.getLongValue()) {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
ajoutEcriture();
}
 
}
// compte Clients
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
 
if (idCompteClient <= 1) {
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
if (idCompteClient <= 1) {
160,9 → 130,10
}
}
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", ttcLongValue);
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
return GenerationMvtTicketCaisse.this.idMvt;
}
};
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationEcritures.java
14,7 → 14,10
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
22,6 → 25,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.ExceptionHandler;
 
47,10 → 51,10
public class GenerationEcritures {
 
protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
private static final SQLTable compteTable = base.getTable("COMPTE_PCE");
private static final SQLTable journalTable = base.getTable("JOURNAL");
private static final SQLTable ecritureTable = base.getTable("ECRITURE");
private static final SQLTable pieceTable = base.getTable("PIECE");
protected static final SQLTable compteTable = base.getTable("COMPTE_PCE");
protected static final SQLTable journalTable = base.getTable("JOURNAL");
protected static final SQLTable ecritureTable = base.getTable("ECRITURE");
protected static final SQLTable pieceTable = base.getTable("PIECE");
 
protected int idMvt;
protected int idPiece;
310,10 → 314,8
* @param nomPiece
* @return id d'un nouveau mouvement
*/
synchronized public int getNewMouvement(String source, int idSource, int idPere, String nomPiece) {
synchronized public int getNewMouvement(String source, int idSource, int idPere, SQLRowValues rowValsPiece) {
 
SQLRowValues rowValsPiece = new SQLRowValues(pieceTable);
rowValsPiece.put("NOM", nomPiece);
SQLRow rowPiece;
try {
rowPiece = rowValsPiece.insert();
325,9 → 327,86
return 1;
}
 
synchronized public int getNewMouvement(String source, int idSource, int idPere, String nomPiece) {
 
SQLRowValues rowValsPiece = new SQLRowValues(pieceTable);
rowValsPiece.put("NOM", nomPiece);
return getNewMouvement(source, idSource, idPere, rowValsPiece);
}
 
protected TotalCalculator getValuesFromElement(SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRowAccessor rowTVAPort, SQLTable tableEchantillon) {
 
TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null);
long remise = 0;
BigDecimal totalAvtRemise = BigDecimal.ZERO;
if (row.getTable().contains("REMISE_HT")) {
remise = row.getLong("REMISE_HT");
if (remise != 0) {
List<SQLRow> rows = row.getReferentRows(foreign);
for (SQLRow sqlRow : rows) {
calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), 1, false);
}
 
if (tableEchantillon != null) {
List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
for (SQLRow sqlRow : rowsEch) {
calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), sqlRow.getForeign("ID_TAXE"));
}
}
calc.checkResult();
totalAvtRemise = calc.getTotalHT();
}
}
 
calc.initValues();
calc.setRemise(remise, totalAvtRemise);
 
List<SQLRow> rows = row.getReferentRows(foreign);
for (int i = 0; i < rows.size(); i++) {
SQLRow sqlRow = rows.get(i);
calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), i, i == rows.size() - 1);
}
 
if (tableEchantillon != null) {
List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
for (SQLRow sqlRow : rowsEch) {
calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), sqlRow.getForeign("ID_TAXE"));
}
}
if (rowTVAPort != null && !rowTVAPort.isUndefined()) {
SQLRowValues rowValsPort = new SQLRowValues(foreign);
rowValsPort.put("T_PV_HT", portHT);
rowValsPort.put("QTE", 1);
rowValsPort.put("ID_TAXE", rowTVAPort);
calc.addLine(rowValsPort, null, 1, false);
}
calc.checkResult();
return calc;
}
 
// FIXME à supprimer et remplacer la methode utiliser pour tickets caisse
protected Map<Integer, Long> getMultiTVAFromRow(SQLRow row, SQLTable foreign, boolean vente, PrixHT totalHt, long remiseHT) {
 
List<SQLRow> rows = row.getReferentRows(foreign);
 
SQLPreferences prefs = new SQLPreferences(row.getTable().getDBRoot());
final boolean tvaLine = prefs.getBoolean(GestionArticleGlobalPreferencePanel.TVA_LINE, false);
 
if (tvaLine) {
Map<Integer, Long> map = new HashMap<Integer, Long>();
for (SQLRow sqlRow : rows) {
SQLRow taxe = sqlRow.getForeignRow("ID_TAXE");
long val = sqlRow.getLong("T_PV_TTC") - sqlRow.getLong("T_PV_HT");
Long l = map.get(taxe.getInt("ID_COMPTE_PCE_COLLECTE"));
if (l == null) {
map.put(taxe.getInt("ID_COMPTE_PCE_COLLECTE"), Long.valueOf(val));
} else {
map.put(taxe.getInt("ID_COMPTE_PCE_COLLECTE"), Long.valueOf(val + l));
}
}
return map;
}
 
// Total HT par TVA
Map<SQLRow, Long> mapTaxeHT = new HashMap<SQLRow, Long>();
for (SQLRow sqlRow : rows) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirClient.java
14,16 → 14,18
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
59,10 → 61,11
rowClient = avoirRow.getForeignRow("ID_CLIENT");
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(((Long) avoirRow.getObject("MONTANT_TTC")).longValue());
PrixHT prixHT = new PrixHT(((Long) avoirRow.getObject("MONTANT_HT")).longValue());
PrixHT prixTVA = new PrixHT(((Long) avoirRow.getObject("MONTANT_TVA")).longValue());
PrixHT prixService = new PrixHT(((Long) avoirRow.getObject("MONTANT_SERVICE")).longValue());
// PrixTTC prixTTC = new PrixTTC(((Long) avoirRow.getObject("MONTANT_TTC")).longValue());
// PrixHT prixHT = new PrixHT(((Long) avoirRow.getObject("MONTANT_HT")).longValue());
// PrixHT prixTVA = new PrixHT(((Long) avoirRow.getObject("MONTANT_TVA")).longValue());
// PrixHT prixService = new PrixHT(((Long)
// avoirRow.getObject("MONTANT_SERVICE")).longValue());
 
// iniatilisation des valeurs de la map
this.date = (Date) avoirRow.getObject("DATE");
88,112 → 91,33
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
}
 
// generation des ecritures + maj des totaux du compte associe
 
int idCompteVenteService = avoirRow.getInt("ID_COMPTE_PCE_SERVICE");
if (idCompteVenteService <= 1) {
idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
if (idCompteVenteService <= 1) {
try {
idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
} catch (Exception e) {
e.printStackTrace();
}
}
}
BigDecimal portHT = BigDecimal.valueOf(avoirRow.getLong("PORT_HT")).movePointLeft(2);
 
try {
// compte Vente Produits
final long produitHT = prixHT.getLongValue() - prixService.getLongValue();
if (produitHT >= 0) {
TotalCalculator calc = getValuesFromElement(avoirRow, avoirRow.getTable().getTable("AVOIR_CLIENT_ELEMENT"), portHT, null, null);
 
if (produitHT > 0) {
int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
if (idCompteVenteProduit <= 1) {
try {
idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
} catch (Exception e) {
e.printStackTrace();
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteProduit));
this.mEcritures.put("DEBIT", Long.valueOf(produitHT));
for (SQLRowAccessor row : calc.getMapHt().keySet()) {
long b = calc.getMapHt().get(row).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (b != 0) {
this.mEcritures.put("ID_COMPTE_PCE", row.getID());
this.mEcritures.put("DEBIT", Long.valueOf(b));
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
}
 
// si on a des frais de service
if (prixService.getLongValue() > 0) {
// compte Vente Services
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteService));
this.mEcritures.put("DEBIT", Long.valueOf(prixService.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
}
} else// la remise déborde sur les frais de service donc aucun frais
// pour les produits
{
// compte Vente Services
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteService));
this.mEcritures.put("DEBIT", Long.valueOf(prixHT.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
}
 
// compte TVA
if (prixTVA.getLongValue() > 0) {
int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
if (idCompteTVA <= 1) {
try {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
} catch (Exception e) {
e.printStackTrace();
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(avoirRow, avoirClientTable.getTable("AVOIR_CLIENT_ELEMENT"), true, prixHT, 0);
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
if (l != null && l > 0) {
// FIXME
int idCpt = i;
if (idCpt <= 1) {
idCpt = idCompteTVA;
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(l));
Map<SQLRowAccessor, BigDecimal> tvaMap = calc.getMapHtTVA();
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("DEBIT", Long.valueOf(longValue));
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
allTaxe += l;
}
}
if (allTaxe < prixTVA.getLongValue()) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
ajoutEcriture();
}
 
}
//
// // compte TVA
// int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
// if (idCompteTVA <= 1) {
// try {
// idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
// } catch (Exception e) {
//
// e.printStackTrace();
// }
// }
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
// this.mEcritures.put("DEBIT", Long.valueOf(prixTVA.getLongValue()));
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// ajoutEcriture();
 
// compte Clients
int idCompteClient = avoirRow.getForeignRow("ID_CLIENT").getInt("ID_COMPTE_PCE");
if (idCompteClient <= 1) {
206,9 → 130,11
}
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTTC.getLongValue()));
long ttc = calc.getTotalTTC().movePointRight(2).longValue();
this.mEcritures.put("CREDIT", Long.valueOf(ttc));
ajoutEcriture();
 
// Mise à jour de mouvement associé à la facture d'avoir
227,7 → 153,7
 
if (affacturage) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("DEBIT", Long.valueOf(ttc));
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
246,7 → 172,7
 
this.mEcritures.put("ID_COMPTE_PCE", idComptefactor);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(ttc));
ajoutEcriture();
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteFacture.java
13,18 → 13,23
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
// FIXME probleme lors de certaines generation tout reste figer
35,6 → 40,7
*/
public class GenerationMvtSaisieVenteFacture extends GenerationEcritures implements Runnable {
 
public static final String ID = "accounting.records.invoice.sales";
private static final String source = "SAISIE_VENTE_FACTURE";
public static final Integer journal = Integer.valueOf(JournalSQLElement.VENTES);
private int idSaisieVenteFacture;
41,6 → 47,7
private static final SQLTable saisieVFTable = base.getTable("SAISIE_VENTE_FACTURE");
private static final SQLTable taxeTable = base.getTable("TAXE");
private static final SQLTable mvtTable = base.getTable("MOUVEMENT");
private static final SQLTable ecrTable = base.getTable("ECRITURE");
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
 
85,8 → 92,6
 
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
 
// iniatilisation des valeurs de la map
this.date = (Date) saisieRow.getObject("DATE");
Boolean acompte = saisieRow.getBoolean("ACOMPTE");
if (acompte != null && acompte) {
this.nom = "Fact. acompte client" + saisieRow.getObject("NUMERO").toString();
93,120 → 98,65
} else {
this.nom = "Fact. vente " + saisieRow.getObject("NUMERO").toString();
}
 
// iniatilisation des valeurs de la map
this.date = (Date) saisieRow.getObject("DATE");
AccountingRecordsProvider provider = AccountingRecordsProviderManager.get(ID);
provider.putLabel(saisieRow, this.mEcritures);
 
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
 
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
 
// on calcule le nouveau numero de mouvement
if (this.idMvt == 1) {
getNewMouvement(GenerationMvtSaisieVenteFacture.source, this.idSaisieVenteFacture, 1, this.nom);
SQLRowValues rowValsPiece = new SQLRowValues(pieceTable);
provider.putPieceLabel(saisieRow, rowValsPiece);
getNewMouvement(GenerationMvtSaisieVenteFacture.source, this.idSaisieVenteFacture, 1, rowValsPiece);
} else {
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
SQLRowValues rowValsPiece = mvtTable.getRow(idMvt).getForeign("ID_PIECE").asRowValues();
rowValsPiece.put("NOM", this.nom);
provider.putPieceLabel(saisieRow, rowValsPiece);
try {
rowValsPiece.update();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
 
SQLTable tableEchantillon = null;
if (saisieVFTable.getDBRoot().contains("ECHANTILLON_ELEMENT")) {
tableEchantillon = saisieVFTable.getTable("ECHANTILLON_ELEMENT");
}
BigDecimal portHT = BigDecimal.valueOf(saisieRow.getLong("PORT_HT")).movePointLeft(2);
TotalCalculator calc = getValuesFromElement(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), portHT, saisieRow.getForeign("ID_TAXE_PORT"), tableEchantillon);
 
// On génére les ecritures si la facture n'est pas un acompte
long ttcLongValue = calc.getTotalTTC().movePointRight(2).longValue();
if (acompte == null || !acompte) {
// generation des ecritures + maj des totaux du compte associe
int idCompteVenteService = saisieRow.getInt("ID_COMPTE_PCE_SERVICE");
if (idCompteVenteService <= 1) {
idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
if (idCompteVenteService <= 1) {
try {
idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// compte Vente Produits
final long produitHT = prixHT.getLongValue() - prixService.getLongValue();
if (produitHT >= 0) {
 
if (produitHT > 0) {
 
int idCompteVenteProduit = saisieRow.getInt("ID_COMPTE_PCE_VENTE");
if (idCompteVenteProduit <= 1) {
idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
if (idCompteVenteProduit <= 1) {
try {
idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
} catch (Exception e) {
e.printStackTrace();
}
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteProduit));
for (SQLRowAccessor row : calc.getMapHt().keySet()) {
long b = calc.getMapHt().get(row).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (b != 0) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(produitHT));
this.mEcritures.put("CREDIT", Long.valueOf(b));
int idEcr = ajoutEcriture();
}
 
// si on a des frais de service
if (prixService.getLongValue() > 0) {
// compte Vente Services
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteService));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixService.getLongValue()));
int idEcr = ajoutEcriture();
 
}
} else// la remise déborde sur les frais de service donc aucun frais pour les produits
{
// compte Vente Services
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteVenteService));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixHT.getLongValue()));
int idEcr = ajoutEcriture();
 
}
 
// compte TVA
int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
if (prixTVA.getLongValue() > 0) {
if (idCompteTVA <= 1) {
try {
idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
} catch (Exception e) {
e.printStackTrace();
}
}
 
Map<Integer, Long> m = getMultiTVAFromRow(saisieRow, saisieVFTable.getTable("SAISIE_VENTE_FACTURE_ELEMENT"), true, prixHT, ((Long) (saisieRow.getObject("REMISE_HT"))).longValue());
long allTaxe = 0;
for (Integer i : m.keySet()) {
Long l = m.get(i);
if (l != null && l > 0) {
// FIXME
int idCpt = i;
if (idCpt <= 1) {
idCpt = idCompteTVA;
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
Map<SQLRowAccessor, BigDecimal> tvaMap = calc.getMapHtTVA();
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(l));
this.mEcritures.put("CREDIT", longValue);
ajoutEcriture();
allTaxe += l;
}
}
if (allTaxe < prixTVA.getLongValue()) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
ajoutEcriture();
}
 
}
// compte Clients
 
if (idCompteClient <= 1) {
220,7 → 170,10
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
if (ecrTable.contains("CODE_CLIENT")) {
this.mEcritures.put("CODE_CLIENT", clientRow.getString("CODE"));
}
this.mEcritures.put("DEBIT", ttcLongValue);
this.mEcritures.put("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java
19,7 → 19,6
import org.openconcerto.erp.core.finance.accounting.ui.ListeGestCommEltPanel;
import org.openconcerto.erp.core.finance.accounting.ui.SuppressionEcrituresPanel;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureElementXmlSheet;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.quote.ui.EtatDevisRenderer;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
30,10 → 29,10
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.users.rights.JListSQLTablePanel;
import org.openconcerto.sql.view.IListPanel;
import org.openconcerto.sql.view.ListeAddPanel;
42,7 → 41,6
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.Color;
import java.awt.Font;
53,10 → 51,8
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
94,7 → 90,6
 
static {
SQLElementDirectory dir = Configuration.getInstance().getDirectory();
elementSheet.put(dir.getElement("SAISIE_VENTE_FACTURE"), VenteFactureXmlSheet.class);
elementSheet.put(dir.getElement("SAISIE_VENTE_FACTURE_ELEMENT"), VenteFactureElementXmlSheet.class);
}
 
102,7 → 97,9
private final ListSelectionListener listListener = new ListSelectionListener() {
 
public void valueChanged(ListSelectionEvent e) {
 
if (e != null && e.getValueIsAdjusting()) {
return;
}
int selectIndex = ListeHistoriquePanel.this.jListePanel.getSelectedIndex();
 
SQLRowAccessor row = ListeHistoriquePanel.this.jListePanel.getModel().getRowAt(selectIndex);
129,17 → 126,7
 
Where w = null;
final SQLTable table = liste.getElement().getTable();
for (String key : ListeHistoriquePanel.this.whereList.keySet()) {
Where wTmp = ListeHistoriquePanel.this.whereList.get(key);
 
if (liste.getListe().getRequest().getAllFields().containsAll(wTmp.getFields())) {
if (w == null) {
w = wTmp;
} else {
w = w.and(wTmp);
}
}
}
if (id > 1) {
if (ListeHistoriquePanel.this.listFieldMap != null && ListeHistoriquePanel.this.listFieldMap.get(table) != null) {
SQLField field = ListeHistoriquePanel.this.listFieldMap.get(table);
175,13 → 162,13
}
};
 
public ListeHistoriquePanel(final String title, final ComboSQLRequest req, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap) {
this(title, req, listTableOnglet, panelBottom, listFieldMap, "Tous");
public ListeHistoriquePanel(final String title, final ComboSQLRequest req, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap, Where where) {
this(title, req, listTableOnglet, panelBottom, listFieldMap, "Tous", where);
}
 
public ListeHistoriquePanel(final String title, final ComboSQLRequest req, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap,
String undefinedLabel) {
this(title, req, listTableOnglet, panelBottom, listFieldMap, undefinedLabel, false);
String undefinedLabel, Where where) {
this(title, req, listTableOnglet, panelBottom, listFieldMap, undefinedLabel, false, where);
}
 
// TODO verifier que les tables contiennent bien la clef etrangere
194,9 → 181,10
* de foreignKey pointant sur tableList
* @param undefinedLabel label pour l'indéfini permettant de tout sélectionner, null si
* l'undefined n'est pas à inclure.
* @param where
*/
public ListeHistoriquePanel(final String title, final ComboSQLRequest req, Map<String, List<String>> listTableOnglet, JPanel panelBottom, Map<SQLTable, SQLField> listFieldMap,
String undefinedLabel, final boolean sourceWithOutTransformer) {
String undefinedLabel, final boolean sourceWithOutTransformer, Where where) {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
231,9 → 219,21
final SQLElement elt = Configuration.getInstance().getDirectory().getElement(listPanelTable.get(i));
 
IListPanel liste;
SQLTableModelSourceOnline createTableSource = elt.getTableSource(true);
final ListSQLRequest request = createTableSource.getReq();
if (sourceWithOutTransformer) {
request.setSelectTransf(null);
}
if (where != null) {
if (request.getAllFields().containsAll(where.getFields())) {
request.setWhere(where);
}
}
 
if (elt.getTable().contains("ID_MOUVEMENT")) {
liste = new ListeGestCommEltPanel(elt, Where.FALSE, "historique-" + title) {
 
liste = new ListeGestCommEltPanel(elt, new IListe(createTableSource), "historique-" + title) {
 
protected void handleAction(JButton source, ActionEvent evt) {
 
if (elt.getTable().contains("ID_MOUVEMENT")) {
257,15 → 257,11
};
 
} else {
SQLTableModelSourceOnline createTableSource = elt.createTableSource(Where.FALSE);
if (sourceWithOutTransformer) {
createTableSource.getReq().setSelectTransf(null);
}
 
liste = new ListeAddPanel(elt, new IListe(createTableSource), "historique-" + title) {
@Override
protected void handleAction(JButton source, ActionEvent evt) {
if (source == this.buttonAjouter) {
final boolean deaf = isDeaf();
// toujours remplir la createFrame avec la ligne sélectionnée
// car la frame écoute la sélection mais pas les modif, et se reset
// qd on la ferme
301,6 → 297,7
liste.getListe().setSQLEditable(false);
liste.setOpaque(false);
liste.setBorder(null);
liste.getListe().getModel().setHibernateDelay(-1);
 
if (listPanelTable.size() > 1) {
Font f = UIManager.getFont("TitledBorder.font");
377,12 → 374,6
}
 
public void selectIDinJList(int id) {
// int index = this.jListePanel.getModel().getIndexForId(id);
// if (index >= 0) {
// this.jListePanel.getJList().setSelectedIndex(index);
// this.jListePanel.getJList().ensureIndexIsVisible(index);
// }
 
this.jListePanel.selectID(id);
}
 
409,21 → 400,9
}
}
 
/**
* @param col Collection de SQLField
* @return liste des noms des champs contenus dans col
*/
private List<String> getListSQLField(Collection<SQLField> col) {
List<String> l = new ArrayList<String>();
for (Iterator<SQLField> i = col.iterator(); i.hasNext();) {
SQLField field = i.next();
l.add(field.getName());
}
return l;
}
 
public void addListSelectionListener(ListSelectionListener l) {
this.jListePanel.addListSelectionListener(l);
System.out.println("ListeHistoriquePanel.addListSelectionListener()" + jListePanel);
}
 
public void removeListSelectionListener(ListSelectionListener l) {
466,7 → 445,7
listeIds.add(liste.idFromIndex(i));
}
} else {
listeIds = Collections.EMPTY_LIST;
listeIds = Collections.emptyList();
}
return listeIds;
}
511,7 → 490,23
*/
 
public IListe getIListeFromTableName(String tableName) {
IListe liste = null;
IListPanel liste = getIListePanelFromTableName(tableName);
if (liste == null) {
return null;
} else {
return liste.getListe();
}
}
 
/**
* Permet d'obtenir la IListe correspondant au nom d'une table
*
* @param tableName nom de la table
* @return la Iliste associée, dans le cas échéant null
*/
 
public IListPanel getIListePanelFromTableName(String tableName) {
IListPanel liste = null;
for (int i = 0; i < this.vectListePanel.size(); i++) {
IListPanel listeTmp = this.vectListePanel.get(i);
// FIXME Null pointer Exception when client deleted
521,7 → 516,7
final ITableModel model = list.getModel();
if (model != null) {
if (model.getTable().getName().equalsIgnoreCase(tableName)) {
liste = listeTmp.getListe();
liste = listeTmp;
}
}
}
552,12 → 547,38
}
 
public void fireListesChanged() {
System.err.println("ListeHistoriquePanel.fireListesChanged()");
final int size = this.vectListePanel.size();
for (int i = 0; i < size; i++) {
final IListPanel listeTmp = this.vectListePanel.get(i);
final ITableModel model = listeTmp.getListe().getModel();
model.fireTableDataChanged();
model.fireTableStructureChanged();
}
 
for (int i = 0; i < this.vectListePanel.size(); i++) {
IListPanel listeTmp = this.vectListePanel.get(i);
listeTmp.getListe().getModel().fireTableDataChanged();
listeTmp.getListe().getModel().fireTableStructureChanged();
}
 
// TODO Gestion de weakListener pour eviter de devoir supprimer les listeners pour le garbage
 
// public void addWeakListenerTable(TableModelListener listener, String tableName) {
// addListenerTable(new WeakListener(listener), tableName);
// }
//
// private final class WeakListener extends WeakReference<TableModelListener> implements
// TableModelListener {
// private WeakListener(TableModelListener referent) {
// super(referent);
// }
//
// @Override
// public void tableChanged(TableModelEvent e) {
//
// final TableModelListener l = this.get();
// if (l != null)
// l.tableChanged(e);
// // else
// //
// // this.rmListener_(this);
// }
// }
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/HistoriqueClientBilanPanel.java
16,7 → 16,6
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
33,7 → 32,6
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
93,15 → 91,11
}
}
 
SwingWorker<String, Object> workerTotalVente;
public synchronized void updateTotalVente(final int idClient) {
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
public synchronized void updateTotalVente(final int idClient) {
if (workerTotalVente != null && !workerTotalVente.isDone()) {
workerTotalVente.cancel(true);
}
workerTotalVente = new SwingWorker<String, Object>() {
@Override
protected String doInBackground() throws Exception {
public void run() {
 
final SQLBase base = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getSQLBaseSociete();
 
109,7 → 103,7
final SQLTable tableVC = base.getTable("SAISIE_VENTE_COMPTOIR");
 
// Total VF
final SQLSelect selVF = new SQLSelect(base);
final SQLSelect selVF = new SQLSelect();
selVF.addSelect(tableVF.getField("T_HT"), "SUM");
 
if (idClient > 1) {
121,7 → 115,7
final long totalVF = o == null ? 0 : ((Number) o).longValue();
 
// Total VC
final SQLSelect selVC = new SQLSelect(base);
final SQLSelect selVC = new SQLSelect();
selVC.addSelect(tableVC.getField("MONTANT_HT"), "SUM");
 
if (idClient > 1) {
132,12 → 126,12
final Object oVC = base.getDataSource().executeScalar(reqVC);
final long totalVC = oVC == null ? 0 : ((Number) oVC).longValue();
 
final SQLSelect selAllVF = new SQLSelect(base);
final SQLSelect selAllVF = new SQLSelect();
selAllVF.addSelect(tableVF.getField("T_HT"), "SUM");
final Object o2 = base.getDataSource().executeScalar(selAllVF.asString());
final long totalAllVF = o2 == null ? 0 : ((Number) o2).longValue();
 
final SQLSelect selAllVC = new SQLSelect(base);
final SQLSelect selAllVC = new SQLSelect();
selAllVC.addSelect(tableVC.getField("MONTANT_HT"), "SUM");
final Object oVCA = base.getDataSource().executeScalar(selAllVC.asString());
final long totalAllVC = oVCA == null ? 0 : ((Number) oVCA).longValue();
148,56 → 142,63
final double pourCentage = (totalVF + totalVC) / (double) (totalAllVC + totalAllVF) * 100.0;
setPoucentageVentes((int) Math.round(pourCentage * 100.0) / 100);
}
return null;
updateLabels();
 
}
});
 
@Override
protected void done() {
updateLabels();
super.done();
}
};
workerTotalVente.execute();
}
 
// TODO: se passer de requete en utilisant les valeurs de la IListe si c'est possible
// TODO: eviter les N meme requetes en double quand on selectionne un client
public synchronized void updateEcheance(final List<Integer> listId) {
 
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
 
long valueTotal = 0;
if (listId != null && listId.size() > 0) {
final SQLBase base = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getSQLBaseSociete();
final SQLTable tableEch = base.getTable("ECHEANCE_CLIENT");
long valueTotal = 0;
if (listId != null) {
for (final Iterator<Integer> i = listId.iterator(); i.hasNext();) {
final SQLRow row = tableEch.getRow(i.next());
if (row != null) {
final Object montantO = row.getObject("MONTANT");
valueTotal += Long.parseLong(montantO.toString());
final SQLSelect select = new SQLSelect();
final SQLTable table = base.getTable("ECHEANCE_CLIENT");
select.addSelect(table.getField("MONTANT"), "SUM");
select.setWhere(new Where(table.getKey(), listId));
final Number n = (Number) base.getDBSystemRoot().getDataSource().executeScalar(select.asString());
if (n != null) {
valueTotal = n.longValue();
}
}
}
setNbFacturesImpayees(listId == null ? 0 : listId.size());
setTotalFacturesImpayees(valueTotal);
updateLabels();
 
}
});
 
}
 
public synchronized void updateVFData(final List<Integer> listId, final int idClient) {
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
final SQLBase base = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getSQLBaseSociete();
 
final SQLTable tableVF = base.getTable("SAISIE_VENTE_FACTURE");
 
long valueTotal = 0;
if (listId != null) {
for (final Iterator<Integer> i = listId.iterator(); i.hasNext();) {
final SQLRow rowTmp = tableVF.getRow(i.next());
if (rowTmp != null) {
final Object montantO = rowTmp.getObject("T_HT");
valueTotal += new Long(montantO.toString());
if (listId != null && listId.size() > 0) {
final SQLSelect select = new SQLSelect();
final SQLTable table = base.getTable("SAISIE_VENTE_FACTURE");
select.addSelect(table.getField("T_HT"), "SUM");
select.setWhere(new Where(table.getKey(), listId));
final Number n = (Number) base.getDBSystemRoot().getDataSource().executeScalar(select.asString());
if (n != null) {
valueTotal = n.longValue();
}
}
}
 
final Map<Object, Date> mapDateFact = new HashMap<Object, Date>();
// On recupere les dates de facturations VF
final SQLSelect selDateFacture = new SQLSelect(base);
final SQLSelect selDateFacture = new SQLSelect();
final SQLTable tableFacture = base.getTable("SAISIE_VENTE_FACTURE");
final SQLTable tableEncaisse = base.getTable("ENCAISSER_MONTANT");
final SQLTable tableEcheance = base.getTable("ECHEANCE_CLIENT");
213,7 → 214,7
addDatesToMap(base, selDateFacture, mapDateFact);
 
// On recupere les dates de facturations
final SQLSelect selDateFactureC = new SQLSelect(base);
final SQLSelect selDateFactureC = new SQLSelect();
final SQLTable tableComptoir = base.getTable("SAISIE_VENTE_COMPTOIR");
selDateFactureC.addSelect(tableComptoir.getField("DATE"));
selDateFactureC.addSelect(tableMvt.getField("ID_PIECE"));
225,7 → 226,7
addDatesToMap(base, selDateFactureC, mapDateFact);
 
// On recupere les dates d'encaissement
final SQLSelect selDateEncaisse = new SQLSelect(base);
final SQLSelect selDateEncaisse = new SQLSelect();
selDateEncaisse.addSelect(tableEncaisse.getField("DATE"));
selDateEncaisse.addSelect(tableMvt.getField("ID_PIECE"));
selDateEncaisse.addSelect(tableEcheance.getField("ID"));
287,6 → 288,8
setNbVentesFacture(listId == null ? 0 : listId.size());
updateLabels();
}
});
}
 
private void addDatesToMap(final SQLBase base, final SQLSelect selDateFacture, final Map mapDateFact) {
final List<Object[]> lDateFact = (List<Object[]>) base.getDataSource().execute(selDateFacture.asString(), new ArrayListHandler());
299,47 → 302,67
}
 
public synchronized void updateVCData(final List<Integer> listId) {
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
final SQLBase base = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getSQLBaseSociete();
final SQLTable tableVC = base.getTable("SAISIE_VENTE_COMPTOIR");
 
long valueTotal = 0;
if (listId != null) {
for (final Iterator<Integer> i = listId.iterator(); i.hasNext();) {
final SQLRow rowTmp = tableVC.getRow(i.next());
if (rowTmp != null) {
final Object montantO = rowTmp.getObject("MONTANT_HT");
valueTotal += new Long(montantO.toString());
 
if (listId != null && listId.size() > 0) {
final SQLSelect select = new SQLSelect();
final SQLTable table = base.getTable("SAISIE_VENTE_COMPTOIR");
select.addSelect(table.getField("MONTANT_HT"), "SUM");
select.setWhere(new Where(table.getKey(), listId));
final Number n = (Number) base.getDBSystemRoot().getDataSource().executeScalar(select.asString());
if (n != null) {
valueTotal = n.longValue();
}
}
}
 
setNbVentesComptoir(listId == null ? 0 : listId.size());
setTotalVentesComptoir(valueTotal);
updateLabels();
}
});
}
 
 
public synchronized void updateChequeData(final List<Integer> listId) {
ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
 
@Override
public void run() {
final SQLBase base = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getSQLBaseSociete();
final SQLTable tableC = base.getTable("CHEQUE_A_ENCAISSER");
final SQLTable table = base.getTable("CHEQUE_A_ENCAISSER");
long valueTotalTmp = 0;
long valueNonEncaisseTmp = 0;
if (listId != null) {
for (final Iterator<Integer> i = listId.iterator(); i.hasNext();) {
final SQLRow row = tableC.getRow(i.next());
if (row != null) {
final Object montantO = row.getObject("MONTANT");
valueTotalTmp += Long.parseLong(montantO.toString());
if (!row.getBoolean("ENCAISSE")) {
valueNonEncaisseTmp++;
 
if (listId != null && listId.size() > 0) {
// Total
final SQLSelect select = new SQLSelect();
select.addSelect(table.getField("MONTANT"), "SUM");
select.setWhere(new Where(table.getKey(), listId));
Number n = (Number) base.getDBSystemRoot().getDataSource().executeScalar(select.asString());
if (n != null) {
valueTotalTmp = n.longValue();
}
// Total non encaissé
select.setWhere(new Where(table.getKey(), listId).and(new Where(table.getField("ENCAISSE"), "=", Boolean.FALSE)));
n = (Number) base.getDBSystemRoot().getDataSource().executeScalar(select.asString());
if (n != null) {
valueNonEncaisseTmp = n.longValue();
}
}
}
 
setNbTotalCheques(listId == null ? 0 : listId.size());
setNbChequesNonEncaisses(valueNonEncaisseTmp);
setTotalCheques(valueTotalTmp);
updateLabels();
}
});
}
 
// Ventes comptoir
public void setNbVentesComptoir(final long nb) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/HistoriqueClientFrame.java
26,7 → 26,6
 
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
65,8 → 64,11
map.put(b.getTable("DEVIS_ELEMENT"), b.getTable("DEVIS_ELEMENT").getField("ID_DEVIS"));
 
final HistoriqueClientBilanPanel bilanPanel = new HistoriqueClientBilanPanel();
this.listPanel = new ListeHistoriquePanel("Clients", JListSQLTablePanel.createComboRequest(b.getTable("CLIENT"), true), mapList, bilanPanel, map);
SQLTable tableEch = Configuration.getInstance().getRoot().findTable("ECHEANCE_CLIENT");
Where wNotRegle = new Where(tableEch.getField("REGLE"), "=", Boolean.FALSE);
wNotRegle = wNotRegle.and(new Where(tableEch.getField("REG_COMPTA"), "=", Boolean.FALSE));
 
this.listPanel = new ListeHistoriquePanel("Clients", JListSQLTablePanel.createComboRequest(b.getTable("CLIENT"), true), mapList, bilanPanel, map, wNotRegle);
this.listPanel.addListenerTable(new TableModelListener() {
public void tableChanged(TableModelEvent arg0) {
bilanPanel.updateRelance(HistoriqueClientFrame.this.listPanel.getListId("RELANCE"));
100,12 → 102,6
}
}, "SAISIE_VENTE_FACTURE");
 
SQLTable tableEch = Configuration.getInstance().getRoot().findTable("ECHEANCE_CLIENT");
Where wNotRegle = new Where(tableEch.getField("REGLE"), "=", Boolean.FALSE);
wNotRegle = wNotRegle.and(new Where(tableEch.getField("REG_COMPTA"), "=", Boolean.FALSE));
 
this.listPanel.addWhere("FiltreEcheance", wNotRegle);
 
this.panelFrame = new PanelFrame(this.listPanel, "Historique client");
this.panelFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
180,7 → 180,7
}
}
CollectionMap<SQLRow, List<SQLRowValues>> map = updateStock(l, false);
if (map.keySet().size() > 0) {
if (map.keySet().size() > 0 && !rowOrigin.getTable().getName().equalsIgnoreCase("TICKET_CAISSE")) {
if (!rowOrigin.getTable().contains("ID_TARIF")) {
System.err.println("Attention la table " + rowOrigin.getTable().getName()
+ " ne contient pas le champ ID_TARIF. La création automatique d'une commande fournisseur est donc impossible!");
270,7 → 270,11
}
 
public static void createCommandeF(final CollectionMap<SQLRow, List<SQLRowValues>> col, final SQLRow rowDevise) {
createCommandeF(col, rowDevise, "");
}
 
public static void createCommandeF(final CollectionMap<SQLRow, List<SQLRowValues>> col, final SQLRow rowDevise, final String ref) {
 
if (col.keySet().size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
315,6 → 319,10
if (rowDevise != null) {
rowVals.put("ID_DEVISE", rowDevise.getID());
}
if (commande.getTable().contains("ID_ADRESSE")) {
rowVals.put("ID_ADRESSE", null);
}
rowVals.put("NOM", ref);
cmp.select(rowVals);
cmp.getRowValuesTable().getRowValuesTable().getRowValuesTableModel().clearRows();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/action/NouvelHistoriqueListeFournAction.java
49,7 → 49,8
mapList.put("Chèques émis", Arrays.asList("CHEQUE_FOURNISSEUR"));
 
final HistoriqueFournBilanPanel panelBilan = new HistoriqueFournBilanPanel();
final ListeHistoriquePanel listHistoriquePanel = new ListeHistoriquePanel("Fournisseurs", JListSQLTablePanel.createComboRequest(b.getTable("FOURNISSEUR"), true), mapList, panelBilan, null);
final ListeHistoriquePanel listHistoriquePanel = new ListeHistoriquePanel("Fournisseurs", JListSQLTablePanel.createComboRequest(b.getTable("FOURNISSEUR"), true), mapList, panelBilan, null,
null);
 
listHistoriquePanel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeSQLElement.java
42,12 → 42,12
super("COMMANDE", "une commande fournisseur", "commandes fournisseur");
 
// Transfert vers facture
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction("Transfert vers saisie achat") {
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
 
CommandeSQLElement.this.transfertFacture(IListe.get(e).getSelectedRow().getID());
}
}, false);
}, false, "supplychain.order.create.purchase");
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(factureAction);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesClientAction.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesCommandesAction.java
47,11 → 47,11
@Override
public List<RowAction> addToMenu() {
// Transfert vers BR
PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction("Transfert vers BR") {
PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
transfertBonReceptionClient(IListe.get(e).getSelectedRow());
}
}, false);
}, false, "supplychain.order.create.receipt");
 
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
399,6 → 399,14
}
});
}
 
this.fourn.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
table.setFournisseur(fourn.getSelectedRow());
}
});
// Bottom
c.gridy++;
c.weighty = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/CodeFournisseurSQLElement.java
New file
0,0 → 1,63
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.sqlobject.ElementComboBox;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JTextField;
 
public class CodeFournisseurSQLElement extends ComptaSQLConfElement {
 
public CodeFournisseurSQLElement() {
super("CODE_FOURNISSEUR", "un code fournisseur", "codes fournisseurs");
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
return l;
}
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
return l;
}
 
/*
* (non-Javadoc)
*
* @see org.openconcerto.devis.SQLElement#getComponent()
*/
public SQLComponent createComponent() {
return new UISQLComponent(this) {
public void addViews() {
this.addRequiredSQLObject(new JTextField(), "CODE", "right");
 
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".productcode";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
51,6 → 51,10
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.SQLException;
import java.util.List;
 
186,6 → 190,14
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
this.add(this.tableBonItem, c);
this.fournisseur.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
tableBonItem.setFournisseur(fournisseur.getSelectedRow());
}
});
 
c.anchor = GridBagConstraints.EAST;
// Totaux
reconfigure(this.textTotalHT);
508,19 → 520,22
if (idArticle > 1) {
// Prix d'achat de l'article à l'origine
SQLRow rowArticle = eltArticle.getTable().getRow(idArticle);
Long prixHA = (Long) rowArticle.getObject("PRIX_METRIQUE_HA_1");
BigDecimal prixHA = (BigDecimal) rowArticle.getObject("PRIX_METRIQUE_HA_1");
 
// Quantité en stock
int idStock = rowArticle.getInt("ID_STOCK");
SQLRow rowStock = eltStock.getTable().getRow(idStock);
int qteStock = rowStock.getInt("QTE_REEL");
if (prixHA != null && qteStock > 0) {
int qteRecue = rowEltBon.getInt("QTE");
Long prixHACmd = (Long) rowEltBon.getObject("PRIX_METRIQUE_HA_1");
if (qteRecue > 0 && prixHACmd != null) {
long prixHaPond = (qteRecue * prixHACmd + qteStock * prixHA) / (qteRecue + qteStock);
BigDecimal qteStock = new BigDecimal(rowStock.getInt("QTE_REEL"));
if (prixHA != null && qteStock.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal qteRecue = new BigDecimal(rowEltBon.getInt("QTE"));
BigDecimal prixHACmd = (BigDecimal) rowEltBon.getObject("PRIX_METRIQUE_HA_1");
if (qteRecue.compareTo(BigDecimal.ZERO) > 0 && prixHACmd != null) {
BigDecimal totalHARecue = qteRecue.multiply(prixHACmd, MathContext.DECIMAL128);
BigDecimal totalHAStock = qteStock.multiply(prixHA, MathContext.DECIMAL128);
BigDecimal totalQte = qteRecue.add(qteStock);
BigDecimal prixHaPond = totalHARecue.add(totalHAStock).divide(totalQte);
SQLRowValues rowValsArticle = rowArticle.createEmptyUpdateRow();
rowValsArticle.put("PRIX_METRIQUE_HA_1", Long.valueOf(prixHaPond));
rowValsArticle.put("PRIX_METRIQUE_HA_1", prixHaPond);
try {
rowValsArticle.commit();
} catch (SQLException e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
15,21 → 15,108
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.customerrelationship.customer.report.FicheClientXmlSheet;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.map.model.Ville;
import org.openconcerto.ql.LabelCreator;
import org.openconcerto.ql.QLPrinter;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
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.EmailComposer;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.SwingUtilities;
 
public class ClientNormalSQLElement extends ComptaSQLConfElement {
 
public ClientNormalSQLElement() {
super("CLIENT", "un client", "clients");
final String property = PrinterNXProps.getInstance().getProperty("QLPrinter");
if (property != null && property.trim().length() > 0) {
PredicateRowAction actionPrintLabel = new PredicateRowAction(new AbstractAction() {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLRowAccessor row = IListe.get(e).getSelectedRow();
final LabelCreator c = new LabelCreator(720);
c.setLeftMargin(10);
c.setTopMargin(10);
c.setDefaultFont(new Font("Verdana", Font.PLAIN, 50));
 
c.addLineBold(row.getString("NOM"));
final SQLRowAccessor foreignRow = row.getForeign("ID_ADRESSE");
final String string = foreignRow.getString("RUE");
String[] s = string.split("\n");
for (String string2 : s) {
System.err.println(string2);
c.addLineNormal(string2);
}
 
Ville v = Ville.getVilleFromVilleEtCode(foreignRow.getString("VILLE"));
c.addLineNormal(v.getCodepostal() + " " + v.getName());
 
System.err.println("\"" + property + "\"");
final QLPrinter prt = new QLPrinter(property);
try {
prt.print(c.getImage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, false, "customerrelationship.customer.label.print");
actionPrintLabel.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionPrintLabel);
}
 
 
 
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);
}
 
protected void sendMail(List<SQLRowAccessor> l) {
 
String mail = "";
for (SQLRowAccessor rowCli : l) {
String string = rowCli.getString("MAIL");
if (string != null && string.trim().length() > 0) {
mail += string + ";";
}
}
try {
EmailComposer.getInstance().compose(mail, "", "");
} catch (Exception exn) {
ExceptionHandler.handle(null, "Impossible de créer le courriel", exn);
}
 
}
 
protected boolean showMdr = true;
 
protected List<String> getListFields() {
52,6 → 139,9
l.add("ID_COMPTE_PCE");
l.add("ID_MODE_REGLEMENT");
l.add("INFOS");
if (getTable().contains("GRAND_COMPTE"))
l.add("GRAND_COMPTE");
 
return l;
}
 
98,5 → 188,4
return new ClientNormalSQLComponent(this);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLComponent.java
178,9 → 178,9
boxPays = new ElementComboBox(true, 25);
c.gridx++;
c.weightx = 0.5;
DefaultGridBagConstraints.lockMinimumSize(boxPays);
this.add(boxPays, c);
this.addView(boxPays, "ID_PAYS");
DefaultGridBagConstraints.lockMinimumSize(boxPays);
}
if (getTable().getFieldsName().contains("LOCALISATION")) {
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/action/ListeDesClientsAction.java
73,41 → 73,7
}
}
 
final String property = PrinterNXProps.getInstance().getProperty("QLPrinter");
if (property != null && property.trim().length() > 0) {
panel.getListe().addRowAction(RowAction.createAction("Imprimer l'étiquette client", null, new IClosure<List<SQLRowAccessor>>() {
@Override
public void executeChecked(List<SQLRowAccessor> input) {
final SQLRowAccessor row = input.get(0);
final LabelCreator c = new LabelCreator(720);
c.setLeftMargin(10);
c.setTopMargin(10);
c.setDefaultFont(new Font("Verdana", Font.PLAIN, 50));
 
c.addLineBold(row.getString("NOM"));
final SQLRowAccessor foreignRow = row.getForeign("ID_ADRESSE");
final String string = foreignRow.getString("RUE");
String[] s = string.split("\n");
for (String string2 : s) {
System.err.println(string2);
c.addLineNormal(string2);
}
 
Ville v = Ville.getVilleFromVilleEtCode(foreignRow.getString("VILLE"));
c.addLineNormal(v.getCodepostal() + " " + v.getName());
 
System.err.println("\"" + property + "\"");
final QLPrinter prt = new QLPrinter(property);
try {
prt.print(c.getImage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}));
}
 
 
panel.setSearchFullMode(true);
panel.setSelectRowOnAdd(false);
return frame;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmSQLElement.java
129,7 → 129,7
SQLRow rowSaisieKm = vals.insert();
idSaisie = rowSaisieKm.getID();
 
SQLSelect selEcriture = new SQLSelect(base);
SQLSelect selEcriture = new SQLSelect();
selEcriture.addSelect(ecrTable.getField("ID"));
 
Where w = new Where(ecrTable.getField("ID_MOUVEMENT"), "=", idMvt);
278,7 → 278,6
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
this.add(this.tableKm, c);
this.tableKm.getModel().clearRows();
 
// Initialisation du panel des Totaux
JPanel panelTotal = new JPanel();
633,19 → 632,13
}
this.tableKm.revalidate();
this.tableKm.repaint();
// totalCred = (float) new PrixHT(totalCred).getValue();
// totalDeb = (float) new PrixHT(totalDeb).getValue();
 
this.isCompteExist = isCompteExist;
this.allLineValid = allLineValid;
this.setTotals(totalCred, totalDeb);
 
updateValidState();
 
// add a row to balance totals
final long diffWithNoValid = totalDebWithNoValid - totalCredWithNoValid;
// System.err.println("Valid ___ " + diff + " NO VALID _____ " +
// diffWithNoValid);
if (diffWithNoValid != 0) {
if (diffWithNoValid > 0) {
this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(0));
652,34 → 645,16
this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(diffWithNoValid));
if (this.model.isLastRowValid()) {
this.tableKm.getModel().addRow(new SQLRowValues(this.defaultEcritureRowVals));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (SaisieKmComponent.this.model.getRowCount() > 0) {
SaisieKmComponent.this.tableKm.editCellAt(SaisieKmComponent.this.model.getRowCount() - 1, 0);
 
}
}
});
}
} else {
this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(-diffWithNoValid));
this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(0));
if (this.model.isLastRowValid()) {
this.tableKm.getModel().addRow(new SQLRowValues(this.defaultEcritureRowVals));
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (SaisieKmComponent.this.model.getRowCount() > 0) {
SaisieKmComponent.this.tableKm.editCellAt(SaisieKmComponent.this.model.getRowCount() - 1, 0);
}
}
});
 
// System.err.println("RowValid " + e.getType());
} else {
System.err.println(e.getType());
}
}
} else {
this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(0));
this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(0));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCESQLElement.java
18,14 → 18,18
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.component.ITextArea;
77,17 → 81,16
 
@Override
public void update() {
// TODO Raccord de méthode auto-généré
int id = getSelectedID();
final int id = getSelectedID();
super.update();
SQLElement eltEcr = Configuration.getInstance().getDirectory().getElement("ECRITURE");
Configuration
.getInstance()
.getBase()
.getDataSource()
.execute(
"UPDATE " + eltEcr.getTable().getSQLName().quote() + " SET \"COMPTE_NUMERO\"=c.\"NUMERO\",\"COMPTE_NOM\"=c.\"NOM\" FROM " + getTable().getSQLName().quote()
+ " c WHERE c.\"ID\"=\"ID_COMPTE_PCE\" AND c.\"ID\"=" + id);
final DBSystemRoot sysRoot = getTable().getDBSystemRoot();
final SQLTable ecrT = sysRoot.getGraph().findReferentTable(getTable(), "ECRITURE");
final UpdateBuilder updateBuilder = new UpdateBuilder(ecrT);
updateBuilder.addTable(getTable());
updateBuilder.set("COMPTE_NUMERO", getTable().getField("NUMERO").getFieldRef());
updateBuilder.set("COMPTE_NOM", getTable().getField("NOM").getFieldRef());
updateBuilder.setWhere(new Where(getTable().getKey(), "=", ecrT.getField("ID_COMPTE_PCE")).and(new Where(getTable().getKey(), "=", id)));
sysRoot.getDataSource().execute(updateBuilder.asString());
}
 
public void addViews() {
222,30 → 225,22
return getId(numero, "Création automatique");
}
 
/**
* retourne l'id d'un compte en fonction de son numero, si le compte n'existe pas il sera créé
* automatiquement
*
* @param numero du compte
* @param nom nom du compte
* @return id du compte
*/
public static int getId(String numero, String nom) {
 
public static SQLRow getRow(String numero, String nom) {
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
SQLTable compteTable = base.getTable("COMPTE_PCE");
SQLSelect selCompte = new SQLSelect(base);
selCompte.addSelect(compteTable.getField("ID"));
SQLSelect selCompte = new SQLSelect();
selCompte.addSelectStar(compteTable);
selCompte.setWhere(new Where(compteTable.getField("NUMERO"), "=", numero.trim()));
 
String reqCompte = selCompte.asString();
// String reqCompte = selCompte.asString();
//
// Object obCompte = base.getDataSource().execute(reqCompte, new ArrayListHandler());
//
// List myListCompte = (List) obCompte;
 
Object obCompte = base.getDataSource().execute(reqCompte, new ArrayListHandler());
 
List myListCompte = (List) obCompte;
 
List<SQLRow> myListCompte = SQLRowListRSH.execute(selCompte);
if (myListCompte.size() != 0) {
return Integer.parseInt(((Object[]) myListCompte.get(0))[0].toString());
return myListCompte.get(0);
} else {
 
SQLRowValues rowVals = new SQLRowValues(compteTable);
252,36 → 247,37
rowVals.put("NUMERO", numero);
rowVals.put("NOM", nom);
try {
SQLRow row = rowVals.insert();
return row.getID();
return rowVals.insert();
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la création du compte numéro : " + numero, e);
return null;
}
 
e.printStackTrace();
}
return rowVals.getID();
}
 
/**
* retourne l'id d'un compte en fonction de son numero, si le compte n'existe pas il sera créé
* automatiquement
*
* @param numero du compte
* @param nom nom du compte
* @return id du compte
*/
public static int getId(String numero, String nom) {
return getRow(numero, nom).getID();
}
 
public static boolean isExist(String numero) {
public static boolean isExist(String account) {
 
if (numero.trim().length() == 0) {
if (account.trim().length() == 0) {
return false;
}
 
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
SQLTable compteTable = base.getTable("COMPTE_PCE");
SQLSelect selCompte = new SQLSelect(base);
selCompte.addSelect(compteTable.getField("ID"));
selCompte.setWhere(new Where(compteTable.getField("NUMERO"), "=", numero.trim()));
final SQLTable tableAccount = Configuration.getInstance().getDirectory().getElement("COMPTE_PCE").getTable();
final SQLBackgroundTableCacheItem item = SQLBackgroundTableCache.getInstance().getCacheForTable(tableAccount);
return (item.getFirstRowContains(account, tableAccount.getField("NUMERO")) != null);
 
String reqCompte = selCompte.asString();
 
Object obCompte = base.getDataSource().execute(reqCompte, new ArrayListHandler());
 
List myListCompte = (List) obCompte;
 
return (myListCompte.size() != 0);
 
}
 
/**
292,7 → 288,7
public static String getComptePceDefault(final String name) throws IllegalArgumentException {
final SQLBase base = Configuration.getInstance().getBase();
final SQLTable tableDefault = base.getTable("COMPTE_PCE_DEFAULT");
final SQLSelect sel = new SQLSelect(base);
final SQLSelect sel = new SQLSelect();
sel.addSelect(tableDefault.getField("NUMERO_DEFAULT"));
 
sel.setWhere(Where.quote("UPPER(%n) = %s", tableDefault.getField("NOM"), name.toUpperCase()));
310,6 → 306,11
return getId(numeroDefault);
}
 
public static SQLRow getRowComptePceDefault(final String name) throws Exception {
final String numeroDefault = getComptePceDefault(name);
return getRow(numeroDefault, "création automatique");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".code.enterprise";
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/PDFImageInsertor.java
New file
0,0 → 1,55
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
/*
* Créé le 2 août 2012
*/
package org.openconcerto.erp.core.finance.accounting.report;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
 
public class PDFImageInsertor {
 
public PDFImageInsertor() {
 
}
 
public void insert(File pdf, Image img, int page, boolean under) throws Exception {
 
PdfReader reader;
 
reader = new PdfReader(new FileInputStream(pdf));
 
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdf));
 
// img.setAbsolutePosition(20, 40);
 
// int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
if (under) {
content = stamper.getUnderContent(page);
} else {
content = stamper.getOverContent(page);
}
content.addImage(img);
stamper.close();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/JournauxSheet.java
15,7 → 15,6
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.SheetInterface;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.Configuration;
28,10 → 27,8
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
 
import java.io.File;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheetXML.java
81,6 → 81,11
return "GrandLivre" + date.getTime();
}
 
@Override
protected String getStoragePathP() {
return "Grand Livre";
}
 
public GrandLivreSheetXML(Date du, Date au, String compteDep, String compteEnd, int lettrage, boolean cumul, boolean excludeCptSolde, boolean centralClient, boolean centralFourn, int idJrnlExclude) {
super();
Calendar cal = Calendar.getInstance();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/BalanceAgeeListeSheetXML.java
36,6 → 36,7
public static String TEMPLATE_ID = "Balance agée";
 
public BalanceAgeeListeSheetXML(Date deb, Date fin) {
super();
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.deb = deb;
this.fin = fin;
46,11 → 47,21
return "BalanceAgee";
}
 
Date d;
 
@Override
public String getName() {
return "BalanceAgee" + new Date().getTime();
if (d == null) {
d = new Date();
}
return "BalanceAgee" + d.getTime();
}
 
@Override
protected String getStoragePathP() {
return "Balance";
}
 
protected void createListeValues() {
SQLElement ecr = Configuration.getInstance().getDirectory().getElement("ECRITURE");
SQLElement cpt = Configuration.getInstance().getDirectory().getElement("COMPTE_PCE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/JournauxSheetXML.java
27,6 → 27,7
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.text.DateFormat;
64,6 → 65,11
return TEMPLATE_ID;
}
 
@Override
public String getStoragePathP() {
return "Journaux";
}
 
Date date;
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteRowValuesRenderer.java
15,10 → 15,10
 
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTableEvent;
import org.openconcerto.sql.model.SQLTableModifiedListener;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.ui.table.AlternateTableCellRenderer;
import org.openconcerto.ui.table.TableCellRendererUtils;
import org.openconcerto.utils.CollectionUtils;
 
import java.awt.Color;
38,26 → 38,27
private static final Color orangeGrey = new Color(255, 160, 110);
private static final Color orangeLight = new Color(255, 201, 168);
private boolean createAutoActive = false;
private Map<String, Boolean> cache = new HashMap<String, Boolean>();
 
private static Map<String, Boolean> cache = new HashMap<String, Boolean>();
static {
final Thread th = new Thread(new Runnable() {
 
static {
Configuration.getInstance().getDirectory().getElement("COMPTE_PCE").getTable().addTableModifiedListener(new SQLTableModifiedListener() {
@Override
public void tableModified(SQLTableEvent evt) {
if (evt != null && evt.getMode() == SQLTableEvent.Mode.ROW_ADDED) {
final SQLRow row = evt.getRow();
if (row != null) {
cache.put(row.getString("NUMERO"), Boolean.TRUE);
public void run() {
final SQLTable table = Configuration.getInstance().getDirectory().getElement("COMPTE_PCE").getTable();
SQLBackgroundTableCache.getInstance().add(table, 3600);
// Force preload
SQLBackgroundTableCache.getInstance().getCacheForTable(table);
 
}
}
}
});
th.setDaemon(true);
th.setPriority(Thread.MIN_PRIORITY);
th.start();
}
 
public CompteRowValuesRenderer() {
super();
cache.clear();
AlternateTableCellRenderer.setBGColorMap(this, CollectionUtils.createMap(orange, orangeGrey, red, redLightGrey));
}
 
64,16 → 65,15
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
 
if (value.getClass() == String.class) {
if (value != null) {
if (column == 0) {
boolean exist;
if (cache.get(value.toString()) == null) {
exist = ComptePCESQLElement.isExist(value.toString());
cache.put(value.toString(), exist);
TableCellRendererUtils.setColors(comp, table, isSelected);
if (column == 0 && value != null && value instanceof String) {
final String account = (String) value;
final boolean exist;
if (cache.get(account) == null) {
exist = ComptePCESQLElement.isExist(account);
cache.put(account, exist);
} else {
exist = cache.get(value.toString());
exist = cache.get(account);
}
if (!exist) {
if (!isSelected) {
91,16 → 91,7
}
comp.setForeground(Color.WHITE);
}
 
}
}
}
 
// TableCellEditor cellEditor = table.getColumnModel().getColumn(column).getCellEditor();
// cellEditor.addCellEditorListener(this);
//
// jumpToNextEditCell(table, hasFocus, isSelected, row, column);
 
return comp;
}
 
108,15 → 99,4
this.createAutoActive = b;
}
 
// @Override
// public void editingCanceled(ChangeEvent e) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void editingStopped(ChangeEvent e) {
// // TODO Auto-generated method stub
// setEditingMode(true);
// }
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieKmItemTable.java
52,6 → 52,8
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class SaisieKmItemTable extends JPanel implements MouseListener {
 
148,18 → 150,20
this.credit.setRenderer(this.deviseRenderer);
 
this.table.addMouseListener(this);
this.table.getModel().addTableModelListener(new TableModelListener() {
 
// numeroCompteRenderer.setMapValue(0, 3);
// numeroCompteRenderer.setMapValue(1, 3);
// numeroCompteRenderer.setMapValue(2, 3);
// deviseRenderer.setMapValue(3, 4);
// deviseRenderer.setMapValue(4, 0);
// deviseRenderer.addcolumnNextRow(3);
// deviseRenderer.addcolumnNextRow(4);
@Override
public void tableChanged(TableModelEvent e) {
// Sélectionne automatiquement la ligne ajoutée
if (e.getType() == TableModelEvent.INSERT) {
editCellAt(e.getFirstRow(), 0);
}
 
// this.deviseCellEditor.addKeyListener(this);
}
});
 
}
 
/**
* Charge une ecriture dans une ligne de la RowValuesTable
*
201,7 → 205,7
final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
final SQLTable ecrTable = base.getTable("ECRITURE");
 
final SQLSelect selEcriture = new SQLSelect(base);
final SQLSelect selEcriture = new SQLSelect();
selEcriture.addSelectStar(ecrTable);
 
final Where w = new Where(ecrTable.getField("ID_MOUVEMENT"), "=", idMvt);
216,8 → 220,6
for (SQLRow sqlRow : myListEcriture) {
loadEcriture(sqlRow, contrePasser);
}
// System.err.println("SaisieKmItemTable.loadMouvement() " + this.table.getRowCount());
// this.table.repaint();
this.table.getRowValuesTableModel().fireTableDataChanged();
}
 
262,21 → 264,6
this.table.editCellAt(row, column);
}
 
public void mouseClicked(final MouseEvent e) {
// TODO Auto-generated method stub
 
}
 
public void mouseEntered(final MouseEvent e) {
// TODO Auto-generated method stub
 
}
 
public void mouseExited(final MouseEvent e) {
// TODO Auto-generated method stub
 
}
 
private long getContrepartie() {
long totalCred = 0;
long totalDeb = 0;
324,7 → 311,6
public void mousePressed(final MouseEvent e) {
final int rowSel = this.table.getSelectedRow();
if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) {
System.err.println("Display Menu");
final JPopupMenu menuDroit = new JPopupMenu();
 
menuDroit.add(new AbstractAction("Contrepartie") {
351,8 → 337,14
}
 
public void mouseReleased(final MouseEvent e) {
// TODO Auto-generated method stub
}
 
public void mouseClicked(final MouseEvent e) {
}
 
public void mouseEntered(final MouseEvent e) {
}
 
public void mouseExited(final MouseEvent e) {
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/LettragePanel.java
428,10 → 428,10
SQLRow rowEcr = LettragePanel.this.ecriturePanel.getListe().getSelectedRow();
MouvementSQLElement.showSource(rowEcr.getInt("ID_MOUVEMENT"));
}
});
}, "financing.accouning.entries.source.show");
 
// if (this.codeLettrage.getText().trim().length() != 0) {
final AbstractAction abstractAction = new AbstractAction("Lettrer") {
final AbstractAction abstractAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
 
int[] rowIndex = LettragePanel.this.ecriturePanel.getListe().getJTable().getSelectedRows();
438,7 → 438,7
actionLettrage(rowIndex);
}
};
this.ecriturePanel.getListe().addRowAction(abstractAction);
this.ecriturePanel.getListe().addRowAction(abstractAction, "financing.accouning.entries.match");
// }
this.codeLettrage.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
453,7 → 453,7
int[] rowIndex = LettragePanel.this.ecriturePanel.getListe().getJTable().getSelectedRows();
actionDelettrage(rowIndex);
}
});
}, "financing.accouning.entries.unmatch");
 
// menu.show(mE.getComponent(), mE.getPoint().x, mE.getPoint().y);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ListeGestCommEltPanel.java
46,6 → 46,13
this.setOpaque(false);
}
 
public ListeGestCommEltPanel(SQLElement elem, IListe l, String variant) {
// TODO verifier que l'element contient la clef etrangere ID_MOUVEMENT
super(elem, l, variant);
this.setAddVisible(false);
this.setOpaque(false);
}
 
public ListeGestCommEltPanel(SQLElement elem, boolean showAdd) {
this(elem, showAdd, null, null);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/action/ListeDesRelancesAction.java
14,6 → 14,7
package org.openconcerto.erp.core.finance.payment.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.generationDoc.gestcomm.FicheRelanceSheet;
import org.openconcerto.erp.generationDoc.gestcomm.RelanceSheet;
21,6 → 22,7
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
31,6 → 33,7
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
162,7 → 165,6
}
}
});
 
menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/component/ModeDeReglementSQLComponent.java
388,7 → 388,7
 
setEcheanceEnabled(!vals.getBoolean("COMPTANT"), vals.getInt("ID_TYPE_REGLEMENT"));
super.select(rVals);
if (rVals.getInt("LENJOUR") != 0 && rVals.getInt("LENJOUR") != 31) {
if (rVals.getObject("LENJOUR") != null && rVals.getInt("LENJOUR") != 0 && rVals.getInt("LENJOUR") != 31) {
this.buttonLe.setSelected(true);
}
this.checkboxComptant.addItemListener(this.listenerComptant);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueSQLComponent.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CaisseCotisationSQLElement.java
113,7 → 113,7
c.gridx = 0;
panelInfos.add(sep, c);
 
this.addView("ID_ADRESSE", REQ + ";" + DEC + ";" + SEP);
this.addView("ID_ADRESSE_COMMON", REQ + ";" + DEC + ";" + SEP);
ElementSQLObject eltAdr = (ElementSQLObject) this.getView("ID_ADRESSE_COMMON");
c.gridy++;
c.gridx = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/element/BonDeLivraisonSQLElement.java
23,6 → 23,7
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
106,8 → 107,11
*
* @param blID
*/
public void transfertFacture(int blID) {
public void transfertFacture(List<SQLRowAccessor> rowsBL) {
 
// MAYBE check if all rows have the same customer
if (rowsBL != null && rowsBL.size() > 0) {
 
SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
EditFrame editFactureFrame = new EditFrame(elt);
editFactureFrame.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage());
115,11 → 119,30
SaisieVenteFactureSQLComponent comp = (SaisieVenteFactureSQLComponent) editFactureFrame.getSQLComponent();
 
comp.setDefaults();
comp.loadBonItems(blID);
 
SQLRowAccessor rowBL = rowsBL.get(0);
SQLRowValues rowVals = new SQLRowValues(elt.getTable());
rowVals.put("ID_CLIENT", rowBL.getForeign("ID_CLIENT").getID());
rowVals.put("NOM", rowBL.getObject("NOM"));
rowVals.put("INFOS", rowBL.getObject("INFOS"));
rowVals.put("IDSOURCE", rowBL.getObject("ID"));
rowVals.put("SOURCE", getTable().getName());
 
comp.select(rowVals);
comp.loadBonItems(rowBL, true);
 
for (int i = 1; i < rowsBL.size(); i++) {
SQLRowAccessor row = rowsBL.get(i);
rowVals.put("NOM", rowVals.getString("NOM") + "\n" + row.getObject("NOM"));
rowVals.put("INFOS", rowVals.getString("INFOS") + "\n" + row.getObject("INFOS"));
comp.loadBonItems(row, false);
}
 
editFactureFrame.pack();
editFactureFrame.setState(JFrame.NORMAL);
editFactureFrame.setVisible(true);
}
}
 
@Override
protected void archive(SQLRow row, boolean cutLinks) throws SQLException {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/action/ListeDesBonsDeLivraisonAction.java
19,7 → 19,7
import org.openconcerto.erp.core.sales.shipment.ui.BonLivraisionRenderer;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
75,12 → 75,12
edit1.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(BonLivraisonXmlSheet.class) {
@Override
public List<RowAction> addToMenu() {
PredicateRowAction actionTransfertFacture = new PredicateRowAction(new AbstractAction("Transfert en facture") {
PredicateRowAction actionTransfertFacture = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent ev) {
transfertFactureClient(IListe.get(ev).getSelectedRow());
transfertFactureClient(IListe.get(ev).getSelectedRows());
}
}, false);
actionTransfertFacture.setPredicate(IListeEvent.getSingleSelectionPredicate());
}, false, "sales.shipment.create.invoice");
actionTransfertFacture.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
List<RowAction> l = new ArrayList<RowAction>();
l.add(actionTransfertFacture);
 
96,8 → 96,8
*
* @param row
*/
private void transfertFactureClient(SQLRow row) {
private void transfertFactureClient(List<SQLRowAccessor> rows) {
BonDeLivraisonSQLElement elt = (BonDeLivraisonSQLElement) Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
elt.transfertFacture(row.getID());
elt.transfertFacture(rows);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/ui/BonDeLivraisonItemTable.java
15,17 → 15,16
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.erp.core.common.ui.DeviseCellEditor;
import org.openconcerto.erp.core.common.ui.DeviseNiceTableCellRenderer;
import org.openconcerto.erp.core.common.ui.DeviseNumericCellEditor;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ArticleRowValuesRenderer;
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import org.openconcerto.erp.model.PrixHT;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
42,6 → 41,7
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
146,18 → 146,22
 
list.add(tableElement_ValeurMetrique1);
// Prix de vente HT de la métrique 1
final SQLTableElement tableElement_PrixMetrique1_VenteHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_VT_1"), Long.class, new DeviseCellEditor()) {
@Override
public TableCellRenderer getTableCellRenderer() {
 
List<Integer> l = new ArrayList<Integer>();
l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_CARRE));
l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_LARGEUR));
l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_LONGUEUR));
l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_POID_METRECARRE));
return new ArticleRowValuesRenderer(l);
}
};
SQLField field = e.getTable().getField("PRIX_METRIQUE_VT_1");
final DeviseNumericCellEditor editorPVHT = new DeviseNumericCellEditor(field);
editorPVHT.setConvertToTTCEnable(true);
final SQLTableElement tableElement_PrixMetrique1_VenteHT = new SQLTableElement(field, BigDecimal.class, editorPVHT);
// {
// @Override
// public TableCellRenderer getTableCellRenderer() {
//
// List<Integer> l = new ArrayList<Integer>();
// l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_CARRE));
// l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_LARGEUR));
// l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_METRE_LONGUEUR));
// l.add(Integer.valueOf(ReferenceArticleSQLElement.AU_POID_METRECARRE));
// return new ArticleRowValuesRenderer(l);
// }
// };
list.add(tableElement_PrixMetrique1_VenteHT);
// Prix d'achat HT de la métrique 1
// final SQLTableElement tableElement_PrixMetrique1_AchatHT = new
188,6 → 192,10
}
}
 
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
211,14 → 219,15
// SQLTableElement(e.getTable().getField("PA_HT"), Long.class, new DeviseCellEditor());
// list.add(tableElement_PrixAchat_HT);
// Prix de vente unitaire HT
final SQLTableElement tableElement_PrixVente_HT = new SQLTableElement(e.getTable().getField("PV_HT"), Long.class, new DeviseCellEditor()) {
@Override
public TableCellRenderer getTableCellRenderer() {
List<Integer> l = new ArrayList<Integer>();
l.add(Integer.valueOf(ReferenceArticleSQLElement.A_LA_PIECE));
return new ArticleRowValuesRenderer(l);
}
};
final SQLTableElement tableElement_PrixVente_HT = new SQLTableElement(e.getTable().getField("PV_HT"), BigDecimal.class);
// , new DeviseCellEditor()) {
// @Override
// public TableCellRenderer getTableCellRenderer() {
// List<Integer> l = new ArrayList<Integer>();
// l.add(Integer.valueOf(ReferenceArticleSQLElement.A_LA_PIECE));
// return new ArticleRowValuesRenderer(l);
// }
// };
list.add(tableElement_PrixVente_HT);
 
// TVA
245,12 → 254,10
// this.service = new SQLTableElement(e.getTable().getField("SERVICE"), Boolean.class);
// list.add(this.service);
// Total HT
this.totalHT = new SQLTableElement(e.getTable().getField("T_PV_HT"), Long.class, new DeviseCellEditor());
this.totalHT.setRenderer(new DeviseNiceTableCellRenderer());
this.totalHT = new SQLTableElement(e.getTable().getField("T_PV_HT"), BigDecimal.class);
list.add(this.totalHT);
// Total TTC
this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PV_TTC"), Long.class, new DeviseCellEditor());
this.tableElementTotalTTC.setRenderer(new DeviseNiceTableCellRenderer());
this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PV_TTC"), BigDecimal.class);
list.add(this.tableElementTotalTTC);
 
model = new RowValuesTableModel(e, list, e.getTable().getField("NOM"));
335,11 → 342,11
public Object computeValueFrom(final SQLRowValues row) {
System.out.println("Compute totalHT");
int qte = Integer.parseInt(row.getObject("QTE").toString());
Number f = (Number) row.getObject("PV_HT");
BigDecimal f = (BigDecimal) row.getObject("PV_HT");
System.out.println("Qte:" + qte + " et PV_HT:" + f);
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
long r = b.multiply(new BigDecimal(f.longValue() * qte), MathContext.DECIMAL128).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
return new Long(r);
BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte)), MathContext.DECIMAL128).setScale(6, BigDecimal.ROUND_HALF_UP);
return r;
}
 
});
352,14 → 359,16
@Override
public Object computeValueFrom(SQLRowValues row) {
 
Number f = (Number) row.getObject("T_PV_HT");
BigDecimal f = (BigDecimal) row.getObject("T_PV_HT");
int idTaux = Integer.parseInt(row.getObject("ID_TAXE").toString());
 
Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
 
PrixHT pHT = new PrixHT(f.longValue());
// PrixHT pHT = new PrixHT(f.longValue());
float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
Long r = new Long(pHT.calculLongTTC(taux / 100f));
// Long r = new Long(pHT.calculLongTTC(taux / 100f));
 
BigDecimal r = f.multiply(BigDecimal.ONE.add(BigDecimal.valueOf(taux).movePointLeft(2)), MathContext.DECIMAL128).setScale(6, BigDecimal.ROUND_HALF_UP);
return r;
}
 
418,12 → 427,12
public Object computeValueFrom(SQLRowValues row) {
if (row.getInt("ID_MODE_VENTE_ARTICLE") == ReferenceArticleSQLElement.A_LA_PIECE) {
System.err.println("Don't computeValue PV_HT --> " + row.getObject("PV_HT") + row);
return new Long(((Number) row.getObject("PRIX_METRIQUE_VT_1")).longValue());
return row.getObject("PRIX_METRIQUE_VT_1");
} else {
 
final long prixVTFromDetails = ReferenceArticleSQLElement.getPrixVTFromDetails(row);
final BigDecimal prixVTFromDetails = ReferenceArticleSQLElement.getPrixVTFromDetails(row);
System.out.println("Prix de vente calculé au détail:" + prixVTFromDetails);
return new Long(prixVTFromDetails);
return prixVTFromDetails.setScale(tableElement_PrixVente_HT.getDecimalDigits(), RoundingMode.HALF_UP);
}
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/element/AvoirClientSQLElement.java
20,8 → 20,10
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ListSQLRequest;
 
import java.sql.SQLException;
import java.util.ArrayList;
80,6 → 82,17
}
 
@Override
public synchronized ListSQLRequest createListRequest() {
return new ListSQLRequest(this.getTable(), this.getListFields()) {
@Override
protected void customizeToFetch(SQLRowValues graphToFetch) {
super.customizeToFetch(graphToFetch);
graphToFetch.put("A_DEDUIRE", null);
}
};
}
 
@Override
protected void archive(SQLRow row, boolean cutLinks) throws SQLException {
 
super.archive(row, cutLinks);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/component/AvoirClientSQLComponent.java
500,13 → 500,14
cFrais.weighty = 1;
cFrais.gridx = 1;
 
// FIXME implémenter la remise et les port pour les avoirs
JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
cFrais.gridy++;
panelPortEtRemise.add(labelPortHT, cFrais);
// panelPortEtRemise.add(labelPortHT, cFrais);
cFrais.gridx++;
DefaultGridBagConstraints.lockMinimumSize(textPortHT);
panelPortEtRemise.add(textPortHT, cFrais);
// panelPortEtRemise.add(textPortHT, cFrais);
 
// Remise
JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
513,10 → 514,10
labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
cFrais.gridy++;
cFrais.gridx = 1;
panelPortEtRemise.add(labelRemiseHT, cFrais);
// panelPortEtRemise.add(labelRemiseHT, cFrais);
cFrais.gridx++;
DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
panelPortEtRemise.add(textRemiseHT, cFrais);
// panelPortEtRemise.add(textRemiseHT, cFrais);
cFrais.gridy++;
 
c.gridx++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientSQLElement.java
17,9 → 17,9
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.core.sales.order.component.CommandeClientSQLComponent;
import org.openconcerto.erp.core.sales.order.ui.CommandeClientRenderer;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
30,8 → 30,13
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.cc.IClosure;
 
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
39,6 → 44,7
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.table.TableColumn;
 
public class CommandeClientSQLElement extends ComptaSQLConfElement {
 
89,6 → 95,25
return s;
}
 
@Override
protected SQLTableModelSourceOnline createTableSource() {
SQLTableModelSourceOnline source = super.createTableSource();
 
final CommandeClientRenderer rend = CommandeClientRenderer.getInstance();
 
for (SQLTableModelColumn col : source.getColumns()) {
col.setColumnInstaller(new IClosure<TableColumn>() {
 
@Override
public void executeChecked(TableColumn input) {
input.setCellRenderer(rend);
 
}
});
}
return source;
}
 
/*
* (non-Javadoc)
*
182,12 → 207,14
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", rowValsElt.getLong("PA_HT") * rowValsElt.getInt("QTE"));
rowValsElt.put("T_PA_TTC", rowValsElt.getLong("T_PA_HT") * (rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0));
 
rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), MathContext.DECIMAL128));
rowValsElt.put("T_PA_TTC",
((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)), MathContext.DECIMAL128));
 
map.put(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
 
}
MouvementStockSQLElement.createCommandeF(map, rowCmd.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"));
MouvementStockSQLElement.createCommandeF(map, rowCmd.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"), rowCmd.getString("NUMERO") + " - " + rowCmd.getString("NOM"));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesCommandesClientAction.java
New file
0,0 → 1,156
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.order.action;
 
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.core.sales.order.ui.CommandeClientRenderer;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
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.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class ListeDesCommandesClientAction extends CreateFrameAbstractAction {
 
public ListeDesCommandesClientAction() {
super();
this.putValue(Action.NAME, "Liste des commandes clients");
}
 
public JFrame createFrame() {
SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
ListeAddPanel listeAddPanel = new ListeAddPanel(eltCmd, new IListe(eltCmd.getTableSource(true))) {
@Override
protected GridBagConstraints createConstraints() {
// TODO Auto-generated method stub
GridBagConstraints c = super.createConstraints();
c.gridy++;
return c;
}
};
 
List<SQLField> fields = new ArrayList<SQLField>(2);
fields.add(eltCmd.getTable().getField("T_HT"));
// fields.add(eltCmd.getTable().getField("T_TTC"));
IListTotalPanel totalPanel = new IListTotalPanel(listeAddPanel.getListe(), fields, "Total Global");
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
c.gridy = 4;
 
listeAddPanel.add(totalPanel, c);
 
// Date panel
IListFilterDatePanel datePanel = new IListFilterDatePanel(listeAddPanel.getListe(), eltCmd.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
listeAddPanel.add(datePanel, c);
 
final IListFrame frame = new IListFrame(listeAddPanel);
 
final CommandeClientRenderer rend = CommandeClientRenderer.getInstance();
c = new DefaultGridBagConstraints();
final JPanel legendePanel = rend.getLegendePanel();
legendePanel.setBorder(BorderFactory.createTitledBorder("Légende"));
legendePanel.setOpaque(true);
c.fill = GridBagConstraints.NONE;
frame.getPanel().add(legendePanel, c);
 
frame.getPanel().getListe().addIListeActions(new MouseSheetXmlListeListener(CommandeClientXmlSheet.class) {
@Override
public List<RowAction> addToMenu() {
// Transfert vers facture
PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
transfertBonLivraisonClient(IListe.get(e).getSelectedRow());
}
}, false, "sales.order.create.deliverynote");
 
// Transfert vers facture
PredicateRowAction factureAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
transfertFactureClient(IListe.get(e).getSelectedRow());
}
}, false, "sales.order.create.invoice");
 
// Transfert vers commande
PredicateRowAction cmdAction = new PredicateRowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
CommandeClientSQLElement elt = (CommandeClientSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
elt.transfertCommande(IListe.get(e).getSelectedId());
}
 
}, false, "sales.order.create.supplier.order");
 
cmdAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
factureAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
List<RowAction> l = new ArrayList<RowAction>();
l.add(bonAction);
l.add(factureAction);
l.add(cmdAction);
return l;
}
}.getRowActions());
 
datePanel.setFilterOnDefault();
 
return frame;
}
 
/**
* Transfert en BL
*
* @param row
*/
private void transfertBonLivraisonClient(SQLRow row) {
CommandeClientSQLElement elt = (CommandeClientSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
elt.transfertBonLivraison(row.getID());
}
 
/**
* Transfert en Facture
*
* @param row
*/
private void transfertFactureClient(SQLRow row) {
CommandeClientSQLElement elt = (CommandeClientSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
elt.transfertFacture(row.getID());
}
}
<
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/ui/CommandeClientRenderer.java
25,19 → 25,23
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.AlternateTableCellRenderer;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.ui.table.TableCellRendererDecorator;
 
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
 
import javax.swing.JComponent;