Dépôt officiel du code source de l'ERP OpenConcerto
/trunk/OpenConcerto/src/org/openconcerto/sql/UserPropsTM.java |
---|
File deleted |
/trunk/OpenConcerto/src/org/openconcerto/sql/Configuration.java |
---|
40,6 → 40,7 |
import java.io.IOException; |
import java.io.StringReader; |
import java.util.List; |
import java.util.Locale; |
import java.util.concurrent.Executor; |
import java.util.concurrent.ExecutorService; |
import java.util.concurrent.Executors; |
208,6 → 209,10 |
return DBItemFileCache.getDescendant(getDBConfDir(), DBFileCache.getJDBCAncestorNames(db, true)); |
} |
public Locale getLocale() { |
return Locale.getDefault(); |
} |
/** |
* Add the directory of <code>o</code> to this. |
* |
/trunk/OpenConcerto/src/org/openconcerto/sql/request/BaseFillSQLRequest.java |
---|
14,7 → 14,6 |
package org.openconcerto.sql.request; |
import org.openconcerto.sql.FieldExpander; |
import org.openconcerto.sql.TM; |
import org.openconcerto.sql.model.FieldRef; |
import org.openconcerto.sql.model.IFieldPath; |
import org.openconcerto.sql.model.OrderComparator; |
614,7 → 613,9 |
if (type.getJavaType() == String.class) { |
return Collections.singletonList(selF.getFieldRef()); |
} else if (type.getJavaType() == Boolean.class) { |
return Collections.singletonList("case when " + selF.getFieldRef() + " then " + syntax.quoteString(TM.tr("true_key")) + " else " + syntax.quoteString(TM.tr("false_key")) + " end"); |
final org.openconcerto.utils.i18n.TM utilsTM = org.openconcerto.utils.i18n.TM.getInstance(l); |
return Collections.singletonList( |
"case when " + selF.getFieldRef() + " then " + syntax.quoteString(utilsTM.translate("true_key")) + " else " + syntax.quoteString(utilsTM.translate("false_key")) + " end"); |
} else if (Timestamp.class.isAssignableFrom(type.getJavaType())) { |
final String shortFmt = formatTime(selF, DateProp.SHORT_DATETIME_SKELETON, l, syntax); |
final String longFmt = formatTime(selF, DateProp.LONG_DATETIME_SKELETON, l, syntax); |
/trunk/OpenConcerto/src/org/openconcerto/sql/TM.java |
---|
14,6 → 14,7 |
package org.openconcerto.sql; |
import org.openconcerto.sql.preferences.UserProps; |
import org.openconcerto.utils.i18n.TMPool; |
import java.util.Locale; |
23,18 → 24,22 |
* |
* @author Sylvain |
*/ |
public class TM extends UserPropsTM { |
public class TM extends org.openconcerto.utils.i18n.TM { |
static private TM INSTANCE; |
private static final TMPool<TM> POOL = new TMPool<TM>(TM::new); |
// to be called as soon as UserProps has the correct Locale to initialize other translation |
// managers |
static public TM getInstance() { |
if (INSTANCE == null) |
INSTANCE = new TM(); |
return INSTANCE; |
return getInstance(getDefaultLocale()); |
} |
static public TM getInstance(final Locale l) { |
return POOL.get(l); |
} |
static public String tr(final Locale l, final String key, final Object... args) { |
return getInstance(l).translate(key, args); |
} |
// useful for static import |
static public TM getTM() { |
return getInstance(); |
44,14 → 49,7 |
return getInstance().translate(key, args); |
} |
private TM() { |
private TM(final Locale l) { |
super(l); |
} |
@Override |
protected void updateLocale(final UserProps userProps) { |
final Locale locale = userProps.getLocale(); |
this.setLocale(locale); |
org.openconcerto.utils.i18n.TM.getInstance().setLocale(locale); |
org.openconcerto.ui.TM.getInstance().setLocale(locale); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLInjector.java |
---|
25,9 → 25,12 |
import org.openconcerto.utils.cc.ITransformer; |
import java.sql.SQLException; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.HashMap; |
import java.util.HashSet; |
import java.util.List; |
import java.util.Map; |
import java.util.Set; |
186,6 → 189,8 |
} |
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); |
protected void transfertNumberReference(SQLRowAccessor srcRow, SQLRowValues rowVals, final SQLTable tableElementDestination, String refField) { |
SQLPreferences prefs = SQLPreferences.getMemCached(srcRow.getTable().getDBRoot()); |
192,14 → 197,27 |
if (prefs.getBoolean("TransfertRef", true)) { |
String label = rowVals.getString("NOM"); |
if (label != null && label.trim().length() > 0) { |
rowVals.put("NOM", label + ", " + srcRow.getString("NUMERO")); |
final String value = label + ", " + srcRow.getString("NUMERO"); |
List<String> l = StringUtils.fastSplit(value, ','); |
Set<String> s = new HashSet<>(l); |
String nom = ""; |
if (s.size() > 1) { |
for (String string : s) { |
nom += string + ","; |
} |
} else if (s.size() == 1) { |
nom = s.iterator().next(); |
} |
rowVals.put("NOM", nom); |
} else { |
rowVals.put("NOM", srcRow.getString("NUMERO")); |
} |
} else if (prefs.getBoolean("TransfertMultiRef", false)) { |
SQLRowValues rowValsHeader = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(tableElementDestination)); |
// FIXME Style forcé en titre 1 via l'ID |
rowValsHeader.put("ID_STYLE", 3); |
String elementName = StringUtils.firstUp(Configuration.getInstance().getDirectory().getElement(getSource()).getName().getVariant(org.openconcerto.utils.i18n.Grammar.SINGULAR)); |
rowValsHeader.put("NOM", elementName + " N° " + srcRow.getString("NUMERO")); |
rowValsHeader.put("NOM", elementName + "\n N° " + srcRow.getString("NUMERO") + " du " + dateFormat.format(srcRow.getDate("DATE").getTime())); |
rowValsHeader.put(refField, rowVals); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLUpdate.java |
---|
27,6 → 27,20 |
this.where = where; |
} |
public void importValuesFrom(SQLRowAccessor row) { |
SQLField pk = row.getTable().getKey(); |
for (String field : row.getFields()) { |
final SQLField sqlField = row.getTable().getField(field); |
if (!pk.equals(sqlField)) { |
if (sqlField.isForeignKey()) { |
add(sqlField, row.getForeignIDNumber(field)); |
} else { |
add(sqlField, row.getObject(field)); |
} |
} |
} |
} |
public void add(SQLField field, Object value) { |
if (this.table == null) { |
this.table = field.getTable(); |
84,10 → 98,14 |
Object value = this.values.get(i); |
final Class<?> javaType = field.getType().getJavaType(); |
Object str = value; |
if (!javaType.isInstance(value)) { |
str = SQLRowValues.convert(value.getClass(), value, javaType); |
if (value != null) { |
if (!javaType.isInstance(value)) { |
str = SQLRowValues.convert(value.getClass(), value, javaType); |
} |
builder.append(field.getType().toString(str)); |
} else { |
builder.append("null"); |
} |
builder.append(field.getType().toString(str)); |
if (i < stop - 1) { |
builder.append(','); |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLTable.java |
---|
123,6 → 123,7 |
@SuppressWarnings("unchecked") |
public static final Map<String, Number> getUndefIDs(final SQLSchema schema) { |
assert Thread.holdsLock(UNDEFINED_IDs); |
if (!UNDEFINED_IDs.containsKey(schema)) { |
final Map<String, Number> r; |
if (schema.contains(undefTable)) { |
164,6 → 165,14 |
} |
} |
public static final Map<String, Number> getUndefinedIDs(final SQLSchema schema) { |
final Map<String, Number> res; |
synchronized (UNDEFINED_IDs) { |
res = new HashMap<>(getUndefIDs(schema)); |
} |
return Collections.unmodifiableMap(res); |
} |
private static final SQLCreateMoveableTable getCreateUndefTable(SQLSyntax syntax) { |
final SQLCreateMoveableTable createTable = new SQLCreateMoveableTable(syntax, undefTable); |
createTable.addVarCharColumn(UNDEF_TABLE_TABLENAME_FIELD, 250); |
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLInsert.java |
---|
13,11 → 13,15 |
package org.openconcerto.sql.model; |
import org.openconcerto.sql.users.User; |
import java.io.IOException; |
import java.io.StringReader; |
import java.sql.Connection; |
import java.sql.SQLException; |
import java.sql.Timestamp; |
import java.util.ArrayList; |
import java.util.Collections; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
32,6 → 36,28 |
private List<Object> values = new ArrayList<>(); |
private SQLTable table; |
public void importValuesFrom(SQLRowAccessor row) { |
SQLField pk = row.getTable().getKey(); |
for (String field : row.getFields()) { |
final SQLField sqlField = row.getTable().getField(field); |
if (!pk.equals(sqlField)) { |
if (sqlField.isForeignKey()) { |
add(sqlField, row.getForeignIDNumber(field)); |
} else { |
add(sqlField, row.getObject(field)); |
} |
} |
} |
} |
public int getFieldsSize() { |
return this.fields.size(); |
} |
public List<SQLField> getFields() { |
return Collections.unmodifiableList(this.fields); |
} |
public void add(SQLField field, Object value) { |
if (this.table == null) { |
this.table = field.getTable(); |
40,6 → 66,10 |
throw new IllegalArgumentException(field + " is not in table " + this.table.toString()); |
} |
} |
int index = this.fields.indexOf(field); |
if (index >= 0) { |
throw new IllegalArgumentException(field + " field already in list"); |
} |
this.fields.add(field); |
this.values.add(value); |
} |
59,6 → 89,23 |
this.values.set(index, value); |
} |
public void addCreationTrackedField(User u, SQLTable table) { |
Timestamp now = new Timestamp(System.currentTimeMillis()); |
final SQLField creationDateField = table.getCreationDateField(); |
final SQLField creationUserField = table.getCreationUserField(); |
if (creationDateField != null && creationUserField != null) { |
add(creationDateField, now); |
add(creationUserField, u.getId()); |
} |
final SQLField modifDateField = table.getModifDateField(); |
final SQLField modifUserField = table.getModifUserField(); |
if (modifDateField != null && modifUserField != null) { |
add(modifDateField, now); |
add(modifUserField, u.getId()); |
} |
} |
public boolean contains(SQLField field) { |
return this.fields.indexOf(field) >= 0; |
} |
95,11 → 142,15 |
final SQLField field = this.fields.get(i); |
final Class<?> javaType = field.getType().getJavaType(); |
Object str = value; |
if (value != null && !javaType.isInstance(value)) { |
str = SQLRowValues.convert(value.getClass(), value, javaType); |
if (value != null) { |
if (!javaType.isInstance(value)) { |
str = SQLRowValues.convert(value.getClass(), value, javaType); |
} |
builder.append(field.getType().toString(str)); |
} else { |
builder.append("null"); |
} |
builder.append(field.getType().toString(str)); |
if (i < stop - 1) { |
builder.append(','); |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/RowValuesTableModel.java |
---|
16,19 → 16,23 |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.model.Constraint; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLInsert; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.SQLRowListRSH; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode; |
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreResult; |
import org.openconcerto.sql.model.SQLSelect; |
import org.openconcerto.sql.model.SQLSyntax.ConstraintType; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.SQLUpdate; |
import org.openconcerto.sql.model.UndefinedRowValuesCache; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.utils.AlterTable; |
import org.openconcerto.utils.CompareUtils; |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.ListMap; |
import org.openconcerto.utils.OrderedSet; |
import java.math.BigDecimal; |
283,6 → 287,13 |
* Valider les modifications dans la base |
*/ |
public void commitData() { |
commitData(false); |
} |
/** |
* Valider les modifications dans la base |
*/ |
public void commitData(boolean useMultipleInsertUpdate) { |
checkEDT(); |
final List<SQLRowValues> rowsToCommmit = new ArrayList<SQLRowValues>(); |
rowsToCommmit.addAll(this.rowValues); |
296,17 → 307,63 |
table.fetchFields(); |
table.getSchema().updateVersion(); |
} |
BigDecimal o = table.getMaxOrder(Boolean.FALSE); |
final int size = rowsToCommmit.size(); |
for (int i = 0; i < size; i++) { |
final SQLRowValues r = rowsToCommmit.get(i); |
r.put(r.getTable().getOrderField().getFieldName(), o.add(new BigDecimal(i + 1))); |
final SQLRow row = r.getGraph().store(StoreMode.COMMIT).getStoredRow(r); |
r.setID(row.getIDNumber()); |
if (useMultipleInsertUpdate) { |
List<SQLUpdate> updates = new ArrayList<>(); |
ListMap<List<SQLField>, SQLInsert> mapInsertByFields = new ListMap<>(); |
ListMap<List<SQLField>, SQLRowValues> mapInsertRowValues = new ListMap<>(); |
for (int i = 0; i < size; i++) { |
final SQLRowValues r = rowsToCommmit.get(i); |
r.put(r.getTable().getOrderField().getFieldName(), o.add(new BigDecimal(i + 1))); |
if (r.hasID()) { |
SQLUpdate up = new SQLUpdate(new Where(table.getKey(), "=", r.getID())); |
up.importValuesFrom(r); |
updates.add(up); |
} else { |
SQLInsert insert = new SQLInsert(); |
insert.importValuesFrom(r); |
List<SQLField> fields = insert.getFields(); |
mapInsertByFields.add(fields, insert); |
mapInsertRowValues.add(fields, r); |
} |
} |
if (!mapInsertByFields.isEmpty()) { |
for (List<SQLField> fieldSize : mapInsertByFields.keySet()) { |
List<Number> ids = SQLInsert.executeSimilarInserts(table.getDBSystemRoot(), mapInsertByFields.get(fieldSize), true); |
List<SQLRowValues> insertsRowValues = mapInsertRowValues.get(fieldSize); |
if (ids.size() == insertsRowValues.size()) { |
for (int i = 0; i < ids.size(); i++) { |
final SQLRowValues r = insertsRowValues.get(i); |
r.setID(ids.get(i)); |
} |
} |
} |
} |
if (!updates.isEmpty()) { |
SQLUpdate.executeMultipleWithBatch(table.getDBSystemRoot(), updates); |
} |
table.fireTableModified(-1); |
} else { |
for (int i = 0; i < size; i++) { |
final SQLRowValues r = rowsToCommmit.get(i); |
r.put(r.getTable().getOrderField().getFieldName(), o.add(new BigDecimal(i + 1))); |
final StoreResult store = r.getGraph().store(StoreMode.COMMIT, false); |
final SQLRow row = store.getStoredRow(r); |
r.setID(row.getIDNumber()); |
} |
} |
} catch (SQLException e) { |
ExceptionHandler.handle("Unable to commit rows", e); |
} |
} |
public void addTableModelListener(TableModelListener l) { |
600,7 → 657,7 |
final List<SQLRowValues> newRows = new ArrayList<SQLRowValues>(); |
if (rowVals.getID() > 1) { |
if (rowVals.hasID() && !rowVals.isUndefined() && rowVals.getID() != SQLRow.NONEXISTANT_ID) { |
SQLRow row = rowVals.getTable().getRow(rowVals.getID()); |
List<SQLRow> rowSet; |
if (referentField == null) { |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/RowValuesTableControlPanel.java |
---|
195,7 → 195,11 |
for (String elt : this.table.getClearCloneTableElement()) { |
if (rowValsBis.getTable().getFieldsName().contains(elt)) { |
rowValsBis.putEmptyLink(elt); |
if (rowValsBis.getTable().getField(elt).isKey()) { |
rowValsBis.putEmptyLink(elt); |
} else { |
rowValsBis.put(elt, this.model.getDefaultRowValues().getObject(elt)); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/ITableModel.java |
---|
47,7 → 47,7 |
import java.util.Timer; |
import java.util.TimerTask; |
import java.util.concurrent.Future; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.RunnableFuture; |
import java.util.concurrent.TimeUnit; |
import java.util.concurrent.TimeoutException; |
import java.util.concurrent.atomic.AtomicInteger; |
198,7 → 198,7 |
@Override |
public void propertyChange(final PropertyChangeEvent evt) { |
if (evt.getPropertyName().equals("beingRun")) { |
final boolean isLoading = UpdateQueue.isUpdate((FutureTask<?>) evt.getNewValue()); |
final boolean isLoading = UpdateQueue.isUpdate((RunnableFuture<?>) evt.getNewValue()); |
SwingUtilities.invokeLater(new Runnable() { |
@Override |
public void run() { |
222,7 → 222,7 |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
if (evt.getPropertyName().equals("beingRun")) { |
final boolean isSearching = SearchQueue.isSearch((FutureTask<?>) evt.getNewValue()); |
final boolean isSearching = SearchQueue.isSearch((RunnableFuture<?>) evt.getNewValue()); |
SwingUtilities.invokeLater(new Runnable() { |
@Override |
public void run() { |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/search/SearchQueue.java |
---|
30,7 → 30,7 |
import java.util.Collection; |
import java.util.Deque; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.RunnableFuture; |
import javax.swing.SwingUtilities; |
45,12 → 45,12 |
* @param f a task in this queue, can be <code>null</code>. |
* @return <code>true</code> if <code>f</code> searches. |
*/ |
public static boolean isSearch(final FutureTask<?> f) { |
public static boolean isSearch(final RunnableFuture<?> f) { |
final Runnable r = getRunnable(f); |
return r instanceof SearchRunnable && ((SearchRunnable) r).performsSearch(); |
} |
public static Runnable getRunnable(final FutureTask<?> f) { |
public static Runnable getRunnable(final RunnableFuture<?> f) { |
if (f instanceof IFutureTask) |
return ((IFutureTask<?>) f).getRunnable(); |
else |
75,7 → 75,7 |
SearchSpec search; |
private final ListAccess listAccess; |
// thread-safe |
private final IClosure<Deque<FutureTask<?>>> cancelClosure; |
private final IClosure<Deque<RunnableFuture<?>>> cancelClosure; |
public SearchQueue(final ListAccess la) { |
super(SearchQueue.class.getName() + " on " + la.getModel()); |
82,9 → 82,9 |
this.listAccess = la; |
this.model = la.getModel(); |
this.search = null; |
this.cancelClosure = UpdateQueue.createCancelClosure(this, new ITransformer<FutureTask<?>, TaskType>() { |
this.cancelClosure = UpdateQueue.createCancelClosure(this, new ITransformer<RunnableFuture<?>, TaskType>() { |
@Override |
public TaskType transformChecked(FutureTask<?> input) { |
public TaskType transformChecked(RunnableFuture<?> input) { |
final Runnable r = getRunnable(input); |
if (r instanceof SearchRunnable) |
return TaskType.COMPUTE; |
137,9 → 137,9 |
// couldn't cancel it. |
// use tasksDo() so that no other runnable can come between setSearch and searchAll. |
// Otherwise a runnable might the new search query but not the new filtered list. |
this.tasksDo(new IClosure<Deque<FutureTask<?>>>() { |
this.tasksDo(new IClosure<Deque<RunnableFuture<?>>>() { |
@Override |
public void executeChecked(Deque<FutureTask<?>> input) { |
public void executeChecked(Deque<RunnableFuture<?>> input) { |
put(new SetStateRunnable() { |
@Override |
public void run() { |
164,7 → 164,7 |
} |
@Override |
protected void willPut(final FutureTask<?> qr) throws InterruptedException { |
protected void willPut(final RunnableFuture<?> qr) throws InterruptedException { |
if (getRunnable(qr) instanceof SearchAll) { |
// si on recherche tout, ne sert à rien de garder les recherches précédentes. |
this.tasksDo(this.cancelClosure); |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/SQLTableModelLinesSourceOffline.java |
---|
300,7 → 300,7 |
// *** Modify virtual rows *** |
private final <T> Future<T> execInUpdateQ(final OfflineCallable<T> call) { |
return this.getModel().getUpdateQ().execute(new FutureTask<T>(call)); |
return this.getModel().getUpdateQ().add(new FutureTask<T>(call)); |
} |
public final Future<Number> add(final SQLRowValues vals) { |
/trunk/OpenConcerto/src/org/openconcerto/sql/view/list/UpdateQueue.java |
---|
46,7 → 46,7 |
import java.util.Iterator; |
import java.util.List; |
import java.util.Set; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.RunnableFuture; |
import java.util.logging.Level; |
import net.jcip.annotations.GuardedBy; |
59,7 → 59,7 |
* @param f a task in this queue, can be <code>null</code>. |
* @return <code>true</code> if <code>f</code> loads from the db. |
*/ |
static boolean isUpdate(FutureTask<?> f) { |
static boolean isUpdate(RunnableFuture<?> f) { |
return isUpdate(SearchQueue.getRunnable(f)); |
} |
103,15 → 103,15 |
// TODO rm : needed for now since our optimizations are false if there's a where not on the |
// primary table, see http://192.168.1.10:3000/issues/show/22 |
private boolean alwaysUpdateAll = false; |
private final IClosure<Deque<FutureTask<?>>> cancelClosure; |
private final IClosure<Deque<RunnableFuture<?>>> cancelClosure; |
public UpdateQueue(ITableModel model) { |
super(UpdateQueue.class.getSimpleName() + " on " + model); |
this.tableModel = model; |
this.fullList = new ArrayList<ListSQLLine>(); |
this.cancelClosure = createCancelClosure(this, new ITransformer<FutureTask<?>, TaskType>() { |
this.cancelClosure = createCancelClosure(this, new ITransformer<RunnableFuture<?>, TaskType>() { |
@Override |
public TaskType transformChecked(FutureTask<?> input) { |
public TaskType transformChecked(RunnableFuture<?> input) { |
final Runnable r = SearchQueue.getRunnable(input); |
if (isCancelableUpdate(r)) |
return TaskType.COMPUTE; |
377,9 → 377,9 |
// use tasksDo() so that no other runnable can come between setState and updateAll. |
// Otherwise an updateOne might use new columns and add a line with different columns than |
// the full list. |
this.tasksDo(new IClosure<Deque<FutureTask<?>>>() { |
this.tasksDo(new IClosure<Deque<RunnableFuture<?>>>() { |
@Override |
public void executeChecked(Deque<FutureTask<?>> input) { |
public void executeChecked(Deque<RunnableFuture<?>> input) { |
put(new SetStateRunnable() { |
@Override |
public void run() { |
528,7 → 528,7 |
} |
@Override |
protected void willPut(final FutureTask<?> qr) throws InterruptedException { |
protected void willPut(final RunnableFuture<?> qr) throws InterruptedException { |
if (SearchQueue.getRunnable(qr) instanceof ChangeAllRunnable) { |
// si on met tout à jour, ne sert à rien de garder les maj précédentes. |
this.tasksDo(this.cancelClosure); |
546,16 → 546,16 |
} |
} |
static public final IClosure<Deque<FutureTask<?>>> createCancelClosure(final SleepingQueue q, final ITransformer<? super FutureTask<?>, TaskType> cancelablePred) { |
return new IClosure<Deque<FutureTask<?>>>() { |
static public final IClosure<Deque<RunnableFuture<?>>> createCancelClosure(final SleepingQueue q, final ITransformer<? super RunnableFuture<?>, TaskType> cancelablePred) { |
return new IClosure<Deque<RunnableFuture<?>>>() { |
@Override |
public void executeChecked(final Deque<FutureTask<?>> tasks) { |
public void executeChecked(final Deque<RunnableFuture<?>> tasks) { |
// on part de la fin et on supprime toutes les maj jusqu'a ce qu'on trouve |
// un runnable qui n'est pas annulable |
final Iterator<FutureTask<?>> iter = tasks.descendingIterator(); |
final Iterator<RunnableFuture<?>> iter = tasks.descendingIterator(); |
boolean needsPrevious = false; |
while (iter.hasNext() && !needsPrevious) { |
final FutureTask<?> current = iter.next(); |
final RunnableFuture<?> current = iter.next(); |
final TaskType type = cancelablePred.transformChecked(current); |
needsPrevious = type.dependsOnPrevious; |
if (type.cancelable) |
565,7 → 565,7 |
if (!needsPrevious) { |
// before trying to cancel being run we should have been through all the backlog |
assert !iter.hasNext(); |
final FutureTask<?> br = q.getBeingRun(); |
final RunnableFuture<?> br = q.getBeingRun(); |
if (br != null && cancelablePred.transformChecked(br).cancelable) { |
// might already be done by now, but it's OK cancel() will just return false |
br.cancel(true); |
/trunk/OpenConcerto/src/org/openconcerto/sql/PropsConfiguration.java |
---|
70,6 → 70,7 |
import java.util.List; |
import java.util.ListIterator; |
import java.util.Locale; |
import java.util.Objects; |
import java.util.Properties; |
import java.util.ResourceBundle.Control; |
import java.util.Set; |
209,6 → 210,8 |
private BaseDirs baseDirs; |
@GuardedBy("restLock") |
private File logDir; |
@GuardedBy("restLock") |
private Locale locale = Locale.getDefault(); |
private final boolean inIDE; |
// split sql tree and the rest since creating the tree is costly |
998,7 → 1001,7 |
} |
protected final SQLFieldTranslator loadTranslations(final SQLFieldTranslator trns, final DBRoot root, final List<String> mappings) { |
final Locale locale = TM.getInstance().getTranslationsLocale(); |
final Locale locale = this.getLocale(); |
final Control cntrl = TranslationManager.getControl(); |
boolean found = false; |
// better to have a translation in the correct language than a translation for the correct |
1373,6 → 1376,13 |
} |
} |
@Override |
public Locale getLocale() { |
synchronized (this.restLock) { |
return this.locale; |
} |
} |
// *** setters |
// MAYBE add synchronized (not necessary since they're private, and only called with the lock) |
1397,6 → 1407,24 |
this.wd = dir; |
} |
public void setLocale(Locale locale) { |
Objects.requireNonNull(locale); |
// don't create the directory |
final boolean localeChangedAndDirExists; |
synchronized (this.restLock) { |
if (locale.equals(this.locale)) { |
localeChangedAndDirExists = false; |
} else { |
this.locale = locale; |
localeChangedAndDirExists = this.directory.isComputeStarted(); |
} |
} |
if (localeChangedAndDirExists) { |
final SQLElementDirectory dir = this.getDirectory(); |
dir.setTranslator(createTranslator(dir)); |
} |
} |
public FieldMapper getFieldMapper() { |
return fieldMapper; |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/ConnexionPanel.java |
---|
15,6 → 15,7 |
import static org.openconcerto.sql.TM.getTM; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.PropsConfiguration; |
import org.openconcerto.sql.TM; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLTable; |
56,6 → 57,7 |
import javax.swing.JButton; |
import javax.swing.JCheckBox; |
import javax.swing.JCheckBoxMenuItem; |
import javax.swing.JComponent; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
513,6 → 515,18 |
this.buttonConnect.setText(bundle.getString("buttonConnect")); |
this.langButton.setText(locale.getLanguage()); |
this.langButton.setVisible(true); |
// for next launch |
UserProps.getInstance().setLocale(locale); |
// for current run |
((PropsConfiguration) Configuration.getInstance()).setLocale(locale); |
// for code that will never need more than one Locale concurrently |
// (e.g. used by TM singletons in various packages) |
Locale.setDefault(locale); |
// as explained in Locale.setDefault() javadoc : "be prepared to reinitialize |
// locale-sensitive code" |
JComponent.setDefaultLocale(locale); |
// throw RuntimeException like ResourceBundle.getBundle() at the beginning of this |
// method |
TranslationManager.createDefaultInstance(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/SoftwareInfoPanel.java |
---|
30,6 → 30,7 |
import org.openconcerto.utils.i18n.I18nUtils; |
import java.util.HashMap; |
import java.util.Locale; |
import java.util.Map; |
import javax.swing.JLabel; |
50,15 → 51,15 |
public static final IFactory<String> FACTORY = new IFactory<String>() { |
@Override |
public String createChecked() { |
return get(false).toString(); |
return get(false, Locale.ENGLISH).toString(); |
} |
}; |
public static Map<Info, String> get(final boolean html) { |
public static Map<Info, String> get(final boolean html, final Locale locale) { |
final Map<Info, String> res = new HashMap<Info, String>(); |
final UserRightsManager userRightsManager = UserRightsManager.getInstance(); |
res.put(Info.RIGHTS, org.openconcerto.utils.i18n.TM.tr(I18nUtils.getYesNoKey(userRightsManager != null))); |
res.put(Info.RIGHTS, org.openconcerto.utils.i18n.TM.tr(locale, I18nUtils.getYesNoKey(userRightsManager != null))); |
final User user = UserManager.getUser(); |
if (user != null) { |
final UserRights userRights = UserRightsManager.getCurrentUserRights(); |
78,11 → 79,11 |
final String name, version; |
if (productInfo == null) { |
name = TM.tr("infoPanel.noAppName"); |
version = TM.tr("infoPanel.noVersion"); |
name = TM.tr(locale, "infoPanel.noAppName"); |
version = TM.tr(locale, "infoPanel.noVersion"); |
} else { |
name = productInfo.getName(); |
version = productInfo.getProperty(ProductInfo.VERSION, TM.tr("infoPanel.noVersion")); |
version = productInfo.getProperty(ProductInfo.VERSION, TM.tr(locale, "infoPanel.noVersion")); |
} |
res.put(Info.APP_NAME, name); |
res.put(Info.APP_VERSION, version); |
93,12 → 94,12 |
if (conf != null) |
res.put(Info.DB_URL, conf.getSystemRoot().getDataSource().getUrl()); |
if (conf != null) { |
final String logs = propsConf == null ? "" : " ; " + SystemInfo.getLink(TM.tr("infoPanel.logs"), propsConf.getLogDir().toURI(), html); |
final String logs = propsConf == null ? "" : " ; " + SystemInfo.getLink(TM.tr(locale, "infoPanel.logs"), propsConf.getLogDir().toURI(), html); |
final BaseDirs baseDirs = conf.getBaseDirs(); |
String dirs = " ; " + SystemInfo.getLink(TM.tr("infoPanel.dataDir"), baseDirs.getAppDataFolder().toURI(), html); |
dirs = dirs + " ; " + SystemInfo.getLink(TM.tr("infoPanel.prefsDir"), baseDirs.getPreferencesFolder().toURI(), html); |
dirs = dirs + " ; " + SystemInfo.getLink(TM.tr("infoPanel.cacheDir"), baseDirs.getCacheFolder().toURI(), html); |
res.put(Info.DIRS, SystemInfo.getLink(TM.tr("infoPanel.docs"), conf.getWD().toURI(), html) + logs + dirs); |
String dirs = " ; " + SystemInfo.getLink(TM.tr(locale, "infoPanel.dataDir"), baseDirs.getAppDataFolder().toURI(), html); |
dirs = dirs + " ; " + SystemInfo.getLink(TM.tr(locale, "infoPanel.prefsDir"), baseDirs.getPreferencesFolder().toURI(), html); |
dirs = dirs + " ; " + SystemInfo.getLink(TM.tr(locale, "infoPanel.cacheDir"), baseDirs.getCacheFolder().toURI(), html); |
res.put(Info.DIRS, SystemInfo.getLink(TM.tr(locale, "infoPanel.docs"), conf.getWD().toURI(), html) + logs + dirs); |
} |
return res; |
106,31 → 107,33 |
private final FormLayouter l; |
public SoftwareInfoPanel() { |
public SoftwareInfoPanel(final Locale locale) { |
this.l = new FormLayouter(this, 1); |
this.refresh(); |
this.refresh(locale); |
} |
public final void refresh() { |
public final void refresh(final Locale locale) { |
this.l.clear(); |
final Map<Info, String> infos = get(true); |
this.l.add(TM.tr("infoPanel.rights"), new JLabel(infos.get(Info.RIGHTS))); |
final Map<Info, String> infos = get(true, locale); |
this.l.add(TM.tr(locale, "infoPanel.rights"), new JLabel(infos.get(Info.RIGHTS))); |
final String user = infos.get(Info.USER); |
if (user != null) { |
this.l.add(org.openconcerto.utils.i18n.TM.tr("user"), new JLabel(user)); |
this.l.add(org.openconcerto.utils.i18n.TM.tr(locale, "user"), new JLabel(user)); |
} |
this.l.add(TM.tr("infoPanel.appName"), new JLabel(infos.get(Info.APP_NAME))); |
this.l.add(TM.tr("infoPanel.version"), new JLabel(infos.get(Info.APP_VERSION))); |
this.l.add(TM.tr(locale, "infoPanel.appName"), new JLabel(infos.get(Info.APP_NAME))); |
this.l.add(TM.tr(locale, "infoPanel.version"), new JLabel(infos.get(Info.APP_VERSION))); |
final String secureLink = infos.get(Info.SECURE_LINK); |
if (secureLink != null) { |
this.l.add(TM.tr("infoPanel.secureLink"), new JLabel(secureLink)); |
this.l.add(TM.tr(locale, "infoPanel.secureLink"), new JLabel(secureLink)); |
} |
final JLabel dbURL = new JLabel(infos.get(Info.DB_URL)); |
if (dbURL != null) |
this.l.add(TM.tr("infoPanel.dbURL"), dbURL); |
this.l.add(TM.tr(locale, "infoPanel.dbURL"), dbURL); |
final String dirs = infos.get(Info.DIRS); |
if (dirs != null) |
this.l.add(TM.tr("infoPanel.dirs"), new HTMLTextField(dirs)); |
this.l.add(TM.tr(locale, "infoPanel.dirs"), new HTMLTextField(dirs)); |
this.l.getComponent().revalidate(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/sql/ui/InfoPanel.java |
---|
23,6 → 23,7 |
import java.awt.event.MouseAdapter; |
import java.awt.event.MouseEvent; |
import java.util.Arrays; |
import java.util.Locale; |
import javax.swing.JLabel; |
import javax.swing.JPanel; |
32,25 → 33,28 |
*/ |
public class InfoPanel extends JPanel { |
public InfoPanel() { |
private final Locale locale; |
public InfoPanel(final Locale locale) { |
super(new GridBagLayout()); |
this.locale = locale; |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
c.weightx = 1; |
c.weighty = 1; |
this.add(createTitle("infoPanel.softwareTitle"), c); |
c.gridy++; |
this.add(new SoftwareInfoPanel(), c); |
this.add(new SoftwareInfoPanel(locale), c); |
c.gridy++; |
this.add(createTitle("infoPanel.systemTitle"), c); |
c.gridy++; |
this.add(new SystemInfoPanel(), c); |
this.add(new SystemInfoPanel(locale), c); |
} |
private JLabel createTitle(final String text) { |
final JLabel res = new JLabel(TM.tr(text)); |
final JLabel res = new JLabel(TM.tr(this.locale, text)); |
final Font font = res.getFont(); |
res.setFont(font.deriveFont(font.getSize2D() * 1.2f).deriveFont(Font.BOLD)); |
res.setToolTipText(TM.tr("infoPanel.refresh")); |
res.setToolTipText(TM.tr(this.locale, "infoPanel.refresh")); |
res.addMouseListener(new MouseAdapter() { |
@Override |
public void mouseClicked(MouseEvent e) { |
66,8 → 70,8 |
private final void refresh(final int index) { |
if (index < 0 || index == 1) |
((SoftwareInfoPanel) this.getComponent(1)).refresh(); |
((SoftwareInfoPanel) this.getComponent(1)).refresh(this.locale); |
if (index < 0 || index == 3) |
((SystemInfoPanel) this.getComponent(3)).refresh(); |
((SystemInfoPanel) this.getComponent(3)).refresh(this.locale); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/SetMap.java |
---|
127,7 → 127,7 |
} |
@Override |
public SetMap<K, V> clone() throws CloneNotSupportedException { |
public SetMap<K, V> clone() { |
return (SetMap<K, V>) super.clone(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/net/HTTPClient.java |
---|
New file |
0,0 → 1,175 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.net; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
import java.net.URL; |
import java.nio.charset.StandardCharsets; |
import java.util.Base64; |
import java.util.Set; |
import java.util.zip.GZIPInputStream; |
import java.util.zip.GZIPOutputStream; |
import javax.net.ssl.HttpsURLConnection; |
import javax.net.ssl.SSLSocketFactory; |
public class HTTPClient { |
private static final int MIN_GZIP_SIZE = 64; |
static public class ServerException extends RuntimeException { |
private final int responseCode; |
private final boolean authenticateError; |
protected ServerException(int responseCode, boolean authenticateError) { |
super("Response code was " + responseCode); |
this.responseCode = responseCode; |
this.authenticateError = authenticateError; |
} |
public final int getResponseCode() { |
return this.responseCode; |
} |
public final boolean isAuthenticateError() { |
return this.authenticateError; |
} |
} |
static public final class Response { |
protected final static Response create(HttpsURLConnection con, final Set<Integer> okCodes) throws IOException { |
final boolean success = okCodes == null ? con.getResponseCode() == 200 : okCodes.contains(con.getResponseCode()); |
return new Response(success, con.getResponseCode(), con.getResponseMessage(), con.getContentEncoding(), con.getContentType()); |
} |
private final boolean success; |
private final int code; |
private final String message; |
private final String contentEncoding, contentType; |
protected Response(boolean success, int code, String message, String contentEncoding, String contentType) { |
super(); |
this.success = success; |
this.code = code; |
this.message = message; |
this.contentEncoding = contentEncoding; |
this.contentType = contentType; |
} |
public final int getCode() { |
return this.code; |
} |
public final boolean isSuccess() { |
return this.success; |
} |
public final String getMessage() { |
return this.message; |
} |
public final String getContentEncoding() { |
return this.contentEncoding; |
} |
public final String getContentType() { |
return this.contentType; |
} |
} |
private final String url; |
private SSLSocketFactory socketFactory; |
private String token; |
private boolean throwException = true; |
public HTTPClient(final String url) { |
this.url = url; |
} |
public final SSLSocketFactory getSocketFactory() { |
return this.socketFactory; |
} |
public final void setSocketFactory(SSLSocketFactory socketFactory) { |
this.socketFactory = socketFactory; |
} |
public final void setToken(String token) { |
this.token = token; |
} |
public final boolean hasToken() { |
return this.getToken() != null; |
} |
protected final String getToken() { |
return this.token; |
} |
public final void setThrowException(boolean throwException) { |
this.throwException = throwException; |
} |
public final boolean throwsException() { |
return this.throwException; |
} |
public final Response checkResponseCode(final HttpsURLConnection con) throws IOException { |
return checkResponseCode(con, null); |
} |
public final Response checkResponseCode(final HttpsURLConnection con, final Set<Integer> okCodes) throws IOException { |
final Response res = Response.create(con, okCodes); |
if (this.throwsException() && !res.isSuccess()) |
throw new ServerException(res.getCode(), con.getHeaderField("WWW-Authenticate") != null); |
return res; |
} |
public final HttpsURLConnection openConnection(final String path) throws IOException { |
final HttpsURLConnection con = (HttpsURLConnection) new URL(this.url + path).openConnection(); |
con.setRequestProperty("Accept-Encoding", "gzip"); |
if (this.getSocketFactory() != null) |
con.setSSLSocketFactory(this.getSocketFactory()); |
if (getToken() != null) |
con.setRequestProperty("Authorization", "Bearer " + Base64.getEncoder().encodeToString(getToken().getBytes(StandardCharsets.UTF_8))); |
return con; |
} |
public final InputStream getInputStream(final HttpsURLConnection con) throws IOException { |
return "gzip".equals(con.getContentEncoding()) ? new GZIPInputStream(con.getInputStream()) : con.getInputStream(); |
} |
public final HttpsURLConnection send(final HttpsURLConnection con, final String params) throws IOException { |
return this.send(con, params, true); |
} |
public final HttpsURLConnection send(final HttpsURLConnection con, final String params, final boolean allowGzip) throws IOException { |
return this.send(con, params.getBytes(StandardCharsets.UTF_8), allowGzip); |
} |
public final HttpsURLConnection send(final HttpsURLConnection con, final byte[] toSend, final boolean allowGzip) throws IOException { |
final boolean useGzip = allowGzip && toSend.length >= MIN_GZIP_SIZE; |
if (useGzip) |
con.setRequestProperty("Content-Encoding", "gzip"); |
con.setRequestMethod("POST"); |
con.setDoOutput(true); |
try (final OutputStream o = useGzip ? new GZIPOutputStream(con.getOutputStream()) : con.getOutputStream()) { |
o.write(toSend); |
} |
return con; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ListMap.java |
---|
119,7 → 119,7 |
} |
@Override |
public ListMap<K, V> clone() throws CloneNotSupportedException { |
public ListMap<K, V> clone() { |
return (ListMap<K, V>) super.clone(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/protocol/JavaSourceFromString.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.utils.protocol; |
import java.net.URI; |
import javax.tools.JavaCompiler; |
import javax.tools.SimpleJavaFileObject; |
/** |
* From {@link JavaCompiler} javadoc. |
*/ |
public class JavaSourceFromString extends SimpleJavaFileObject { |
/** |
* The source code of this "file". |
*/ |
private final String code; |
/** |
* Constructs a new JavaSourceFromString. |
* |
* @param name the name of the compilation unit represented by this file object |
* @param code the source code for the compilation unit represented by this file object |
*/ |
JavaSourceFromString(String name, String code) { |
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); |
this.code = code; |
} |
@Override |
public CharSequence getCharContent(boolean ignoreEncodingErrors) { |
return this.code; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/protocol/Helper.java |
---|
26,11 → 26,16 |
static private final PropertyList PL = new PropertyList("java.protocol.handler.pkgs", "|"); |
static final public void register() { |
// works even if setURLStreamHandlerFactory() is called (as long as the factoy returns null |
// Works even if setURLStreamHandlerFactory() is called (as long as the factory returns null |
// for our protocols) |
// On Java 11, there's also URLStreamHandlerProvider |
PL.add(Helper.class.getPackage().getName()); |
} |
static final public void unregister() { |
PL.remove(Helper.class.getPackage().getName()); |
} |
/** |
* Set the {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory) factory} to add our |
* protocols. This is needed for example in web start when one of our url is embedded into a |
59,10 → 64,14 |
* "jar:jarjar:file:/C:/mylibs/Outer.jar^/Inner.jar!/". |
*/ |
public static final URL toJarJar(URL u) { |
return toJarJar(u, ""); |
} |
public static final URL toJarJar(final URL u, final String s) { |
// if it's a jar inside another jar |
if ("jar".equals(u.getProtocol()) && u.getPath().endsWith(".jar")) { |
try { |
return new URL("jar:jar" + u.toString().replace('!', '^') + "!/"); |
return new URL("jar:jar" + u.toString().replace('!', '^') + "!/" + s); |
} catch (MalformedURLException e) { |
// shouldn't happen since we modify a valid URL |
throw new IllegalStateException("Couldn't transform " + u, e); |
/trunk/OpenConcerto/src/org/openconcerto/utils/prog/VMLauncher.java |
---|
16,11 → 16,11 |
import org.openconcerto.utils.FileUtils; |
import org.openconcerto.utils.OSFamily; |
import org.openconcerto.utils.ProcessStreams; |
import org.openconcerto.utils.ProcessStreams.Action; |
import org.openconcerto.utils.PropertiesUtils; |
import java.io.File; |
import java.io.IOException; |
import java.lang.ProcessBuilder.Redirect; |
import java.lang.management.ManagementFactory; |
import java.util.ArrayList; |
import java.util.Arrays; |
167,7 → 167,7 |
return restart(mainClass, Arrays.asList(args)); |
} |
public static final Process restart(final Action action, final Class<?> mainClass, final String... args) throws IOException { |
public static final Process restart(final Redirect action, final Class<?> mainClass, final String... args) throws IOException { |
return restart(action, mainClass, Arrays.asList(args)); |
} |
182,16 → 182,16 |
* @see #NO_RESTART |
*/ |
public static final Process restart(final Class<?> mainClass, final List<String> args) throws IOException { |
return restart(Action.CLOSE, mainClass, args); |
return restart(ProcessStreams.DISCARD, mainClass, args); |
} |
public static final Process restart(final Action action, final Class<?> mainClass, final List<String> args) throws IOException { |
public static final Process restart(final Redirect action, final Class<?> mainClass, final List<String> args) throws IOException { |
if (Boolean.getBoolean(NO_RESTART)) |
return null; |
final File wd = FileUtils.getWD(); |
final List<String> command = getNativeCommand(args); |
if (command != null) { |
return ProcessStreams.handle(new ProcessBuilder(command).directory(wd).start(), action); |
return new ProcessBuilder(command).directory(wd).redirectErrorStream(true).redirectOutput(action).start(); |
} else { |
try { |
mainClass.getMethod("main", String[].class); |
210,7 → 210,7 |
} |
@Override |
protected Action getStreamAction() { |
protected Redirect getStreamRedirect() { |
return action; |
} |
}.launch(mainClass.getName(), args); |
278,7 → 278,7 |
return split(res); |
} |
protected final Process launch(final String mainClass) throws IOException { |
public final Process launch(final String mainClass) throws IOException { |
return this.launch(mainClass, Collections.<String> emptyList()); |
} |
302,7 → 302,7 |
* @return the new Process. |
* @throws IOException if the process couldn't be started. |
*/ |
protected final Process launch(final String mainClass, final List<String> progParams) throws IOException { |
public final Process launch(final String mainClass, final List<String> progParams) throws IOException { |
final boolean debug = Boolean.getBoolean("launcher.debug"); |
final String javaBinary = getJavaBinary(); |
final File sameJava = new File(System.getProperty("java.home"), "bin/" + javaBinary); |
353,17 → 353,15 |
System.err.println("Std out and err :"); |
} |
final Process res = procBuilder.start(); |
ProcessStreams.handle(res, debug ? Action.REDIRECT : this.getStreamAction()); |
return res; |
procBuilder.redirectErrorStream(true).redirectOutput(debug ? Redirect.INHERIT : this.getStreamRedirect()); |
return procBuilder.start(); |
} |
protected void modifyEnv(Map<String, String> environment) { |
} |
protected Action getStreamAction() { |
return Action.CLOSE; |
protected Redirect getStreamRedirect() { |
return ProcessStreams.DISCARD; |
} |
protected boolean enableRemoteDebug(Properties props) { |
/trunk/OpenConcerto/src/org/openconcerto/utils/SystemInfo.java |
---|
28,6 → 28,7 |
import java.util.Enumeration; |
import java.util.Formatter; |
import java.util.List; |
import java.util.Locale; |
import java.util.NavigableMap; |
import java.util.TreeMap; |
47,7 → 48,8 |
public static final String CLASS_PROTOCOL = "class"; |
static public NavigableMap<Info, String> get(final boolean html) { |
static public NavigableMap<Info, String> get(final boolean html, final Locale locale) { |
final TM tm = TM.getInstance(locale); |
final NavigableMap<Info, String> res = new TreeMap<Info, String>(); |
final String lineBreak = getLineBreak(html); |
65,11 → 67,12 |
e1.printStackTrace(); |
} |
final Runtime rt = Runtime.getRuntime(); |
final String stats = "<i>" + TM.tr("memory") + " :</i> " + formatBytes(rt.freeMemory()) + " / " + formatBytes(rt.totalMemory()) + " ; " + TM.tr("processors", rt.availableProcessors()); |
final String lafDesc = lookAndFeel == null ? TM.tr("no.laf") : getLink(lookAndFeel.getName(), lafURI, html) + ", " + lookAndFeel.getDescription(); |
final String stats = "<i>" + tm.translate("memory") + " :</i> " + formatBytes(tm, rt.freeMemory()) + " / " + formatBytes(tm, rt.totalMemory()) + " ; " |
+ tm.translate("processors", rt.availableProcessors()); |
final String lafDesc = lookAndFeel == null ? tm.translate("no.laf") : getLink(lookAndFeel.getName(), lafURI, html) + ", " + lookAndFeel.getDescription(); |
final String p = TM.tr("javaVersion", version, getLink(getProperty("java.vendor"), vendorURI, html)) + " ; " + getLink(TM.tr("javaHome"), new File(getProperty("java.home")).toURI(), html) |
+ lineBreak + stats + lineBreak + lafDesc; |
final String p = tm.translate("javaVersion", version, getLink(getProperty("java.vendor"), vendorURI, html)) + " ; " |
+ getLink(tm.translate("javaHome"), new File(getProperty("java.home")).toURI(), html) + lineBreak + stats + lineBreak + lafDesc; |
res.put(Info.JAVA, p); |
77,8 → 80,8 |
res.put(Info.OS, "<b>" + getProperty("os.name") + "</b> " + getProperty("os.version") + " (" + getProperty("os.arch") + ")"); |
// * Sylvain ; C:\Documents and Settings\Sylvain ; D:\workspace\CTech |
res.put(Info.USER, getProperty("user.name") + " ; " + getLink(TM.tr("home.dir"), new File(getProperty("user.home")).toURI(), html) + " ; " |
+ getLink(TM.tr("cwd"), new File(getProperty("user.dir")).toURI(), html)); |
res.put(Info.USER, getProperty("user.name") + " ; " + getLink(tm.translate("home.dir"), new File(getProperty("user.home")).toURI(), html) + " ; " |
+ getLink(tm.translate("cwd"), new File(getProperty("user.dir")).toURI(), html)); |
// * eth0 192.168.28.52/24, état: inactif, nom complet: "" |
final List<String> ifs = new ArrayList<String>(); |
96,12 → 99,12 |
return "<b>" + input.getAddress().getHostAddress() + "</b>" + "/" + input.getNetworkPrefixLength(); |
} |
})); |
sb.append(" ; <i>" + TM.tr("interfaceState") + " :</i> " + TM.tr(ni.isUp() ? "interfaceStateUp" : "interfaceStateDown")); |
sb.append(" ; <i>" + tm.translate("interfaceState") + " :</i> " + tm.translate(ni.isUp() ? "interfaceStateUp" : "interfaceStateDown")); |
sb.append(lineBreak); |
sb.append(" <i>" + TM.tr("interfaceFullName") + " :</i> " + ni.getDisplayName()); |
sb.append(" <i>" + tm.translate("interfaceFullName") + " :</i> " + ni.getDisplayName()); |
sb.append(lineBreak); |
sb.append(" <i>" + TM.tr("hardwareAddress") + " :</i> "); |
sb.append(" <i>" + tm.translate("hardwareAddress") + " :</i> "); |
final Formatter fmt = new Formatter(sb); |
final byte[] mac = ni.getHardwareAddress(); |
for (int i = 0; i < mac.length; i++) { |
134,7 → 137,7 |
} |
} |
private static String formatBytes(long b) { |
return TM.tr("megabytes", b / 1024 / 1024); |
private static String formatBytes(final TM tm, final long b) { |
return tm.translate("megabytes", b / 1024 / 1024); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/MessageDigestUtils.java |
---|
17,6 → 17,7 |
import java.io.FileInputStream; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
import java.security.DigestOutputStream; |
import java.security.MessageDigest; |
import java.security.NoSuchAlgorithmException; |
96,18 → 97,30 |
} |
public static String getHashString(MessageDigest md, final InputStream ins) throws IOException { |
final DigestOutputStream out = new DigestOutputStream(StreamUtils.NULL_OS, md); |
StreamUtils.copy(ins, out); |
out.close(); |
return getHashString(md); |
return asHex(getHash(md, ins)); |
} |
public static String getMD5(File f) throws IOException { |
public static byte[] getHash(MessageDigest md, final InputStream ins) throws IOException { |
return getHash(md, ins, StreamUtils.NULL_OS); |
} |
public static byte[] getHash(MessageDigest md, final InputStream ins, final OutputStream out) throws IOException { |
try (final DigestOutputStream digestStream = new DigestOutputStream(out, md)) { |
StreamUtils.copy(ins, digestStream); |
} |
return md.digest(); |
} |
public static byte[] getHash(MessageDigest md, final File f) throws IOException { |
try (final InputStream ins = new FileInputStream(f)) { |
return getHashString(getMD5(), ins); |
return getHash(md, ins); |
} |
} |
public static String getMD5(File f) throws IOException { |
return asHex(getHash(getMD5(), f)); |
} |
public static MessageDigest getMD5() { |
try { |
return MessageDigest.getInstance("MD5"); |
/trunk/OpenConcerto/src/org/openconcerto/utils/UnmodifiableCollectionMap.java |
---|
201,6 → 201,11 |
} |
@Override |
public boolean containsInCollection(K key, V val) { |
return getDel().containsInCollection(key, val); |
} |
@Override |
public Collection<V> allValues() { |
if (this.values == null) { |
this.values = Collections.unmodifiableCollection(getDel().allValues()); |
/trunk/OpenConcerto/src/org/openconcerto/utils/CollectionUtils.java |
---|
417,7 → 417,8 |
return null; |
} |
final List<E> result = new ArrayList<E>(); |
final int size = list.size(); |
final List<E> result = new ArrayList<E>(size); |
for (int i = 0; i < list.size(); i++) { |
result.add(c.cast(list.get(i))); |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/CollectionMap2Itf.java |
---|
51,6 → 51,21 |
public C getCollection(Object key); |
/** |
* Returns <tt>true</tt> if the collection mapped to the passed key contains the specified |
* element. |
* |
* @param key the key. |
* @param element element whose presence in the collection is to be tested. |
* @return <tt>true</tt> if the collection mapped to the passed key contains the specified |
* element or if the key exists, its collection is <code>null</code> and the |
* {@link #getMode() mode} is {@link Mode#NULL_MEANS_ALL} <br> |
* <code>false</code> if <code>!this.containsKey(key)</code>. |
* @throws NullPointerException if the key exists, its collection is <code>null</code> and the |
* {@link #getMode() mode} is not {@link Mode#NULL_MEANS_ALL}. |
*/ |
public boolean containsInCollection(K key, V element) throws NullPointerException; |
/** |
* Returns a {@link Collection} view of all the values contained in this map. The collection is |
* backed by the map, so changes to the map are reflected in the collection, and vice-versa. If |
* the map is modified while an iteration over the collection is in progress (except through the |
/trunk/OpenConcerto/src/org/openconcerto/utils/Zip.java |
---|
173,7 → 173,9 |
*/ |
public void zip(File newFile) throws IOException { |
// on ne garde que la derniere partie du chemin |
this.zip(newFile.getName(), new BufferedInputStream(new FileInputStream(newFile))); |
try (final BufferedInputStream ins = new BufferedInputStream(new FileInputStream(newFile))) { |
this.zip(newFile.getName(), ins); |
} |
} |
/** |
/trunk/OpenConcerto/src/org/openconcerto/utils/change/CollectionChangeEvent.java |
---|
51,16 → 51,28 |
super(source, propertyName, oldValue, newValue); |
} |
@Override |
public Collection<?> getOldValue() { |
// checked by constructor |
return (Collection<?>) super.getOldValue(); |
} |
@Override |
public Collection<?> getNewValue() { |
// checked by constructor |
return (Collection<?>) super.getNewValue(); |
} |
public Collection getItemsAdded() { |
return CollectionUtils.subtract((Collection<?>) this.getNewValue(), (Collection<?>) this.getOldValue()); |
return CollectionUtils.subtract(this.getNewValue(), this.getOldValue()); |
} |
public Collection getItemsRemoved() { |
return CollectionUtils.subtract((Collection<?>) this.getOldValue(), (Collection<?>) this.getNewValue()); |
return CollectionUtils.subtract(this.getOldValue(), this.getNewValue()); |
} |
public Collection getItemsNotChanged() { |
return CollectionUtils.intersection((Collection<?>) this.getNewValue(), (Collection<?>) this.getOldValue()); |
return CollectionUtils.intersection(this.getNewValue(), this.getOldValue()); |
} |
/** |
/trunk/OpenConcerto/src/org/openconcerto/utils/CollectionMap2.java |
---|
223,6 → 223,19 |
return this.get(key, !this.isEmptyCollSameAsNoColl(), true); |
} |
@Override |
public boolean containsInCollection(K key, V val) throws NullPointerException { |
final C c = this.get(key); |
if (c != null) |
return c.contains(val); |
else if (!this.containsKey(key)) |
return false; |
else if (getMode() == Mode.NULL_MEANS_ALL) |
return true; |
else |
throw new NullPointerException("Null value for " + key); |
} |
/** |
* Returns a {@link Collection} view of all the values contained in this map. The collection is |
* backed by the map, so changes to the map are reflected in the collection, and vice-versa. If |
664,7 → 677,7 |
} |
@Override |
public CollectionMap2<K, C, V> clone() throws CloneNotSupportedException { |
public CollectionMap2<K, C, V> clone() { |
@SuppressWarnings("unchecked") |
final CollectionMap2<K, C, V> result = (CollectionMap2<K, C, V>) super.clone(); |
// allValues has a reference to this |
/trunk/OpenConcerto/src/org/openconcerto/utils/ProcessStreams.java |
---|
57,6 → 57,9 |
DO_NOTHING |
} |
// Added to Java 9 |
public static final Redirect DISCARD = Redirect.to(StreamUtils.NULL_FILE); |
static public final ProcessBuilder redirect(final ProcessBuilder pb) throws IOException { |
return pb.redirectErrorStream(true).redirectOutput(Redirect.INHERIT); |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ooxml/XLSXSheet.java |
---|
66,7 → 66,8 |
this.startX = start.x; |
this.startY = start.y; |
final Point end = resolve(parts.get(1)); |
// Feuille vierge dimension = A1 |
final Point end = resolve(parts.size() == 1 ? parts.get(0) : parts.get(1)); |
this.endX = end.x; |
this.endY = end.y; |
this.rows = new ArrayList<>(end.y - start.y); |
/trunk/OpenConcerto/src/org/openconcerto/utils/StringUtils.java |
---|
19,6 → 19,8 |
import java.awt.FontMetrics; |
import java.math.BigDecimal; |
import java.nio.charset.Charset; |
import java.text.Normalizer; |
import java.text.Normalizer.Form; |
import java.util.ArrayList; |
import java.util.Collections; |
import java.util.HashMap; |
26,11 → 28,14 |
import java.util.Iterator; |
import java.util.LinkedHashMap; |
import java.util.List; |
import java.util.Locale; |
import java.util.Map; |
import java.util.Set; |
import java.util.regex.Matcher; |
import java.util.regex.Pattern; |
import com.ibm.icu.lang.UCharacter; |
/** |
* @author Sylvain CUAZ |
*/ |
830,4 → 835,152 |
} |
return null; |
} |
static public interface Search { |
public boolean equals(String str, String anotherString); |
public boolean startsWith(String str, String prefix); |
public boolean endsWith(String str, String suffix); |
public boolean contains(String str, String anotherString); |
} |
static public final Search EXACT_SEARCH = new Search() { |
@Override |
public boolean startsWith(String str, String prefix) { |
return str.startsWith(prefix); |
} |
@Override |
public boolean equals(String str, String anotherString) { |
return str.equals(anotherString); |
} |
@Override |
public boolean endsWith(String str, String suffix) { |
return str.endsWith(suffix); |
} |
@Override |
public boolean contains(String str, String searchStr) { |
return str.contains(searchStr); |
} |
}; |
// Simple (Single-Character) Case Mapping |
static public final Search SIMPLE_CASE_MAPPING_SEARCH = new Search() { |
@Override |
public boolean startsWith(String str, String prefix) { |
return str.regionMatches(true, 0, prefix, 0, prefix.length()); |
} |
@Override |
public boolean equals(String str, String anotherString) { |
return str.equalsIgnoreCase(anotherString); |
} |
@Override |
public boolean endsWith(String str, String suffix) { |
final int suffixLength = suffix.length(); |
return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength); |
} |
@Override |
public boolean contains(String str, String searchStr) { |
final int length = searchStr.length(); |
if (length == 0) |
return true; |
for (int i = str.length() - length; i >= 0; i--) { |
if (str.regionMatches(true, i, searchStr, 0, length)) |
return true; |
} |
return false; |
} |
}; |
static public abstract class NormalizeSearch implements Search { |
protected abstract String normalize(String s); |
@Override |
public boolean startsWith(String str, String prefix) { |
return normalize(str).startsWith(normalize(prefix)); |
} |
@Override |
public boolean equals(String str, String anotherString) { |
return normalize(str).equals(normalize(anotherString)); |
} |
@Override |
public boolean endsWith(String str, String suffix) { |
return normalize(str).endsWith(normalize(suffix)); |
} |
@Override |
public boolean contains(String str, String searchStr) { |
return normalize(str).contains(normalize(searchStr)); |
} |
}; |
// Fixed Locale |
static public final class LowerCaseMappingSearch extends NormalizeSearch { |
private final Locale locale; |
public LowerCaseMappingSearch(Locale locale) { |
super(); |
this.locale = locale; |
} |
public final Locale getLocale() { |
return this.locale; |
} |
@Override |
protected String normalize(String s) { |
return s.toLowerCase(this.getLocale()); |
} |
}; |
// Locale.getDefault() at the time of the call |
static public final Search DEFAULT_LOWERCASE_MAPPING_SEARCH = new NormalizeSearch() { |
@Override |
protected String normalize(String s) { |
return s.toLowerCase(); |
} |
}; |
static public final Search CASE_FOLDING_SEARCH = new NormalizeSearch() { |
@Override |
protected String normalize(String s) { |
return normalizeCase(s); |
} |
}; |
static private final Pattern BLANK_PATTERN = Pattern.compile("\\p{Blank}+"); |
// replace tabs and multiple spaces by one space |
static public final String normalizeBlanks(String s) { |
return BLANK_PATTERN.matcher(s.trim()).replaceAll(" "); |
} |
static private final Pattern DIACRITICAL_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); |
static public String removeDiacritical(final String s) { |
return DIACRITICAL_PATTERN.matcher(Normalizer.normalize(s, Form.NFD)).replaceAll(""); |
} |
static public final String normalizeCase(final String s) { |
// the JRE only does Single-Character Case Mapping so it can't handle Tschüß/TSCHÜSS |
// http://userguide.icu-project.org/transforms/casemappings |
// https://unicode.org/faq/casemap_charprop.html#casemap |
return UCharacter.foldCase(s, true); |
} |
static public final String normalizeForSearch(final String s) { |
return normalizeCase(removeDiacritical(normalizeBlanks(s))); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/sync/HashWriter.java |
---|
23,6 → 23,8 |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.security.MessageDigest; |
import java.util.Arrays; |
import java.util.Objects; |
public class HashWriter { |
public static final int BLOCK_SIZE = 1024; |
78,51 → 80,13 |
public static byte[] getHash(File f) throws IOException { |
final MessageDigest hashSum = MessageDigestUtils.getSHA256(); |
FileInputStream fIn = null; |
try { |
fIn = new FileInputStream(f); |
BufferedInputStream fb = null; |
try { |
fb = new BufferedInputStream(fIn); |
final byte[] buffer = new byte[BLOCK_SIZE]; |
int readSize = fb.read(buffer); |
while (readSize > 0) { |
// Update |
hashSum.update(buffer, 0, readSize); |
// read |
readSize = fb.read(buffer); |
} |
} catch (Exception e) { |
throw new IOException(e); |
} finally { |
if (fb != null) { |
fb.close(); |
} |
} |
} catch (Exception e) { |
throw new IOException(e); |
} finally { |
if (fIn != null) { |
fIn.close(); |
} |
} |
byte[] fileHash = new byte[hashSum.getDigestLength()]; |
fileHash = hashSum.digest(); |
return fileHash; |
return MessageDigestUtils.getHash(hashSum, f); |
} |
public static boolean compareHash(byte[] h1, byte[] h2) { |
final int length = h1.length; |
if (length != h2.length) { |
return false; |
} |
for (int i = 0; i < length; i++) { |
if (h1[i] != h2[i]) { |
return false; |
} |
} |
return true; |
Objects.requireNonNull(h1); |
Objects.requireNonNull(h2); |
return Arrays.equals(h1, h2); |
} |
private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); |
/trunk/OpenConcerto/src/org/openconcerto/utils/sync/SimpleSyncClient.java |
---|
15,17 → 15,18 |
import org.openconcerto.utils.CollectionUtils; |
import org.openconcerto.utils.MessageDigestUtils; |
import org.openconcerto.utils.NetUtils; |
import org.openconcerto.utils.StreamUtils; |
import org.openconcerto.utils.net.HTTPClient; |
import java.io.BufferedInputStream; |
import java.io.BufferedOutputStream; |
import java.io.ByteArrayOutputStream; |
import java.io.File; |
import java.io.FileInputStream; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
import java.io.UnsupportedEncodingException; |
import java.net.MalformedURLException; |
import java.net.ProtocolException; |
import java.net.URL; |
import java.nio.charset.StandardCharsets; |
import java.nio.file.Files; |
import java.nio.file.Path; |
42,20 → 43,15 |
import java.util.concurrent.atomic.AtomicBoolean; |
import java.util.function.BiFunction; |
import java.util.function.Predicate; |
import java.util.zip.GZIPInputStream; |
import java.util.zip.GZIPOutputStream; |
import javax.net.ssl.HttpsURLConnection; |
import javax.net.ssl.SSLSocketFactory; |
import net.minidev.json.JSONArray; |
import net.minidev.json.JSONObject; |
import net.minidev.json.parser.JSONParser; |
public final class SimpleSyncClient { |
public final class SimpleSyncClient extends HTTPClient { |
private static final int MIN_GZIP_SIZE = 64; |
static protected final long getLong(final Object o) { |
return ((Number) o).longValue(); |
} |
64,67 → 60,6 |
return Instant.ofEpochMilli(getLong(o)); |
} |
static public class ServerException extends RuntimeException { |
private final int responseCode; |
private final boolean authenticateError; |
protected ServerException(int responseCode, boolean authenticateError) { |
super("Response code was " + responseCode); |
this.responseCode = responseCode; |
this.authenticateError = authenticateError; |
} |
public final int getResponseCode() { |
return this.responseCode; |
} |
public final boolean isAuthenticateError() { |
return this.authenticateError; |
} |
} |
static public final class Response { |
protected final static Response create(HttpsURLConnection con, final Set<Integer> okCodes) throws IOException { |
final boolean success = okCodes == null ? con.getResponseCode() == 200 : okCodes.contains(con.getResponseCode()); |
return new Response(success, con.getResponseCode(), con.getResponseMessage(), con.getContentEncoding(), con.getContentType()); |
} |
private final boolean success; |
private final int code; |
private final String message; |
private final String contentEncoding, contentType; |
protected Response(boolean success, int code, String message, String contentEncoding, String contentType) { |
super(); |
this.success = success; |
this.code = code; |
this.message = message; |
this.contentEncoding = contentEncoding; |
this.contentType = contentType; |
} |
public final int getCode() { |
return this.code; |
} |
public final boolean isSuccess() { |
return this.success; |
} |
public final String getMessage() { |
return this.message; |
} |
public final String getContentEncoding() { |
return this.contentEncoding; |
} |
public final String getContentType() { |
return this.contentType; |
} |
} |
static protected abstract class BaseAttrs { |
private final String path; |
private final String name; |
264,87 → 199,13 |
} |
} |
private final String url; |
private SSLSocketFactory socketFactory; |
private String token; |
private boolean throwException = true; |
public SimpleSyncClient(final String url) { |
this.url = url; |
super(url); |
} |
public final SSLSocketFactory getSocketFactory() { |
return this.socketFactory; |
} |
public final void setSocketFactory(SSLSocketFactory socketFactory) { |
this.socketFactory = socketFactory; |
} |
public final void setToken(String token) { |
this.token = token; |
} |
public final boolean hasToken() { |
return this.getToken() != null; |
} |
protected final String getToken() { |
return this.token; |
} |
public final void setThrowException(boolean throwException) { |
this.throwException = throwException; |
} |
public final boolean throwsException() { |
return this.throwException; |
} |
protected Response checkResponseCode(final HttpsURLConnection con) throws IOException { |
return checkResponseCode(con, null); |
} |
protected Response checkResponseCode(final HttpsURLConnection con, final Set<Integer> okCodes) throws IOException { |
final Response res = Response.create(con, okCodes); |
if (this.throwsException() && !res.isSuccess()) |
throw new ServerException(res.getCode(), con.getHeaderField("WWW-Authenticate") != null); |
return res; |
} |
private final HttpsURLConnection openConnection(final String path) throws IOException { |
final HttpsURLConnection con = (HttpsURLConnection) new URL(this.url + path).openConnection(); |
con.setRequestProperty("Accept-Encoding", "gzip"); |
if (this.getSocketFactory() != null) |
con.setSSLSocketFactory(this.getSocketFactory()); |
if (getToken() != null) |
con.setRequestProperty("Authorization", "Bearer " + Base64.getEncoder().encodeToString(getToken().getBytes(StandardCharsets.UTF_8))); |
return con; |
} |
private final InputStream getInputStream(final HttpsURLConnection con) throws IOException { |
return "gzip".equals(con.getContentEncoding()) ? new GZIPInputStream(con.getInputStream()) : con.getInputStream(); |
} |
private final HttpsURLConnection send(final HttpsURLConnection con, final String params) throws IOException { |
return this.send(con, params.getBytes(StandardCharsets.UTF_8), false); |
} |
private final HttpsURLConnection send(final HttpsURLConnection con, final byte[] toSend, final boolean allowGzip) throws IOException { |
final boolean useGzip = allowGzip && toSend.length >= MIN_GZIP_SIZE; |
if (useGzip) |
con.setRequestProperty("Content-Encoding", "gzip"); |
con.setRequestMethod("POST"); |
con.setDoOutput(true); |
try (final OutputStream o = useGzip ? new GZIPOutputStream(con.getOutputStream()) : con.getOutputStream()) { |
o.write(toSend); |
} |
return con; |
} |
public DirContent getDir(final String path) throws Exception { |
final HttpsURLConnection con = openConnection("/getDir"); |
final Response res = checkResponseCode(send(con, "rp=" + path + "&type=json")); |
final Response res = checkResponseCode(send(con, NetUtils.urlEncode("rp", path, "type", "json"))); |
if (!res.isSuccess()) |
return null; |
final JSONParser p = new JSONParser(JSONParser.MODE_STRICTEST); |
362,7 → 223,7 |
public Response getFile(final String path, final String fileName, final FileConsumer fileConsumer) throws IOException { |
final HttpsURLConnection con = openConnection("/get"); |
send(con, "rn=" + fileName + "&rp=" + path); |
send(con, NetUtils.urlEncode("rn", fileName, "rp", path)); |
final Response res = checkResponseCode(con, GETFILE_OK_CODES); |
if (res.getCode() == 404) { |
fileConsumer.accept(null, null); |
391,23 → 252,44 |
return !missing.get(); |
} |
public Response deleteFile(final String path, final String fileName) throws MalformedURLException, IOException, ProtocolException, UnsupportedEncodingException { |
public Response deleteFile(final String path, final String fileName) throws IOException { |
final HttpsURLConnection con = openConnection("/delete"); |
return checkResponseCode(send(con, "rn=" + fileName + "&rp=" + path)); |
return checkResponseCode(send(con, NetUtils.urlEncode("rn", fileName, "rp", path))); |
} |
public Response sendFile(String path, File localFile) throws Exception, MalformedURLException, IOException, ProtocolException { |
byte[] newsha256 = HashWriter.getHash(localFile); |
long size = localFile.length(); |
public final Response renameFile(final String path, final String fileName, final String newFileName) throws IOException { |
return this.renameFile(path, fileName, null, newFileName); |
} |
public final Response renameFile(final String path, final String fileName, final String newPath, final String newFileName) throws IOException { |
final HttpsURLConnection con = openConnection("/rename"); |
return checkResponseCode(send(con, NetUtils.urlEncode("rn", fileName, "rp", path, "newPath", newPath, "newName", newFileName))); |
} |
public Response sendFile(String path, File localFile) throws IOException { |
return this.sendFile(path, localFile, false); |
} |
public Response sendFile(String path, File localFile, final boolean overwrite) throws IOException { |
final long size = localFile.length(); |
if (size >= Integer.MAX_VALUE) |
throw new OutOfMemoryError("Required array size too large : " + size); |
final ByteArrayOutputStream ba = new ByteArrayOutputStream((int) size); |
final byte[] newsha256; |
// compute digest at the same time to protect against race conditions |
try (final InputStream ins = new BufferedInputStream(new FileInputStream(localFile))) { |
newsha256 = MessageDigestUtils.getHash(MessageDigestUtils.getSHA256(), ins, ba); |
} |
final HttpsURLConnection con = openConnection("/put"); |
// We use Base64 because headers are not supporting UTF8 |
con.setRequestProperty("X_FILENAME_B64", Base64.getEncoder().encodeToString(localFile.getName().getBytes(StandardCharsets.UTF_8))); |
con.setRequestProperty("X_PATH_B64", Base64.getEncoder().encodeToString(path.getBytes(StandardCharsets.UTF_8))); |
con.setRequestProperty("X-OVERWRITE", Boolean.toString(overwrite)); |
con.setRequestProperty("X_FILESIZE", String.valueOf(size)); |
con.setRequestProperty("X_SHA256", HashWriter.bytesToHex(newsha256)); |
con.setRequestProperty("X-Last-Modified-ms", String.valueOf(localFile.lastModified())); |
return checkResponseCode(send(con, Files.readAllBytes(localFile.toPath()), true)); |
return checkResponseCode(send(con, ba.toByteArray(), true)); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/ExceptionHandler.java |
---|
47,6 → 47,7 |
import java.net.URI; |
import java.net.URL; |
import java.nio.charset.Charset; |
import java.util.Locale; |
import java.util.Map; |
import java.util.concurrent.CompletableFuture; |
import java.util.concurrent.Future; |
481,7 → 482,7 |
version = productInfo.getProperty(ProductInfo.VERSION, version); |
} |
final Map<Info, String> systemInfos = SystemInfo.get(false); |
final Map<Info, String> systemInfos = SystemInfo.get(false, Locale.ENGLISH); |
final String os = systemInfos.remove(Info.OS); |
final String java = systemInfos.toString(); |
final String encodedData = "java=" + PercentEncoder.encode(java, cs) + "&os=" + PercentEncoder.encode(os, cs) + "&software=" + PercentEncoder.encode(name + version, cs) + "&stack=" |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TranslationPool.java |
---|
New file |
0,0 → 1,102 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.i18n; |
import java.util.Collection; |
import java.util.HashMap; |
import java.util.Locale; |
import java.util.Map; |
import java.util.Objects; |
import java.util.function.Function; |
import net.jcip.annotations.ThreadSafe; |
@ThreadSafe |
public class TranslationPool<T, X extends Exception> { |
static public enum Mode { |
/** |
* Try to create if needed, but allow <code>null</code>. |
*/ |
OPTIONAL_CREATE(true, true), |
/** |
* Try to create if needed, but disallow <code>null</code>. |
*/ |
GET_OR_CREATE(true, false), |
/** |
* The item must already exist. |
*/ |
GET_CREATED(false, false); |
private final boolean allowCreation, allowNull; |
private Mode(boolean allowCreation, boolean allowNull) { |
this.allowCreation = allowCreation; |
this.allowNull = allowNull; |
} |
} |
// it's rare to load many Locale |
private final Map<Locale, T> byLocale = new HashMap<>(8); |
private final Function<Locale, T> createInstance; |
public TranslationPool() { |
this(null); |
} |
public TranslationPool(final Function<Locale, T> createInstance) { |
this.createInstance = createInstance; |
} |
protected T createTM(final Locale l) throws X { |
return this.createInstance.apply(l); |
} |
public final T get(final Locale l) throws X { |
return this.get(l, Mode.GET_OR_CREATE); |
} |
public final T get(final Locale l, final Mode mode) throws X { |
Objects.requireNonNull(l, "Missing locale"); |
Objects.requireNonNull(mode, "Missing mode"); |
T res; |
synchronized (this) { |
res = this.byLocale.get(l); |
if (res == null && mode.allowCreation) { |
res = this.createTM(l); |
if (res != null) |
this.byLocale.put(l, res); |
} |
if (res == null && !mode.allowNull) |
throw new IllegalStateException("Missing instance for " + l); |
} |
return res; |
} |
public final T getCreated(final Locale l) { |
// Don't call get(Locale, Mode) since it throws a generic exception that can't be caught |
Objects.requireNonNull(l, "Missing locale"); |
synchronized (this) { |
final T res = this.byLocale.get(l); |
if (res == null) |
throw new IllegalStateException("Missing instance for " + l); |
return res; |
} |
} |
final Collection<T> getCreated() { |
assert Thread.holdsLock(this); |
return this.byLocale.values(); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TranslationManager.java |
---|
14,10 → 14,12 |
package org.openconcerto.utils.i18n; |
import org.openconcerto.utils.Log; |
import org.openconcerto.utils.i18n.TranslationPool.Mode; |
import java.io.IOException; |
import java.io.InputStream; |
import java.util.ArrayList; |
import java.util.Collection; |
import java.util.Collections; |
import java.util.HashMap; |
import java.util.List; |
24,14 → 26,17 |
import java.util.Locale; |
import java.util.Map; |
import java.util.ResourceBundle.Control; |
import java.util.function.Consumer; |
import javax.xml.XMLConstants; |
import javax.xml.parsers.DocumentBuilder; |
import javax.xml.parsers.DocumentBuilderFactory; |
import javax.xml.parsers.ParserConfigurationException; |
import org.w3c.dom.Document; |
import org.w3c.dom.Element; |
import org.w3c.dom.NodeList; |
import org.xml.sax.SAXException; |
import net.jcip.annotations.GuardedBy; |
import net.jcip.annotations.ThreadSafe; |
38,6 → 43,16 |
@ThreadSafe |
public class TranslationManager { |
public static final void setVMLocale(Locale locale) { |
Locale.setDefault(locale); |
// As explained in Locale.setDefault() javadoc : "be prepared to reinitialize |
// locale-sensitive code". As ResourceBundle.getBundle(), this throws RuntimeException if no |
// instance can be created. |
TranslationManager.createDefaultInstance(); |
// nothing to do for TM |
} |
private static final Locale FALLBACK_LOCALE = Locale.ENGLISH; |
private static final Control CONTROL = new I18nUtils.SameLanguageControl() { |
53,64 → 68,110 |
return CONTROL; |
} |
static public interface Loader extends Consumer<TranslationManager> { |
} |
private static final String BASENAME = "translation"; |
private static final TranslationManager instance = new TranslationManager(); |
private static final TranslationPool<TranslationManager, RuntimeException> POOL = new TranslationPool<TranslationManager, RuntimeException>() { |
@Override |
protected TranslationManager createTM(Locale l) throws RuntimeException { |
assert Thread.holdsLock(POOL); |
// Allow some apps to not create an instance at all |
if (classes.isEmpty()) |
return null; |
final TranslationManager res = new TranslationManager(l); |
res.setTranslations(classes, true); |
return res; |
} |
}; |
/** |
* Create the default instance if needed. Must be called each time {@link TM#getDefaultLocale()} |
* changes otherwise {@link #getInstance()} will throw an exception. |
* |
* @return the instance for the default locale, <code>null</code> if |
* {@link #addTranslationStreamFromClass(Class)} wasn't called. |
*/ |
public static final TranslationManager createDefaultInstance() { |
return POOL.get(TM.getDefaultLocale(), Mode.OPTIONAL_CREATE); |
} |
public static final TranslationManager getInstance() { |
return instance; |
return getInstance(TM.getDefaultLocale()); |
} |
@GuardedBy("classes") |
private final List<Class<?>> classes; |
@GuardedBy("classes") |
private Locale locale; |
// TODO throw exception |
public static final TranslationManager createInstance(final Locale l) { |
return POOL.get(l); |
} |
private final Object trMutex = new Object(); |
@GuardedBy("trMutex") |
private Map<String, String> menuTranslation; |
@GuardedBy("trMutex") |
private Map<String, String> itemTranslation; |
@GuardedBy("trMutex") |
private Map<String, String> actionTranslation; |
/** |
* Get an instance already created by {@link #createInstance(Locale)}. This method won't block, |
* that's what createInstance() is for. |
* |
* @param l the locale |
* @return the cached instance. |
*/ |
public static final TranslationManager getInstance(final Locale l) { |
return POOL.getCreated(l); |
} |
private TranslationManager() { |
this.classes = new ArrayList<>(); |
@GuardedBy("POOL") |
private static final List<Object> classes = new ArrayList<>(); |
public static final void addTranslationStreamFromClass(Class<?> c) { |
_addLoader(c); |
} |
public void addTranslationStreamFromClass(Class<?> c) { |
synchronized (this.classes) { |
this.classes.add(c); |
if (this.getLocale() != null) { |
loadTranslation(this.getLocale(), c); |
} |
} |
public static final void addLoader(final Loader loader) { |
_addLoader(loader); |
} |
public void removeTranslationStreamFromClass(Class<?> c) { |
synchronized (this.classes) { |
if (this.classes.remove(c) && this.getLocale() != null) { |
loadAllTranslation(); |
private static final void _addLoader(final Object loader) { |
synchronized (POOL) { |
classes.add(loader); |
for (final TranslationManager tm : POOL.getCreated()) { |
tm.addTranslations(loader, true); |
} |
} |
} |
public final Locale getLocale() { |
synchronized (this.classes) { |
return this.locale; |
} |
public static final void removeTranslationStreamFromClass(Class<?> c) { |
_removeLoader(c); |
} |
public final void setLocale(Locale l) { |
if (l == null) |
throw new NullPointerException("null Locale"); |
synchronized (this.classes) { |
if (!l.equals(this.locale)) { |
this.locale = l; |
loadAllTranslation(); |
public static final void removeLoader(final Loader loader) { |
_removeLoader(loader); |
} |
private static final void _removeLoader(final Object o) { |
synchronized (POOL) { |
if (classes.remove(o)) { |
for (final TranslationManager tm : POOL.getCreated()) { |
tm.setTranslations(classes, false); |
} |
} |
} |
} |
private final Locale locale; |
private final Object trMutex = new Object(); |
@GuardedBy("trMutex") |
private Map<String, String> menuTranslation; |
@GuardedBy("trMutex") |
private Map<String, String> itemTranslation; |
@GuardedBy("trMutex") |
private Map<String, String> actionTranslation; |
private TranslationManager(final Locale locale) { |
this.locale = locale; |
} |
public final Locale getLocale() { |
return this.locale; |
} |
private void checkNulls(String id, String label) { |
if (id == null) |
throw new NullPointerException("null id"); |
118,7 → 179,7 |
throw new NullPointerException("null label"); |
} |
// Menus |
// Menus in menu bar and menu items |
public String getTranslationForMenu(String id) { |
synchronized (this.trMutex) { |
133,7 → 194,7 |
} |
} |
// Items |
// Items labels in panels |
public String getTranslationForItem(String id) { |
synchronized (this.trMutex) { |
148,7 → 209,7 |
} |
} |
// Actions |
// Actions (buttons or contextual menus) |
public String getTranslationForAction(String id) { |
synchronized (this.trMutex) { |
163,35 → 224,43 |
} |
} |
private void loadAllTranslation() { |
private void setTranslations(final Collection<?> classes, final boolean warn) { |
synchronized (this.trMutex) { |
this.menuTranslation = new HashMap<>(); |
this.itemTranslation = new HashMap<>(); |
this.actionTranslation = new HashMap<>(); |
if (this.classes.isEmpty()) { |
if (warn && classes.isEmpty()) { |
Log.get().warning("TranslationManager has no resources to load (" + this.getLocale() + ")"); |
} |
for (Class<?> c : this.classes) { |
boolean loaded = loadTranslation(this.getLocale(), c); |
if (!loaded) { |
Log.get().warning("TranslationManager was unable to load translation " + c.getCanonicalName() + " for locale " + this.getLocale()); |
} |
for (Object o : classes) { |
this.addTranslations(o, warn); |
} |
} |
} |
private void addTranslations(final Object o, final boolean warn) { |
if (o instanceof Class) { |
final Class<?> c = (Class<?>) o; |
boolean loaded = loadTranslation(this.getLocale(), c); |
if (warn && !loaded) { |
Log.get().warning("TranslationManager was unable to load translation " + c.getCanonicalName() + " for locale " + this.getLocale()); |
} |
} else { |
final Loader loader = (Loader) o; |
loader.accept(this); |
} |
} |
// return all existing (e.g fr_CA only specify differences with fr) |
private List<InputStream> findStream(final Locale locale, final Class<?> c, final boolean rootLast) { |
private List<String> findResources(final Locale locale, final Class<?> c, final boolean rootLast) { |
final Control cntrl = CONTROL; |
final List<InputStream> res = new ArrayList<>(); |
final List<String> res = new ArrayList<>(); |
final String baseName = c.getPackage().getName() + "." + BASENAME; |
// test emptiness to not mix languages |
for (Locale targetLocale = locale; targetLocale != null && res.isEmpty(); targetLocale = cntrl.getFallbackLocale(baseName, targetLocale)) { |
for (final Locale candidate : cntrl.getCandidateLocales(baseName, targetLocale)) { |
final InputStream ins = c.getClassLoader().getResourceAsStream(cntrl.toResourceName(cntrl.toBundleName(baseName, candidate), "xml")); |
if (ins != null) |
res.add(ins); |
res.add(cntrl.toResourceName(cntrl.toBundleName(baseName, candidate), "xml")); |
} |
} |
if (!rootLast) |
199,49 → 268,47 |
return res; |
} |
private boolean loadTranslation(final Locale l, Class<?> c) { |
private boolean loadTranslation(final Locale l, final Class<?> c) { |
boolean translationLoaded = false; |
// we want more specific translations to replace general ones, i.e. root Locale first |
for (final InputStream input : findStream(l, c, false)) { |
// create new instances to check if there's no duplicates in each resource |
final Map<String, String> menuTranslation = new HashMap<>(), itemTranslation = new HashMap<>(), actionTranslation = new HashMap<>(); |
loadTranslation(input, menuTranslation, itemTranslation, actionTranslation); |
// on the other hand, it's OK for one resource to override another |
this.menuTranslation.putAll(menuTranslation); |
this.itemTranslation.putAll(itemTranslation); |
this.actionTranslation.putAll(actionTranslation); |
translationLoaded = true; |
} |
return translationLoaded; |
} |
private static void loadTranslation(final InputStream input, final Map<String, String> menuTranslation, final Map<String, String> itemTranslation, final Map<String, String> actionTranslation) { |
// FIXME : l'implementation de Java est lente |
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl : 60 ms! |
// On pourrait passer à 1ms avec Piccolo... |
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); |
final DocumentBuilder dBuilder; |
try { |
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); |
dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); |
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); |
final Document doc = dBuilder.parse(input); |
// Menus |
loadTranslation(doc, "menu", menuTranslation); |
// Items (title, labels not related to fields...) |
loadTranslation(doc, "item", itemTranslation); |
// Actions |
loadTranslation(doc, "action", actionTranslation); |
} catch (Exception e) { |
e.printStackTrace(); |
} finally { |
try { |
if (input != null) { |
input.close(); |
} |
} catch (IOException e) { |
dBuilder = dbFactory.newDocumentBuilder(); |
} catch (ParserConfigurationException e) { |
throw new IllegalStateException("Couldn't create DocumentBuilder", e); |
} |
// we want more specific translations to replace general ones, i.e. root Locale first |
for (final String rsrcName : findResources(l, c, false)) { |
// create new instances to check if there's no duplicates in each resource |
final Map<String, String> menuTranslation = new HashMap<>(), itemTranslation = new HashMap<>(), actionTranslation = new HashMap<>(); |
try (final InputStream input = c.getClassLoader().getResourceAsStream(rsrcName)) { |
if (input == null) |
continue; |
final Document doc = dBuilder.parse(input); |
// Menus |
loadTranslation(doc, "menu", menuTranslation); |
// Items (title, labels not related to fields...) |
loadTranslation(doc, "item", itemTranslation); |
// Actions |
loadTranslation(doc, "action", actionTranslation); |
} catch (SAXException | IOException e) { |
e.printStackTrace(); |
// don't return to load as much as possible |
} |
// on the other hand, it's OK for one resource to override another |
this.menuTranslation.putAll(menuTranslation); |
this.itemTranslation.putAll(itemTranslation); |
this.actionTranslation.putAll(actionTranslation); |
translationLoaded = true; |
} |
return translationLoaded; |
} |
private static void loadTranslation(final Document doc, final String tagName, final Map<String, String> m) { |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/RuleBasedNumberFormatUtils.java |
---|
New file |
0,0 → 1,76 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.i18n; |
import org.openconcerto.utils.SystemUtils.PropertyList; |
import java.util.ArrayList; |
import java.util.Collections; |
import java.util.List; |
import com.ibm.icu.text.MessageFormat; |
import com.ibm.icu.text.RuleBasedNumberFormat; |
import com.ibm.icu.util.ULocale; |
/** |
* Prints names that can be passed to {@link RuleBasedNumberFormat#setDefaultRuleSet(String)}, |
* {@link RuleBasedNumberFormat#format(long, String)} or {@link MessageFormat}. Can also be used to |
* test {@link MessageFormat}, e.g. "{0, ordinal, %digits-ordinal-feminine} femme" => "1re femme". |
* |
* @author sylvain |
*/ |
public class RuleBasedNumberFormatUtils { |
public static final String LOCALE_PROP_NAME = "locales"; |
public static void main(String[] args) { |
if (args.length == 0) { |
System.out.println("--list\tList rule names"); |
System.out.println("--eval number message\tEvaluate the passed string using MessageFormat"); |
System.out.println("Use " + LOCALE_PROP_NAME + " system property to define locales to use"); |
System.exit(0); |
} |
final String action = args[0]; |
if (action.equals("--list")) { |
for (final ULocale l : getLocales()) { |
System.out.println(I18nUtils.dumpAllRules(l)); |
System.out.println(); |
} |
} else if (action.equals("--eval")) { |
final Object[] params = new Object[] { Long.valueOf(args[1]) }; |
final String message = args[2]; |
for (final ULocale l : getLocales()) { |
System.out.println(l.getName() + ":"); |
System.out.println(new MessageFormat(message, l).format(params)); |
System.out.println(); |
} |
} else { |
throw new IllegalArgumentException("Unknown action : " + action); |
} |
} |
private static List<ULocale> getLocales() { |
final List<ULocale> res; |
final List<String> pl = new PropertyList(LOCALE_PROP_NAME, ",").getValues(); |
if (pl == null || pl.isEmpty()) { |
res = Collections.singletonList(ULocale.getDefault()); |
} else { |
res = new ArrayList<>(pl.size()); |
for (final String l : pl) { |
res.add(ULocale.forLanguageTag(l)); |
} |
} |
return res; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TMPool.java |
---|
New file |
0,0 → 1,23 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.i18n; |
import java.util.Locale; |
import java.util.function.Function; |
public class TMPool<T extends TM> extends TranslationPool<T, RuntimeException> { |
public TMPool(final Function<Locale, T> createInstance) { |
super(createInstance); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/i18n/TM.java |
---|
39,6 → 39,8 |
import com.ibm.icu.text.MessagePattern.Part; |
import com.ibm.icu.text.MessagePattern.Part.Type; |
import net.jcip.annotations.ThreadSafe; |
/** |
* Translation manager. The translations are provided by {@link Translator} instances, they are |
* created either from a class ending in a language tag that implements it, or by properties files |
48,6 → 50,7 |
* @author Sylvain |
* @see LocalizedInstances |
*/ |
@ThreadSafe |
public class TM { |
static public enum MissingMode { |
89,11 → 92,11 |
static private final MissingMode DEFAULT_MISSING_MODE = MissingMode.STRING; |
static private final TM INSTANCE = new TM(); |
private static final TMPool<TM> POOL = new TMPool<TM>(TM::new); |
static private final Pattern splitPtrn = Pattern.compile("__", Pattern.LITERAL); |
static private boolean USE_DYNAMIC_MAP = true; |
public static void setUseDynamicMap(boolean b) { |
public static synchronized void setUseDynamicMap(boolean b) { |
USE_DYNAMIC_MAP = b; |
} |
106,14 → 109,31 |
* |
* @return <code>true</code> if <code>DynamicMap</code> should be used. |
*/ |
public static boolean useDynamicMap() { |
public static synchronized boolean useDynamicMap() { |
return USE_DYNAMIC_MAP; |
} |
/** |
* The default locale for {@link #getInstance()}. Currently just {@link Locale#getDefault()}. |
* |
* @return the default locale. |
*/ |
public static final Locale getDefaultLocale() { |
return Locale.getDefault(); |
} |
static public TM getInstance() { |
return INSTANCE; |
return getInstance(getDefaultLocale()); |
} |
static public TM getInstance(final Locale l) { |
return POOL.get(l); |
} |
static public String tr(final Locale l, final String key, final Object... args) { |
return getInstance(l).translate(key, args); |
} |
static public String tr(final String key, final Object... args) { |
return getInstance().translate(key, args); |
} |
122,16 → 142,11 |
private TranslatorChain translations; |
private Locale translationsLocale; |
protected TM() { |
init(); |
protected TM(final Locale locale) { |
setLocale(locale); |
} |
protected void init() { |
setLocale(Locale.getDefault()); |
} |
public final void setLocale(final Locale locale) { |
this.locale = locale; |
private final void setLocale(final Locale locale) { |
final LocalizedInstances<Translator> localizedInstances = new LocalizedInstances<Translator>(Translator.class, TranslationManager.getControl()) { |
@Override |
protected Translator createInstance(final String bundleName, final Locale l, final Class<?> cl) throws IOException { |
154,8 → 169,11 |
}; |
}; |
final Tuple2<Locale, List<Translator>> createInstances = localizedInstances.createInstances(getBaseName(), locale); |
this.translationsLocale = createInstances.get0(); |
this.translations = new TranslatorChain(createInstances.get1()); |
synchronized (this) { |
this.locale = locale; |
this.translationsLocale = createInstances.get0(); |
this.translations = new TranslatorChain(createInstances.get1()); |
} |
} |
/** |
164,7 → 182,7 |
* @return the requested locale. |
* @see #setLocale(Locale) |
*/ |
public final Locale getLocale() { |
public final synchronized Locale getLocale() { |
return this.locale; |
} |
173,10 → 191,14 |
* |
* @return the actual locale. |
*/ |
public final Locale getTranslationsLocale() { |
public final synchronized Locale getTranslationsLocale() { |
return this.translationsLocale; |
} |
private final synchronized TranslatorChain getTranslations() { |
return this.translations; |
} |
protected String getBaseName() { |
return I18nUtils.getBaseName(this.getClass()); |
} |
239,7 → 261,7 |
Objects.requireNonNull(mode, "Null mode"); |
Objects.requireNonNull(key, "Null key"); |
Objects.requireNonNull(args, "Null arguments"); |
final String res = this.translations.translate(key, args); |
final String res = this.getTranslations().translate(key, args); |
return mode.returnResult(this, res, key); |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/PEMImporter.java |
---|
18,9 → 18,9 |
import java.io.File; |
import java.io.FileReader; |
import java.io.IOException; |
import java.security.GeneralSecurityException; |
import java.security.KeyFactory; |
import java.security.KeyStore; |
import java.security.KeyStoreException; |
import java.security.NoSuchAlgorithmException; |
import java.security.PrivateKey; |
import java.security.cert.CertificateException; |
40,7 → 40,7 |
public class PEMImporter { |
public static SSLServerSocketFactory createSSLFactory(File privateKeyPem, File certificatePem, String password) throws Exception { |
public static SSLServerSocketFactory createSSLFactory(File privateKeyPem, File certificatePem, String password) throws IOException, GeneralSecurityException { |
final SSLContext context = SSLContext.getInstance("TLS"); |
final KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password); |
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); |
57,8 → 57,7 |
* @param certificatePem the certificate(s) PEM file |
* @param the password to set to protect the private key |
*/ |
public static KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password) |
throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { |
public static KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password) throws IOException, GeneralSecurityException { |
final X509Certificate[] cert = createCertificates(certificatePem); |
final KeyStore keystore = KeyStore.getInstance("JKS"); |
keystore.load(null); |
68,7 → 67,7 |
return keystore; |
} |
private static PrivateKey createPrivateKey(File privateKeyPem) throws Exception { |
private static PrivateKey createPrivateKey(File privateKeyPem) throws IOException, GeneralSecurityException { |
final BufferedReader r = new BufferedReader(new FileReader(privateKeyPem)); |
String s = r.readLine(); |
if (s == null || !s.contains("BEGIN PRIVATE KEY")) { |
90,7 → 89,7 |
return generatePrivateKeyFromDER(bytes); |
} |
private static X509Certificate[] createCertificates(File certificatePem) throws Exception { |
private static X509Certificate[] createCertificates(File certificatePem) throws IOException, CertificateException { |
final List<X509Certificate> result = new ArrayList<X509Certificate>(); |
final BufferedReader r = new BufferedReader(new FileReader(certificatePem)); |
String s = r.readLine(); |
/trunk/OpenConcerto/src/org/openconcerto/utils/SystemUtils.java |
---|
13,6 → 13,7 |
package org.openconcerto.utils; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.Collections; |
import java.util.List; |
98,5 → 99,28 |
} else |
return false; |
} |
public final boolean remove(final String value) { |
return this.remove(value, true); |
} |
public final boolean remove(final String value, final boolean unsetIfEmpty) { |
if (value == null) |
throw new NullPointerException("Null value"); |
final List<String> l = getValues(); |
if (l == null || l.size() == 0 || !l.contains(value)) |
return false; |
final List<String> newList = new ArrayList<>(l.size() - 1); |
for (final String item : l) { |
if (!item.equals(value)) |
newList.add(item); |
} |
if (unsetIfEmpty && newList.isEmpty()) |
System.clearProperty(this.name); |
else |
System.setProperty(this.name, CollectionUtils.join(newList, this.getSeparator())); |
return true; |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/IClosureFuture.java |
---|
24,6 → 24,6 |
* @param <E> The parameter type for the <tt>executeChecked</tt> method |
* @param <X> The type of exception thrown by the <tt>executeChecked</tt> method |
*/ |
public interface IClosureFuture<E, X extends Exception> extends Future<Object>, IExnClosure<E, X> { |
public interface IClosureFuture<E, X extends Exception> extends Future<Void>, IExnClosure<E, X> { |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/ExceptionFuture.java |
---|
New file |
0,0 → 1,55 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.cc; |
import java.util.concurrent.ExecutionException; |
import java.util.concurrent.FutureTask; |
public class ExceptionFuture<V, X extends Exception, X2 extends Exception> extends FutureTask<V> { |
static public class OneExceptionFuture<V, X extends Exception> extends ExceptionFuture<V, X, RuntimeException> { |
public <X2 extends RuntimeException> OneExceptionFuture(final I2ExnFactory<? extends V, ? extends X, ? extends RuntimeException> cl) { |
super(cl, RuntimeException.class); |
} |
} |
private final Class<X2> exnClass; |
public ExceptionFuture(final I2ExnFactory<? extends V, ? extends X, ? extends X2> cl, final Class<X2> exnClass) { |
super(cl::createChecked); |
this.exnClass = exnClass; |
} |
public final V getWithOriginalException() throws InterruptedException, X, X2 { |
try { |
return this.get(); |
} catch (ExecutionException e) { |
final Throwable cause = e.getCause(); |
if (cause instanceof Error) { |
throw (Error) cause; |
} else if (cause instanceof RuntimeException) { |
throw (RuntimeException) cause; |
// Not strictly necessary but it feels more robust than to cast "cause" to X even |
// when it's really X2 |
} else if (this.exnClass.isInstance(cause)) { |
throw this.exnClass.cast(cause); |
} else { |
// our Callable throws X or X2 but the latter is already handled above. |
@SuppressWarnings("unchecked") |
final X casted = (X) cause; |
throw casted; |
} |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/IncludeExclude.java |
---|
17,6 → 17,7 |
import org.openconcerto.utils.CompareUtils; |
import org.openconcerto.utils.Tuple2; |
import java.util.Arrays; |
import java.util.Collection; |
import java.util.Collections; |
import java.util.HashSet; |
47,6 → 48,11 |
return (IncludeExclude<T>) FULL; |
} |
@SafeVarargs |
public static <T> IncludeExclude<T> getNormalized(final T... includes) { |
return getNormalized(Arrays.asList(includes)); |
} |
public static <T> IncludeExclude<T> getNormalized(final Collection<? extends T> includes) { |
return getNormalized(includes, Collections.<T> emptySet()); |
} |
109,6 → 115,8 |
* @return <code>true</code> if is in include and not in exclude. |
*/ |
public final boolean isIncluded(final T s) { |
// "if" order is irrelevant since those methods use getNormal() and it can't be both "all" |
// and "none". |
if (this.isAllIncluded()) |
return true; |
else if (this.isNoneIncluded()) |
170,6 → 178,7 |
* @return <code>true</code> if {@link #isIncluded(Object)} always return <code>true</code> |
*/ |
public final boolean isAllIncluded() { |
// use normalized value to avoid ambiguous "include all" and "exclude all" |
return this.normal == FULL; |
} |
179,6 → 188,7 |
* @return <code>true</code> if {@link #isIncluded(Object)} always return <code>false</code> |
*/ |
public final boolean isNoneIncluded() { |
// use normalized value to avoid ambiguous "include all" and "exclude all" |
return this.normal == EMPTY; |
} |
212,6 → 222,11 |
return ifNoSole; |
} |
@SafeVarargs |
public final IncludeExclude<T> include(final T... items) { |
return this.include(Arrays.asList(items)); |
} |
public final IncludeExclude<T> include(final Collection<? extends T> items) { |
if (this.areAllIncluded(items)) |
return this; |
238,6 → 253,11 |
return new IncludeExclude<T>(newIncludes, newExcludes, false, false); |
} |
@SafeVarargs |
public final IncludeExclude<T> exclude(final T... items) { |
return this.exclude(Arrays.asList(items)); |
} |
public final IncludeExclude<T> exclude(final Collection<? extends T> items) { |
if (this.areNoneIncluded(items)) |
return this; |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/TransformerFuture.java |
---|
14,10 → 14,9 |
package org.openconcerto.utils.cc; |
import org.openconcerto.utils.Value; |
import org.openconcerto.utils.cc.ExceptionFuture.OneExceptionFuture; |
import java.util.concurrent.Callable; |
import java.util.concurrent.ExecutionException; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.TimeUnit; |
import java.util.concurrent.TimeoutException; |
import java.util.concurrent.atomic.AtomicReference; |
25,13 → 24,13 |
public class TransformerFuture<E, T, X extends Exception> implements ITransformerFuture<E, T, X> { |
private final AtomicReference<Value<E>> input; |
private final FutureTask<T> f; |
private final OneExceptionFuture<T, X> f; |
public TransformerFuture(final ITransformerExn<? super E, ? extends T, ? extends X> cl) { |
super(); |
this.f = new FutureTask<T>(new Callable<T>() { |
this.f = new OneExceptionFuture<T, X>(new IExnFactory<T, X>() { |
@Override |
public T call() throws X { |
public T createChecked() throws X { |
return cl.transformChecked(TransformerFuture.this.input.get().getValue()); |
} |
}); |
70,22 → 69,10 |
this.f.run(); |
assert this.f.isDone(); |
try { |
return this.f.get(); |
return this.f.getWithOriginalException(); |
} catch (InterruptedException e) { |
// shouldn't happen since f is done |
throw new IllegalStateException(e); |
} catch (ExecutionException e) { |
final Throwable cause = e.getCause(); |
if (cause instanceof Error) { |
throw (Error) cause; |
} else if (cause instanceof RuntimeException) { |
throw (RuntimeException) cause; |
} else { |
// our Callable throws X |
@SuppressWarnings("unchecked") |
final X casted = (X) cause; |
throw casted; |
} |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/AbstractMapDecorator.java |
---|
109,7 → 109,7 |
} |
@Override |
protected Object clone() throws CloneNotSupportedException { |
protected Object clone() { |
try { |
final Map<K, V> delegate = CopyUtils.copy(this.delegate); |
@SuppressWarnings("unchecked") |
117,11 → 117,8 |
res.delegate = delegate; |
return res; |
} catch (CloneNotSupportedException e) { |
throw e; |
} catch (Exception e) { |
final CloneNotSupportedException exn = new CloneNotSupportedException(); |
exn.initCause(e); |
throw exn; |
// As done in java.util collections |
throw new InternalError(e); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/ClosureFuture.java |
---|
13,12 → 13,12 |
package org.openconcerto.utils.cc; |
public class ClosureFuture<E, X extends Exception> extends TransformerFuture<E, Object, X> implements IClosureFuture<E, X> { |
public class ClosureFuture<E, X extends Exception> extends TransformerFuture<E, Void, X> implements IClosureFuture<E, X> { |
public ClosureFuture(final IExnClosure<? super E, ? extends X> cl) { |
super(new ITransformerExn<E, Object, X>() { |
super(new ITransformerExn<E, Void, X>() { |
@Override |
public Object transformChecked(E input) throws X { |
public Void transformChecked(E input) throws X { |
cl.executeChecked(input); |
return null; |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/I2ExnFactory.java |
---|
New file |
0,0 → 1,20 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.utils.cc; |
public interface I2ExnFactory<E, X extends Exception, X2 extends Exception> { |
public abstract E createChecked() throws X, X2; |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/cc/IExnFactory.java |
---|
13,8 → 13,6 |
package org.openconcerto.utils.cc; |
public interface IExnFactory<E, X extends Exception> { |
public interface IExnFactory<E, X extends Exception> extends I2ExnFactory<E, X, RuntimeException> { |
public abstract E createChecked() throws X; |
} |
/trunk/OpenConcerto/src/org/openconcerto/utils/NetUtils.java |
---|
17,15 → 17,21 |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
import java.io.UnsupportedEncodingException; |
import java.net.InetAddress; |
import java.net.NetworkInterface; |
import java.net.ServerSocket; |
import java.net.SocketException; |
import java.net.URL; |
import java.net.URLEncoder; |
import java.nio.charset.StandardCharsets; |
import java.security.KeyManagementException; |
import java.security.NoSuchAlgorithmException; |
import java.security.cert.X509Certificate; |
import java.util.Enumeration; |
import java.util.LinkedHashMap; |
import java.util.Map; |
import java.util.Map.Entry; |
import javax.net.ssl.HostnameVerifier; |
import javax.net.ssl.HttpsURLConnection; |
178,6 → 184,41 |
return content; |
} |
static public final String urlEncode(final String... kv) { |
final int size = kv.length; |
if (size % 2 != 0) |
throw new IllegalArgumentException("Odd number of items : " + size); |
final LinkedHashMap<String, Object> map = new LinkedHashMap<>(size / 2, 1); |
for (int i = 0; i < size; i += 2) { |
map.put(kv[i], kv[i + 1]); |
} |
return urlEncode(map); |
} |
static public final String urlEncode(final Map<String, ?> map) { |
if (map.isEmpty()) |
return ""; |
final String charset = StandardCharsets.UTF_8.name(); |
final StringBuilder sb = new StringBuilder(256); |
for (final Entry<String, ?> e : map.entrySet()) { |
final Object value = e.getValue(); |
// Avoid null and "null" confusion. |
if (value != null) { |
try { |
sb.append(URLEncoder.encode(e.getKey(), charset)); |
sb.append('='); |
sb.append(URLEncoder.encode(String.valueOf(value), charset)); |
sb.append('&'); |
} catch (UnsupportedEncodingException exn) { |
throw new IllegalStateException("UTF-8 should be standard", exn); |
} |
} |
} |
// remove last '&' |
sb.setLength(sb.length() - 1); |
return sb.toString(); |
} |
// Create a trust manager that does not validate certificate chains |
static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() { |
public java.security.cert.X509Certificate[] getAcceptedIssuers() { |
/trunk/OpenConcerto/src/org/openconcerto/utils/NumberUtils.java |
---|
13,13 → 13,17 |
package org.openconcerto.utils; |
import org.openconcerto.utils.convertor.NumberConvertor; |
import java.math.BigDecimal; |
import java.math.BigInteger; |
import java.math.RoundingMode; |
import java.util.Collections; |
import java.util.EnumSet; |
import java.util.Set; |
import java.util.concurrent.atomic.AtomicInteger; |
import java.util.concurrent.atomic.AtomicLong; |
import org.openconcerto.utils.convertor.NumberConvertor; |
public class NumberUtils { |
/** |
215,6 → 219,47 |
} |
} |
static public final int divideRoundUp(final int n, final int d) { |
return divideRound(n, d, RoundingMode.UP); |
} |
static public final int divideRoundDown(final int n, final int d) { |
return divideRound(n, d, RoundingMode.DOWN); |
} |
static public final int divideRoundCeiling(final int n, final int d) { |
return divideRound(n, d, RoundingMode.CEILING); |
} |
static public final int divideRoundFloor(final int n, final int d) { |
return divideRound(n, d, RoundingMode.FLOOR); |
} |
static final Set<RoundingMode> DIVIDE_SUPPORTED_MODES = Collections.unmodifiableSet(EnumSet.of(RoundingMode.UP, RoundingMode.DOWN, RoundingMode.CEILING, RoundingMode.FLOOR)); |
static final int divideRound(final int n, final int d, final RoundingMode mode) { |
if (n == 0) |
return 0; |
final int mult; |
if (mode == RoundingMode.DOWN) { |
mult = 0; |
} else if (mode == RoundingMode.UP) { |
mult = signum(n) * (d - 1); |
} else if (mode == RoundingMode.CEILING) { |
// If the result is positive, behaves as for RoundingMode.UP; if negative, behaves as |
// for RoundingMode.DOWN |
mult = n > 0 ? (d - 1) : 0; |
} else if (mode == RoundingMode.FLOOR) { |
// If the result is positive, behave as for RoundingMode.DOWN; if negative, behave as |
// for RoundingMode.UP |
mult = n > 0 ? 0 : -(d - 1); |
} else { |
throw new UnsupportedOperationException(); |
} |
return (n + mult) / d; |
} |
static public Number negate(Number n) { |
if (n == null) |
return null; |
249,6 → 294,17 |
return res; |
} |
static public int signum(final long l) { |
final int res; |
if (l == 0) |
res = 0; |
else if (l < 0) |
res = -1; |
else |
res = 1; |
return res; |
} |
static public int signum(Number n) { |
if (n == null) |
throw new NullPointerException(); |
263,13 → 319,7 |
} else if (clazz == Float.class) { |
res = (int) Math.signum(n.floatValue()); |
} else if (clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class || clazz == AtomicInteger.class || clazz == AtomicLong.class) { |
final long l = n.longValue(); |
if (l == 0) |
res = 0; |
else if (l < 0) |
res = -1; |
else |
res = 1; |
res = signum(n.longValue()); |
} else { |
// limit overflow for unknown class |
res = (int) Math.signum(n.doubleValue()); |
/trunk/OpenConcerto/src/org/openconcerto/utils/SleepingQueue.java |
---|
24,8 → 24,10 |
import java.util.concurrent.Callable; |
import java.util.concurrent.CancellationException; |
import java.util.concurrent.ExecutionException; |
import java.util.concurrent.Executor; |
import java.util.concurrent.Future; |
import java.util.concurrent.FutureTask; |
import java.util.concurrent.RunnableFuture; |
import java.util.concurrent.ScheduledFuture; |
import java.util.concurrent.ScheduledThreadPoolExecutor; |
import java.util.concurrent.TimeUnit; |
36,12 → 38,12 |
import net.jcip.annotations.GuardedBy; |
/** |
* A queue that can be put to sleep. Submitted runnables are converted to FutureTask, that can later |
* be cancelled. |
* A queue that can be put to sleep. Submitted runnables are converted to RunnableFuture, that can |
* later be cancelled. |
* |
* @author Sylvain |
*/ |
public class SleepingQueue { |
public class SleepingQueue implements Executor { |
public static enum RunningState { |
NEW, RUNNING, WILL_DIE, DYING, DEAD |
146,7 → 148,7 |
public void run() { |
final boolean isDone; |
final RunningState runningState; |
final FutureTask<?> beingRun; |
final RunnableFuture<?> beingRun; |
final SleepingQueue q = lethalFuture.getQueue(); |
synchronized (q) { |
runningState = q.getRunningState(); |
201,13 → 203,13 |
private final PropertyChangeSupport support; |
@GuardedBy("this") |
private FutureTask<?> beingRun; |
private RunnableFuture<?> beingRun; |
private final SingleThreadedExecutor tasksQueue; |
@GuardedBy("this") |
private boolean canceling; |
@GuardedBy("this") |
private IPredicate<FutureTask<?>> cancelPredicate; |
private IPredicate<? super RunnableFuture<?>> cancelPredicate; |
public SleepingQueue() { |
this(SleepingQueue.class.getName() + System.currentTimeMillis()); |
287,44 → 289,49 |
thr.setPriority(Thread.MIN_PRIORITY); |
} |
protected final <T> FutureTask<T> newTaskFor(final Runnable task) { |
protected final <T> RunnableFuture<T> newTaskFor(final Runnable task) { |
return this.newTaskFor(task, null); |
} |
protected <T> FutureTask<T> newTaskFor(final Runnable task, T value) { |
protected <T> RunnableFuture<T> newTaskFor(final Runnable task, T value) { |
return new IFutureTask<T>(task, value, " for {" + this.name + "}"); |
} |
public final FutureTask<?> put(Runnable workRunnable) { |
// otherwise if passing a FutureTask, it will itself be wrapped in another FutureTask. The |
// outer FutureTask will call the inner one's run(), which just record any exception. So the |
// outer one's get() won't throw it and the exception will effectively be swallowed. |
final FutureTask<?> t; |
if (workRunnable instanceof FutureTask) { |
t = ((FutureTask<?>) workRunnable); |
public final RunnableFuture<?> put(Runnable workRunnable) { |
/* |
* Otherwise if passing a RunnableFuture, it will itself be wrapped in another |
* RunnableFuture. The outer RunnableFuture will call the inner one's run(), which just |
* record any exception. So the outer one's get() won't throw it and the exception will |
* effectively be swallowed. |
*/ |
final RunnableFuture<?> t; |
if (workRunnable instanceof RunnableFuture) { |
t = ((RunnableFuture<?>) workRunnable); |
} else { |
t = this.newTaskFor(workRunnable); |
} |
return this.execute(t); |
return this.add(t); |
} |
public final <F extends FutureTask<?>> F execute(F t) { |
@Override |
public final void execute(Runnable command) { |
this.put(command); |
} |
public final <F extends RunnableFuture<?>> F add(F t) { |
if (this.shallAdd(t)) { |
this.add(t); |
// no need to synchronize, if die() is called after our test, t won't be executed anyway |
if (this.dieCalled()) |
throw new IllegalStateException("Already dead, cannot exec " + t); |
this.tasksQueue.put(t); |
return t; |
} else |
} else { |
return null; |
} |
} |
private void add(FutureTask<?> t) { |
// no need to synchronize, if die() is called after our test, t won't be executed anyway |
if (this.dieCalled()) |
throw new IllegalStateException("Already dead, cannot exec " + t); |
this.tasksQueue.put(t); |
} |
private final boolean shallAdd(FutureTask<?> runnable) { |
private final boolean shallAdd(RunnableFuture<?> runnable) { |
if (runnable == null) |
throw new NullPointerException("null runnable"); |
try { |
342,7 → 349,7 |
* @param r the runnable that is being added. |
* @throws InterruptedException if r should not be added to this queue. |
*/ |
protected void willPut(FutureTask<?> r) throws InterruptedException { |
protected void willPut(RunnableFuture<?> r) throws InterruptedException { |
} |
/** |
378,16 → 385,16 |
* |
* @param pred a predicate to know which tasks to cancel. |
*/ |
protected final void cancel(final IPredicate<FutureTask<?>> pred) { |
this.tasksDo(new IClosure<Collection<FutureTask<?>>>() { |
protected final void cancel(final IPredicate<? super RunnableFuture<?>> pred) { |
this.tasksDo(new IClosure<Collection<RunnableFuture<?>>>() { |
@Override |
public void executeChecked(Collection<FutureTask<?>> tasks) { |
public void executeChecked(Collection<RunnableFuture<?>> tasks) { |
cancel(pred, tasks); |
} |
}); |
} |
private final void cancel(IPredicate<FutureTask<?>> pred, Collection<FutureTask<?>> tasks) { |
private final void cancel(IPredicate<? super RunnableFuture<?>> pred, Collection<RunnableFuture<?>> tasks) { |
try { |
synchronized (this) { |
this.canceling = true; |
395,7 → 402,7 |
this.cancelCheck(this.getBeingRun()); |
} |
for (final FutureTask<?> t : tasks) { |
for (final RunnableFuture<?> t : tasks) { |
this.cancelCheck(t); |
} |
} finally { |
407,11 → 414,11 |
} |
} |
public final void tasksDo(IClosure<? super Deque<FutureTask<?>>> c) { |
public final void tasksDo(IClosure<? super Deque<RunnableFuture<?>>> c) { |
this.tasksQueue.itemsDo(c); |
} |
private void cancelCheck(FutureTask<?> t) { |
private void cancelCheck(RunnableFuture<?> t) { |
if (t != null) |
synchronized (this) { |
if (this.canceling && (this.cancelPredicate == null || this.cancelPredicate.evaluateChecked(t))) |
419,7 → 426,7 |
} |
} |
private void setBeingRun(final FutureTask<?> beingRun) { |
private void setBeingRun(final RunnableFuture<?> beingRun) { |
final Future<?> old; |
synchronized (this) { |
old = this.beingRun; |
428,7 → 435,7 |
this.support.firePropertyChange("beingRun", old, beingRun); |
} |
public final synchronized FutureTask<?> getBeingRun() { |
public final synchronized RunnableFuture<?> getBeingRun() { |
return this.beingRun; |
} |
546,13 → 553,13 |
} |
}); |
// die as soon as possible not after all currently queued tasks |
this.tasksQueue.itemsDo(new IClosure<Deque<FutureTask<?>>>() { |
this.tasksQueue.itemsDo(new IClosure<Deque<RunnableFuture<?>>>() { |
@Override |
public void executeChecked(Deque<FutureTask<?>> input) { |
public void executeChecked(Deque<RunnableFuture<?>> input) { |
// since we cancel the current task, we might as well remove all of them since they |
// might depend on the cancelled one |
// cancel removed tasks so that callers of get() don't wait forever |
for (final FutureTask<?> ft : input) { |
for (final RunnableFuture<?> ft : input) { |
// by definition tasks in the queue aren't executing, so interrupt parameter is |
// useless. On the other hand cancel() might return false if already cancelled. |
ft.cancel(false); |
561,7 → 568,7 |
input.addFirst(res); |
// die as soon as possible, even if there's a long task already running |
final FutureTask<?> beingRun = getBeingRun(); |
final RunnableFuture<?> beingRun = getBeingRun(); |
// since we hold the lock on items |
assert beingRun != res : "beingRun: " + beingRun + " ; res: " + res; |
if (beingRun != null) |
633,13 → 640,13 |
this.support.removePropertyChangeListener(l); |
} |
private final class SingleThreadedExecutor extends DropperQueue<FutureTask<?>> { |
private final class SingleThreadedExecutor extends DropperQueue<RunnableFuture<?>> { |
private SingleThreadedExecutor() { |
super(SleepingQueue.this.name + System.currentTimeMillis()); |
} |
@Override |
protected void process(FutureTask<?> task) { |
protected void process(RunnableFuture<?> task) { |
if (!task.isDone()) { |
/* |
* From ThreadPoolExecutor : Track execution state to ensure that afterExecute is |
662,12 → 669,12 |
} |
} |
protected void beforeExecute(final FutureTask<?> f) { |
protected void beforeExecute(final RunnableFuture<?> f) { |
cancelCheck(f); |
setBeingRun(f); |
} |
protected void afterExecute(final FutureTask<?> f, final Throwable t) { |
protected void afterExecute(final RunnableFuture<?> f, final Throwable t) { |
setBeingRun(null); |
try { |
/trunk/OpenConcerto/src/org/openconcerto/utils/StreamUtils.java |
---|
41,6 → 41,8 |
} |
}; |
public static final File NULL_FILE = new File(System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null"); |
/** |
* Verbatim copy an entry from input to output stream. |
* |
/trunk/OpenConcerto/src/org/openconcerto/task/config/ComptaBasePropsConfiguration.java |
---|
20,10 → 20,13 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.DBSystemRoot; |
import org.openconcerto.sql.model.SQLBase; |
import org.openconcerto.sql.model.SQLDataSource; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLFilter; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.SQLTableEvent; |
import org.openconcerto.sql.model.SQLTableModifiedListener; |
import org.openconcerto.sql.users.UserCommonSQLElement; |
import org.openconcerto.sql.users.rights.RightSQLElement; |
import org.openconcerto.sql.users.rights.UserRightSQLElement; |
49,6 → 52,8 |
import java.util.List; |
import java.util.Properties; |
import net.jcip.annotations.GuardedBy; |
public abstract class ComptaBasePropsConfiguration extends PropsConfiguration { |
public abstract void setUpSocieteDataBaseConnexion(int base); |
100,8 → 105,10 |
throw new FileNotFoundException(name + " not found in " + Arrays.asList(dirs)); |
} |
private int idSociete = SQLRow.NONEXISTANT_ID; |
@GuardedBy("this") |
private SQLRow rowSociete = null; |
private final SQLTableModifiedListener rowSocieteListener = (evt) -> updateRowSociete(evt); |
@GuardedBy("this") |
private DBRoot baseSociete; |
{ |
115,15 → 122,26 |
super(props); |
this.setProductInfo(productInfo); |
String name = "ilm"; |
// don't overwrite (allow to map no roots, just to test connection) |
if (getProperty("systemRoot.rootsToMap") == null) { |
this.setProperty("systemRoot.rootsToMap", name + "_Common"); |
this.setProperty("systemRoot.rootPath", name + "_Common"); |
final String interAppRootName = getInterAppRootName(); |
this.setProperty("systemRoot.rootsToMap", interAppRootName); |
this.setProperty("systemRoot.rootPath", interAppRootName); |
} |
} |
@Override |
public void destroy() { |
this.setRowSociete(null); |
super.destroy(); |
} |
public final String getInterAppRootName() { |
String name = "ilm"; |
return name + "_Common"; |
} |
// use Configuration directory if it exists |
@Override |
protected FileMode getFileMode() { |
131,6 → 149,17 |
} |
@Override |
protected void initDS(SQLDataSource ds) { |
super.initDS(ds); |
// Old H2 versions need this to safely open page store files |
// (https://github.com/h2database/h2database/issues/1023), and new version ignore it |
// (https://github.com/h2database/h2database/pull/1208). |
ds.addConnectionProperty("MVCC", "false"); |
// Don't begin transition from page store just yet. |
ds.addConnectionProperty("MV_STORE", "false"); |
} |
@Override |
protected List<String> getMappings() { |
final List<String> res = new ArrayList<>(super.getMappings()); |
final String pkg = "/" + TM.class.getPackage().getName().replace('.', '/'); |
168,32 → 197,64 |
return getRowSociete().getString("DATABASE_NAME"); |
} |
public final SQLRow getRowSociete() { |
public synchronized final SQLRow getRowSociete() { |
return this.rowSociete; |
} |
public final int getSocieteID() { |
return this.idSociete; |
final SQLRow row = this.getRowSociete(); |
return row == null ? SQLRow.NONEXISTANT_ID : row.getID(); |
} |
protected final void setRowSociete(int id) { |
this.idSociete = id; |
final SQLTable tableSociete = getSystemRoot().findTable("SOCIETE_COMMON"); |
final SQLRow row = tableSociete.getRow(id); |
if (row == null) { |
throw new IllegalArgumentException("no row for id " + id + " in " + tableSociete); |
} else if (!row.isValid()) { |
throw new IllegalArgumentException("invalid row : " + row); |
private synchronized void updateRowSociete(SQLTableEvent evt) { |
if (evt.getRow().equals(this.rowSociete)) { |
this.rowSociete.fetchValues(); |
} |
this.rowSociete = row; |
} |
public final SQLTable getSocieteTable() { |
return getSocieteTable(true); |
} |
protected final SQLTable getSocieteTable(final boolean mustExist) { |
return getSystemRoot().findTable("SOCIETE_COMMON", mustExist); |
} |
// undefined ID is allowed (used for the template root) |
protected final void setRowSociete(Number id) { |
final boolean clear = id == null; |
final SQLRow row; |
final SQLTable tableSociete = getSocieteTable(!clear); |
if (clear) { |
row = null; |
// might be null if mapsToRoot is empty (e.g. tests) |
if (tableSociete != null) |
tableSociete.removeTableModifiedListener(this.rowSocieteListener); |
} else { |
row = tableSociete.getRow(id.intValue()); |
if (row == null) { |
throw new IllegalArgumentException("no row for id " + id + " in " + tableSociete); |
} else if (!row.isValid()) { |
throw new IllegalArgumentException("invalid row : " + row); |
} |
tableSociete.addTableModifiedListener(this.rowSocieteListener); |
} |
synchronized (this) { |
this.rowSociete = row; |
} |
} |
@Deprecated |
public final SQLBase getSQLBaseSociete() { |
return this.getRootSociete().getBase(); |
} |
public final DBRoot getRootSociete() { |
if (this.baseSociete == null && this.rowSociete != null) |
return this.getRootSociete(true); |
} |
protected synchronized final DBRoot getRootSociete(final boolean create) { |
if (create && this.baseSociete == null && this.getRowSociete() != null) |
this.baseSociete = this.createSQLBaseSociete(); |
return this.baseSociete; |
} |
/trunk/OpenConcerto/src/org/openconcerto/task/TM.java |
---|
13,20 → 13,27 |
package org.openconcerto.task; |
import org.openconcerto.sql.UserPropsTM; |
import org.openconcerto.utils.i18n.TMPool; |
public class TM extends UserPropsTM { |
import java.util.Locale; |
static private final TM INSTANCE = new TM(); |
public class TM extends org.openconcerto.utils.i18n.TM { |
static public final TM getTM() { |
return INSTANCE; |
private static final TMPool<TM> POOL = new TMPool<TM>(TM::new); |
static public TM getTM() { |
return getTM(getDefaultLocale()); |
} |
static public TM getTM(final Locale l) { |
return POOL.get(l); |
} |
static public final String tr(final String key, final Object... args) { |
return getTM().translate(key, args); |
} |
private TM() { |
private TM(final Locale l) { |
super(l); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateListFrameAbstractAction.java |
---|
14,7 → 14,6 |
package org.openconcerto.erp.action; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.utils.TM; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.PropsConfiguration; |
import org.openconcerto.sql.element.SQLElement; |
67,10 → 66,9 |
protected CreateListFrameAbstractAction(final ComptaPropsConfiguration conf, final E elem) { |
super(elem); |
this.conf = conf; |
// TODO use conf to find TM |
final NounClass nounClass = this.getElem().getName().getNounClass(); |
final String[] translationKeys = nounClass == null ? TRANSLATION_KEY_ARRAY : new String[] { TRANSLATION_KEY + '.' + nounClass.getName(), TRANSLATION_KEY }; |
this.putValue(NAME, StringUtils.firstUp(TM.getTM().translateFirst(MissingMode.NULL, MessageArgs.create("elem", this.getElem().getName()), translationKeys))); |
this.putValue(NAME, StringUtils.firstUp(conf.getERP_TM().translateFirst(MissingMode.STRING, MessageArgs.create("elem", this.getElem().getName()), translationKeys))); |
} |
public final ComptaPropsConfiguration getConf() { |
/trunk/OpenConcerto/src/org/openconcerto/erp/action/CreateEditFrameAbstractAction.java |
---|
13,7 → 13,8 |
package org.openconcerto.erp.action; |
import org.openconcerto.erp.utils.TM; |
import static org.openconcerto.erp.utils.TM.getERP_TM; |
import org.openconcerto.sql.PropsConfiguration; |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.view.EditFrame; |
34,10 → 35,9 |
protected CreateEditFrameAbstractAction(final PropsConfiguration conf, final E elem) { |
super(elem); |
// TODO use conf to find TM |
final NounClass nounClass = this.getElem().getName().getNounClass(); |
final String[] translationKeys = nounClass == null ? TRANSLATION_KEY_ARRAY : new String[] { TRANSLATION_KEY + '.' + nounClass.getName(), TRANSLATION_KEY }; |
this.putValue(NAME, StringUtils.firstUp(TM.getTM().translateFirst(MissingMode.NULL, MessageArgs.create("elem", this.getElem().getName()), translationKeys))); |
this.putValue(NAME, StringUtils.firstUp(getERP_TM(conf.getLocale()).translateFirst(MissingMode.STRING, MessageArgs.create("elem", this.getElem().getName()), translationKeys))); |
} |
@Override |
/trunk/OpenConcerto/src/org/openconcerto/erp/action/AboutAction.java |
---|
44,15 → 44,11 |
public final class AboutAction extends AbstractAction { |
static private final AboutAction instance = new AboutAction(); |
private final ComptaPropsConfiguration conf; |
public static AboutAction getInstance() { |
return instance; |
} |
private AboutAction() { |
public AboutAction(final ComptaPropsConfiguration conf) { |
super("Informations"); |
this.conf = conf; |
} |
@Override |
61,7 → 57,7 |
JPanel p = new JPanel(); |
p.setLayout(new BorderLayout()); |
final JScrollPane contentPane = new JScrollPane(new InfoPanel()); |
final JScrollPane contentPane = new JScrollPane(new InfoPanel(this.conf.getLocale())); |
p.add(createComptaInfoPanel(), BorderLayout.NORTH); |
p.add(contentPane, BorderLayout.CENTER); |
p.add(createBenchMarkPanel(), BorderLayout.SOUTH); |
107,9 → 103,9 |
p.add(new JLabel(path), c); |
c.gridy++; |
c.gridx = 0; |
final String serverIp = ComptaPropsConfiguration.getInstanceCompta().getServerIp(); |
final String serverIp = this.conf.getServerIp(); |
if (serverIp.startsWith("file:")) { |
final String dbPath = ComptaPropsConfiguration.getInstanceCompta().getServerIp().substring(5); |
final String dbPath = serverIp.substring(5); |
c.weightx = 0; |
c.anchor = GridBagConstraints.EAST; |
p.add(new JLabelBold("Fichier de base de données : "), c); |
/trunk/OpenConcerto/src/org/openconcerto/erp/action/NouvelleConnexionAction.java |
---|
64,7 → 64,6 |
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.GridBagConstraints; |
110,9 → 109,6 |
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() { |
304,7 → 300,7 |
public void run() { |
// laisse le temps au logiciel de demarrer |
try { |
Thread.sleep(10000); |
Thread.sleep(1000); |
} catch (InterruptedException e) { |
e.printStackTrace(); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeBrSQLInjector.java |
---|
43,6 → 43,9 |
if (getSource().contains("ID_AFFAIRE") && getDestination().contains("ID_AFFAIRE")) { |
map(getSource().getField("ID_AFFAIRE"), getDestination().getField("ID_AFFAIRE")); |
} |
if (getSource().contains("ID_POLE_PRODUIT") && getDestination().contains("ID_POLE_PRODUIT")) { |
map(getSource().getField("ID_POLE_PRODUIT"), getDestination().getField("ID_POLE_PRODUIT")); |
} |
} |
@Override |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLElement.java |
---|
176,7 → 176,7 |
int aJ = row.getInt("AJOURS"); |
int nJ = row.getInt("LENJOUR"); |
if (aJ + nJ == 0) { |
if (row.getBoolean("DATE_FACTURE")) { |
if (!row.getBoolean("COMPTANT") && row.getBoolean("DATE_FACTURE")) { |
return Configuration.getInstance().getTranslator().getLabelFor(row.getTable().getField("DATE_FACTURE")); |
} else { |
return " "; |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/FichePayeHeureTotalProvider.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.erp.generationDoc.SpreadSheetCellValueContext; |
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider; |
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import java.util.Arrays; |
import java.util.List; |
import com.ibm.icu.math.BigDecimal; |
public class FichePayeHeureTotalProvider implements SpreadSheetCellValueProvider { |
private boolean cumul = false; |
public FichePayeHeureTotalProvider(boolean c) { |
this.cumul = c; |
} |
@Override |
public Object getValue(SpreadSheetCellValueContext context) { |
BigDecimal total = BigDecimal.ZERO; |
SQLRowAccessor rowVar = context.getRow().getForeign("ID_VARIABLE_SALARIE"); |
List<String> fieldHeures = Arrays.asList("HEURE_TRAV", "HEURE_110", "HEURE_125", "HEURE_150", "HEURE_200"); |
for (String field : fieldHeures) { |
if (cumul) { |
field = field + "_CUMUL_VAL"; |
} |
total = total.add(new BigDecimal(rowVar.getFloat(field))); |
} |
return total; |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("fichepaye.heure.total", new FichePayeHeureTotalProvider(false)); |
SpreadSheetCellValueProviderManager.put("fichepaye.heure.cumul.total", new FichePayeHeureTotalProvider(true)); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/FichePayePlafondAProvider.java |
---|
New file |
0,0 → 1,46 |
/* |
* 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.SQLBackgroundTableCache; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLTable; |
import java.util.List; |
import com.ibm.icu.math.BigDecimal; |
public class FichePayePlafondAProvider implements SpreadSheetCellValueProvider { |
@Override |
public Object getValue(SpreadSheetCellValueContext context) { |
SQLTable tableVar = context.getRow().getTable().getDBRoot().findTable("VARIABLE_PAYE"); |
List<SQLRow> rows = SQLBackgroundTableCache.getInstance().getCacheForTable(tableVar).getRows(); |
for (SQLRow sqlRow : rows) { |
if (sqlRow.getString("NOM").equals("PLAFOND_TRANCHE_A")) { |
return new BigDecimal(sqlRow.getFloat("VALEUR")); |
} |
} |
BigDecimal smic = new BigDecimal(3377); |
return smic; |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("fichepaye.plafond", new FichePayePlafondAProvider()); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/QteTotalDocProvider.java |
---|
24,13 → 24,19 |
public class QteTotalDocProvider extends UserInitialsValueProvider { |
private enum TypeQteTotalDocProvider { |
QTE, COLIS |
QTE_KG, QTE, COLIS, PDS_BRUT, QTE_MULT |
}; |
private final TypeQteTotalDocProvider type; |
private boolean ha = false; |
public QteTotalDocProvider(TypeQteTotalDocProvider t) { |
this(t, false); |
} |
public QteTotalDocProvider(TypeQteTotalDocProvider t, boolean ha) { |
this.type = t; |
this.ha = ha; |
} |
@Override |
43,18 → 49,29 |
for (SQLRowAccessor sqlRowAccessor : cols) { |
if (!sqlRowAccessor.getTable().contains("NIVEAU") || sqlRowAccessor.getInt("NIVEAU") == 1) { |
String field = "PV_HT"; |
if (this.ha) { |
field = "PA_HT"; |
} |
BigDecimal prixUnitaire = sqlRowAccessor.getBigDecimal(field); |
if (prixUnitaire != null && prixUnitaire.signum() != 0) { |
if (this.type == TypeQteTotalDocProvider.QTE || this.type == TypeQteTotalDocProvider.QTE_KG) { |
if (this.type == TypeQteTotalDocProvider.QTE || sqlRowAccessor.getForeignID("ID_UNITE_VENTE") == 7) { |
if (this.type == TypeQteTotalDocProvider.QTE) { |
BigDecimal qte = sqlRowAccessor.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRowAccessor.getInt("QTE"))); |
total = total.add(qte); |
} else { |
if (sqlRowAccessor.getObject("NB_COLIS") != null) { |
total = total.add(new BigDecimal(sqlRowAccessor.getInt("NB_COLIS"))); |
BigDecimal qte = sqlRowAccessor.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRowAccessor.getInt("QTE"))); |
total = total.add(qte); |
} |
} else if (this.type == TypeQteTotalDocProvider.PDS_BRUT) { |
total = total.add(sqlRowAccessor.getBigDecimal("T_POIDS_BRUT")); |
} else if (this.type == TypeQteTotalDocProvider.QTE_MULT) { |
BigDecimal qte = new BigDecimal(sqlRowAccessor.getInt("QTE")); |
total = total.add(qte); |
} else { |
if (sqlRowAccessor.getObject("NB_COLIS") != null) { |
total = total.add(new BigDecimal(sqlRowAccessor.getInt("NB_COLIS"))); |
} |
} |
} |
} |
} |
62,7 → 79,11 |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("sales.qty.multiple.total", new QteTotalDocProvider(TypeQteTotalDocProvider.QTE_MULT)); |
SpreadSheetCellValueProviderManager.put("sales.qty.total", new QteTotalDocProvider(TypeQteTotalDocProvider.QTE)); |
SpreadSheetCellValueProviderManager.put("purchase.qty.total", new QteTotalDocProvider(TypeQteTotalDocProvider.QTE, true)); |
SpreadSheetCellValueProviderManager.put("sales.qty.total.kg", new QteTotalDocProvider(TypeQteTotalDocProvider.QTE_KG)); |
SpreadSheetCellValueProviderManager.put("sales.package.total", new QteTotalDocProvider(TypeQteTotalDocProvider.COLIS)); |
SpreadSheetCellValueProviderManager.put("sales.package.brut", new QteTotalDocProvider(TypeQteTotalDocProvider.PDS_BRUT)); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/IbanProvider.java |
---|
New file |
0,0 → 1,69 |
/* |
* 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 org.openconcerto.utils.Tuple2; |
public class IbanProvider implements SpreadSheetCellValueProvider { |
private static Tuple2<Integer, Integer> CODE_PAYS = Tuple2.create(0, 2); |
private static Tuple2<Integer, Integer> CLE_IBAN = Tuple2.create(2, 4); |
private static Tuple2<Integer, Integer> CODE_BANQUE = Tuple2.create(4, 9); |
private static Tuple2<Integer, Integer> CODE_GUICHET = Tuple2.create(9, 14); |
private static Tuple2<Integer, Integer> NUMERO_COMPTE = Tuple2.create(14, 25); |
private static Tuple2<Integer, Integer> CLE_RIB = Tuple2.create(25, 27); |
private final Tuple2<Integer, Integer> currentTuple; |
public IbanProvider(Tuple2<Integer, Integer> tuple) { |
this.currentTuple = tuple; |
} |
public Object getValue(SpreadSheetCellValueContext context) { |
final SQLRowAccessor row = context.getRow(); |
String iban = row.getString("IBAN").trim().replaceAll(" ", ""); |
if (iban.length() >= this.currentTuple.get1()) { |
return iban.substring(this.currentTuple.get0(), this.currentTuple.get1()); |
} else { |
return ""; |
} |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("iban.codepays", new IbanProvider(CODE_PAYS)); |
SpreadSheetCellValueProviderManager.put("iban.cleiban", new IbanProvider(CLE_IBAN)); |
SpreadSheetCellValueProviderManager.put("iban.codebanque", new IbanProvider(CODE_BANQUE)); |
SpreadSheetCellValueProviderManager.put("iban.codeguichet", new IbanProvider(CODE_GUICHET)); |
SpreadSheetCellValueProviderManager.put("iban.numerocompte", new IbanProvider(NUMERO_COMPTE)); |
SpreadSheetCellValueProviderManager.put("iban.clerib", new IbanProvider(CLE_RIB)); |
} |
public static void main(String[] args) { |
String iban = "FR763000401587000260111220"; |
System.err.println(iban.substring(CODE_PAYS.get0(), CODE_PAYS.get1())); |
System.err.println(iban.substring(CLE_IBAN.get0(), CLE_IBAN.get1())); |
System.err.println(iban.substring(CODE_BANQUE.get0(), CODE_BANQUE.get1())); |
System.err.println(iban.substring(CODE_GUICHET.get0(), CODE_GUICHET.get1())); |
System.err.println(iban.substring(NUMERO_COMPTE.get0(), NUMERO_COMPTE.get1())); |
if (iban.length() >= CLE_RIB.get1()) { |
System.err.println(iban.substring(CLE_RIB.get0(), CLE_RIB.get1())); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/FichePayeSmicHProvider.java |
---|
New file |
0,0 → 1,47 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.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.SQLBackgroundTableCache; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLTable; |
import java.util.List; |
import com.ibm.icu.math.BigDecimal; |
public class FichePayeSmicHProvider implements SpreadSheetCellValueProvider { |
@Override |
public Object getValue(SpreadSheetCellValueContext context) { |
SQLTable tableVar = context.getRow().getTable().getDBRoot().findTable("VARIABLE_PAYE"); |
List<SQLRow> rows = SQLBackgroundTableCache.getInstance().getCacheForTable(tableVar).getRows(); |
for (SQLRow sqlRow : rows) { |
if (sqlRow.getString("NOM").equals("SMIC")) { |
return new BigDecimal(sqlRow.getFloat("VALEUR")); |
} |
} |
BigDecimal smic = new BigDecimal(10.03); |
return smic; |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("fichepaye.smic", new FichePayeSmicHProvider()); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/FichePayeHeureSupTotalProvider.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.erp.generationDoc.SpreadSheetCellValueContext; |
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider; |
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import java.util.Arrays; |
import java.util.List; |
import com.ibm.icu.math.BigDecimal; |
public class FichePayeHeureSupTotalProvider implements SpreadSheetCellValueProvider { |
private boolean cumul = false; |
public FichePayeHeureSupTotalProvider(boolean c) { |
this.cumul = c; |
} |
@Override |
public Object getValue(SpreadSheetCellValueContext context) { |
BigDecimal total = BigDecimal.ZERO; |
SQLRowAccessor rowVar = context.getRow().getForeign("ID_VARIABLE_SALARIE"); |
List<String> fieldHeures = Arrays.asList("HEURE_110", "HEURE_125", "HEURE_150", "HEURE_200"); |
for (String field : fieldHeures) { |
if (cumul) { |
field = field + "_CUMUL_VAL"; |
} |
total = total.add(new BigDecimal(rowVar.getFloat(field))); |
} |
return total; |
} |
public static void register() { |
SpreadSheetCellValueProviderManager.put("fichepaye.heure.sup.total", new FichePayeHeureSupTotalProvider(false)); |
SpreadSheetCellValueProviderManager.put("fichepaye.heure.sup.cumul.total", new FichePayeHeureSupTotalProvider(true)); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java |
---|
479,7 → 479,14 |
} |
y++; |
} catch (IllegalArgumentException e) { |
JOptionPane.showMessageDialog(null, "La cellule " + resolveHint + " n'existe pas ou est fusionnée.", "Erreur pendant la génération", JOptionPane.ERROR_MESSAGE); |
SwingUtilities.invokeLater(new Runnable() { |
@Override |
public void run() { |
System.err.println(resolveHint + " : " + value); |
JOptionPane.showMessageDialog(null, "La cellule " + resolveHint + " n'existe pas ou est fusionnée.", "Erreur pendant la génération", JOptionPane.ERROR_MESSAGE); |
} |
}); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetUtils.java |
---|
19,12 → 19,12 |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.FileUtils; |
import java.awt.Graphics2D; |
import java.io.File; |
import java.io.FileOutputStream; |
import java.io.FilenameFilter; |
import java.io.IOException; |
import java.util.ArrayList; |
import java.util.Calendar; |
import java.util.Collections; |
import java.util.Comparator; |
import java.util.List; |
32,14 → 32,22 |
import javax.swing.JOptionPane; |
import javax.swing.SwingUtilities; |
import org.apache.pdfbox.pdmodel.PDDocument; |
import org.apache.pdfbox.pdmodel.PDDocumentInformation; |
import org.apache.pdfbox.pdmodel.PDPage; |
import org.apache.pdfbox.pdmodel.PDPageContentStream; |
import org.apache.pdfbox.pdmodel.common.PDRectangle; |
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; |
import org.apache.pdfbox.util.Matrix; |
import org.jopendocument.model.OpenDocument; |
import org.jopendocument.renderer.ODTRenderer; |
import com.lowagie.text.Document; |
import com.lowagie.text.PageSize; |
import com.lowagie.text.pdf.PdfContentByte; |
import com.lowagie.text.pdf.PdfWriter; |
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D; |
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawer; |
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DFontTextDrawerDefaultFonts; |
public class SheetUtils { |
public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest) { |
132,40 → 140,41 |
public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate) throws Exception { |
assert (!SwingUtilities.isEventDispatchThread()); |
// Open the PDF document |
Document document = new Document(PageSize.A4, 50, 50, 50, 50); |
try { |
PDDocument document = new PDDocument(); |
PDDocumentInformation info = new PDDocumentInformation(); |
info.setCreator("OpenConcerto"); |
info.setProducer("OpenConcerto"); |
info.setCreationDate(Calendar.getInstance()); |
info.setModificationDate(Calendar.getInstance()); |
document.setDocumentInformation(info); |
FileOutputStream fileOutputStream = new FileOutputStream(pdfFileToCreate); |
// Create the writer |
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); |
writer.setPdfVersion(PdfWriter.VERSION_1_6); |
writer.setFullCompression(); |
PdfBoxGraphics2DFontTextDrawer fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts(); |
final File dir = new File("Fonts"); |
if (dir.exists()) { |
fontTextDrawer.registerFontFromDirectory(dir); |
} |
document.open(); |
PdfContentByte cb = writer.getDirectContent(); |
// Configure the renderer |
ODTRenderer renderer = new ODTRenderer(doc); |
renderer.setIgnoreMargins(false); |
renderer.setPaintMaxResolution(true); |
PDRectangle pageSize = PDRectangle.A4; |
// Scale the renderer to fit width or height |
final double widthFactor = renderer.getPrintWidth() / document.getPageSize().getWidth(); |
final double heightFactor = renderer.getPrintHeight() / document.getPageSize().getHeight(); |
final double widthFactor = renderer.getPrintWidth() / pageSize.getWidth(); |
final double heightFactor = renderer.getPrintHeight() / pageSize.getHeight(); |
renderer.setResizeFactor(Math.max(widthFactor, heightFactor)); |
// Print pages |
for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) { |
PDPage page = new PDPage(pageSize); |
document.addPage(page); |
PdfBoxGraphics2D g2 = new PdfBoxGraphics2D(document, pageSize.getWidth(), pageSize.getHeight()); |
g2.setFontTextDrawer(fontTextDrawer); |
Graphics2D g2 = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight()); |
// If you want to prevent copy/paste, you can use |
// g2 = tp.createGraphicsShapes(w, h, true, 0.9f); |
// centrage horizontal, alignement vertical en haut |
g2.translate((PageSize.A4.getWidth() - renderer.getPrintWidthInPixel()) / 2.0, 0); |
174,15 → 183,17 |
renderer.paintComponent(g2); |
g2.dispose(); |
// Add our spreadsheet in the middle of the page |
if (i < renderer.getPrintedPagesNumber() - 1) |
document.newPage(); |
final PDFormXObject xform = g2.getXFormObject(); |
final Matrix matrix = new Matrix(); |
matrix.translate(0, 0); |
final PDPageContentStream contentStream = new PDPageContentStream(document, page); |
contentStream.transform(matrix); |
contentStream.drawForm(xform); |
contentStream.close(); |
} |
document.save(fileOutputStream); |
// Close the PDF document |
document.close(); |
// writer.close(); |
fileOutputStream.close(); |
} catch (Exception originalExn) { |
ExceptionHandler.handle("Impossible de créer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn); |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementFactureFournisseur.java |
---|
16,8 → 16,10 |
import org.openconcerto.erp.core.common.element.BanqueSQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement; |
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement; |
import org.openconcerto.erp.model.PrixTTC; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowValues; |
25,11 → 27,14 |
import org.openconcerto.utils.ExceptionHandler; |
import java.sql.SQLException; |
import java.sql.Timestamp; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.ArrayList; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
// FIXME mettre toute les generations dans des threads à part |
78,7 → 83,7 |
this.nom = "Règlement Achat : " + rowFournisseur.getString("NOM") + " Facture : " + saisieRow.getObject("NUMERO").toString() + " (" + typeRegRow.getString("NOM") + ")"; |
// si paiement comptant |
if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0)) { |
if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0) && !typeRegRow.getBoolean("ECHEANCE")) { |
System.out.println("Règlement Comptant"); |
// test Cheque |
134,6 → 139,7 |
this.putValue("CREDIT", Long.valueOf(prixTTC.getLongValue())); |
ajoutEcriture(); |
} |
setDateReglement(saisieRow, this.date); |
} else { |
Date dateEch = ModeDeReglementSQLElement.calculDate(modeRegRow.getInt("AJOURS"), modeRegRow.getInt("LENJOUR"), this.date); |
151,6 → 157,7 |
// Ajout dans echeance |
Map<String, Object> mEcheance = new HashMap<String, Object>(); |
SQLTable echeanceTable = base.getTable("ECHEANCE_FOURNISSEUR"); |
SQLRow rowMvtPere = tableMouvement.getRow(this.idPere); |
this.idMvt = getNewMouvement("ECHEANCE_FOURNISSEUR", 1, this.idPere, rowMvtPere.getInt("ID_PIECE")); |
157,9 → 164,14 |
mEcheance.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt)); |
mEcheance.put("DATE", new java.sql.Date(dateEch.getTime())); |
mEcheance.put("MONTANT", Long.valueOf(prixTTC.getLongValue())); |
mEcheance.put("ID_FOURNISSEUR", Integer.valueOf(saisieRow.getInt("ID_FOURNISSEUR"))); |
mEcheance.put("ID_FOURNISSEUR", saisieRow.getForeignID("ID_FOURNISSEUR")); |
mEcheance.put("ID_FACTURE_FOURNISSEUR", saisieRow.getID()); |
if (saisieRow.getTable().contains("ID_AFFAIRE") && echeanceTable.contains("ID_AFFAIRE")) { |
if (!saisieRow.isForeignEmpty("ID_AFFAIRE")) { |
mEcheance.put("ID_AFFAIRE", saisieRow.getForeignID("ID_AFFAIRE")); |
} |
} |
SQLTable echeanceTable = base.getTable("ECHEANCE_FOURNISSEUR"); |
SQLRowValues valEcheance = new SQLRowValues(echeanceTable, mEcheance); |
if (valEcheance.getInvalid() == null) { |
227,6 → 239,14 |
} |
private void setDateReglement(SQLRow source, Date d) throws SQLException { |
SQLRowValues rowValsUpdateVF = source.createEmptyUpdateRow(); |
rowValsUpdateVF.put("DATE_REGLEMENT", d); |
rowValsUpdateVF.update(); |
} |
public void run() { |
try { |
genereReglement(); |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Ecriture.java |
---|
92,7 → 92,7 |
insert.add(table.getField("VALIDE"), Boolean.FALSE); |
} |
insert.add(table.getField("DATE_LETTRAGE"), this.dateLettrage); |
insert.add(table.getField("LETTRAGE"), this.lettrage == null || this.lettrage.isEmpty() ? " " : this.lettrage); |
insert.add(table.getField("LETTRAGE"), this.lettrage == null || this.lettrage.isEmpty() ? "" : this.lettrage); |
return insert; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Piece.java |
---|
15,6 → 15,8 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLInsert; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.users.User; |
import java.util.ArrayList; |
import java.util.List; |
41,9 → 43,11 |
return mouvements; |
} |
public SQLInsert createInsert(final DBRoot root) { |
public SQLInsert createInsert(final DBRoot root, User user) { |
final SQLInsert insert = new SQLInsert(); |
insert.add(root.getTable("PIECE").getField("NOM"), this.nom); |
final SQLTable table = root.getTable("PIECE"); |
insert.add(table.getField("NOM"), this.nom); |
insert.addCreationTrackedField(user, table); |
return insert; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementVenteNG.java |
---|
20,6 → 20,7 |
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.SEPAMandateSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement; |
import org.openconcerto.erp.model.PrixTTC; |
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel; |
53,21 → 54,21 |
public SQLRow ecrClient = null; |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource) throws Exception { |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource) throws SQLException { |
this(label, rowClient, ttc, d, modeReglement, source, mvtSource, true); |
} |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse) throws Exception { |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse) throws SQLException { |
this(label, rowClient, ttc, d, modeReglement, source, mvtSource, createEncaisse, false); |
} |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse, boolean avance) |
throws Exception { |
throws SQLException { |
this(label, rowClient, ttc, d, modeReglement, source, mvtSource, createEncaisse, avance, rowClient.getString("NOM"), null); |
} |
public GenerationReglementVenteNG(String label, SQLRow rowClient, PrixTTC ttc, Date d, SQLRow modeReglement, SQLRow source, SQLRow mvtSource, boolean createEncaisse, boolean avance, String tiers, |
SQLRowAccessor cptTiers) throws Exception { |
SQLRowAccessor cptTiers) throws SQLException { |
SQLRow typeRegRow = modeReglement.getForeignRow("ID_TYPE_REGLEMENT"); |
setRowAnalytiqueSource(source); |
155,8 → 156,8 |
if (modeReglement.getObject("DATE") != null) { |
dateTmp = modeReglement.getDate("DATE").getTime(); |
} |
// On fixe la date du règlement de la facture |
setDateReglement(source, dateTmp); |
// On fixe la date du règlement de la facture à reception du cheque |
setDateReglement(source, this.date); |
Calendar c = modeReglement.getDate("DATE_DEPOT"); |
if (c != null) { |
182,6 → 183,11 |
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES); |
} |
if (typeRegRow.getID() == TypeReglementSQLElement.CB && this.rowPrefsCompte.getTable().contains("ID_JOURNAL_CB_ATTENTE") |
&& !this.rowPrefsCompte.isForeignEmpty("ID_JOURNAL_CB_ATTENTE")) { |
this.putValue("ID_JOURNAL", this.rowPrefsCompte.getForeignID("ID_JOURNAL_CB_ATTENTE")); |
} |
int idCompteClient = cptTiers != null && !cptTiers.isUndefined() ? cptTiers.getID() : rowClient.getInt("ID_COMPTE_PCE"); |
if (avance) { |
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_AVANCE_CLIENT"); |
214,8 → 220,18 |
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl)); |
} else { |
fillCompteBanqueFromRow(modeReglement, "VenteCB", false); |
try { |
fillCompteBanqueFromRow(modeReglement, "VenteCB", false); |
} catch (Exception e) { |
throw new SQLException(e); |
} |
} |
if (typeRegRow.getID() == TypeReglementSQLElement.CB && this.rowPrefsCompte.getTable().contains("ID_COMPTE_PCE_CB_ATTENTE") |
&& !this.rowPrefsCompte.isForeignEmpty("ID_COMPTE_PCE_CB_ATTENTE")) { |
this.putValue("ID_COMPTE_PCE", this.rowPrefsCompte.getForeignID("ID_COMPTE_PCE_CB_ATTENTE")); |
} |
this.putValue("DEBIT", Long.valueOf(ttc.getLongValue())); |
this.putValue("CREDIT", Long.valueOf(0)); |
ajoutEcriture(); |
251,7 → 267,33 |
if (source.getTable().equals(tableSaisieVenteFacture)) { |
valEcheance.put("ID_SAISIE_VENTE_FACTURE", source.getID()); |
} |
if (source.getTable().getName().equals(valEcheance.getTable().getName())) { |
valEcheance.put("ID_SAISIE_VENTE_FACTURE", source.getObject("ID_SAISIE_VENTE_FACTURE")); |
} |
if (modeReglement.getForeign("ID_TYPE_REGLEMENT").getBoolean("SEPA")) { |
final String foreignBanqueFieldName = "ID_" + BanqueSQLElement.TABLENAME; |
if (valEcheance.getTable().contains(foreignBanqueFieldName)) |
valEcheance.put(foreignBanqueFieldName, modeReglement.getInt(foreignBanqueFieldName)); |
valEcheance.put("ETS", modeReglement.getObject("ETS")); |
if (!modeReglement.isForeignEmpty("ID_SEPA_MANDATE")) { |
valEcheance.put("ID_SEPA_MANDATE", modeReglement.getForeignID("ID_SEPA_MANDATE")); |
} else if (rowClient != null && !rowClient.isForeignEmpty("ID_SEPA_MANDATE_DEFAULT")) { |
valEcheance.put("ID_SEPA_MANDATE", rowClient.getForeignID("ID_SEPA_MANDATE_DEFAULT")); |
} else { |
SEPAMandateSQLElement mandateElem = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(SEPAMandateSQLElement.class); |
final String mandateID = mandateElem.generateMandateIdentification("Facturation", '0', true, true); |
// TODO gestion si pas de client (ex : don ou cotisation association) |
if (rowClient != null) { |
final SQLRowValues newVals = mandateElem.createRecurrent(rowClient.getID(), mandateID, source.getDate("DATE").getTime()); |
SQLRow rowMandate = newVals.commit(); |
valEcheance.put("ID_SEPA_MANDATE", rowMandate.getID()); |
rowClient.createEmptyUpdateRow().put("ID_SEPA_MANDATE_DEFAULT", rowMandate.getID()).commit(); |
} |
} |
} |
// ajout de l'ecriture |
SQLRow row = valEcheance.insert(); |
SQLRowValues rowVals = new SQLRowValues(tableMouvement); |
342,7 → 384,8 |
} |
} |
private void paiementCheque(Date dateEch, SQLRow source, PrixTTC ttc, SQLRow rowClient, SQLRow modeRegl, SQLRow mvtSource, boolean avance, String tiers, SQLRowAccessor cptTiers) throws Exception { |
private void paiementCheque(Date dateEch, SQLRow source, PrixTTC ttc, SQLRow rowClient, SQLRow modeRegl, SQLRow mvtSource, boolean avance, String tiers, SQLRowAccessor cptTiers) |
throws SQLException { |
SQLRowValues valCheque = new SQLRowValues(base.getTable("CHEQUE_A_ENCAISSER")); |
SQLPreferences prefs = SQLPreferences.getMemCached(valCheque.getTable().getDBRoot()); |
396,7 → 439,7 |
if (rowPrefsCompte.getObject("ID_JOURNAL_VALEUR_ENCAISSEMENT") != null && !rowPrefsCompte.isForeignEmpty("ID_JOURNAL_VALEUR_ENCAISSEMENT")) { |
idJournal = rowPrefsCompte.getForeignID("ID_JOURNAL_VALEUR_ENCAISSEMENT"); |
} |
this.putValue("ID_JOURNAL", idJournal); |
this.putValue("ID_COMPTE_PCE", idCompteClient); |
this.putValue("DEBIT", Long.valueOf(0)); |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSepa.java |
---|
New file |
0,0 → 1,171 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.generationEcritures; |
import org.openconcerto.erp.core.common.element.BanqueSQLElement; |
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement; |
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement; |
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.StringUtils; |
import java.util.ArrayList; |
import java.util.List; |
public class GenerationMvtSepa extends GenerationEcritures { |
private long montant; |
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE"); |
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2); |
private final List<SQLRow> sepaRows; |
private SQLRowAccessor banque; |
public GenerationMvtSepa(List<SQLRow> sepaRows) { |
this.sepaRows = sepaRows; |
// SQLRow chequeRow = base.getTable("CHEQUE_A_ENCAISSER").getRow(this.idCheque); |
// String num = ""; |
// if (chequeRow != null && !chequeRow.isUndefined() && |
// chequeRow.getString("NUMERO").trim().length() > 0) { |
// num = " N° " + chequeRow.getString("NUMERO"); |
// } |
// |
// if (s != null && s.trim().length() > 0) { |
// this.nom = s + (num.trim().length() > 0 ? " - Cheque" + num : ""); |
// } else { |
// this.nom = "Reglement cheque client" + num; |
// } |
} |
public void genere() throws Exception { |
System.err.println("génération des ecritures de règlement d'un prelevement client du mouvement " + this.idMvt); |
List<Integer> pieceIDs = new ArrayList<>(); |
for (SQLRow rowSepa : sepaRows) { |
this.montant = rowSepa.getLong("MONTANT"); |
this.date = rowSepa.getDate("DATE").getTime(); |
this.banque = rowSepa.getForeign("ID_" + BanqueSQLElement.TABLENAME); |
final SQLRowAccessor foreignPiece = rowSepa.getForeign("ID_MOUVEMENT").getForeign("ID_PIECE"); |
this.nom = "Prélèvement " + foreignPiece.getString("NOM"); |
final SQLRowAccessor clientRow = rowSepa.getForeign("ID_CLIENT"); |
// Création de l'encaissement |
SQLRowValues rowVals = new SQLRowValues(base.getTable("ENCAISSER_MONTANT")); |
rowVals.put("MONTANT", montant); |
rowVals.put("ID_CLIENT", clientRow != null ? clientRow.getID() : null); |
rowVals.put("TIERS", rowSepa.getString("TIERS")); |
rowVals.put("DATE", this.date); |
SQLRowValues rowValsRegl = new SQLRowValues(base.getTable("MODE_REGLEMENT")); |
rowValsRegl.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.PRELEVEMENT); |
SQLRow copy = rowValsRegl.insert(); |
rowVals.put("ID_MODE_REGLEMENT", copy.getID()); |
rowVals.put("NOM", this.nom); |
// rowVals.put("ID_MOUVEMENT", this.idMvt); |
SQLRow rowEncaisse = rowVals.insert(); |
SQLRowValues rowValsElt = new SQLRowValues(base.getTable("ENCAISSER_MONTANT_ELEMENT")); |
rowValsElt.put("MONTANT_REGLE", this.montant); |
rowValsElt.put("ID_ENCAISSER_MONTANT", rowEncaisse.getID()); |
rowValsElt.put("ID_MOUVEMENT_ECHEANCE", rowSepa.getForeignID("ID_MOUVEMENT")); |
rowValsElt.insert(); |
this.idMvt = getNewMouvement(rowEncaisse.getTable().getName(), rowEncaisse.getID(), rowSepa.getForeignID("ID_MOUVEMENT"), foreignPiece.getID()); |
rowEncaisse.createEmptyUpdateRow().put("ID_MOUVEMENT", this.idMvt).commit(); |
// initialisation des valeurs de la map |
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt)); |
this.putValue("DATE", new java.sql.Date(this.date.getTime())); |
this.putValue("NOM", this.nom); |
if (this.banque == null || this.banque.isUndefined() || this.banque.isForeignEmpty("ID_JOURNAL")) { |
fillJournalBanqueFromRow(rowSepa); |
} else { |
int idJrnl = this.banque.getForeignID("ID_JOURNAL"); |
this.putValue("ID_JOURNAL", idJrnl); |
} |
this.putValue("NOM", this.nom + " " + foreignPiece.getString("NOM") + " " + StringUtils.limitLength(clientRow.getString("NOM"), 20)); |
// compte Clients |
SQLRowAccessor rowCptTiers = rowSepa.getForeign("ID_COMPTE_PCE_TIERS"); |
int idCompteClient = rowCptTiers != null && !rowCptTiers.isUndefined() ? rowCptTiers.getID() : -1; |
if (idCompteClient == -1) { |
if (clientRow != null) { |
idCompteClient = clientRow.getInt("ID_COMPTE_PCE"); |
} |
if (idCompteClient <= 1) { |
idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT"); |
if (idCompteClient <= 1) { |
idCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients"); |
} |
} |
} |
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient)); |
this.putValue("DEBIT", new Long(0)); |
this.putValue("CREDIT", new Long(rowSepa.getLong("MONTANT"))); |
ajoutEcriture(); |
// compte de reglement cheque, ... |
fillCompteBanqueFromRow(rowSepa, "VenteCheque", false); |
this.putValue("NOM", this.nom); |
this.putValue("DEBIT", new Long(this.montant)); |
this.putValue("CREDIT", new Long(0)); |
ajoutEcriture(); |
pieceIDs.add(foreignPiece.getID()); |
System.err.println("Ecritures générées pour le mouvement " + this.idMvt); |
} |
lettrageAuto(pieceIDs, this.date); |
// TODO mettre à jour la date de réglement dee la facture |
} |
// private void setDateReglement(int idCheque, Date d) throws SQLException { |
// if (idCheque > 1) { |
// SQLRow chequeRow = |
// Configuration.getInstance().getBase().getTable("CHEQUE_A_ENCAISSER").getRow(idCheque); |
// final int sourceId = MouvementSQLElement.getSourceId(chequeRow.getInt("ID_MOUVEMENT")); |
// SQLRow rowMvt = Configuration.getInstance().getBase().getTable("MOUVEMENT").getRow(sourceId); |
// |
// if (rowMvt.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) { |
// SQLElement eltFacture = |
// Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE"); |
// SQLRow saisieRow = eltFacture.getTable().getRow(rowMvt.getInt("IDSOURCE")); |
// // On fixe la date du paiement |
// SQLRowValues rowValsUpdateVF = saisieRow.createEmptyUpdateRow(); |
// rowValsUpdateVF.put("DATE_REGLEMENT", new Timestamp(d.getTime())); |
// rowValsUpdateVF.update(); |
// } |
// } |
// } |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtDepotChequeClient.java |
---|
96,7 → 96,7 |
rowValsDepotElt.putNulls("MONTANT", "TIERS", "PIECE"); |
rowValsDepotElt.putRowValues("ID_CLIENT").putNulls("NOM", "ID_COMPTE_PCE"); |
final SQLRowValues rowValuesChq = rowValsDepotElt.putRowValues("ID_CHEQUE_A_ENCAISSER"); |
rowValuesChq.putNulls("SANS_VALEUR_ENCAISSEMENT").putRowValues("ID_MOUVEMENT").putNulls("ID_PIECE"); |
rowValuesChq.putNulls("SANS_VALEUR_ENCAISSEMENT").putRowValues("ID_MOUVEMENT").putRowValues("ID_PIECE").putNulls("NOM"); |
rowValuesChq.putNulls("ID_COMPTE_PCE_TIERS").putNulls("NUMERO"); |
List<SQLRowValues> cheques = SQLRowValuesListFetcher.create(rowValsDepotElt).fetch(new Where(rowValsDepotElt.getTable().getField("ID_DEPOT_CHEQUE"), "=", depot.getID())); |
for (SQLRowValues sqlRowAccessor : cheques) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Journal.java |
---|
16,6 → 16,7 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLInsert; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.users.User; |
public class Journal { |
private final Long id; |
54,11 → 55,12 |
return ((Journal) obj).code.equalsIgnoreCase(this.code); |
} |
SQLInsert createInsert(DBRoot root) { |
SQLInsert createInsert(DBRoot root, User user) { |
final SQLInsert insert = new SQLInsert(); |
final SQLTable table = root.getTable("JOURNAL"); |
insert.add(table.getField("CODE"), this.code); |
insert.add(table.getField("NOM"), this.nom); |
insert.addCreationTrackedField(user, table); |
return insert; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Mouvement.java |
---|
16,6 → 16,7 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLInsert; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.users.User; |
import java.math.BigDecimal; |
import java.util.ArrayList; |
61,7 → 62,7 |
return this.id; |
} |
SQLInsert createInsert(DBRoot root) { |
SQLInsert createInsert(DBRoot root, User user) { |
final SQLInsert insert = new SQLInsert(); |
final SQLTable table = root.getTable("MOUVEMENT"); |
// FIXME le numero doit être généré en auto |
77,7 → 78,7 |
if (this.pere != null) { |
insert.add(table.getField("ID_MOUVEMENT_PERE"), this.pere.getId().intValue()); |
} |
// TODO CREATION_DATE MODIFICATION_DATE |
insert.addCreationTrackedField(user, table); |
return insert; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Compte.java |
---|
16,6 → 16,7 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLInsert; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.users.User; |
public class Compte { |
private final Long id; |
54,14 → 55,16 |
return ((Compte) obj).numero.equalsIgnoreCase(this.numero); |
} |
SQLInsert createInsert(DBRoot root) { |
SQLInsert createInsert(DBRoot root, User user) { |
final SQLInsert insert = new SQLInsert(); |
final SQLTable table = root.getTable("COMPTE_PCE"); |
insert.add(table.getField("NUMERO"), this.numero); |
insert.add(table.getField("NOM"), this.nom); |
insert.addCreationTrackedField(user, table); |
return insert; |
} |
@Override |
public String toString() { |
return "Compte numero:" + this.numero + " " + this.nom + " (id:" + this.id + ")"; |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Exercice.java |
---|
72,7 → 72,7 |
LOGGER.log(Level.INFO, "insertion de {0} pièces comptables", pieces.size()); |
for (Piece p : pieces) { |
// Pièces |
insertsPiece.add(p.createInsert(root)); |
insertsPiece.add(p.createInsert(root, user)); |
// Vérification des mouvements |
final List<Mouvement> mouvements = p.getMouvements(); |
156,7 → 156,7 |
// journal non déjà existant |
if (codesDesJournauxExistants.get(journal.getCode().toLowerCase()) == null) { |
list.add(journal); |
insertsJournaux.add(journal.createInsert(root)); |
insertsJournaux.add(journal.createInsert(root, user)); |
} |
} |
final List<Number> journauxIds = new ArrayList<>(); |
207,7 → 207,7 |
LOGGER.fine("création du compte : " + c.getNumero().toLowerCase()); |
} |
list.add(c); |
insertsComptes.add(c.createInsert(root)); |
insertsComptes.add(c.createInsert(root, user)); |
} |
} |
List<Number> comptesIds = new ArrayList<>(); |
352,7 → 352,7 |
piece.setId(idsPieces.get(i)); |
for (Mouvement m : piece.getMouvements()) { |
listMvtWithoutIDs.add(m); |
insertsMouvement.add(m.createInsert(root)); |
insertsMouvement.add(m.createInsert(root, user)); |
} |
} |
370,11 → 370,11 |
} |
List<SQLUpdate> mvtUpdate = new ArrayList<>(); |
for (int i = 0; i < idsMouvements.size(); i++) { |
maxMvt++; |
Number mvtId = idsMouvements.get(i); |
SQLUpdate update = new SQLUpdate(new Where(tableMvt.getKey(), "=", mvtId)); |
update.add(tableMvt.getField("NUMERO"), maxMvt); |
mvtUpdate.add(update); |
maxMvt++; |
listMvtWithoutIDs.get(i).setId(mvtId); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirFournisseur.java |
---|
64,7 → 64,9 |
this.putValue("NOM", "Avoir fournisseur : " + avoirRow.getString("NUMERO") + " " + rowFourn.getString("NOM")); |
this.putValue("ID_JOURNAL", GenerationMvtAvoirFournisseur.journal); |
this.putValue("ID_MOUVEMENT", Integer.valueOf(1)); |
if (rowFourn.getTable().getTable("ECRITURE").contains("CODE_CLIENT")) { |
this.putValue("CODE_CLIENT", rowFourn.getString("CODE")); |
} |
// on cree un nouveau mouvement |
if (this.idMvt == 1) { |
getNewMouvement(GenerationMvtAvoirFournisseur.source, this.idAvoirFourn, 1, "Avoir Fournisseur : " + avoirRow.getString("NUMERO")); |
87,6 → 89,7 |
} |
} |
} |
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteAchat)); |
this.putValue("DEBIT", Long.valueOf(0)); |
this.putValue("CREDIT", Long.valueOf(prixHT.getLongValue())); |
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementAchat.java |
---|
21,10 → 21,13 |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.request.UpdateBuilder; |
import java.sql.SQLException; |
import java.text.DateFormat; |
import java.text.SimpleDateFormat; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
61,6 → 64,8 |
List<SQLRow> l = regMontantRow.getReferentRows(regMontantRow.getTable().getTable("REGLER_MONTANT_ELEMENT")); |
int mvtSource = -1; |
List<Integer> factureFids = new ArrayList<Integer>(); |
for (SQLRow sqlRow : l) { |
SQLRow mvtEch = sqlRow.getForeignRow("ID_MOUVEMENT_ECHEANCE"); |
if (mvtEch.getID() != mvtSource) { |
69,6 → 74,12 |
mvtSource = mvtEch.getID(); |
} |
} |
if (!sqlRow.isForeignEmpty("ID_ECHEANCE_FOURNISSEUR")) { |
SQLRow ech = sqlRow.getForeign("ID_ECHEANCE_FOURNISSEUR"); |
if (!ech.isForeignEmpty("ID_FACTURE_FOURNISSEUR")) { |
factureFids.add(ech.getForeignID("ID_FACTURE_FOURNISSEUR")); |
} |
} |
} |
SQLRow rowMvtSource = tableMouvement.getRow(mvtSource); |
124,6 → 135,9 |
ajoutEcriture(); |
} |
setDateReglement(regMontantRow.getTable().getTable("FACTURE_FOURNISSEUR"), factureFids, this.date); |
} else { |
Date dateEch = ModeDeReglementSQLElement.calculDate(modeRegRow.getInt("AJOURS"), modeRegRow.getInt("LENJOUR"), this.date); |
141,7 → 155,7 |
// Ajout dans echeance |
Map<String, Object> mEcheance = new HashMap<String, Object>(); |
this.idMvt = getNewMouvement("ECHEANCE_FOURNISSEUR", 1, rowMvtSource.getID(), rowMvtSource.getInt("ID_PIECE")); |
this.idMvt = getNewMouvement(rowMvtSource.getString("SOURCE"), rowMvtSource.getInt("IDSOURCE"), rowMvtSource.getID(), rowMvtSource.getInt("ID_PIECE")); |
mEcheance.put("ID_MOUVEMENT", new Integer(this.idMvt)); |
mEcheance.put("DATE", dateEch); |
162,6 → 176,15 |
} |
} |
private void setDateReglement(SQLTable table, List<Integer> ids, Date d) throws SQLException { |
if (!ids.isEmpty()) { |
UpdateBuilder b = new UpdateBuilder(table); |
b.setObject("DATE_REGLEMENT", d); |
b.setWhere(new Where(table.getKey(), ids)); |
table.getDBSystemRoot().getDataSource().execute(b.asString()); |
} |
} |
private void paiementCheque(Date dateEch, SQLRow rowMvtSource, int idFourn, int idRegMontant) throws SQLException { |
SQLRow regMontantRow = base.getTable("REGLER_MONTANT").getRow(idRegMontant); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java |
---|
26,6 → 26,7 |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.element.SQLElementDirectory; |
import org.openconcerto.sql.model.AliasedTable; |
import org.openconcerto.sql.model.SQLDataSource; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLFieldsSet; |
65,6 → 66,7 |
import java.io.File; |
import java.io.FilenameFilter; |
import java.io.IOException; |
import java.math.BigDecimal; |
import java.math.BigInteger; |
import java.sql.SQLException; |
import java.util.ArrayList; |
124,7 → 126,7 |
SQLRowAccessor row = ListeHistoriquePanel.this.jListePanel.getModel().getRowAt(selectIndex); |
if ((row == null || row.isUndefined()) && undefinedLabel == null) { |
if ((row == null || row.isUndefined()) && ListeHistoriquePanel.this.undefinedLabel == null) { |
return; |
} |
160,10 → 162,53 |
w2 = w2.and(new Where(table.getForeignTable(field.getName()).getField("ID_" + ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName()), "=", id)); |
liste.getListe().getRequest().setWhere(w2.and(w)); |
} else { |
if (liste.getElement().getTable().equals(jListePanel.getModel().getTable())) { |
liste.getListe().getRequest().setWhere(new Where(table.getKey(), "=", id).and(w)); |
if (liste.getElement().getTable().equals(ListeHistoriquePanel.this.jListePanel.getModel().getTable())) { |
final Where whereMatch = new Where(table.getField("ID_" + ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName()), "=", id); |
if ((table.getName().equals("COMMANDE_ELEMENT") || table.getName().equals("BON_RECEPTION_ELEMENT")) |
&& ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName().equals("AFFAIRE")) { |
// FIXME alias forcé à la main, voir pour remplacer avec un |
// selectTransformer |
final String tablePere = table.getName().replaceAll("_ELEMENT", ""); |
AliasedTable tableAlias = new AliasedTable(table.getTable(tablePere), "tAlias__ID_" + tablePere + "__" + tablePere); |
final int idAffaire = id; |
Where wPere = new Where(tableAlias.getField("ID_AFFAIRE"), "=", idAffaire); |
liste.getListe().getRequest().setWhere(whereMatch.or(wPere).and(w)); |
// whereMatch = whereMatch.or(new Where(new |
// AliasedTable(table.getForeignTable("ID_"+tablePere), |
// alias).getField("ID_AFFAIRE"), "=", id)); |
} else { |
liste.getListe().getRequest().setWhere(whereMatch.and(w)); |
} |
} else { |
liste.getListe().getRequest().setWhere(new Where(table.getField("ID_" + ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName()), "=", id).and(w)); |
if ((table.getName().equals("MOUVEMENT_STOCK")) && ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName().equals("AFFAIRE")) { |
final String tableStock = "STOCK"; |
AliasedTable tableAlias = new AliasedTable(table.getTable(tableStock), "tAlias__ID_" + tableStock + "__" + tableStock); |
final int idAffaire = table.getTable("AFFAIRE").getRow(id).getForeignID("ID_DEPOT_STOCK"); |
Where w2 = new Where(table.getField("REEL"), "=", Boolean.TRUE); |
w2 = w2.and(new Where(table.getField("SOURCE"), "=", "")); |
Where wPere = new Where(tableAlias.getField("ID_DEPOT_STOCK"), "=", idAffaire).and(w2); |
liste.getListe().getRequest().setWhere(wPere); |
} else { |
final Where whereMatch = new Where(table.getField("ID_" + ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName()), "=", id); |
if ((table.getName().equals("FACTURE_FOURNISSEUR_ELEMENT") || table.getName().equals("COMMANDE_ELEMENT") || table.getName().equals("BON_RECEPTION_ELEMENT")) |
&& ListeHistoriquePanel.this.jListePanel.getModel().getTable().getName().equals("AFFAIRE")) { |
// FIXME alias forcé à la main, voir pour remplacer avec un |
// selectTransformer |
final String tablePere = table.getName().replaceAll("_ELEMENT", ""); |
AliasedTable tableAlias = new AliasedTable(table.getTable(tablePere), "tAlias__ID_" + tablePere + "__" + tablePere); |
final int idAffaire = id; |
Where wPere = new Where(tableAlias.getField("ID_AFFAIRE"), "=", idAffaire); |
liste.getListe().getRequest().setWhere(whereMatch.or(wPere).and(w).and(new Where(table.getField("PA_HT"), "!=", BigDecimal.ZERO))); |
} else { |
liste.getListe().getRequest().setWhere(whereMatch.and(w)); |
} |
} |
} |
} |
} else { |
342,8 → 387,10 |
} |
}; |
} else { |
} else |
{ |
liste = new ListeAddPanel(elt, new IListe(createTableSource), "historique-" + title) { |
@Override |
protected void handleAction(JButton source, ActionEvent evt) { |
499,7 → 546,7 |
this.addAncestorListener(new AncestorListener() { |
@Override |
public void ancestorAdded(AncestorEvent event) { |
jListePanel.addListSelectionListener(listListener); |
ListeHistoriquePanel.this.jListePanel.addListSelectionListener(ListeHistoriquePanel.this.listListener); |
} |
@Override |
509,7 → 556,7 |
@Override |
public void ancestorRemoved(AncestorEvent event) { |
jListePanel.removeListSelectionListener(listListener); |
ListeHistoriquePanel.this.jListePanel.removeListSelectionListener(ListeHistoriquePanel.this.listListener); |
} |
}); |
547,7 → 594,7 |
public void addListSelectionListener(ListSelectionListener l) { |
this.jListePanel.addListSelectionListener(l); |
System.out.println("ListeHistoriquePanel.addListSelectionListener()" + jListePanel); |
System.out.println("ListeHistoriquePanel.addListSelectionListener()" + this.jListePanel); |
} |
public void removeListSelectionListener(ListSelectionListener l) { |
583,11 → 630,17 |
IListe liste = getIListeFromTableName(tableName); |
List<Integer> listeIds = null; |
if (liste != null) { |
int size = liste.getRowCount(); |
listeIds = new ArrayList<Integer>(size); |
ITableModel m = liste.getModel(); |
int size = m.getRowCount(); |
listeIds = new ArrayList<>(size); |
for (int i = 0; i < size; i++) { |
listeIds.add(liste.idFromIndex(i)); |
try { |
listeIds.add(m.idFromIndex(i)); |
} catch (Exception e) { |
e.printStackTrace(); |
} |
} |
} else { |
listeIds = Collections.emptyList(); |
} |
597,7 → 650,7 |
public void removeAllTableListener() { |
this.jListePanel.removeAllTableListener(); |
for (Integer i : this.mapListener.keySet()) { |
IListPanel panel = vectListePanel.get(i); |
IListPanel panel = this.vectListePanel.get(i); |
List<TableModelListener> l = this.mapListener.get(i); |
for (TableModelListener tableModelListener : l) { |
final IListe liste = panel.getListe(); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/ImportInventairePanel.java |
---|
New file |
0,0 → 1,122 |
/* |
* 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 23 avr. 2012 |
*/ |
package org.openconcerto.erp.core.supplychain.stock.element; |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.model.ConnectionHandlerNoSetup; |
import org.openconcerto.sql.model.SQLDataSource; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.sqlobject.SQLRequestComboBox; |
import org.openconcerto.sql.utils.SQLUtils; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.SwingThreadUtils; |
import org.openconcerto.utils.ExceptionHandler; |
import java.awt.Component; |
import java.awt.FileDialog; |
import java.awt.Frame; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
import java.awt.Window; |
import java.awt.event.ActionEvent; |
import java.io.File; |
import java.io.IOException; |
import java.sql.SQLException; |
import javax.swing.AbstractAction; |
import javax.swing.JButton; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.SwingUtilities; |
public class ImportInventairePanel extends JPanel { |
public ImportInventairePanel(final SQLElement depotElt) { |
super(new GridBagLayout()); |
final SQLRequestComboBox boxDepot = new SQLRequestComboBox(false); |
boxDepot.uiInit(depotElt.createComboRequest()); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
JLabel labelCom = new JLabel("Dépôt "); |
this.add(labelCom, c); |
c.gridx++; |
this.add(boxDepot, c); |
// final JDate dateDeb = new JDate(); |
// this.add(dateDeb, c); |
// c.gridx++; |
// JLabel labelD = new JLabel("Début au"); |
// final JDate dateDebut = new JDate(); |
final JButton buttonValid = new JButton(new AbstractAction("Valider") { |
@Override |
public void actionPerformed(ActionEvent e) { |
SQLRowAccessor row = boxDepot.getSelectedRow(); |
final SQLRowAccessor rowDepot; |
if (row != null && !row.isUndefined()) { |
rowDepot = boxDepot.getSelectedRow(); |
} else { |
rowDepot = depotElt.getTable().getRow(DepotStockSQLElement.DEFAULT_ID); |
} |
((Window) SwingUtilities.getRoot(ImportInventairePanel.this)).dispose(); |
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource()); |
final FileDialog fd = new FileDialog(frame, "Import Inventaire", FileDialog.LOAD); |
fd.setVisible(true); |
if (fd.getFile() != null) { |
final File f = new File(fd.getDirectory(), fd.getFile()); |
if (!f.exists()) { |
JOptionPane.showMessageDialog(null, "Le ficher selectionné n'existe pas", "Erreur", JOptionPane.ERROR_MESSAGE); |
} else if (f.isDirectory()) { |
JOptionPane.showMessageDialog(null, "Le fichier selectionné n'est pas valide", "Erreur", JOptionPane.ERROR_MESSAGE); |
} else { |
new Thread(new Runnable() { |
@Override |
public void run() { |
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter(rowDepot); |
try { |
SQLUtils.executeAtomic(depotElt.getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() { |
@Override |
public Object handle(final SQLDataSource ds) throws SQLException, IOException { |
impoter.importArticles(f, depotElt.getTable().getDBRoot()); |
return null; |
} |
}); |
} catch (Exception e1) { |
ExceptionHandler.handle("Erreur lors de l'importation", e1); |
} |
} |
}).start(); |
} |
} |
} |
}); |
c.gridx++; |
// buttonValid.setEnabled(false); |
this.add(buttonValid, c); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSQLElement.java |
---|
19,11 → 19,8 |
import org.openconcerto.sql.element.GroupSQLComponent; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.model.ConnectionHandlerNoSetup; |
import org.openconcerto.sql.model.SQLDataSource; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.utils.SQLUtils; |
import org.openconcerto.sql.view.IListFrame; |
import org.openconcerto.sql.view.list.IListe; |
import org.openconcerto.sql.view.list.IListeAction.IListeEvent; |
30,16 → 27,10 |
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction; |
import org.openconcerto.sql.view.list.SQLTableModelSource; |
import org.openconcerto.ui.FrameUtil; |
import org.openconcerto.ui.SwingThreadUtils; |
import org.openconcerto.ui.PanelFrame; |
import org.openconcerto.utils.ExceptionHandler; |
import java.awt.Component; |
import java.awt.FileDialog; |
import java.awt.Frame; |
import java.awt.event.ActionEvent; |
import java.io.File; |
import java.io.IOException; |
import java.sql.SQLException; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.List; |
46,7 → 37,6 |
import javax.swing.AbstractAction; |
import javax.swing.JComponent; |
import javax.swing.JOptionPane; |
import javax.swing.JTextField; |
public class EtatStockSQLElement extends ComptaSQLConfElement { |
59,7 → 49,7 |
@Override |
public void actionPerformed(ActionEvent e) { |
EtatStockSnapshotCreator creator = new EtatStockSnapshotCreator(new Date(), getTable().getDBRoot()); |
EtatStockSnapshotCreator creator = new EtatStockSnapshotCreator(getTable().getTable("DEPOT_STOCK").getRow(DepotStockSQLElement.DEFAULT_ID), new Date(), getTable().getDBRoot()); |
creator.create(); |
} |
}, true); |
103,38 → 93,8 |
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Import Inventaire") { |
@Override |
public void actionPerformed(ActionEvent e) { |
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource()); |
final FileDialog fd = new FileDialog(frame, "Import Inventaire", FileDialog.LOAD); |
fd.setVisible(true); |
if (fd.getFile() != null) { |
final File f = new File(fd.getDirectory(), fd.getFile()); |
if (!f.exists()) { |
JOptionPane.showMessageDialog(null, "Le ficher selectionné n'existe pas", "Erreur", JOptionPane.ERROR_MESSAGE); |
} else if (f.isDirectory()) { |
JOptionPane.showMessageDialog(null, "Le fichier selectionné n'est pas valide", "Erreur", JOptionPane.ERROR_MESSAGE); |
} else { |
new Thread(new Runnable() { |
@Override |
public void run() { |
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter(); |
try { |
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() { |
@Override |
public Object handle(final SQLDataSource ds) throws SQLException, IOException { |
impoter.importArticles(f, getTable().getDBRoot()); |
return null; |
} |
}); |
} catch (Exception e1) { |
ExceptionHandler.handle("Erreur lors de l'importation", e1); |
} |
} |
}).start(); |
} |
} |
PanelFrame frame = new PanelFrame(new ImportInventairePanel(getDirectory().getElement(DepotStockSQLElement.class)), "Import inventaire"); |
FrameUtil.showPacked(frame); |
} |
}, true); |
action.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/InventaireFromEtatStockImporter.java |
---|
27,6 → 27,7 |
import org.openconcerto.sql.model.SQLRowValuesListFetcher; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.utils.SQLUtils; |
import org.openconcerto.utils.Tuple2; |
import java.io.File; |
import java.io.IOException; |
45,11 → 46,12 |
public class InventaireFromEtatStockImporter { |
Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>(); |
List<String> codeKits = new ArrayList<String>(); |
private Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>(); |
private List<String> codeKits = new ArrayList<String>(); |
private SQLRowAccessor depot; |
public InventaireFromEtatStockImporter() { |
public InventaireFromEtatStockImporter(SQLRowAccessor depot) { |
this.depot = depot; |
} |
public void importArticles(File file, DBRoot root) throws IOException, SQLException { |
57,7 → 59,7 |
final SQLTable table = root.findTable("ARTICLE"); |
final SQLTable tableArtElt = root.findTable("ARTICLE_ELEMENT"); |
Map<String, SQLRowValues> articles = getArticles(); |
Map<String, Tuple2<SQLRowValues, SQLRowValues>> articles = getArticles(); |
final DataImporter importer = new DataImporter(table) { |
@Override |
81,6 → 83,7 |
SQLRowValues rowVals = new SQLRowValues(table.getTable("ETAT_STOCK")); |
rowVals.put("DATE", today); |
rowVals.put("INVENTAIRE", Boolean.TRUE); |
rowVals.put("ID_DEPOT_STOCK", this.depot.getID()); |
SQLRow rowEtat = rowVals.commit(); |
for (int i = 1; i < m.getRowCount(); i++) { |
95,21 → 98,21 |
final String stringQtyOld = o.get(3).toString(); |
float qtyOld = stringQtyOld.trim().length() == 0 ? 0 : Float.valueOf(stringQtyOld); |
SQLRowValues match = articles.get(code); |
Tuple2<SQLRowValues, SQLRowValues> match = articles.get(code); |
if (match != null) { |
SQLRowAccessor stockValues = match.getForeign("ID_STOCK"); |
SQLRowAccessor stockValues = match.get1(); |
final SQLTable tableMvt = table.getTable("MOUVEMENT_STOCK"); |
SQLRowValues rowValsMvtStockClotureFermeture = new SQLRowValues(tableMvt); |
rowValsMvtStockClotureFermeture.put("QTE", -qtyOld); |
rowValsMvtStockClotureFermeture.put("NOM", "Clôture stock avant inventaire"); |
rowValsMvtStockClotureFermeture.put("ID_ARTICLE", match.getID()); |
rowValsMvtStockClotureFermeture.put("ID_ARTICLE", match.get0().getID()); |
rowValsMvtStockClotureFermeture.put("DATE", today); |
rowValsMvtStockClotureFermeture.put("REEL", Boolean.TRUE); |
rowValsMvtStockClotureFermeture.put("ID_STOCK", stockValues.getID()); |
BigDecimal prc = getPRC(match, Math.round(qtyOld), today); |
BigDecimal prc = getPRC(match.get0(), Math.round(qtyOld), today); |
if (prc == null) { |
prc = BigDecimal.ZERO; |
} |
127,9 → 130,9 |
rowValsItem.put("QTE", qtyOld); |
rowValsItem.put("T_PA", prc.multiply(new BigDecimal(qtyOld))); |
rowValsItem.put("T_PV", BigDecimal.ZERO); |
rowValsItem.put("CODE", match.getString("CODE")); |
rowValsItem.put("NOM", match.getString("NOM")); |
rowValsItem.put("ID_ARTICLE", match.getID()); |
rowValsItem.put("CODE", match.get0().getString("CODE")); |
rowValsItem.put("NOM", match.get0().getString("NOM")); |
rowValsItem.put("ID_ARTICLE", match.get0().getID()); |
rowValsItem.getGraph().store(StoreMode.COMMIT, false); |
SQLRowValues rowValsMvtStockClotureOuverture = new SQLRowValues(tableMvt); |
136,24 → 139,25 |
rowValsMvtStockClotureOuverture.put("QTE", qty); |
rowValsMvtStockClotureOuverture.put("NOM", "Mise en stock inventaire"); |
rowValsMvtStockClotureOuverture.put("ID_ETAT_STOCK", rowEtat.getID()); |
rowValsMvtStockClotureOuverture.put("ID_ARTICLE", match.getID()); |
rowValsMvtStockClotureOuverture.put("ID_ARTICLE", match.get0().getID()); |
rowValsMvtStockClotureOuverture.put("DATE", today); |
rowValsMvtStockClotureOuverture.put("REEL", Boolean.TRUE); |
rowValsMvtStockClotureOuverture.put("ID_STOCK", stockValues.getID()); |
rowValsMvtStockClotureOuverture.put("OUVERTURE", Boolean.TRUE); |
if (tableMvt.contains("PRICE")) { |
rowValsMvtStockClotureOuverture.put("PRICE", getPRC(match, qty.intValue(), today)); |
rowValsMvtStockClotureOuverture.put("PRICE", getPRC(match.get0(), qty.intValue(), today)); |
} |
rowValsMvtStockClotureOuverture.getGraph().store(StoreMode.COMMIT, false); |
if (!match.isForeignEmpty("ID_STOCK")) { |
match.getForeign("ID_STOCK").createEmptyUpdateRow().put("QTE_REEL", qty).commit(); |
} else { |
final SQLRowValues createEmptyUpdateRow = match.createEmptyUpdateRow(); |
createEmptyUpdateRow.putRowValues("ID_STOCK").put("QTE_REEL", qty); |
createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false); |
// if (!match.isForeignEmpty("ID_STOCK")) { |
// match.getForeign("ID_STOCK").createEmptyUpdateRow().put("QTE_REEL", |
// qty).commit(); |
// } else { |
final SQLRowValues createEmptyUpdateRow = match.get1().createEmptyUpdateRow(); |
createEmptyUpdateRow.put("QTE_REEL", qty); |
createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false); |
} |
// } |
} else { |
System.err.println("Aucun article correspondant au code " + code); |
305,7 → 309,7 |
// return result; |
} |
private Map<String, SQLRowValues> getArticles() throws SQLException { |
private Map<String, Tuple2<SQLRowValues, SQLRowValues>> getArticles() throws SQLException { |
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE"); |
SQLRowValues graph = new SQLRowValues(table); |
graph.put("ID", null); |
312,7 → 316,10 |
graph.put("CODE", null); |
graph.put("NOM", null); |
graph.put("NOM", null); |
graph.putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE"); |
final SQLTable foreignTableStock = table.getForeignTable("ID_STOCK"); |
SQLRowValues graphStock = new SQLRowValues(foreignTableStock); |
graphStock.putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE"); |
graphStock.put("ID_ARTICLE", graph); |
final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT"); |
SQLRowValues artElt = new SQLRowValues(tableArtElt); |
320,7 → 327,11 |
artElt.put("QTE", null); |
artElt.put("QTE_UNITAIRE", null); |
artElt.put("ID_ARTICLE_PARENT", graph); |
artElt.putRowValues("ID_ARTICLE").putNulls("ID", "CODE", "NOM").putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE"); |
final SQLRowValues articleParent = artElt.putRowValues("ID_ARTICLE"); |
articleParent.putNulls("ID", "CODE", "NOM"); |
SQLRowValues graphStockItem = new SQLRowValues(foreignTableStock); |
graphStockItem.putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE"); |
graphStockItem.put("ID_ARTICLE", articleParent); |
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph); |
List<SQLRowValues> results = fetcher.fetch(); |
331,11 → 342,24 |
c.set(Calendar.DAY_OF_MONTH, 31); |
Date dEndYear = c.getTime(); |
Map<String, SQLRowValues> vals = new HashMap<String, SQLRowValues>(); |
Map<String, Tuple2<SQLRowValues, SQLRowValues>> vals = new HashMap<String, Tuple2<SQLRowValues, SQLRowValues>>(); |
for (SQLRowValues sqlRowValues : results) { |
final String code = sqlRowValues.getString("CODE"); |
vals.put(code, sqlRowValues); |
Collection<SQLRowValues> stocks = sqlRowValues.getReferentRows(foreignTableStock); |
SQLRowValues rowValsStock = null; |
for (SQLRowValues sqlRowValues2 : stocks) { |
if (sqlRowValues2.getForeignID("ID_DEPOT_STOCK") == depot.getID()) { |
rowValsStock = sqlRowValues2; |
} |
} |
if (rowValsStock == null) { |
rowValsStock = ProductComponent.findOrCreateStock(sqlRowValues, depot).asRowValues(); |
} |
vals.put(code, Tuple2.create(sqlRowValues, rowValsStock)); |
final Set<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT")); |
if (referentRows.size() == 0) { |
// if (!sqlRowValues.isForeignEmpty("ID_STOCK")) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSnapshotCreator.java |
---|
15,6 → 15,7 |
import org.openconcerto.sql.model.DBRoot; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.SQLRowListRSH; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLRowValuesListFetcher; |
27,7 → 28,6 |
import java.math.BigDecimal; |
import java.sql.SQLException; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
37,9 → 37,11 |
private final Date d; |
private final DBRoot root; |
private final SQLRowAccessor depot; |
public EtatStockSnapshotCreator(Date d, DBRoot root) { |
public EtatStockSnapshotCreator(SQLRowAccessor depot, Date d, DBRoot root) { |
this.d = d; |
this.depot = depot; |
this.root = root; |
} |
49,15 → 51,19 |
SQLSelect sel = new SQLSelect(); |
sel.addSelectStar(tableEtatStock); |
Where wEtat = new Where(tableEtatStock.getField("INVENTAIRE"), "=", Boolean.TRUE); |
wEtat = wEtat.and(new Where(tableEtatStock.getField("ID_DEPOT_STOCK"), "=", this.depot.getID())); |
sel.setWhere(wEtat); |
List<SQLRow> rowsEtatStock = SQLRowListRSH.execute(sel); |
Map<Integer, Integer> mapEtatStock = new HashMap<Integer, Integer>(); |
for (SQLRow sqlRow : rowsEtatStock) { |
SQLTable tableMvtStock = this.root.getTable("MOUVEMENT_STOCK"); |
SQLTable tableStock = this.root.getTable("STOCK"); |
SQLSelect selMvt = new SQLSelect(); |
selMvt.addSelect(tableMvtStock.getKey(), "MIN"); |
Where wMvt = new Where(tableMvtStock.getField("OUVERTURE"), "=", Boolean.TRUE); |
wMvt = new Where(tableMvtStock.getField("ID_ETAT_STOCK"), "=", sqlRow.getID()); |
wMvt = wMvt.and(new Where(tableMvtStock.getField("ID_ETAT_STOCK"), "=", sqlRow.getID())); |
wMvt = wMvt.and(new Where(tableMvtStock.getField("ID_STOCK"), "=", tableStock.getKey())); |
wMvt = wMvt.and(new Where(tableStock.getField("ID_DEPOT_STOCK"), "=", depot.getID())); |
selMvt.setWhere(wMvt); |
Integer idMvt = (Integer) tableMvtStock.getDBSystemRoot().getDataSource().executeScalar(selMvt.asString()); |
if (idMvt != null) { |
76,6 → 82,8 |
vals.put("PRICE", null); |
} |
vals.put("ID_ARTICLE", null); |
vals.putRowValues("ID_STOCK").putNulls("QTE_REEL").putRowValues("ID_DEPOT_STOCK").putNulls("ID", "NOM", "CODE"); |
// Calendar cal0116 = Calendar.getInstance(); |
// cal0116.set(2016, Calendar.JANUARY, 1, 0, 0, 0); |
// final Date dateDeb = cal0116.getTime(); |
84,6 → 92,7 |
SQLSelect selEtatD = new SQLSelect(); |
selEtatD.addSelectStar(tableEtatStock); |
Where wEtatD = new Where(tableEtatStock.getField("INVENTAIRE"), "=", Boolean.TRUE); |
wEtatD = wEtatD.and(new Where(tableEtatStock.getField("ID_DEPOT_STOCK"), "=", this.depot.getID())); |
selEtatD.setWhere(wEtatD); |
List<SQLRow> rowsEtatStockD = SQLRowListRSH.execute(selEtatD); |
SQLRow rowEtatStockDeb = null; |
120,6 → 129,7 |
w = w.and(new Where(tableStock.getField("CLOTURE"), "!=", Boolean.TRUE)); |
} |
w = w.and(new Where(tableStock.getField("REEL"), "=", Boolean.TRUE)); |
w = w.and(new Where(sel.getJoin(tableStock.getField("ID_STOCK")).getJoinedTable().getField("ID_DEPOT_STOCK"), "=", depot.getID())); |
sel.setWhere(w); |
return sel; |
150,6 → 160,7 |
SQLRowValues rowVals = new SQLRowValues(tableEtatStock); |
rowVals.put("DATE", d); |
rowVals.put("MONTANT_HA", totalHT); |
rowVals.put("ID_DEPOT_STOCK", depot.getID()); |
for (EtatStock etatItem : mapStockSnap.values()) { |
SQLRowValues rowValsItem = new SQLRowValues(tableEtatStock.getTable("ETAT_STOCK_ELEMENT")); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/credit/component/AvoirFournisseurSQLComponent.java |
---|
110,7 → 110,7 |
} |
} |
vals.put("ID_COMPTE_PCE", idCompteAchat); |
vals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID()); |
vals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxeAchat().getID()); |
vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date())); |
return vals; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/purchase/importer/FacturXExporter.java |
---|
New file |
0,0 → 1,571 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.supplychain.purchase.importer; |
import org.openconcerto.sql.model.DBRoot; |
import java.math.BigDecimal; |
import java.text.DecimalFormat; |
import java.text.DecimalFormatSymbols; |
import java.text.SimpleDateFormat; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.List; |
import java.util.Locale; |
import org.jdom2.Document; |
import org.jdom2.Element; |
import org.jdom2.Namespace; |
import org.jdom2.output.Format; |
import org.jdom2.output.XMLOutputter; |
/** |
* FacturX export (EN 16931 format) |
*/ |
public class FacturXExporter { |
private class Tax { |
// Taux, ex pour 20% : 20.00 |
BigDecimal rate; |
// Montant de la TVA |
BigDecimal amount; |
// montant HT sur lequel s'applique la TVA |
BigDecimal basisAmount; |
} |
public static Namespace QDT_NS = Namespace.getNamespace("qdt", "urn:un:unece:uncefact:data:standard:QualifiedDataType:100"); |
public static Namespace RAM_NS = Namespace.getNamespace("ram", "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"); |
public static Namespace RSM_NS = Namespace.getNamespace("rsm", "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"); |
public static Namespace UDT_NS = Namespace.getNamespace("udt", "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100"); |
public static Namespace XSI_NS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); |
public static void main(String[] args) { |
FacturXExporter ex = new FacturXExporter(); |
System.err.println("FacturXExporter.main() " + ex.checkEAN13("5987854125989")); |
String xml = ex.createXMLFrom(null, 1); |
System.out.println(xml); |
} |
public String createXMLFrom(DBRoot row, int invoiceId) { |
List<Tax> taxes = new ArrayList<>(); |
Tax t1 = new Tax(); |
t1.rate = new BigDecimal("20.0"); |
t1.amount = new BigDecimal("40.0"); |
t1.basisAmount = new BigDecimal("200.0"); |
taxes.add(t1); |
DecimalFormat format = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); |
DecimalFormat fQty = new DecimalFormat("#0.########", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); |
String invoiceNumber = "-"; |
Date invoiceDate = new Date(); |
String regNote = "SARL au capital de 50 000 EUR"; |
String legNote = "RCS MAVILLE 123 456 789"; |
int nbLines = 4; |
final Document doc = new Document(); |
Element root = new Element("CrossIndustryInvoice", RSM_NS); |
root.addNamespaceDeclaration(QDT_NS); |
root.addNamespaceDeclaration(RAM_NS); |
root.addNamespaceDeclaration(RSM_NS); |
root.addNamespaceDeclaration(UDT_NS); |
root.addNamespaceDeclaration(XSI_NS); |
doc.setRootElement(root); |
// ExchangedDocumentContext : Le truc qui s'ecrirait en une ligne si les génies, grands |
// créateurs de cette norme, connaissaient la notion d'attributs... |
Element eDC = new Element("ExchangedDocumentContext", RSM_NS); |
Element bPSDCP = new Element("BusinessProcessSpecifiedDocumentContextParameter", RAM_NS); |
final Element bPSDCP_ID = new Element("ID", RAM_NS); |
// CHORUSPRO specifications: A1 (invoice deposit), A2 (prepaid invoice deposit)... |
bPSDCP_ID.setText("A1"); |
bPSDCP.addContent(bPSDCP_ID); |
eDC.addContent(bPSDCP); |
Element bGSDCP = new Element("GuidelineSpecifiedDocumentContextParameter", RAM_NS); |
final Element bGSDCP_ID = new Element("ID", RAM_NS); |
// For Profile EN 16931 (Comfort): |
bGSDCP_ID.setText("urn:cen.eu:en16931:2017"); |
bGSDCP.addContent(bGSDCP_ID); |
eDC.addContent(bGSDCP); |
root.addContent(eDC); |
// ExchangedDocument |
Element ed = new Element("ExchangedDocument", RSM_NS); |
Element edID = new Element("ID", RAM_NS); |
if (invoiceNumber.length() > 20) { |
// CHORUSPRO: the invoice number is limited to 20 characters (lol) |
invoiceNumber = invoiceNumber.substring(0, 20); |
} |
edID.setText(invoiceNumber); |
ed.addContent(edID); |
Element edTypeCode = new Element("TypeCode", RAM_NS); |
// The types of documents used are: |
// 380: Commercial Invoice |
// 381: Credit note |
// 384: Corrected invoice |
// 389: Self-billied invoice (created by the buyer on behalf of the supplier) |
// 261: Self billed credit note (not accepted by CHORUSPRO) |
// 386: Prepayment invoice |
// 751: Invoice information for accounting purposes (not accepted by CHORUSPRO) |
edTypeCode.setText("380"); |
ed.addContent(edTypeCode); |
Element edIssueDateTime = new Element("IssueDateTime", RAM_NS); |
addDateTime(invoiceDate, edIssueDateTime); |
ed.addContent(edIssueDateTime); |
addIncludedNote(regNote, "REG", ed); |
addIncludedNote(legNote, "ABL", ed); |
// SupplyChainTradeTransaction |
Element eSupplyChainTradeTransaction = new Element("SupplyChainTradeTransaction", RSM_NS); |
for (int i = 0; i < nbLines; i++) { |
String productCode = "a"; |
String productName = "b"; |
BigDecimal pHT = new BigDecimal("12.46"); |
BigDecimal tax = new BigDecimal("0.20"); |
BigDecimal pTTC = new BigDecimal("14.95"); |
BigDecimal qte = new BigDecimal("10.0"); |
BigDecimal totalHTLigne = new BigDecimal("124.60"); |
Element eLineItem = new Element("IncludedSupplyChainTradeLineItem", RAM_NS); |
// AssociatedDocumentLineDocument |
Element eAssociatedDocumentLineDocument = new Element("AssociatedDocumentLineDocument", RAM_NS); |
Element eLineID = new Element("LineID", RAM_NS); |
eLineID.setText(String.valueOf(i + 1)); |
eAssociatedDocumentLineDocument.addContent(eLineID); |
eLineItem.addContent(eAssociatedDocumentLineDocument); |
// SpecifiedTradeProduct |
Element eSpecifiedTradeProduct = new Element("SpecifiedTradeProduct", RAM_NS); |
if (!productCode.isEmpty()) { |
Element eGlobalID = new Element("GlobalID", RAM_NS); |
if (productCode.length() > 40) { |
// CHORUSPRO: this field is limited to 40 characters |
productCode = productCode.substring(0, 40); |
} |
if (checkEAN13(productCode)) { |
// 0088 : EAN |
eGlobalID.setAttribute("schemeID", "0088"); |
} else { |
// 0197 : Not Known |
eGlobalID.setAttribute("schemeID", "0197"); |
} |
eGlobalID.setText(productCode); |
eSpecifiedTradeProduct.addContent(eGlobalID); |
} |
Element eName = new Element("Name", RAM_NS); |
eName.setText(productName); |
eSpecifiedTradeProduct.addContent(eName); |
eLineItem.addContent(eSpecifiedTradeProduct); |
// |
Element eSpecifiedLineTradeAgreement = new Element("SpecifiedLineTradeAgreement", RAM_NS); |
// Prix unitaire TTC |
Element eGrossPriceProductTradePrice = new Element("GrossPriceProductTradePrice", RAM_NS); |
Element eChargeAmount = new Element("ChargeAmount", RAM_NS); |
eChargeAmount.setText(format.format(pTTC)); |
eGrossPriceProductTradePrice.addContent(eChargeAmount); |
Element eAppliedTradeAllowanceCharge = new Element("AppliedTradeAllowanceCharge", RAM_NS); |
Element eChargeIndicator = new Element("ChargeIndicator", RAM_NS); |
Element eIndicator = new Element("ChargeIndicator", UDT_NS); |
// pas de remise |
eIndicator.setText("false"); |
eChargeIndicator.addContent(eIndicator); |
eAppliedTradeAllowanceCharge.addContent(eChargeIndicator); |
Element eActualAmount = new Element("ActualAmount", RAM_NS); |
// Montant de TVA (unitaire) |
eActualAmount.setText(format.format(pTTC.subtract(pHT))); |
eAppliedTradeAllowanceCharge.addContent(eActualAmount); |
eGrossPriceProductTradePrice.addContent(eAppliedTradeAllowanceCharge); |
eSpecifiedLineTradeAgreement.addContent(eGrossPriceProductTradePrice); |
// Prix unitaire HT |
Element eNetPriceProductTradePrice = new Element("NetPriceProductTradePrice", RAM_NS); |
Element eChargeAmountHT = new Element("ChargeAmount", RAM_NS); |
eChargeAmountHT.setText(format.format(pHT)); |
eNetPriceProductTradePrice.addContent(eChargeAmountHT); |
eSpecifiedLineTradeAgreement.addContent(eNetPriceProductTradePrice); |
eLineItem.addContent(eSpecifiedLineTradeAgreement); |
// Quantité |
Element eSpecifiedLineTradeDelivery = new Element("SpecifiedLineTradeDelivery", RAM_NS); |
// LTR = Liter (1 dm3), MTQ = cubic meter , KGM = Kilogram , MTR = Meter , C62 = Unit , |
// TNE = Tonne |
// TODO : gerer les unités |
Element eBilledQuantity = new Element("BilledQuantity", RAM_NS); |
eBilledQuantity.setAttribute("unitCode", "C62"); |
eBilledQuantity.setText(fQty.format(qte)); |
eSpecifiedLineTradeDelivery.addContent(eBilledQuantity); |
eLineItem.addContent(eSpecifiedLineTradeDelivery); |
Element eSpecifiedLineTradeSettlement = new Element("SpecifiedLineTradeSettlement", RAM_NS); |
Element eApplicableTradeTaxt = new Element("ApplicableTradeTax", RAM_NS); |
Element eTypeCode = new Element("TypeCode", RAM_NS); |
eTypeCode.setText("VAT"); |
eApplicableTradeTaxt.addContent(eTypeCode); |
// S = Taux de TVA standard |
// E = Exempté de TVA |
// AE = Autoliquidation de TVA |
// K = Autoliquidation pour cause de livraison intracommunautaire |
// G = Exempté de TVA pour Export hors UE |
// O = Hors du périmètre d'application de la TVA |
// L = Iles Canaries |
// M = Ceuta et Mellila |
// TODO : TVA 0 |
Element eCategoryCode = new Element("CategoryCode", RAM_NS); |
eCategoryCode.setText("S"); |
eApplicableTradeTaxt.addContent(eCategoryCode); |
Element eRateApplicablePercent = new Element("RateApplicablePercent", RAM_NS); |
// 20% -> 20.0 |
eRateApplicablePercent.setText(format.format(tax.multiply(new BigDecimal(100)))); |
eApplicableTradeTaxt.addContent(eRateApplicablePercent); |
eSpecifiedLineTradeSettlement.addContent(eApplicableTradeTaxt); |
Element eSpecifiedTradeSettlementLineMonetarySummation = new Element("SpecifiedTradeSettlementLineMonetarySummation", RAM_NS); |
// Total HT |
Element eLineTotalAmount = new Element("LineTotalAmount", RAM_NS); |
eLineTotalAmount.setText(format.format(totalHTLigne)); |
eSpecifiedTradeSettlementLineMonetarySummation.addContent(eLineTotalAmount); |
eSpecifiedLineTradeSettlement.addContent(eSpecifiedTradeSettlementLineMonetarySummation); |
eLineItem.addContent(eSpecifiedLineTradeSettlement); |
// |
eSupplyChainTradeTransaction.addContent(eLineItem); |
} |
addApplicableHeader(eSupplyChainTradeTransaction, taxes); |
ed.addContent(eSupplyChainTradeTransaction); |
root.addContent(ed); |
final XMLOutputter xmlOutput = new XMLOutputter(); |
xmlOutput.setFormat(Format.getPrettyFormat()); |
return xmlOutput.outputString(doc); |
} |
public void addValue(Element parent, Element element, String value) { |
element.setText(value); |
parent.addContent(element); |
} |
private void addApplicableHeader(Element eSupplyChainTradeTransaction, List<Tax> taxes) { |
// |
// ApplicableHeaderTradeAgreement |
// |
final Element eApplicableHeaderTradeAgreement = new Element("ApplicableHeaderTradeAgreement", RAM_NS); |
addSupplierInfo(eApplicableHeaderTradeAgreement); |
addBuyerInfo(eApplicableHeaderTradeAgreement); |
String orderRef = ""; |
String contractRef = ""; |
// Date de livraison, facultative |
Date effectiveDeliveryDate = new Date(65454654); |
String invoiceNumber = "FA-2017-0010"; |
String currencyCode = "EUR"; |
String dueDescription = "30% d'acompte, solde à 30 j"; |
Date dueDate = new Date(65455654); |
final Element eBuyerOrderReferencedDocument = new Element("BuyerOrderReferencedDocument", RAM_NS); |
addValue(eBuyerOrderReferencedDocument, new Element("IssuerAssignedID", RAM_NS), orderRef); |
eApplicableHeaderTradeAgreement.addContent(eBuyerOrderReferencedDocument); |
final Element eContractReferencedDocument = new Element("ContractReferencedDocument", RAM_NS); |
addValue(eContractReferencedDocument, new Element("IssuerAssignedID", RAM_NS), contractRef); |
eApplicableHeaderTradeAgreement.addContent(eContractReferencedDocument); |
eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeAgreement); |
// |
// ApplicableHeaderTradeDelivery |
// |
final Element eApplicableHeaderTradeDelivery = new Element("ApplicableHeaderTradeDelivery", RAM_NS); |
// <ram:ShipToTradeParty> |
// <ram:PostalTradeAddress> |
// <ram:PostcodeCode>69001</ram:PostcodeCode> |
// <ram:LineOne>35 rue de la République</ram:LineOne> |
// <ram:CityName>Lyon</ram:CityName> |
// <ram:CountryID>FR</ram:CountryID> |
// </ram:PostalTradeAddress> |
// </ram:ShipToTradeParty> |
if (effectiveDeliveryDate != null) { |
// Date de livraison effective (facultative) |
final Element eActualDeliverySupplyChainEvent = new Element("ActualDeliverySupplyChainEvent", RAM_NS); |
final Element eOccurrenceDateTime = new Element("OccurrenceDateTime", RAM_NS); |
addDateTime(effectiveDeliveryDate, eOccurrenceDateTime); |
eActualDeliverySupplyChainEvent.addContent(eOccurrenceDateTime); |
eApplicableHeaderTradeDelivery.addContent(eActualDeliverySupplyChainEvent); |
} |
eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeDelivery); |
// |
// ApplicableHeaderTradeSettlement |
// |
final Element eApplicableHeaderTradeSettlement = new Element("ApplicableHeaderTradeSettlement", RAM_NS); |
addValue(eApplicableHeaderTradeSettlement, new Element("PaymentReference", RAM_NS), invoiceNumber); |
addValue(eApplicableHeaderTradeSettlement, new Element("InvoiceCurrencyCode", RAM_NS), currencyCode); |
final Element aSpecifiedTradeSettlementPaymentMeans = new Element("SpecifiedTradeSettlementPaymentMeans", RAM_NS); |
// <ram:TypeCode>30</ram:TypeCode> |
// <ram:Information>Virement sur compte Banque Fiducial</ram:Information> |
// <ram:PayeePartyCreditorFinancialAccount> |
// <ram:IBANID>FR2012421242124212421242124</ram:IBANID> |
// </ram:PayeePartyCreditorFinancialAccount> |
// <ram:PayeeSpecifiedCreditorFinancialInstitution> |
// <ram:BICID>FIDCFR21XXX</ram:BICID> |
// </ram:PayeeSpecifiedCreditorFinancialInstitution> |
eApplicableHeaderTradeSettlement.addContent(aSpecifiedTradeSettlementPaymentMeans); |
DecimalFormat format = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); |
for (Tax t : taxes) { |
final Element aApplicableTradeTax = new Element("ApplicableTradeTax", RAM_NS); |
// Montant de la TVA |
addValue(aApplicableTradeTax, new Element("CalculatedAmount", RAM_NS), format.format(t.amount)); |
// LOL |
addValue(aApplicableTradeTax, new Element("TypeCode", RAM_NS), "VAT"); |
// montant HT sur lequel s'applique la TVA |
addValue(aApplicableTradeTax, new Element("BasisAmount", RAM_NS), format.format(t.basisAmount)); |
// S = Taux de TVA standard |
// E = Exempté de TVA |
// AE = Autoliquidation de TVA |
// K = Autoliquidation pour cause de livraison intracommunautaire |
// G = Exempté de TVA pour Export hors UE |
// O = Hors du périmètre d'application de la TVA |
// L = Iles Canaries |
// M = Ceuta et Mellila |
// TODO : TVA 0 |
addValue(aApplicableTradeTax, new Element("CategoryCode", RAM_NS), "S"); |
// TODO : type de TVA : |
// 5 : Date de la facture (TVA sur DEBITS) |
// 29 : Date de livraison (TVA sur DEBITS) |
// 72 : Date de paiement (TVA sur ENCAISSEMENTS) |
addValue(aApplicableTradeTax, new Element("DueDateTypeCode", RAM_NS), "5"); |
addValue(aApplicableTradeTax, new Element("RateApplicablePercent", RAM_NS), format.format(t.rate)); |
eApplicableHeaderTradeSettlement.addContent(aApplicableTradeTax); |
} |
final Element eSpecifiedTradePaymentTerms = new Element("SpecifiedTradePaymentTerms", RAM_NS); |
addValue(eSpecifiedTradePaymentTerms, new Element("Description", RAM_NS), dueDescription); |
final Element eDueDateDateTime = new Element("DueDateDateTime", RAM_NS); |
addDateTime(dueDate, eDueDateDateTime); |
eSpecifiedTradePaymentTerms.addContent(eDueDateDateTime); |
eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradePaymentTerms); |
final Element eSpecifiedTradeSettlementHeaderMonetarySummation = new Element("SpecifiedTradeSettlementHeaderMonetarySummation", RAM_NS); |
// Total HT |
// <ram:LineTotalAmount>624.90</ram:LineTotalAmount> |
// Total HT sur leque est appliqué la TVA |
// <ram:TaxBasisTotalAmount>624.90</ram:TaxBasisTotalAmount> |
// Total des TVA |
// <ram:TaxTotalAmount currencyID="EUR">46.25</ram:TaxTotalAmount> |
// Total TTC |
// <ram:GrandTotalAmount>671.15</ram:GrandTotalAmount> |
// Montant déjà payé |
// <ram:TotalPrepaidAmount>201.00</ram:TotalPrepaidAmount> |
// Reste à payer |
// <ram:DuePayableAmount>470.15</ram:DuePayableAmount> |
eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradeSettlementHeaderMonetarySummation); |
eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeSettlement); |
} |
private void addBuyerInfo(final Element eApplicableHeaderTradeAgreement) { |
// Acheteur |
String buyerName = "Ma jolie boutique"; |
String buyerSIRET = "78787878400035"; |
String buyerVAT = "FR19787878784"; |
String buyerContactName = "Alexandre Payet"; |
String buyerPhone = "+33 4 72 07 08 67"; |
String buyerEmail = "alexandre.payet@majolieboutique.net"; |
String buyerAddrL1 = "35 rue de la République"; |
String buyerAddrL2 = ""; |
String buyerAddrL3 = ""; |
String buyerPostalCode = "69001"; |
String buyerCity = "Lyon"; |
String buyerCountryCode = "FR"; |
final Element eBuyerTradeParty = new Element("BuyerTradeParty", RAM_NS); |
this.addValue(eBuyerTradeParty, new Element("Name", RAM_NS), buyerName); |
final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS); |
Element eSpecifiedLegalOrganizationId = new Element("ID", RAM_NS); |
eSpecifiedLegalOrganizationId.setAttribute("schemeID", "0002"); |
eSpecifiedLegalOrganizationId.setText(buyerSIRET); |
eSpecifiedLegalOrganization.addContent(eSpecifiedLegalOrganizationId); |
eBuyerTradeParty.addContent(eSpecifiedLegalOrganization); |
// Contact |
final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS); |
addValue(eDefinedTradeContact, new Element("PersonName", RAM_NS), buyerContactName); |
final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS); |
addValue(eTelephoneUniversalCommunication, new Element("CompleteNumber", RAM_NS), buyerPhone); |
eDefinedTradeContact.addContent(eTelephoneUniversalCommunication); |
final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS); |
final Element eURIID = new Element("URIID", RAM_NS); |
eURIID.setAttribute("schemeID", "SMTP"); |
eURIID.setText(buyerEmail); |
eEmailURIUniversalCommunication.addContent(eURIID); |
eDefinedTradeContact.addContent(eEmailURIUniversalCommunication); |
eBuyerTradeParty.addContent(eDefinedTradeContact); |
// Adresse postale |
final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS); |
addValue(ePostalTradeAddress, new Element("LineOne>", RAM_NS), buyerAddrL1); |
if (buyerAddrL2 != null && !buyerAddrL2.trim().isEmpty()) { |
addValue(ePostalTradeAddress, new Element("LineTwo>", RAM_NS), buyerAddrL2); |
} |
if (buyerAddrL3 != null && !buyerAddrL3.trim().isEmpty()) { |
addValue(ePostalTradeAddress, new Element("LineThree>", RAM_NS), buyerAddrL3); |
} |
addValue(ePostalTradeAddress, new Element("PostcodeCode>", RAM_NS), buyerPostalCode); |
addValue(ePostalTradeAddress, new Element("CityName>", RAM_NS), buyerCity); |
addValue(ePostalTradeAddress, new Element("CountryID>", RAM_NS), buyerCountryCode); |
eBuyerTradeParty.addContent(ePostalTradeAddress); |
// TVA |
final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS); |
final Element eSpecifiedTaxRegistrationId = new Element("ID", RAM_NS); |
eSpecifiedTaxRegistrationId.setAttribute("schemeID", "VA"); |
eSpecifiedTaxRegistrationId.setText(buyerVAT); |
eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationId); |
eBuyerTradeParty.addContent(eSpecifiedTaxRegistration); |
eApplicableHeaderTradeAgreement.addContent(eBuyerTradeParty); |
} |
private void addSupplierInfo(final Element eApplicableHeaderTradeAgreement) { |
String supplierName = "Au bon moulin"; |
String supplierSIRET = "121321321321"; |
String supplierContactName = "Tony Dubois"; |
String supplierContactPhone = "+33 4 72 07 08 56"; |
String supplierContactEmail = "tony.dubois@aubonmoulin.fr"; |
String supplierAddrL1 = "3 rue du pont"; |
String supplierAddrL2 = ""; |
String supplierAddrL3 = ""; |
String supplierAddrPostalCode = "80100"; |
String supplierAddrCityName = "Abbeville"; |
String supplierAddrCountryID = "FR"; |
String supplierNumTVA = "FR121321321321"; |
// Vendeur |
final Element eSellerTradeParty = new Element("SellerTradeParty", RAM_NS); |
addValue(eSellerTradeParty, new Element("Name", RAM_NS), supplierName); |
final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS); |
final Element eID = new Element("ID", RAM_NS); |
eID.setAttribute("schemeID", "0002"); |
eID.setText(supplierSIRET); |
eSpecifiedLegalOrganization.addContent(eID); |
eSellerTradeParty.addContent(eSpecifiedLegalOrganization); |
final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS); |
final Element ePersonName = new Element("PersonName", RAM_NS); |
ePersonName.setText(supplierContactName); |
eDefinedTradeContact.addContent(ePersonName); |
final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS); |
final Element eCompleteNumber = new Element("CompleteNumber", RAM_NS); |
eCompleteNumber.setText(supplierContactPhone); |
eTelephoneUniversalCommunication.addContent(eCompleteNumber); |
eDefinedTradeContact.addContent(eTelephoneUniversalCommunication); |
final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS); |
final Element eURIID = new Element("URIID", RAM_NS); |
eURIID.setAttribute("schemeID", "SMTP"); |
eURIID.setText(supplierContactEmail); |
eEmailURIUniversalCommunication.addContent(eURIID); |
eDefinedTradeContact.addContent(eEmailURIUniversalCommunication); |
eSellerTradeParty.addContent(eDefinedTradeContact); |
final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS); |
addValue(ePostalTradeAddress, new Element("LineOne", RAM_NS), supplierAddrL1); |
if (supplierAddrL2 != null && !supplierAddrL2.trim().isEmpty()) { |
addValue(ePostalTradeAddress, new Element("LineTwo", RAM_NS), supplierAddrL2); |
} |
if (supplierAddrL3 != null && !supplierAddrL3.trim().isEmpty()) { |
addValue(ePostalTradeAddress, new Element("LineThree", RAM_NS), supplierAddrL3); |
} |
addValue(ePostalTradeAddress, new Element("PostcodeCode", RAM_NS), supplierAddrPostalCode); |
addValue(ePostalTradeAddress, new Element("CityName", RAM_NS), supplierAddrCityName); |
addValue(ePostalTradeAddress, new Element("CountryID", RAM_NS), supplierAddrCountryID); |
eSellerTradeParty.addContent(ePostalTradeAddress); |
final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS); |
final Element eSpecifiedTaxRegistrationID = new Element("ID", RAM_NS); |
eSpecifiedTaxRegistrationID.setAttribute("schemeID", "VA"); |
eSpecifiedTaxRegistrationID.setText(supplierNumTVA); |
eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationID); |
eSellerTradeParty.addContent(eSpecifiedTaxRegistration); |
eApplicableHeaderTradeAgreement.addContent(eSellerTradeParty); |
} |
private void addIncludedNote(String content, String code, Element ed) { |
final Element e = new Element("IncludedNote", RAM_NS); |
final Element eContent = new Element("Content", RAM_NS); |
eContent.setText(content); |
e.addContent(eContent); |
final Element eCode = new Element("SubjectCode", RAM_NS); |
eCode.setText(code); |
e.addContent(eCode); |
ed.addContent(e); |
} |
private void addDateTime(Date date, Element eTime) { |
final Element e = new Element("DateTimeString", UDT_NS); |
// From the doc : Only value "102" ... |
e.setAttribute("format", "102"); |
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd"); |
e.setText(s.format(date)); |
eTime.addContent(e); |
} |
boolean checkEAN13(String code) { |
if (code == null || code.length() != 13) { |
return false; |
} |
int checkdigit = 0; |
for (int i = 1; i < 12; i += 2) { |
checkdigit += Integer.valueOf(code.substring(i, i + 1)); |
} |
checkdigit *= 3; |
for (int i = 0; i < 11; i += 2) { |
checkdigit += Integer.valueOf(code.substring(i, i + 1)); |
} |
checkdigit %= 10; |
if (checkdigit != 0) { |
checkdigit = 10 - checkdigit; |
} |
return Integer.valueOf(code.substring(12, 13)).intValue() == checkdigit; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/FactureFournisseurSQLComponent.java |
---|
21,6 → 21,7 |
import org.openconcerto.erp.core.common.ui.TotalPanel; |
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement; |
import org.openconcerto.erp.core.finance.accounting.model.CurrencyConverter; |
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent; |
import org.openconcerto.erp.core.finance.tax.model.TaxeCache; |
import org.openconcerto.erp.core.supplychain.order.ui.FactureFournisseurItemTable; |
import org.openconcerto.erp.generationDoc.gestcomm.FactureFournisseurXmlSheet; |
64,6 → 65,7 |
import java.util.Set; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.JScrollPane; |
import javax.swing.JTextField; |
393,7 → 395,11 |
c.gridy++; |
c.weighty = 0; |
this.add(getBottomPanel(), c); |
ModeDeReglementSQLComponent modeReglComp; |
modeReglComp = (ModeDeReglementSQLComponent) this.eltModeRegl.getSQLChild(); |
modeReglComp.addDateCompListener(this.dateCommande); |
c.gridx = 0; |
c.gridy++; |
c.fill = GridBagConstraints.HORIZONTAL; |
698,6 → 704,9 |
totalTTC.updateTotal(); |
} |
}); |
ModeDeReglementSQLComponent modeReglComp = (ModeDeReglementSQLComponent) this.eltModeRegl.getSQLChild(); |
modeReglComp.addDateCompListener(this.dateCommande); |
return panel; |
} |
736,16 → 745,27 |
this.table.updateField("ID_FACTURE_FOURNISSEUR", row.getID()); |
this.table.createArticle(getSelectedID(), this.getElement()); |
int idMvt = (row.getObject("ID_MOUVEMENT") == null ? 1 : row.getInt("ID_MOUVEMENT")); |
System.err.println("__________***************** UPDATE" + idMvt); |
boolean createCompte = (rowFactureOld.getForeignID("ID_FOURNISSEUR") != row.getForeignID("ID_FOURNISSEUR")); |
createCompte = createCompte || (rowFactureOld.getForeignID("ID_COMPTE_PCE") != row.getForeignID("ID_COMPTE_PCE")); |
createCompte = createCompte || rowFactureOld.getLong("T_TTC") != row.getLong("T_TTC"); |
createCompte = createCompte || rowFactureOld.getLong("T_TVA") != row.getLong("T_TVA"); |
createCompte = createCompte || rowFactureOld.getLong("T_HT") != row.getLong("T_HT"); |
if (!createCompte) { |
int a = JOptionPane.showConfirmDialog(null, "Voulez vous recréer la comptabilité ?", "Comptabilité", JOptionPane.YES_NO_OPTION); |
createCompte = a == JOptionPane.YES_OPTION; |
} |
if (createCompte) { |
int idMvt = (row.getObject("ID_MOUVEMENT") == null ? 1 : row.getInt("ID_MOUVEMENT")); |
System.err.println("__________***************** UPDATE" + idMvt); |
// on supprime tout ce qui est lié à la facture |
EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE"); |
eltEcr.archiveMouvementProfondeur(idMvt, false); |
if (idMvt > 1) { |
new GenerationMvtFactureFournisseur(row, idMvt); |
} else { |
new GenerationMvtFactureFournisseur(row); |
// on supprime tout ce qui est lié à la facture |
EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE"); |
eltEcr.archiveMouvementProfondeur(idMvt, false); |
if (idMvt > 1) { |
new GenerationMvtFactureFournisseur(row, idMvt); |
} else { |
new GenerationMvtFactureFournisseur(row); |
} |
} |
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(row); |
sheet.createDocumentAsynchronous(); |
923,7 → 943,10 |
if (idFacture > 1) { |
SQLRow row = fact.getTable().getRow(idFacture); |
SQLRowValues rowVals = new SQLRowValues(fact.getTable()); |
rowVals.put("ID_FOURNISSEUR", row.getInt("ID_FOURNISSEUR")); |
rowVals.put("ID_FOURNISSEUR", row.getForeignID("ID_FOURNISSEUR")); |
if (!row.isForeignEmpty("ID_COMPTE_PCE")) { |
rowVals.put("ID_COMPTE_PCE", row.getForeignID("ID_COMPTE_PCE")); |
} |
// if (getTable().contains("ID_NUMEROTATION_AUTO")) { |
// rowVals.put("NUMERO", |
// NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/SaisieAchatSQLComponent.java |
---|
329,7 → 329,7 |
this.addSQLObject(this.comboAvoir, "ID_AVOIR_FOURNISSEUR"); |
this.addSQLObject(this.checkImmo, "IMMO"); |
this.montant.setChoixTaxe(TaxeCache.getCache().getFirstTaxe().getID()); |
this.montant.setChoixTaxe(TaxeCache.getCache().getFirstTaxeAchat().getID()); |
this.nomFournisseur.addModelListener("wantedID", this.listenerModeReglDefaut); |
496,7 → 496,7 |
} |
} |
vals.put("ID_COMPTE_PCE", idCompteAchat); |
vals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID()); |
vals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxeAchat().getID()); |
return vals; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java |
---|
91,6 → 91,8 |
import javax.swing.event.TableModelEvent; |
import javax.swing.event.TableModelListener; |
import com.ibm.icu.math.BigDecimal; |
public class CommandeSQLComponent extends TransfertBaseSQLComponent { |
private CommandeItemTable table = new CommandeItemTable(); |
1187,6 → 1189,9 |
final SQLRowValues rowVals = rowElt.createUpdateRow(); |
rowVals.clearPrimaryKeys(); |
rowVals.put("RECU", Boolean.FALSE); |
rowVals.put("RECU_FORCED", Boolean.FALSE); |
rowVals.put("QTE_RECUE", BigDecimal.ZERO); |
this.table.getModel().addRow(rowVals); |
final int rowIndex = this.table.getModel().getRowCount() - 1; |
this.table.getModel().fireTableModelModified(rowIndex); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/table/ChiffrageCommandeTable.java |
---|
65,12 → 65,25 |
final SQLTableElement tableElementNom = new SQLTableElement(e.getTable().getField("NOM")); |
list.add(tableElementNom); |
if (e.getTable().contains("ID_TYPE_CMD")) { |
final SQLTableElement cat = new SQLTableElement(e.getTable().getField("ID_TYPE_CMD")); |
list.add(cat); |
} |
if (e.getTable().contains("ID_CATEGORIE_HEURE")) { |
final SQLTableElement cat = new SQLTableElement(e.getTable().getField("ID_CATEGORIE_HEURE")); |
list.add(cat); |
} |
final SQLTableElement fam = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE")); |
list.add(fam); |
final SQLField fieldHA = e.getTable().getField("PA_HT"); |
final DeviseNumericCellEditor editorPAHT = new DeviseNumericCellEditor(fieldHA); |
final SQLTableElement pa = new SQLTableElement(fieldHA, BigDecimal.class, editorPAHT); |
pa.setRenderer(new DeviseTableCellRenderer()); |
if (e.getTable().contains("ID_CATEGORIE_HEURE")) { |
pa.setEditable(false); |
} |
list.add(pa); |
final SQLField fieldPV = e.getTable().getField("PV_HT"); |
87,7 → 100,29 |
}; |
qteU.setRenderer(new DeviseTableCellRenderer()); |
list.add(qteU); |
if (e.getTable().contains("ANT")) { |
SQLTableElement ant = new SQLTableElement(e.getTable().getField("ANT"), BigDecimal.class) { |
protected Object getDefaultNullValue() { |
return BigDecimal.ZERO; |
} |
}; |
ant.setRenderer(new DeviseTableCellRenderer()); |
list.add(ant); |
} |
if (e.getTable().contains("RESTANT")) { |
SQLTableElement restant = new SQLTableElement(e.getTable().getField("RESTANT"), BigDecimal.class) { |
protected Object getDefaultNullValue() { |
return BigDecimal.ZERO; |
} |
}; |
restant.setRenderer(new DeviseTableCellRenderer()); |
list.add(restant); |
} |
final SQLTableElement unit = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE")); |
list.add(unit); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/FactureFournisseurSQLElement.java |
---|
19,17 → 19,27 |
import org.openconcerto.erp.generationDoc.gestcomm.FactureFournisseurXmlSheet; |
import org.openconcerto.erp.model.MouseSheetXmlListeListener; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.model.FieldPath; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.graph.Path; |
import org.openconcerto.sql.view.EditFrame; |
import org.openconcerto.sql.view.EditPanel; |
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn; |
import org.openconcerto.sql.view.list.IListe; |
import org.openconcerto.sql.view.list.RowAction; |
import org.openconcerto.sql.view.list.SQLTableModelSource; |
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.table.PercentTableCellRenderer; |
import org.openconcerto.utils.CollectionUtils; |
import org.openconcerto.utils.DecimalUtils; |
import org.openconcerto.utils.ListMap; |
import java.awt.event.ActionEvent; |
import java.math.BigDecimal; |
import java.math.RoundingMode; |
import java.util.ArrayList; |
import java.util.Collection; |
import java.util.HashSet; |
import java.util.List; |
import java.util.Set; |
82,6 → 92,7 |
l.add("T_HT"); |
l.add("T_TTC"); |
l.add("INFOS"); |
l.add("DATE_REGLEMENT"); |
return l; |
} |
100,6 → 111,58 |
return l; |
} |
@Override |
protected void _initTableSource(SQLTableModelSource res) { |
super._initTableSource(res); |
final BaseSQLTableModelColumn colAvancement = new BaseSQLTableModelColumn("Avancement réglement", BigDecimal.class) { |
@Override |
protected Object show_(SQLRowAccessor r) { |
return getAvancement(r); |
} |
@Override |
public Set<FieldPath> getPaths() { |
Path p = new Path(getTable()); |
p = p.add(getTable().getTable("ECHEANCE_FOURNISSEUR")); |
Path p2 = new Path(getTable()); |
p2 = p2.add(getTable().getField("ID_AVOIR_FOURNISSEUR")); |
return CollectionUtils.createSet(new FieldPath(p, "MONTANT"), new FieldPath(p, "REG_COMPTA"), new FieldPath(p, "REGLE"), new FieldPath(p2, "MONTANT_TTC")); |
} |
}; |
res.getColumns().add(colAvancement); |
colAvancement.setRenderer(new PercentTableCellRenderer()); |
} |
private BigDecimal getAvancement(SQLRowAccessor r) { |
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("ECHEANCE_FOURNISSEUR")); |
long totalEch = 0; |
for (SQLRowAccessor row : rows) { |
if (!row.getBoolean("REGLE") && !row.getBoolean("REG_COMPTA")) { |
totalEch += row.getLong("MONTANT"); |
} |
} |
SQLRowAccessor avoir = r.getForeign("ID_AVOIR_FOURNISSEUR"); |
BigDecimal avoirTTC = BigDecimal.ZERO; |
if (avoir != null && !avoir.isUndefined()) { |
avoirTTC = new BigDecimal(avoir.getLong("MONTANT_TTC")); |
} |
final BigDecimal totalAregler = new BigDecimal(r.getLong("T_TTC")).subtract(avoirTTC); |
if (totalAregler.signum() > 0 && totalEch > 0) { |
return totalAregler.subtract(new BigDecimal(totalEch)).divide(totalAregler, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP); |
} else { |
return BigDecimal.ONE.movePointRight(2); |
} |
} |
/* |
* (non-Javadoc) |
* |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandeAchatItemSQLElement.java |
---|
107,7 → 107,7 |
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row); |
rowValsCmdElt.put("ID_STYLE", idNormal); |
rowValsCmdElt.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE); |
rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID()); |
rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxeAchat().getID()); |
rowValsCmdElt.put("ID_DEMANDE_PRIX", rowVals); |
rowValsCmdElt.put("ID_DEMANDE_ACHAT_ELEMENT", row.getID()); |
if (row.getObject("ID_ARTICLE") != null && !row.isForeignEmpty("ID_ARTICLE")) { |
165,7 → 165,7 |
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row); |
rowValsCmdElt.put("ID_STYLE", idNormal); |
rowValsCmdElt.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE); |
rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID()); |
rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxeAchat().getID()); |
rowValsCmdElt.put("ID_COMMANDE", rowVals); |
rowValsCmdElt.put("ID_DEMANDE_ACHAT_ELEMENT", row.getID()); |
if (row.getObject("ID_ARTICLE") != null && !row.isForeignEmpty("ID_ARTICLE")) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesFacturesFournisseurAction.java |
---|
17,12 → 17,17 |
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel; |
import org.openconcerto.erp.core.common.ui.IListTotalPanel; |
import org.openconcerto.erp.core.finance.accounting.ui.ListeGestCommEltPanel; |
import org.openconcerto.erp.core.sales.invoice.ui.DateEnvoiRenderer; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.element.SQLElement; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.view.IListFrame; |
import org.openconcerto.sql.view.list.IListe; |
import org.openconcerto.sql.view.list.SQLTableModelColumn; |
import org.openconcerto.sql.view.list.SQLTableModelColumnPath; |
import org.openconcerto.sql.view.list.SQLTableModelSource; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.utils.cc.IClosure; |
import java.awt.GridBagConstraints; |
import java.util.Arrays; |
31,6 → 36,7 |
import javax.swing.Action; |
import javax.swing.JFrame; |
import javax.swing.table.TableColumn; |
public class ListeDesFacturesFournisseurAction extends CreateFrameAbstractAction { |
44,6 → 50,31 |
ListeGestCommEltPanel panel = new ListeGestCommEltPanel(element); |
panel.setAddVisible(true); |
IListFrame frame = new IListFrame(panel); |
panel.getListe().setModificationAllowed(true); |
SQLTableModelSource src = panel.getListe().getSource(); |
for (SQLTableModelColumn column : src.getColumns()) { |
if (column.getClass().isAssignableFrom(SQLTableModelColumnPath.class)) { |
((SQLTableModelColumnPath) column).setEditable(false); |
} |
} |
final SQLTableModelColumn dateReglCol = src.getColumn(element.getTable().getField("DATE_REGLEMENT")); |
// Edition des dates de reglement |
if (dateReglCol != null) { |
((SQLTableModelColumnPath) dateReglCol).setEditable(true); |
dateReglCol.setColumnInstaller(new IClosure<TableColumn>() { |
@Override |
public void executeChecked(TableColumn columnDateReglement) { |
final org.openconcerto.ui.table.TimestampTableCellEditor cellEditor = new org.openconcerto.ui.table.TimestampTableCellEditor(); |
cellEditor.setAllowNull(true); |
columnDateReglement.setCellEditor(cellEditor); |
columnDateReglement.setCellRenderer(new DateEnvoiRenderer()); |
} |
}); |
} |
IListTotalPanel total = new IListTotalPanel(frame.getPanel().getListe(), Arrays.asList(element.getTable().getField("T_HT"), element.getTable().getField("T_TTC"))); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
c.gridy = 3; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionElementSQLElement.java |
---|
37,7 → 37,7 |
protected List<String> getListFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("ID_STYLE"); |
l.add("ID_BON_RECEPTION"); |
l.add("CODE"); |
l.add("NOM"); |
l.add("PA_HT"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerSQLComponent.java |
---|
16,8 → 16,10 |
import org.openconcerto.erp.core.common.component.AdresseSQLComponent; |
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement; |
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseClientItemTable; |
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement; |
import org.openconcerto.erp.core.sales.product.element.ClientCodeArticleTable; |
import org.openconcerto.erp.core.sales.product.ui.CustomerProductQtyPriceListTable; |
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel; |
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel; |
import org.openconcerto.erp.utils.TM; |
import org.openconcerto.sql.Configuration; |
27,8 → 29,11 |
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.UndefinedRowValuesCache; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.preferences.SQLPreferences; |
import org.openconcerto.sql.sqlobject.JUniqueTextField; |
import org.openconcerto.sql.sqlobject.SQLSearchableTextCombo; |
import org.openconcerto.sql.ui.textmenu.TextFieldWithMenu; |
49,6 → 54,7 |
import java.awt.Component; |
import java.awt.Dimension; |
import java.awt.Font; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
import java.awt.event.ActionEvent; |
70,8 → 76,6 |
import javax.swing.event.DocumentEvent; |
import javax.swing.event.DocumentListener; |
import com.lowagie.text.Font; |
public class CustomerSQLComponent extends GroupSQLComponent { |
private ContactItemTable table; |
private ClientCodeArticleTable tableCustomProduct; |
326,9 → 330,48 |
}); |
} |
} |
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot()); |
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.COMPTE_CLIENT_AUTO, Boolean.FALSE)) { |
createCompteClientFromCodeAuto(id); |
} |
return id; |
} |
private void createCompteClientFromCodeAuto(int idClient) { |
final SQLRow rowClient = getTable().getRow(idClient); |
if (rowClient.isForeignEmpty("ID_COMPTE_PCE")) { |
SQLRowValues rowVals = rowClient.createEmptyUpdateRow(); |
final String text = rowClient.getString("CODE"); |
String compte = "411" + text; |
SQLTable table = getTable().getForeignTable("ID_COMPTE_PCE"); |
SQLSelect selCompte = new SQLSelect(); |
selCompte.addSelectFunctionStar("COUNT"); |
selCompte.setArchivedPolicy(SQLSelect.BOTH); |
selCompte.setWhere(new Where(table.getField("NUMERO"), "LIKE", compte + "%")); |
System.err.println(selCompte.asString()); |
Object o = getTable().getDBRoot().getDBSystemRoot().getDataSource().executeScalar(selCompte.asString()); |
int nb = 0; |
if (o != null) { |
Long i = (Long) o; |
nb = i.intValue(); |
} |
if (nb > 0) { |
compte = compte + nb; |
} |
int idCpt = ComptePCESQLElement.getId(compte, rowClient.getString("NOM")); |
rowVals.put("ID_COMPTE_PCE", idCpt); |
try { |
rowVals.update(); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
} |
} |
private JComponent createAdressesComponent() { |
final JTabbedPane tabbedAdresse = new JTabbedPane() { |
public void insertTab(String title, Icon icon, Component component, String tip, int index) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CustomerGroup.java |
---|
75,6 → 75,7 |
gPayment.addItem("BIC", LayoutHints.DEFAULT_FIELD_HINTS); |
gPayment.addItem("ID_MODE_REGLEMENT", new LayoutHints(true, true, true, true, true, false, true, true)); |
gPayment.addItem("ID_COMPTE_PCE"); |
gPayment.addItem("ID_SEPA_MANDATE_DEFAULT"); |
gPayment.addItem("ENCOURS_MAX"); |
gPayment.addItem("ID_COMPTE_PCE_PRODUIT"); |
gPayment.addItem("ID_COMPTE_PCE_SERVICE"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplate.java |
---|
24,6 → 24,7 |
import java.awt.Container; |
import java.awt.Dimension; |
import java.awt.FlowLayout; |
import java.awt.Font; |
import java.awt.Frame; |
import java.awt.event.ActionEvent; |
import java.awt.event.ActionListener; |
42,8 → 43,6 |
import javax.swing.ListSelectionModel; |
import javax.swing.SwingUtilities; |
import com.lowagie.text.Font; |
public class EmailTemplate { |
private String name; |
private String title; |
137,7 → 136,7 |
if (t.isDefault) { |
l.setFont(l.getFont().deriveFont(Font.BOLD)); |
} else { |
l.setFont(l.getFont().deriveFont(Font.NORMAL)); |
l.setFont(l.getFont().deriveFont(Font.PLAIN)); |
} |
return l; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateSQLComponent.java |
---|
25,7 → 25,7 |
@Override |
protected SQLRowValues createDefaults() { |
final SQLRowValues defaultValues = super.createDefaults(); |
final SQLRowValues defaultValues = new SQLRowValues(getTable()); |
defaultValues.put("FORMAT_DATE", "dd/MM/yyyy"); |
return defaultValues; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmSQLElement.java |
---|
15,6 → 15,7 |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.erp.core.finance.accounting.ui.AnalytiqueItemTable; |
import org.openconcerto.erp.core.finance.accounting.ui.SaisieKmItemTable; |
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm; |
import org.openconcerto.sql.Configuration; |
114,6 → 115,7 |
SQLTable ecrTable = base.getTable("ECRITURE"); |
SQLTable compteTable = base.getTable("COMPTE_PCE"); |
SQLTable saisieKmTable = base.getTable("SAISIE_KM_ELEMENT"); |
SQLTable assocTable = base.getTable("ASSOCIATION_ANALYTIQUE"); |
SQLRowValues vals = new SQLRowValues(base.getTable("SAISIE_KM")); |
vals.put("ID_MOUVEMENT", new Integer(idMvt)); |
152,7 → 154,16 |
valsTmp.put("DEBIT", rowEcrTmp.getObject("DEBIT")); |
valsTmp.put("CREDIT", rowEcrTmp.getObject("CREDIT")); |
valsTmp.put("ID_ECRITURE", new Integer(rowEcrTmp.getID())); |
valsTmp.insert(); |
List<SQLRow> assocRows = rowEcrTmp.getReferentRows(assocTable); |
if (assocRows.size() > 0) { |
for (int a = 0; a < assocRows.size(); a++) { |
assocRows.get(a).createUpdateRow().put("ID_SAISIE_KM_ELEMENT", valsTmp); |
} |
valsTmp.put("ANALYTIQUE", AnalytiqueItemTable.getStringAssocs(valsTmp)); |
} |
valsTmp.commit(); |
} |
Object[] objTmp = (Object[]) myListEcriture.get(0); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/EcritureSQLElement.java |
---|
20,6 → 20,7 |
import org.openconcerto.erp.core.edm.AttachmentAction; |
import org.openconcerto.erp.core.finance.accounting.ui.AssociationAnalytiquePanel; |
import org.openconcerto.erp.core.finance.accounting.ui.ConsultationCompteFrame; |
import org.openconcerto.erp.core.finance.accounting.ui.LettragePanel; |
import org.openconcerto.erp.core.finance.accounting.ui.LettrageRenderer; |
import org.openconcerto.erp.core.finance.accounting.ui.ListEcritureRenderer; |
import org.openconcerto.erp.core.finance.accounting.ui.ListeDesEcrituresPanel; |
100,6 → 101,18 |
consult.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(consult); |
PredicateRowAction interrogation = new PredicateRowAction(new AbstractAction("Interrogation du compte") { |
public void actionPerformed(ActionEvent event) { |
SQLRowAccessor row = IListe.get(event).getSelectedRow(); |
PanelFrame f = new PanelFrame(new LettragePanel(row.getForeignID("ID_COMPTE_PCE")), "Lettrage manuel par compte"); |
f.setVisible(true); |
} |
}, false); |
interrogation.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(interrogation); |
PredicateRowAction contre = new PredicateRowAction(new AbstractAction("Contrepassation") { |
public void actionPerformed(ActionEvent event) { |
EcritureSQLElement.contrePassationPiece(IListe.get(event).getSelectedId()); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/BalanceSheet.java |
---|
14,10 → 14,12 |
package org.openconcerto.erp.core.finance.accounting.report; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.element.objet.Compte; |
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager; |
import org.openconcerto.erp.generationDoc.SheetInterface; |
import org.openconcerto.erp.preferences.PrinterNXProps; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLBase; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowListRSH; |
import org.openconcerto.sql.model.SQLSelect; |
26,6 → 28,7 |
import org.openconcerto.utils.GestionDevise; |
import java.text.DateFormat; |
import java.util.ArrayList; |
import java.util.Calendar; |
import java.util.Date; |
import java.util.HashMap; |
67,7 → 70,7 |
return TEMPLATE_ID; |
} |
public BalanceSheet(Date du, Date au, String compteDeb, String compteEnd, boolean centralClient, boolean centralFourn, boolean centralFournImmo) { |
public BalanceSheet(Date du, Date au, String compteDeb, String compteEnd, boolean centralClient, boolean centralFourn, boolean centralFournImmo, boolean displayAll) { |
super(); |
Calendar cal = Calendar.getInstance(); |
84,7 → 87,7 |
// this.locationPDF = storage.getPDFOutputDirectory(TEMPLATE_ID); |
this.dateAu = au; |
this.dateDu = du; |
this.viewMode = displayAll; |
this.compteDeb = compteDeb; |
this.compteEnd = compteEnd; |
this.centralClient = centralClient; |
121,45 → 124,11 |
this.mapStyleRow.put(new Integer(row), "Titre 1"); |
} |
private boolean viewMode = true; |
protected void createMap() { |
this.mapReplace = new HashMap(); |
this.mCell = new HashMap(); |
this.mapStyleRow = new HashMap(); |
SQLSelect sel = new SQLSelect(); |
sel.addSelect(tableCompte.getField("ID")); |
sel.addSelect(tableEcriture.getField("DEBIT"), "SUM"); |
sel.addSelect(tableEcriture.getField("CREDIT"), "SUM"); |
Where w = (new Where(tableEcriture.getField("DATE"), this.dateDu, this.dateAu)); |
if (dateDu == null) { |
w = (new Where(tableEcriture.getField("DATE"), "<=", this.dateAu)); |
} |
if (compteDeb.equals(this.compteEnd)) { |
w = w.and(new Where(tableCompte.getField("NUMERO"), "=", this.compteDeb)); |
} else { |
w = w.and(new Where(tableCompte.getField("NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd)); |
} |
// FIXME use flag cloture |
Where wCloture = new Where(tableEcriture.getField("NOM"), "NOT LIKE", "Fermeture du compte%"); |
wCloture = wCloture.and(new Where(tableEcriture.getField("DATE"), "=", this.dateAu)); |
wCloture = wCloture.or(new Where(tableEcriture.getField("DATE"), "<", this.dateAu)); |
w = w.and(wCloture); |
sel.setWhere(w); |
String req = sel.asString() + " AND \"ECRITURE\".\"ID_COMPTE_PCE\" = \"COMPTE_PCE\".\"ID\" GROUP BY \"COMPTE_PCE\".\"NUMERO\", \"COMPTE_PCE\".\"ID\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
System.err.println(req); |
List l = (List) base.getDataSource().execute(req, new ArrayListHandler()); |
int posLine = 1; |
int firstLine = 1; |
System.err.println("START CREATE Grand livre, NB ecritures " + l.size()); |
this.nbPage = 0; |
long totalDebit, totalCredit, sousTotalDebit, sousTotalCredit; |
189,160 → 158,279 |
int j = 0; |
String classe = ""; |
SQLSelect selCompte = new SQLSelect(); |
selCompte.addSelectStar(tableCompte); |
List<SQLRow> compteRows = SQLRowListRSH.execute(selCompte); |
Map<Integer, SQLRow> mapCompte = new HashMap<Integer, SQLRow>(); |
for (SQLRow sqlRow : compteRows) { |
mapCompte.put(sqlRow.getID(), sqlRow); |
} |
if (viewMode) { |
getBalance(); |
for (int i = 0; i < l.size();) { |
for (int i = 0; i < this.vecteurCompte.size();) { |
System.err.println("START NEW PAGE; POS : " + posLine); |
System.err.println("START NEW PAGE; POS : " + posLine); |
/*************************************************************************************** |
* ENTETE |
**************************************************************************************/ |
makeEntete(posLine); |
posLine += debutFill - 1; |
/*************************************************************************************** |
* ENTETE |
**************************************************************************************/ |
makeEntete(posLine); |
posLine += debutFill - 1; |
/*************************************************************************************** |
* CONTENU |
**************************************************************************************/ |
for (j = 0; (j < endFill - debutFill + 1) && i < l.size(); j++) { |
Object[] o = (Object[]) l.get(i); |
int idCpt = Integer.parseInt(o[0].toString()); |
// SQLRow rowCpt = tableCompte.getRow(idCpt); |
SQLRow rowCpt = mapCompte.get(idCpt); |
/*************************************************************************************** |
* CONTENU |
**************************************************************************************/ |
for (j = 0; (j < endFill - debutFill + 1) && i < this.vecteurCompte.size(); j++) { |
Compte compte = this.vecteurCompte.get(i); |
String numeroCpt = rowCpt.getString("NUMERO").trim(); |
String nomCpt = rowCpt.getString("NOM"); |
// Changement de classe de compte |
if (classe.trim().length() != 0 && numeroCpt.length() > 0 && !classe.trim().equalsIgnoreCase(numeroCpt.substring(0, 1))) { |
String numeroCpt = compte.getNumero(); |
String nomCpt = compte.getNom(); |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
long deb = compte.getTotalDebit(); |
long cred = compte.getTotalCredit(); |
sousTotalCredit = 0; |
sousTotalDebit = 0; |
classe = numeroCpt.substring(0, 1); |
} else { |
if (classe.trim().length() == 0 && numeroCpt.trim().length() > 0) { |
classe = numeroCpt.substring(0, 1); |
} |
long deb = new Double(o[1].toString()).longValue(); |
long cred = new Double(o[2].toString()).longValue(); |
totalCredit += cred; |
sousTotalCredit += cred; |
totalDebit += deb; |
sousTotalDebit += deb; |
// Centralisation compte client |
if (this.centralClient && (numeroCpt.equalsIgnoreCase("411") || numeroCpt.startsWith("411"))) { |
totalDebitClient += deb; |
totalCreditClient += cred; |
deb = totalDebitClient; |
cred = totalCreditClient; |
this.mCell.put("A" + posLine, numeroCpt); |
this.mCell.put("B" + posLine, nomCpt); |
this.mCell.put("C" + posLine, new Double(GestionDevise.currencyToString(deb, false))); |
this.mCell.put("D" + posLine, new Double(GestionDevise.currencyToString(cred, false))); |
this.mCell.put("E" + posLine, new Double(GestionDevise.currencyToString(deb - cred, false))); |
if (compte.getSousCompte().isEmpty()) { |
this.mapStyleRow.put(new Integer(posLine), "Normal"); |
} else { |
this.mapStyleRow.put(new Integer(posLine), "Titre 1"); |
} |
// Centralisation compte fournisseur immo |
else if (this.centralFournImmo && (numeroCpt.equalsIgnoreCase("404") || numeroCpt.startsWith("404"))) { |
totalDebitFournImmo += deb; |
totalCreditFournImmo += cred; |
deb = totalDebitFournImmo; |
cred = totalCreditFournImmo; |
} |
// Centralisation compte fournisseur |
else if (this.centralFourn && (numeroCpt.equalsIgnoreCase("401") || numeroCpt.startsWith("401"))) { |
totalDebitFourn += deb; |
totalCreditFourn += cred; |
deb = totalDebitFourn; |
cred = totalCreditFourn; |
} |
i++; |
if (this.centralClient && !numeroCpt.equalsIgnoreCase("411") && numeroCpt.startsWith("411")) { |
if (addedLine || !this.centralFournImmo) { |
posLine--; |
j--; |
} else { |
addedLine = true; |
} |
this.mCell.put("A" + posLine, numCptClient); |
this.mCell.put("B" + posLine, nomCptClient); |
} else if (this.centralFourn && !numeroCpt.equalsIgnoreCase("401") && numeroCpt.startsWith("401")) { |
posLine++; |
} |
if (addedLineFourn) { |
posLine--; |
j--; |
} else { |
addedLineFourn = true; |
} |
if (i >= this.vecteurCompte.size() && j < endFill - debutFill + 1) { |
this.mCell.put("A" + posLine, numCptFourn); |
this.mCell.put("B" + posLine, nomCptFourn); |
} else if (this.centralFournImmo && !numeroCpt.equalsIgnoreCase("404") && numeroCpt.startsWith("404")) { |
if (addedLineImmo || !this.centralFourn) { |
posLine--; |
j--; |
} else { |
addedLineImmo = true; |
} |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
} |
this.mCell.put("A" + posLine, numCptFournImmo); |
this.mCell.put("B" + posLine, nomCptFournImmo); |
} else { |
this.mCell.put("A" + posLine, numeroCpt); |
this.mCell.put("B" + posLine, nomCpt); |
} |
posLine = firstLine + endFill; |
/* |
* if (this.mapStyleRow.get(new Integer(posLine - 1)) != null) { |
* this.mapStyleRow.put(new Integer(posLine - 1), "Titre 2"); } |
*/ |
this.mCell.put("C" + posLine, new Double(GestionDevise.currencyToString(deb, false))); |
this.mCell.put("D" + posLine, new Double(GestionDevise.currencyToString(cred, false))); |
this.mCell.put("E" + posLine, new Double(GestionDevise.currencyToString(deb - cred, false))); |
// Total |
this.mCell.put("C" + posLine, ((totalDebit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit, false)))); |
this.mCell.put("D" + posLine, ((totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalCredit, false)))); |
this.mCell.put("E" + posLine, (totalDebit - totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false))); |
this.mapStyleRow.put(new Integer(posLine), "Normal"); |
i++; |
} |
posLine += 2; |
// bas de page |
makePiedPage(posLine); |
posLine++; |
firstLine = posLine; |
this.nbPage++; |
// if (i >= this.vecteurCompte.size() && j >= (endFill - debutFill + 1)) { |
// |
// makeEntete(posLine); |
// posLine += debutFill - 1; |
// |
// makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
// |
// this.nbPage++; |
// } |
} |
} else { |
if (i >= l.size() && j < endFill - debutFill + 1) { |
this.mapReplace = new HashMap(); |
this.mCell = new HashMap(); |
this.mapStyleRow = new HashMap(); |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
SQLSelect sel = new SQLSelect(); |
sel.addSelect(tableCompte.getField("ID")); |
sel.addSelect(tableEcriture.getField("DEBIT"), "SUM"); |
sel.addSelect(tableEcriture.getField("CREDIT"), "SUM"); |
Where w = (new Where(tableEcriture.getField("DATE"), this.dateDu, this.dateAu)); |
if (dateDu == null) { |
w = (new Where(tableEcriture.getField("DATE"), "<=", this.dateAu)); |
} |
posLine = firstLine + endFill; |
/* |
* if (this.mapStyleRow.get(new Integer(posLine - 1)) != null) { |
* this.mapStyleRow.put(new Integer(posLine - 1), "Titre 2"); } |
*/ |
if (compteDeb.equals(this.compteEnd)) { |
w = w.and(new Where(tableCompte.getField("NUMERO"), "=", this.compteDeb)); |
} else { |
w = w.and(new Where(tableCompte.getField("NUMERO"), (Object) this.compteDeb, (Object) this.compteEnd)); |
} |
// Total |
this.mCell.put("C" + posLine, ((totalDebit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit, false)))); |
this.mCell.put("D" + posLine, ((totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalCredit, false)))); |
this.mCell.put("E" + posLine, (totalDebit - totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false))); |
// FIXME use flag cloture |
Where wCloture = new Where(tableEcriture.getField("NOM"), "NOT LIKE", "Fermeture du compte%"); |
wCloture = wCloture.and(new Where(tableEcriture.getField("DATE"), "=", this.dateAu)); |
wCloture = wCloture.or(new Where(tableEcriture.getField("DATE"), "<", this.dateAu)); |
w = w.and(wCloture); |
posLine += 2; |
sel.setWhere(w); |
// bas de page |
makePiedPage(posLine); |
String req = sel.asString() + " AND \"ECRITURE\".\"ID_COMPTE_PCE\" = \"COMPTE_PCE\".\"ID\" GROUP BY \"COMPTE_PCE\".\"NUMERO\", \"COMPTE_PCE\".\"ID\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
posLine++; |
firstLine = posLine; |
this.nbPage++; |
System.err.println(req); |
if (i >= l.size() && j >= (endFill - debutFill + 1)) { |
List l = (List) base.getDataSource().execute(req, new ArrayListHandler()); |
SQLSelect selCompte = new SQLSelect(); |
selCompte.addSelectStar(tableCompte); |
List<SQLRow> compteRows = SQLRowListRSH.execute(selCompte); |
Map<Integer, SQLRow> mapCompte = new HashMap<Integer, SQLRow>(); |
for (SQLRow sqlRow : compteRows) { |
mapCompte.put(sqlRow.getID(), sqlRow); |
} |
for (int i = 0; i < l.size();) { |
System.err.println("START NEW PAGE; POS : " + posLine); |
/*************************************************************************************** |
* ENTETE |
**************************************************************************************/ |
makeEntete(posLine); |
posLine += debutFill - 1; |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
/*************************************************************************************** |
* CONTENU |
**************************************************************************************/ |
for (j = 0; (j < endFill - debutFill + 1) && i < l.size(); j++) { |
Object[] o = (Object[]) l.get(i); |
int idCpt = Integer.parseInt(o[0].toString()); |
// SQLRow rowCpt = tableCompte.getRow(idCpt); |
SQLRow rowCpt = mapCompte.get(idCpt); |
String numeroCpt = rowCpt.getString("NUMERO").trim(); |
String nomCpt = rowCpt.getString("NOM"); |
// Changement de classe de compte |
if (classe.trim().length() != 0 && numeroCpt.length() > 0 && !classe.trim().equalsIgnoreCase(numeroCpt.substring(0, 1))) { |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
sousTotalCredit = 0; |
sousTotalDebit = 0; |
classe = numeroCpt.substring(0, 1); |
} else { |
if (classe.trim().length() == 0 && numeroCpt.trim().length() > 0) { |
classe = numeroCpt.substring(0, 1); |
} |
long deb = new Double(o[1].toString()).longValue(); |
long cred = new Double(o[2].toString()).longValue(); |
totalCredit += cred; |
sousTotalCredit += cred; |
totalDebit += deb; |
sousTotalDebit += deb; |
// Centralisation compte client |
if (this.centralClient && (numeroCpt.equalsIgnoreCase("411") || numeroCpt.startsWith("411"))) { |
totalDebitClient += deb; |
totalCreditClient += cred; |
deb = totalDebitClient; |
cred = totalCreditClient; |
} |
// Centralisation compte fournisseur immo |
else if (this.centralFournImmo && (numeroCpt.equalsIgnoreCase("404") || numeroCpt.startsWith("404"))) { |
totalDebitFournImmo += deb; |
totalCreditFournImmo += cred; |
deb = totalDebitFournImmo; |
cred = totalCreditFournImmo; |
} |
// Centralisation compte fournisseur |
else if (this.centralFourn && (numeroCpt.equalsIgnoreCase("401") || numeroCpt.startsWith("401"))) { |
totalDebitFourn += deb; |
totalCreditFourn += cred; |
deb = totalDebitFourn; |
cred = totalCreditFourn; |
} |
if (this.centralClient && !numeroCpt.equalsIgnoreCase("411") && numeroCpt.startsWith("411")) { |
if (addedLine || !this.centralFournImmo) { |
posLine--; |
j--; |
} else { |
addedLine = true; |
} |
this.mCell.put("A" + posLine, numCptClient); |
this.mCell.put("B" + posLine, nomCptClient); |
} else if (this.centralFourn && !numeroCpt.equalsIgnoreCase("401") && numeroCpt.startsWith("401")) { |
if (addedLineFourn) { |
posLine--; |
j--; |
} else { |
addedLineFourn = true; |
} |
this.mCell.put("A" + posLine, numCptFourn); |
this.mCell.put("B" + posLine, nomCptFourn); |
} else if (this.centralFournImmo && !numeroCpt.equalsIgnoreCase("404") && numeroCpt.startsWith("404")) { |
if (addedLineImmo || !this.centralFourn) { |
posLine--; |
j--; |
} else { |
addedLineImmo = true; |
} |
this.mCell.put("A" + posLine, numCptFournImmo); |
this.mCell.put("B" + posLine, nomCptFournImmo); |
} else { |
this.mCell.put("A" + posLine, numeroCpt); |
this.mCell.put("B" + posLine, nomCpt); |
} |
this.mCell.put("C" + posLine, new Double(GestionDevise.currencyToString(deb, false))); |
this.mCell.put("D" + posLine, new Double(GestionDevise.currencyToString(cred, false))); |
this.mCell.put("E" + posLine, new Double(GestionDevise.currencyToString(deb - cred, false))); |
this.mapStyleRow.put(new Integer(posLine), "Normal"); |
i++; |
} |
posLine++; |
} |
if (i >= l.size() && j < endFill - debutFill + 1) { |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
} |
posLine = firstLine + endFill; |
/* |
* if (this.mapStyleRow.get(new Integer(posLine - 1)) != null) { |
* this.mapStyleRow.put(new Integer(posLine - 1), "Titre 2"); } |
*/ |
// Total |
this.mCell.put("C" + posLine, ((totalDebit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit, false)))); |
this.mCell.put("D" + posLine, ((totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalCredit, false)))); |
this.mCell.put("E" + posLine, (totalDebit - totalCredit == 0) ? new Double(0) : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false))); |
posLine += 2; |
// bas de page |
makePiedPage(posLine); |
posLine++; |
firstLine = posLine; |
this.nbPage++; |
if (i >= l.size() && j >= (endFill - debutFill + 1)) { |
makeEntete(posLine); |
posLine += debutFill - 1; |
makeSousTotalClasse(posLine, sousTotalDebit, sousTotalCredit, classe); |
this.nbPage++; |
} |
} |
} |
// on conserve la page d'origine du model |
350,4 → 438,118 |
this.nbPage--; |
} |
} |
private long totalDebitBalance = 0; |
private long totalCreditBalance = 0; |
private List<Compte> vecteurCompte = new ArrayList<Compte>(); |
public void getBalance() { |
// Compte numero -- totalDebit |
Map<Number, Long> mapCompteDebit = new HashMap<Number, Long>(); |
Map<Number, Long> mapCompteCredit = new HashMap<Number, Long>(); |
List<Compte> comptes = new ArrayList<Compte>(); |
this.totalDebitBalance = 0; |
this.totalCreditBalance = 0; |
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
SQLTable compteTable = base.getTable("COMPTE_PCE"); |
SQLTable ecritureTable = base.getTable("ECRITURE"); |
SQLSelect sel = new SQLSelect(); |
// On recupere le solde des comptes |
sel.addSelect(compteTable.getField("ID")); |
sel.addSelect(ecritureTable.getField("DEBIT"), "SUM"); |
sel.addSelect(ecritureTable.getField("CREDIT"), "SUM"); |
sel.addSelect(compteTable.getField("NUMERO")); |
sel.setDistinct(true); |
Where w = (new Where(tableEcriture.getField("DATE"), this.dateDu, this.dateAu)); |
if (dateDu == null) { |
w = (new Where(tableEcriture.getField("DATE"), "<=", this.dateAu)); |
} |
sel.setWhere(w.and(new Where(compteTable.getField("ID"), "=", ecritureTable.getField("ID_COMPTE_PCE")))); |
String req = sel.asString() + " GROUP BY \"COMPTE_PCE\".\"ID\",\"COMPTE_PCE\".\"NUMERO\" ORDER BY \"COMPTE_PCE\".\"NUMERO\""; |
System.out.println(req); |
Object ob = base.getDataSource().execute(req, new ArrayListHandler()); |
List myList = (List) ob; |
if (myList.size() != 0) { |
for (int i = 0; i < myList.size(); i++) { |
Object[] tmp = (Object[]) myList.get(i); |
mapCompteDebit.put((Number) tmp[0], Long.parseLong(tmp[1].toString())); |
mapCompteCredit.put((Number) tmp[0], Long.parseLong(tmp[2].toString())); |
} |
} |
// Création du vecteur balance |
sel = new SQLSelect(); |
sel.addSelect(compteTable.getKey()); |
sel.addSelect(compteTable.getField("NUMERO")); |
sel.addSelect(compteTable.getField("NOM")); |
sel.addRawOrder("\"COMPTE_PCE\".\"NUMERO\""); |
String reqCompte = sel.asString(); |
System.out.println(req); |
Object obCompte = base.getDataSource().execute(reqCompte, new ArrayListHandler()); |
List myListCompte = (List) obCompte; |
if (myListCompte.size() != 0) { |
for (int i = 0; i < myListCompte.size(); i++) { |
Object[] tmp = (Object[]) myListCompte.get(i); |
System.err.println("Compte " + tmp[1].toString().trim()); |
long totalDebit = 0; |
long totalCredit = 0; |
if (mapCompteDebit.get(tmp[0]) != null) { |
totalDebit = Long.parseLong(mapCompteDebit.get(tmp[0]).toString()); |
} |
if (mapCompteCredit.get(tmp[0]) != null) { |
totalCredit = Long.parseLong(mapCompteCredit.get(tmp[0]).toString()); |
} |
this.totalDebitBalance += totalDebit; |
this.totalCreditBalance += totalCredit; |
List<String> sousCompte = new ArrayList<>(); |
for (int j = i + 1; j < (myListCompte.size() - 1); j++) { |
Object[] tmpNext = (Object[]) myListCompte.get(j); |
if (tmpNext[1].toString().trim().startsWith(tmp[1].toString().trim())) { |
System.err.println("Sous Compte " + tmpNext[1].toString().trim()); |
sousCompte.add(tmpNext[1].toString().trim()); |
if (mapCompteDebit.get(tmpNext[0]) != null) { |
totalDebit += Long.parseLong(mapCompteDebit.get(tmpNext[0]).toString()); |
} |
if (mapCompteCredit.get(tmpNext[0]) != null) { |
totalCredit += Long.parseLong(mapCompteCredit.get(tmpNext[0]).toString()); |
} |
} else { |
break; |
} |
} |
if ((totalDebit != 0.0) || (totalCredit != 0.0)) { |
Compte cpt = new Compte(((Number) tmp[0]).intValue(), tmp[1].toString(), tmp[2].toString(), "", totalDebit, totalCredit); |
cpt.addSousCompte(sousCompte); |
comptes.add(cpt); |
} |
} |
} |
this.vecteurCompte = comptes; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/JournauxSheetXML.java |
---|
191,6 → 191,10 |
values.put("NUMERO_COMPTE", rowEcr.getString("COMPTE_NUMERO")); |
if (tableEcriture.contains("NOM_PIECE")) { |
values.put("NOM_PIECE", rowEcr.getObject("NOM_PIECE")); |
} |
values.put("NUMERO_MOUVEMENT", rowMvt.getObject("NUMERO")); |
Object libelle = rowEcr.getObject("NOM"); |
values.put("LIBELLE", libelle); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033A.java |
---|
17,7 → 17,9 |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.utils.GestionDevise; |
import java.text.DateFormat; |
24,8 → 26,10 |
import java.text.SimpleDateFormat; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
import javax.swing.JOptionPane; |
import javax.swing.JProgressBar; |
import javax.swing.SwingUtilities; |
117,8 → 121,9 |
// Fix Abaque 208 - 2087 |
long v014 = this.sommeCompte.soldeCompteDebiteur(109, 109, true, this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("201", this.dateDebut, this.dateFin) |
+ this.sommeCompte.sommeCompteFils("203", this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("232", this.dateDebut, this.dateFin) |
+ this.sommeCompte.sommeCompteFils("205", this.dateDebut, this.dateFin) + this.sommeCompte.soldeCompte(208, 208, true, this.dateDebut, this.dateFin) |
- this.sommeCompte.soldeCompte(2087, 2087, true, this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("237", this.dateDebut, this.dateFin); |
+ this.sommeCompte.sommeCompteFils("234", this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("205", this.dateDebut, this.dateFin) |
+ this.sommeCompte.soldeCompte(208, 208, true, this.dateDebut, this.dateFin) - this.sommeCompte.soldeCompte(2087, 2087, true, this.dateDebut, this.dateFin) |
+ this.sommeCompte.sommeCompteFils("237", this.dateDebut, this.dateFin); |
this.m.put("ACTIF1.1", GestionDevise.currencyToString(v014, false)); |
// 016 -SommeSolde( 280, 280* ) - SommeSolde(2905) - SommeSolde (2908) |
148,7 → 153,8 |
// Racine = "210-215, 218, 230-231, 238" |
// S028=211...215+218+22+231+238 |
long v028 = this.sommeCompte.soldeCompte(211, 215, true, this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("218", this.dateDebut, this.dateFin) |
+ this.sommeCompte.sommeCompteFils("231", this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("238", this.dateDebut, this.dateFin); |
+ this.sommeCompte.sommeCompteFils("231", this.dateDebut, this.dateFin) + this.sommeCompte.sommeCompteFils("238", this.dateDebut, this.dateFin) |
+ this.sommeCompte.soldeCompte(24, 24, true, this.dateDebut, this.dateFin); |
this.m.put("ACTIF1.2", GestionDevise.currencyToString(v028, false)); |
// 030 -SommeSolde( 281, 289* )-SommeSolde( 290, 295* ) |
579,7 → 585,9 |
// Racine1 = "7" |
// long v136 = -this.sommeCompte.sommeCompteFils("12", dateDebut, |
// dateFin); |
long v136 = -this.sommeCompte.sommeCompteFils("7", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("6", this.dateDebut, this.dateFin); |
long v136 = -this.sommeCompte.sommeCompteFils("12", this.dateDebut, this.dateFin) - this.sommeCompte.sommeCompteFils("7", this.dateDebut, this.dateFin) |
- this.sommeCompte.sommeCompteFils("6", this.dateDebut, this.dateFin); |
this.m.put("PASSIF3.21", GestionDevise.currencyToString(v136, false)); |
// 137 -N-1: +R136 |
847,6 → 855,15 |
this.m.put("PASSIF4.33", ""); |
this.m.put("PASSIF4.34", ""); |
final SQLField field = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable("COMPTE_PCE").getField("NUMERO"); |
Where where = new Where(field, "NOT LIKE", "6%"); |
where = where.and(new Where(field, "NOT LIKE", "7%")); |
where = where.and(new Where(field, "NOT LIKE", "8%")); |
List<String> unused = this.sommeCompte.getNonUsedCompte(where, this.dateDebut, this.dateFin); |
if (unused != null && !unused.isEmpty()) { |
JOptionPane.showMessageDialog(null, "Certains comptes n'ont pas été intégré : " + unused); |
} |
p.generateFrom(this.m); |
SwingUtilities.invokeLater(new Runnable() { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033B.java |
---|
17,7 → 17,9 |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.finance.accounting.model.SommeCompte; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.utils.GestionDevise; |
import java.text.DateFormat; |
24,8 → 26,10 |
import java.text.SimpleDateFormat; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
import javax.swing.JOptionPane; |
import javax.swing.JProgressBar; |
import javax.swing.SwingUtilities; |
82,7 → 86,9 |
this.m.put("PRODUIT1.1", GestionDevise.currencyToString(v215, false)); |
// 214 -SommeSolde( 700, 705* )-SommeSolde( 7090, 7095* ) |
long v214 = -this.sommeCompte.soldeCompte(700, 705, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(7090, 7095, true, this.dateDeb, this.dateFin); |
long v214 = -this.sommeCompte.soldeCompte(700, 705, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte("709", this.dateDeb, this.dateFin) |
- this.sommeCompte.soldeCompte(7090, 7095, true, this.dateDeb, this.dateFin); |
this.m.put("PRODUIT2.1", GestionDevise.currencyToString(v214, false)); |
// 201 |
264,7 → 270,7 |
******************************************************************************************/ |
// 250 SommeSolde( 640, 644* )+SommeSolde( 648, 649* ) |
long v250 = this.sommeCompte.soldeCompte(644, 644, true, this.dateDeb, this.dateFin) + this.sommeCompte.soldeCompte(648, 649, true, this.dateDeb, this.dateFin) |
+ this.sommeCompte.soldeCompte(641, 641, true, this.dateDeb, this.dateFin)+ this.sommeCompte.soldeCompte(642, 642, true, this.dateDeb, this.dateFin); |
+ this.sommeCompte.soldeCompte(641, 641, true, this.dateDeb, this.dateFin) + this.sommeCompte.soldeCompte(642, 642, true, this.dateDeb, this.dateFin); |
this.m.put("CHARGES3.14", GestionDevise.currencyToString(v250, false)); |
// 220 |
369,8 → 375,8 |
* PRODUITS EXCEPTIONNELS |
******************************************************************************************/ |
// 290 -SommeSolde( 77, 77* )-SommeSolde( 787, 789* )-SommeSolde( 797, 799* ) |
long v290 = -this.sommeCompte.soldeCompte(770, 772, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(775, 778, true, this.dateDeb, this.dateFin) |
- this.sommeCompte.soldeCompte(787, 787, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(797, 797, true, this.dateDeb, this.dateFin); |
long v290 = -this.sommeCompte.soldeCompte(77, 77, true, this.dateDeb, this.dateFin) - this.sommeCompte.soldeCompte(787, 787, true, this.dateDeb, this.dateFin) |
- this.sommeCompte.soldeCompte(797, 797, true, this.dateDeb, this.dateFin); |
this.m.put("PCHARGES3.22", GestionDevise.currencyToString(v290, false)); |
// 245 |
484,6 → 490,14 |
this.m.put("T4.41", ""); |
this.m.put("T2.42", ""); |
final SQLField field = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable("COMPTE_PCE").getField("NUMERO"); |
Where where = new Where(field, "LIKE", "6%"); |
where = where.or(new Where(field, "LIKE", "7%")); |
List<String> unused = this.sommeCompte.getNonUsedCompte(where, this.dateDeb, this.dateFin); |
if (unused != null && !unused.isEmpty()) { |
JOptionPane.showMessageDialog(null, "Certains comptes n'ont pas été intégré : " + unused); |
} |
// final SQLField field = |
// ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable("COMPTE_PCE").getField("NUMERO"); |
// Where where = new Where(field, "LIKE", "6%"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/ImportEcritureFECAction.java |
---|
New file |
0,0 → 1,42 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.finance.accounting.action; |
import org.openconcerto.erp.core.finance.accounting.ui.ImportEcritureFECPanel; |
import org.openconcerto.sql.Configuration; |
import org.openconcerto.ui.FrameUtil; |
import org.openconcerto.ui.PanelFrame; |
import java.awt.event.ActionEvent; |
import javax.swing.AbstractAction; |
public class ImportEcritureFECAction extends AbstractAction { |
public ImportEcritureFECAction() { |
super("Import d'écritures FEC"); |
} |
@Override |
public void actionPerformed(ActionEvent e) { |
final PanelFrame frame = new PanelFrame(new ImportEcritureFECPanel(Configuration.getInstance().getDirectory()), "Import d'écritures FEC"); |
frame.pack(); |
frame.setResizable(false); |
frame.setLocationRelativeTo(null); |
FrameUtil.show(frame); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieKmItemTable.java |
---|
166,7 → 166,7 |
m2.setWhere(w); |
TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table); |
JButton buttonClone = new JButton(TM.tr("duplicateLine")); |
JButton buttonClone = new JButton(TM.tr(Configuration.getInstance().getLocale(), "duplicateLine")); |
buttonClone.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent event) { |
cloneLine(table.getSelectedRow()); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/LettragePanel.java |
---|
104,6 → 104,10 |
private JDate dateDeb, dateFin, dateLettrage; |
public LettragePanel() { |
this(ComptePCESQLElement.getId("4")); |
} |
public LettragePanel(int idCompte) { |
this.setLayout(new GridBagLayout()); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
final SQLElementDirectory directory = Configuration.getInstance().getDirectory(); |
124,7 → 128,7 |
} |
createComboRequest.setWhere(new Where(eltCpt.getTable().getField("NUMERO"), function, "^4.*$")); |
this.selCompte.init(eltCpt, createComboRequest); |
this.selCompte.setValue(ComptePCESQLElement.getId("4")); |
this.selCompte.setValue(idCompte); |
c.gridx++; |
c.weightx = 1; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalItemTable.java |
---|
34,7 → 34,6 |
import org.openconcerto.sql.view.list.RowValuesTableControlPanel; |
import org.openconcerto.sql.view.list.RowValuesTableModel; |
import org.openconcerto.sql.view.list.SQLTableElement; |
import org.openconcerto.sql.view.list.TextTableCellEditorWithCompletion; |
import org.openconcerto.sql.view.list.ValidStateChecker; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.JComponentUtils; |
48,6 → 47,7 |
import java.awt.GridBagLayout; |
import java.awt.event.ActionEvent; |
import java.awt.event.ActionListener; |
import java.awt.event.KeyAdapter; |
import java.awt.event.KeyEvent; |
import java.awt.event.KeyListener; |
import java.awt.event.MouseEvent; |
109,9 → 109,9 |
final SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_KM_ELEMENT"); |
// TODO Obligation de choisir un compte correct |
final List<SQLTableElement> list = new Vector<SQLTableElement>(); |
final List<SQLTableElement> list = new Vector<>(); |
final SQLTable tableElement = elt.getTable(); |
final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, rangedIntegerTableCellEditor) { |
final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, this.rangedIntegerTableCellEditor) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
158,6 → 158,7 |
final MultiLineTableCellEditor multiLineTableCellEditor = new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable); |
SQLTableElement eltPourcentAnalytique = new SQLTableElement(tableElement.getField("ANALYTIQUE"), String.class, multiLineTableCellEditor) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7")); |
}; |
173,12 → 174,10 |
final int debitIndex = getColumnIndexForElement(SaisieJournalItemTable.this.debit); |
final int creditIndex = getColumnIndexForElement(SaisieJournalItemTable.this.credit); |
// float debitVal = ((Float) model.getValueAt(rowIndex, debitIndex); |
if (debitIndex == columnIndex && ((Long) aValue).longValue() != 0 && ((Long) getValueAt(rowIndex, creditIndex)).longValue() != 0) { |
if (debitIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, creditIndex)).longValue() != 0) { |
setValueAt(Long.valueOf(0), rowIndex, creditIndex); |
} else { |
if (creditIndex == columnIndex && ((Long) aValue).longValue() != 0 && ((Long) getValueAt(rowIndex, debitIndex)).longValue() != 0) { |
if (creditIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, debitIndex)).longValue() != 0) { |
setValueAt(Long.valueOf(0), rowIndex, debitIndex); |
} |
} |
189,54 → 188,54 |
ToolTipManager.sharedInstance().unregisterComponent(this.table); |
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader()); |
tableElementNomEcriture.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() { |
tableElementNomEcriture.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() { |
@Override |
public void editingStopped(ChangeEvent e) { |
e.getSource(); |
int row = table.getSelectedRow(); |
int row = SaisieJournalItemTable.this.table.getSelectedRow(); |
int col = 4; |
if (table.getValueAt(row, col) != null) { |
defaultRowVals.put("NOM_ECRITURE", table.getValueAt(row, col)); |
if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) { |
defaultRowVals.put("NOM_ECRITURE", SaisieJournalItemTable.this.table.getValueAt(row, col)); |
} |
// defaultRowVals.put |
} |
@Override |
public void editingCanceled(ChangeEvent e) { |
// TODO Auto-generated method stub |
// |
} |
}); |
tableElementNomPiece.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() { |
tableElementNomPiece.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() { |
@Override |
public void editingStopped(ChangeEvent e) { |
e.getSource(); |
int row = table.getSelectedRow(); |
int row = SaisieJournalItemTable.this.table.getSelectedRow(); |
int col = 3; |
if (table.getValueAt(row, col) != null) { |
defaultRowVals.put("NOM_PIECE", table.getValueAt(row, col)); |
if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) { |
defaultRowVals.put("NOM_PIECE", SaisieJournalItemTable.this.table.getValueAt(row, col)); |
} |
// defaultRowVals.put |
} |
@Override |
public void editingCanceled(ChangeEvent e) { |
// TODO Auto-generated method stub |
// |
} |
}); |
tableElementJour.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() { |
tableElementJour.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() { |
@Override |
public void editingStopped(ChangeEvent e) { |
final Object valueAt = table.getValueAt(0, 0); |
final Object valueAt = SaisieJournalItemTable.this.table.getValueAt(0, 0); |
defaultRowVals.put("JOUR", valueAt); |
if (table.getRowCount() > 1) { |
for (int i = 1; i < table.getRowCount(); i++) { |
table.getRowValuesTableModel().putValue(valueAt, i, "JOUR"); |
if (SaisieJournalItemTable.this.table.getRowCount() > 1) { |
for (int i = 1; i < SaisieJournalItemTable.this.table.getRowCount(); i++) { |
SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(valueAt, i, "JOUR"); |
} |
} |
} |
243,25 → 242,13 |
@Override |
public void editingCanceled(ChangeEvent e) { |
// TODO Auto-generated method stub |
// |
} |
}); |
; |
final KeyListener keyListenerContrepartie = new KeyListener() { |
final KeyListener keyListenerContrepartie = new KeyAdapter() { |
@Override |
public void keyTyped(KeyEvent e) { |
} |
@Override |
public void keyReleased(KeyEvent e) { |
} |
@Override |
public void keyPressed(KeyEvent e) { |
if (e.getKeyCode() == KeyEvent.VK_ENTER) { |
montantValid(defaultRowVals, false, textField); |
281,7 → 268,7 |
@Override |
public ValidState getValidState(Object o) { |
if (o != null) { |
return elt.getCompteNumeroValidState(o.toString()); |
return this.elt.getCompteNumeroValidState(o.toString()); |
} |
return super.getValidState(o); |
} |
298,12 → 285,10 |
m2.setFillWithField("NOM"); |
m2.setWhere(w); |
TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table); |
JButton buttonClone = new JButton(TM.tr("duplicateLine")); |
JButton buttonClone = new JButton(TM.tr(Configuration.getInstance().getLocale(), "duplicateLine")); |
buttonClone.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent event) { |
cloneLine(table.getSelectedRow()); |
cloneLine(SaisieJournalItemTable.this.table.getSelectedRow()); |
} |
}); |
buttonClone.setEnabled(false); |
332,7 → 317,7 |
public void tableChanged(TableModelEvent e) { |
// Sélectionne automatiquement la ligne ajoutée |
if (e.getType() == TableModelEvent.INSERT) { |
if (table.getRowCount() == 1) { |
if (SaisieJournalItemTable.this.table.getRowCount() == 1) { |
editCellAt(e.getFirstRow(), 0); |
} else { |
editCellAt(e.getFirstRow(), 1); |
397,7 → 382,7 |
final PropertyChangeListener lActiveAddButton = new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty()); |
SaisieJournalItemTable.this.controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty()); |
} |
}; |
panel.getBoxJournal().addModelListener("wantedID", lActiveAddButton); |
414,7 → 399,7 |
c.set(Calendar.DAY_OF_MONTH, 1); |
c.set(Calendar.YEAR, (Integer) SaisieJournalItemTable.this.panel.spin.getValue()); |
c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth()); |
rangedIntegerTableCellEditor.setMax(c.getActualMaximum(Calendar.DAY_OF_MONTH)); |
SaisieJournalItemTable.this.rangedIntegerTableCellEditor.setMax(c.getActualMaximum(Calendar.DAY_OF_MONTH)); |
} |
} |
} |
429,14 → 414,14 |
long totalD = 0L; |
long totalC = 0L; |
for (int i = 0; i < table.getRowCount(); i++) { |
Long c = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("DEBIT")); |
Long d = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("CREDIT")); |
for (int i = 0; i < this.table.getRowCount(); i++) { |
Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT")); |
Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT")); |
if (c != null) { |
totalC += c; |
totalC += c.longValue(); |
} |
if (d != null) { |
totalD += d; |
totalD += d.longValue(); |
} |
} |
453,19 → 438,19 |
long totalC = 0L; |
boolean cptOK = true; |
String lib = null; |
for (int i = 0; i < table.getRowCount(); i++) { |
Long c = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("DEBIT")); |
Long d = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("CREDIT")); |
for (int i = 0; i < this.table.getRowCount(); i++) { |
Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT")); |
Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT")); |
if (c != null) { |
totalC += c; |
totalC += c.longValue(); |
} |
if (d != null) { |
totalD += d; |
totalD += d.longValue(); |
} |
if (lib == null) { |
lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM")); |
lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM")); |
} |
String cptNUmber = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NUMERO")); |
String cptNUmber = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NUMERO")); |
cptOK = cptOK && cptNUmber != null && ComptePCESQLElement.isExist(cptNUmber); |
} |
return totalD + totalC != 0 && totalD == totalC && cptOK; |
475,10 → 460,10 |
int day = 1; |
String lib = null; |
for (int i = 0; i < table.getRowCount(); i++) { |
day = (Integer) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("JOUR")); |
for (int i = 0; i < this.table.getRowCount(); i++) { |
day = (Integer) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("JOUR")); |
if (lib == null) { |
lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM")); |
lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM")); |
} |
} |
// Create saisieKM |
490,13 → 475,12 |
} |
public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique, final JTextField textPiece) { |
System.err.println("Enter"); |
final SQLRowValues vals = SaisieJournalItemTable.this.table.getSelectedRowValues(); |
final int selectedRow = SaisieJournalItemTable.this.table.getSelectedRow(); |
SwingUtilities.invokeLater(new Runnable() { |
public void run() { |
if (boxAutoInsert.isSelected() && isSaisieValid()) { |
if (SaisieJournalItemTable.this.boxAutoInsert.isSelected() && isSaisieValid()) { |
if (SaisieJournalItemTable.this.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) { |
JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!"); |
} else { |
503,7 → 487,8 |
createSaisie(defaultRowVals, textPiece); |
} |
} else { |
if (!fromAnalytique && !hideAnalytique && vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) { |
if (!fromAnalytique && !SaisieJournalItemTable.this.hideAnalytique && vals.getString("NUMERO") != null |
&& (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) { |
// Update montant |
Collection<SQLRowValues> rowsLinked = vals.getReferentRows(vals.getTable().getTable("ASSOCIATION_ANALYTIQUE")); |
513,7 → 498,7 |
.setScale(0, RoundingMode.HALF_UP).longValue()); |
} |
editCellAt(selectedRow, table.getRowValuesTableModel().getColumnForField("ANALYTIQUE")); |
editCellAt(selectedRow, SaisieJournalItemTable.this.table.getRowValuesTableModel().getColumnForField("ANALYTIQUE")); |
} else { |
long l = getContrepartie(); |
551,19 → 536,19 |
try { |
id = rowVAlsKM.insert().getID(); |
table.updateField("ID_SAISIE_KM", id); |
table.clear(); |
this.table.updateField("ID_SAISIE_KM", id); |
this.table.clear(); |
GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id); |
int idMvt = gen.genereMouvement(); |
// maj de l'id du mouvement correspondant |
SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM")); |
rowValsKMMvt.put("ID_MOUVEMENT", new Integer(idMvt)); |
rowValsKMMvt.put("ID_MOUVEMENT", Integer.valueOf(idMvt)); |
rowValsKMMvt.update(id); |
defaultRowVals.put("NOM_PIECE", ""); |
defaultRowVals.put("NOM_ECRITURE", ""); |
table.getRowValuesTableModel().addNewRow(); |
this.table.getRowValuesTableModel().addNewRow(); |
pieceText.setText(""); |
} catch (SQLException e) { |
e.printStackTrace(); |
626,11 → 611,11 |
final int debitIndex = model.getColumnIndexForElement(getDebitElement()); |
for (int i = 0; i < this.table.getRowCount(); i++) { |
if (model.isRowValid(i)) { |
final Long fTc = (Long) model.getValueAt(i, creditIndex); |
final Number fTc = (Number) model.getValueAt(i, creditIndex); |
if (fTc != null) { |
totalCred += fTc.longValue(); |
} |
final Long fTd = (Long) model.getValueAt(i, debitIndex); |
final Number fTd = (Number) model.getValueAt(i, debitIndex); |
if (fTd != null) { |
totalDeb += fTd.longValue(); |
} |
653,7 → 638,7 |
assert SwingUtilities.isEventDispatchThread(); |
if (text == null) |
return; |
RowValuesTableModel model = table.getRowValuesTableModel(); |
RowValuesTableModel model = this.table.getRowValuesTableModel(); |
int size = model.getRowCount(); |
for (int i = 0; i < size; i++) { |
SQLRowValues r = model.getRowValuesAt(i); |
664,6 → 649,7 |
model.fireTableDataChanged(); |
} |
@Override |
public void mousePressed(final MouseEvent e) { |
final int rowSel = this.table.getSelectedRow(); |
if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) { |
692,22 → 678,28 |
} |
} |
@Override |
public void mouseReleased(final MouseEvent e) { |
// Nothing |
} |
@Override |
public void mouseClicked(final MouseEvent e) { |
// Nothing |
} |
@Override |
public void mouseEntered(final MouseEvent e) { |
// Nothing |
} |
@Override |
public void mouseExited(final MouseEvent e) { |
// Nothing |
} |
private void cloneLine(int row) { |
if (row < 0) { |
System.err.println("RowValuesTableControlPanel.cloneLine() wrong selected line, index = " + row); |
Thread.dumpStack(); |
return; |
} |
SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImpressionBalancePanel.java |
---|
50,6 → 50,7 |
private JCheckBox checkClientCentral; |
private JCheckBox checkFournCentral; |
private JCheckBox checkFournImmoCentral; |
private JCheckBox checkTotalRacine; |
private JProgressBar bar = new JProgressBar(0, 3); |
private JTextField compteDeb, compteEnd; |
122,6 → 123,13 |
this.checkFournImmoCentral = new JCheckBox("Centralisation des comptes fournisseurs d'immobilisations"); |
this.add(this.checkFournImmoCentral, c); |
// Centralisation Fournisseurs |
c.gridy++; |
c.gridwidth = GridBagConstraints.REMAINDER; |
c.gridx = 0; |
this.checkTotalRacine = new JCheckBox("Total par racine"); |
this.add(this.checkTotalRacine, c); |
// Progress bar |
c.gridwidth = GridBagConstraints.REMAINDER; |
c.gridy++; |
163,7 → 171,7 |
new Thread(new Runnable() { |
public void run() { |
BalanceSheet bSheet = new BalanceSheet(dateStart.getDate(), dateEnd.getDate(), compteDeb.getText(), compteEnd.getText(), checkClientCentral.isSelected(), |
checkFournCentral.isSelected(), checkFournImmoCentral.isSelected()); |
checkFournCentral.isSelected(), checkFournImmoCentral.isSelected(), checkTotalRacine.isSelected()); |
final SpreadSheetGeneratorCompta generator = new SpreadSheetGeneratorCompta(bSheet, "Balance" + new Date().getTime(), checkImpr.isSelected(), checkVisu.isSelected()); |
SwingUtilities.invokeLater(new Runnable() { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImportEcriturePanel.java |
---|
112,12 → 112,6 |
button.setEnabled(false); |
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, ImportEcriturePanel.this); |
final FileDialog fd = new FileDialog(frame, "Import d'écritures", FileDialog.LOAD); |
fd.setFilenameFilter(new FilenameFilter() { |
@Override |
public boolean accept(File dir, String name) { |
return name.endsWith("." + ContentTypeVersioned.SPREADSHEET.getExtension()); |
} |
}); |
fd.setVisible(true); |
rlPanel.setMode(ReloadPanel.MODE_ROTATE); |
if (fd.getFile() != null) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteGestCommPreferencePanel.java |
---|
44,9 → 44,9 |
public class CompteGestCommPreferencePanel extends DefaultPreferencePanel { |
private ISQLCompteSelector selCompteTVAIntraComm, selCompteFourn, selCompteAchat, selCompteValeurEncaissement, selCompteAvanceClient, selCompteClient, selCompteVenteProduits, |
private ISQLCompteSelector selCompteCBAttente, selCompteTVAIntraComm, selCompteFourn, selCompteAchat, selCompteValeurEncaissement, selCompteAvanceClient, selCompteClient, selCompteVenteProduits, |
selCompteVenteService, selCompteTVACol, selCompteTVADed, selCompteTVAImmo, selCompteAchatIntra, selCompteFactor, selComptePortSoumis, selComptePortNonSoumis; |
private ElementComboBox selJrnlFactor, selJrnlValEnc; |
private ElementComboBox selJrnlFactor, selJrnlValEnc, selJrnlCB; |
private final static SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE"); |
private SQLRowValues rowPrefCompteVals = new SQLRowValues(tablePrefCompte); |
186,6 → 186,27 |
this.selJrnlValEnc.init(Configuration.getInstance().getDirectory().getElement("JOURNAL")); |
this.add(this.selJrnlValEnc, c); |
// Journal |
c.gridy++; |
c.weightx = 0; |
c.gridx = 0; |
this.add(new JLabel("Journal CB Attente"), c); |
c.weightx = 1; |
c.gridx++; |
this.selJrnlCB = new ElementComboBox(); |
this.selJrnlCB.init(Configuration.getInstance().getDirectory().getElement("JOURNAL")); |
this.add(this.selJrnlCB, c); |
c.gridy++; |
c.weightx = 0; |
c.gridx = 0; |
this.add(new JLabel("Compte CB Attente"), c); |
c.weightx = 1; |
c.gridx++; |
this.selCompteCBAttente = new ISQLCompteSelector(); |
this.selCompteCBAttente.init(); |
this.add(this.selCompteCBAttente, c); |
// Compte vente produits |
c.gridy++; |
c.weightx = 0; |
341,6 → 362,9 |
final int selectedIdEnc = this.selJrnlValEnc.getSelectedId(); |
this.rowPrefCompteVals.put("ID_JOURNAL_VALEUR_ENCAISSEMENT", (selectedIdEnc > 1) ? selectedIdEnc : 1); |
final int selectedIdCB = this.selJrnlCB.getSelectedId(); |
this.rowPrefCompteVals.put("ID_JOURNAL_CB_ATTENTE", (selectedIdCB > 1) ? selectedIdCB : 1); |
this.rowPrefCompteVals.put("ID_COMPTE_PCE_CB_ATTENTE", this.selCompteCBAttente.getSelectedId() > 1 ? this.selCompteCBAttente.getSelectedId() : 1); |
this.rowPrefCompteVals.put("ID_COMPTE_PCE_FOURNISSEUR", this.selCompteFourn.getValue()); |
this.rowPrefCompteVals.put("ID_COMPTE_PCE_CLIENT", this.selCompteClient.getValue()); |
this.rowPrefCompteVals.put("ID_COMPTE_PCE_AVANCE_CLIENT", this.selCompteAvanceClient.getValue()); |
480,7 → 504,20 |
} |
this.selJrnlFactor.setValue(value); |
} |
{ |
// Journal CB |
int value = (this.rowPrefCompteVals.getObject("ID_JOURNAL_CB_ATTENTE") == null ? 1 : this.rowPrefCompteVals.getInt("ID_JOURNAL_CB_ATTENTE")); |
if (value > 1) { |
this.selJrnlCB.setValue(value); |
} |
int valueCpt = (this.rowPrefCompteVals.getObject("ID_COMPTE_PCE_CB_ATTENTE") == null ? 1 : this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_CB_ATTENTE")); |
if (valueCpt > 1) { |
this.selCompteCBAttente.setValue(valueCpt); |
} |
} |
{ |
// Journal Val enc |
int value = (this.rowPrefCompteVals.getObject("ID_JOURNAL_VALEUR_ENCAISSEMENT") == null ? 1 : this.rowPrefCompteVals.getInt("ID_JOURNAL_VALEUR_ENCAISSEMENT")); |
if (value <= 1) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImportEcritureFECPanel.java |
---|
New file |
0,0 → 1,110 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.finance.accounting.ui; |
import org.openconcerto.erp.panel.compta.ImportFEC; |
import org.openconcerto.sql.element.SQLElementDirectory; |
import org.openconcerto.sql.users.UserManager; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.ReloadPanel; |
import org.openconcerto.ui.SwingThreadUtils; |
import java.awt.FileDialog; |
import java.awt.Frame; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
import java.awt.event.ActionEvent; |
import java.awt.event.ActionListener; |
import java.io.File; |
import java.io.IOException; |
import java.sql.SQLException; |
import java.util.HashMap; |
import java.util.Map; |
import javax.swing.JButton; |
import javax.swing.JLabel; |
import javax.swing.JOptionPane; |
import javax.swing.JPanel; |
import javax.swing.SwingUtilities; |
public class ImportEcritureFECPanel extends JPanel { |
private final Map<String, Integer> mapJournal = new HashMap<>(); |
private final Map<String, Integer> mapCompte = new HashMap<>(); |
public ImportEcritureFECPanel(final SQLElementDirectory dir) { |
super(new GridBagLayout()); |
JLabel label = new JLabel("Import depuis un fichier au format FEC."); |
final JButton button = new JButton("Sélectionner le ficher"); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
c.gridwidth = 2; |
this.add(label, c); |
c.gridy++; |
c.gridwidth = 1; |
c.weightx = 1; |
final ReloadPanel rlPanel = new ReloadPanel(); |
c.anchor = GridBagConstraints.EAST; |
c.fill = GridBagConstraints.NONE; |
this.add(rlPanel, c); |
c.gridx++; |
c.weightx = 0; |
this.add(button, c); |
button.addActionListener(new ActionListener() { |
@Override |
public void actionPerformed(ActionEvent e) { |
button.setEnabled(false); |
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, ImportEcritureFECPanel.this); |
final FileDialog fd = new FileDialog(frame, "Import d'écritures", FileDialog.LOAD); |
fd.setVisible(true); |
rlPanel.setMode(ReloadPanel.MODE_ROTATE); |
if (fd.getFile() != null) { |
new Thread() { |
@Override |
public void run() { |
final File fileToImport = new File(fd.getDirectory(), fd.getFile()); |
ImportFEC fec = new ImportFEC(); |
try { |
fec.loadFrom(fileToImport); |
fec.importTo(dir, dir.getElement("ECRITURE").getTable().getDBRoot(), UserManager.getUser()); |
} catch (IOException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} catch (SQLException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
}finally { |
SwingUtilities.invokeLater(new Runnable() { |
@Override |
public void run() { |
if (fd != null) { |
rlPanel.setMode(ReloadPanel.MODE_EMPTY); |
} |
JOptionPane.showMessageDialog(null, "Import terminé!"); |
} |
}); |
} |
} |
}.start(); |
} |
} |
}); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/model/SommeCompte.java |
---|
123,6 → 123,62 |
return sommeDebit - sommeCredit; |
} |
public long soldeCompte(String numeroCompte, Date dateDebut, Date dateFin) { |
long sommeDebit = 0; |
long sommeCredit = 0; |
SQLTable ecritureTable = base.getTable("ECRITURE"); |
SQLTable compteTable = base.getTable("COMPTE_PCE"); |
SQLSelect sel = new SQLSelect(); |
sel.addSelect(ecritureTable.getField("DEBIT"), "SUM"); |
sel.addSelect(ecritureTable.getField("CREDIT"), "SUM"); |
// sel.addSelect(compteTable.getField("ID")); |
// sel.addSelect(compteTable.getField("NUMERO")); |
// Where w = new Where(ecritureTable.getField("ID_COMPTE_PCE"), "=", |
// compteTable.getField("ID")); |
sel.addJoin("LEFT", ecritureTable.getField("ID_COMPTE_PCE")); |
Where w2 = new Where(compteTable.getField("NUMERO"), "LIKE", numeroCompte); |
this.compteUsed.add(numeroCompte); |
Where w4 = new Where(ecritureTable.getField("DATE"), dateDebut, dateFin); |
if (this.removeClotureCompte) { |
Where w5 = new Where(ecritureTable.getField("NOM"), "NOT LIKE", "Fermeture du compte %"); |
sel.setWhere(w2.and(w4).and(w5)); |
} else { |
sel.setWhere(w2.and(w4)); |
} |
addAnalytiqueJoin(sel); |
// String req = sel.asString() + |
// " GROUP BY \"COMPTE_PCE\".\"ID\",\"COMPTE_PCE\".\"NUMERO\" ORDER BY |
// \"COMPTE_PCE\".\"NUMERO\""; |
String req = sel.asString(); |
Object ob = base.getDataSource().execute(req, new ArrayListHandler()); |
List myList = (List) ob; |
if (myList.size() != 0) { |
for (int i = 0; i < myList.size(); i++) { |
Object[] objTmp = (Object[]) myList.get(i); |
if (objTmp[0] != null) { |
sommeDebit += ((Number) objTmp[0]).longValue(); |
} |
if (objTmp[1] != null) { |
sommeCredit += ((Number) objTmp[1]).longValue(); |
} |
} |
} |
return sommeDebit - sommeCredit; |
} |
/*********************************************************************************************** |
* Calcul le solde débiteur des comptes compris dans l'intervalle numeroStart numeroEnd |
* |
380,7 → 436,7 |
this.compteUsed.clear(); |
} |
public void getNonUsedCompte(Where where, Date dateDebut, Date dateFin) { |
public List<String> getNonUsedCompte(Where where, Date dateDebut, Date dateFin) { |
SQLSelect sel = new SQLSelect(); |
final SQLTable table = base.getTable("COMPTE_PCE"); |
402,6 → 458,6 |
for (String string : s) { |
System.err.println("Compte " + s); |
} |
return s; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/tax/model/TaxeCache.java |
---|
38,7 → 38,7 |
final DBRoot root = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(); |
final SQLTable table = root.getTable("TAXE"); |
SQLRowValues rowVals = new SQLRowValues(table); |
rowVals.putNulls("TAUX", "CODE", "NOM", "ID_TAXE", "DEFAULT"); |
rowVals.putNulls("TAUX", "CODE", "NOM", "ID_TAXE", "DEFAULT", "DEFAULT_ACHAT"); |
List<String> compteFields = Arrays.asList("ID_COMPTE_PCE_COLLECTE", "ID_COMPTE_PCE_DED", "ID_COMPTE_PCE", "ID_COMPTE_PCE_VENTE", "ID_COMPTE_PCE_VENTE_SERVICE", "ID_COMPTE_PCE_COLLECTE_INTRA", |
"ID_COMPTE_PCE_DED_INTRA"); |
for (String foreignFieldName : compteFields) { |
51,6 → 51,7 |
private final Map<SQLRowAccessor, Float> mapRowTaux = new LinkedHashMap<>(); |
private static TaxeCache instance; |
private SQLRow firstIdTaxe = null; |
private SQLRow firstIdTaxeAchat = null; |
private TaxeCache() { |
loadCache(); |
61,6 → 62,7 |
this.mapRowTaux.clear(); |
this.mapTaux.clear(); |
this.firstIdTaxe = null; |
this.firstIdTaxeAchat = null; |
final SQLRowValuesListFetcher sel = getSel(); |
71,6 → 73,9 |
if (sqlRow.getBoolean("DEFAULT")) { |
this.firstIdTaxe = sqlRow.asRow(); |
} |
if (sqlRow.getBoolean("DEFAULT_ACHAT")) { |
this.firstIdTaxeAchat = sqlRow.asRow(); |
} |
} |
} |
123,6 → 128,20 |
return this.firstIdTaxe; |
} |
public synchronized SQLRow getFirstTaxeAchat() { |
if (this.firstIdTaxeAchat == null) { |
final SQLRowValuesListFetcher sel = getSel(); |
final List<SQLRowValues> rows = sel.fetch(new Where(sel.getReq().getTable("TAXE").getField("DEFAULT_ACHAT"), "=", Boolean.TRUE)); |
if (rows != null && !rows.isEmpty()) { |
this.firstIdTaxeAchat = rows.get(0).asRow(); |
} else { |
this.firstIdTaxeAchat = getFirstTaxe(); |
} |
} |
return this.firstIdTaxeAchat; |
} |
public synchronized Integer getIdFromTaux(Float tax) { |
Set<Integer> s = mapTaux.keySet(); |
for (Integer integer : s) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/ui/EncaisseMontantTable.java |
---|
62,15 → 62,18 |
final SQLTableElement tableElement_Mvt = new SQLTableElement(e.getTable().getField("ID_MOUVEMENT_ECHEANCE"), Integer.class, new DefaultCellEditor(new JTextField())); |
tableElement_Mvt.setRenderer(new KeyTableCellRenderer(Configuration.getInstance().getDirectory().getElement("MOUVEMENT"))); |
tableElement_Mvt.setEditable(false); |
list.add(tableElement_Mvt); |
// Date |
final SQLTableElement dateElement = new SQLTableElement(e.getTable().getField("DATE"), Timestamp.class, new TimestampTableCellEditor()); |
dateElement.setEditable(false); |
list.add(dateElement); |
// Total HT |
montantARegler = new SQLTableElement(e.getTable().getField("MONTANT_A_REGLER"), Long.class, new DeviseCellEditor()); |
montantARegler.setRenderer(new DeviseNiceTableCellRenderer()); |
montantARegler.setEditable(false); |
list.add(montantARegler); |
// Total HT |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/component/EncaisserMontantSQLComponent.java |
---|
17,7 → 17,6 |
import org.openconcerto.erp.core.common.ui.DeviseField; |
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.EncaisserMontantSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement; |
import org.openconcerto.erp.core.finance.payment.ui.EncaisseMontantTable; |
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel; |
import org.openconcerto.sql.Configuration; |
66,7 → 65,85 |
private JLabel labelWarning = new JLabelWarning("Le montant est trop élevé!"); |
private JDate date; |
private ElementSQLObject eltModeRegl; |
final TableModelListener tableListener = new TableModelListener() { |
@Override |
public void tableChanged(TableModelEvent e) { |
final RowValuesTableModel model = table.getRowValuesTable().getRowValuesTableModel(); |
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantElement())) { |
final int rowCount = model.getRowCount(); |
long total = 0; |
for (int i = 0; i < rowCount; i++) { |
Number nHT = (Number) model.getValueAt(i, model.getColumnIndexForElement(table.getMontantElement())); |
if (nHT != null) { |
total += nHT.longValue(); |
} |
} |
montant.getDocument().removeDocumentListener(listenerMontant); |
montant.setText(GestionDevise.currencyToString(total)); |
montant.getDocument().addDocumentListener(listenerMontant); |
// Selection du mode de reglement |
if (getMode() == SQLComponent.Mode.INSERTION) { |
if (rowCount >= 1) { |
MouvementSQLElement element = getElement().getDirectory().getElement(MouvementSQLElement.class); |
SQLRowValues row1 = model.getRowValuesAt(0); |
if (row1.getObject("ID_MOUVEMENT_ECHEANCE") != null && !row1.isForeignEmpty("ID_MOUVEMENT_ECHEANCE")) { |
final int idScr = element.getSourceId(row1.getForeignID("ID_MOUVEMENT_ECHEANCE")); |
SQLTable tableMvt = element.getTable(); |
if (idScr > 1) { |
SQLRow rowMvt = tableMvt.getRow(idScr); |
String source = rowMvt.getString("SOURCE"); |
int idSource = rowMvt.getInt("IDSOURCE"); |
SQLElement eltSource = element.getDirectory().getElement(source); |
if (eltSource != null) { |
SQLRow rowSource = eltSource.getTable().getRow(idSource); |
if (rowSource != null) { |
SQLRow rowModeRegl = rowSource.getForeignRow("ID_MODE_REGLEMENT"); |
if (rowModeRegl != null) { |
System.err.println("Set mode de règlement"); |
int idTypeRegl = rowModeRegl.getInt("ID_TYPE_REGLEMENT"); |
SQLTable tableModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT").getTable(); |
SQLRowValues rowVals = new SQLRowValues(tableModeRegl); |
rowVals.put("ID_TYPE_REGLEMENT", idTypeRegl); |
rowVals.put("COMPTANT", Boolean.TRUE); |
rowVals.put("AJOURS", 0); |
rowVals.put("LENJOUR", 0); |
rowVals.put("ID_" + BanqueSQLElement.TABLENAME, rowModeRegl.getInt("ID_" + BanqueSQLElement.TABLENAME)); |
eltModeRegl.setValue(rowVals); |
} |
} |
} |
} |
} |
} |
} |
} |
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantElement()) |
|| e.getColumn() == model.getColumnIndexForElement(table.getMontantAReglerElement())) { |
updateWarning(); |
} |
} |
}; |
final SimpleDocumentListener listenerMontant = new SimpleDocumentListener() { |
@Override |
public void update(DocumentEvent e) { |
table.getRowValuesTable().getRowValuesTableModel().removeTableModelListener(tableListener); |
updateMontant(montant.getText()); |
table.getRowValuesTable().getRowValuesTableModel().addTableModelListener(tableListener); |
updateWarning(); |
} |
}; |
public EncaisserMontantSQLComponent(SQLElement elt) { |
super(elt); |
} |
84,7 → 161,6 |
c.weighty = 1; |
c.fill = GridBagConstraints.BOTH; |
this.add(this.table, c); |
this.table.getRowValuesTable().setEnabled(false); |
c.fill = GridBagConstraints.HORIZONTAL; |
c.gridwidth = 1; |
c.gridy++; |
144,11 → 220,13 |
c.gridx++; |
c.gridwidth = 3; |
c.weightx = 1; |
c.fill = GridBagConstraints.NONE; |
this.add(this.montant, c); |
// Warning |
c.gridx++; |
c.weightx = 0; |
c.gridwidth = GridBagConstraints.REMAINDER; |
this.labelWarning.setHorizontalAlignment(SwingConstants.RIGHT); |
this.add(this.labelWarning, c); |
170,9 → 248,12 |
c.gridy++; |
c.gridwidth = GridBagConstraints.REMAINDER; |
this.addView("ID_MODE_REGLEMENT", BaseSQLComponent.REQ + ";" + BaseSQLComponent.DEC + ";" + BaseSQLComponent.SEP); |
final ElementSQLObject eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT"); |
this.add(eltModeRegl, c); |
this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT"); |
this.add(this.eltModeRegl, c); |
ModeDeReglementSQLComponent modeReglComp; |
modeReglComp = (ModeDeReglementSQLComponent) this.eltModeRegl.getSQLChild(); |
modeReglComp.addDateCompListener(this.date); |
this.addRequiredSQLObject(this.date, "DATE"); |
this.addRequiredSQLObject(this.montant, "MONTANT"); |
182,78 → 263,7 |
this.addSQLObject(new JTextField(), "TIERS"); |
DefaultGridBagConstraints.lockMinimumSize(this.montant); |
final TableModelListener tableListener = new TableModelListener() { |
@Override |
public void tableChanged(TableModelEvent e) { |
final RowValuesTableModel model = table.getRowValuesTable().getRowValuesTableModel(); |
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantElement())) { |
final int rowCount = model.getRowCount(); |
long total = 0; |
for (int i = 0; i < rowCount; i++) { |
Number nHT = (Number) model.getValueAt(i, model.getColumnIndexForElement(table.getMontantElement())); |
if (nHT != null) { |
total += nHT.longValue(); |
} |
} |
montant.setText(GestionDevise.currencyToString(total)); |
// Selection du mode de reglement |
if (getMode() == SQLComponent.Mode.INSERTION) { |
if (rowCount >= 1 && model.getRowValuesAt(0).getObject("ID_MOUVEMENT_ECHEANCE") != null && !model.getRowValuesAt(0).isForeignEmpty("ID_MOUVEMENT_ECHEANCE")) { |
final int idScr = MouvementSQLElement.getSourceId(model.getRowValuesAt(0).getInt("ID_MOUVEMENT_ECHEANCE")); |
SQLTable tableMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT").getTable(); |
if (idScr > 1) { |
SQLRow rowMvt = tableMvt.getRow(idScr); |
String source = rowMvt.getString("SOURCE"); |
int idSource = rowMvt.getInt("IDSOURCE"); |
SQLElement eltSource = Configuration.getInstance().getDirectory().getElement(source); |
if (eltSource != null) { |
SQLRow rowSource = eltSource.getTable().getRow(idSource); |
if (rowSource != null) { |
SQLRow rowModeRegl = rowSource.getForeignRow("ID_MODE_REGLEMENT"); |
if (rowModeRegl != null) { |
System.err.println("Set mode de règlement"); |
int idTypeRegl = rowModeRegl.getInt("ID_TYPE_REGLEMENT"); |
SQLTable tableModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT").getTable(); |
SQLRowValues rowVals = new SQLRowValues(tableModeRegl); |
if (idTypeRegl == TypeReglementSQLElement.INDEFINI) { |
idTypeRegl = TypeReglementSQLElement.CHEQUE; |
} |
rowVals.put("ID_TYPE_REGLEMENT", idTypeRegl); |
rowVals.put("COMPTANT", Boolean.TRUE); |
rowVals.put("AJOURS", 0); |
rowVals.put("LENJOUR", 0); |
rowVals.put("ID_" + BanqueSQLElement.TABLENAME, rowModeRegl.getInt("ID_" + BanqueSQLElement.TABLENAME)); |
eltModeRegl.setValue(rowVals); |
} |
} |
} |
} |
} |
} |
} |
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantAReglerElement())) { |
updateWarning(); |
} |
} |
}; |
this.montant.getDocument().addDocumentListener(new SimpleDocumentListener() { |
@Override |
public void update(DocumentEvent e) { |
table.getRowValuesTable().getRowValuesTableModel().removeTableModelListener(tableListener); |
updateMontant(montant.getText()); |
table.getRowValuesTable().getRowValuesTableModel().addTableModelListener(tableListener); |
updateWarning(); |
} |
}); |
this.montant.getDocument().addDocumentListener(listenerMontant); |
this.table.getRowValuesTable().getRowValuesTableModel().addTableModelListener(tableListener); |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/component/ModeDeReglementSQLComponent.java |
---|
15,6 → 15,7 |
import org.openconcerto.erp.config.Log; |
import org.openconcerto.erp.core.common.element.BanqueSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement; |
import org.openconcerto.erp.model.BanqueModifiedListener; |
import org.openconcerto.sql.element.BaseSQLComponent; |
40,6 → 41,7 |
import java.awt.event.ItemListener; |
import java.beans.PropertyChangeEvent; |
import java.beans.PropertyChangeListener; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.Map; |
import java.util.Set; |
279,6 → 281,39 |
}); |
} |
public void addDateCompListener(JDate dateParent) { |
dateParent.addPropertyChangeListener(new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
ModeDeReglementSQLComponent.this.currentDate = dateParent.getValue(); |
refreshDatePrev(); |
} |
}); |
dateParent.addValueListener(new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
ModeDeReglementSQLComponent.this.currentDate = dateParent.getValue(); |
refreshDatePrev(); |
} |
}); |
} |
private void refreshDatePrev() { |
if (this.currentDate != null) { |
int aJ = this.comboA.getValue().trim().length() == 0 ? 0 : Integer.valueOf(this.comboA.getValue()); |
int nJ = this.comboLe.getValue().trim().length() == 0 ? 0 : Integer.valueOf(this.comboLe.getValue()); |
Date d = ModeDeReglementSQLElement.calculDate(aJ, nJ, this.currentDate); |
this.datePrev.setDate(d); |
} else { |
this.datePrev.setDate(null); |
} |
} |
private JDate datePrev = new JDate(); |
private Date currentDate = null; |
private void createPanelEcheance() { |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
290,6 → 325,13 |
this.comboA.setMinimumSize(new Dimension(60, this.comboA.getMinimumSize().height)); |
this.comboA.setPreferredSize(new Dimension(60, this.comboA.getMinimumSize().height)); |
this.comboA.setMaximumSize(new Dimension(60, this.comboA.getMinimumSize().height)); |
this.comboA.addValueListener(new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
refreshDatePrev(); |
} |
}); |
this.panelEcheance.add(this.comboA, c); |
c.gridx += 1; |
c.gridwidth = 1; |
300,7 → 342,21 |
c.fill = GridBagConstraints.HORIZONTAL; |
this.buttonDateFacture.setOpaque(false); |
this.panelEcheance.add(this.buttonDateFacture, c); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 1; |
c.gridwidth = 1; |
// ((BaseSQLComponent)((ElementSQLObject)getSQLParent()).getSQLParent()).getView("DATE"); |
this.panelEcheance.add(new JLabel("Soit le"), c); |
c.gridx++; |
c.gridwidth = 1; |
this.datePrev.setEnabled(false); |
this.panelEcheance.add(this.datePrev, c); |
// c.gridy++; |
c.gridwidth = 2; |
c.gridx = 3; |
c.weightx = 0; |
c.fill = GridBagConstraints.NONE; |
this.buttonFinMois.setOpaque(false); |
314,6 → 370,13 |
this.comboLe.setMinimumSize(new Dimension(60, this.comboLe.getMinimumSize().height)); |
this.comboLe.setPreferredSize(new Dimension(60, this.comboLe.getMinimumSize().height)); |
this.comboLe.setMaximumSize(new Dimension(60, this.comboLe.getMinimumSize().height)); |
this.comboLe.addValueListener(new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
refreshDatePrev(); |
} |
}); |
this.panelEcheance.add(this.comboLe, c); |
this.panelActive = this.panelEcheance; |
this.m.put(Mode.ECHEANCE, this.panelEcheance); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/DepotChequeSQLElement.java |
---|
13,6 → 13,7 |
package org.openconcerto.erp.core.finance.payment.element; |
import org.openconcerto.erp.core.common.element.BanqueSQLElement; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.erp.core.finance.payment.component.DepotChequeSQLComponent; |
import org.openconcerto.erp.generationDoc.gestcomm.DepotChequeXmlSheet; |
47,7 → 48,7 |
final List<String> l = new ArrayList<String>(); |
l.add("DATE"); |
l.add("NOM"); |
l.add("ID_BANQUE"); |
l.add("ID_" + BanqueSQLElement.TABLENAME); |
l.add("MONTANT"); |
return l; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/SDDMessageSQLElement.java |
---|
75,10 → 75,12 |
import java.util.NavigableMap; |
import java.util.Set; |
import java.util.TreeMap; |
import java.util.concurrent.ExecutionException; |
import java.util.prefs.Preferences; |
import javax.swing.AbstractAction; |
import javax.swing.JFileChooser; |
import javax.swing.SwingWorker; |
import org.jdom2.Document; |
import org.jdom2.Element; |
113,11 → 115,29 |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListe l = IListe.get(e); |
// XML field values are quite large so only fetch them when needed |
final SQLTable t = l.getSource().getPrimaryTable(); |
final SQLSelect sel = new SQLSelect().addSelectStar(t); |
sel.setWhere(new Where(t.getKey(), l.getSelection().getUserSelectedIDs())); |
exportXML(l, SQLRowListRSH.execute(sel)); |
final Set<Integer> userSelectedIDs = l.getSelection().getUserSelectedIDs(); |
new SwingWorker<List<SQLRow>, Void>() { |
@Override |
protected List<SQLRow> doInBackground() throws Exception { |
final SQLSelect sel = new SQLSelect().addSelectStar(t); |
// XML field values are quite large so only fetch them when needed |
sel.setWhere(new Where(t.getKey(), userSelectedIDs)); |
return SQLRowListRSH.execute(sel); |
} |
@Override |
protected void done() { |
List<SQLRow> execute; |
try { |
execute = get(); |
exportXML(l, execute); |
} catch (InterruptedException | ExecutionException e) { |
e.printStackTrace(); |
} |
} |
}.execute(); |
} |
}, true, false).setPredicate(IListeEvent.getNonEmptySelectionPredicate())); |
this.rowSociété = conf.getRowSociete(); |
196,7 → 216,11 |
} |
protected static BigDecimal getInvoiceAmount(final SQLRowValues invoice) { |
return BigDecimal.valueOf(invoice.getLong("NET_A_PAYER")).movePointLeft(2); |
if (invoice.getTable().getName().equals("SAISIE_VENTE_FACTURE")) { |
return BigDecimal.valueOf(invoice.getLong("NET_A_PAYER")).movePointLeft(2); |
} else { |
return BigDecimal.valueOf(invoice.getLong("MONTANT")).movePointLeft(2); |
} |
} |
static private final class InvoiceElem extends Tuple2<SQLRowValues, Element> { |
296,6 → 320,47 |
return IgnoreReason.NONE; |
} |
final IgnoreReason addEcheance(final SQLRowValues prlvt) { |
Date date = prlvt.getDate("DATE").getTime(); |
// don't ask direct debit too far in advance |
if (date.after(this.upperBound)) { |
return IgnoreReason.TOO_FAR_IN_FUTURE; |
} else if (date.before(this.lowerBound)) { |
date = this.lowerBound; |
} |
final Element elem; |
try { |
elem = createDDTx(this.elemCreator, prlvt); |
} catch (MissingInfoException e) { |
return IgnoreReason.MISSING_INFO; |
} |
// needed so that EndToEndId is unique |
if (!this.invoiceNumbers.add(prlvt.getForeign("ID_MOUVEMENT").getForeign("ID_PIECE").getString("NOM"))) |
throw new IllegalStateException("Duplicate invoice number : " + prlvt); |
final SQLRowAccessor mandate = prlvt.getForeign("ID_SEPA_MANDATE"); |
if (!mandate.getBoolean("ACTIVE")) |
throw new IllegalStateException("Inactive mandate for " + prlvt); |
// needed otherwise would have to update seqType while generating |
// MAYBE sum all invoices for a single mandate, but which date to choose ? |
if (!this.invoiceMandates.add(mandate.getString("MandateIdentification"))) |
return IgnoreReason.DUPLICATE_MANDATE; |
this.lockedInvoicesIDs.add(prlvt.getIDNumber()); |
ListMap<String, InvoiceElem> bySeqType = this.map.get(date); |
if (bySeqType == null) { |
bySeqType = new ListMap<>(); |
this.map.put(date, bySeqType); |
} |
bySeqType.add(mandate.getString("SequenceType"), new InvoiceElem(prlvt, elem)); |
this.sum = this.sum.add(BigDecimal.valueOf(prlvt.getLong("MONTANT")).movePointLeft(2)); |
return IgnoreReason.NONE; |
} |
public final int getTransactionCount() { |
return this.lockedInvoicesIDs.size(); |
} |
323,9 → 388,12 |
private final ListMapItf<IgnoreReason, SQLRowValues> ignoredInvoices; |
private final SQLRow insertedMessage; |
private final int invoiceCount; |
private final SQLTable table; |
protected GenerationResult(Collection<? extends Number> passedIDs, List<SQLRowValues> withDDWithoutMessage, ListMap<IgnoreReason, SQLRowValues> ignoredInvoices, SQLRow insertedMessage) { |
protected GenerationResult(SQLTable table, Collection<? extends Number> passedIDs, List<SQLRowValues> withDDWithoutMessage, ListMap<IgnoreReason, SQLRowValues> ignoredInvoices, |
SQLRow insertedMessage) { |
super(); |
this.table = table; |
this.passedIDs = passedIDs; |
this.withDDWithoutMessage = Collections.unmodifiableList(withDDWithoutMessage); |
assert !ignoredInvoices.containsKey(null) && !ignoredInvoices.containsKey(IgnoreReason.NONE); |
353,6 → 421,10 |
return this.invoiceCount; |
} |
public SQLTable getTable() { |
return table; |
} |
@Override |
public String toString() { |
return this.getClass().getSimpleName() + ": of the " + this.passedIDs.size() + " passed, " + this.withDDWithoutMessage.size() + " needed a SDD message, of those " |
360,7 → 432,7 |
} |
} |
public GenerationResult generateXML(Collection<? extends Number> invoiceIDs) throws SQLException { |
public GenerationResult generateXML(final SQLTable table, Collection<? extends Number> invoiceIDs) throws SQLException { |
final Namespace painNS = Namespace.getNamespace("urn:iso:std:iso:20022:tech:xsd:pain.008.001.02"); |
final Element rootElem = new Element("Document", painNS); |
final Namespace xsiNS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); |
394,8 → 466,7 |
} |
}); |
final SQLTable invoiceT = getDirectory().getElement(SaisieVenteFactureSQLElement.class).getTable(); |
final SQLField invoiceSDDMessageF = invoiceT.getField(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME); |
final SQLField invoiceSDDMessageF = table.getField(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME); |
return SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<GenerationResult, SQLException>() { |
@Override |
public GenerationResult handle(SQLDataSource ds) throws SQLException { |
402,12 → 473,29 |
final SQLRowValues lockedSociété = selSociété.fetchOne(SDDMessageSQLElement.this.rowSociété.getIDNumber()); |
if (lockedSociété == null) |
throw new IllegalStateException("Missing société " + SDDMessageSQLElement.this.rowSociété); |
if (lockedSociété.getString("IBAN").trim().length() == 0) { |
throw new IllegalStateException("Missing société IBAN " + SDDMessageSQLElement.this.rowSociété); |
} |
if (lockedSociété.getString("BIC").trim().length() == 0) { |
throw new IllegalStateException("Missing société BIC " + SDDMessageSQLElement.this.rowSociété); |
} |
// find and lock invoices with TYPE_REGLEMENT direct debit and no message |
final SQLRowValues invoiceVals = new SQLRowValues(invoiceT); |
invoiceVals.putRowValues("ID_CLIENT").putNulls("NOM", "BIC", "IBAN"); |
invoiceVals.putRowValues("ID_MODE_REGLEMENT").putNulls("AJOURS", "LENJOUR").putRowValues("ID_SEPA_MANDATE").setAllToNull(); |
invoiceVals.putNulls("NET_A_PAYER", "DATE", "NUMERO", "NOM"); |
final SQLRowValues invoiceVals = new SQLRowValues(table); |
final boolean fromInvoices = table.getName().equals("SAISIE_VENTE_FACTURE"); |
if (fromInvoices) { |
invoiceVals.putRowValues("ID_CLIENT").putNulls("NOM", "BIC", "IBAN"); |
invoiceVals.putRowValues("ID_MODE_REGLEMENT").putNulls("AJOURS", "LENJOUR").putRowValues("ID_SEPA_MANDATE").setAllToNull(); |
invoiceVals.putNulls("NET_A_PAYER", "DATE", "NUMERO", "NOM"); |
} else { |
invoiceVals.putRowValues("ID_CLIENT").putNulls("NOM", "BIC", "IBAN"); |
invoiceVals.putRowValues("ID_SEPA_MANDATE").setAllToNull(); |
invoiceVals.putNulls("MONTANT", "DATE"); |
invoiceVals.putRowValues("ID_MOUVEMENT").putRowValues("ID_PIECE").setAllToNull(); |
} |
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(invoiceVals); |
fetcher.setReturnedRowsUnmodifiable(true); |
// required for locking rows and to make sure that there's a SEPA Mandate |
417,19 → 505,28 |
public SQLSelect transformChecked(SQLSelect sel) { |
// we will update FACTURE.ID_MESSAGE |
sel.setLockStrength(LockStrength.UPDATE); |
final SQLSelectJoin join = sel.getJoin(invoiceT.getField("ID_MODE_REGLEMENT")); |
join.setWhere(new Where(join.getJoinedTable().getField("ID_TYPE_REGLEMENT"), "=", TypeReglementSQLElement.PRELEVEMENT)); |
if (fromInvoices) { |
final SQLSelectJoin join = sel.getJoin(table.getField("ID_MODE_REGLEMENT")); |
join.setWhere(new Where(join.getJoinedTable().getField("ID_TYPE_REGLEMENT"), "=", TypeReglementSQLElement.PRELEVEMENT)); |
} |
return sel; |
} |
}); |
final List<SQLRowValues> ddInvoices = fetcher |
.fetch(new Where(invoiceT.getKey(), invoiceIDs).and(new Where(invoiceSDDMessageF, "=", invoiceSDDMessageF.getForeignTable().getUndefinedIDNumber()))); |
.fetch(new Where(table.getKey(), invoiceIDs).and(new Where(invoiceSDDMessageF, "=", invoiceSDDMessageF.getForeignTable().getUndefinedIDNumber()))); |
final InvoicesByPaymentInfo map = new InvoicesByPaymentInfo(lowerBound, upperBound, new ElementCreator(painNS, SDDMessageSQLElement.this.fieldTranslator)); |
final ListMap<IgnoreReason, SQLRowValues> ignoredInvoices = new ListMap<>(); |
for (final SQLRowValues invoice : ddInvoices) { |
final IgnoreReason ignoredReason = map.addInvoice(invoice); |
if (ignoredReason != IgnoreReason.NONE) { |
ignoredInvoices.add(ignoredReason, invoice); |
if (fromInvoices) { |
final IgnoreReason ignoredReason = map.addInvoice(invoice); |
if (ignoredReason != IgnoreReason.NONE) { |
ignoredInvoices.add(ignoredReason, invoice); |
} |
} else { |
final IgnoreReason ignoredReason = map.addEcheance(invoice); |
if (ignoredReason != IgnoreReason.NONE) { |
ignoredInvoices.add(ignoredReason, invoice); |
} |
} |
} |
481,7 → 578,7 |
getTable().getDBRoot().setMetadata(SERIAL_MD, msgSerial); |
} |
return new GenerationResult(invoiceIDs, ddInvoices, ignoredInvoices, newMsg); |
return new GenerationResult(table, invoiceIDs, ddInvoices, ignoredInvoices, newMsg); |
} |
}); |
} |
555,7 → 652,8 |
res.addContent(creditor); |
final Element creditorAccount = new Element("CdtrAcct", painNS); |
creditorAccount.addContent(new Element("Id", painNS).addContent(elemCreator.createWithNonEmptyText("IBAN", lockedSociété, "IBAN"))); |
String iban = lockedSociété.getString("IBAN").replaceAll(" ", ""); |
creditorAccount.addContent(new Element("Id", painNS).addContent(elemCreator.createWithNonEmptyText("IBAN", iban, "IBAN"))); |
res.addContent(creditorAccount); |
final Element creditorAgent = new Element("CdtrAgt", painNS); |
592,7 → 690,13 |
invoiceElem.get1().addContent(0, paymentId); |
// update mandate fields |
final SQLRowAccessor mandate = invoiceElem.get0().getForeign("ID_MODE_REGLEMENT").getForeign("ID_SEPA_MANDATE"); |
final SQLRowAccessor mandate; |
if (invoiceElem.get0().contains("ID_SEPA_MANDATE")) { |
mandate = invoiceElem.get0().getForeign("ID_SEPA_MANDATE"); |
} else { |
mandate = invoiceElem.get0().getForeign("ID_MODE_REGLEMENT").getForeign("ID_SEPA_MANDATE"); |
} |
final String seqType = mandate.getString("SequenceType"); |
if (seqType.equals(SEPAMandateSQLElement.SEQ_FIRST)) { |
mandate.createEmptyUpdateRow().put("SequenceType", SEPAMandateSQLElement.SEQ_RECURRENT).update(); |
610,7 → 714,14 |
res.addContent(new Element("InstdAmt", painNS).setAttribute("Ccy", "EUR").setText(getInvoiceAmount(invoice).toPlainString())); |
final Element mandateRltdInfo = new Element("MndtRltdInf", painNS); |
final SQLRowAccessor mandate = invoice.getForeign("ID_MODE_REGLEMENT").getForeign("ID_SEPA_MANDATE"); |
final SQLRowAccessor mandate; |
final boolean fromInvoice = invoice.getTable().getName().equals("SAISIE_VENTE_FACTURE"); |
if (fromInvoice) { |
mandate = invoice.getForeign("ID_MODE_REGLEMENT").getForeign("ID_SEPA_MANDATE"); |
} else { |
mandate = invoice.getForeign("ID_SEPA_MANDATE"); |
} |
assert !mandate.isUndefined() : "Undefined mandate returned by fetcher"; |
mandateRltdInfo.addContent(elemCreator.createWithNonEmptyText("MndtId", mandate, "MandateIdentification")); |
mandateRltdInfo.addContent(elemCreator.createWithNonEmptyText("DtOfSgntr", formatDate(mandate.getObjectAs("DateOfSignature", Date.class)))); |
624,7 → 735,12 |
res.addContent(new Element("Purp", painNS).addContent(new Element("Cd", painNS).setText("OTHR"))); |
final String info = (invoice.getString("NUMERO") + ' ' + invoice.getString("NOM")).trim(); |
final String info; |
if (fromInvoice) { |
info = (invoice.getString("NUMERO") + ' ' + invoice.getString("NOM")).trim(); |
} else { |
info = invoice.getForeign("ID_MOUVEMENT").getForeign("ID_PIECE").getString("NOM"); |
} |
if (!info.isEmpty()) |
res.addContent(new Element("RmtInf", painNS).addContent(elemCreator.create("Ustrd").setText(elemCreator.shortenText(info, 140)))); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ReglerMontantSQLElement.java |
---|
15,9 → 15,16 |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.model.FieldPath; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.graph.Path; |
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn; |
import org.openconcerto.sql.view.list.SQLTableModelSource; |
import org.openconcerto.utils.CollectionUtils; |
import java.util.ArrayList; |
import java.util.List; |
import java.util.Set; |
public class ReglerMontantSQLElement extends ComptaSQLConfElement { |
28,7 → 35,7 |
protected List<String> getListFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("DATE"); |
l.add("ID_ECHEANCE_FOURNISSEUR"); |
l.add("ID_FOURNISSEUR"); |
l.add("ID_MODE_REGLEMENT"); |
l.add("MONTANT"); |
return l; |
41,6 → 48,27 |
return l; |
} |
@Override |
protected void _initTableSource(SQLTableModelSource res) { |
super._initTableSource(res); |
final BaseSQLTableModelColumn racCol = new BaseSQLTableModelColumn("Report échéance", Boolean.class) { |
@Override |
protected Object show_(SQLRowAccessor r) { |
return !r.getForeign("ID_MODE_REGLEMENT").getBoolean("COMPTANT"); |
} |
@Override |
public Set<FieldPath> getPaths() { |
Path p = new Path(getTable()); |
Path p2 = p.add(p.getLast().getField("ID_MODE_REGLEMENT")); |
return CollectionUtils.createSet(new FieldPath(p2, "COMPTANT")); |
} |
}; |
res.getColumns().add(racCol); |
} |
public SQLComponent createComponent() { |
return new ReglerMontantSQLComponent(this); |
}; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ReglerMontantSQLComponent.java |
---|
16,6 → 16,7 |
import org.openconcerto.erp.core.common.element.BanqueSQLElement; |
import org.openconcerto.erp.core.common.ui.DeviseField; |
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement; |
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent; |
import org.openconcerto.erp.core.finance.payment.ui.RegleMontantTable; |
import org.openconcerto.erp.generationEcritures.GenerationReglementAchat; |
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel; |
145,6 → 146,9 |
this.addView("ID_MODE_REGLEMENT", BaseSQLComponent.REQ + ";" + BaseSQLComponent.DEC + ";" + BaseSQLComponent.SEP); |
final ElementSQLObject eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT"); |
this.add(eltModeRegl, c); |
ModeDeReglementSQLComponent modeReglComp; |
modeReglComp = (ModeDeReglementSQLComponent) eltModeRegl.getSQLChild(); |
modeReglComp.addDateCompListener(this.date); |
this.addRequiredSQLObject(this.date, "DATE"); |
this.addRequiredSQLObject(this.montant, "MONTANT"); |
186,10 → 190,7 |
System.err.println("Set mode de règlement"); |
int idTypeRegl = rowModeRegl.getInt("ID_TYPE_REGLEMENT"); |
SQLTable tableModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT").getTable(); |
SQLRowValues rowVals = new SQLRowValues(tableModeRegl); |
if (idTypeRegl > TypeReglementSQLElement.TRAITE) { |
idTypeRegl = TypeReglementSQLElement.CHEQUE; |
} |
SQLRowValues rowVals = new SQLRowValues(tableModeRegl); |
rowVals.put("ID_TYPE_REGLEMENT", idTypeRegl); |
rowVals.put("COMPTANT", Boolean.TRUE); |
rowVals.put("AJOURS", 0); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ReglementPayeSQLElement.java |
---|
57,8 → 57,8 |
protected List<String> getComboFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("NOM_BANQUE"); |
l.add("RIB"); |
l.add("IBAN"); |
l.add("BIC"); |
return l; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/VariablePayeSQLElement.java |
---|
261,6 → 261,7 |
l2.add(tableFichePaye.getField("NET_IMP")); |
l2.add(tableFichePaye.getField("NET_A_PAYER")); |
l2.add(tableFichePaye.getField("CSG")); |
l2.add(tableFichePaye.getField("CSG_REDUITE")); |
mapTree.put("Contenu paye", l2); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ContratSalarieSQLElement.java |
---|
22,6 → 22,8 |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
import java.beans.PropertyChangeEvent; |
import java.beans.PropertyChangeListener; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.HashSet; |
98,8 → 100,10 |
this.add(labelNature, c); |
c.gridx++; |
c.weightx = 1; |
c.gridwidth = 3; |
this.add(textNature, c); |
c.gridwidth = 1; |
// Catégorie socioprofessionnelle |
JLabel labelCatSocio = new JLabel(getLabelFor("ID_CODE_EMPLOI")); |
labelCatSocio.setHorizontalAlignment(SwingConstants.RIGHT); |
112,21 → 116,61 |
c.gridx++; |
c.weightx = 1; |
this.add(selCodeCatSocio, c); |
JLabel complPCSLabel = new JLabel(getLabelFor("COMPLEMENT_PCS")); |
complPCSLabel.setHorizontalAlignment(SwingConstants.RIGHT); |
JTextField complPCS = new JTextField(); |
c.gridy++; |
c.gridx = 0; |
c.gridx++; |
c.weightx = 0; |
this.add(complPCSLabel, c); |
c.gridx++; |
c.weightx = 1; |
this.add(complPCS, c); |
addView(complPCS,"COMPLEMENT_PCS"); |
addView(complPCS, "COMPLEMENT_PCS"); |
JLabel objetSpecLabel = new JLabel(getLabelFor("SPECTACLE_OBJET")); |
objetSpecLabel.setHorizontalAlignment(SwingConstants.RIGHT); |
JTextField objetSpec = new JTextField(); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
this.add(objetSpecLabel, c); |
c.gridx++; |
c.weightx = 1; |
this.add(objetSpec, c); |
addView(objetSpec, "SPECTACLE_OBJET"); |
objetSpec.setEditable(false); |
JLabel jourContratLabel = new JLabel(getLabelFor("SPECTACLE_JOUR_CONTRAT")); |
jourContratLabel.setHorizontalAlignment(SwingConstants.RIGHT); |
JTextField jourContrat = new JTextField(); |
c.gridx++; |
c.weightx = 0; |
this.add(jourContratLabel, c); |
c.gridx++; |
c.weightx = 1; |
this.add(jourContrat, c); |
addView(jourContrat, "SPECTACLE_JOUR_CONTRAT"); |
jourContrat.setEditable(false); |
final ElementComboBox selCaractActivite = new ElementComboBox(); |
selCaractActivite.setInfoIconVisible(false); |
this.addRequiredSQLObject(selCaractActivite, "ID_CODE_CARACT_ACTIVITE"); |
selCaractActivite.addModelListener("wantedID", new PropertyChangeListener() { |
@Override |
public void propertyChange(PropertyChangeEvent evt) { |
final boolean b = selCaractActivite.getSelectedRow() != null && selCaractActivite.getSelectedRow().getString("CODE").equals("04"); |
objetSpec.setEditable(b); |
jourContrat.setEditable(b); |
if (!b) { |
objetSpec.setText(""); |
; |
jourContrat.setText(""); |
} |
} |
}); |
// Contrat de travail |
JLabel labelContratTravail = new JLabel(getLabelFor("ID_CODE_CONTRAT_TRAVAIL")); |
labelContratTravail.setHorizontalAlignment(SwingConstants.RIGHT); |
145,8 → 189,7 |
labelDroitContrat.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selDroitContrat = new ElementComboBox(); |
selDroitContrat.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.gridx++; |
c.weightx = 0; |
this.add(labelDroitContrat, c); |
c.gridx++; |
156,8 → 199,7 |
// caracteristiques activité |
JLabel labelCaractActivite = new JLabel(getLabelFor("ID_CODE_CARACT_ACTIVITE")); |
labelCaractActivite.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selCaractActivite = new ElementComboBox(); |
selCaractActivite.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
171,8 → 213,7 |
labelStatutProf.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selStatutProf = new ElementComboBox(); |
selStatutProf.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.gridx++; |
c.weightx = 0; |
this.add(labelStatutProf, c); |
c.gridx++; |
189,7 → 230,6 |
c.weightx = 0; |
this.add(labelStatutCat, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(selStatutCat, c); |
198,25 → 238,28 |
labelStatutCatConv.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selStatutCatConv = new ElementComboBox(); |
selStatutCatConv.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.gridx++; |
c.weightx = 0; |
this.add(labelStatutCatConv, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(selStatutCatConv, c); |
List<String> dsnFF = Arrays.asList("ID_CONTRAT_MODALITE_TEMPS", "ID_CONTRAT_REGIME_MALADIE", "ID_CONTRAT_REGIME_VIEILLESSE", "ID_CONTRAT_DETACHE_EXPATRIE", |
"ID_CONTRAT_DISPOSITIF_POLITIQUE"); |
"ID_CONTRAT_DISPOSITIF_POLITIQUE", "ID_CONTRAT_MOTIF_RECOURS"); |
int p = 0; |
for (String ffName : dsnFF) { |
JLabel labelFF = new JLabel(getLabelFor(ffName)); |
labelFF.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selFF = new ElementComboBox(); |
selFF.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
if (p % 2 == 0) { |
c.gridy++; |
c.gridx = 0; |
} else { |
c.gridx++; |
} |
p++; |
c.weightx = 0; |
this.add(labelFF, c); |
c.gridx++; |
223,21 → 266,12 |
c.weighty = 1; |
c.weightx = 1; |
this.add(selFF, c); |
this.addRequiredSQLObject(selFF, ffName); |
if (ffName.equals("ID_CONTRAT_MOTIF_RECOURS")) { |
this.addSQLObject(selFF, ffName); |
} else { |
this.addRequiredSQLObject(selFF, ffName); |
} |
} |
JLabel labelFF = new JLabel(getLabelFor("ID_CONTRAT_MOTIF_RECOURS")); |
labelFF.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selFF = new ElementComboBox(); |
selFF.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
this.add(labelFF, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(selFF, c); |
this.addSQLObject(selFF, "ID_CONTRAT_MOTIF_RECOURS"); |
// Code Arrco, agirc retirés du contrat et ajoutés dans les caisses de cotisations |
338,18 → 372,18 |
// this.add(textCodeRegimeRetraite, c); |
// addRequiredSQLObject(textCodeRegimeRetraite, "CODE_REGIME_RETRAITE_DSN"); |
JLabel labelDateModif = new JLabel(getLabelFor("DATE_MODIFICATION")); |
labelDateModif.setHorizontalAlignment(SwingConstants.RIGHT); |
JDate textDateModif = new JDate(); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
this.add(textDateModif, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(textDateModif, c); |
addSQLObject(textDateModif, "DATE_MODIFICATION"); |
// JLabel labelDateModif = new JLabel(getLabelFor("DATE_MODIFICATION")); |
// labelDateModif.setHorizontalAlignment(SwingConstants.RIGHT); |
// JDate textDateModif = new JDate(); |
// c.gridy++; |
// c.gridx = 0; |
// c.weightx = 0; |
// this.add(textDateModif, c); |
// c.gridx++; |
// c.weighty = 1; |
// c.weightx = 1; |
// this.add(textDateModif, c); |
// addSQLObject(textDateModif, "DATE_MODIFICATION"); |
// JLabel labelCM = new JLabel(getLabelFor("ID_INFOS_SALARIE_PAYE_MODIFIE")); |
// labelCM.setHorizontalAlignment(SwingConstants.RIGHT); |
376,7 → 410,6 |
c.weightx = 0; |
this.add(labelDateDebut, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(textDateDebut, c); |
addSQLObject(textDateDebut, "DATE_DEBUT", REQ); |
384,19 → 417,64 |
JLabel labelDateFin = new JLabel(getLabelFor("DATE_PREV_FIN")); |
labelDateFin.setHorizontalAlignment(SwingConstants.RIGHT); |
JDate textDateFin = new JDate(); |
c.gridy++; |
c.gridx = 0; |
c.gridx++; |
c.weightx = 0; |
this.add(labelDateFin, c); |
c.gridx++; |
c.weighty = 1; |
c.weightx = 1; |
this.add(textDateFin, c); |
addSQLObject(textDateFin, "DATE_PREV_FIN"); |
JLabel labelAmen = new JLabel(getLabelFor("ID_CODE_AMENAGEMENT_PARTIEL")); |
labelAmen.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selAmen = new ElementComboBox(); |
selAmen.setInfoIconVisible(false); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
this.add(labelAmen, c); |
c.gridx++; |
c.weightx = 1; |
this.add(selAmen, c); |
this.addSQLObject(selAmen, "ID_CODE_AMENAGEMENT_PARTIEL"); |
JLabel labelSupsension = new JLabel(getLabelFor("ID_CODE_SUSPENSION")); |
labelSupsension.setHorizontalAlignment(SwingConstants.RIGHT); |
ElementComboBox selSupsension = new ElementComboBox(); |
selSupsension.setInfoIconVisible(false); |
c.gridx++; |
c.weightx = 0; |
this.add(labelSupsension, c); |
c.gridx++; |
c.weightx = 1; |
this.add(selSupsension, c); |
this.addSQLObject(selSupsension, "ID_CODE_SUSPENSION"); |
JLabel labelDateDebutSusp = new JLabel(getLabelFor("DATE_DEBUT_SUSPENSION")); |
labelDateDebutSusp.setHorizontalAlignment(SwingConstants.RIGHT); |
JDate textDateDebutSups = new JDate(); |
c.gridy++; |
c.gridx = 0; |
c.weightx = 0; |
this.add(labelDateDebutSusp, c); |
c.gridx++; |
c.weightx = 1; |
this.add(textDateDebutSups, c); |
this.addSQLObject(textDateDebutSups, "DATE_DEBUT_SUSPENSION"); |
JLabel labelDateFinSups = new JLabel(getLabelFor("DATE_FIN_SUSPENSION")); |
labelDateFinSups.setHorizontalAlignment(SwingConstants.RIGHT); |
JDate textDateFinSuspension = new JDate(); |
c.gridx++; |
c.weightx = 0; |
this.add(labelDateFinSups, c); |
c.gridx++; |
c.weightx = 1; |
this.add(textDateFinSuspension, c); |
this.addSQLObject(textDateFinSuspension, "DATE_FIN_SUSPENSION"); |
this.addRequiredSQLObject(selCodeCatSocio, "ID_CODE_EMPLOI"); |
this.addRequiredSQLObject(selContratTravail, "ID_CODE_CONTRAT_TRAVAIL"); |
this.addRequiredSQLObject(selCaractActivite, "ID_CODE_CARACT_ACTIVITE"); |
this.addRequiredSQLObject(selDroitContrat, "ID_CODE_DROIT_CONTRAT"); |
this.addRequiredSQLObject(selStatutProf, "ID_CODE_STATUT_PROF"); |
this.addRequiredSQLObject(selStatutCat, "ID_CODE_STATUT_CATEGORIEL"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeAmenagementPartielSQLElement.java |
---|
New file |
0,0 → 1,28 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.humanresources.payroll.element; |
import org.openconcerto.sql.model.DBRoot; |
public class CodeAmenagementPartielSQLElement extends AbstractCodeSQLElement { |
public CodeAmenagementPartielSQLElement(final DBRoot root) { |
super(root.getTable("CODE_AMENAGEMENT_PARTIEL"), "un code d'aménagement partiel", "codes d'aménagement partiel"); |
} |
@Override |
protected String createCode() { |
return createCodeOfPackage() + ".partiel.code"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeSuspensionSQLElement.java |
---|
New file |
0,0 → 1,28 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.humanresources.payroll.element; |
import org.openconcerto.sql.model.DBRoot; |
public class CodeSuspensionSQLElement extends AbstractCodeSQLElement { |
public CodeSuspensionSQLElement(final DBRoot root) { |
super(root.getTable("CODE_SUSPENSION"), "un code de suspension", "codes suspension"); |
} |
@Override |
protected String createCode() { |
return createCodeOfPackage() + ".supension.code"; |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueBrutSQLElement.java |
---|
27,6 → 27,7 |
import org.openconcerto.sql.sqlobject.SQLRequestComboBox; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.utils.ListMap; |
import org.openconcerto.utils.NoneSelectedButtonGroup; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
69,7 → 70,8 |
l.add("COTISABLE"); |
l.add("PART_CP"); |
l.add("TAXABLE_CM"); |
l.add("CSG_NORMAL"); |
l.add("CSG_REDUIT"); |
return l; |
} |
339,6 → 341,28 |
JCheckBox checkCP = new JCheckBox(getLabelFor("PART_CP")); |
panelProp.add(checkCP, cPanel); |
// CSG Normal |
cPanel.gridx = 1; |
cPanel.weightx = 1; |
cPanel.gridy++; |
c.fill = GridBagConstraints.HORIZONTAL; |
cPanel.gridwidth = GridBagConstraints.REMAINDER; |
JCheckBox checkCSGN = new JCheckBox(getLabelFor("CSG_NORMAL")); |
panelProp.add(checkCSGN, cPanel); |
// CSG Réduite |
cPanel.gridx = 1; |
cPanel.weightx = 1; |
cPanel.gridy++; |
c.fill = GridBagConstraints.HORIZONTAL; |
cPanel.gridwidth = GridBagConstraints.REMAINDER; |
JCheckBox checkCSGR = new JCheckBox(getLabelFor("CSG_REDUIT")); |
panelProp.add(checkCSGR, cPanel); |
NoneSelectedButtonGroup groupCSG = new NoneSelectedButtonGroup(); |
groupCSG.add(checkCSGN); |
groupCSG.add(checkCSGR); |
// Type |
JLabel labelSelCodeRubrique = new JLabel("Code DSN (S21.G00.51.011)"); |
labelSelCodeRubrique.setHorizontalAlignment(SwingConstants.RIGHT); |
377,6 → 401,8 |
this.addSQLObject(checkCotis, "COTISABLE"); |
this.addSQLObject(checkCP, "PART_CP"); |
this.addSQLObject(checkImpo, "TAXABLE_CM"); |
this.addSQLObject(checkCSGN, "CSG_NORMAL"); |
this.addSQLObject(checkCSGR, "CSG_REDUIT"); |
selSalarie.addValueListener(new PropertyChangeListener() { |
394,7 → 420,7 |
rowVals.put("TAXABLE_CM", Boolean.TRUE); |
rowVals.put("COTISABLE", Boolean.TRUE); |
rowVals.put("PART_BRUT", Boolean.TRUE); |
rowVals.put("CSG_NORMAL", Boolean.TRUE); |
return rowVals; |
} |
}; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/FichePayeSQLElement.java |
---|
21,7 → 21,6 |
import org.openconcerto.erp.core.humanresources.payroll.report.FichePayeSheetXML; |
import org.openconcerto.erp.core.humanresources.payroll.ui.FichePayeRenderer; |
import org.openconcerto.erp.core.humanresources.payroll.ui.PanelCumulsPaye; |
import org.openconcerto.erp.generationEcritures.GenerationMvtFichePaye; |
import org.openconcerto.erp.model.FichePayeModel; |
import org.openconcerto.erp.model.MouseSheetXmlListeListener; |
import org.openconcerto.erp.model.RubriquePayeTree; |
49,9 → 48,9 |
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.JDate; |
import org.openconcerto.ui.component.ITextArea; |
import org.openconcerto.ui.component.InteractionMode; |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.ListMap; |
import java.awt.GridBagConstraints; |
import java.awt.GridBagLayout; |
102,9 → 101,32 |
}, true); |
actionCumuls.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(actionCumuls); |
PredicateRowAction genererNonSimplifie = new PredicateRowAction(new AbstractAction("Créer le bulletin détaillé") { |
@Override |
public void actionPerformed(ActionEvent e) { |
SQLRow row = IListe.get(e).getSelectedRow().asRow(); |
FichePayeSheetXML sheet = new FichePayeSheetXML(row, false); |
try { |
sheet.createDocument(); |
sheet.showPrintAndExport(true, false, true); |
} catch (Exception e1) { |
ExceptionHandler.handle("Erreur lors de la création du document.", e1); |
} |
} |
}, false); |
genererNonSimplifie.setPredicate(IListeEvent.getSingleSelectionPredicate()); |
getRowActions().add(genererNonSimplifie); |
} |
@Override |
public ListMap<String, String> getShowAs() { |
final ListMap<String, String> map = new ListMap<>(); |
map.put("ID_SALARIE", Arrays.asList("CODE", "NOM", "PRENOM", "ID_REGLEMENT_PAYE")); |
return map; |
} |
protected List<String> getListFields() { |
final List<String> l = new ArrayList<String>(); |
l.add("ID_SALARIE"); |
155,7 → 177,6 |
JDate dateDu, dateAu; |
private JScrollPane paneTreeLeft; |
private JPanel pDate; |
private JButton buttonValider, buttonGenCompta; |
public void addViews() { |
187,7 → 208,7 |
c.gridheight = 1; |
c.gridwidth = 2; |
this.selSalCombo = new ElementComboBox(); |
// c.gridx++; |
panelRight.add(this.selSalCombo, c); |
// Mois |
199,7 → 220,6 |
this.dateDu = new JDate(); |
this.dateAu = new JDate(); |
// JTextField textMois = new JTextField(); |
JLabel labelAnnee = new JLabel("Année"); |
this.textAnnee = new JTextField(); |
{ |
225,7 → 245,6 |
this.pDate.add(this.dateAu, cDate); |
c.gridy++; |
// c.gridx++; |
c.fill = GridBagConstraints.HORIZONTAL; |
c.weightx = 1; |
c.weighty = 0; |
233,11 → 252,6 |
c.gridwidth = 2; |
panelRight.add(this.pDate, c); |
} |
// c.gridx += 2; |
// c.weightx = 1; |
// c.gridwidth = 1; |
// c.fill = GridBagConstraints.HORIZONTAL; |
// panelRight.add(new JPanel(), c); |
// Action Button |
303,16 → 317,16 |
// Total Periode |
JPanel panelTotal = new JPanel(new GridBagLayout()); |
panelTotal.setBorder(BorderFactory.createTitledBorder("Total période")); |
panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux sur la période")); |
GridBagConstraints cPanel = new DefaultGridBagConstraints(); |
JLabel labelInfosConges = new JLabel(getLabelFor("DETAILS_CONGES")); |
panelTotal.add(labelInfosConges, cPanel); |
ITextArea textConges = new ITextArea(); |
JTextField textConges = new JTextField(); |
cPanel.gridx++; |
cPanel.weightx = 1; |
cPanel.gridwidth = GridBagConstraints.REMAINDER; |
cPanel.gridwidth = 5; |
panelTotal.add(textConges, cPanel); |
addView(textConges, "DETAILS_CONGES"); |
325,7 → 339,7 |
panelTotal.add(labelBrut, cPanel); |
JTextField textSalBrut = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 0; |
cPanel.weightx = 1; |
panelTotal.add(textSalBrut, cPanel); |
textSalBrut.setEditable(false); |
textSalBrut.setEnabled(false); |
332,10 → 346,12 |
// acompte |
cPanel.gridx++; |
cPanel.weightx = 0; |
JLabel labelAcompte = new JLabel(getLabelFor("ACOMPTE")); |
panelTotal.add(labelAcompte, cPanel); |
JTextField textAcompte = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textAcompte, cPanel); |
// textAcompte.setEditable(false); |
// textAcompte.setEnabled(false); |
342,19 → 358,23 |
// Conges Acquis |
cPanel.gridx++; |
cPanel.weightx = 0; |
JLabel labelCongesAcquis = new JLabel(getLabelFor("CONGES_ACQUIS")); |
panelTotal.add(labelCongesAcquis, cPanel); |
JTextField textCongesAcquis = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textCongesAcquis, cPanel); |
// cotisation salariale |
cPanel.gridx = 0; |
cPanel.gridy++; |
cPanel.weightx = 0; |
JLabel labelCotSal = new JLabel(getLabelFor("COT_SAL")); |
panelTotal.add(labelCotSal, cPanel); |
JTextField textCotSal = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textCotSal, cPanel); |
textCotSal.setEditable(false); |
textCotSal.setEnabled(false); |
361,10 → 381,12 |
// cotisation patronale |
cPanel.gridx++; |
cPanel.weightx = 0; |
JLabel labelCotPat = new JLabel(getLabelFor("COT_PAT")); |
panelTotal.add(labelCotPat, cPanel); |
JTextField textCotPat = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textCotPat, cPanel); |
textCotPat.setEditable(false); |
textCotPat.setEnabled(false); |
371,9 → 393,11 |
JLabel labelCSG = new JLabel(getLabelFor("CSG")); |
cPanel.gridx++; |
cPanel.weightx = 0; |
panelTotal.add(labelCSG, cPanel); |
JTextField textCSG = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textCSG, cPanel); |
textCSG.setEditable(false); |
textCSG.setEnabled(false); |
381,28 → 405,34 |
// net imposable |
cPanel.gridx = 0; |
cPanel.gridy++; |
cPanel.weightx = 0; |
JLabel labelNetImp = new JLabel(getLabelFor("NET_IMP")); |
panelTotal.add(labelNetImp, cPanel); |
JTextField textNetImp = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textNetImp, cPanel); |
textNetImp.setEditable(false); |
textNetImp.setEnabled(false); |
cPanel.gridx++; |
cPanel.weightx = 0; |
JLabel labelNetAPayer = new JLabel(getLabelFor("NET_A_PAYER")); |
panelTotal.add(labelNetAPayer, cPanel); |
JTextField textNetAPayer = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textNetAPayer, cPanel); |
textNetAPayer.setEditable(false); |
textNetAPayer.setEnabled(false); |
cPanel.gridx++; |
cPanel.weightx = 0; |
JLabel labelCice = new JLabel(getLabelFor("CICE")); |
panelTotal.add(labelCice, cPanel); |
JTextField textCice = new JTextField(10); |
cPanel.gridx++; |
cPanel.weightx = 1; |
panelTotal.add(textCice, cPanel); |
textCice.setEditable(false); |
textCice.setEnabled(false); |
418,18 → 448,6 |
// Cumuls |
c.gridx = 1; |
c.gridy++; |
c.gridwidth = 1; |
c.fill = GridBagConstraints.NONE; |
this.buttonValider = new JButton("Valider"); |
// panelRight.add(buttonValider, c); |
c.gridx++; |
c.gridwidth = 1; |
this.buttonGenCompta = new JButton("Generer la comptabilité"); |
// panelRight.add(buttonGenCompta, c); |
GridBagConstraints cGlobal = new DefaultGridBagConstraints(); |
cGlobal.gridx = 0; |
cGlobal.gridy = 0; |
440,32 → 458,6 |
cGlobal.weighty = 1; |
this.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, this.paneTreeLeft, panelRight), cGlobal); |
// Listeners |
this.buttonGenCompta.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent e) { |
try { |
int[] i = new int[1]; |
i[0] = getSelectedID(); |
SQLRow rowMois = getTable().getBase().getTable("MOIS").getRow(selMois.getSelectedId()); |
new GenerationMvtFichePaye(i, rowMois.getString("NOM"), textAnnee.getText()); |
} catch (Exception ex) { |
ExceptionHandler.handle("Erreur de génération des mouvements", ex); |
} |
} |
}); |
this.buttonValider.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent e) { |
try { |
validationFiche(); |
} catch (SQLException e1) { |
ExceptionHandler.handle("Error while updating pay slip", e1); |
} |
} |
}); |
buttonUp.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent e) { |
565,7 → 557,6 |
cal.set(Calendar.DAY_OF_MONTH, 1); |
cal.set(Calendar.MONTH, selMois.getSelectedId() - 2); |
System.err.println("Du " + cal.getTime()); |
dateDu.setValue(cal.getTime()); |
} |
fireValidChange(); |
591,7 → 582,6 |
cal.set(Calendar.DAY_OF_MONTH, 1); |
cal.set(Calendar.MONTH, selMois.getSelectedId() - 2); |
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); |
System.err.println("Au " + cal.getTime()); |
dateAu.setValue(cal.getTime()); |
} |
fireValidChange(); |
680,7 → 670,6 |
this.selSalCombo.setVisible(((Boolean) r.getObject("VALIDE")).booleanValue()); |
this.paneTreeLeft.setVisible(!((Boolean) r.getObject("VALIDE")).booleanValue()); |
this.buttonValider.setVisible(!((Boolean) r.getObject("VALIDE")).booleanValue()); |
setpDateEnabled(!((Boolean) r.getObject("VALIDE")).booleanValue()); |
} |
this.selSalCombo.setInteractionMode(InteractionMode.DISABLED); |
690,30 → 679,16 |
} |
private void setpDateEnabled(boolean b) { |
// System.err.println("Set date enable --> " + b); |
this.selMois.setInteractionMode((b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED); |
// this.selMois.setEnabled(b); |
this.textAnnee.setEditable(b); |
this.textAnnee.setEnabled(b); |
this.dateDu.setInteractionMode((b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED); |
this.dateAu.setInteractionMode((b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED); |
} |
private void validationFiche() throws SQLException { |
this.update(); |
FichePayeSQLElement.validationFiche(this.getSelectedID()); |
} |
protected SQLRowValues createDefaults() { |
System.err.println("**********Set Defaults on FichePaye.date"); |
SQLRowValues rowVals = new SQLRowValues(getTable()); |
Calendar cal = Calendar.getInstance(); |
final SQLRowValues rowVals = new SQLRowValues(getTable()); |
final Calendar cal = Calendar.getInstance(); |
rowVals.put("ID_MOIS", cal.get(Calendar.MONTH) + 2); |
rowVals.put("ANNEE", cal.get(Calendar.YEAR)); |
739,7 → 714,6 |
if (JOptionPane.showConfirmDialog(null, "Soustraire les cumuls de cette fiche à celle en cours?", "Suppression d'une fiche de paye", |
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { |
// on effectue le cumul |
// System.err.println("Calcul des cumuls"); |
SQLRow rowSal = row.getForeignRow("ID_SALARIE"); |
845,13 → 819,8 |
// creer et associer une nouvelle fiche au salarie |
final SQLRowValues rowValsNewFiche = new SQLRowValues(tableFiche); |
try { |
SQLRow r = rowValsNewFiche.insert(); |
rowValsNewFiche.put("ID", r.getID()); |
// System.err.println("rowValsNewFiche -----> " + r.getID()); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
SQLRow r = rowValsNewFiche.insert(); |
rowValsNewFiche.put("ID", r.getID()); |
// mis a jour de la periode |
int mois = rowFiche.getInt("ID_MOIS"); |
865,22 → 834,6 |
calDu.set(Calendar.DAY_OF_MONTH, calDu.getActualMaximum(Calendar.DAY_OF_MONTH)); |
rowValsNewFiche.put("AU", calDu.getTime()); |
rowValsNewFiche.put("ID_PROFIL_PAYE", rowFiche.getInt("ID_PROFIL_PAYE")); |
/* |
* int ancMois = rowFiche.getInt("ID_MOIS"); int ancAnnee = rowFiche.getInt("ANNEE"); |
* |
* rowValsSal.put("DERNIER_MOIS", ancMois); rowValsSal.put("DERNIERE_ANNEE", ancAnnee); |
* |
* try { rowValsSal.update(rowFiche.getInt("ID_SALARIE")); } catch (SQLException e1) { |
* e1.printStackTrace(); } |
* |
* int mois = ancMois - 2; mois = (mois + 1) % 12; mois += 2; int annee = ancAnnee; if (mois |
* == 2) { annee++; } rowValsNewFiche.put("ID_MOIS", mois); rowValsNewFiche.put("ANNEE", |
* annee); rowValsNewFiche.put("ID_PROFIL_PAYE", rowFiche.getInt("ID_PROFIL_PAYE")); |
* |
* try { rowValsNewFiche.update(); } catch (SQLException e) { e.printStackTrace(); } |
*/ |
rowValsNewFiche.put("ID_SALARIE", rowSal.getID()); |
rowValsSal.put("ID_FICHE_PAYE", rowValsNewFiche.getID()); |
919,7 → 872,6 |
} |
// on effectue le cumul |
// System.err.println("Calcul des cumuls"); |
final SQLRow rowVarSal = tableVariableSal.getRow(rowSal.getInt("ID_VARIABLE_SALARIE")); |
int idCumuls = rowSal.getInt("ID_CUMULS_PAYE"); |
SQLRow rowCumuls = tableCumuls.getRow(idCumuls); |
932,10 → 884,9 |
float netAPayer = rowCumuls.getFloat("NET_A_PAYER_C") + rowFiche.getFloat("NET_A_PAYER") + rowFiche.getFloat("ACOMPTE"); |
rowValsCumul.put("NET_A_PAYER_C", new Float(netAPayer)); |
SQLRow r = rowValsCumul.insert(); |
rowValsCumul.put("ID", r.getID()); |
SQLRow row = rowValsCumul.insert(); |
rowValsCumul.put("ID", row.getID()); |
// System.err.println("Mis a jour de la fiche de paye"); |
rowValsSal.put("ID_CUMULS_PAYE", rowValsCumul.getID()); |
SwingUtilities.invokeLater(new Runnable() { |
1054,13 → 1005,7 |
e1.printStackTrace(); |
} |
} |
/* |
* int mois = ancMois - 2; mois = (mois + 1) % 12; mois += 2; int annee = ancAnnee; if (mois |
* == 2) { annee++; } rowValsNewFiche.put("ID_MOIS", mois); rowValsNewFiche.put("ANNEE", |
* annee); rowValsNewFiche.put("ID_PROFIL_PAYE", rowFiche.getInt("ID_PROFIL_PAYE")); |
* |
* try { rowValsNewFiche.update(); } catch (SQLException e) { e.printStackTrace(); } |
*/ |
} |
// stocke les éléments validés (cumuls congés, paye, ...) |
1094,7 → 1039,6 |
private static void validElements(int id) { |
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete(); |
System.err.println("Validation des éléments de la fiche."); |
String trueString = "1"; |
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) { |
trueString = "true"; |
1103,7 → 1047,6 |
base.getDataSource().execute(req); |
System.err.println("Validation terminée."); |
} |
private static boolean checkDateValid(int idFiche) { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/FichePayeSheetXML.java |
---|
46,13 → 46,16 |
final Map<Integer, String> cotisationSimplifieeLink = new HashMap<>(); |
public FichePayeSheetXML(final SQLRow row) { |
this(row, !new SQLPreferences(row.getTable().getDBRoot()).getBoolean(PayeGlobalPreferencePanel.NOT_PAYE_SIMPL, Boolean.FALSE)); |
} |
public FichePayeSheetXML(final SQLRow row, boolean simplifie) { |
super(row); |
this.printer = PrinterNXProps.getInstance().getStringProperty("FichePayePrinter"); |
this.elt = Configuration.getInstance().getDirectory().getElement("FICHE_PAYE"); |
SQLPreferences prefs = new SQLPreferences(elt.getTable().getDBRoot()); |
boolean prefBulletinSimpl = !prefs.getBoolean(PayeGlobalPreferencePanel.NOT_PAYE_SIMPL, Boolean.FALSE); |
if (prefBulletinSimpl) { |
if (simplifie) { |
SQLSelect sel = new SQLSelect(); |
sel.addSelect(row.getTable().getDBRoot().findTable("RUBRIQUE_COTISATION").getField("LIGNE_PAYE_SIMPLIFIEE")); |
sel.addSelect(row.getTable().getDBRoot().findTable("RUBRIQUE_COTISATION").getKey()); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/LivrePayeSheet.java |
---|
21,6 → 21,7 |
import org.openconcerto.sql.model.SQLSelect; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.utils.StringUtils; |
import java.text.DateFormat; |
import java.util.Date; |
156,75 → 157,88 |
mapSal.put(new Integer(idSal), ""); |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_BRUT")) { |
float montantTestTotal = 0; |
if (rowFicheElt.getObject("MONTANT_SAL_AJ") != null) { |
montantTestTotal += rowFicheElt.getFloat("MONTANT_SAL_AJ"); |
} |
if (rowFicheElt.getObject("MONTANT_SAL_DED") != null) { |
montantTestTotal -= rowFicheElt.getFloat("MONTANT_SAL_DED"); |
} |
mapRubriqueBrut.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalbrut; |
if (mapSalarieBrut.get(new Integer(idSal)) == null) { |
mapSalarieBrut.put(new Integer(idSal), mapValue); |
} else { |
mapValue = (Map) mapSalarieBrut.get(new Integer(idSal)); |
} |
} else { |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_COTISATION")) { |
mapRubriqueCot.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalCot; |
if (mapSalarieCot.get(new Integer(idSal)) == null) { |
mapSalarieCot.put(new Integer(idSal), mapValue); |
if (rowFicheElt.getObject("MONTANT_PAT") != null) { |
montantTestTotal += rowFicheElt.getFloat("MONTANT_PAT"); |
} |
if (montantTestTotal != 0) { |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_BRUT")) { |
mapRubriqueBrut.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalbrut; |
if (mapSalarieBrut.get(new Integer(idSal)) == null) { |
mapSalarieBrut.put(new Integer(idSal), mapValue); |
} else { |
mapValue = (Map) mapSalarieCot.get(new Integer(idSal)); |
mapValue = (Map) mapSalarieBrut.get(new Integer(idSal)); |
} |
} else { |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_NET")) { |
mapRubriqueNet.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalNet; |
if (mapSalarieNet.get(new Integer(idSal)) == null) { |
mapSalarieNet.put(new Integer(idSal), mapValue); |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_COTISATION")) { |
mapRubriqueCot.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalCot; |
if (mapSalarieCot.get(new Integer(idSal)) == null) { |
mapSalarieCot.put(new Integer(idSal), mapValue); |
} else { |
mapValue = (Map) mapSalarieNet.get(new Integer(idSal)); |
mapValue = (Map) mapSalarieCot.get(new Integer(idSal)); |
} |
} else { |
if (rowFicheElt.getString("SOURCE").equalsIgnoreCase("RUBRIQUE_NET")) { |
mapRubriqueNet.put(new Integer(rowFicheElt.getInt("IDSOURCE")), ""); |
mapTotal = mapTotalNet; |
if (mapSalarieNet.get(new Integer(idSal)) == null) { |
mapSalarieNet.put(new Integer(idSal), mapValue); |
} else { |
mapValue = (Map) mapSalarieNet.get(new Integer(idSal)); |
} |
} |
} |
} |
} |
if (rowFicheElt.getObject("MONTANT_SAL_AJ") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
if (rowFicheElt.getObject("MONTANT_SAL_AJ") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTotal = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant += rowFicheElt.getFloat("MONTANT_SAL_AJ"); |
montantTotal += rowFicheElt.getFloat("MONTANT_SAL_AJ"); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTotal = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant += rowFicheElt.getFloat("MONTANT_SAL_AJ"); |
montantTotal += rowFicheElt.getFloat("MONTANT_SAL_AJ"); |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montantTotal)); |
} |
if (rowFicheElt.getObject("MONTANT_SAL_DED") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montantTotal)); |
} |
if (rowFicheElt.getObject("MONTANT_SAL_DED") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE"))); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTot = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant -= rowFicheElt.getFloat("MONTANT_SAL_DED"); |
montantTot -= rowFicheElt.getFloat("MONTANT_SAL_DED"); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTot = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant -= rowFicheElt.getFloat("MONTANT_SAL_DED"); |
montantTot -= rowFicheElt.getFloat("MONTANT_SAL_DED"); |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montantTot)); |
} |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")), new Float(montantTot)); |
} |
if (rowFicheElt.getObject("MONTANT_PAT") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT"); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT"); |
if (rowFicheElt.getObject("MONTANT_PAT") != null) { |
Object o = mapValue.get(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT"); |
Object oTot = mapTotal.get(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT"); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTotal = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant += rowFicheElt.getFloat("MONTANT_PAT"); |
montantTotal += rowFicheElt.getFloat("MONTANT_PAT"); |
float montant = (o == null) ? 0.0F : ((Float) o).floatValue(); |
float montantTotal = (oTot == null) ? 0.0F : ((Float) oTot).floatValue(); |
montant += rowFicheElt.getFloat("MONTANT_PAT"); |
montantTotal += rowFicheElt.getFloat("MONTANT_PAT"); |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT", new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT", new Float(montantTotal)); |
mapValue.put(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT", new Float(montant)); |
mapTotal.put(new Integer(rowFicheElt.getInt("IDSOURCE")) + "_PAT", new Float(montantTotal)); |
} |
} |
} |
// Dump |
287,7 → 301,7 |
int idRub = ((Number) mapRubriqueBrut.keySet().toArray()[i]).intValue(); |
SQLRow rowRub = tableRubBrut.getRow(idRub); |
this.mCell.put("A" + posLine, rowRub.getObject("NOM")); |
this.mCell.put("A" + posLine, StringUtils.limitLength(rowRub.getString("NOM"), 55)); |
this.mCell.put("B" + posLine, fillLine(mapSalarieBrut, idRub, mapSal, numFirstSal, mapTotalbrut, false)); |
this.mCell.put("C" + posLine, fillLine(mapSalarieBrut, idRub, mapSal, numFirstSal, mapTotalbrut, true)); |
303,7 → 317,7 |
int idRub = ((Number) mapRubriqueCot.keySet().toArray()[i]).intValue(); |
SQLRow rowRub = tableRubCot.getRow(idRub); |
this.mCell.put("A" + posLine, rowRub.getObject("NOM")); |
this.mCell.put("A" + posLine, StringUtils.limitLength(rowRub.getString("NOM"), 55)); |
this.mCell.put("B" + posLine, fillLine(mapSalarieCot, idRub, mapSal, numFirstSal, mapTotalCot, false)); |
this.mCell.put("C" + posLine, fillLine(mapSalarieCot, idRub, mapSal, numFirstSal, mapTotalCot, true)); |
320,7 → 334,7 |
int idRub = ((Number) mapRubriqueNet.keySet().toArray()[i]).intValue(); |
SQLRow rowRub = tableRubNet.getRow(idRub); |
this.mCell.put("A" + posLine, rowRub.getObject("NOM")); |
this.mCell.put("A" + posLine, StringUtils.limitLength(rowRub.getString("NOM"), 55)); |
this.mCell.put("B" + posLine, fillLine(mapSalarieNet, idRub, mapSal, numFirstSal, mapTotalNet, false)); |
this.mCell.put("C" + posLine, fillLine(mapSalarieNet, idRub, mapSal, numFirstSal, mapTotalNet, true)); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/action/ListeDesBonsDeLivraisonAction.java |
---|
21,7 → 21,6 |
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement; |
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet; |
import org.openconcerto.erp.model.MouseSheetXmlListeListener; |
import org.openconcerto.erp.utils.TM; |
import org.openconcerto.sql.model.FieldPath; |
import org.openconcerto.sql.model.SQLField; |
import org.openconcerto.sql.model.SQLInjector; |
74,9 → 73,9 |
// Tabs |
final JTabbedPane tabs = new JTabbedPane(); |
tabs.addTab(TM.tr("sales.shipment.allShipments"), createAllDeliveryPanel(toInvoiceAction)); |
tabs.addTab(TM.tr("sales.shipment.nonInvoicedShipments"), createDeliveryWithoutInvoicePanel(toInvoiceAction)); |
tabs.addTab(TM.tr("sales.shipment.invoicedShipments"), createDeliveryWithInvoicePanel()); |
tabs.addTab(getConf().getERP_TM().translate("sales.shipment.allShipments"), createAllDeliveryPanel(toInvoiceAction)); |
tabs.addTab(getConf().getERP_TM().translate("sales.shipment.nonInvoicedShipments"), createDeliveryWithoutInvoicePanel(toInvoiceAction)); |
tabs.addTab(getConf().getERP_TM().translate("sales.shipment.invoicedShipments"), createDeliveryWithInvoicePanel()); |
frame.setContentPane(tabs); |
return frame; |
87,7 → 86,7 |
final List<SQLField> fields = new ArrayList<SQLField>(2); |
fields.add(eltCmd.getTable().getField("TOTAL_HT")); |
final IListTotalPanel totalPanel = new IListTotalPanel(panel.getListe(), fields, TM.tr("sales.shipment.listTotal")); |
final IListTotalPanel totalPanel = new IListTotalPanel(panel.getListe(), fields, getConf().getERP_TM().translate("sales.shipment.listTotal")); |
final GridBagConstraints c = new DefaultGridBagConstraints(); |
c.gridwidth = GridBagConstraints.REMAINDER; |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/ui/BonDeLivraisonItemTable.java |
---|
27,6 → 27,7 |
import org.openconcerto.erp.core.sales.pos.io.BarcodeReader; |
import org.openconcerto.erp.core.sales.pos.ui.BarcodeListener; |
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement; |
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement; |
import org.openconcerto.erp.core.sales.product.ui.ArticleRowValuesRenderer; |
import org.openconcerto.erp.core.sales.product.ui.CurrencyWithSymbolRenderer; |
import org.openconcerto.erp.core.sales.product.ui.DeliveredQtyRowValuesRenderer; |
33,6 → 34,7 |
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer; |
import org.openconcerto.erp.core.sales.product.ui.QtyToDeliverRowValuesRenderer; |
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable; |
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement; |
import org.openconcerto.erp.preferences.DefaultNXProps; |
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel; |
import org.openconcerto.sql.Configuration; |
51,6 → 53,8 |
import org.openconcerto.sql.sqlobject.ITextWithCompletion; |
import org.openconcerto.sql.users.rights.UserRights; |
import org.openconcerto.sql.users.rights.UserRightsManager; |
import org.openconcerto.sql.view.EditFrame; |
import org.openconcerto.sql.view.EditPanel.EditMode; |
import org.openconcerto.sql.view.list.AutoCompletionManager; |
import org.openconcerto.sql.view.list.CellDynamicModifier; |
import org.openconcerto.sql.view.list.RowValuesTable; |
66,6 → 70,7 |
import java.awt.Component; |
import java.awt.event.ActionEvent; |
import java.awt.event.ActionListener; |
import java.awt.event.HierarchyEvent; |
import java.awt.event.HierarchyListener; |
import java.awt.event.KeyEvent; |
75,7 → 80,9 |
import java.math.RoundingMode; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.HashMap; |
import java.util.List; |
import java.util.Map; |
import java.util.Vector; |
import javax.swing.AbstractAction; |
105,12 → 112,20 |
this.reliquatTable = reliquatTable; |
} |
public static Map<String, Boolean> customVisibilityMap = new HashMap<String, Boolean>(); |
@Override |
protected Map<String, Boolean> getCustomVisibilityMap() { |
return customVisibilityMap; |
} |
@Override |
protected void init() { |
final SQLElement e = getSQLElement(); |
SQLPreferences prefs = new SQLPreferences(getSQLElement().getTable().getDBRoot()); |
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false); |
final boolean activeCalculM2 = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_CALCUL_M2, false); |
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true); |
final boolean filterFamilleArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.FILTER_BY_FAMILY, false); |
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false); |
126,7 → 141,11 |
final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE")); |
list.add(tableFamille); |
// Article |
SQLTableElement tableElementDepot = new SQLTableElement(e.getTable().getField("ID_DEPOT_STOCK"), true, true, true); |
list.add(tableElementDepot); |
// Article |
final SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
321,6 → 340,29 |
list.add(eltUnitDevise); |
} |
SQLTableElement eltLongueur = new SQLTableElement(e.getTable().getField("LONGUEUR")) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
int idUv = vals.getForeignID("ID_UNITE_VENTE"); |
return idUv == UniteVenteArticleSQLElement.M2; |
} |
}; |
list.add(eltLongueur); |
SQLTableElement eltLargeur = new SQLTableElement(e.getTable().getField("LARGEUR")) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
int idUv = vals.getForeignID("ID_UNITE_VENTE"); |
return idUv == UniteVenteArticleSQLElement.M2; |
} |
}; |
list.add(eltLargeur); |
SQLTableElement eltHauteur = new SQLTableElement(e.getTable().getField("HAUTEUR")); |
list.add(eltHauteur); |
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) { |
@Override |
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) { |
328,6 → 370,8 |
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE"); |
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) { |
return false; |
} else if (activeCalculM2 && row != null && !row.isUndefined() && row.getID() == UniteVenteArticleSQLElement.M2) { |
return false; |
} else { |
return super.isCellEditable(vals, rowIndex, columnIndex); |
} |
596,7 → 640,7 |
rowVals.put("PV_T_DEVISE", rowVals.getBigDecimal("PRIX_METRIQUE_VT_1").multiply(globalQty)); |
} |
} |
super.commitData(); |
super.commitData(true); |
} |
}; |
this.setModel(model); |
603,6 → 647,7 |
this.table = new RowValuesTable(model, getConfigurationFile()); |
ToolTipManager.sharedInstance().unregisterComponent(this.table); |
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader()); |
this.table.getClearCloneTableElement().add("ID_COMMANDE_CLIENT_ELEMENT"); |
if (filterFamilleArticle) { |
((SQLTextComboTableCellEditor) tableElementArticle.getTableCellEditor(this.table)).setDynamicWhere(e.getTable().getTable("ARTICLE").getField("ID_FAMILLE_ARTICLE")); |
636,6 → 681,9 |
completionField.add("PRIX_METRIQUE_VT_3"); |
completionField.add("SERVICE"); |
completionField.add("ID_FAMILLE_ARTICLE"); |
completionField.add("LONGUEUR"); |
completionField.add("LARGEUR"); |
completionField.add("HAUTEUR"); |
if (getSQLElement().getTable().getFieldsName().contains("DESCRIPTIF")) { |
completionField.add("DESCRIPTIF"); |
} |
655,7 → 703,7 |
Object res = tarifCompletion(row, field, rowDest, true); |
if (res == null) { |
res = super.getValueFrom(row, field, rowDest); |
} |
} |
if (field.equals("POURCENT_REMISE")) { |
return getRemiseClient(row); |
} |
747,7 → 795,7 |
Object res = tarifCompletion(row, field, rowDest, true); |
if (res == null) { |
res = super.getValueFrom(row, field, rowDest); |
} |
} |
if (field.equals("POURCENT_REMISE")) { |
return getRemiseClient(row); |
} |
770,7 → 818,7 |
Object res = tarifCompletion(row, field, rowDest, true); |
if (res == null) { |
res = super.getValueFrom(row, field, rowDest); |
} |
} |
if (field.equals("POURCENT_REMISE")) { |
return getRemiseClient(row); |
} |
1071,6 → 1119,28 |
} |
}); |
uniteVente.addModificationListener(qteU); |
eltLargeur.addModificationListener(qteU); |
eltLongueur.addModificationListener(qteU); |
qteU.setModifier(new CellDynamicModifier() { |
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) { |
SQLRowAccessor rowUnite = row.getForeign("ID_UNITE_VENTE"); |
if (rowUnite != null && !rowUnite.isUndefined() && rowUnite.getBoolean("A_LA_PIECE")) { |
return BigDecimal.ONE; |
} else if (activeCalculM2 && rowUnite != null && !rowUnite.isUndefined() && rowUnite.getID() == UniteVenteArticleSQLElement.M2) { |
BigDecimal longueur = row.getBigDecimal("LONGUEUR"); |
BigDecimal largeur = row.getBigDecimal("LARGEUR"); |
if (longueur == null || largeur == null) { |
return BigDecimal.ONE; |
} |
return longueur.multiply(largeur); |
} else { |
return row.getObject("QTE_UNITAIRE"); |
} |
} |
}); |
// Mode Gestion article avancé |
String valModeAvanceVt = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance"); |
Boolean bModeAvance = Boolean.valueOf(valModeAvanceVt); |
1088,6 → 1158,11 |
setColumnVisible(model.getColumnForField("T_POIDS_COLIS_NET"), false); |
} |
// ACtivation calcul m2 |
setColumnVisible(model.getColumnForField("HAUTEUR"), false); |
setColumnVisible(model.getColumnForField("LARGEUR"), activeCalculM2); |
setColumnVisible(model.getColumnForField("LONGUEUR"), activeCalculM2); |
setColumnVisible(model.getColumnForField("ID_ARTICLE"), selectArticle); |
setColumnVisible(model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto)); |
setColumnVisible(model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto)); |
1108,10 → 1183,23 |
setColumnVisible(model.getColumnForField("PRIX_METRIQUE_HA_1"), showHAPrice); |
setColumnVisible(model.getColumnForField("MARGE_HT"), showHAPrice); |
setColumnVisible(model.getColumnForField("T_PA_HT"), showHAPrice); |
setColumnVisible(model.getColumnForField("ID_DEPOT_STOCK"), prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)); |
if (e.getTable().contains("ID_COMMANDE_CLIENT_ELEMENT")) { |
setColumnVisible(model.getColumnForField("ID_COMMANDE_CLIENT_ELEMENT"), false); |
} |
for (String string : AbstractVenteArticleItemTable.getVisibilityMap().keySet()) { |
setColumnVisible(model.getColumnForField(string), AbstractVenteArticleItemTable.getVisibilityMap().get(string)); |
} |
Map<String, Boolean> mapCustom = getCustomVisibilityMap(); |
if (mapCustom != null) { |
for (String string : mapCustom.keySet()) { |
setColumnVisible(model.getColumnForField(string), mapCustom.get(string)); |
} |
} |
// Barcode reader |
final BarcodeReader barcodeReader = ComptaPropsConfiguration.getInstanceCompta().getBarcodeReader(); |
if (barcodeReader != null) { |
1159,6 → 1247,34 |
} |
if (this.table.getRowValuesTableModel().getColumnForField("ID_DEPOT_STOCK") >= 0 && this.table.getRowValuesTableModel().getColumnForField("ID_ARTICLE") >= 0) { |
if (this.buttons == null) { |
this.buttons = new ArrayList<>(); |
} |
JButton buttonStock = new JButton("Consulter le stock"); |
buttonStock.addActionListener(new ActionListener() { |
public void actionPerformed(ActionEvent event) { |
SQLRowValues rowValsSel = table.getSelectedRowValues(); |
if (rowValsSel != null) { |
SQLRowAccessor foreignArt = rowValsSel.getForeign("ID_ARTICLE"); |
if (foreignArt != null && !foreignArt.isUndefined()) { |
SQLRowAccessor rowValsStock = StockSQLElement.getStock(rowValsSel); |
if (rowValsStock != null && !rowValsStock.isUndefined()) { |
EditFrame frame = new EditFrame(table.getRowValuesTableModel().getSQLElement().getDirectory().getElement("STOCK"), EditMode.READONLY); |
frame.selectionId(rowValsStock.getID()); |
frame.setVisible(true); |
} |
} |
} |
} |
}); |
this.buttons.add(buttonStock); |
} |
// On réécrit la configuration au cas ou les preferences aurait changé |
this.table.writeState(); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/component/AvoirClientSQLComponent.java |
---|
956,13 → 956,16 |
} |
rowVals.update(); |
EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE"); |
final int foreignIDmvt = rowFacture.getForeignID("ID_MOUVEMENT"); |
eltEcr.archiveMouvementProfondeur(foreignIDmvt, false); |
System.err.println("Regeneration des ecritures"); |
new GenerationMvtSaisieVenteFacture(rowFacture.getID(), foreignIDmvt); |
System.err.println("Fin regeneration"); |
List<SQLRow> rowEch = rowFacture.getReferentRows(rowFacture.getTable().getTable("ECHEANCE_CLIENT")); |
for (SQLRow sqlRow : rowEch) { |
if (!sqlRow.getBoolean("REG_COMPTA") && !sqlRow.getBoolean("REGLE")) { |
// update echeance |
SQLRowValues createEmptyUpdateRow2 = sqlRow.createEmptyUpdateRow(); |
createEmptyUpdateRow2.put("MONTANT", Math.max(0, sqlRow.getLong("MONTANT") - totalAvoir)); |
createEmptyUpdateRow2.commit(); |
break; |
} |
} |
} catch (SQLException e1) { |
ExceptionHandler.handle("Erreur lors de l'affection de l'avoir sur la facture!", e1); |
} finally { |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/component/CommandeClientSQLComponent.java |
---|
864,10 → 864,10 |
super.select(rVals); |
} |
if (r != null) { |
this.table.insertFrom("ID_COMMANDE_CLIENT", r.getID()); |
this.tableFacturationItem.insertFrom("ID_COMMANDE_CLIENT", r.getID()); |
this.table.getRowValuesTable().insertFrom(r); |
this.tableFacturationItem.getRowValuesTable().insertFrom(r); |
if (this.tableChiffrageItem != null) { |
this.tableChiffrageItem.insertFrom("ID_COMMANDE_CLIENT", r.getID()); |
this.tableChiffrageItem.getRowValuesTable().insertFrom(r); |
} |
} |
// this.radioEtat.setVisible(r.getID() > 1); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientElementSQLElement.java |
---|
74,6 → 74,22 |
rowAction.setPredicate(IListeEvent.getNonEmptySelectionPredicate()); |
getRowActions().add(rowAction); |
PredicateRowAction rowActionBL = new PredicateRowAction(new AbstractAction("Transférer la commande en BL") { |
@Override |
public void actionPerformed(ActionEvent e) { |
List<SQLRowValues> resultId = new ArrayList<>(); |
CommandeClientSQLElement cmdElt = (CommandeClientSQLElement) getForeignElement("ID_COMMANDE_CLIENT"); |
for (SQLRowValues sqlRowAccessor : IListe.get(e).getSelectedRows()) { |
resultId.add(sqlRowAccessor.getForeign("ID_COMMANDE_CLIENT").asRowValues()); |
} |
cmdElt.transfertBonLivraisonClient(resultId); |
} |
}, true); |
rowActionBL.setPredicate(IListeEvent.getNonEmptySelectionPredicate()); |
getRowActions().add(rowActionBL); |
PredicateRowAction rowActionCmd = new PredicateRowAction(new AbstractAction("Modifier la commande associée") { |
@Override |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/ChiffrageCommandeClientSQLElement.java |
---|
17,11 → 17,14 |
import org.openconcerto.erp.core.common.ui.DeviseTableCellRenderer; |
import org.openconcerto.sql.element.SQLComponent; |
import org.openconcerto.sql.element.UISQLComponent; |
import org.openconcerto.sql.view.list.SQLTableModelColumn; |
import org.openconcerto.sql.view.list.SQLTableModelSource; |
import org.openconcerto.utils.ListMap; |
import java.util.ArrayList; |
import java.util.HashSet; |
import java.util.List; |
import java.util.Set; |
public class ChiffrageCommandeClientSQLElement extends ComptaSQLConfElement { |
30,6 → 33,20 |
} |
@Override |
public Set<String> getReadOnlyFields() { |
Set<String> s = new HashSet<>(); |
s.add("NOM"); |
s.add("ID_FAMILLE_ARTICLE"); |
s.add("PA_HT"); |
s.add("PV_HT"); |
s.add("QTE"); |
s.add("ID_UNITE_VENTE"); |
s.add("T_PA_HT"); |
s.add("T_PV_HT"); |
return s; |
} |
/* |
* (non-Javadoc) |
* |
53,11 → 70,31 |
@Override |
protected void _initTableSource(SQLTableModelSource res) { |
super._initTableSource(res); |
res.getColumn(getTable().getField("QTE")).setRenderer(new DeviseTableCellRenderer()); |
res.getColumn(getTable().getField("PA_HT")).setRenderer(new DeviseTableCellRenderer()); |
res.getColumn(getTable().getField("MARGE")).setRenderer(new DeviseTableCellRenderer()); |
res.getColumn(getTable().getField("T_PA_HT")).setRenderer(new DeviseTableCellRenderer()); |
SQLTableModelColumn columnQte = res.getColumn(getTable().getField("QTE")); |
if (columnQte != null) { |
columnQte.setRenderer(new DeviseTableCellRenderer()); |
} |
if (getTable().contains("ANT")) { |
final SQLTableModelColumn columnAnt = res.getColumn(getTable().getField("ANT")); |
if (columnAnt != null) { |
columnAnt.setRenderer(new DeviseTableCellRenderer()); |
} |
} |
final SQLTableModelColumn columnPA = res.getColumn(getTable().getField("PA_HT")); |
if (columnPA != null) { |
columnPA.setRenderer(new DeviseTableCellRenderer()); |
} |
final SQLTableModelColumn columnmarge = res.getColumn(getTable().getField("MARGE")); |
if (columnmarge != null) { |
columnmarge.setRenderer(new DeviseTableCellRenderer()); |
} |
SQLTableModelColumn column = res.getColumn(getTable().getField("T_PA_HT")); |
if (column != null) { |
column.setRenderer(new DeviseTableCellRenderer()); |
} |
} |
/* |
92,16 → 129,25 |
* @see org.openconcerto.devis.SQLElement#getComponent() |
*/ |
public SQLComponent createComponent() { |
return new UISQLComponent(this) { |
return new UISQLComponent(this, 3) { |
public void addViews() { |
this.addView("NOM"); |
this.addView("ID_FAMILLE_ARTICLE"); |
this.addView("PA_HT"); |
this.addView("PV_HT"); |
this.addView("QTE"); |
this.addView("ID_UNITE_VENTE"); |
this.addView("T_PA_HT"); |
this.addView("T_PV_HT"); |
this.addView("NOM", "1"); |
this.addView("ID_FAMILLE_ARTICLE", "1"); |
this.addView("PA_HT", "1"); |
this.addView("PV_HT", "1"); |
this.addView("QTE", "1"); |
if (getTable().contains("RESTANT")) { |
this.addView("RESTANT", "1"); |
} |
this.addView("ID_UNITE_VENTE", "1"); |
this.addView("T_PA_HT", "1"); |
this.addView("T_PV_HT", "1"); |
if (getTable().contains("ANT")) { |
this.addView("ANT", "1"); |
} |
if (getTable().contains("MOTIF")) { |
this.addView("MOTIF", "1"); |
} |
} |
}; |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/account/VenteFactureSoldeSQLComponent.java |
---|
14,22 → 14,29 |
package org.openconcerto.erp.core.sales.account; |
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement; |
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable.TypeCalcul; |
import org.openconcerto.erp.core.common.ui.Acompte; |
import org.openconcerto.erp.core.common.ui.AcompteField; |
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable.TypeCalcul; |
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement; |
import org.openconcerto.erp.core.sales.invoice.ui.FactureSituationItemTable; |
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater; |
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate; |
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel; |
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel; |
import org.openconcerto.sql.element.GlobalMapper; |
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.preferences.SQLPreferences; |
import org.openconcerto.ui.group.Group; |
import org.openconcerto.utils.DecimalUtils; |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.Tuple2; |
import java.math.BigDecimal; |
import java.math.RoundingMode; |
import java.sql.SQLException; |
import java.util.Collection; |
import java.util.Date; |
import java.util.HashSet; |
66,10 → 73,28 |
@Override |
public int insert(SQLRow order) { |
return super.insert(order); |
int id = super.insert(order); |
try { |
updateStock(id); |
} catch (SQLException e) { |
ExceptionHandler.handle("Erreur lors de la mise à jour du stock.", e); |
e.printStackTrace(); |
} |
return id; |
} |
@Override |
public void update() { |
super.update(); |
try { |
updateStock(getSelectedID()); |
} catch (SQLException e) { |
ExceptionHandler.handle("Erreur lors de la mise à jour du stock.", e); |
e.printStackTrace(); |
} |
} |
@Override |
public void importFrom(List<SQLRowValues> rows) { |
super.importFrom(rows); |
114,6 → 139,34 |
return l; |
} |
protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) { |
return "Saisie vente facture N°" + row.getString("NUMERO"); |
} |
/** |
* Mise à jour des stocks pour chaque article composant la facture |
* |
* @throws SQLException |
*/ |
private void updateStock(int id) throws SQLException { |
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot()); |
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) { |
SQLRow row = getTable().getRow(id); |
StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() { |
@Override |
public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) { |
return getLibelleStock(rowOrigin, rowElt); |
} |
}, row, row.getReferentRows(getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")), |
getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_DELIVER : TypeStockUpdate.REAL_DELIVER); |
stockUpdater.update(); |
} |
} |
// @Override |
// public Component addView(MutableRowItemView rowItemView, String fields, Object specObj) { |
// |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/account/VenteFactureSituationSQLComponent.java |
---|
67,6 → 67,8 |
import javax.swing.SwingConstants; |
import javax.swing.SwingUtilities; |
import javax.swing.event.DocumentEvent; |
import javax.swing.event.TableModelEvent; |
import javax.swing.event.TableModelListener; |
public class VenteFactureSituationSQLComponent extends TransfertGroupSQLComponent { |
public static final String ID = "sales.invoice.partial"; |
201,7 → 203,7 |
sqlRequestComboBox.setEnabled(false); |
final AcompteField acompteField = ((AcompteField) getEditor("sales.invoice.partial.amount")); |
acompteField.getDocument().addDocumentListener(new SimpleDocumentListener() { |
listenerAcompteField = new SimpleDocumentListener() { |
@Override |
public void update(DocumentEvent e) { |
208,7 → 210,25 |
Acompte a = acompteField.getValue(); |
table.calculPourcentage(a, TypeCalcul.CALCUL_FACTURABLE); |
} |
}); |
}; |
acompteField.getDocument().addDocumentListener(listenerAcompteField); |
listenerTable = new TableModelListener() { |
@Override |
public void tableChanged(TableModelEvent e) { |
acompteField.getDocument().removeDocumentListener(listenerAcompteField); |
if (e.getColumn() == table.getModel().getColumnForField("POURCENT_FACTURABLE")) { |
Acompte a = new Acompte(null, table.getTotalHT(TypeCalcul.CALCUL_MONTANT_TOTAL)); |
acompteField.setValue(a); |
} |
acompteField.getDocument().addDocumentListener(listenerAcompteField); |
} |
}; |
table.getRowValuesTable().getModel().addTableModelListener(listenerTable); |
total.addValueListener(new PropertyChangeListener() { |
@Override |
220,19 → 240,9 |
} |
int countPole = 0; |
private SimpleDocumentListener listenerAcompteField; |
private TableModelListener listenerTable; |
// @Override |
// public Component addView(MutableRowItemView rowItemView, String fields, Object specObj) { |
// |
// if (fields.contains("ID_POLE_PRODUIT") && countPole == 0) { |
// countPole++; |
// return null; |
// } else { |
// return super.addView(rowItemView, fields, specObj); |
// } |
// } |
@Override |
public JComponent getLabel(String id) { |
if (id.equals("sales.invoice.partial.amount")) { |
283,10 → 293,11 |
// Set only VAT Editable |
for (int i = 0; i < items.getRowValuesTable().getColumnModel().getColumnCount(false); i++) { |
final SQLTableElement sqlTableElementAt = items.getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(i); |
if (sqlTableElementAt.getField() == null || !sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_TAXE")) { |
if (sqlTableElementAt.getField() != null && (sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_STYLE") |
|| sqlTableElementAt.getField().getName().equalsIgnoreCase("POURCENT_FACTURABLE") || sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_TAXE"))) { |
sqlTableElementAt.setEditable(true); |
} else { |
sqlTableElementAt.setEditable(false); |
} else { |
sqlTableElementAt.setEditable(true); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureItemSQLElement.java |
---|
164,23 → 164,23 |
* |
* @see org.openconcerto.devis.BaseSQLElement#getListFields() |
*/ |
@Override |
protected List<String> getListFields() { |
List<String> l = new ArrayList<String>(); |
l.add("ID_SAISIE_VENTE_FACTURE"); |
l.add("CODE"); |
l.add("NOM"); |
l.add("DESCRIPTIF"); |
String articleAdvanced = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance"); |
Boolean bArticleAdvanced = Boolean.valueOf(articleAdvanced); |
if (bArticleAdvanced) { |
l.add("PRIX_METRIQUE_VT_1"); |
l.add("ID_MODE_VENTE_ARTICLE"); |
} |
if (UserRightsManager.getCurrentUserRights().haveRight(AbstractVenteArticleItemTable.SHOW_PRIX_ACHAT_CODE)) { |
l.add("PA_HT"); |
} |
l.add("PV_HT"); |
l.add("CODE"); |
l.add("NOM"); |
l.add("DESCRIPTIF"); |
String articleAdvanced = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance"); |
Boolean bArticleAdvanced = Boolean.valueOf(articleAdvanced); |
if (bArticleAdvanced) { |
l.add("PRIX_METRIQUE_VT_1"); |
l.add("ID_MODE_VENTE_ARTICLE"); |
} |
if (UserRightsManager.getCurrentUserRights().haveRight(AbstractVenteArticleItemTable.SHOW_PRIX_ACHAT_CODE)) { |
l.add("PA_HT"); |
} |
l.add("PV_HT"); |
l.add("QTE"); |
if (getTable().contains("ID_ECO_CONTRIBUTION")) { |
l.add("ID_ECO_CONTRIBUTION"); |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/EcheanceClientSQLElement.java |
---|
14,6 → 14,7 |
package org.openconcerto.erp.core.sales.invoice.element; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.config.Gestion; |
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement; |
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement; |
import org.openconcerto.erp.core.common.ui.DeviseField; |
51,6 → 52,7 |
import org.openconcerto.sql.utils.SQLUtils; |
import org.openconcerto.sql.view.EditFrame; |
import org.openconcerto.sql.view.EditPanel.EditMode; |
import org.openconcerto.sql.view.EditPanelListener; |
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn; |
import org.openconcerto.sql.view.list.IListe; |
import org.openconcerto.sql.view.list.IListeAction.IListeEvent; |
447,7 → 449,7 |
@Override |
protected void _initListRequest(ListSQLRequest req) { |
super._initListRequest(req); |
req.addToGraphToFetch("REG_COMPTA", "REGLE"); |
req.addToGraphToFetch("REG_COMPTA", "REGLE","NOMBRE_RELANCE"); |
} |
/* |
538,4 → 540,63 |
return createCodeOfPackage() + ".commitment"; |
} |
public void relanceClient(final SQLRow rowEch) { |
final SQLElement relanceElt = getDirectory().getElement("RELANCE"); |
rowEch.fetchValues(); |
if (rowEch != null) { |
int idMvtSource = MouvementSQLElement.getSourceId(rowEch.getForeignID("ID_MOUVEMENT")); |
SQLRow rowMvtSource = getTable().getTable("MOUVEMENT").getRow(idMvtSource); |
if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) { |
return; |
} |
EditFrame editRelance = new EditFrame(relanceElt); |
editRelance.setIconImages(Gestion.getFrameIcon()); |
editRelance.addEditPanelListener(new EditPanelListener() { |
public void cancelled() { |
// rien |
} |
public void modified() { |
// rien |
} |
public void deleted() { |
// rien |
} |
public void inserted(int id) { |
int nbRelance = rowEch.getInt("NOMBRE_RELANCE"); |
nbRelance++; |
SQLRowValues rowValsEch = new SQLRowValues(rowEch.getTable()); |
rowValsEch.put("NOMBRE_RELANCE", nbRelance); |
rowValsEch.put("DATE_LAST_RELANCE", new Date()); |
try { |
rowValsEch.update(rowEch.getID()); |
relanceElt.getTable().getRow(id).createEmptyUpdateRow().put("ID_ECHEANCE_CLIENT", rowEch.getID()).commit(); |
} catch (SQLException e1) { |
ExceptionHandler.handle("erreur lors de la mise à jour du nombre de relances", e1); |
} |
} |
}); |
SQLRowValues rowVals = new SQLRowValues(relanceElt.getTable()); |
rowVals.put("ID_SAISIE_VENTE_FACTURE", rowMvtSource.getInt("IDSOURCE")); |
rowVals.put("MONTANT", rowEch.getObject("MONTANT")); |
rowVals.put("ID_CLIENT", rowEch.getForeignID("ID_CLIENT")); |
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(RelanceSQLElement.class, new Date())); |
editRelance.getSQLComponent().select(rowVals); |
editRelance.pack(); |
editRelance.setVisible(true); |
} |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeDesVentesAction.java |
---|
14,6 → 14,7 |
package org.openconcerto.erp.core.sales.invoice.action; |
import org.openconcerto.erp.action.CreateFrameAbstractAction; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.core.common.ui.PanelFrame; |
import org.openconcerto.erp.core.sales.invoice.ui.ListeDesVentesPanel; |
20,15 → 21,17 |
import javax.swing.Action; |
import javax.swing.JFrame; |
public class ListeDesVentesAction extends CreateFrameAbstractAction { |
public ListeDesVentesAction() { |
private final ComptaPropsConfiguration conf; |
public ListeDesVentesAction(final ComptaPropsConfiguration conf) { |
super(); |
this.putValue(Action.NAME, "Liste des ventes"); |
this.conf = conf; |
} |
@Override |
public JFrame createFrame() { |
return new PanelFrame(new ListeDesVentesPanel(), "Liste des ventes"); |
return new PanelFrame(new ListeDesVentesPanel(this.conf), (String) this.getValue(Action.NAME)); |
} |
} |
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeEcheancePrelevementAction.java |
---|
New file |
0,0 → 1,491 |
/* |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
* |
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. |
* |
* The contents of this file are subject to the terms of the GNU General Public License Version 3 |
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a |
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific |
* language governing permissions and limitations under the License. |
* |
* When distributing the software, include this License Header Notice in each file. |
*/ |
package org.openconcerto.erp.core.sales.invoice.action; |
import org.openconcerto.erp.action.CreateFrameAbstractAction; |
import org.openconcerto.erp.config.ComptaPropsConfiguration; |
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement; |
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.GenerationResult; |
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.IgnoreReason; |
import org.openconcerto.erp.core.sales.invoice.element.EcheanceClientSQLElement; |
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement; |
import org.openconcerto.erp.generationEcritures.GenerationMvtSepa; |
import org.openconcerto.erp.utils.TM; |
import org.openconcerto.sql.model.FieldPath; |
import org.openconcerto.sql.model.SQLRow; |
import org.openconcerto.sql.model.SQLRowAccessor; |
import org.openconcerto.sql.model.SQLRowValues; |
import org.openconcerto.sql.model.SQLRowValuesListFetcher; |
import org.openconcerto.sql.model.SQLTable; |
import org.openconcerto.sql.model.Where; |
import org.openconcerto.sql.model.graph.Path; |
import org.openconcerto.sql.request.UpdateBuilder; |
import org.openconcerto.sql.view.IListFrame; |
import org.openconcerto.sql.view.ListeAddPanel; |
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn; |
import org.openconcerto.sql.view.list.IListe; |
import org.openconcerto.sql.view.list.IListeAction.IListeEvent; |
import org.openconcerto.sql.view.list.RowAction; |
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline; |
import org.openconcerto.ui.DefaultGridBagConstraints; |
import org.openconcerto.ui.FrameUtil; |
import org.openconcerto.utils.CollectionUtils; |
import org.openconcerto.utils.ExceptionHandler; |
import org.openconcerto.utils.i18n.Grammar_fr; |
import java.awt.GridBagConstraints; |
import java.awt.event.ActionEvent; |
import java.awt.event.ActionListener; |
import java.sql.SQLException; |
import java.util.ArrayList; |
import java.util.Arrays; |
import java.util.Collection; |
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 java.util.concurrent.ExecutionException; |
import javax.swing.AbstractAction; |
import javax.swing.JCheckBox; |
import javax.swing.JFrame; |
import javax.swing.JOptionPane; |
import javax.swing.SwingWorker; |
public class ListeEcheancePrelevementAction extends CreateFrameAbstractAction { |
private final EcheanceClientSQLElement elem; |
private final ComptaPropsConfiguration conf; |
public ListeEcheancePrelevementAction(ComptaPropsConfiguration conf) { |
super(); |
this.elem = conf.getDirectory().getElement(EcheanceClientSQLElement.class); |
this.conf = conf; |
} |
public final EcheanceClientSQLElement getElem() { |
return this.elem; |
} |
private void setWhere(final SQLTableModelSourceOnline tableSource, boolean showHistory) { |
final SQLTable tableEcheance = this.elem.getTable(); |
Where w = new Where(tableEcheance.getField("ID_SEPA_MANDATE"), "!=", (Object) null); |
if (!showHistory) { |
w = w.and(new Where(tableEcheance.getField("REGLE"), "=", Boolean.FALSE)); |
w = w.and(new Where(tableEcheance.getField("REG_COMPTA"), "=", Boolean.FALSE)); |
} |
tableSource.getReq().setWhere(w); |
} |
@Override |
public JFrame createFrame() { |
final SQLTableModelSourceOnline tableSource = this.elem.getTableSource(true); |
setWhere(tableSource, false); |
final TM tm = conf.getERP_TM(); |
tableSource.getColumns().add(new BaseSQLTableModelColumn("Etat", String.class) { |
@Override |
protected Object show_(SQLRowAccessor r) { |
if (r.getBoolean("REGLE")) { |
return TM.tr("sepa.deadline.done"); |
} else if (r.getBoolean("REG_COMPTA")) { |
return TM.tr("sepa.deadline.regul"); |
} else if (!r.isForeignEmpty("ID_SDD_MESSAGE")) { |
return TM.tr("sepa.deadline.filecreated"); |
} |
return TM.tr("sepa.deadline.waiting"); |
} |
@Override |
public Set<FieldPath> getPaths() { |
Path p = new Path(elem.getTable()); |
return CollectionUtils.createSet(new FieldPath(p, "REGLE"), new FieldPath(p, "REG_COMPTA"), new FieldPath(p, "ID_SDD_MESSAGE")); |
} |
}); |
tableSource.getColumns().add(new BaseSQLTableModelColumn("Fichier SEPA", String.class) { |
@Override |
protected Object show_(SQLRowAccessor r) { |
if (r.isForeignEmpty("ID_SDD_MESSAGE")) { |
return ""; |
} else { |
return r.getForeign("ID_SDD_MESSAGE").getString("MessageIdentification"); |
} |
} |
@Override |
public Set<FieldPath> getPaths() { |
Path p = new Path(elem.getTable()); |
p = p.add(elem.getTable().getField("ID_SDD_MESSAGE")); |
return CollectionUtils.createSet(new FieldPath(p, "MessageIdentification")); |
} |
}); |
final ListeAddPanel panel = new ListeAddPanel(this.elem, new IListe(tableSource)); |
final IListFrame res = new IListFrame(panel); |
res.setTextTitle("Prélèvements SEPA"); |
res.getPanel().setReadWriteButtonsVisible(false); |
GridBagConstraints c = new DefaultGridBagConstraints(); |
c.gridy += 2; |
c.weighty = 0; |
c.fill = GridBagConstraints.NONE; |
c.anchor = GridBagConstraints.WEST; |
final JCheckBox checkboxHistory = new JCheckBox(TM.tr("sepa.history.hide")); |
checkboxHistory.setSelected(true); |
checkboxHistory.addActionListener(new ActionListener() { |
@Override |
public void actionPerformed(ActionEvent e) { |
setWhere(tableSource, !checkboxHistory.isSelected()); |
} |
}); |
res.getPanel().add(checkboxHistory, c); |
final SDDMessageSQLElement sepaMsgElem = this.elem.getDirectory().getElement(SDDMessageSQLElement.class); |
final String aMessageLabel = this.elem.getForeignElement(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME).getName().getVariant(Grammar_fr.INDEFINITE_ARTICLE_SINGULAR); |
RowAction actionFileCreate = new RowAction.PredicateRowAction(new AbstractAction("Générer " + aMessageLabel, null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListe l = IListe.get(e); |
final List<Integer> selectedIDs = new ArrayList<>(); |
final Set<Integer> selectedClientIDs = new HashSet<>(); |
for (SQLRowValues rowVals : l.getSelectedRows()) { |
selectedClientIDs.add(rowVals.getForeignID("ID_CLIENT")); |
if (rowVals.getLong("MONTANT") > 0) { |
selectedIDs.add(rowVals.getID()); |
} |
} |
// TODO dialog with label informing of the successful creation of message for n |
// invoices/n2 messages too far in the future/n3 messages with collection date |
// changed and having a button to open the file chooser |
new SwingWorker<String, Void>() { |
@Override |
protected String doInBackground() throws Exception { |
return checkSEPA(selectedClientIDs); |
} |
@Override |
protected void done() { |
try { |
String msg = get(); |
if (msg.trim().length() > 0) { |
msg = "Des informations nécessaires à la création du fichier sont manquantes : \n" + msg; |
msg += "Le fichier ne pourra être créer tant que ces informations n'auront pas été renseignées."; |
JOptionPane.showMessageDialog(null, msg, "Création du fichier SEPA annulée", JOptionPane.WARNING_MESSAGE); |
return; |
} |
} catch (Exception e) { |
ExceptionHandler.handle(l, "Impossible de générer " + aMessageLabel, e); |
return; |
} |
new SwingWorker<GenerationResult, Void>() { |
@Override |
protected GenerationResult doInBackground() throws Exception { |
return sepaMsgElem.generateXML(elem.getTable(), selectedIDs); |
} |
@Override |
protected void done() { |
final GenerationResult genRes; |
try { |
genRes = this.get(); |
} catch (Exception e) { |
ExceptionHandler.handle(l, "Impossible de générer " + aMessageLabel, e); |
return; |
} |
final int includedInvoicesCount = genRes.getIncludedInvoicesCount(); |
final Map<String, Object> tmMap = new HashMap<>(); |
tmMap.put("msgElem", sepaMsgElem.getName()); |
tmMap.put("invoiceElem", elem.getName()); |
tmMap.put("invoiceElemCount", includedInvoicesCount); |
if (genRes.getDDInvoicesWithoutMessage().isEmpty()) { |
JOptionPane.showMessageDialog(l, tm.trM("sddMessage.generation.noneNeeded", tmMap)); |
} else if (genRes.getIgnoredInvoices().isEmpty()) { |
JOptionPane.showMessageDialog(l, tm.trM("sddMessage.generation.noneIgnored", tmMap)); |
} else { |
final int futureCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.TOO_FAR_IN_FUTURE).size(); |
final int duplicateCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.DUPLICATE_MANDATE).size(); |
final int missingInfoCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.MISSING_INFO).size(); |
tmMap.put("futureCount", futureCount); |
tmMap.put("duplicateCount", duplicateCount); |
tmMap.put("missingInfoCount", missingInfoCount); |
final StringBuilder msg = new StringBuilder(256); |
msg.append(tm.trM("sddMessage.generation.someIgnored", tmMap)); |
if (futureCount > 0) { |
msg.append("\n- "); |
msg.append(tm.trM("sddMessage.generation.someIgnored.future", tmMap)); |
} |
if (duplicateCount > 0) { |
msg.append("\n- "); |
msg.append(tm.trM("sddMessage.generation.someIgnored.duplicateMandate", tmMap)); |
} |
if (missingInfoCount > 0) { |
msg.append("\n- "); |
msg.append(tm.trM("sddMessage.generation.someIgnored.missingInfo", tmMap)); |
} |
final int messageType = duplicateCount == 0 ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE; |
JOptionPane.showMessageDialog(l, msg.toString(), null, messageType); |
} |
if (genRes.getInsertedMessage() != null) { |
sepaMsgElem.exportXML(l, Collections.singletonList(genRes.getInsertedMessage())); |
} |
} |
}.execute(); |
} |
}.execute(); |
} |
}, true, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()); |
// TODO remove once we have a join with {SENT, OK, DEFINITIVE_ERROR, TRANSIENT_ERROR} |
RowAction actionSepaAgain = new RowAction.PredicateRowAction(new AbstractAction("Prélever à nouveau", null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListe l = IListe.get(e); |
if (JOptionPane.showConfirmDialog(l, "Voulez-vous vraiment prélever à nouveau les factures sélectionnées ? Cette action est définitive.", "Prélever à nouveau", |
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) |
return; |
final List<Integer> selectedIDs = l.getSelection().getSelectedIDs(); |
final SQLTable table = l.getSource().getPrimaryTable(); |
new SwingWorker<Void, Void>() { |
@Override |
protected Void doInBackground() throws Exception { |
final UpdateBuilder upd = new UpdateBuilder(table); |
upd.setObject(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME, upd.getTable().getForeignTable(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME).getUndefinedIDNumber()); |
upd.setObject(SaisieVenteFactureSQLElement.END2END_FIELD_NAME, ""); |
// don't allow to debit already payed invoices |
upd.setWhere(new Where(upd.getTable().getKey(), selectedIDs).and(new Where(upd.getTable().getField("REGLE"), "=", Boolean.FALSE)) |
.and(new Where(upd.getTable().getField("REG_COMPTA"), "=", Boolean.FALSE))); |
upd.getTable().getDBSystemRoot().getDataSource().execute(upd.asString()); |
return null; |
} |
@Override |
protected void done() { |
try { |
get(); |
final SQLTable table = l.getSource().getPrimaryTable().getTable(); |
final List<String> modifiedFields = Arrays.asList(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME, SaisieVenteFactureSQLElement.END2END_FIELD_NAME); |
for (final Integer id : selectedIDs) { |
table.fireTableModified(id, modifiedFields); |
} |
} catch (InterruptedException | ExecutionException e) { |
e.printStackTrace(); |
} |
} |
}.execute(); |
} |
}, false, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()); |
panel.getListe().addIListeAction(actionFileCreate); |
panel.getListe().addIListeAction(actionSepaAgain); |
RowAction actionCompta = new RowAction(new AbstractAction("Valider le paiement", null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListe l = IListe.get(e); |
if (JOptionPane.showConfirmDialog(l, "Voulez-vous vraiment transférer ces prélèvements en comptabilité ?", "Comptabiliser", JOptionPane.OK_CANCEL_OPTION, |
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) |
return; |
List<SQLRow> rows = new ArrayList<>(); |
List<Integer> ids = new ArrayList<>(); |
for (SQLRowAccessor sqlRow : l.getSelectedRows()) { |
rows.add(sqlRow.asRow()); |
ids.add(sqlRow.getID()); |
} |
new SwingWorker<Void, Void>() { |
@Override |
protected Void doInBackground() throws Exception { |
try { |
GenerationMvtSepa sepa = new GenerationMvtSepa(rows); |
sepa.genere(); |
UpdateBuilder build = new UpdateBuilder(elem.getTable()); |
build.setObject(elem.getTable().getField("REGLE"), Boolean.TRUE); |
build.setWhere(new Where(elem.getTable().getKey(), ids)); |
elem.getTable().getDBSystemRoot().getDataSource().execute(build.asString()); |
} catch (Exception e) { |
ExceptionHandler.handle("Erreur lors du transfert en comptabilité", e); |
} |
return null; |
} |
@Override |
protected void done() { |
try { |
get(); |
for (final Integer id : ids) |
elem.getTable().fireTableModified(id, Arrays.asList("REGLE")); |
} catch (InterruptedException | ExecutionException e) { |
e.printStackTrace(); |
} |
} |
}.execute(); |
} |
}, true, true) { |
@Override |
public boolean enabledFor(List<SQLRowValues> selection) { |
if (selection != null && selection.size() >= 1) { |
for (SQLRowValues sqlRowValues : selection) { |
if (sqlRowValues.getBoolean("REGLE")) { |
return false; |
} |
} |
return true; |
} |
return false; |
} |
}; |
panel.getListe().addIListeAction(actionCompta); |
RowAction actionHistoSEPA = new RowAction.PredicateRowAction(new AbstractAction("Historique Fichiers SEPA", null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListFrame res = new IListFrame(new ListeAddPanel(elem.getDirectory().getElement(SDDMessageSQLElement.class))); |
res.getPanel().setReadWriteButtonsVisible(false); |
FrameUtil.showPacked(res); |
} |
}, true, true).setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE)); |
panel.getListe().addIListeAction(actionHistoSEPA); |
RowAction actionRelancer = new RowAction.PredicateRowAction(new AbstractAction("Relancer", null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
elem.relanceClient(IListe.get(e).getSelectedRow().asRow()); |
} |
}, true, true).setPredicate(IListeEvent.getSingleSelectionPredicate()); |
panel.getListe().addIListeAction(actionRelancer); |
RowAction actionCancelPaiement = new RowAction(new AbstractAction("Annuler la validation", null) { |
@Override |
public void actionPerformed(ActionEvent e) { |
final IListe l = IListe.get(e); |
if (JOptionPane.showConfirmDialog(l, "Voulez-vous vraiment annuler le transfert de ce prélèvement en comptabilité ?", "Comptabiliser", JOptionPane.OK_CANCEL_OPTION, |
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) |
return; |
final SQLRowValues selectedRow = IListe.get(e).getSelectedRow(); |
new SwingWorker<Void, Void>() { |
@Override |
protected Void doInBackground() throws Exception { |
Collection<? extends SQLRowAccessor> res = selectedRow.asRow().getForeign("ID_MOUVEMENT") |
.getReferentRows(elem.getTable().getTable("ENCAISSER_MONTANT_ELEMENT").getField("ID_MOUVEMENT_ECHEANCE")); |
if (res.size() >= 1) { |
try { |
elem.getDirectory().getElement("MOUVEMENT").archive(res.iterator().next().getForeign("ID_ENCAISSER_MONTANT").getForeignID("ID_MOUVEMENT")); |
UpdateBuilder build = new UpdateBuilder(elem.getTable()); |
build.setObject(elem.getTable().getField("REGLE"), Boolean.FALSE); |
build.setWhere(new Where(elem.getTable().getKey(), "=", l.getSelectedId())); |
elem.getTable().getDBSystemRoot().getDataSource().execute(build.asString()); |
} catch (SQLException e1) { |
e1.printStackTrace(); |
} |
} |
return null; |
} |
@Override |
protected void done() { |
try { |
get(); |
elem.getTable().fireTableModified(l.getSelectedId(), Arrays.asList("REGLE")); |
} catch (InterruptedException | ExecutionException e) { |
e.printStackTrace(); |
} |
} |
}.execute(); |
} |
}, false, true) { |
@Override |
public boolean enabledFor(List<SQLRowValues> selection) { |
if (selection != null && selection.size() == 1) { |
return selection.get(0).getBoolean("REGLE"); |
} |
return false; |
} |
}; |