OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 148 → Rev 149

/trunk/OpenConcerto/lib/postgresql-9.2-1003.jdbc4.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/postgresql-42.2.2.jre7.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/postgresql-42.2.2.jre7.jar
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/lib/jOpenDocument-1.4rc2.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/jOpenCalendar.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatVentes.xml
3,10 → 3,10
<element0 location="A4" type="Value" ValueName="DATE">
</element0>
 
<element0 location="G54" type="Value" ValueName="TOTAL_PV_TTC">
</element0>
<!-- <element0 location="G54" type="Value" ValueName="TOTAL_PV_TTC">
</element0> -->
 
<table0 firstLine="7" endLine="51" endPageLine="54" lastColumn="E" base="Societe" table="SAISIE_VENTE_FACTURE_ELEMENT">
<table0 firstLine="7" endLine="52" endPageLine="54" lastColumn="H" base="Societe" table="SAISIE_VENTE_FACTURE_ELEMENT">
<element location="A" type="fill">
<field base="Societe" name="NOM" />
</element>
22,12 → 22,15
<element location="E" type="fill">
<field base="Societe" name="NB_ESPECES" />
</element>
<element location="F" type="fill">
<field base="Societe" name="NB_ESPECES" />
</element>
 
<element location="F" type="fill">
<element location="G" type="fill">
<field base="Societe" name="T_MARGE" />
</element>
 
<element location="G" type="fill">
<element location="H" type="fill">
<field base="Societe" name="T_PV_TTC" />
</element>
</table0>
80,4 → 83,45
<field base="Societe" name="TOTAL" />
</element>
</table2>
<element3 location="A1" type="Value" ValueName="DATE">
</element3>
<element3 location="C19" type="Value" ValueName="TOTAL_TVA">
</element3>
 
<table3 firstLine="4" endLine="52" endPageLine="54" lastColumn="I" base="Societe" table="SAISIE_VENTE_FACTURE_ELEMENT">
<element location="A" type="fill">
<field base="Societe" name="VT_TAUX_TVA" />
</element>
 
<element location="B" type="fill">
<field base="Societe" name="VT_HT" />
</element>
 
<element location="C" type="fill">
<field base="Societe" name="VT_TVA" />
</element>
 
<element location="D" type="fill">
<field base="Societe" name="VT_TTC" />
</element>
 
<element location="F" type="fill">
<field base="Societe" name="VT_TAUX_TVA" />
</element>
<element location="G" type="fill">
<field base="Societe" name="HA_HT" />
</element>
 
<element location="H" type="fill">
<field base="Societe" name="HA_TVA" />
</element>
<element location="I" type="fill">
<field base="Societe" name="HA_TTC" />
</element>
</table3>
</contentDocument>
/trunk/OpenConcerto/Configuration/Template/Default/Devis.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatVentes.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/DemandePrix.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/postgresql/jdbc2/AbstractJdbc2DatabaseMetaData.java
File deleted
/trunk/OpenConcerto/src/org/jopendocument/link/OOConnexion.java
82,6 → 82,15
perms.add(new FilePermission("<<ALL FILES>>", "read"));
// needed by ThreadPoolExecutor.shutdown()
perms.add(new RuntimePermission("modifyThread"));
// needed by PrinterJob.getPrinterJob()
perms.add(new RuntimePermission("queuePrintJob"));
// needed by OOConnexion.init() to find the port
perms.add(new FilePermission("/usr/bin/lsof", "execute"));
perms.add(new FilePermission("/bin/ps", "execute"));
perms.add(new FilePermission("C:/Windows/System32/tasklist.exe", "execute"));
perms.add(new RuntimePermission("getenv.*"));
// needed by OOConnexion.convertToUrl()
perms.add(new FilePermission("/usr/bin/gvfs-info", "execute"));
return perms;
}
};
/trunk/OpenConcerto/src/org/jopendocument/link/Component.java
13,6 → 13,7
package org.jopendocument.link;
 
import java.awt.print.PrinterJob;
import java.io.File;
import java.util.Map;
import java.util.concurrent.Future;
30,7 → 31,7
return this.parent;
}
 
public abstract void printDocument();
public abstract void printDocument(PrinterJob job);
 
public final void printDocument(final Map<String, ?> printProps) {
printDocument(printProps, null);
51,7 → 52,7
* par défaut du modéle
* @param printOpt
*/
public abstract void printDocument(final Map<String, ?> printProps, final Map<String, ?> printOpt);
public abstract void printDocument(final Map<String, ?> printProps, final Map<String, ?> printOpt) throws IllegalArgumentException;
 
public abstract Future<String> save();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeColumnXML.java
58,6 → 58,9
final SAXBuilder builder = new SAXBuilder();
try {
InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
if (xmlConfiguration == null) {
throw new IllegalStateException("Template configuration " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
Document doc = builder.build(xmlConfiguration);
 
// On initialise un nouvel élément racine avec l'élément racine du
66,7 → 69,9
 
// Création et génération du fichier OO
final InputStream template = TemplateManager.getInstance().getTemplate(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
 
if (template == null) {
throw new IllegalStateException("Template " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
Sheet sheet0 = spreadSheet.getSheet(0);
if (sheetName != null && sheetName.size() > 0) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/EtatVentesXmlSheet.java
25,10 → 25,13
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSelectJoin;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.Tuple2;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
58,10 → 61,12
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
 
private Timestamp du, au;
public boolean ticketCaisse = false;
 
public EtatVentesXmlSheet(Date du, Date au) {
public EtatVentesXmlSheet(Date du, Date au, boolean ticketCaisse) {
super();
this.printer = PrinterNXProps.getInstance().getStringProperty("BonPrinter");
this.ticketCaisse = ticketCaisse;
if (du != null) {
final Calendar c1 = Calendar.getInstance();
c1.setTime(du);
101,6 → 106,8
}
 
protected void createListeValues() {
Map<Integer, Tuple2<BigDecimal, BigDecimal>> mapTVAVT = new HashMap<Integer, Tuple2<BigDecimal, BigDecimal>>();
Map<Integer, Tuple2<BigDecimal, BigDecimal>> mapTVAHA = new HashMap<Integer, Tuple2<BigDecimal, BigDecimal>>();
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
final SQLElement eltVenteFacutreElement = directory.getElement("SAISIE_VENTE_FACTURE_ELEMENT");
final SQLElement eltVenteFacture = directory.getElement("SAISIE_VENTE_FACTURE");
110,19 → 117,38
final SQLTable tableModeReglement = eltModeReglement.getTable();
final SQLTable tableFactureElement = eltVenteFacutreElement.getTable();
final SQLTable tableFacture = eltVenteFacture.getTable();
BigDecimal totalTPVTTC = BigDecimal.ZERO;
BigDecimal totalTPA = BigDecimal.ZERO;
 
// Liste des valeurs de la feuille OO
ArrayList<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>();
Map<Integer, String> style = styleAllSheetValues.get(0);
if (style == null) {
style = new HashMap<Integer, String>();
styleAllSheetValues.put(0, style);
}
 
// Ventes
{
 
final AliasedTable tableModeReglement1 = new AliasedTable(tableModeReglement, MODE1);
final AliasedTable tableModeReglement2 = new AliasedTable(tableModeReglement, MODE2);
final AliasedTable tableTicket = new AliasedTable(eltTicketCaisse.getTable(), "ticket");
 
// Requete Pour obtenir les quantités pour chaque type de réglement
SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
SQLSelect sel = new SQLSelect();
 
sel.addSelect(tableFactureElement.getField("CODE"));
sel.addSelect(tableFactureElement.getField("NOM"));
sel.addSelect(tableFactureElement.getField("ID_ARTICLE"));
sel.addSelect(tableFactureElement.getField("ID_TAXE"));
 
// Elements assosciés à une facture
Where w = new Where(tableFactureElement.getField("ID_TICKET_CAISSE"), "=", tableTicket.getTable().getUndefinedID());
sel.addJoin("LEFT", tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE")).setWhere(w);
SQLSelectJoin joinArt = sel.addJoin("LEFT", tableFactureElement.getField("ID_ARTICLE"));
SQLSelectJoin joinFamArt = sel.addJoin("LEFT", joinArt.getJoinedTable().getField("ID_FAMILLE_ARTICLE"));
sel.addSelect(joinFamArt.getJoinedTable().getField("NOM"));
 
// Elements associés à un ticket de caisse
Where w2 = new Where(tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE"), "=", 1);
142,16 → 168,23
 
Where w3 = new Where(tableTicket.getField("DATE"), this.du, this.au);
Where w4 = new Where(tableFacture.getField("DATE"), this.du, this.au);
Where wN = new Where(tableFactureElement.getField("NIVEAU"), "=", 1);
if (this.du != null && this.au != null) {
sel.setWhere(w3.or(w4));
sel.setWhere(w3.or(w4).and(wN));
} else {
sel.setWhere(wN);
}
// FIXME traiter le cas du!=null et au==null et vice versa
sel.addGroupBy(tableFactureElement.getField("NOM"));
sel.addGroupBy(tableFactureElement.getField("CODE"));
sel.addGroupBy(tableFactureElement.getField("ID_ARTICLE"));
sel.addGroupBy(tableFactureElement.getField("ID_TAXE"));
sel.addGroupBy(joinFamArt.getJoinedTable().getField("NOM"));
sel.addFieldOrder(joinFamArt.getJoinedTable().getField("NOM"));
System.err.println(sel.asString());
 
// Requete pour obtenir les quantités vendus
SQLSelect selQte = new SQLSelect(Configuration.getInstance().getBase());
SQLSelect selQte = new SQLSelect();
selQte.addSelect(tableFactureElement.getField("CODE"));
selQte.addSelect(tableFactureElement.getField("NOM"));
selQte.addSelect(tableFactureElement.getField("QTE"), "SUM");
160,15 → 193,27
selQte.addSelect(tableFactureElement.getField("T_PV_TTC"), "SUM");
selQte.addSelect(tableFactureElement.getField("ID_TAXE"));
selQte.addSelect(tableFactureElement.getField("ID_ARTICLE"));
if (!this.ticketCaisse) {
selQte.addJoin("LEFT", tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE")).setWhere(w);
} else {
selQte.addJoin("LEFT", tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE")).setWhere(Where.FALSE);
}
selQte.addJoin("LEFT", tableFactureElement.getField("ID_TICKET_CAISSE"), "ticket").setWhere(w2);
SQLSelectJoin joinArt2 = selQte.addJoin("LEFT", tableFactureElement.getField("ID_ARTICLE"));
SQLSelectJoin joinFamArt2 = selQte.addJoin("LEFT", joinArt2.getJoinedTable().getField("ID_FAMILLE_ARTICLE"));
selQte.addSelect(joinFamArt2.getJoinedTable().getField("NOM"));
// FIXME traiter le cas du!=null et au==null et vice
// versa
if (this.du != null && this.au != null) {
selQte.setWhere(w3.or(w4)); // FIXME traiter le cas du!=null et au==null et vice versa
selQte.setWhere(w3.or(w4).and(wN));
} else {
selQte.setWhere(wN);
}
selQte.addGroupBy(tableFactureElement.getField("NOM"));
selQte.addGroupBy(tableFactureElement.getField("CODE"));
selQte.addGroupBy(tableFactureElement.getField("ID_TAXE"));
selQte.addGroupBy(tableFactureElement.getField("ID_ARTICLE"));
selQte.addGroupBy(joinFamArt2.getJoinedTable().getField("NOM"));
 
List<Object[]> listeQte = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(selQte.asString(), new ArrayListHandler());
 
180,12 → 225,19
Number qteVendu = (Number) sqlRow[2];
Number ha = (Number) sqlRow[3];
Number ht = (Number) sqlRow[4];
Number ttc = (Number) sqlRow[5];
BigDecimal ttc = (BigDecimal) sqlRow[5];
Number tvaID = (Number) sqlRow[6];
if (!mapTVAVT.containsKey(tvaID.intValue())) {
mapTVAVT.put(tvaID.intValue(), Tuple2.create((BigDecimal) ht, ttc));
} else {
Tuple2<BigDecimal, BigDecimal> t = mapTVAVT.get(tvaID.intValue());
mapTVAVT.put(tvaID.intValue(), Tuple2.create(t.get0().add((BigDecimal) ht), t.get1().add(ttc)));
}
Number articleID = (Number) sqlRow[7];
ArticleVendu a = new ArticleVendu(code, nom, qteVendu.intValue(), (BigDecimal) ht, (BigDecimal) ha, (BigDecimal) ttc, tvaID.intValue(),
ArticleVendu a = new ArticleVendu(code, nom, qteVendu.intValue(), (BigDecimal) ht, (BigDecimal) ha, ttc, tvaID.intValue(),
tableFactureElement.getForeignTable("ID_ARTICLE").getRow(articleID.intValue()));
map.put(code + "##" + nom, a);
map.put(articleID + "##" + code + "##" + nom + "##" + tvaID, a);
 
}
 
List<Object[]> listeIds = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
194,19 → 246,35
return;
}
 
// Liste des valeurs de la feuille OO
ArrayList<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>(listeIds.size());
String famille = null;
 
BigDecimal totalTPA = BigDecimal.ZERO;
BigDecimal totalTPVTTC = BigDecimal.ZERO;
 
for (Object[] obj : listeIds) {
final Object valueFam = obj[4];
if ((valueFam == null && famille == null) || (famille != null && !famille.equalsIgnoreCase("Non classés") && (valueFam == null || valueFam.toString().trim().length() == 0))) {
famille = "Non classés";
Map<String, Object> mValues = new HashMap<String, Object>();
mValues.put("NOM", famille);
style.put(listValues.size(), "Titre 1");
listValues.add(mValues);
} else if (valueFam != null && !valueFam.toString().equalsIgnoreCase(famille)) {
famille = valueFam.toString();
Map<String, Object> mValues = new HashMap<String, Object>();
mValues.put("NOM", famille);
style.put(listValues.size(), "Titre 1");
listValues.add(mValues);
}
 
Map<String, Object> mValues = new HashMap<String, Object>();
 
String code = (String) obj[0];
String nom = (String) obj[1];
ArticleVendu a = map.get(code + "##" + nom);
 
Number articleID = (Number) obj[2];
Number taxeID = (Number) obj[3];
ArticleVendu a = map.get(articleID + "##" + code + "##" + nom + "##" + taxeID);
if (a == null) {
System.err.println("Aucune correspondance pour l'article " + articleID + "##" + code + "##" + nom + "##" + taxeID);
}
if (a != null && a.ttc != null && (a.ttc.signum() != 0 || (articleID != null && articleID.intValue() > 1))) {
mValues.put("CODE", code);
mValues.put("NOM", nom);
mValues.put("QTE", a.qte);
215,22 → 283,26
mValues.put("TVA_TAUX", a.tva);
mValues.put("NUMERO_COMPTE", a.numeroCompte);
mValues.put("T_PV_TTC", a.ttc);
mValues.put("NB_CHEQUE", obj[2]);
mValues.put("NB_CB", obj[3]);
mValues.put("NB_ESPECES", obj[4]);
mValues.put("NB_CHEQUE", obj[5]);
mValues.put("NB_CB", obj[6]);
mValues.put("NB_ESPECES", obj[7]);
mValues.put("FAMILLE", valueFam);
totalTPA = totalTPA.add(a.ha);
totalTPVTTC = totalTPVTTC.add(a.ttc);
style.put(listValues.size(), "Normal");
listValues.add(mValues);
}
// System.out.println("EtatVentesXmlSheet.createListeValues():" + listValues);
}
 
}
// Liste des ventes comptoirs
final SQLTable venteComptoirT = directory.getElement("SAISIE_VENTE_COMPTOIR").getTable();
SQLSelect selVC = new SQLSelect(venteComptoirT.getBase());
SQLSelect selVC = new SQLSelect();
selVC.addSelect(venteComptoirT.getField("NOM"));
selVC.addSelect(venteComptoirT.getField("MONTANT_HT"), "SUM");
selVC.addSelect(venteComptoirT.getField("MONTANT_TTC"), "SUM");
selVC.addSelect(venteComptoirT.getField("NOM"), "COUNT");
selVC.addSelect(venteComptoirT.getField("ID_TAXE"));
 
if (this.du != null && this.au != null) {
Where wVC = new Where(venteComptoirT.getField("DATE"), this.du, this.au);
241,6 → 313,7
}
// FIXME traiter le cas du!=null et au==null et vice versa
selVC.addGroupBy(venteComptoirT.getField("NOM"));
selVC.addGroupBy(venteComptoirT.getField("ID_TAXE"));
List<Object[]> listVC = (List<Object[]>) venteComptoirT.getDBSystemRoot().getDataSource().execute(selVC.asString(), new ArrayListHandler());
long totalVCInCents = 0;
if (listVC.size() > 0) {
254,14 → 327,9
} else {
mValues2.put("NOM", "VENTE COMPTOIR");
}
Map<Integer, String> style = styleAllSheetValues.get(0);
if (style == null) {
style = new HashMap<Integer, String>();
}
 
style.put(listValues.size(), "Titre 1");
 
styleAllSheetValues.put(0, style);
listValues.add(mValues2);
 
}
270,49 → 338,240
// Nom
mValues.put("NOM", rowVenteComptoir[0]);
// HT
mValues.put("T_PV_HT", ((Number) rowVenteComptoir[1]).longValue() / 100.0D);
final long ht = ((Number) rowVenteComptoir[1]).longValue();
mValues.put("T_PV_HT", ht / 100.0D);
// TTC
final long ttcInCents = ((Number) rowVenteComptoir[2]).longValue();
mValues.put("T_PV_TTC", ttcInCents / 100.0D);
totalVCInCents += ttcInCents;
 
final Integer idTaxe = ((Number) rowVenteComptoir[4]).intValue();
mValues.put("ID_TAXE", idTaxe);
if (!mapTVAVT.containsKey(idTaxe)) {
mapTVAVT.put(idTaxe, Tuple2.create(new BigDecimal(ht).movePointLeft(2), new BigDecimal(ttcInCents).movePointLeft(2)));
} else {
Tuple2<BigDecimal, BigDecimal> t = mapTVAVT.get(idTaxe);
mapTVAVT.put(idTaxe, Tuple2.create(t.get0().add(new BigDecimal(ht).movePointLeft(2)), t.get1().add(new BigDecimal(ttcInCents).movePointLeft(2))));
}
 
// Quantité
mValues.put("QTE", rowVenteComptoir[3]);
listValues.add(mValues);
}
// Avoir
{
 
SQLTable tableAvoirElement = directory.getElement("AVOIR_CLIENT_ELEMENT").getTable();
 
// Requete Pour obtenir les quantités pour chaque type de réglement
SQLSelect sel = new SQLSelect();
 
sel.addSelect(tableAvoirElement.getField("CODE"));
sel.addSelect(tableAvoirElement.getField("NOM"));
sel.addSelect(tableAvoirElement.getField("ID_ARTICLE"));
sel.addSelect(tableAvoirElement.getField("ID_TAXE"));
 
// Elements assosciés à une facture
sel.addJoin("LEFT", tableAvoirElement.getField("ID_AVOIR_CLIENT"));
SQLSelectJoin joinArt = sel.addJoin("LEFT", tableAvoirElement.getField("ID_ARTICLE"));
SQLSelectJoin joinFamArt = sel.addJoin("LEFT", joinArt.getJoinedTable().getField("ID_FAMILLE_ARTICLE"));
sel.addSelect(joinFamArt.getJoinedTable().getField("NOM"));
 
Where w4 = new Where(tableAvoirElement.getTable("AVOIR_CLIENT").getField("DATE"), this.du, this.au);
Where wN = new Where(tableAvoirElement.getField("NIVEAU"), "=", 1);
if (this.du != null && this.au != null) {
sel.setWhere(w4.and(wN));
} else {
sel.setWhere(wN);
}
// FIXME traiter le cas du!=null et au==null et vice versa
sel.addGroupBy(tableAvoirElement.getField("NOM"));
sel.addGroupBy(tableAvoirElement.getField("CODE"));
sel.addGroupBy(tableAvoirElement.getField("ID_ARTICLE"));
sel.addGroupBy(tableAvoirElement.getField("ID_TAXE"));
sel.addGroupBy(joinFamArt.getJoinedTable().getField("NOM"));
sel.addFieldOrder(joinFamArt.getJoinedTable().getField("NOM"));
System.err.println(sel.asString());
 
// Requete pour obtenir les quantités vendus
SQLSelect selQte = new SQLSelect();
selQte.addSelect(tableAvoirElement.getField("CODE"));
selQte.addSelect(tableAvoirElement.getField("NOM"));
selQte.addSelect(tableAvoirElement.getField("QTE"), "SUM");
selQte.addSelect(tableAvoirElement.getField("T_PA_HT"), "SUM");
selQte.addSelect(tableAvoirElement.getField("T_PV_HT"), "SUM");
selQte.addSelect(tableAvoirElement.getField("T_PV_TTC"), "SUM");
selQte.addSelect(tableAvoirElement.getField("ID_TAXE"));
selQte.addSelect(tableAvoirElement.getField("ID_ARTICLE"));
selQte.addJoin("LEFT", tableAvoirElement.getField("ID_AVOIR_CLIENT"));
SQLSelectJoin joinArt2 = selQte.addJoin("LEFT", tableAvoirElement.getField("ID_ARTICLE"));
SQLSelectJoin joinFamArt2 = selQte.addJoin("LEFT", joinArt2.getJoinedTable().getField("ID_FAMILLE_ARTICLE"));
selQte.addSelect(joinFamArt2.getJoinedTable().getField("NOM"));
// FIXME traiter le cas du!=null et au==null et vice
// versa
if (this.du != null && this.au != null) {
selQte.setWhere(w4.and(wN));
} else {
selQte.setWhere(wN);
}
selQte.addGroupBy(tableAvoirElement.getField("NOM"));
selQte.addGroupBy(tableAvoirElement.getField("CODE"));
selQte.addGroupBy(tableAvoirElement.getField("ID_TAXE"));
selQte.addGroupBy(tableAvoirElement.getField("ID_ARTICLE"));
selQte.addGroupBy(joinFamArt2.getJoinedTable().getField("NOM"));
 
List<Object[]> listeQte = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(selQte.asString(), new ArrayListHandler());
 
// Récupération des quantités et des montant totaux pour chaque article
Map<String, ArticleVendu> map = new HashMap<String, ArticleVendu>();
for (Object[] sqlRow : listeQte) {
String code = (String) sqlRow[0];
String nom = (String) sqlRow[1];
Number qteVendu = (Number) sqlRow[2];
Number ha = (Number) sqlRow[3];
Number ht = (Number) sqlRow[4];
BigDecimal ttc = (BigDecimal) sqlRow[5];
Number tvaID = (Number) sqlRow[6];
if (!mapTVAVT.containsKey(tvaID.intValue())) {
mapTVAVT.put(tvaID.intValue(), Tuple2.create(((BigDecimal) ht).negate(), ttc.negate()));
} else {
Tuple2<BigDecimal, BigDecimal> t = mapTVAVT.get(tvaID.intValue());
mapTVAVT.put(tvaID.intValue(), Tuple2.create(t.get0().subtract((BigDecimal) ht), t.get1().subtract(ttc)));
}
Number articleID = (Number) sqlRow[7];
ArticleVendu a = new ArticleVendu(code, nom, -qteVendu.intValue(), ((BigDecimal) ht).negate(), ((BigDecimal) ha).negate(), ttc.negate(), tvaID.intValue(),
tableFactureElement.getForeignTable("ID_ARTICLE").getRow(articleID.intValue()));
map.put(articleID + "##" + code + "##" + nom + "##" + tvaID, a);
 
}
 
List<Object[]> listeIds = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
 
if (listeIds == null) {
return;
}
 
Map<String, Object> mValuesA = new HashMap<String, Object>();
mValuesA.put("NOM", "AVOIRS");
style.put(listValues.size(), "Titre 1");
listValues.add(mValuesA);
 
for (Object[] obj : listeIds) {
final Object valueFam = obj[4];
 
Map<String, Object> mValues = new HashMap<String, Object>();
 
String code = (String) obj[0];
String nom = (String) obj[1];
Number articleID = (Number) obj[2];
Number taxeID = (Number) obj[3];
ArticleVendu a = map.get(articleID + "##" + code + "##" + nom + "##" + taxeID);
if (a.ttc != null && a.ttc.signum() != 0) {
mValues.put("CODE", code);
mValues.put("NOM", nom);
mValues.put("QTE", a.qte);
mValues.put("T_PA", a.ha);
mValues.put("T_PV_HT", a.ht);
mValues.put("TVA_TAUX", a.tva);
mValues.put("NUMERO_COMPTE", a.numeroCompte);
mValues.put("T_PV_TTC", a.ttc);
mValues.put("FAMILLE", valueFam);
totalTPA = totalTPA.add(a.ha);
totalTPVTTC = totalTPVTTC.add(a.ttc);
style.put(listValues.size(), "Normal");
listValues.add(mValues);
}
// System.out.println("EtatVentesXmlSheet.createListeValues():" + listValues);
}
}
totalTPVTTC = totalTPVTTC.add(new BigDecimal(totalVCInCents).movePointLeft(2));
 
// Liste des Achats
final ArrayList<Map<String, Object>> listValuesAchat = new ArrayList<Map<String, Object>>(listeIds.size());
final ArrayList<Map<String, Object>> listValuesAchat = new ArrayList<Map<String, Object>>();
Map<String, Object> valuesAchat = this.mapAllSheetValues.get(1);
if (valuesAchat == null) {
valuesAchat = new HashMap<String, Object>();
}
// Saisie Achat
long totalAchatInCents = 0;
{
final SQLElement eltAchat = directory.getElement("SAISIE_ACHAT");
final SQLTable tableAchat = eltAchat.getTable();
final SQLSelect selAchat = new SQLSelect(Configuration.getInstance().getBase());
final SQLSelect selAchat = new SQLSelect();
 
selAchat.addSelect(tableAchat.getField("NOM"));
selAchat.addSelect(tableAchat.getField("MONTANT_HT"), "SUM");
selAchat.addSelect(tableAchat.getField("MONTANT_TTC"), "SUM");
selAchat.addSelect(tableAchat.getField("ID_TAXE"));
final Where wHA = new Where(tableAchat.getField("DATE"), this.du, this.au);
selAchat.setWhere(wHA);
selAchat.addGroupBy(tableAchat.getField("NOM"));
selAchat.addGroupBy(tableAchat.getField("ID_TAXE"));
List<Object[]> listAchat = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(selAchat.asString(), new ArrayListHandler());
 
long totalAchatInCents = 0;
 
for (Object[] row : listAchat) {
Map<String, Object> mValues = new HashMap<String, Object>();
mValues.put("NOM", row[0]);
final Integer tvaID = ((Number) row[3]).intValue();
mValues.put("TAXE", tvaID);
long ht = ((Number) row[1]).longValue();
long pA = ((Number) row[2]).longValue();
if (!mapTVAHA.containsKey(tvaID.intValue())) {
mapTVAHA.put(tvaID.intValue(), Tuple2.create(new BigDecimal(ht).movePointLeft(2), new BigDecimal(pA).movePointLeft(2)));
} else {
Tuple2<BigDecimal, BigDecimal> t = mapTVAHA.get(tvaID.intValue());
mapTVAHA.put(tvaID.intValue(), Tuple2.create(t.get0().add(new BigDecimal(ht).movePointLeft(2)), t.get1().add(new BigDecimal(pA).movePointLeft(2))));
}
mValues.put("T_PV_HT", -ht / 100.0D);
mValues.put("T_PV_TTC", -pA / 100.0D);
totalAchatInCents -= pA;
listValuesAchat.add(mValues);
}
}
// Facture Fournisseur
{
final SQLElement eltFactElt = directory.getElement("FACTURE_FOURNISSEUR_ELEMENT");
final SQLTable tableFactElt = eltFactElt.getTable();
final SQLTable tableFactF = eltFactElt.getTable().getForeignTable("ID_FACTURE_FOURNISSEUR");
final SQLSelect selAchat = new SQLSelect();
selAchat.addSelect(tableFactElt.getField("ID_ARTICLE"));
selAchat.addSelect(tableFactElt.getField("CODE"));
selAchat.addSelect(tableFactElt.getField("NOM"));
selAchat.addSelect(tableFactElt.getField("T_PA_HT"), "SUM");
selAchat.addSelect(tableFactElt.getField("T_PA_TTC"), "SUM");
selAchat.addSelect(tableFactElt.getField("ID_TAXE"));
selAchat.addSelect(tableFactElt.getField("QTE"), "SUM");
selAchat.addJoin("LEFT", tableFactElt.getField("ID_FACTURE_FOURNISSEUR"));
selAchat.addGroupBy(tableFactElt.getField("ID_ARTICLE"));
selAchat.addGroupBy(tableFactElt.getField("CODE"));
selAchat.addGroupBy(tableFactElt.getField("NOM"));
selAchat.addGroupBy(tableFactElt.getField("ID_TAXE"));
 
totalTPVTTC = totalTPVTTC.add(new BigDecimal(totalVCInCents).movePointLeft(2));
Where wFactF = new Where(tableFactF.getField("DATE"), this.du, this.au);
selAchat.setWhere(wFactF.and(new Where(tableFactElt.getField("NIVEAU"), "=", 1)));
List<Object[]> listAchat = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(selAchat.asString(), new ArrayListHandler());
 
for (Object[] row : listAchat) {
Map<String, Object> mValues = new HashMap<String, Object>();
mValues.put("NOM", row[2]);
final Integer tvaID = ((Number) row[5]).intValue();
mValues.put("TAXE", tvaID);
BigDecimal ht = ((BigDecimal) row[3]);
BigDecimal pA = ((BigDecimal) row[4]);
if (!mapTVAHA.containsKey(tvaID.intValue())) {
mapTVAHA.put(tvaID.intValue(), Tuple2.create(ht, pA));
} else {
Tuple2<BigDecimal, BigDecimal> t = mapTVAHA.get(tvaID.intValue());
mapTVAHA.put(tvaID.intValue(), Tuple2.create(t.get0().add(ht), t.get1().add(pA)));
}
mValues.put("T_PV_HT", ht.negate());
mValues.put("T_PV_TTC", pA.negate());
mValues.put("QTE", row[6]);
totalAchatInCents -= pA.movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
listValuesAchat.add(mValues);
}
}
 
// Récapitulatif
Map<String, Object> valuesE = this.mapAllSheetValues.get(2);
if (valuesE == null) {
321,7 → 580,7
SQLElement eltE = directory.getElement("ENCAISSER_MONTANT");
SQLElement eltM = directory.getElement("MODE_REGLEMENT");
SQLElement eltT = directory.getElement("TYPE_REGLEMENT");
SQLSelect selE = new SQLSelect(Configuration.getInstance().getBase());
SQLSelect selE = new SQLSelect();
selE.addSelect(eltT.getTable().getField("NOM"));
selE.addSelect(eltT.getTable().getField("NOM"), "COUNT");
selE.addSelect(eltE.getTable().getField("MONTANT"), "SUM");
332,7 → 591,7
selE.addGroupBy(eltT.getTable().getField("NOM"));
selE.addFieldOrder(eltT.getTable().getField("NOM"));
List<Object[]> listE = (List<Object[]>) Configuration.getInstance().getBase().getDataSource().execute(selE.asString(), new ArrayListHandler());
ArrayList<Map<String, Object>> listValuesE = new ArrayList<Map<String, Object>>(listeIds.size());
ArrayList<Map<String, Object>> listValuesE = new ArrayList<Map<String, Object>>();
long totalEInCents = 0;
 
for (Object[] o : listE) {
374,6 → 633,12
values.put("DATE", periode);
valuesAchat.put("DATE", periode);
valuesE.put("DATE", periode);
 
Map<String, Object> valuesTotalVT = new HashMap<String, Object>();
valuesTotalVT.put("T_MARGE", "Total");
valuesTotalVT.put("T_PV_TTC", totalTPVTTC);
style.put(listValues.size(), "Titre 2");
listValues.add(valuesTotalVT);
System.err.println(this.du);
System.err.println(this.au);
this.listAllSheetValues.put(0, listValues);
385,8 → 650,71
this.listAllSheetValues.put(2, listValuesE);
this.mapAllSheetValues.put(2, valuesE);
 
// Recap TVA
Map<Integer, String> styleTVA = styleAllSheetValues.get(3);
if (styleTVA == null) {
styleTVA = new HashMap<Integer, String>();
styleAllSheetValues.put(3, styleTVA);
}
ArrayList<Map<String, Object>> listValuesTVA = new ArrayList<Map<String, Object>>();
BigDecimal totalHT = BigDecimal.ZERO;
BigDecimal totalTTC = BigDecimal.ZERO;
BigDecimal totalHTHA = BigDecimal.ZERO;
BigDecimal totalTTCHA = BigDecimal.ZERO;
for (Integer idTaxe : mapTVAVT.keySet()) {
Map<String, Object> vals = new HashMap<String, Object>();
vals.put("VT_TAUX_TVA", TaxeCache.getCache().getTauxFromId(idTaxe));
BigDecimal ht = mapTVAVT.get(idTaxe).get0();
BigDecimal ttc = mapTVAVT.get(idTaxe).get1();
totalHT = totalHT.add(ht);
totalTTC = totalTTC.add(ttc);
vals.put("VT_HT", ht);
vals.put("VT_TVA", ttc.subtract(ht));
vals.put("VT_TTC", ttc);
if (mapTVAHA.containsKey(idTaxe)) {
BigDecimal haht = mapTVAHA.get(idTaxe).get0();
BigDecimal hattc = mapTVAHA.get(idTaxe).get1();
vals.put("HA_HT", haht);
vals.put("HA_TVA", hattc.subtract(haht));
vals.put("HA_TTC", hattc);
totalHTHA = totalHTHA.add(haht);
totalTTCHA = totalTTCHA.add(hattc);
mapTVAHA.remove(idTaxe);
}
styleTVA.put(listValuesTVA.size(), "Normal");
listValuesTVA.add(vals);
}
for (Integer idTaxe : mapTVAHA.keySet()) {
Map<String, Object> vals = new HashMap<String, Object>();
BigDecimal haht = mapTVAHA.get(idTaxe).get0();
BigDecimal hattc = mapTVAHA.get(idTaxe).get1();
vals.put("VT_TAUX_TVA", TaxeCache.getCache().getTauxFromId(idTaxe));
vals.put("HA_HT", haht);
vals.put("HA_TVA", hattc.subtract(haht));
vals.put("HA_TTC", hattc);
totalHTHA = totalHTHA.add(haht);
totalTTCHA = totalTTCHA.add(hattc);
styleTVA.put(listValuesTVA.size(), "Normal");
listValuesTVA.add(vals);
}
Map<String, Object> vals = new HashMap<String, Object>();
vals.put("VT_TAUX_TVA", "Total");
vals.put("VT_HT", totalHT);
vals.put("VT_TVA", totalTTC.subtract(totalHT));
vals.put("VT_TTC", totalTTC);
vals.put("HA_HT", totalHTHA);
vals.put("HA_TVA", totalTTCHA.subtract(totalHTHA));
vals.put("HA_TTC", totalTTCHA);
styleTVA.put(listValuesTVA.size(), "Titre 1");
listValuesTVA.add(vals);
 
Map<String, Object> valuesTVA = new HashMap<String, Object>();
valuesTVA.put("TOTAL_TVA", totalTTC.subtract(totalHT).subtract(totalTTCHA.subtract(totalHTHA)));
this.listAllSheetValues.put(3, listValuesTVA);
valuesTVA.put("DATE", periode);
this.mapAllSheetValues.put(3, valuesTVA);
}
 
public static SQLRow rowDefaultCptService, rowDefaultCptProduit;
static {
final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
479,7 → 479,7
}
}
}
rowValsPort.putRowValues("ID_ARTICLE").put("ID_COMPTE_PCE", rowDefaultCptPort.getID());
rowValsPort.putRowValues("ID_ARTICLE").put("ID_COMPTE_PCE", rowDefaultCptPort.getID()).put("ID_COMPTE_PCE_ACHAT", rowDefaultCptPort.getID());
 
calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
60,7 → 60,7
try {
InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
if (xmlConfiguration == null) {
throw new IllegalStateException("Template configuration " + templateId + " not found");
throw new IllegalStateException("Template configuration " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
Document doc = builder.build(xmlConfiguration);
 
70,7 → 70,9
 
// Création et génération du fichier OO
final InputStream template = TemplateManager.getInstance().getTemplate(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
 
if (template == null) {
throw new IllegalStateException("Template " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
}
final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
Sheet sheet0 = spreadSheet.getSheet(0);
if (sheetName != null && sheetName.size() > 0) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
455,7 → 455,7
 
if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, true);
doc.printDocument();
doc.printDocument(job);
doc.close();
} else {
// Load the spreadsheet.
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/ODTPrinterNX.java
53,7 → 53,7
final MediaPrintableArea printableArea = new MediaPrintableArea((float) (paper.getImageableX() / POINTS_PER_INCH), (float) (paper.getImageableY() / POINTS_PER_INCH),
(float) (paper.getImageableWidth() / POINTS_PER_INCH), (float) (paper.getImageableHeight() / POINTS_PER_INCH), Size2DSyntax.INCH);
attributes.add(printableArea);
 
// hghghgh
final PageFormat format = printJob.getPageFormat(null);
format.setPaper(paper);
printJob.setPrintable(this, format);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/PaiementRemainedDevisProvider.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.SQLRowAccessor;
 
import java.math.BigDecimal;
 
public class PaiementRemainedDevisProvider implements SpreadSheetCellValueProvider {
 
private PaiementRemainedDevisProvider() {
}
 
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
return getRestant(row);
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("quote.payment.remained", new PaiementRemainedDevisProvider());
}
 
private BigDecimal getRestant(SQLRowAccessor r) {
long acompte = r.getLong("T_ACOMPTE");
long ttc = r.getLong("T_TTC");
 
long total = ttc - acompte;
 
return new BigDecimal(total).movePointLeft(2);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/ConditionsReglementDetailsProvider.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.
*/
/*
* Créé le 25 oct. 2012
*/
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;
 
public class ConditionsReglementDetailsProvider implements SpreadSheetCellValueProvider {
 
public ConditionsReglementDetailsProvider() {
 
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
String r = "";
final SQLRowAccessor foreignRow = row.getForeign("ID_MODE_REGLEMENT");
if (foreignRow != null) {
if (foreignRow.getForeign("ID_TYPE_REGLEMENT") != null) {
SQLRowAccessor rowT = foreignRow.getForeign("ID_TYPE_REGLEMENT");
if (!rowT.getString("NOM").equalsIgnoreCase("Indéfini")) {
r = rowT.getString("NOM");
}
}
int ajours = foreignRow.getInt("AJOURS");
int njour = foreignRow.getInt("LENJOUR");
 
if (ajours == 0 && njour == 0) {
if (foreignRow.getBoolean("COMPTANT") != null && !foreignRow.getBoolean("COMPTANT")) {
r = "Date de facture";
} else {
r = "Comptant";
}
} else {
 
if (ajours != 0) {
 
r = "à" + ajours + ((ajours > 1) ? " jours" : " jour");
}
if (njour > 0 && njour < 31) {
r += " le " + njour;
} else {
if (njour == 0) {
r += " date de facture";
} else {
r += " fin de mois";
}
}
}
}
return r;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("conditions.paiement.details", new ConditionsReglementDetailsProvider());
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/PrixUnitaireRemiseProvider.java
23,9 → 23,25
 
public class PrixUnitaireRemiseProvider extends UserInitialsValueProvider {
 
public static int UNITAIRE_REMISE = 0;
public static int TOTAL_NON_ACOMPTE = 1;
public final int type;
 
public PrixUnitaireRemiseProvider(int t) {
this.type = t;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
if (this.type == UNITAIRE_REMISE) {
return getPrixUnitaire(row);
} else {
return getPrixTotalOrigin(row);
}
}
 
public Object getPrixTotalOrigin(SQLRowAccessor row) {
final BigDecimal pv = row.getBigDecimal("PV_HT");
BigDecimal remise = (BigDecimal) row.getObject("POURCENT_REMISE");
if (remise == null) {
32,6 → 48,19
remise = BigDecimal.ZERO;
}
BigDecimal acompte = BigDecimal.ONE;
 
BigDecimal result = BigDecimal.ONE.subtract(remise.movePointLeft(2)).multiply(pv, DecimalUtils.HIGH_PRECISION).multiply(acompte, DecimalUtils.HIGH_PRECISION);
 
return result.multiply(row.getBigDecimal("QTE_UNITAIRE")).multiply(new BigDecimal(row.getInt("QTE"))).setScale(2, RoundingMode.HALF_UP);
}
 
public Object getPrixUnitaire(SQLRowAccessor row) {
final BigDecimal pv = row.getBigDecimal("PV_HT");
BigDecimal remise = (BigDecimal) row.getObject("POURCENT_REMISE");
if (remise == null) {
remise = BigDecimal.ZERO;
}
BigDecimal acompte = BigDecimal.ONE;
if (row.getTable().contains("POURCENT_ACOMPTE") && row.getObject("POURCENT_ACOMPTE") != null) {
acompte = ((BigDecimal) row.getObject("POURCENT_ACOMPTE")).movePointLeft(2);
}
41,6 → 70,7
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("PrixUnitaireRemise", new PrixUnitaireRemiseProvider());
SpreadSheetCellValueProviderManager.put("PrixUnitaireRemise", new PrixUnitaireRemiseProvider(UNITAIRE_REMISE));
SpreadSheetCellValueProviderManager.put("PrixTotalSansAcompte", new PrixUnitaireRemiseProvider(TOTAL_NON_ACOMPTE));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/TotalAcompteProvider.java
16,6 → 16,7
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.math.BigDecimal;
45,7 → 46,7
Set<SQLRowAccessor> facture = new HashSet<SQLRowAccessor>();
facture.add(row);
for (SQLRowAccessor sqlRowAccessor : rows) {
total += getPreviousAcompte(sqlRowAccessor.getForeign("ID_COMMANDE_CLIENT"), facture, c);
total += getPreviousAcompte(sqlRowAccessor.getForeign("ID_COMMANDE_CLIENT"), facture, c, row);
}
 
return new BigDecimal(total).movePointLeft(2);
56,7 → 57,7
SpreadSheetCellValueProviderManager.put("sales.account.total.ttc", new TotalAcompteProvider(TypeTotalAcompteProvider.TTC));
}
 
public long getPreviousAcompte(SQLRowAccessor sqlRowAccessor, Set<SQLRowAccessor> alreadyAdded, Calendar c) {
public long getPreviousAcompte(SQLRowAccessor sqlRowAccessor, Set<SQLRowAccessor> alreadyAdded, Calendar c, SQLRowAccessor origin) {
if (sqlRowAccessor == null || sqlRowAccessor.isUndefined()) {
return 0L;
}
65,7 → 66,8
for (SQLRowAccessor sqlRowAccessor2 : rows) {
SQLRowAccessor rowFact = sqlRowAccessor2.getForeign("ID_SAISIE_VENTE_FACTURE");
 
if (rowFact != null && !rowFact.isUndefined() && !alreadyAdded.contains(rowFact) && rowFact.getDate("DATE").before(c)) {
if (rowFact != null && !rowFact.isUndefined() && !alreadyAdded.contains(rowFact)
&& (rowFact.getDate("DATE").before(c) || (rowFact.getDate("DATE").equals(c) && rowFact.getID() < origin.getID()))) {
alreadyAdded.add(rowFact);
l += this.type == TypeTotalAcompteProvider.HT ? rowFact.getLong("T_HT") : rowFact.getLong("T_TTC");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieKm.java
41,10 → 41,10
this.date = (Date) saisieRow.getObject("DATE");
final String labelSaisie = saisieRow.getObject("NOM").toString();
this.nom = labelSaisie;
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", saisieRow.getObject("ID_JOURNAL"));
this.mEcritures.put("ID_MOUVEMENT", new Integer(1));
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
this.putValue("ID_JOURNAL", saisieRow.getObject("ID_JOURNAL"));
this.putValue("ID_MOUVEMENT", new Integer(1));
 
// on calcule le nouveau numero de mouvement
getNewMouvement(GenerationMvtSaisieKm.source, this.idSaisieKm, 1, (labelSaisie.length() == 0 ? "Saisie au km " : labelSaisie));
60,12 → 60,12
int idCpt = ComptePCESQLElement.getId(rowElement.getString("NUMERO"), rowElement.getString("NOM"));
 
// Ajout de l'écriture
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCpt));
this.mEcritures.put("NOM", rowElement.getString("NOM_ECRITURE"));
this.mEcritures.put("DEBIT", rowElement.getObject("DEBIT"));
this.mEcritures.put("CREDIT", rowElement.getObject("CREDIT"));
this.putValue("ID_COMPTE_PCE", new Integer(idCpt));
this.putValue("NOM", rowElement.getString("NOM_ECRITURE"));
this.putValue("DEBIT", rowElement.getObject("DEBIT"));
this.putValue("CREDIT", rowElement.getObject("CREDIT"));
if (tableElt.contains("NOM_PIECE")) {
this.mEcritures.put("NOM_PIECE", rowElement.getObject("NOM_PIECE"));
this.putValue("NOM_PIECE", rowElement.getObject("NOM_PIECE"));
}
SQLRow rowEcr = ajoutEcriture();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtTicketCaisse.java
67,16 → 67,16
// iniatilisation des valeurs de la map
GenerationMvtTicketCaisse.this.date = GenerationMvtTicketCaisse.this.rowTicket.getDate("DATE").getTime();
GenerationMvtTicketCaisse.this.nom = "Ticket " + GenerationMvtTicketCaisse.this.rowTicket.getString("NUMERO");
GenerationMvtTicketCaisse.this.mEcritures.put("DATE", GenerationMvtTicketCaisse.this.date);
GenerationMvtTicketCaisse.this.mEcritures.put("NOM", GenerationMvtTicketCaisse.this.nom);
GenerationMvtTicketCaisse.this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
GenerationMvtTicketCaisse.this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
GenerationMvtTicketCaisse.this.putValue("DATE", GenerationMvtTicketCaisse.this.date);
GenerationMvtTicketCaisse.this.putValue("NOM", GenerationMvtTicketCaisse.this.nom);
GenerationMvtTicketCaisse.this.putValue("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
GenerationMvtTicketCaisse.this.putValue("ID_MOUVEMENT", Integer.valueOf(1));
 
// on calcule le nouveau numero de mouvement
if (GenerationMvtTicketCaisse.this.idMvt == 1) {
getNewMouvement(GenerationMvtTicketCaisse.source, GenerationMvtTicketCaisse.this.rowTicket.getID(), 1, GenerationMvtTicketCaisse.this.nom);
} else {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(GenerationMvtTicketCaisse.this.idMvt));
GenerationMvtTicketCaisse.this.putValue("ID_MOUVEMENT", Integer.valueOf(GenerationMvtTicketCaisse.this.idMvt));
}
 
TotalCalculator calc = getValuesFromElement(rowTicket, rowTicket.getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT"), BigDecimal.ZERO, null, null);
87,9 → 87,9
for (SQLRowAccessor row : calc.getMapHt().keySet()) {
long b = calc.getMapHt().get(row).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (b != 0) {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(b));
GenerationMvtTicketCaisse.this.putValue("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
GenerationMvtTicketCaisse.this.putValue("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.putValue("CREDIT", Long.valueOf(b));
ajoutEcriture();
}
}
99,9 → 99,9
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", longValue);
GenerationMvtTicketCaisse.this.putValue("ID_COMPTE_PCE", rowAc.getID());
GenerationMvtTicketCaisse.this.putValue("DEBIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.putValue("CREDIT", longValue);
ajoutEcriture();
}
}
118,9 → 118,9
}
}
}
GenerationMvtTicketCaisse.this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
GenerationMvtTicketCaisse.this.mEcritures.put("DEBIT", ttcLongValue);
GenerationMvtTicketCaisse.this.mEcritures.put("CREDIT", Long.valueOf(0));
GenerationMvtTicketCaisse.this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
GenerationMvtTicketCaisse.this.putValue("DEBIT", ttcLongValue);
GenerationMvtTicketCaisse.this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
return GenerationMvtTicketCaisse.this.idMvt;
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtRetourNatexis.java
57,17 → 57,17
 
this.nom = "Retour natexis facture " + rowFacture.getObject("NUMERO").toString();
this.date = new Date();
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
 
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
this.putValue("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
 
int idJrnlFactor = rowPrefsCompte.getInt("ID_JOURNAL_FACTOR");
if (idJrnlFactor > 1) {
this.mEcritures.put("ID_JOURNAL", idJrnlFactor);
this.putValue("ID_JOURNAL", idJrnlFactor);
}
 
this.mEcritures.put("ID_MOUVEMENT", this.idMvt);
this.putValue("ID_MOUVEMENT", this.idMvt);
 
// compte Factor
int idComptefactor = rowPrefsCompte.getInt("ID_COMPTE_PCE_FACTOR");
78,9 → 78,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", idComptefactor);
this.mEcritures.put("CREDIT", rowFacture.getObject("T_TTC"));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", idComptefactor);
this.putValue("CREDIT", rowFacture.getObject("T_TTC"));
this.putValue("DEBIT", Long.valueOf(0));
ajoutEcriture();
 
// compte Clients
95,9 → 95,9
}
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", rowFacture.getObject("T_TTC"));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("DEBIT", rowFacture.getObject("T_TTC"));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
SQLRowValues rowValsFacture = rowFacture.asRowValues();
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementChequeClient.java
61,15 → 61,15
SQLRow clientRow = base.getTable("CLIENT").getRow(chequeRow.getInt("ID_CLIENT"));
 
// initialisation des valeurs de la map
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
if (this.banque == null || this.banque.isUndefined() || this.banque.isForeignEmpty("ID_JOURNAL")) {
fillJournalBanqueFromRow(chequeRow);
} else {
int idJrnl = this.banque.getForeignID("ID_JOURNAL");
this.mEcritures.put("ID_JOURNAL", idJrnl);
this.putValue("ID_JOURNAL", idJrnl);
}
 
setDateReglement(this.idCheque, this.date);
93,16 → 93,16
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(this.montant));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(this.montant));
ajoutEcriture();
System.err.println("First ECriture for mvt " + this.idMvt);
 
// compte de reglement cheque, ...
fillCompteBanqueFromRow(chequeRow, "VenteCheque", false);
this.mEcritures.put("DEBIT", new Long(this.montant));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("DEBIT", new Long(this.montant));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
System.err.println("Ecritures générées pour le mouvement " + this.idMvt);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementAvoirChequeClient.java
43,12 → 43,12
// initialisation des valeurs de la map
 
this.nom = "Reglement avoir client par chéque";
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
 
fillJournalBanqueFromRow(chequeAvoirRow);
 
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// compte Clients
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
59,15 → 59,15
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(this.montant));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(this.montant));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
// compte de reglement cheque, ...
fillCompteBanqueFromRow(chequeAvoirRow, "VenteCheque", false);
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(this.montant));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(this.montant));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieAchat.java
50,12 → 50,12
// iniatilisation des valeurs de la map
this.date = (Date) saisieRow.getObject("DATE");
this.nom = "Achat : " + rowFournisseur.getString("NOM") + " Facture : " + this.saisieRow.getObject("NUMERO_FACTURE").toString() + " " + saisieRow.getObject("NOM").toString();
this.mEcritures.put("DATE", this.date);
this.putValue("DATE", this.date);
AccountingRecordsProvider provider = AccountingRecordsProviderManager.get(ID);
provider.putLabel(saisieRow, this.mEcritures);
 
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieAchat.journal);
this.mEcritures.put("ID_MOUVEMENT", new Integer(1));
this.putValue("ID_JOURNAL", GenerationMvtSaisieAchat.journal);
this.putValue("ID_MOUVEMENT", new Integer(1));
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(this.saisieRow.getLong("MONTANT_TTC"));
72,7 → 72,7
provider.putPieceLabel(this.saisieRow, rowValsPiece);
rowValsPiece.update();
 
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
}
 
// generation des ecritures + maj des totaux du compte associe
86,9 → 86,9
idCompteAchat = ComptePCESQLElement.getIdComptePceDefault("Achats");
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteAchat));
this.mEcritures.put("DEBIT", new Long(prixHT.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteAchat));
this.putValue("DEBIT", new Long(prixHT.getLongValue()));
this.putValue("CREDIT", new Long(0));
SQLRow rowEcr = ajoutEcriture();
 
// addAssocAnalytiqueFromProvider(rowEcr, saisieRow);
112,9 → 112,9
idCompteTVA = rowCptTva.getID();
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVA));
this.mEcritures.put("DEBIT", new Long(prixTVA.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteTVA));
this.putValue("DEBIT", new Long(prixTVA.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
if (rowFournisseur.getBoolean("UE")) {
129,9 → 129,9
} else {
idCompteTVAIntra = rowCptTva.getID();
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixTVA.getLongValue()));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixTVA.getLongValue()));
ajoutEcriture();
}
}
145,12 → 145,12
idCompteFourn = ComptePCESQLElement.getIdComptePceDefault("Fournisseurs");
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.mEcritures.put("DEBIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.putValue("DEBIT", new Long(0));
if (rowFournisseur.getBoolean("UE")) {
this.mEcritures.put("CREDIT", new Long(prixHT.getLongValue()));
this.putValue("CREDIT", new Long(prixHT.getLongValue()));
} else {
this.mEcritures.put("CREDIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(prixTTC.getLongValue()));
}
ajoutEcriture();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationEcritures.java
44,6 → 44,8
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import com.ibm.icu.text.SimpleDateFormat;
 
/**
* Generation des ecritures comptables, permet l'ajout d'ecriture, la creation des mouvements
*
71,11 → 73,11
private SQLRow rowAnalytiqueSource;
 
// Map contenant les valeurs pour la SQLRowValues de la table Ecritures à ajouter
public Map<String, Object> mEcritures = new HashMap<String, Object>();
protected final Map<String, Object> mEcritures = new HashMap<String, Object>();
 
// public GenerationEcritures(SQLRow rowSource) {
// this.rowAnalytiqueSource = rowSource;
// }
public void putValue(String field, Object value) {
mEcritures.put(field, value);
}
 
public void setRowAnalytiqueSource(SQLRow rowAnalytiqueSource) {
this.rowAnalytiqueSource = rowAnalytiqueSource;
145,19 → 147,15
 
if (dCloture != null) {
if (dCloture.after(d)) {
System.err.println("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
// ExceptionHandler.handle("Impossible de générer l'écriture pour la date " + d + ".
// Cette période est cloturée.");
throw new IllegalArgumentException("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
// return -1;
final String error = "Impossible de générer l'écriture pour la date " + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(d)
+ ". Cette date est postérieure à la date de clôture (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dCloture) + ")";
throw new IllegalArgumentException(error);
}
} else {
if (dDebEx.after(d)) {
System.err.println("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
// ExceptionHandler.handle("Impossible de générer l'écriture pour la date " + d + ".
// Cette période est cloturée.");
// return -1;
throw new IllegalArgumentException("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
final String error = "Impossible de générer l'écriture pour la date " + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(d)
+ ". Cette date est antérieure à la date de début d'exercice (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dDebEx) + ")";
throw new IllegalArgumentException(error);
}
}
 
440,7 → 438,7
}
if (rowTVAPort != null && !rowTVAPort.isUndefined()) {
SQLRowValues rowValsPort = new SQLRowValues(foreign);
rowValsPort.put("T_PV_HT", portHT);
rowValsPort.put(achat ? "T_PA_HT" : "T_PV_HT", portHT);
rowValsPort.put("QTE", 1);
rowValsPort.put("ID_TAXE", rowTVAPort.getIDNumber());
 
467,7 → 465,7
}
}
final SQLRowValues rowValsArt = rowValsPort.putRowValues("ID_ARTICLE");
rowValsArt.put("ID_COMPTE_PCE", rowDefaultCptPort.getID());
rowValsArt.put(achat ? "ID_COMPTE_PCE_ACHAT" : "ID_COMPTE_PCE", rowDefaultCptPort.getID());
rowValsArt.put("ID_TAXE_COMPLEMENTAIRE", null);
calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirClient.java
63,26 → 63,26
rowClient = avoirRow.getForeignRow("ID_CLIENT");
 
if (ecritureTable.contains("CODE_CLIENT")) {
this.mEcritures.put("CODE_CLIENT", rowClient.getString("CODE"));
this.putValue("CODE_CLIENT", rowClient.getString("CODE"));
}
 
// iniatilisation des valeurs de la map
this.date = (Date) avoirRow.getObject("DATE");
this.nom = avoirRow.getObject("NOM").toString();
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
AccountingRecordsProvider provider = AccountingRecordsProviderManager.get(ID);
provider.putLabel(avoirRow, this.mEcritures);
 
this.mEcritures.put("ID_JOURNAL", GenerationMvtAvoirClient.journal);
this.putValue("ID_JOURNAL", GenerationMvtAvoirClient.journal);
if (affacturage) {
 
int idJrnlFactor = rowPrefsCompte.getInt("ID_JOURNAL_FACTOR");
if (idJrnlFactor > 1) {
this.mEcritures.put("ID_JOURNAL", idJrnlFactor);
this.putValue("ID_JOURNAL", idJrnlFactor);
}
}
 
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
this.putValue("ID_MOUVEMENT", Integer.valueOf(1));
 
// on cree un nouveau mouvement
if (this.idMvt == 1) {
90,7 → 90,7
provider.putPieceLabel(avoirRow, rowValsPiece);
getNewMouvement(GenerationMvtAvoirClient.source, this.idAvoirClient, 1, rowValsPiece);
} else {
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
SQLRowValues rowValsPiece = pieceTable.getTable("MOUVEMENT").getRow(idMvt).getForeign("ID_PIECE").asRowValues();
provider.putPieceLabel(avoirRow, rowValsPiece);
116,23 → 116,23
for (SQLRowAccessor rowCompl : compl.keySet()) {
if (compl.get(rowCompl) != null) {
long taxeC = compl.get(rowCompl).multiply(rowCompl.getBigDecimal("POURCENT").movePointLeft(2)).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
this.mEcritures.put("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", Long.valueOf(taxeC));
this.putValue("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", Long.valueOf(taxeC));
ajoutEcriture();
taxe += taxeC;
// this.mEcritures.put("ID_COMPTE_PCE",
// this.putValue("ID_COMPTE_PCE",
// rowCompl.getForeignID("ID_COMPTE_PCE_PRODUITS"));
// this.mEcritures.put("CREDIT", Long.valueOf(taxeC));
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", Long.valueOf(taxeC));
// this.putValue("DEBIT", Long.valueOf(0));
// ajoutEcriture();
}
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", row.getID());
this.mEcritures.put("DEBIT", Long.valueOf(b - taxe));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", row.getID());
this.putValue("DEBIT", Long.valueOf(b - taxe));
this.putValue("CREDIT", Long.valueOf(0));
SQLRow rowEcr = ajoutEcriture();
// addAssocAnalytiqueFromProvider(rowEcr, avoirRow);
}
143,9 → 143,9
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("DEBIT", Long.valueOf(longValue));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("DEBIT", Long.valueOf(longValue));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
}
}
159,10 → 159,10
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("DEBIT", Long.valueOf(0));
long ttc = calc.getTotalTTC().movePointRight(2).longValue();
this.mEcritures.put("CREDIT", Long.valueOf(ttc));
this.putValue("CREDIT", Long.valueOf(ttc));
ajoutEcriture();
 
// Mise à jour de mouvement associé à la facture d'avoir
175,9 → 175,9
}
 
if (affacturage) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(ttc));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("DEBIT", Long.valueOf(ttc));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
// compte Factor
193,9 → 193,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", idComptefactor);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(ttc));
this.putValue("ID_COMPTE_PCE", idComptefactor);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc));
ajoutEcriture();
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementVenteNG.java
68,17 → 68,25
setRowAnalytiqueSource(source);
// iniatilisation des valeurs de la map
this.date = d;
if (typeRegRow.getID() == TypeReglementSQLElement.CB && modeReglement.getObject("DATE") != null) {
this.date = (Date) modeReglement.getObject("DATE");
}
 
// TODO Nommage des ecritures
 
this.nom = label;
 
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
fillJournalBanqueFromRow(modeReglement);
 
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
if (source.getTable().getName().equalsIgnoreCase("ENCAISSER_MONTANT")) {
if (source.getBoolean("ACOMPTE")) {
final String numeroDevis = source.asRow().getForeign("ID_DEVIS").getString("NUMERO");
this.idMvt = getNewMouvement(source.getTable().getName(), source.getID(), 1, numeroDevis);
this.putValue("NOM_PIECE", numeroDevis);
} else {
List<SQLRow> l = source.getReferentRows(source.getTable().getTable("ENCAISSER_MONTANT_ELEMENT"));
for (SQLRow sqlRow : l) {
SQLRow mvtEch = sqlRow.getForeignRow("ID_MOUVEMENT_ECHEANCE");
87,6 → 95,7
}
}
}
}
// si paiement comptant
if ((!typeRegRow.getBoolean("ECHEANCE"))
&& ((modeReglement.getBoolean("COMPTANT")) || (!modeReglement.getBoolean("DATE_FACTURE") && (modeReglement.getInt("AJOURS") == 0 && modeReglement.getInt("LENJOUR") == 0)))) {
117,11 → 126,11
rowEncaisseElt = rowValsElt.insert();
 
}
 
if (!source.getTable().getName().equalsIgnoreCase("ENCAISSER_MONTANT") || !source.getBoolean("ACOMPTE")) {
this.idMvt = getNewMouvement(rowEncaisse.getTable().getName(), rowEncaisse.getID(), mvtSource.getID(), mvtSource.getInt("ID_PIECE"));
}
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
SQLRowValues rowVals = rowEncaisse.createEmptyUpdateRow();
rowVals.put("ID_MOUVEMENT", this.idMvt);
 
164,7 → 173,7
setDateReglement(source, this.date);
}
if (typeRegRow.getID() == TypeReglementSQLElement.ESPECE) {
this.mEcritures.put("ID_JOURNAL", JournalSQLElement.CAISSES);
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES);
}
 
int idCompteClient = rowClient.getInt("ID_COMPTE_PCE");
184,9 → 193,9
}
}
}
this.mEcritures.put("ID_COMPTE_PCE", idCompteClient);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(ttc.getLongValue()));
this.putValue("ID_COMPTE_PCE", idCompteClient);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc.getLongValue()));
 
this.ecrClient = ajoutEcriture();
 
197,12 → 206,12
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("VenteEspece");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
} else {
fillCompteBanqueFromRow(modeReglement, "VenteCB", false);
}
this.mEcritures.put("DEBIT", Long.valueOf(ttc.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", Long.valueOf(ttc.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
}
363,10 → 372,10
}
}
 
this.mEcritures.put("ID_JOURNAL", JournalSQLElement.BANQUES);
this.mEcritures.put("ID_COMPTE_PCE", idCompteClient);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(ttc.getLongValue()));
this.putValue("ID_JOURNAL", JournalSQLElement.BANQUES);
this.putValue("ID_COMPTE_PCE", idCompteClient);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc.getLongValue()));
 
this.ecrClient = ajoutEcriture();
 
375,9 → 384,9
if (idCompteRegl <= 1) {
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("ValeurEncaissement");
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.mEcritures.put("DEBIT", Long.valueOf(ttc.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("DEBIT", Long.valueOf(ttc.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
 
ajoutEcriture();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementAchat.java
96,12 → 96,12
this.idMvt = this.idPere;
 
// iniatilisation des valeurs de la map
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationMvtReglementAchat.journalCaisse);
this.putValue("ID_JOURNAL", GenerationMvtReglementAchat.journalCaisse);
} else {
fillJournalBanqueFromRow(modeRegRow);
}
115,9 → 115,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(compteFourn));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(compteFourn));
this.putValue("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
// compte de reglement, caisse, CB, ...
126,13 → 126,13
if (idCompteRegl <= 1) {
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("VenteEspece");
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
 
} else {
fillCompteBanqueFromRow(modeRegRow, "VenteCB", true);
}
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(prixTTC.getLongValue()));
ajoutEcriture();
}
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementAvoir.java
66,15 → 66,15
} else {
 
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationMvtReglementAvoir.journalCaisse);
this.putValue("ID_JOURNAL", GenerationMvtReglementAvoir.journalCaisse);
} else {
fillJournalBanqueFromRow(modeRegRow);
}
 
this.idMvt = idPere;
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// compte Clients
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
87,9 → 87,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
// compte de reglement, caisse, cheque, ...
99,12 → 99,12
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("VenteEspece");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
} else {
fillCompteBanqueFromRow(modeRegRow, "VenteCB", false);
}
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixTTC.getLongValue()));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixTTC.getLongValue()));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirFournisseur.java
58,16 → 58,16
// iniatilisation des valeurs de la map
this.date = (Date) avoirRow.getObject("DATE");
this.nom = avoirRow.getObject("NOM").toString();
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", "Avoir fournisseur : " + avoirRow.getString("NUMERO") + " " + rowFourn.getString("NOM"));
this.mEcritures.put("ID_JOURNAL", GenerationMvtAvoirFournisseur.journal);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", "Avoir fournisseur : " + avoirRow.getString("NUMERO") + " " + rowFourn.getString("NOM"));
this.putValue("ID_JOURNAL", GenerationMvtAvoirFournisseur.journal);
this.putValue("ID_MOUVEMENT", Integer.valueOf(1));
 
// on cree un nouveau mouvement
if (this.idMvt == 1) {
getNewMouvement(GenerationMvtAvoirFournisseur.source, this.idAvoirFourn, 1, "Avoir Fournisseur : " + avoirRow.getString("NUMERO"));
} else {
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
}
 
// generation des ecritures + maj des totaux du compte associe
85,9 → 85,9
}
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteAchat));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixHT.getLongValue()));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteAchat));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(prixHT.getLongValue()));
SQLRow rowEcr = ajoutEcriture();
// addAssocAnalytiqueFromProvider(rowEcr, avoirRow);
 
106,9 → 106,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue()));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(prixTVA.getLongValue()));
ajoutEcriture();
 
if (rowFourn.getBoolean("UE")) {
116,9 → 116,9
if (idCompteTVAIntra <= 1) {
idCompteTVAIntra = ComptePCESQLElement.getIdComptePceDefault("TVAIntraComm");
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVAIntra));
this.mEcritures.put("DEBIT", Long.valueOf(prixTVA.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTVAIntra));
this.putValue("DEBIT", Long.valueOf(prixTVA.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
}
}
130,9 → 130,9
idCompteFourn = ComptePCESQLElement.getIdComptePceDefault("Fournisseurs");
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteFourn));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteFourn));
this.putValue("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
// Mise à jour de mouvement associé à la facture d'avoir
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementChequeFourn.java
14,7 → 14,6
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTable;
 
37,11 → 36,11
this.date = d;
SQLRow rowFournisseur = tableFourn.getRow(rowCheque.getInt("ID_FOURNISSEUR"));
this.nom = "Reglement cheque " + rowFournisseur.getString("NOM");
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
 
fillJournalBanqueFromRow(rowCheque);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// compte Fournisseurs
int idCompteFourn = rowFournisseur.getInt("ID_COMPTE_PCE");
54,15 → 53,15
 
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.mEcritures.put("DEBIT", new Long(montant));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.putValue("DEBIT", new Long(montant));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
// compte de reglement cheque, ...
fillCompteBanqueFromRow(rowCheque, "AchatCheque", true);
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(montant));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(montant));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAcompte.java
56,10 → 56,10
this.date = new Date();
// TODO recuperer le mois et l'année
this.nom = "Acompte " + rowSal.getString("NOM");
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", journalOD);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_JOURNAL", journalOD);
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
// Acompte
int idCompteAcompte = rowPrefsCompte.getInt("ID_COMPTE_PCE_ACOMPTE");
67,10 → 67,10
idCompteAcompte = ComptePCESQLElement.getIdComptePceDefault("PayeAcompte");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompte));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("DEBIT", Long.valueOf(this.montant));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompte));
this.putValue("NOM", this.nom);
this.putValue("DEBIT", Long.valueOf(this.montant));
this.putValue("CREDIT", Long.valueOf(0));
 
ajoutEcriture();
 
84,10 → 84,10
e.printStackTrace();
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTresor));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(this.montant));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTresor));
this.putValue("NOM", this.nom);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(this.montant));
 
ajoutEcriture();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtVirement.java
24,6 → 24,8
private long debit, credit;
private String labelPiece;
private boolean clearMvt = true;
private boolean fermeture = false;
private boolean ouverture = false;
 
/***********************************************************************************************
*
54,6 → 56,14
 
}
 
public void setOuverture(boolean ouverture) {
this.ouverture = ouverture;
}
 
public void setFermeture(boolean fermeture) {
this.fermeture = fermeture;
}
 
/**
* Permet de générer plusieurs virement pour une meme piece
*
79,10 → 89,12
public int genereMouvement() throws SQLException {
 
// iniatilisation des valeurs de la map
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", this.id_journal);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
this.putValue("DATE", this.date);
this.putValue("CLOTURE", this.fermeture);
this.putValue("RAN", this.ouverture);
this.putValue("NOM", this.nom);
this.putValue("ID_JOURNAL", this.id_journal);
this.putValue("ID_MOUVEMENT", Integer.valueOf(1));
 
// on calcule le nouveau numero de mouvement
if (this.idPiece <= 1) {
92,20 → 104,20
getNewMouvement("", 1, 1, this.idPiece);
}
}
this.mEcritures.put("ID_MOUVEMENT", this.idMvt);
this.putValue("ID_MOUVEMENT", this.idMvt);
 
// generation des ecritures + maj des totaux du compte associe
 
// compte Départ
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(this.id_compte_depart));
this.mEcritures.put("DEBIT", Long.valueOf(this.debit));
this.mEcritures.put("CREDIT", Long.valueOf(this.credit));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(this.id_compte_depart));
this.putValue("DEBIT", Long.valueOf(this.debit));
this.putValue("CREDIT", Long.valueOf(this.credit));
ajoutEcriture();
 
// compte arrivé
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(this.id_compte_arrive));
this.mEcritures.put("DEBIT", Long.valueOf(this.credit));
this.mEcritures.put("CREDIT", Long.valueOf(this.debit));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(this.id_compte_arrive));
this.putValue("DEBIT", Long.valueOf(this.credit));
this.putValue("CREDIT", Long.valueOf(this.debit));
ajoutEcriture();
 
return this.idMvt;
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteFacture.java
25,6 → 25,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
103,7 → 104,7
} else {
this.nom = "Fact. vente " + saisieRow.getObject("NUMERO").toString();
}
this.mEcritures.put("NOM", this.nom);
this.putValue("NOM", this.nom);
 
// iniatilisation des valeurs de la map
this.date = (Date) saisieRow.getObject("DATE");
110,9 → 111,9
AccountingRecordsProvider provider = AccountingRecordsProviderManager.get(ID);
provider.putLabel(saisieRow, this.mEcritures);
 
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(1));
this.putValue("DATE", this.date);
this.putValue("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
this.putValue("ID_MOUVEMENT", Integer.valueOf(1));
 
// on calcule le nouveau numero de mouvement
if (this.idMvt == 1) {
120,7 → 121,7
provider.putPieceLabel(saisieRow, rowValsPiece);
getNewMouvement(GenerationMvtSaisieVenteFacture.source, this.idSaisieVenteFacture, 1, rowValsPiece);
} else {
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
SQLRowValues rowValsPiece = mvtTable.getRow(idMvt).getForeign("ID_PIECE").asRowValues();
provider.putPieceLabel(saisieRow, rowValsPiece);
rowValsPiece.update();
152,15 → 153,15
for (SQLRowAccessor rowCompl : compl.keySet()) {
if (compl.get(rowCompl) != null) {
long taxeC = compl.get(rowCompl).multiply(rowCompl.getBigDecimal("POURCENT").movePointLeft(2)).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
this.mEcritures.put("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(taxeC));
this.putValue("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(taxeC));
ajoutEcriture();
taxe += taxeC;
// this.mEcritures.put("ID_COMPTE_PCE",
// this.putValue("ID_COMPTE_PCE",
// rowCompl.getForeignID("ID_COMPTE_PCE_PRODUITS"));
// this.mEcritures.put("DEBIT", Long.valueOf(taxeC));
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// this.putValue("DEBIT", Long.valueOf(taxeC));
// this.putValue("CREDIT", Long.valueOf(0));
// ajoutEcriture();
}
}
173,9 → 174,9
idComptePCE = Integer.valueOf(row.getID());
}
 
this.mEcritures.put("ID_COMPTE_PCE", idComptePCE);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(b - taxe));
this.putValue("ID_COMPTE_PCE", idComptePCE);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(b - taxe));
ajoutEcriture();
}
}
184,9 → 185,9
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", longValue);
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", longValue);
ajoutEcriture();
}
}
199,12 → 200,12
idCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients");
}
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
if (ecrTable.contains("CODE_CLIENT")) {
this.mEcritures.put("CODE_CLIENT", clientRow.getString("CODE"));
this.putValue("CODE_CLIENT", clientRow.getString("CODE"));
}
this.mEcritures.put("DEBIT", ttcLongValue);
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", ttcLongValue);
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
// TODO Gestion des factures d'acomptes
220,13 → 221,13
// for (SQLRow sqlRow : rowsAcompte) {
// long acompteTTC = sqlRow.getLong("T_TTC");
// long acompteHT = sqlRow.getLong("T_HT");
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompteClient));
// this.mEcritures.put("DEBIT", acompteTTC);
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompteClient));
// this.putValue("DEBIT", acompteTTC);
// this.putValue("CREDIT", Long.valueOf(0));
// ajoutEcriture();
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", acompteTTC);
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", acompteTTC);
// ajoutEcriture();
//
// montantAcompteTTC += acompteTTC;
235,9 → 236,9
// if (tva > 0) {
//
//
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idTVAAcompte));
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", Long.valueOf(tva));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idTVAAcompte));
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", Long.valueOf(tva));
// ajoutEcriture();
//
// Map<Integer, Long> m = getMultiTVAFromRow(saisieRow,
251,23 → 252,23
// if (idCpt <= 1) {
// idCpt = idCompteTVA;
// }
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCpt));
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", Long.valueOf(l));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCpt));
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", Long.valueOf(l));
// ajoutEcriture();
// allTaxe += l;
// }
// }
// if (allTaxe < prixTVA.getLongValue()) {
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteTVA));
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", Long.valueOf(prixTVA.getLongValue() - allTaxe));
// ajoutEcriture();
// }
//
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(compteDebitTvaAcompte));
// this.mEcritures.put("DEBIT", Long.valueOf(tva));
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(compteDebitTvaAcompte));
// this.putValue("DEBIT", Long.valueOf(tva));
// this.putValue("CREDIT", Long.valueOf(0));
// ajoutEcriture();
// }
// }
284,7 → 285,7
// Génération du reglement
SQLRow modeRegl = saisieRow.getForeignRow("ID_MODE_REGLEMENT");
final SQLRow typeRegRow = modeRegl.getForeignRow("ID_TYPE_REGLEMENT");
String label = this.nom + " (" + typeRegRow.getString("NOM") + ")";
String label = this.nom + " (" + typeRegRow.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
int idAvoir = saisieRow.getInt("ID_AVOIR_CLIENT");
if (idAvoir > 1) {
// SQLRow avoirRow = base.getTable("AVOIR_CLIENT").getRow(idAvoir);
293,7 → 294,7
}
prixTTC = new PrixTTC(saisieRow.getLong("NET_A_PAYER"));
if (prixTTC.getLongValue() > 0) {
new GenerationReglementVenteNG(label, clientRow, prixTTC, this.date, modeRegl, saisieRow, mvtTable.getRow(idMvt));
new GenerationReglementVenteNG(label.trim(), clientRow, prixTTC, this.date, modeRegl, saisieRow, mvtTable.getRow(idMvt));
}
}
// Mise à jour de mouvement associé à la facture
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementAchat.java
85,7 → 85,7
} else {
 
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationReglementAchat.journalCaisse);
this.putValue("ID_JOURNAL", GenerationReglementAchat.journalCaisse);
} else {
fillJournalBanqueFromRow(modeRegRow);
}
94,9 → 94,9
 
this.idMvt = getNewMouvement("REGLER_MONTANT", idRegMontant, rowMvtSource.getID(), rowMvtSource.getInt("ID_PIECE"));
 
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// compte Fournisseurs
int idCompteFourn = rowFournisseur.getInt("ID_COMPTE_PCE");
109,15 → 109,15
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.putValue("DEBIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
// compte de reglement, caisse, CB, ...
fillCompteBanqueFromRow(modeRegRow, "AchatCB", true);
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixTTC.getLongValue()));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixTTC.getLongValue()));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteComptoir.java
66,16 → 66,16
string += saisieRow.getForeignRow("ID_ARTICLE").getString("NOM");
}
this.nom = string;
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteComptoir.journal);
this.mEcritures.put("ID_MOUVEMENT", new Integer(1));
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
this.putValue("ID_JOURNAL", GenerationMvtSaisieVenteComptoir.journal);
this.putValue("ID_MOUVEMENT", new Integer(1));
 
// on calcule le nouveau numero de mouvement
if (this.idMvt == 1) {
this.idMvt = getNewMouvement(GenerationMvtSaisieVenteComptoir.source, this.idSaisieVenteComptoir, 1, string);
}
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// generation des ecritures + maj des totaux du compte associe
 
86,9 → 86,9
if (idCompteVenteService <= 1) {
idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteService));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(service));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteVenteService));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(service));
ajoutEcriture();
 
if ((prixHT.getLongValue() - service) > 0) {
96,9 → 96,9
if (idCompteVenteProduit <= 1) {
idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixHT.getLongValue() - service));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixHT.getLongValue() - service));
ajoutEcriture();
}
 
108,9 → 108,9
if (idCompteVenteProduit <= 1) {
idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixHT.getLongValue()));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixHT.getLongValue()));
ajoutEcriture();
}
 
129,9 → 129,9
idCompteTVA = rowCptTva.getID();
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVA));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(tva));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteTVA));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(tva));
ajoutEcriture();
}
 
143,9 → 143,9
idCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients");
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
// Règlement
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtFichePaye.java
103,10 → 103,10
// SQLRow rowMois = tableMois.getRow(rowFiche.getInt("ID_MOIS"));
// SQLRow rowSal = tableSalarie.getRow(rowFiche.getInt("ID_SALARIE"));
this.nom = "Paye " + this.mois + " " + this.annee;
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_JOURNAL", journalOD);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_JOURNAL", journalOD);
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
int idComptePaye = rowPrefsCompte.getInt("ID_COMPTE_PCE_PAYE");
if (idComptePaye <= 1) {
144,14 → 144,14
 
SQLRow rowFiche = tableFichePaye.getRow(this.idFichePaye[i]);
SQLRow rowSal = tableSalarie.getRow(rowFiche.getInt("ID_SALARIE"));
this.mEcritures.put("NOM", rowSal.getString("NOM") + " " + this.nom);
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idComptePaye));
this.putValue("NOM", rowSal.getString("NOM") + " " + this.nom);
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idComptePaye));
 
// float sal = rowFiche.getFloat("SAL_BRUT");
// totalSalaireBrut += sal;
 
this.mEcritures.put("DEBIT", totalSalaireBrut.setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue());
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", totalSalaireBrut.setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue());
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
}
 
209,23 → 209,23
}
 
String nomRub = rowSource.getString("NOM");
this.mEcritures.put("ID_COMPTE_PCE", idCompteCharge);
this.mEcritures.put("NOM", nomRub + ", " + rowSal.getString("NOM") + ", " + this.nom);
this.putValue("ID_COMPTE_PCE", idCompteCharge);
this.putValue("NOM", nomRub + ", " + rowSal.getString("NOM") + ", " + this.nom);
if (montant > 0) {
this.mEcritures.put("DEBIT", montant);
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", montant);
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", montant);
// this.mEcritures.put("ID_COMPTE_PCE", idComptePayeRegl);
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", montant);
// this.putValue("ID_COMPTE_PCE", idComptePayeRegl);
// ajoutEcriture();
} else {
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", -montant);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", -montant);
ajoutEcriture();
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// this.mEcritures.put("DEBIT", -montant);
// this.mEcritures.put("ID_COMPTE_PCE", idComptePayeRegl);
// this.putValue("CREDIT", Long.valueOf(0));
// this.putValue("DEBIT", -montant);
// this.putValue("ID_COMPTE_PCE", idComptePayeRegl);
// ajoutEcriture();
}
}
268,20 → 268,20
if (idComptePayeRegl <= 1) {
idComptePayeRegl = ComptePCESQLElement.getIdComptePceDefault("PayeReglement");
}
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idComptePayeRegl));
this.mEcritures.put("NOM", rowSal.getString("NOM") + " " + this.nom);
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idComptePayeRegl));
this.putValue("NOM", rowSal.getString("NOM") + " " + this.nom);
 
// float sal = rowFiche.getFloat("NET_A_PAYER");
 
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", totalSalaireNet.setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue());
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", totalSalaireNet.setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue());
ajoutEcriture();
}
 
/*
* this.mEcritures.put("ID_COMPTE_PCE", new Integer(ComptePCESQLElement.getId("421")));
* this.mEcritures.put("NOM", this.nom); this.mEcritures.put("DEBIT", new Float(0));
* this.mEcritures.put("CREDIT", new Float(totalSalaireBrut)); ajoutEcriture();
* this.putValue("ID_COMPTE_PCE", new Integer(ComptePCESQLElement.getId("421")));
* this.putValue("NOM", this.nom); this.putValue("DEBIT", new Float(0));
* this.putValue("CREDIT", new Float(totalSalaireBrut)); ajoutEcriture();
*/
 
// Acomptes
296,10 → 296,10
// if (idCompteAcompte <= 1) {
// idCompteAcompte = ComptePCESQLElement.getIdComptePceDefault("PayeAcompte");
// }
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompte));
// this.mEcritures.put("NOM", rowSal.getString("NOM") + " Acompte sur " + this.nom);
// this.mEcritures.put("DEBIT", Long.valueOf(0));
// this.mEcritures.put("CREDIT", Long.valueOf(acompte));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteAcompte));
// this.putValue("NOM", rowSal.getString("NOM") + " Acompte sur " + this.nom);
// this.putValue("DEBIT", Long.valueOf(0));
// this.putValue("CREDIT", Long.valueOf(acompte));
// ajoutEcriture();
//
// SQLRow rowRegl = tableReglementPaye.getRow(rowSal.getInt("ID_REGLEMENT_PAYE"));
307,10 → 307,10
// if (idComptePayeRegl <= 1) {
// idComptePayeRegl = ComptePCESQLElement.getIdComptePceDefault("PayeReglement");
// }
// this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idComptePayeRegl));
// this.mEcritures.put("NOM", rowSal.getString("NOM") + " Acompte sur " + this.nom);
// this.mEcritures.put("DEBIT", Long.valueOf(acompte));
// this.mEcritures.put("CREDIT", Long.valueOf(0));
// this.putValue("ID_COMPTE_PCE", Integer.valueOf(idComptePayeRegl));
// this.putValue("NOM", rowSal.getString("NOM") + " Acompte sur " + this.nom);
// this.putValue("DEBIT", Long.valueOf(acompte));
// this.putValue("CREDIT", Long.valueOf(0));
// ajoutEcriture();
// }
// }
395,36 → 395,36
// enregistrement des ecritures pour les cotisations salariales et patronales
for (Entry<Integer, Long> entry : mapCompteCredSal.entrySet()) {
Integer idCompte = entry.getKey();
this.mEcritures.put("ID_COMPTE_PCE", idCompte);
this.mEcritures.put("NOM", "Cotisations salariales, " + this.nom);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", entry.getValue());
this.putValue("ID_COMPTE_PCE", idCompte);
this.putValue("NOM", "Cotisations salariales, " + this.nom);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", entry.getValue());
ajoutEcriture();
}
for (Entry<Integer, Long> entry : mapCompteDebSal.entrySet()) {
Integer idCompte = entry.getKey();
this.mEcritures.put("ID_COMPTE_PCE", idCompte);
this.mEcritures.put("NOM", "Cotisations salariales, " + this.nom);
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", entry.getValue());
this.putValue("ID_COMPTE_PCE", idCompte);
this.putValue("NOM", "Cotisations salariales, " + this.nom);
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", entry.getValue());
ajoutEcriture();
}
 
for (Entry<Integer, Long> entry : mapCompteCredPat.entrySet()) {
Integer idCompte = entry.getKey();
this.mEcritures.put("ID_COMPTE_PCE", idCompte);
this.mEcritures.put("NOM", "Cotisations patronales, " + this.nom);
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", entry.getValue());
this.putValue("ID_COMPTE_PCE", idCompte);
this.putValue("NOM", "Cotisations patronales, " + this.nom);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", entry.getValue());
ajoutEcriture();
}
 
for (Entry<Integer, Long> entry : mapCompteDebPat.entrySet()) {
Integer idCompte = entry.getKey();
this.mEcritures.put("ID_COMPTE_PCE", idCompte);
this.mEcritures.put("NOM", "Cotisations patronales, " + this.nom);
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", entry.getValue());
this.putValue("ID_COMPTE_PCE", idCompte);
this.putValue("NOM", "Cotisations patronales, " + this.nom);
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", entry.getValue());
ajoutEcriture();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementVente.java
25,7 → 25,6
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
 
import java.sql.SQLException;
import java.sql.Timestamp;
57,11 → 56,11
String s = encaisseMontantRow.getString("NOM");
this.nom = "Règlement vente " + ((s == null) ? "" : s) + " (" + typeRegRow.getString("NOM") + ")";
 
this.mEcritures.put("DATE", this.date);
this.mEcritures.put("NOM", this.nom);
this.putValue("DATE", this.date);
this.putValue("NOM", this.nom);
 
fillJournalBanqueFromRow(modeRegRow);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
// si paiement comptant
if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0)) {
76,7 → 75,7
} else {
setDateReglement(idEncaisseRegl, idEchCli, this.date);
if (typeRegRow.getID() == TypeReglementSQLElement.ESPECE) {
this.mEcritures.put("ID_JOURNAL", GenerationReglementVente.journalCaisse);
this.putValue("ID_JOURNAL", GenerationReglementVente.journalCaisse);
}
 
SQLRow echeanceRow = null;
100,9 → 99,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(prixTTC.getLongValue()));
ajoutEcriture();
 
// compte de reglement, caisse, cheque, ...
112,12 → 111,12
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("VenteEspece");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
} else {
fillCompteBanqueFromRow(modeRegRow, "VenteCB", false);
}
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementVenteFacture.java
17,11 → 17,13
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
 
import java.sql.SQLException;
import java.sql.Timestamp;
70,9 → 72,11
}
 
// iniatilisation des valeurs de la map
 
this.date = (Date) saisieRow.getObject("DATE");
this.nom = "Saisie Vente facture " + saisieRow.getObject("NUMERO").toString() + " (" + typeRegRow.getString("NOM") + ")";
 
this.nom = "Facture " + saisieRow.getObject("NUMERO").toString() + " (" + typeRegRow.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
this.nom = this.nom.trim();
// si paiement comptant
if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0)) {
// test Cheque
80,17 → 84,21
// Ajout dans cheque à encaisser sans date minimum d'encaissement
paiementCheque(this.date);
} else {
 
if (typeRegRow.getID() == TypeReglementSQLElement.CB && modeRegRow.getObject("DATE") != null) {
this.date = (Date) modeRegRow.getObject("DATE");
}
setDateReglement(saisieRow);
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationMvtReglementVenteFacture.journalCaisse);
this.putValue("ID_JOURNAL", GenerationMvtReglementVenteFacture.journalCaisse);
} else {
fillJournalBanqueFromRow(modeRegRow);
}
 
this.idMvt = idPere;
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
// compte Clients
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
101,15 → 109,15
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixTTC.getLongValue()));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixTTC.getLongValue()));
ajoutEcriture();
 
// compte de reglement, caisse, cheque, ...
fillCompteBanqueFromRow(modeRegRow, "VenteCB", false);
this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("DEBIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtFactureFournisseur.java
61,12 → 61,12
// iniatilisation des valeurs de la map
this.date = (Date) saisieRow.getObject("DATE");
this.nom = "Achat : " + rowFournisseur.getString("NOM") + " Facture : " + saisieRow.getObject("NUMERO").toString() + " " + saisieRow.getObject("NOM").toString();
this.mEcritures.put("DATE", this.date);
this.putValue("DATE", this.date);
// AccountingRecordsProvider provider = AccountingRecordsProviderManager.get(ID);
// provider.putLabel(saisieRow, this.mEcritures);
this.mEcritures.put("NOM", nom);
this.mEcritures.put("ID_JOURNAL", GenerationMvtFactureFournisseur.journal);
this.mEcritures.put("ID_MOUVEMENT", new Integer(1));
this.putValue("NOM", nom);
this.putValue("ID_JOURNAL", GenerationMvtFactureFournisseur.journal);
this.putValue("ID_MOUVEMENT", new Integer(1));
 
// on calcule le nouveau numero de mouvement
if (this.idMvt == 1) {
80,7 → 80,7
rowValsPiece.put("NOM", saisieRow.getObject("NUMERO").toString());
rowValsPiece.update();
 
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
}
 
// generation des ecritures + maj des totaux du compte associe
94,10 → 94,10
rowCompteAchat = ComptePCESQLElement.getRowComptePceDefault("Achats");
}
}
BigDecimal portHT = BigDecimal.valueOf(saisieRow.getLong("PORT_HT")).movePointLeft(2);
TotalCalculator calc = getValuesFromElement(rowFournisseur.getBoolean("UE"), true, "T_PA_HT", saisieRow, saisieRow.getTable().getTable("FACTURE_FOURNISSEUR_ELEMENT"), portHT,
saisieRow.getForeign("ID_TAXE_PORT"), null, rowCompteAchat);
 
TotalCalculator calc = getValuesFromElement(rowFournisseur.getBoolean("UE"), true, "T_PA_HT", saisieRow, saisieRow.getTable().getTable("FACTURE_FOURNISSEUR_ELEMENT"), BigDecimal.ZERO, null,
null, rowCompteAchat);
 
long ttcLongValue = calc.getTotalTTC().movePointRight(2).longValue();
long htLongValue = calc.getTotalHT().movePointRight(2).longValue();
 
104,9 → 104,9
for (SQLRowAccessor row : calc.getMapHt().keySet()) {
long b = calc.getMapHt().get(row).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (b != 0) {
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", Long.valueOf(b));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(row.getID()));
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", Long.valueOf(b));
SQLRow rowEcr = ajoutEcriture();
// addAssocAnalytiqueFromProvider(rowEcr, saisieRow);
}
116,9 → 116,9
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
long longValue = tvaMap.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.mEcritures.put("DEBIT", longValue);
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", longValue);
ajoutEcriture();
 
// if (rowFournisseur.getBoolean("UE")) {
126,9 → 126,9
// if (idCompteTVAIntra <= 1) {
// idCompteTVAIntra = ComptePCESQLElement.getIdComptePceDefault("TVAIntraComm");
// }
// this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
// this.mEcritures.put("DEBIT", new Long(0));
// this.mEcritures.put("CREDIT", new Long(longValue));
// this.putValue("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
// this.putValue("DEBIT", new Long(0));
// this.putValue("CREDIT", new Long(longValue));
// ajoutEcriture();
// }
}
138,9 → 138,9
for (SQLRowAccessor rowAc : tvaMapIntra.keySet()) {
long longValue = tvaMapIntra.get(rowAc).setScale(2, RoundingMode.HALF_UP).movePointRight(2).longValue();
if (longValue != 0) {
this.mEcritures.put("ID_COMPTE_PCE", rowAc.getID());
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", longValue);
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", longValue);
ajoutEcriture();
 
// if (rowFournisseur.getBoolean("UE")) {
148,9 → 148,9
// if (idCompteTVAIntra <= 1) {
// idCompteTVAIntra = ComptePCESQLElement.getIdComptePceDefault("TVAIntraComm");
// }
// this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
// this.mEcritures.put("DEBIT", new Long(0));
// this.mEcritures.put("CREDIT", new Long(longValue));
// this.putValue("ID_COMPTE_PCE", new Integer(idCompteTVAIntra));
// this.putValue("DEBIT", new Long(0));
// this.putValue("CREDIT", new Long(longValue));
// ajoutEcriture();
// }
}
165,12 → 165,12
idCompteFourn = ComptePCESQLElement.getIdComptePceDefault("Fournisseurs");
}
}
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.mEcritures.put("DEBIT", new Long(0));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteFourn));
this.putValue("DEBIT", new Long(0));
if (rowFournisseur.getBoolean("UE")) {
this.mEcritures.put("CREDIT", new Long(htLongValue));
this.putValue("CREDIT", new Long(htLongValue));
} else {
this.mEcritures.put("CREDIT", new Long(ttcLongValue));
this.putValue("CREDIT", new Long(ttcLongValue));
}
ajoutEcriture();
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementVenteComptoir.java
79,12 → 79,12
this.idMvt = idPere;
 
// iniatilisation des valeurs de la map pour les ecritures
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", new Integer(this.idMvt));
 
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationMvtReglementVenteComptoir.journalCaisse);
this.putValue("ID_JOURNAL", GenerationMvtReglementVenteComptoir.journalCaisse);
} else {
fillJournalBanqueFromRow(modeRegRow);
}
98,9 → 98,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
this.mEcritures.put("DEBIT", new Long(0));
this.mEcritures.put("CREDIT", new Long(prixTTC.getLongValue()));
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(prixTTC.getLongValue()));
ajoutEcriture();
 
// compte de reglement
110,12 → 110,12
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("VenteEspece");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
} else {
fillCompteBanqueFromRow(modeRegRow, "VenteCB", false);
}
this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", new Long(0));
this.putValue("DEBIT", new Long(prixTTC.getLongValue()));
this.putValue("CREDIT", new Long(0));
ajoutEcriture();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementFactureFournisseur.java
94,12 → 94,12
this.idMvt = this.idPere;
 
// iniatilisation des valeurs de la map
this.mEcritures.put("DATE", new java.sql.Date(this.date.getTime()));
this.mEcritures.put("NOM", this.nom);
this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
this.putValue("DATE", new java.sql.Date(this.date.getTime()));
this.putValue("NOM", this.nom);
this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
 
if (typeRegRow.getID() == 4) {
this.mEcritures.put("ID_JOURNAL", GenerationMvtReglementFactureFournisseur.journalCaisse);
this.putValue("ID_JOURNAL", GenerationMvtReglementFactureFournisseur.journalCaisse);
} else {
 
fillJournalBanqueFromRow(modeRegRow);
114,9 → 114,9
}
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(compteFourn));
this.mEcritures.put("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.mEcritures.put("CREDIT", Long.valueOf(0));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(compteFourn));
this.putValue("DEBIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
ajoutEcriture();
 
// compte de reglement, caisse, CB, ...
126,12 → 126,12
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("AchatEspece");
}
 
this.mEcritures.put("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
} else {
fillCompteBanqueFromRow(modeRegRow, "AchatCB", true);
}
this.mEcritures.put("DEBIT", Long.valueOf(0));
this.mEcritures.put("CREDIT", Long.valueOf(prixTTC.getLongValue()));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(prixTTC.getLongValue()));
ajoutEcriture();
}
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ContactSQLElementBase.java
13,12 → 13,6
package org.openconcerto.erp.core.customerrelationship.customer.element;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
27,9 → 21,17
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.EmailComposer;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Value;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public abstract class ContactSQLElementBase extends ConfSQLElement {
 
public ContactSQLElementBase() {
45,6 → 47,13
return this.getTable().getName();
}
 
// @Override
// public String getDescription(SQLRowValues r, DescLength l) {
// final Value<String> firstName = r.getNonDefaultObject("PRENOM", String.class);
// return (firstName.hasValue() && !StringUtils.isEmpty(firstName.getValue()) ?
// firstName.getValue() + " " : "") + r.getString("NOM");
// }
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
if (getTable().contains("ID_TITRE_PERSONNEL")) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
154,6 → 154,7
l.add("ID_COMPTE_PCE");
l.add("ID_MODE_REGLEMENT");
l.add("INFOS");
l.add("ID_COMMERCIAL");
return l;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/report/FicheClientXmlSheet.java
23,7 → 23,7
public class FicheClientXmlSheet extends AbstractSheetXMLWithDate {
 
public static final String TEMPLATE_ID = "FicheClient";
public static final String TEMPLATE_PROPERTY_NAME = DEFAULT_PROPERTY_NAME;
public static final String TEMPLATE_PROPERTY_NAME = "LocationFicheClient";
 
public FicheClientXmlSheet(SQLRow row) {
super(row);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCESQLElement.java
19,6 → 19,7
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.TreesOfSQLRows;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
152,6 → 153,8
protected void _initComboRequest(ComboSQLRequest req) {
super._initComboRequest(req);
req.setWhere(new Where(getTable().getField("OBSOLETE"), "=", Boolean.FALSE));
// Ne pas écraser l'ordre de la base (equals, startwith, etc..)
req.setItemsOrder(null);
}
 
protected List<String> getListFields() {
325,9 → 328,13
}
 
public static SQLRow getRow(String numero, String nom) {
SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
SQLTable compteTable = base.getTable("COMPTE_PCE");
return getRow(numero, nom, ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete());
}
 
public static SQLRow getRow(String numero, String nom, DBRoot root) {
 
SQLTable compteTable = root.getTable("COMPTE_PCE");
 
final SQLBackgroundTableCacheItem cacheForTable = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
if (numero == null) {
throw new IllegalArgumentException("null numero");
423,4 → 430,5
protected String createCode() {
return createCodeFromPackage() + ".code.enterprise";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033B.java
431,12 → 431,12
******************************************************************************************/
// 312
// 374 SommeSoldeDebit( 4457, 4457* )
// TODO répartir les comptes crediteurs
long v374 = this.sommeCompte.soldeCompteDebiteur(4457, 4457, true, this.dateDeb, this.dateFin);
// TODO répartir les comptes débiteurs
long v374 = this.sommeCompte.soldeCompteCrediteur(4457, 4457, true, this.dateDeb, this.dateFin);
this.m.put("T1.41", GestionDevise.currencyToString(v374, false));
 
// 378 SommeSoldeCredit( 44566 )
long v378 = this.sommeCompte.soldeCompteCrediteur(44566, 44566, true, this.dateDeb, this.dateFin);
long v378 = this.sommeCompte.soldeCompteDebiteur(44566, 44566, true, this.dateDeb, this.dateFin);
this.m.put("T1.42", GestionDevise.currencyToString(v378, false));
 
SwingUtilities.invokeLater(new Runnable() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheetXML.java
100,7 → 100,9
this.excludeCompteSolde = excludeCptSolde;
this.centralClient = centralClient;
this.centralFourn = centralFourn;
 
Map<String, Object> map = new HashMap<>();
recapSousTotaux.add(map);
map.put("DATE", "Récapitulatif");
// createMap();
}
 
120,8 → 122,9
// this.mCell.put("E" + row, "Période du " + dateFormatEcr.format(this.dateDu) + " au " +
// dateFormatEcr.format(this.dateAu));
// }
private List<Map<String, Object>> recapSousTotaux = new ArrayList<>();
 
private void makeSousTotal(Map<String, Object> line, Map<Integer, String> style, int pos, long debit, long credit) {
private void makeSousTotal(String numCpt, String nomCpt, Map<String, Object> line, Map<Integer, String> style, int pos, long debit, long credit) {
style.put(pos, "Titre 1");
 
line.put("DATE", "");
131,6 → 134,14
line.put("DEBIT", Double.valueOf(GestionDevise.currencyToString(debit, false)));
line.put("CREDIT", Double.valueOf(GestionDevise.currencyToString(credit, false)));
line.put("SOLDE", Double.valueOf(GestionDevise.currencyToString(debit - credit, false)));
 
Map<String, Object> lineRecap = new HashMap<>();
lineRecap.putAll(line);
lineRecap.put("DATE", numCpt);
lineRecap.put("JOURNAL", nomCpt);
lineRecap.put("LIBELLE", "");
recapSousTotaux.add(lineRecap);
 
}
 
protected void createListeValues() {
271,6 → 282,8
setTitle = true;
// ligne vide avant de mettre le setTitle
setLine = false;
String nomCpt = "";
String numCpt = "";
for (int i = 0; i < size;) {
// System.err.println(i);
// // System.err.println("START NEW PAGE; POS : " + posLine);
289,8 → 302,8
SQLRowValues rowEcr = list.get(i);
 
int idCpt = rowEcr.getInt("ID_COMPTE_PCE");
String nomCpt = rowEcr.getString("COMPTE_NOM");
String numCpt = rowEcr.getString("COMPTE_NUMERO");
nomCpt = rowEcr.getString("COMPTE_NOM");
numCpt = rowEcr.getString("COMPTE_NUMERO");
 
Map<String, Object> ooLine = new HashMap<String, Object>();
tableauVals.add(ooLine);
373,7 → 386,7
rowFirstEcr = rowEcr;
idCptFirstEcr = rowFirstEcr.getInt("ID_COMPTE_PCE");
numCptFirstEcr = rowEcr.getString("COMPTE_NUMERO");
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
makeSousTotal(numCpt, nomCpt, ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sousTotalCredit = 0;
sousTotalDebit = 0;
507,14 → 520,32
this.mapAllSheetValues.put(0, sheetVals);
 
if (size > 0) {
 
Map<String, Object> ooLine = new HashMap<String, Object>();
tableauVals.add(ooLine);
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
makeSousTotal(numCpt, nomCpt, ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sheetVals.put("TOTAL_DEBIT", (totalDebit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit, false)));
sheetVals.put("TOTAL_CREDIT", (totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalCredit, false)));
sheetVals.put("TOTAL_SOLDE", (totalDebit - totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false)));
 
Map<String, Object> emptyLine = new HashMap<String, Object>();
style.put(tableauVals.size(), "Normal");
tableauVals.add(emptyLine);
for (Map<String, Object> recap : recapSousTotaux) {
style.put(tableauVals.size(), "Titre 1");
tableauVals.add(recap);
}
Map<String, Object> lineRecap = new HashMap<>();
lineRecap.put("DEBIT", (totalDebit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit, false)));
lineRecap.put("CREDIT", (totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalCredit, false)));
lineRecap.put("SOLDE", (totalDebit - totalCredit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit - totalCredit, false)));
lineRecap.put("DATE", "");
lineRecap.put("JOURNAL", "");
lineRecap.put("LIBELLE", "Global");
style.put(tableauVals.size(), "Titre 1");
tableauVals.add(lineRecap);
}
 
sheetVals.put("TITRE_1", "GRAND LIVRE " + this.rowSociete.getString("TYPE") + " " + this.rowSociete.getString("NOM"));
sheetVals.put("DATE_EDITION", new Date());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/LettragePanel.java
25,11 → 25,14
import org.openconcerto.erp.utils.UpperCaseFormatFilter;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
102,6 → 105,7
public LettragePanel() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
 
this.modeSelect = allEcriture;
 
111,8 → 115,15
 
this.add(labelPointageCompte, c);
this.selCompte = new ISQLCompteSelector();
this.selCompte.init();
this.selCompte.setValue(ComptePCESQLElement.getId("5"));
SQLElement eltCpt = directory.getElement("COMPTE_PCE");
final ComboSQLRequest createComboRequest = eltCpt.createComboRequest();
String function = "REGEXP";
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) {
function = "~";
}
createComboRequest.setWhere(new Where(eltCpt.getTable().getField("NUMERO"), function, "^4.*$"));
this.selCompte.init(eltCpt, createComboRequest);
this.selCompte.setValue(ComptePCESQLElement.getId("4"));
 
c.gridx++;
c.weightx = 1;
253,7 → 264,7
this.add(sepEcriture, c);
 
// Liste des ecritures
final EcritureSQLElement ecritureElem = Configuration.getInstance().getDirectory().getElement(EcritureSQLElement.class);
final EcritureSQLElement ecritureElem = directory.getElement(EcritureSQLElement.class);
this.ecriturePanel = new ListPanelEcritures(ecritureElem, new IListe(ecritureElem.createLettrageTableSource()));
c.gridx = 0;
c.gridy++;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteCloturePreferencePanel.java
15,6 → 15,7
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLBase;
22,6 → 23,8
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.preferences.DefaultPreferencePanel;
 
29,11 → 32,14
import java.awt.GridBagLayout;
import java.sql.SQLException;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
public class CompteCloturePreferencePanel extends DefaultPreferencePanel {
private ISQLCompteSelector selCompteOuverture, selCompteFermeture, selCompteResultat, selCompteResultatPerte;
private SQLRequestComboBox selJournal;
private JCheckBox boxCompteSolde;
private final static SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
private SQLRowValues rowPrefCompteVals = new SQLRowValues(tablePrefCompte);
88,6 → 94,28
this.selCompteResultatPerte.init();
this.add(this.selCompteResultatPerte, c);
 
// Compte résultat
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Journal des à nouveaux"), c);
c.weightx = 1;
c.gridx++;
this.selJournal = new SQLRequestComboBox(false);
this.selJournal.uiInit(Configuration.getInstance().getDirectory().getElement("JOURNAL").createComboRequest());
this.add(this.selJournal, c);
 
// Compte résultat
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Générer des écritures de fermetures et d'à nouveaux pour les comptes soldés"), c);
c.weightx = 1;
c.gridx++;
this.boxCompteSolde = new JCheckBox();
this.boxCompteSolde.setSelected(true);
this.add(this.boxCompteSolde, c);
 
// Spacer
 
JPanel p = new JPanel();
104,6 → 132,8
this.rowPrefCompteVals.put("ID_COMPTE_PCE_BILAN_F", this.selCompteFermeture.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_RESULTAT", this.selCompteResultat.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_RESULTAT_PERTE", this.selCompteResultat.getValue());
this.rowPrefCompteVals.put("ID_JOURNAL_AN", this.selJournal.getValue());
this.rowPrefCompteVals.put("CREATE_NUL_SOLDE_ECR", this.boxCompteSolde.isSelected());
 
try {
this.rowPrefCompteVals.update();
137,6 → 167,11
value = ComptePCESQLElement.getId(compte);
this.selCompteResultatPerte.setValue(value);
 
// AN
this.selJournal.setValue(JournalSQLElement.OD);
 
this.boxCompteSolde.setSelected(true);
 
} catch (Exception e) {
e.printStackTrace();
}
190,6 → 225,22
}
this.selCompteResultatPerte.setValue(value);
 
// Journal
SQLRowAccessor rowJ = this.rowPrefCompteVals.getForeign("ID_JOURNAL_AN");
if (rowJ == null || rowJ.isUndefined()) {
value = JournalSQLElement.OD;
} else {
value = rowJ.getID();
}
this.selJournal.setValue(value);
 
// Journal
boolean b = true;
if (this.rowPrefCompteVals.getObject("CREATE_NUL_SOLDE_ECR") != null) {
b = this.rowPrefCompteVals.getBoolean("CREATE_NUL_SOLDE_ECR");
}
this.boxCompteSolde.setSelected(b);
 
} catch (Exception e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalAction.java
New file
0,0 → 1,33
/*
* 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.action.CreateFrameAbstractAction;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.sql.Configuration;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class SaisieJournalAction extends CreateFrameAbstractAction {
 
public SaisieJournalAction() {
super();
this.putValue(Action.NAME, "Saisie au journal");
}
 
public JFrame createFrame() {
return new PanelFrame(new SaisieJournalPanel(Configuration.getInstance().getDirectory().getElement("ECRITURE")), "Saisie au journal");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/PointagePanel.java
22,11 → 22,15
import org.openconcerto.erp.model.ISQLCompteSelector;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
95,7 → 99,7
public PointagePanel() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
this.modeSelect = allEcriture;
 
// Selection du compte à pointer
106,8 → 110,14
this.add(labelPointageCompte, c);
 
this.selCompte = new ISQLCompteSelector();
 
this.selCompte.init();
SQLElement eltCpt = directory.getElement("COMPTE_PCE");
final ComboSQLRequest createComboRequest = eltCpt.createComboRequest();
String function = "REGEXP";
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) {
function = "~";
}
createComboRequest.setWhere(new Where(eltCpt.getTable().getField("NUMERO"), function, "^5.*$"));
this.selCompte.init(eltCpt, createComboRequest);
new SwingWorker<Integer, Object>() {
 
@Override
257,7 → 267,7
this.add(sepEcriture, c);
 
// Liste des ecritures
final EcritureSQLElement ecritureElem = Configuration.getInstance().getDirectory().getElement(EcritureSQLElement.class);
final EcritureSQLElement ecritureElem = directory.getElement(EcritureSQLElement.class);
this.ecriturePanel = new ListPanelEcritures(ecritureElem, new IListe(ecritureElem.createPointageTableSource()));
this.ecriturePanel.setShowReadOnlyFrameOnDoubleClick(false);
c.gridx = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalPanel.java
New file
0,0 → 1,281
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.ui;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.ISpinnerIntegerModel;
import org.openconcerto.ui.coreanimation.Animator;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
import com.ibm.icu.util.Calendar;
 
public class SaisieJournalPanel extends JPanel {
final SQLRequestComboBox boxMois = new SQLRequestComboBox();
final SQLRequestComboBox boxJournal = new SQLRequestComboBox();
final Calendar cal = Calendar.getInstance();
final JSpinner spin = new JSpinner(new ISpinnerIntegerModel(2000, cal.get(Calendar.YEAR) + 3, cal.get(Calendar.YEAR)));
 
public SaisieJournalPanel(SQLElement ecrElt) {
super(new GridBagLayout());
 
boxMois.uiInit(ecrElt.getDirectory().getElement("MOIS").createComboRequest());
 
boxJournal.uiInit(ecrElt.getDirectory().getElement("JOURNAL").createComboRequest());
 
animate();
 
final IListe listeEcr = new IListe(ecrElt.createTableSource());
listeEcr.getSource().getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.setWhere(Where.FALSE);
return input;
}
});
GridBagConstraints cListe = new DefaultGridBagConstraints();
cListe.fill = GridBagConstraints.BOTH;
cListe.gridwidth = 1;
cListe.weightx = 1;
cListe.weighty = 1;
 
JPanel panelEcr = new JPanel(new GridBagLayout());
panelEcr.add(listeEcr, cListe);
cListe.weighty = 0;
cListe.weightx = 0;
cListe.gridy = 4;
cListe.gridx = 0;
cListe.fill = GridBagConstraints.NONE;
cListe.anchor = GridBagConstraints.EAST;
 
List<SQLField> lFields = new ArrayList<SQLField>();
lFields.add(ecrElt.getTable().getField("DEBIT"));
lFields.add(ecrElt.getTable().getField("CREDIT"));
 
IListTotalPanel comp2 = new IListTotalPanel(listeEcr, lFields);
panelEcr.add(comp2, cListe);
 
final PropertyChangeListener l = new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
final int wantedID = boxMois.getWantedID();
final int journalID = boxJournal.getSelectedId();
final Integer year = (Integer) spin.getValue();
setFilter(listeEcr, wantedID, journalID, year);
animate();
}
 
};
boxMois.addModelListener("wantedID", l);
boxJournal.addModelListener("wantedID", l);
spin.getModel().addChangeListener(new ChangeListener() {
 
@Override
public void stateChanged(ChangeEvent e) {
l.propertyChange(null);
 
}
});
 
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 6, 4));
headerPanel.add(new JLabel("Journal"));
headerPanel.add(boxJournal);
headerPanel.add(new JLabel("Mois"));
headerPanel.add(boxMois);
headerPanel.add(new JLabel("Année"));
headerPanel.add(spin);
 
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
this.add(headerPanel, c);
 
JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.gridy++;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
split.setTopComponent(panelEcr);
final SQLRowValues defaultRowVals = new SQLRowValues(ecrElt.getTable().getTable("SAISIE_KM_ELEMENT"));
defaultRowVals.put("DEBIT", 0L);
defaultRowVals.put("CREDIT", 0L);
 
final JCheckBox boxAutoInsert = new JCheckBox("Insertion automatique");
 
final SaisieJournalItemTable table = new SaisieJournalItemTable(defaultRowVals, boxAutoInsert);
table.setPanel(this);
 
split.setBottomComponent(table);
 
this.add(split, c);
 
c.weightx = 0;
c.weighty = 0;
 
JPanel footerPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 4));
 
//
 
boxAutoInsert.setSelected(true);
footerPanel.add(boxAutoInsert);
 
final JButton buttonAdd = new JButton("Ajouter");
buttonAdd.setEnabled(false);
buttonAdd.setVisible(false);
boxAutoInsert.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
buttonAdd.setVisible(!boxAutoInsert.isSelected());
buttonAdd.setEnabled(!boxAutoInsert.isSelected() && table.isSaisieValid());
}
});
footerPanel.add(buttonAdd);
 
final JButton buttonClose = new JButton("Fermer");
footerPanel.add(buttonClose);
 
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(footerPanel, c);
buttonAdd.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
table.createSaisie(defaultRowVals);
}
});
buttonClose.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
((Window) SwingUtilities.getRoot(buttonClose)).dispose();
}
});
table.getModel().addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
buttonAdd.setEnabled(!boxAutoInsert.isSelected() && table.isSaisieValid());
 
}
});
}
 
public SQLRequestComboBox getBoxMois() {
return boxMois;
}
 
public SQLRequestComboBox getBoxJournal() {
return boxJournal;
}
 
private void animate() {
Animator.getInstance().animate(boxJournal, boxJournal.isEmpty());
Animator.getInstance().animate(boxMois, boxMois.isEmpty());
}
 
public int getSelectedYear() {
return (Integer) this.spin.getValue();
}
 
public int getSelectedMonth() {
return this.boxMois.getSelectedId() - 2;
}
 
public int getSelectedJournal() {
return this.boxJournal.getSelectedId();
}
 
public void setFilter(final IListe listeEcr, final int wantedID, final int journalID, final Integer year) {
if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID && journalID > 1) {
listeEcr.getSource().getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, wantedID - 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
Date d1 = c.getTime();
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR, 23);
c.set(Calendar.MINUTE, 59);
Date d2 = c.getTime();
input.setWhere(new Where(input.getTable("ECRITURE").getField("ID_JOURNAL"), "=", journalID).and(new Where(input.getTable("ECRITURE").getField("DATE"), d1, d2)));
return input;
}
});
} else {
listeEcr.getSource().getReq().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.setWhere(Where.FALSE);
return input;
}
});
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImportEcriturePanel.java
15,16 → 15,16
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.generationEcritures.GenerationEcritures;
import org.openconcerto.erp.importer.ArrayTableModel;
import org.openconcerto.erp.importer.DataImporter;
import org.openconcerto.openoffice.ContentTypeVersioned;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.ReloadPanel;
46,6 → 46,7
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JButton;
57,20 → 58,12
 
public class ImportEcriturePanel extends JPanel {
 
private final Map<String, Integer> mapJournal;
private final SQLTable tableEcr;
private final Map<String, Integer> mapJournal = new HashMap<>();
private final Map<String, Integer> mapCompte = new HashMap<>();
 
public ImportEcriturePanel() {
super(new GridBagLayout());
 
this.tableEcr = Configuration.getInstance().getDirectory().getElement("ECRITURE").getTable();
this.mapJournal = new HashMap<String, Integer>();
this.mapJournal.put("HA", JournalSQLElement.ACHATS);
this.mapJournal.put("VE", JournalSQLElement.VENTES);
this.mapJournal.put("BA", JournalSQLElement.BANQUES);
this.mapJournal.put("CA", JournalSQLElement.CAISSES);
this.mapJournal.put("OD", JournalSQLElement.OD);
 
JLabel label = new JLabel("Import depuis un fichier CSV, XLS ou ODT.");
JLabel label2 = new JLabel("Le fichier doit contenir les colonnes :");
JLabel label3 = new JLabel(" - Date dd/MM/yyyy (dd/MM/yy pour le CSV)");
128,32 → 121,56
rlPanel.setMode(ReloadPanel.MODE_ROTATE);
if (fd.getFile() != null) {
 
final DBRoot rootSociete = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getRootSociete();
new Thread() {
@Override
public void run() {
final File fileToImport = new File(fd.getDirectory(), fd.getFile());
try {
final ArrayTableModel model = loadData(fileToImport);
try {
final DBRoot rootSociete = ((ComptaPropsConfiguration) ComptaPropsConfiguration.getInstance()).getRootSociete();
SQLUtils.executeAtomic(rootSociete.getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(final SQLDataSource ds) throws SQLException, IOException {
 
try {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
importData(new File(fd.getDirectory(), fd.getFile()), "Import " + format.format(new Date()), frame);
SQLSelect sel = new SQLSelect();
sel.addSelectStar(rootSociete.getTable("JOURNAL"));
List<SQLRow> rowsJrnl = SQLRowListRSH.execute(sel);
for (SQLRow sqlRow : rowsJrnl) {
mapJournal.put(sqlRow.getString("CODE"), sqlRow.getID());
}
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
final String mouvementName = "Import " + format.format(new Date());
// Vérification des données
boolean ok = importTableModel(model, mouvementName, frame, true);
if (ok) {
// Importation des données
importTableModel(model, mouvementName, frame, false);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "Importation des écritures terminée");
}
});
}
} catch (Exception exn) {
if (exn.getMessage().toLowerCase().contains("file format")) {
JOptionPane.showMessageDialog(ImportEcriturePanel.this, "Mauvais format de fichier");
} else {
ExceptionHandler.handle("Erreur pendant l'importation", exn);
}
}
return null;
}
});
} catch (IOException exn) {
ExceptionHandler.handle(frame, "Erreur lors de la lecture du fichier", exn);
} catch (SQLException exn) {
} catch (Exception exn) {
ExceptionHandler.handle(frame, "Erreur lors de l'insertion dans la base", exn);
}
 
} catch (Exception e) {
if (e.getMessage().toLowerCase().contains("file format")) {
JOptionPane.showMessageDialog(ImportEcriturePanel.this, "Format de fichier non pris en charge");
} else {
ExceptionHandler.handle(frame, "Erreur lors de la lecture du fichier " + fileToImport.getAbsolutePath(), e);
}
}
 
frame.dispose();
}
}.start();
162,106 → 179,145
});
}
 
public void importData(File f, String mvtName, final Frame owner) throws Exception {
DataImporter importer = new DataImporter(this.tableEcr);
public ArrayTableModel loadData(File f) throws IOException {
final DataImporter importer = new DataImporter();
importer.setSkipFirstLine(false);
DateFormat dF = new SimpleDateFormat("dd/MM/yyyy");
ArrayTableModel m = importer.createModelFrom(f);
return importer.createModelFrom(f);
}
 
GenerationEcritures gen = new GenerationEcritures();
int idMvt = gen.getNewMouvement("", 1, 1, mvtName);
 
long solde = 0;
for (int i = 0; i < m.getRowCount(); i++) {
 
final Object valueAt = m.getValueAt(i, 0);
 
if (valueAt == null) {
public boolean importTableModel(ArrayTableModel m, String mvtName, final Frame owner, boolean dryRun) throws Exception {
final DateFormat dF = new SimpleDateFormat("dd/MM/yyyy");
final GenerationEcritures gen = new GenerationEcritures();
int idMvt = -1;
if (!dryRun) {
idMvt = gen.getNewMouvement("", 1, 1, mvtName);
}
long soldeGlobal = 0;
String dateOrigin = null;
final int rowCount = m.getRowCount();
for (int i = 0; i < rowCount; i++) {
int column = 0;
try {
// Column 0
final Object firstValue = m.getValueAt(i, column);
if (firstValue == null) {
break;
}
final Date dateValue;
if (valueAt.getClass().isAssignableFrom(Date.class)) {
dateValue = (Date) valueAt;
if (firstValue.getClass().isAssignableFrom(Date.class)) {
dateValue = (Date) firstValue;
} else if (firstValue.toString().trim().isEmpty()) {
break;
} else {
if (valueAt.toString().trim().length() == 0) {
break;
dateValue = dF.parse(firstValue.toString());
}
dateValue = dF.parse(valueAt.toString());
final String dateStringValue = dF.format(dateValue);
if (dateOrigin == null) {
dateOrigin = dateStringValue;
}
// Mouvement
gen.mEcritures.put("ID_MOUVEMENT", idMvt);
// Date
gen.putValue("DATE", dateValue);
column++;
 
// Cpt
final String trim = m.getValueAt(i, 2).toString().trim();
String numCompt = trim;
if (trim.contains(".")) {
numCompt = trim.substring(0, trim.indexOf('.'));
if (!dateOrigin.equals(dateStringValue)) {
dateOrigin = dateStringValue;
if (!dryRun) {
idMvt = gen.getNewMouvement("", 1, 1, mvtName);
} else if (soldeGlobal != 0) {
final double soldeMvt = soldeGlobal / 100.0;
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
JOptionPane.showMessageDialog(null,
"Le mouvement du " + dateStringValue + " ne respecte pas la partie double (Solde du mouvement : " + soldeMvt + ")!\nImport annulé!");
}
int idCpt = ComptePCESQLElement.getId(numCompt);
gen.mEcritures.put("ID_COMPTE_PCE", idCpt);
});
return false;
}
}
 
// Montant
final String stringValueD = m.getValueAt(i, 5).toString();
long montantD = GestionDevise.parseLongCurrency(stringValueD);
final String stringValueC = m.getValueAt(i, 6).toString();
long montantC = GestionDevise.parseLongCurrency(stringValueC);
gen.mEcritures.put("CREDIT", montantC);
gen.mEcritures.put("DEBIT", montantD);
solde += montantD;
solde -= montantC;
 
System.err.println("(" + stringValueD + " : " + stringValueC + ") ---- (" + montantD + " : " + montantC + ")");
// Journal
 
final String valueJrnl = m.getValueAt(i, 1).toString();
if (mapJournal.get(valueJrnl) == null) {
 
try {
System.err.println("LOCKED");
 
// Column 1
final String valueJrnl = m.getValueAt(i, column).toString();
if (!dryRun && mapJournal.get(valueJrnl) == null) {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// try {
JDialog diag = new JDialog(owner);
final JDialog diag = new JDialog(owner);
diag.setModal(true);
diag.setContentPane(new SelectionJournalImportPanel(valueJrnl, mapJournal, null));
diag.setTitle("Import écritures");
diag.setTitle("Import d'écritures");
diag.setLocationRelativeTo(null);
diag.pack();
diag.setVisible(true);
}
});
}
gen.putValue("ID_JOURNAL", this.mapJournal.get(valueJrnl));
column++;
 
System.err.println("PASSED");
} catch (InterruptedException e1) {
e1.printStackTrace();
// Compte
// Column 2
final String trim = m.getValueAt(i, column).toString().trim();
String numCompt = trim;
if (trim.contains(".")) {
numCompt = trim.substring(0, trim.indexOf('.'));
}
numCompt = numCompt.trim();
if (!dryRun) {
int idCpt = getOrCreateCompte(numCompt);
gen.putValue("ID_COMPTE_PCE", idCpt);
}
column++;
 
// Nom de la pièce
// Column 3
String stringPiece = m.getValueAt(i, column).toString();
if (stringPiece != null && stringPiece.length() > 0 && stringPiece.contains(".")) {
stringPiece = stringPiece.substring(0, stringPiece.indexOf('.'));
}
column++;
// Column 4
gen.putValue("NOM", m.getValueAt(i, column).toString() + " " + stringPiece);
column++;
 
gen.mEcritures.put("ID_JOURNAL", this.mapJournal.get(valueJrnl));
// Montants
// Column 5
final String stringValueD = m.getValueAt(i, column).toString();
long montantD = GestionDevise.parseLongCurrency(stringValueD);
column++;
// Column 6
final String stringValueC = m.getValueAt(i, column).toString();
long montantC = GestionDevise.parseLongCurrency(stringValueC);
gen.putValue("CREDIT", montantC);
gen.putValue("DEBIT", montantD);
soldeGlobal += montantD;
soldeGlobal -= montantC;
 
// Date
gen.mEcritures.put("DATE", dateValue);
// Mouvement
gen.putValue("ID_MOUVEMENT", idMvt);
 
String stringPiece = m.getValueAt(i, 3).toString();
if (stringPiece != null && stringPiece.length() > 0 && stringPiece.contains(".")) {
stringPiece = stringPiece.substring(0, stringPiece.indexOf('.'));
gen.putValue("NOM", m.getValueAt(i, 4).toString() + " " + stringPiece);
} catch (Exception e) {
throw new IllegalStateException("Donnée invalide sur la ligne " + (i + 1) + " , colonne " + (column + 1), e);
}
gen.mEcritures.put("NOM", m.getValueAt(i, 4).toString() + " " + stringPiece);
 
if (!dryRun) {
gen.ajoutEcriture();
}
if (solde != 0) {
throw new IllegalArgumentException("La partie double n'est respectée (solde = " + solde + "). Import annulé!");
}
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
JOptionPane.showMessageDialog(owner, "Importation des écritures terminée");
if (soldeGlobal != 0) {
throw new IllegalArgumentException("La partie double n'est respectée (solde = " + soldeGlobal + "). Import annulé!");
}
});
return true;
}
 
private int getOrCreateCompte(String numeroCompte) {
if (mapCompte.containsKey(numeroCompte)) {
return mapCompte.get(numeroCompte);
}
int id = ComptePCESQLElement.getId(numeroCompte);
mapCompte.put(numeroCompte, id);
return id;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteGestCommPreferencePanel.java
48,7 → 48,7
private SQLRowValues rowPrefCompteVals = new SQLRowValues(tablePrefCompte);
private JCheckBox checkHideCompteFacture = new JCheckBox("Ne pas afficher les comptes dans les factures.");
private JCheckBox checkHideCompteClient = new JCheckBox("Ne pas afficher les comptes dans les clients.");
private JCheckBox checkHideAnalytique = new JCheckBox("Ne pas afficher l'analityque dans les saisies au kilomètre.");
private JCheckBox checkHideAnalytique = new JCheckBox("Ne pas afficher l'analytique dans les saisies au kilomètre.");
 
public CompteGestCommPreferencePanel() {
super();
147,6 → 147,7
 
// Avance Compte client
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Compte Avance Client"), c);
c.weightx = 1;
158,6 → 159,7
 
// Valeur à l'encaissement
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Compte dépôt chèque"), c);
c.weightx = 1;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalItemTable.java
New file
0,0 → 1,684
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.ui;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.DeviseCellEditor;
import org.openconcerto.erp.core.common.ui.MultiLineTableCellEditor;
import org.openconcerto.erp.core.common.ui.RowValuesMultiLineEditTable;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.RowValuesTable;
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.RangedIntegerTableCellEditor;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;
 
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class SaisieJournalItemTable extends JPanel implements MouseListener {
 
private final RowValuesTable table;
private final SQLTableElement debit;
private final SQLTableElement credit;
private JLabel labelTotalDebit;
private JLabel labelTotalCredit;
private JLabel labelTotalSolde;
private final SQLTableElement tableElementNumeroCompte;
private final CompteRowValuesRenderer numeroCompteRenderer = new CompteRowValuesRenderer();
private final DeviseKmRowValuesRenderer deviseRenderer = new DeviseKmRowValuesRenderer();
final RangedIntegerTableCellEditor rangedIntegerTableCellEditor = new RangedIntegerTableCellEditor(1, 31);
private final RowValuesTableControlPanel controlPanel;
 
private SaisieJournalPanel panel;
private final JCheckBox boxAutoInsert;
private boolean hideAnalytique = false;
 
public SaisieJournalItemTable(final SQLRowValues defaultRowVals, JCheckBox boxAutoInsert) {
setLayout(new GridBagLayout());
this.boxAutoInsert = boxAutoInsert;
final GridBagConstraints c = new DefaultGridBagConstraints();
c.weightx = 1;
 
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 SQLTable tableElement = elt.getTable();
final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, rangedIntegerTableCellEditor) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
 
return super.isCellEditable(vals, rowIndex, columnIndex) && rowIndex == 0;
}
 
@Override
protected Object getDefaultNullValue() {
return 1;
}
 
};
 
list.add(tableElementJour);
 
this.tableElementNumeroCompte = new SQLTableElement(tableElement.getField("NUMERO"));
list.add(this.tableElementNumeroCompte);
 
final SQLTableElement tableElementNomCompte = new SQLTableElement(tableElement.getField("NOM"));
list.add(tableElementNomCompte);
 
final SQLTableElement tableElementNomPiece = new SQLTableElement(tableElement.getField("NOM_PIECE"));
list.add(tableElementNomPiece);
 
final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE"));
list.add(tableElementNomEcriture);
 
//
DeviseCellEditor deviseDebitEditor = new DeviseCellEditor();
DeviseCellEditor deviseCreditEditor = new DeviseCellEditor();
this.debit = new SQLTableElement(tableElement.getField("DEBIT"), Long.class, deviseDebitEditor);
list.add(this.debit);
this.credit = new SQLTableElement(tableElement.getField("CREDIT"), Long.class, deviseCreditEditor);
list.add(this.credit);
this.hideAnalytique = DefaultNXProps.getInstance().getBooleanValue("HideAnalytique");
if (!this.hideAnalytique) {
final AnalytiqueItemTable analytiqueAssocTable = new AnalytiqueItemTable(true, new AbstractAction() {
 
@Override
public void actionPerformed(ActionEvent e) {
montantValid(defaultRowVals, true);
}
});
final MultiLineTableCellEditor multiLineTableCellEditor = new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable);
 
SQLTableElement eltPourcentAnalytique = new SQLTableElement(tableElement.getField("ANALYTIQUE"), String.class, multiLineTableCellEditor) {
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"));
};
};
list.add(eltPourcentAnalytique);
}
 
final RowValuesTableModel model = new RowValuesTableModel(elt, list, tableElement.getField("NUMERO"), false, defaultRowVals) {
@Override
public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
super.setValueAt(aValue, rowIndex, columnIndex);
 
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) {
setValueAt(Long.valueOf(0), rowIndex, creditIndex);
} else {
if (creditIndex == columnIndex && ((Long) aValue).longValue() != 0 && ((Long) getValueAt(rowIndex, debitIndex)).longValue() != 0) {
setValueAt(Long.valueOf(0), rowIndex, debitIndex);
}
}
}
};
 
this.table = new RowValuesTable(model, null);
ToolTipManager.sharedInstance().unregisterComponent(this.table);
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
 
tableElementNomEcriture.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
 
@Override
public void editingStopped(ChangeEvent e) {
e.getSource();
int row = table.getSelectedRow();
int col = 4;
if (table.getValueAt(row, col) != null) {
defaultRowVals.put("NOM_ECRITURE", table.getValueAt(row, col));
}
// defaultRowVals.put
}
 
@Override
public void editingCanceled(ChangeEvent e) {
// TODO Auto-generated method stub
 
}
});
tableElementNomPiece.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
 
@Override
public void editingStopped(ChangeEvent e) {
e.getSource();
int row = table.getSelectedRow();
int col = 3;
if (table.getValueAt(row, col) != null) {
defaultRowVals.put("NOM_PIECE", table.getValueAt(row, col));
}
// defaultRowVals.put
}
 
@Override
public void editingCanceled(ChangeEvent e) {
// TODO Auto-generated method stub
 
}
});
 
tableElementJour.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
 
@Override
public void editingStopped(ChangeEvent e) {
final Object valueAt = 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");
}
}
}
 
@Override
public void editingCanceled(ChangeEvent e) {
// TODO Auto-generated method stub
 
}
});
;
 
final KeyListener keyListenerContrepartie = new KeyListener() {
 
@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);
}
}
};
deviseCreditEditor.addKeyListener(keyListenerContrepartie);
deviseDebitEditor.addKeyListener(keyListenerContrepartie);
 
// Autocompletion
final AutoCompletionManager m = new AutoCompletionManager(this.tableElementNumeroCompte,
((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NUMERO"), this.table, this.table.getRowValuesTableModel(),
ITextWithCompletion.MODE_STARTWITH, true, false, new ValidStateChecker() {
 
ComptePCESQLElement elt = Configuration.getInstance().getDirectory().getElement(ComptePCESQLElement.class);
 
@Override
public ValidState getValidState(Object o) {
if (o != null) {
return elt.getCompteNumeroValidState(o.toString());
}
return super.getValidState(o);
}
});
m.fill("NOM", "NOM");
m.setFillWithField("NUMERO");
final Where w = new Where(elt.getTable().getTable("COMPTE_PCE").getField("OBSOLETE"), "=", Boolean.FALSE);
m.setWhere(w);
 
// FIXME erreur fill numero
final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNomCompte, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NOM"),
this.table, this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true);
m2.fill("NUMERO", "NUMERO");
m2.setFillWithField("NOM");
m2.setWhere(w);
 
TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table);
 
this.controlPanel = new RowValuesTableControlPanel(this.table);
controlPanel.setButtonAjouterEnabled(false);
this.add(controlPanel, c);
 
c.gridy++;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
this.add(new JScrollPane(this.table), c);
 
this.tableElementNumeroCompte.setRenderer(this.numeroCompteRenderer);
this.debit.setRenderer(this.deviseRenderer);
this.credit.setRenderer(this.deviseRenderer);
 
this.table.addMouseListener(this);
this.table.getModel().addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
// Sélectionne automatiquement la ligne ajoutée
if (e.getType() == TableModelEvent.INSERT) {
if (table.getRowCount() == 1) {
editCellAt(e.getFirstRow(), 0);
} else {
editCellAt(e.getFirstRow(), 1);
}
}
refreshTotal();
}
});
 
// Initialisation du panel des Totaux
this.labelTotalCredit = new JLabel("0.00", SwingConstants.RIGHT);
this.labelTotalDebit = new JLabel("0.00", SwingConstants.RIGHT);
this.labelTotalSolde = new JLabel("0.00", SwingConstants.RIGHT);
JPanel panelTotal = new JPanel();
panelTotal.setLayout(new GridBagLayout());
panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
final GridBagConstraints cc = new DefaultGridBagConstraints();
cc.anchor = GridBagConstraints.EAST;
 
// Total Debit
cc.fill = GridBagConstraints.NONE;
panelTotal.add(new JLabel("Débit"), cc);
cc.fill = GridBagConstraints.HORIZONTAL;
cc.gridx++;
cc.weightx = 1;
 
panelTotal.add(this.labelTotalDebit, cc);
 
// Total Credit
cc.gridy++;
cc.gridx = 0;
cc.weightx = 0;
cc.fill = GridBagConstraints.NONE;
panelTotal.add(new JLabel("Crédit"), cc);
cc.weightx = 1;
cc.gridx++;
cc.fill = GridBagConstraints.HORIZONTAL;
panelTotal.add(this.labelTotalCredit, cc);
 
// Total Credit
cc.gridy++;
cc.gridx = 0;
cc.weightx = 0;
cc.fill = GridBagConstraints.NONE;
panelTotal.add(new JLabel("Solde"), cc);
cc.weightx = 1;
cc.gridx++;
cc.fill = GridBagConstraints.HORIZONTAL;
panelTotal.add(this.labelTotalSolde, cc);
 
c.gridy++;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
c.weighty = 0;
this.add(panelTotal, c);
}
 
public void setPanel(final SaisieJournalPanel panel) {
this.panel = panel;
 
final PropertyChangeListener lActiveAddButton = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty());
}
};
panel.getBoxJournal().addModelListener("wantedID", lActiveAddButton);
panel.getBoxMois().addModelListener("wantedID", lActiveAddButton);
 
final PropertyChangeListener l = new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!SaisieJournalItemTable.this.panel.boxMois.isEmpty()) {
final SQLRow selectedRow = SaisieJournalItemTable.this.panel.boxMois.getSelectedRow();
if (selectedRow != null && !selectedRow.isUndefined()) {
Calendar c = Calendar.getInstance();
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));
}
}
}
 
};
panel.boxMois.addModelListener("wantedID", l);
 
}
 
public void refreshTotal() {
 
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"));
if (c != null) {
totalC += c;
}
if (d != null) {
totalD += d;
}
 
}
this.labelTotalCredit.setText(GestionDevise.currencyToString(totalC));
this.labelTotalDebit.setText(GestionDevise.currencyToString(totalD));
this.labelTotalSolde.setText(GestionDevise.currencyToString(totalD - totalC));
 
}
 
public boolean isSaisieValid() {
// Check if partie double
 
long totalD = 0L;
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"));
if (c != null) {
totalC += c;
}
if (d != null) {
totalD += d;
}
if (lib == null) {
lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM"));
}
String cptNUmber = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NUMERO"));
cptOK = cptOK && cptNUmber != null && ComptePCESQLElement.isExist(cptNUmber);
}
return totalD + totalC != 0 && totalD == totalC && cptOK;
}
 
private Tuple2<Date, String> getDateAndLabelFromSaisie() {
int day = 1;
String lib = null;
 
for (int i = 0; i < table.getRowCount(); i++) {
day = (Integer) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("JOUR"));
if (lib == null) {
lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM"));
}
}
// Create saisieKM
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, SaisieJournalItemTable.this.panel.getSelectedYear());
c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
c.set(Calendar.DAY_OF_MONTH, day);
return Tuple2.create(c.getTime(), lib);
}
 
public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique) {
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.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) {
JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!");
} else {
createSaisie(defaultRowVals);
}
} else {
if (!fromAnalytique && !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"));
long montant = vals.getLong("DEBIT") - vals.getLong("CREDIT");
for (SQLRowValues sqlRowValues : rowsLinked) {
sqlRowValues.put("MONTANT", sqlRowValues.getBigDecimal("POURCENT").movePointLeft(2).multiply(new BigDecimal(montant), DecimalUtils.HIGH_PRECISION)
.setScale(0, RoundingMode.HALF_UP).longValue());
}
 
editCellAt(selectedRow, table.getRowValuesTableModel().getColumnForField("ANALYTIQUE"));
} else {
 
long l = getContrepartie();
SQLRowValues rowVals = new SQLRowValues(defaultRowVals);
if (l > 0) {
rowVals.put("DEBIT", 0L);
rowVals.put("CREDIT", l);
} else {
rowVals.put("DEBIT", -l);
rowVals.put("CREDIT", 0L);
}
SaisieJournalItemTable.this.table.getRowValuesTableModel().addRow(rowVals);
}
}
 
}
});
 
}
 
public synchronized void createSaisie(final SQLRowValues defaultRowVals) {
 
Tuple2<Date, String> t = getDateAndLabelFromSaisie();
final Date d = t.get0();
final String lib = t.get1();
 
// Create saisieKM
SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
 
rowVAlsKM.put("DATE", d);
rowVAlsKM.put("NOM", lib);
rowVAlsKM.put("ID_JOURNAL", SaisieJournalItemTable.this.panel.getSelectedJournal());
int id;
try {
id = rowVAlsKM.insert().getID();
 
table.updateField("ID_SAISIE_KM", id);
table.clear();
GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id);
gen.genereMouvement();
 
defaultRowVals.put("NOM_PIECE", "");
defaultRowVals.put("NOM_ECRITURE", "");
table.getRowValuesTableModel().addNewRow();
 
} catch (SQLException e) {
e.printStackTrace();
}
 
}
 
public void updateField(final String field, final int id) {
this.table.updateField(field, id);
}
 
public void insertFrom(final String field, final int id) {
this.table.insertFrom(field, id);
}
 
public void insertFrom(final SQLRowAccessor row) {
this.table.insertFrom(row);
}
 
public RowValuesTableModel getModel() {
return this.table.getRowValuesTableModel();
}
 
public SQLTableElement getCreditElement() {
return this.credit;
}
 
public SQLTableElement getDebitElement() {
return this.debit;
}
 
public SQLTableElement getNumeroCompteElement() {
return this.tableElementNumeroCompte;
}
 
public void setCreateAutoActive(final boolean b) {
this.numeroCompteRenderer.setCreateActive(b);
this.table.revalidate();
this.table.repaint();
}
 
public void setRowDeviseValidAt(final boolean b, final int index) {
this.deviseRenderer.setValid(b, index);
 
}
 
public void editCellAt(final int row, final int column) {
assert SwingUtilities.isEventDispatchThread();
this.table.setColumnSelectionInterval(column, column);
this.table.setRowSelectionInterval(row, row);
this.table.editCellAt(row, column);
}
 
private long getContrepartie() {
assert SwingUtilities.isEventDispatchThread();
long totalCred = 0;
long totalDeb = 0;
final RowValuesTableModel model = this.table.getRowValuesTableModel();
final int creditIndex = model.getColumnIndexForElement(getCreditElement());
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);
if (fTc != null) {
totalCred += fTc.longValue();
}
final Long fTd = (Long) model.getValueAt(i, debitIndex);
if (fTd != null) {
totalDeb += fTd.longValue();
}
}
}
return totalDeb - totalCred;
}
 
private long getSoldeRow(final int index) {
assert SwingUtilities.isEventDispatchThread();
if (index >= 0 && index < this.table.getRowCount()) {
final SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(index);
return rowVals.getLong("DEBIT") - rowVals.getLong("CREDIT");
} else {
return 0;
}
}
 
public void fillEmptyEntryLabel(String previousText, String text) {
assert SwingUtilities.isEventDispatchThread();
if (text == null)
return;
RowValuesTableModel model = table.getRowValuesTableModel();
int size = model.getRowCount();
for (int i = 0; i < size; i++) {
SQLRowValues r = model.getRowValuesAt(i);
if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").trim().equals(previousText)) {
r.put("NOM_ECRITURE", text);
}
}
model.fireTableDataChanged();
}
 
public void mousePressed(final MouseEvent e) {
final int rowSel = this.table.getSelectedRow();
if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) {
final JPopupMenu menuDroit = new JPopupMenu();
 
menuDroit.add(new AbstractAction("Contrepartie") {
public void actionPerformed(final ActionEvent ev) {
 
long l = getContrepartie();
if (SaisieJournalItemTable.this.table.getRowValuesTableModel().isRowValid(rowSel)) {
l += getSoldeRow(rowSel);
}
 
if (l > 0) {
SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "DEBIT");
SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(l, rowSel, "CREDIT");
} else {
SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "CREDIT");
SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(-l, rowSel, "DEBIT");
}
}
});
menuDroit.pack();
menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
menuDroit.setVisible(true);
}
}
 
public void mouseReleased(final MouseEvent e) {
}
 
public void mouseClicked(final MouseEvent e) {
}
 
public void mouseEntered(final MouseEvent e) {
}
 
public void mouseExited(final MouseEvent e) {
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/AnalytiqueItemTable.java
43,10 → 43,13
import java.util.List;
import java.util.Vector;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
 
public class AnalytiqueItemTable extends JPanel {
 
57,11 → 60,17
private static final SQLElement elt = Configuration.getInstance().getDirectory().getElement("ASSOCIATION_ANALYTIQUE");
private final SQLRowValues rowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(elt.getTable()));
 
private long totalArepartir;
 
public SQLRowValues getDefaultRowValues() {
return this.rowVals;
}
 
public AnalytiqueItemTable(boolean multilineEditor) {
this(multilineEditor, null);
}
 
public AnalytiqueItemTable(boolean multilineEditor, final AbstractAction actionOnValidate) {
setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
c.weightx = 1;
76,7 → 85,12
tableElementPourcent.setRenderer(new PercentTableCellRenderer());
list.add(tableElementPourcent);
 
final SQLTableElement tableElementMontant = new SQLTableElement(tableElement.getField("MONTANT"), Long.class, this.deviseCellEditor);
final SQLTableElement tableElementMontant = new SQLTableElement(tableElement.getField("MONTANT"), Long.class, this.deviseCellEditor) {
@Override
protected Object getDefaultNullValue() {
return 0L;
}
};
list.add(tableElementMontant);
 
rowVals.put("POURCENT", BigDecimal.ONE.movePointRight(2));
93,8 → 107,10
rowEcr = row;
getDefaultRowValues().put("POURCENT", BigDecimal.TEN.movePointRight(1));
getDefaultRowValues().put("MONTANT", rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT"));
totalArepartir = rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT");
super.insertFrom(row);
}
 
};
 
ToolTipManager.sharedInstance().unregisterComponent(this.table);
126,10 → 142,27
c.fill = GridBagConstraints.NONE;
c.gridwidth = GridBagConstraints.REMAINDER;
final JPanel panelButton = new JPanel();
buttonValider.setEnabled(false);
panelButton.add(buttonValider);
panelButton.add(buttonFermer);
this.add(panelButton, c);
model.addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
long totalReparti = 0;
if (totalArepartir != 0) {
for (int i = 0; i < model.getRowCount(); i++) {
totalReparti += model.getRowValuesAt(i).getLong("MONTANT");
}
 
getDefaultRowValues().put("POURCENT", new BigDecimal(totalReparti).divide(new BigDecimal(totalArepartir), DecimalUtils.HIGH_PRECISION).setScale(6, RoundingMode.HALF_UP));
getDefaultRowValues().put("MONTANT", totalArepartir - totalReparti);
}
buttonValider.setEnabled(totalReparti == totalArepartir);
 
}
});
final RowValuesMultiLineEditTable multiTable = (RowValuesMultiLineEditTable) this.table;
buttonValider.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
136,7 → 169,10
multiTable.updateField(multiTable.getForeignField(), multiTable.getRowValuesRoot());
// buttonValider.setEnabled(false);
multiTable.closeTable();
if (actionOnValidate != null) {
actionOnValidate.actionPerformed(null);
}
}
});
buttonFermer.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
172,8 → 208,8
BigDecimal pourcent = BigDecimal.ZERO;
 
if (total != 0) {
pourcent = new BigDecimal(montant).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).abs().movePointRight(2)
.setScale(tableElementPourcent.getDecimalDigits(), RoundingMode.HALF_UP);
pourcent = new BigDecimal(montant).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).abs().movePointRight(2).setScale(tableElementPourcent.getDecimalDigits(),
RoundingMode.HALF_UP);
}
return pourcent;
}
226,6 → 262,7
}
getDefaultRowValues().put("POURCENT", BigDecimal.TEN.movePointRight(1));
getDefaultRowValues().put("MONTANT", rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT"));
this.totalArepartir = rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT");
}
this.table.insertFrom(row);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SelectionJournalImportPanel.java
54,7 → 54,6
button.setEnabled(false);
tableJrnl.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
 
button.setEnabled(true);
}
});
66,14 → 65,7
public void actionPerformed(ActionEvent e) {
int id = model.getIdForRow(tableJrnl.getSelectedRow());
m.put(journalTitle, new Integer(id));
// synchronized (t) {
// System.err.println("Notify");
// t.notify();
// }
//
// sema.release();
((Window) SwingUtilities.getRoot(SelectionJournalImportPanel.this)).dispose();
 
}
});
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CloturePanel.java
323,6 → 323,7
if (myList.size() != 0) {
GenerationMvtVirement gen = new GenerationMvtVirement(1, id_Compte_Bilan_Cloture, 0, 0, "Fermeture du compte ", CloturePanel.this.rowExercice.getDate("DATE_FIN").getTime(),
JournalSQLElement.OD, "Fermeture des comptes");
gen.setFermeture(true);
for (int i = 0; i < myList.size(); i++) {
 
Object[] objTmp = (Object[]) myList.get(i);
357,8 → 358,12
 
// A nouveaux
Object[] compteAnouveau = CloturePanel.this.mRAN.keySet().toArray();
GenerationMvtVirement genAnouveaux = new GenerationMvtVirement(id_Compte_Bilan_Ouverture, 1, 0, 0, "A nouveaux", CloturePanel.this.dateOuv.getValue(), JournalSQLElement.OD,
"A nouveaux");
int journalAN = JournalSQLElement.OD;
if (rowPrefCompte.getObject("ID_JOURNAL_AN") != null && !rowPrefCompte.isForeignEmpty("ID_JOURNAL_AN")) {
journalAN = rowPrefCompte.getForeignID("ID_JOURNAL_AN");
}
GenerationMvtVirement genAnouveaux = new GenerationMvtVirement(id_Compte_Bilan_Ouverture, 1, 0, 0, "A nouveaux", CloturePanel.this.dateOuv.getValue(), journalAN, "A nouveaux");
genAnouveaux.setOuverture(true);
for (int i = 0; i < CloturePanel.this.mRAN.keySet().size(); i++) {
 
long solde = CloturePanel.this.mRAN.get(compteAnouveau[i]).longValue();
366,10 → 371,10
// if (solde != 0) {
if (solde > 0) {
genAnouveaux.setValues(id_Compte_Bilan_Ouverture, Integer.parseInt(compteAnouveau[i].toString()), 0, Math.abs(solde), "A nouveaux", CloturePanel.this.dateOuv.getValue(),
JournalSQLElement.OD, false);
journalAN, false);
} else {
genAnouveaux.setValues(id_Compte_Bilan_Ouverture, Integer.parseInt(compteAnouveau[i].toString()), Math.abs(solde), 0, "A nouveaux", CloturePanel.this.dateOuv.getValue(),
JournalSQLElement.OD, false);
journalAN, false);
}
genAnouveaux.genereMouvement();
// }
472,9 → 477,13
List myList = (List) ob;
 
if (myList != null && myList.size() != 0) {
 
boolean genSoldeNul = true;
if (rowPrefCompte.getObject("CREATE_NUL_SOLDE_ECR") != null) {
genSoldeNul = rowPrefCompte.getBoolean("CREATE_NUL_SOLDE_ECR");
}
GenerationMvtVirement genFerm = new GenerationMvtVirement(1, compteDest, 0, 0, "Fermeture du compte ", this.rowExercice.getDate("DATE_FIN").getTime(), JournalSQLElement.OD,
"Fermeture des comptes");
genFerm.setFermeture(true);
for (int i = 0; i < myList.size(); i++) {
 
Object[] objTmp = (Object[]) myList.get(i);
482,21 → 491,22
 
long solde = cptTmp.getTotalDebit() - cptTmp.getTotalCredit();
 
// if (solde != 0) {
if (genSoldeNul || solde != 0) {
if (compteBilan) {
this.mRAN.put(objTmp[0], Long.valueOf(solde));
}
 
if (solde > 0) {
genFerm.setValues(cptTmp.getId(), compteDest, 0, Math.abs(solde), "Fermeture du compte " + cptTmp.getNumero(), this.rowExercice.getDate("DATE_FIN").getTime(), JournalSQLElement.OD,
false);
genFerm.setValues(cptTmp.getId(), compteDest, 0, Math.abs(solde), "Fermeture du compte " + cptTmp.getNumero(), this.rowExercice.getDate("DATE_FIN").getTime(),
JournalSQLElement.OD, false);
} else {
 
genFerm.setValues(cptTmp.getId(), compteDest, Math.abs(solde), 0, "Fermeture du compte " + cptTmp.getNumero(), this.rowExercice.getDate("DATE_FIN").getTime(), JournalSQLElement.OD,
false);
genFerm.setValues(cptTmp.getId(), compteDest, Math.abs(solde), 0, "Fermeture du compte " + cptTmp.getNumero(), this.rowExercice.getDate("DATE_FIN").getTime(),
JournalSQLElement.OD, false);
}
genFerm.genereMouvement();
}
}
// }
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/component/EncaisserMontantSQLComponent.java
52,6 → 52,7
import java.util.Comparator;
import java.util.List;
 
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
117,6 → 118,10
this.add(this.date, c);
 
this.addSQLObject(comboClient, "ID_CLIENT");
 
final ElementComboBox comboD = new ElementComboBox();
this.addSQLObject(comboD, "ID_DEVIS");
 
// Nom
c.gridy++;
c.gridx = 0;
125,8 → 130,14
this.add(label, c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
this.add(this.nom, c);
c.gridx += 2;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(this.nom, c);
JCheckBox box = new JCheckBox(getLabelFor("ACOMPTE"));
box.setEnabled(false);
this.add(box, c);
addView(box, "ACOMPTE");
 
// Montant
c.gridwidth = 1;
192,7 → 203,7
 
// Selection du mode de reglement
if (getMode() == SQLComponent.Mode.INSERTION) {
if (rowCount >= 1) {
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) {
210,7 → 221,7
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) {
if (idTypeRegl == TypeReglementSQLElement.INDEFINI) {
idTypeRegl = TypeReglementSQLElement.CHEQUE;
}
rowVals.put("ID_TYPE_REGLEMENT", idTypeRegl);
279,6 → 290,9
super.select(r);
if (r != null && r.getID() > 1) {
this.table.insertFrom("ID_ENCAISSER_MONTANT", r.getID());
} else if (r != null && r instanceof SQLRowValues) {
this.table.insertFrom((SQLRowValues) r);
 
}
}
 
312,6 → 326,8
 
// Mise a jour du montant de l'echeance
boolean supplement = false;
 
if (!row.getBoolean("ACOMPTE")) {
// On marque les echeances comme reglees
for (SQLRow sqlRow : l) {
 
329,6 → 345,7
// this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
// getTable().fireTableModified(rowEch.getID());
}
}
// si le montant réglé est supérieur, on crée une facture de complément
if (supplement) {
SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/EncaisserMontantSQLElement.java
17,8 → 17,10
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.payment.component.EncaisserMontantSQLComponent;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.TreesOfSQLRows;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRow;
30,10 → 32,19
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.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;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
43,12 → 54,39
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
 
public class EncaisserMontantSQLElement extends ComptaSQLConfElement {
 
public EncaisserMontantSQLElement() {
super("ENCAISSER_MONTANT", "un encaissement de montant", "encaissements de montant");
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Annuler l'acompte") {
 
public void actionPerformed(ActionEvent e) {
final SQLRow selRow = IListe.get(e).getSelectedRow().asRow();
if (selRow.getBoolean("ACOMPTE")) {
int idDevis = selRow.getForeignID("ID_DEVIS");
try {
archive(selRow.getID());
String up = "UPDATE " + getTable().getTable("DEVIS").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
+ getTable().getSQLName().quote() + " where \"ID_DEVIS\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID_DEVIS\"=" + idDevis;
getTable().getDBSystemRoot().getDataSource().execute(up);
} catch (SQLException e1) {
e1.printStackTrace();
ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
}
}
}
}, false);
actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(actionClient);
}
 
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
58,6 → 96,10
// l.add("ID_MOUVEMENT");
l.add("ID_MODE_REGLEMENT");
l.add("MONTANT");
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
l.add("ACOMPTE");
}
return l;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/ui/EncaisseMontantTable.java
17,6 → 17,7
import org.openconcerto.erp.core.common.ui.DeviseNiceTableCellRenderer;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.view.list.KeyTableCellRenderer;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableModel;
126,6 → 127,10
this.table.insertFrom(field, id);
}
 
public void insertFrom(SQLRowValues rowVals) {
this.table.insertFrom(rowVals);
}
 
public RowValuesTableModel getModel() {
return this.table.getRowValuesTableModel();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/FichePayeSheetXML.java
15,6 → 15,7
 
import org.openconcerto.erp.core.common.element.StyleSQLElement;
import org.openconcerto.erp.generationDoc.AbstractSheetXMLWithDate;
import org.openconcerto.erp.preferences.PayeGlobalPreferencePanel;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
23,6 → 24,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.cc.ITransformer;
 
import java.math.BigDecimal;
39,8 → 41,7
 
public class FichePayeSheetXML extends AbstractSheetXMLWithDate {
 
private static boolean prefBulletinSimpl = true;
public static final String TEMPLATE_ID = prefBulletinSimpl ? "FichePayeSimplifiee" : "FichePaye";
public static final String TEMPLATE_ID = "FichePayeSimplifiee";
public static final String TEMPLATE_PROPERTY_NAME = "LocationFichePaye";
final Map<Integer, String> cotisationSimplifieeLink = new HashMap<>();
 
48,6 → 49,9
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) {
SQLSelect sel = new SQLSelect();
sel.addSelect(row.getTable().getDBRoot().findTable("RUBRIQUE_COTISATION").getField("LIGNE_PAYE_SIMPLIFIEE"));
189,13 → 193,14
if (sqlRowAccessor.getBigDecimal("MONTANT_PAT") != null) {
montantPatLigne = sqlRowAccessor.getBigDecimal("MONTANT_PAT");
}
if (montantPatLigne.add(montantSalLigne).signum() != 0) {
ligneSimplifiee.put("NB_BASE", sqlRowAccessor.getBigDecimal("NB_BASE"));
ligneSimplifiee.put("MONTANT_SAL_DED", montantSalBulletinSimpl.add(montantSalLigne));
ligneSimplifiee.put("MONTANT_PAT", montantPatBulletinSimpl.add(montantPatLigne));
 
}
}
}
}
 
private StyleSQLElement eltStyle = Configuration.getInstance().getDirectory().getElement(StyleSQLElement.class);
 
260,10 → 265,15
 
@Override
public String getName() {
SQLPreferences prefs = new SQLPreferences(elt.getTable().getDBRoot());
boolean prefNomSal = prefs.getBoolean(PayeGlobalPreferencePanel.SALARIE_NOM_FICHIER, Boolean.FALSE);
SQLRow rowSal = row.getForeign("ID_SALARIE");
SQLRow rowMois = row.getForeign("ID_MOIS");
Calendar du = row.getDate("DU");
String suffix = "";
if (prefNomSal) {
suffix = "_" + rowSal.getString("NOM");
}
if (du != null && du.get(Calendar.DAY_OF_MONTH) != 1) {
suffix = "_" + du.get(Calendar.DAY_OF_MONTH);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/report/GroupePayeSimplifiee.java
30,7 → 30,7
Arrays.asList(LignePayeSimplifiee.RETRAITE_SECURITE_PLAF, LignePayeSimplifiee.RETRAITE_SECURITE_NON_PLAF, LignePayeSimplifiee.RETRAITE_COMPLEMENTAIRE_TA,
LignePayeSimplifiee.RETRAITE_COMPLEMENTAIRE_GMP, LignePayeSimplifiee.RETRAITE_COMPLEMENTAIRE_TB, LignePayeSimplifiee.RETRAITE_COMPLEMENTAIRE_TC,
LignePayeSimplifiee.RETRAITE_SUPPLEMENTAIRE)), FAMILLE("famille", false, Arrays.asList(LignePayeSimplifiee.FAMILLE_ALLOCATIONS)), CHOMAGE_NON_CADRE(
"chomage.noncadre", false, Arrays.asList(LignePayeSimplifiee.ASSURANCE_CHOMAGE_CHOMAGE)), CHOMAGE_CADRE("chomage.cadre", false,
"chomage.noncadre", false, Arrays.asList(LignePayeSimplifiee.ASSURANCE_CHOMAGE_CHOMAGE)), CHOMAGE_CADRE("chomage.cadre", true,
Arrays.asList(LignePayeSimplifiee.ASSURANCE_CHOMAGE_CHOMAGE, LignePayeSimplifiee.ASSURANCE_CHOMAGE_APEC)), AUTRES_CONTRIBUTIONS("autres",
false, Arrays.asList(LignePayeSimplifiee.AUTRES_CONTRIBUTIONS)), COTISATIONS_CONVENTION("cotisations.convention", false,
Arrays.asList(LignePayeSimplifiee.COTISATIONS_STATUAIRES)), CSG_NON_IMP("csg.nonimp", false,
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/ui/EditionFichePayePanel.java
23,6 → 23,7
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.preferences.DefaultProps;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.TableSorter;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
33,8 → 34,10
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
128,7 → 131,10
 
// Liste des salariés
c.gridy++;
this.table = new JTable(this.model);
TableSorter s = new TableSorter(this.model);
this.table = new JTable(s);
s.setTableHeader(this.table.getTableHeader());
// this.table = new JTable(this.model);
this.table.addMouseListener(this);
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
160,6 → 166,7
@Override
public void propertyChange(PropertyChangeEvent evt) {
buttonValid.setEnabled(dateDeb.getValue() != null && dateFin.getValue() != null && dateDeb.getValue().before(dateFin.getValue()));
model.setDateLimit(dateDeb.getValue());
}
};
dateDeb.addValueListener(dateListener);
269,6 → 276,46
frameModifySal.setVisible(true);
}
});
 
menuDroit.add(new AbstractAction("Marquer tout \"A créer\"") {
 
public void actionPerformed(ActionEvent e) {
int rows = table.getModel().getRowCount();
for (int i = 0; i < rows; i++) {
table.getModel().setValueAt(Boolean.TRUE, i, 0);
}
model.fireTableDataChanged();
}
});
 
menuDroit.add(new AbstractAction("Désélectionner tout \"A créer\"") {
 
public void actionPerformed(ActionEvent e) {
int rows = table.getModel().getRowCount();
for (int i = 0; i < rows; i++) {
table.getModel().setValueAt(Boolean.FALSE, i, 0);
}
model.fireTableDataChanged();
}
});
 
menuDroit.add(new AbstractAction("Marquer la sélection \"A créer\"") {
 
public void actionPerformed(ActionEvent e) {
int[] selectedRows = table.getSelectedRows();
 
List<Integer> l = new ArrayList<>(selectedRows.length);
for (int i : selectedRows) {
l.add(i);
}
int rows = table.getModel().getRowCount();
for (int i = 0; i < rows; i++) {
table.setValueAt(l.contains(i), i, 0);
}
model.fireTableDataChanged();
}
});
 
menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/FilePanel.java
13,7 → 13,6
package org.openconcerto.erp.core.edm;
 
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.JImage;
23,6 → 22,7
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
31,8 → 31,11
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
41,20 → 44,29
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
 
public class FilePanel extends JPanel {
JImage image = null;
private static final Color HOVER_COLOR = new Color(230, 240, 255);
private static final Color SELECTED_COLOR = new Color(193, 220, 252);
 
public static final int WIDTH = 128;
public static final int HEIGHT = 80;
JLabel label;
public static final int PREFERRED_WIDTH = 128;
public static final int PREFERRED_HEIGHT = 74;
 
public FilePanel(final SQLRowValues rowAttachment, final AttachmentPanel panelSource) {
final String name = rowAttachment.getString("NAME");
private final JLabel label;
private JImage image;
private AttachmentPanel attachmentPanel;
private Attachment attachment;
 
public FilePanel(final Attachment attachment, final AttachmentPanel panelSource) {
this.attachment = attachment;
this.attachmentPanel = panelSource;
final String name = attachment.getName();
this.setOpaque(true);
this.setLayout(new BorderLayout());
try {
String type = rowAttachment.getString("MIMETYPE");
String type = attachment.getMimeType();
if (type == null || type.trim().isEmpty() || type.equals("application/octet-stream")) {
image = new JImage(this.getClass().getResource("data-icon.png"));
} else if (type.equals("application/msword")) {
75,36 → 87,151
image = new JImage(this.getClass().getResource("xls-icon.png"));
} else if (type.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
image = new JImage(this.getClass().getResource("xlsx-icon.png"));
} else if (type.equals(Attachment.MIMETYPE_FOLDER)) {
image = new JImage(this.getClass().getResource("folder-icon.png"));
} else {
image = new JImage(this.getClass().getResource("data-icon.png"));
}
image.setOpaque(true);
 
image.setCenterImage(true);
this.add(image, BorderLayout.CENTER);
} catch (Exception e) {
e.printStackTrace();
ExceptionHandler.handle("image error", e);
}
setBackground(Color.WHITE);
label = new JLabel(name, SwingConstants.CENTER);
label.setOpaque(false);
label.setPreferredSize(new Dimension(label.getPreferredSize().width, new JTextField("a").getPreferredSize().height));
this.add(label, BorderLayout.SOUTH);
 
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
this.setMinimumSize(new Dimension(WIDTH, HEIGHT));
this.setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
this.setMinimumSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
updateBackgroundFromState();
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
final JComponent lab = (JComponent) e.getSource();
final TransferHandler handle = lab.getTransferHandler();
handle.exportAsDrag(lab, e, TransferHandler.MOVE);
}
});
this.addMouseListener(new MouseAdapter() {
 
@Override
public void mouseExited(MouseEvent e) {
setBackground(Color.WHITE);
updateBackgroundFromState();
}
 
@Override
public void mouseEntered(MouseEvent e) {
setBackground(new Color(230, 240, 255));
if (panelSource.isSelected(attachment)) {
setBackground(SELECTED_COLOR);
} else {
setBackground(HOVER_COLOR);
}
}
 
@Override
public void mousePressed(MouseEvent e) {
final boolean ctrlPressed = (e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK;
if (!ctrlPressed) {
panelSource.select(attachment);
updateBackgroundFromState();
} else {
if (!panelSource.isSelected(FilePanel.this.attachment)) {
// Add to selection if selected
panelSource.select(attachment);
} else {
panelSource.deselect(attachment);
}
updateBackgroundFromState();
}
}
 
@Override
public void mouseReleased(MouseEvent e) {
final boolean ctrlPressed = (e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK;
if (!ctrlPressed) {
panelSource.clearSelection();
panelSource.select(attachment);
panelSource.updatePanels();
}
}
});
initMenu(attachment, panelSource, name);
 
this.setTransferHandler(new TransferHandler("id") {
 
@SuppressWarnings("unchecked")
@Override
public boolean canImport(TransferSupport support) {
if (!attachment.isFolder())
return false;
try {
final List<Attachment> attachmentsToImport = (List<Attachment>) support.getTransferable().getTransferData(support.getDataFlavors()[0]);
for (Attachment a : attachmentsToImport) {
if (a.getId() == attachment.getId()) {
return false;
}
}
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return true;
}
 
@Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
try {
@SuppressWarnings("unchecked")
final List<Attachment> attachmentsToImport = (List<Attachment>) support.getTransferable().getTransferData(support.getDataFlavors()[0]);
final AttachmentUtils utils = new AttachmentUtils();
for (Attachment a : attachmentsToImport) {
utils.move(a, attachment);
}
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
panelSource.initUI();
 
}
});
} catch (Exception e) {
e.printStackTrace();
}
 
return true;
}
 
@Override
protected java.awt.datatransfer.Transferable createTransferable(JComponent c) {
return new AttachmentTransferable(new ArrayList<>(attachmentPanel.getSelectedAttachments()));
}
 
@Override
public int getSourceActions(JComponent c) {
return MOVE;
}
 
}
 
);
 
}
 
public void updateBackgroundFromState() {
if (this.attachmentPanel.isSelected(this.attachment)) {
setBackground(SELECTED_COLOR);
} else {
setBackground(Color.WHITE);
}
}
 
private void initMenu(final Attachment attachment, final AttachmentPanel panelSource, final String name) {
final JPopupMenu menu = new JPopupMenu();
final JMenuItem menuItemDelete = new JMenuItem("Supprimer");
menuItemDelete.addActionListener(new ActionListener() {
111,17 → 238,21
 
@Override
public void actionPerformed(ActionEvent e) {
 
int value = JOptionPane.showConfirmDialog(FilePanel.this, "Voulez-vous vraiment supprimer ce fichier ?\n" + rowAttachment.getString("NAME") + "\nFichier orignal : "
+ rowAttachment.getString("FILENAME") + "\nType : " + rowAttachment.getString("MIMETYPE"), "Supprimer le ficher", JOptionPane.YES_NO_OPTION);
 
int value = 0;
if (attachment.isFolder()) {
value = JOptionPane.showConfirmDialog(FilePanel.this, "Voulez-vous vraiment supprimer ce dossier ?\n" + attachment.getName(), "Supprimer le dossier", JOptionPane.YES_NO_OPTION);
} else {
value = JOptionPane.showConfirmDialog(FilePanel.this,
"Voulez-vous vraiment supprimer ce fichier ?\n" + attachment.getName() + "\nFichier original : " + attachment.getFileName() + "\nType : " + attachment.getMimeType(),
"Supprimer le fichier", JOptionPane.YES_NO_OPTION);
}
if (value == JOptionPane.YES_OPTION) {
AttachmentUtils utils = new AttachmentUtils();
try {
utils.deleteFile(rowAttachment);
utils.deleteFile(attachment);
panelSource.initUI();
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de la suppression du fichier!", e1);
ExceptionHandler.handle("Erreur lors de la suppression", e1);
}
}
 
141,15 → 272,15
FilePanel.this.repaint();
}
 
public void validText(final SQLRowValues rowAttachment, final String name, final JTextField text) {
public void validText(final Attachment attachment, final String name, final JTextField text) {
try {
String newName = text.getText();
if (newName.trim().isEmpty()) {
newName = name;
}
rowAttachment.put("NAME", newName).commit();
AttachmentUtils.rename(attachment, newName);
label.setText(newName);
} catch (SQLException e1) {
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors du renommage du fichier!", e1);
}
}
156,13 → 287,13
 
@Override
public void actionPerformed(ActionEvent e) {
final String name = rowAttachment.getString("NAME");
final String name = attachment.getName();
 
text.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
validText(rowAttachment, name, text);
validText(attachment, name, text);
stopNameEditing();
} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
stopNameEditing();
174,12 → 305,13
 
@Override
public void focusLost(FocusEvent e) {
validText(rowAttachment, name, text);
validText(attachment, name, text);
stopNameEditing();
}
 
@Override
public void focusGained(FocusEvent e) {
// Nothing to do here
}
 
});
187,7 → 319,7
 
@Override
public void mouseExited(MouseEvent e) {
validText(rowAttachment, name, text);
validText(attachment, name, text);
stopNameEditing();
}
 
206,6 → 338,7
 
});
menu.add(menuItemRename);
if (!attachment.isFolder()) {
menu.addSeparator();
JMenuItem menuItemProperties = new JMenuItem("Propriétés");
menuItemProperties.addActionListener(new ActionListener() {
213,7 → 346,7
@Override
public void actionPerformed(ActionEvent e) {
JFrame f = new JFrame();
f.setTitle("Propriétés de " + rowAttachment.getString("NAME"));
f.setTitle("Propriétés de " + attachment.getName());
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
222,7 → 355,7
p.add(new JLabel("Nom : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
p.add(new JLabel(rowAttachment.getString("NAME")), c);
p.add(new JLabel(attachment.getName()), c);
c.gridy++;
// Type
c.gridx = 0;
230,7 → 363,7
p.add(new JLabel("Type : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
p.add(new JLabel(rowAttachment.getString("MIMETYPE")), c);
p.add(new JLabel(attachment.getMimeType()), c);
c.gridy++;
// FileName
c.gridx = 0;
238,7 → 371,7
p.add(new JLabel("Fichier original : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
p.add(new JLabel(rowAttachment.getString("FILENAME")), c);
p.add(new JLabel(attachment.getFileName()), c);
c.gridy++;
// Size
c.gridx = 0;
246,7 → 379,7
p.add(new JLabel("Taille : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
p.add(new JLabel(rowAttachment.getInt("FILESIZE") + " octets"), c);
p.add(new JLabel(attachment.getFileSize() + " octets"), c);
 
// Spacer
c.gridx = 1;
266,6 → 399,7
}
});
menu.add(menuItemProperties);
}
setComponentPopupMenu(menu);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/folder-icon.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/folder-icon.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentPanel.java
43,10 → 43,17
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
58,12 → 65,20
public class AttachmentPanel extends JPanel {
 
private final SQLRowAccessor rowSource;
private List<ListDataListener> listeners = new ArrayList<ListDataListener>();
private List<ListDataListener> listeners = new ArrayList<>();
 
private int idParent = 1;
private List<Integer> parents = new ArrayList<>();
private List<String> parentsNames = new ArrayList<>();
private Set<Attachment> selectedAttachments = new HashSet<>();
private List<FilePanel> filePanels = new ArrayList<>();
 
public AttachmentPanel(SQLRowAccessor rowSource) {
super();
this.rowSource = rowSource;
this.setLayout(new GridBagLayout());
this.parents.add(1);
this.parentsNames.add("Racine");
initUI();
setFocusable(true);
}
83,6 → 98,7
}
 
public void initUI() {
filePanels.clear();
this.invalidate();
this.removeAll();
GridBagConstraints c = new DefaultGridBagConstraints();
97,31 → 113,118
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
Where where = new Where(tableAttachment.getField("SOURCE_TABLE"), "=", this.rowSource.getTable().getName());
where = where.and(new Where(tableAttachment.getField("SOURCE_ID"), "=", this.rowSource.getID()));
// TODO en premier les dossier, puis trier par nom
List<SQLRowValues> attachments = fetcher.fetch(where);
 
// AJout d'un fichier
final JButton addButton = new JButton("Ajouter un fichier");
this.add(addButton, c);
where = where.and(new Where(tableAttachment.getField("ID_PARENT"), "=", this.idParent));
 
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
final List<SQLRowValues> rAttachments = fetcher.fetch(where);
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
// Folder paths
if (this.parents.size() > 1) {
JPanel navPanel = new JPanel();
navPanel.setBackground(Color.WHITE);
navPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
navPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 8, 2));
 
for (int i = 0; i < this.parents.size(); i++) {
JLabel b = new JLabel(" " + this.parentsNames.get(i) + " ");
b.setOpaque(true);
b.setBackground(new Color(230, 240, 255));
navPanel.add(b);
final int id = this.parents.get(i);
final int index = i;
if (i < this.parents.size() - 1) {
b.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
AttachmentPanel.this.idParent = id;
int nb = AttachmentPanel.this.parents.size() - index - 1;
for (int n = 0; n < nb; n++) {
final int pos = AttachmentPanel.this.parents.size() - 1;
AttachmentPanel.this.parents.remove(pos);
AttachmentPanel.this.parentsNames.remove(pos);
}
clearSelection();
initUI();
}
});
}
if (i < this.parents.size() - 1) {
b.setDropTarget(new DropTarget() {
 
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
dtde.acceptDrop(DnDConstants.ACTION_MOVE);
Transferable t = dtde.getTransferable();
try {
for (int i = 0; i < t.getTransferDataFlavors().length; i++) {
final DataFlavor dataFlavor = t.getTransferDataFlavors()[i];
if (dataFlavor.isMimeTypeEqual(DataFlavor.javaSerializedObjectMimeType)) {
@SuppressWarnings("unchecked")
List<Attachment> attachments = (List<Attachment>) t.getTransferData(dataFlavor);
AttachmentUtils utils = new AttachmentUtils();
for (Attachment a : attachments) {
if (a.getParentId() != id) {
utils.move(a, id);
}
}
initUI();
break;
}
}
 
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
 
}
this.add(navPanel, c);
c.gridy++;
}
 
// Tools
final JPanel toolbar = new JPanel();
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
final JButton addFolderButton = new JButton("Nouveau dossier");
toolbar.add(addFolderButton);
final JButton addFileButton = new JButton("Ajouter un fichier");
toolbar.add(addFileButton);
 
final JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(100);
progressBar.setStringPainted(true);
progressBar.setVisible(false);
this.add(progressBar, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
toolbar.add(progressBar);
 
this.add(toolbar, c);
 
c.gridy++;
 
addButton.addActionListener(new ActionListener() {
addFolderButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
AttachmentUtils utils = new AttachmentUtils();
try {
utils.createFolder("Nouveau dossier", rowSource, idParent);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, "Impossible de créer le dossier.", "Erreur", JOptionPane.ERROR_MESSAGE);
}
initUI();
 
}
});
 
addFileButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource());
 
final FileDialog fd = new FileDialog(frame, "Ajouter un fichier", FileDialog.LOAD);
fd.setVisible(true);
final String fileName = fd.getFile();
128,7 → 231,7
if (fileName != null) {
File inFile = new File(fd.getDirectory(), fileName);
AttachmentUtils utils = new AttachmentUtils();
utils.uploadFile(inFile, rowSource);
utils.uploadFile(inFile, rowSource, idParent);
initUI();
}
}
138,7 → 241,7
@Override
public Dimension getPreferredSize() {
int w = getSize().width;
int nbPerRow = (w - 5) / (FilePanel.WIDTH + 5);
int nbPerRow = (w - 5) / (FilePanel.PREFERRED_WIDTH + 5);
if (nbPerRow < 1) {
nbPerRow = 1;
}
146,7 → 249,7
if (nbRow < 1) {
nbRow = 1;
}
return new Dimension(w, 5 + nbRow * (FilePanel.HEIGHT + 5));
return new Dimension(w, 5 + nbRow * (FilePanel.PREFERRED_HEIGHT + 5));
}
 
};
155,19 → 258,41
files.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.FIT);
files.setScrollableHeight(ScrollablePanel.ScrollableSizeHint.NONE);
files.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
final List<Attachment> attachments = new ArrayList<>(rAttachments.size());
for (final SQLRowValues sqlRowValues : rAttachments) {
final Attachment a = new Attachment(sqlRowValues);
attachments.add(a);
}
Collections.sort(attachments, new Comparator<Attachment>() {
 
@Override
public int compare(Attachment o1, Attachment o2) {
if (o1.isFolder() && !o2.isFolder()) {
return -1;
}
if (!o1.isFolder() && o2.isFolder()) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
 
// Liste des fichiers
for (final SQLRowValues sqlRowValues : attachments) {
 
final FilePanel filePanel = new FilePanel(sqlRowValues, this);
for (final Attachment a : attachments) {
final FilePanel filePanel = new FilePanel(a, this);
this.filePanels.add(filePanel);
filePanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
Thread t = new Thread() {
if (a.isFolder()) {
openFolder(a);
} else {
final Thread t = new Thread() {
@Override
public void run() {
AttachmentUtils utils = new AttachmentUtils();
File f = utils.getFile(sqlRowValues);
File f = utils.getFile(a);
if (f == null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
174,7 → 299,6
JOptionPane.showMessageDialog(null, "Impossible de récupérer le fichier.", "Erreur", JOptionPane.ERROR_MESSAGE);
}
});
System.err.println("Impossible de récupérer le fichier.");
} else {
try {
FileUtils.openFile(f);
181,6 → 305,7
} catch (IOException e1) {
ExceptionHandler.handle("Erreur lors de l'ouverture du fichier.", e1);
}
 
}
}
};
187,16 → 312,19
t.start();
}
}
}
 
});
files.add(filePanel);
 
}
c.gridwidth = 2;
 
c.gridx = 0;
c.gridy++;
c.weightx = 1;
c.weighty = 1;
JScrollPane scroll = new JScrollPane(files);
 
final JScrollPane scroll = new JScrollPane(files);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setMinimumSize(new Dimension((int) (400 * 1.618), 400));
204,11 → 332,19
scroll.setBackground(Color.WHITE);
scroll.getViewport().setBackground(Color.WHITE);
this.add(scroll, c);
scroll.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
clearSelection();
updatePanels();
}
});
 
this.validate();
this.repaint();
 
DropTarget dt = new DropTarget() {
 
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
226,12 → 362,13
if (cancelledByUser) {
break;
}
utils.uploadFile(f, rowSource);
if (!f.isDirectory()) {
utils.uploadFile(f, rowSource, idParent);
}
}
initUI();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
241,4 → 378,40
fireDataChanged();
}
 
public Set<Attachment> getSelectedAttachments() {
return selectedAttachments;
}
 
public void select(Attachment a) {
this.selectedAttachments.add(a);
}
 
public void deselect(Attachment a) {
this.selectedAttachments.remove(a);
}
 
public boolean isSelected(Attachment a) {
return this.selectedAttachments.contains(a);
}
 
public void clearSelection() {
this.selectedAttachments.clear();
}
 
public void updatePanels() {
for (FilePanel p : this.filePanels) {
p.updateBackgroundFromState();
}
}
 
public void openFolder(final Attachment a) {
if (!a.isFolder()) {
throw new IllegalStateException(a.getName() + " is not a folder");
}
clearSelection();
this.idParent = a.getId();
this.parents.add(a.getId());
this.parentsNames.add(a.getName());
initUI();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentUtils.java
13,18 → 13,6
package org.openconcerto.erp.core.edm;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.storage.StorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.sync.SyncClient;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
37,10 → 25,21
 
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
import org.openconcerto.erp.storage.StorageEngine;
import org.openconcerto.erp.storage.StorageEngines;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.sync.SyncClient;
 
public class AttachmentUtils {
 
public void uploadFile(File inFile, SQLRowAccessor rowSource) {
public void uploadFile(File inFile, SQLRowAccessor rowSource, int idParent) {
try {
 
// Création de la row attachment
47,11 → 46,12
SQLRowValues rowValsAttachment = new SQLRowValues(rowSource.getTable().getTable("ATTACHMENT"));
rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
rowValsAttachment.put("SOURCE_ID", rowSource.getID());
 
rowValsAttachment.put("ID_PARENT", idParent);
SQLRow rowAttachment = rowValsAttachment.insert();
int id = rowAttachment.getID();
 
String subDir = "EDM" + File.separator + String.valueOf((id / 1000) * 1000);
final String folderId = String.valueOf((id / 1000) * 1000);
String subDir = "EDM" + File.separator + folderId;
String fileNameID = String.valueOf(id);
String ext = "";
 
73,9 → 73,10
for (StorageEngine storageEngine : engines) {
if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
final String path = remotePath;
try {
 
try (FileInputStream in = new FileInputStream(inFile)) {
storageEngine.connect();
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inFile));
final BufferedInputStream inStream = new BufferedInputStream(in);
storageEngine.store(inStream, path, fileWithIDNAme, true);
inStream.close();
storageEngine.disconnect();
142,22 → 143,20
// needed for update count
 
rowValsAttachment.commit();
 
updateAttachmentsCountFromAttachment(rowValsAttachment);
} catch (IOException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
final Attachment a = new Attachment(rowValsAttachment);
updateAttachmentsCountFromAttachment(a);
} catch (Exception e) {
e.printStackTrace();
}
}
 
public File getFile(SQLRowAccessor rowAttachment) {
public File getFile(Attachment attachment) {
 
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
boolean isOnCloud = config.isOnCloud();
 
String subDir = rowAttachment.getString("STORAGE_PATH");
String fileName = rowAttachment.getString("STORAGE_FILENAME");
String subDir = attachment.getStoragePath();
String fileName = attachment.getStorageFileName();
 
String remotePath = config.getSocieteID() + File.separator + subDir;
 
209,14 → 208,14
 
}
 
public void deleteFile(SQLRowAccessor rowAttachment) throws SQLException, IllegalStateException {
public void deleteFile(Attachment rowAttachment) throws SQLException, IllegalStateException {
 
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
if (!rowAttachment.isFolder()) {
boolean isOnCloud = config.isOnCloud();
 
// Delete File
String subDir = rowAttachment.getString("STORAGE_PATH");
String fileName = rowAttachment.getString("STORAGE_FILENAME");
String subDir = rowAttachment.getStoragePath();
String fileName = rowAttachment.getStorageFileName();
 
String remotePath = config.getSocieteID() + File.separator + subDir;
if (isOnCloud) {
238,21 → 237,23
}
}
}
 
}
// Delete Row
config.getDirectory().getElement(rowAttachment.getTable()).archive(rowAttachment.getID());
config.getDirectory().getElement(AttachmentSQLElement.class).archive(rowAttachment.getId());
updateAttachmentsCountFromAttachment(rowAttachment);
}
 
public void updateAttachmentsCountFromAttachment(SQLRowAccessor rowAttachment) {
SQLTable table = rowAttachment.getTable().getTable(rowAttachment.getString("SOURCE_TABLE"));
SQLRow source = table.getRow(rowAttachment.getInt("SOURCE_ID"));
private void updateAttachmentsCountFromAttachment(Attachment rowAttachment) {
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
final SQLTable table = attachmentTable.getTable(rowAttachment.getSourceTable());
final SQLRow source = table.getRow(rowAttachment.getSourceId());
updateAttachmentsCountFromSource(source);
}
 
public void updateAttachmentsCountFromSource(SQLRow rowSource) {
SQLTable tableSource = rowSource.getTable();
SQLTable tableAtt = rowSource.getTable().getTable("ATTACHMENT");
private void updateAttachmentsCountFromSource(SQLRow rowSource) {
final SQLTable tableSource = rowSource.getTable();
final SQLTable tableAtt = rowSource.getTable().getTable("ATTACHMENT");
 
String req = "UPDATE " + tableSource.getSQLName().quote() + " SET " + tableSource.getField("ATTACHMENTS").getQuotedName() + "=(SELECT COUNT(*) FROM " + tableAtt.getSQLName().quote();
req += " WHERE " + tableAtt.getArchiveField().getQuotedName() + "=0 AND " + tableAtt.getField("SOURCE_TABLE").getQuotedName() + "='" + tableSource.getName() + "'";
261,4 → 262,44
tableSource.getDBSystemRoot().getDataSource().execute(req);
}
 
public static void rename(Attachment rowAttachment, String newName) {
rowAttachment.setName(newName);
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
final String req = "UPDATE " + attachmentTable.getSQLName().quote() + " SET " + attachmentTable.getField("NAME").getQuotedName() + "=" + attachmentTable.getBase().quoteString(newName)
+ " WHERE " + attachmentTable.getKey().getQuotedName() + "=" + rowAttachment.getId();
attachmentTable.getDBSystemRoot().getDataSource().execute(req);
}
 
public void createFolder(String folderName, SQLRowAccessor rowSource, int idParent) throws SQLException {
final SQLRowValues rowValsAttachment = new SQLRowValues(rowSource.getTable().getTable("ATTACHMENT"));
rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
rowValsAttachment.put("SOURCE_ID", rowSource.getID());
rowValsAttachment.put("ID_PARENT", idParent);
rowValsAttachment.put("NAME", folderName);
rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
rowValsAttachment.put("SOURCE_ID", rowSource.getID());
rowValsAttachment.put("MIMETYPE", Attachment.MIMETYPE_FOLDER);
rowValsAttachment.put("FILENAME", "");
rowValsAttachment.put("FILESIZE", 0);
rowValsAttachment.put("STORAGE_PATH", "");
rowValsAttachment.put("STORAGE_FILENAME", "");
rowValsAttachment.commit();
}
 
public void move(Attachment a, Attachment folder) {
if (!folder.isFolder()) {
throw new IllegalArgumentException(folder + " is not a folder");
}
move(a, folder.getId());
}
 
public void move(Attachment a, int folderId) {
final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
final String req = "UPDATE " + attachmentTable.getSQLName().quote() + " SET " + attachmentTable.getField("ID_PARENT").getQuotedName() + "=" + folderId + " WHERE "
+ attachmentTable.getKey().getQuotedName() + "=" + a.getId();
attachmentTable.getDBSystemRoot().getDataSource().execute(req);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentTransferable.java
New file
0,0 → 1,54
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.edm;
 
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.List;
 
public class AttachmentTransferable implements Transferable {
 
private final List<Attachment> attachments;
private static final DataFlavor[] FLAVORS = new DataFlavor[] { new DataFlavor(String.class, "id") };
 
public AttachmentTransferable(List<Attachment> a) {
this.attachments = a;
}
 
public List<Attachment> getA() {
return attachments;
}
 
@Override
public DataFlavor[] getTransferDataFlavors() {
return FLAVORS;
}
 
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return FLAVORS[0].equals(flavor);
}
 
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return attachments;
}
 
@Override
public String toString() {
return super.toString() + " " + this.attachments.size() + " attachements";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentSQLElement.java
13,27 → 13,23
package org.openconcerto.erp.core.edm;
 
import java.util.ArrayList;
import java.util.List;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
 
public class AttachmentSQLElement extends ComptaSQLConfElement {
 
public final static String DIRECTORY_PREFS = "EDMdirectory";
public static final String DIRECTORY_PREFS = "EDMdirectory";
 
public AttachmentSQLElement() {
super("ATTACHMENT", "un attachement", "attachements");
 
}
 
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(10);
l.add("SOURCE_TABLE");
l.add("SOURCE_ID");
l.add("NAME");
47,31 → 43,21
return l;
}
 
@Override
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>(1);
l.add("NAME");
return l;
}
 
@Override
protected String getParentFFName() {
return "ID_PARENT";
}
 
public SQLComponent createComponent() {
return new BaseSQLComponent(this) {
public void addViews() {
this.setLayout(new GridBagLayout());
 
final GridBagConstraints c = new DefaultGridBagConstraints();
c.anchor = GridBagConstraints.NORTHEAST;
c.gridwidth = 1;
 
// // Numero
// JLabel labelNumero = new JLabel("Numéro ");
// this.add(labelNumero, c);
//
// JTextField textNumero = new JTextField();
// c.gridx++;
// c.weightx = 1;
// this.add(textNumero, c);
 
// this.addRequiredSQLObject(textNumero, "NUMERO");
}
};
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/Attachment.java
New file
0,0 → 1,115
/*
* 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.edm;
 
import org.openconcerto.sql.model.SQLRowValues;
 
import java.io.Serializable;
 
public class Attachment implements Serializable {
private final int id;
private String name;
private String mimeType;
private String fileName;
private int fileSize;
private String storagePath;
private String storageFileName;
private String sourceTable;
private int sourceId;
private int parentId;
 
public static final String MIMETYPE_FOLDER = "inode/directory";
 
public Attachment(SQLRowValues rowAttachment) {
this.id = rowAttachment.getID();
this.name = rowAttachment.getString("NAME");
this.mimeType = rowAttachment.getString("MIMETYPE");
this.fileName = rowAttachment.getString("FILENAME");
this.fileSize = rowAttachment.getInt("FILESIZE");
this.storagePath = rowAttachment.getString("STORAGE_PATH");
this.storageFileName = rowAttachment.getString("STORAGE_FILENAME");
this.sourceTable = rowAttachment.getString("SOURCE_TABLE");
this.sourceId = rowAttachment.getInt("SOURCE_ID");
this.parentId = rowAttachment.getInt("ID_PARENT");
}
 
public int getId() {
return id;
}
 
public String getName() {
return name;
}
 
public void setName(String newName) {
this.name = newName;
}
 
public String getMimeType() {
return mimeType;
}
 
public String getFileName() {
return fileName;
}
 
public int getFileSize() {
return fileSize;
}
 
public String getStorageFileName() {
return storageFileName;
}
 
public String getStoragePath() {
return storagePath;
}
 
public String getSourceTable() {
return sourceTable;
}
 
public int getSourceId() {
return sourceId;
}
 
public int getParentId() {
return parentId;
}
 
public boolean isFolder() {
return this.mimeType.equals(MIMETYPE_FOLDER);
}
 
@Override
public String toString() {
return super.toString() + " attachment id:" + this.getId() + " name:" + this.getName();
}
 
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
 
if (this.getClass() != obj.getClass())
return false;
 
return this.getId() == ((Attachment) obj).getId();
}
 
@Override
public int hashCode() {
return getId();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/ChiffrageCommandeClientSQLElement.java
37,7 → 37,10
*/
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
// remove id_commande_client for CIM
if (!getTable().getDBRoot().contains("ID_AFFAIRE")) {
l.add("ID_COMMANDE_CLIENT");
}
l.add("NOM");
return l;
}
50,6 → 53,8
@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());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/FacturationCommandeClientSQLElement.java
14,6 → 14,7
package org.openconcerto.erp.core.sales.order.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.DeviseTableCellRenderer;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.core.sales.order.ui.TypeFactureCommandeCellRenderer;
import org.openconcerto.erp.core.sales.order.ui.TypeFactureCommandeClient;
22,17 → 23,23
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
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.graph.Path;
import org.openconcerto.sql.view.EditFrame;
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.RowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
214,7 → 221,26
@Override
protected void _initTableSource(SQLTableModelSource res) {
res.init();
res.getColumn(getTable().getField("POURCENT")).setRenderer(new DeviseTableCellRenderer());
res.getColumn(getTable().getField("TYPE_FACTURE")).setRenderer(new TypeFactureCommandeCellRenderer());
final BaseSQLTableModelColumn pourcentFact = new BaseSQLTableModelColumn("Montant facturé", BigDecimal.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
long ht = r.getForeign("ID_COMMANDE_CLIENT").getLong("T_TTC");
BigDecimal percent = r.getBigDecimal("POURCENT");
return percent.movePointLeft(2).multiply(new BigDecimal(ht).movePointLeft(2), DecimalUtils.HIGH_PRECISION);
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
Path p2 = p.add(p.getFirst().getField("ID_COMMANDE_CLIENT"));
return CollectionUtils.createSet(new FieldPath(p, "POURCENT"), new FieldPath(p2, "T_TTC"));
}
};
pourcentFact.setRenderer(new DeviseTableCellRenderer());
res.getColumns().add(pourcentFact);
super._initTableSource(res);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/action/ListeDesCommandesClientAction.java
158,10 → 158,13
totalQte = totalQte.add(qte);
if (row.getBoolean("LIVRE_FORCED") || row.getBoolean("LIVRE")) {
totalQteL = totalQteL.add(qte);
} else {
totalQteL = totalQteL.add(row.getBigDecimal("QTE_LIVREE"));
} else if (row.getBigDecimal("QTE_LIVREE") != null) {
final BigDecimal qteLivree = row.getBigDecimal("QTE_LIVREE");
if (qteLivree != null) {
totalQteL = totalQteL.add(qteLivree);
}
}
}
if (totalQte.signum() != 0) {
return totalQteL.divide(totalQte, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
} else {
225,22 → 228,8
return null;
}
});
this.btnMngr.setAdditional(this.buttonModifier, new ITransformer<JButton, String>() {
 
@Override
public String transformChecked(JButton input) {
 
SQLRowAccessor row = getListe().fetchSelectedRow();
 
BigDecimal b = getAvancement(row);
 
if (row.getLong("T_HT") > 0 && b.signum() != 0) {
return "Vous ne pouvez pas modifier une commande facturée !";
}
return null;
}
});
}
};
 
final List<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>> fields = new ArrayList<Tuple2<? extends SQLTableModelColumn, IListTotalPanel.Type>>(2);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureItemSQLElement.java
18,6 → 18,7
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.rights.NXRights;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
24,11 → 25,15
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
117,6 → 122,7
l.add("ECO_CONTRIBUTION");
l.add("T_ECO_CONTRIBUTION");
}
l.add("T_PA_HT");
l.add("T_PV_HT");
l.add("T_PV_TTC");
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/action/ListeDesFactureItemsAction.java
New file
0,0 → 1,75
/*
* 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.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.Action;
import javax.swing.JFrame;
 
public class ListeDesFactureItemsAction extends CreateFrameAbstractAction {
 
public ListeDesFactureItemsAction() {
super();
this.putValue(Action.NAME, "Liste des articles facturés");
}
 
public JFrame createFrame() {
final SQLElement element = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
 
IListe liste = new IListe(element.getTableSource(true));
final ListeViewPanel listeAddPanel = new ListeViewPanel(element, liste);
listeAddPanel.getListe().getRequest().setWhere(new Where(element.getTable().getField("ID_SAISIE_VENTE_FACTURE"), ">", 1));
List<SQLField> l = new ArrayList<SQLField>();
l.add(element.getTable().getField("T_PA_HT"));
l.add(element.getTable().getField("T_PV_HT"));
l.add(element.getTable().getField("T_PV_TTC"));
IListTotalPanel total = new IListTotalPanel(listeAddPanel.getListe(), l);
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridy = 2;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
listeAddPanel.add(total, c);
IListFrame frame = new IListFrame(listeAddPanel);
frame.setTextTitle("Liste des articles facturés");
frame.getPanel().getListe().setSQLEditable(false);
frame.getPanel().setAddVisible(false);
frame.getPanel().setSearchFullMode(true);
 
// Date panel
IListFilterDatePanel datePanel = new IListFilterDatePanel(frame.getPanel().getListe(), element.getTable().getTable("SAISIE_VENTE_FACTURE").getField("DATE"),
IListFilterDatePanel.getDefaultMap());
c.gridy++;
c.anchor = GridBagConstraints.CENTER;
frame.getPanel().add(datePanel, c);
 
return frame;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/ui/EtatVentesPanel.java
25,11 → 25,13
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
 
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
41,6 → 43,7
private JDate du, au;
private JButton buttonGen = new JButton("Créer");
private JButton buttonClose = new JButton("Fermer");
JCheckBox boxTicket = new JCheckBox("Uniquement les ventes en caisse");
 
public EtatVentesPanel() {
super(new GridBagLayout());
59,6 → 62,16
final JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 1));
final DefaultComboBoxModel model = new DefaultComboBoxModel();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date d1 = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
Date d2 = cal.getTime();
map.put("Aujourd'hui", Tuple2.create(d1, d2));
for (String s : map.keySet()) {
model.addElement(s);
}
100,7 → 113,14
 
c.gridy++;
c.gridx = 0;
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
 
this.add(boxTicket, c);
 
c.gridy++;
c.gridx = 0;
 
JPanel panelButton = new JPanel();
panelButton.add(this.buttonGen);
panelButton.add(this.buttonClose);
147,7 → 167,7
if (e.getSource() == this.buttonGen) {
final Date start = this.du.getDate();
final Date stop = this.au.getDate();
final EtatVentesXmlSheet sheet = new EtatVentesXmlSheet(start, stop);
final EtatVentesXmlSheet sheet = new EtatVentesXmlSheet(start, stop, boxTicket.isSelected());
try {
// FIXME probleme de rendu avec le viewer
sheet.createDocumentAsynchronous().get();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/component/SaisieVenteFactureSQLComponent.java
109,7 → 109,7
private AbstractArticleItemTable tableFacture;
private JLabel labelAffaire = new JLabel("Affaire");
private final JDate dateSaisie = new JDate(true);
private DeviseField textPortHT, textAvoirTTC, textRemiseHT, fieldTTC, textNetAPayer;
private DeviseField textPortHT, textAcompte, textAvoirTTC, textRemiseHT, fieldTTC, textNetAPayer;
private DeviseField totalTimbre, netPayer;
private JTextField tauxTimbre;
 
151,6 → 151,7
if (!rowCli.isForeignEmpty("ID_COMMERCIAL")) {
comboCommercial.setValue(rowCli.getForeignID("ID_COMMERCIAL"));
}
 
if (getMode() == SQLComponent.Mode.INSERTION || !isFilling()) {
SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
226,6 → 227,7
final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
 
this.textAvoirTTC = new DeviseField();
this.textAcompte = new DeviseField();
 
// Champ Module
c.gridx = 0;
268,7 → 270,7
@Override
public String getAutoRefreshNumber() {
if (getMode() == Mode.INSERTION) {
return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate());
return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate(), defaultNum);
} else {
return null;
}
826,6 → 828,7
this.add(this.panelOO, c);
 
this.addSQLObject(this.textAvoirTTC, "T_AVOIR_TTC");
this.addSQLObject(this.textAcompte, "T_ACOMPTE");
 
this.addRequiredSQLObject(dateSaisie, "DATE");
this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
1140,6 → 1143,10
netAPayer += timbre;
}
}
Long acompte = this.textAcompte.getValue();
if (acompte != null) {
netAPayer -= acompte;
}
this.textNetAPayer.setValue(netAPayer);
this.textAvoirTTC.setValue(totalAvoirTTC);
}
1290,7 → 1297,7
} catch (InterruptedException e) {
e.printStackTrace();
}
String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate());
String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate(), defaultNum);
this.textNumeroUnique.setText(num);
validated = this.textNumeroUnique.checkValidation(false);
System.err.println("ATTEMPT " + attempt + " WITH NUMERO " + num + " validated : " + validated);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/component/DevisSQLComponent.java
355,9 → 355,10
});
 
}
final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
 
final ElementComboBox boxTarif = new ElementComboBox();
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
 
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ADDRESS_SPEC, true)) {
 
final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
594,6 → 595,24
this.textRemiseHT.setMinimumSize(new Dimension(150, 20));
this.textRemiseHT.setPreferredSize(new Dimension(150, 20));
 
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
// Acompte
cRemise.gridy++;
cRemise.gridx = 0;
cRemise.weightx = 0;
cRemise.weighty = 0;
cRemise.gridwidth = 1;
JLabel compAcompte = new JLabel(getLabelFor("T_ACOMPTE"), SwingConstants.RIGHT);
panelRemise.add(compAcompte, cRemise);
cRemise.gridx++;
cRemise.gridwidth = GridBagConstraints.REMAINDER;
DeviseField fieldAcompte = new DeviseField();
fieldAcompte.setEnabled(false);
cRemise.weightx = 1;
panelRemise.add(fieldAcompte, cRemise);
this.addView(fieldAcompte, "T_ACOMPTE");
}
 
// cRemise.gridx = 1;
// cRemise.gridy++;
// cRemise.weightx = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisLogMailSQLElement.java
New file
0,0 → 1,39
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.quote.element;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.SocieteJoinSQLElement;
import org.openconcerto.sql.element.JoinSQLElement;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.utils.SQLCreateTable;
 
public class DevisLogMailSQLElement extends SocieteJoinSQLElement {
 
public static final String TABLENAME = "DEVIS_MAIL_LOG";
private static final String TO_OWNER_FIELDNAME = "ID_DEVIS";
 
private static final SQLCreateTable getCreateTable(final SQLTable devisT, final SQLTable logT) {
return JoinSQLElement.createBuilder(devisT, logT).setTableName(TABLENAME).setOwnerFK(TO_OWNER_FIELDNAME).getCreateTable();
}
 
public DevisLogMailSQLElement() {
this(ComptaPropsConfiguration.getInstanceCompta().getRootSociete());
}
 
public DevisLogMailSQLElement(final DBRoot root) {
super((SQLTable) root.getCheckedChild(TABLENAME).getJDBC(), TO_OWNER_FIELDNAME);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisItemSQLElement.java
18,8 → 18,6
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.utils.KDUtils;
import org.openconcerto.erp.utils.KDUtils.Folder;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.SQLRowAccessor;
28,11 → 26,8
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
 
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
52,7 → 47,6
return "ID_DEVIS";
}
 
 
protected List<String> getListFields() {
List<String> l = new ArrayList<String>();
l.add("ID_DEVIS");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisSQLElement.java
26,8 → 26,7
import org.openconcerto.erp.core.sales.quote.ui.QuoteSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.utils.KDUtils;
import org.openconcerto.erp.utils.KDUtils.Folder;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.GlobalMapper;
import org.openconcerto.sql.element.SQLComponent;
45,6 → 44,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.UserRightsManager;
63,6 → 63,7
import org.openconcerto.ui.light.ColumnsSpec;
import org.openconcerto.ui.light.CustomEditorProvider;
import org.openconcerto.ui.light.LightControler;
import org.openconcerto.ui.light.LightUIButtonUnmanaged;
import org.openconcerto.ui.light.LightUIComboBox;
import org.openconcerto.ui.light.LightUIElement;
import org.openconcerto.ui.light.LightUILine;
153,6 → 154,12
 
}
 
@Override
public Set<String> getReadOnlyFields() {
Set<String> s = new HashSet<String>();
s.add("T_ACOMPTE");
return s;
}
 
private List<RowAction> getDevisRowActions() {
 
164,6 → 171,65
 
rowsActions.add(factureAction);
 
SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Saisir un acompte") {
EditFrame edit;
 
public void actionPerformed(ActionEvent e) {
final SQLElement eltEncaisser = Configuration.getInstance().getDirectory()
.getElement(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ENCAISSER_MONTANT"));
 
if (this.edit == null) {
this.edit = new EditFrame(eltEncaisser, EditMode.CREATION);
}
final SQLRowAccessor selRow = IListe.get(e).getSelectedRow();
SQLRowValues rowVals = new SQLRowValues(eltEncaisser.getTable());
rowVals.put("ACOMPTE", true);
rowVals.put("NOM", "Acompte devis " + selRow.getString("NUMERO"));
rowVals.put("ID_CLIENT", selRow.getForeignID("ID_CLIENT"));
rowVals.put("ID_DEVIS", selRow.getID());
SQLRowValues rowValsElt = new SQLRowValues(eltEncaisser.getTable().getTable("ENCAISSER_MONTANT_ELEMENT"));
rowValsElt.put("MONTANT_A_REGLER", selRow.getLong("T_TTC"));
rowValsElt.put("DATE", selRow.getObject("DATE"));
rowValsElt.put("ID_ENCAISSER_MONTANT", rowVals);
this.edit.getSQLComponent().select(rowVals);
this.edit.setVisible(true);
this.edit.addEditPanelListener(new EditPanelListener() {
 
@Override
public void modified() {
// TODO Auto-generated method stub
 
}
 
@Override
public void inserted(int id) {
// Put id devis and refresh devis.t_acompte
SQLRow rowE = eltEncaisser.getTable().getRow(id);
String up = "UPDATE " + selRow.getTable().getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from " + rowE.getTable().getSQLName().quote()
+ " where \"ARCHIVE\"=0 and \"ID_DEVIS\"=" + selRow.getID() + ") where \"ID_DEVIS\"=" + selRow.getID();
eltEncaisser.getTable().getDBSystemRoot().getDataSource().execute(up);
}
 
@Override
public void deleted() {
// TODO Auto-generated method stub
 
}
 
@Override
public void cancelled() {
// TODO Auto-generated method stub
 
}
});
}
}, false);
actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
rowsActions.add(actionClient);
}
 
PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Détails client") {
EditFrame edit;
private SQLElement eltClient = Configuration.getInstance().getDirectory().getElement(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT"));
537,6 → 603,10
}
l.add("T_HT");
l.add("T_TTC");
SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
l.add("T_ACOMPTE");
}
l.add("INFOS");
if (getTable().contains("DUNNING_DATE")) {
l.add("DUNNING_DATE");
555,7 → 625,7
SQLRowAccessor rowAd;
if (!r.isForeignEmpty("ID_ADRESSE_LIVRAISON")) {
rowAd = r.getForeign("ID_ADRESSE_LIVRAISON");
} else if (!r.getForeign("ID_CLIENT").isForeignEmpty("ID_ADRESSE_L")) {
} else if (r.getForeign("ID_CLIENT").getObject("ID_ADRESSE_L") != null && !r.getForeign("ID_CLIENT").isForeignEmpty("ID_ADRESSE_L")) {
rowAd = r.getForeign("ID_CLIENT").getForeign("ID_ADRESSE_L");
} else {
rowAd = r.getForeign("ID_CLIENT").getForeign("ID_ADRESSE");
811,38 → 881,34
 
LightUILine toolbarLine = new LightUILine();
 
LightUIElement b1 = new LightUIElement("up");
b1.setType(LightUIElement.TYPE_BUTTON_UNMANAGED);
b1.setGridWidth(1);
LightUIButtonUnmanaged b1 = new LightUIButtonUnmanaged("up");
b1.setIcon("up.png");
panel.addControler(new ActivationOnSelectionControler(id, b1.getId()));
panel.addControler(new LightControler(LightControler.TYPE_UP, id, b1.getId()));
toolbarLine.addChild(b1);
 
final LightUIElement b2 = new LightUIElement("down");
b2.setType(LightUIElement.TYPE_BUTTON_UNMANAGED);
b2.setGridWidth(1);
final LightUIButtonUnmanaged b2 = new LightUIButtonUnmanaged("down");
b2.setIcon("down.png");
panel.addControler(new ActivationOnSelectionControler(id, b2.getId()));
panel.addControler(new LightControler(LightControler.TYPE_DOWN, id, b2.getId()));
toolbarLine.addChild(b2);
// Add
LightUIElement addButton = createButton("add", "Ajouter une ligne");
LightUIElement addButton = new LightUIButtonUnmanaged("add", "Ajouter une ligne");
panel.addControler(new LightControler(LightControler.TYPE_ADD_DEFAULT, id, addButton.getId()));
toolbarLine.addChild(addButton);
// Insert
LightUIElement insertButton = createButton("insert", "Insérer une ligne");
LightUIElement insertButton = new LightUIButtonUnmanaged("insert", "Insérer une ligne");
panel.addControler(new LightControler(LightControler.TYPE_INSERT_DEFAULT, id, insertButton.getId()));
toolbarLine.addChild(insertButton);
 
// Copy
LightUIElement copyButton = createButton("copy", "Dupliquer");
LightUIElement copyButton = new LightUIButtonUnmanaged("copy", "Dupliquer");
panel.addControler(new ActivationOnSelectionControler(id, copyButton.getId()));
panel.addControler(new LightControler(LightControler.TYPE_COPY, id, copyButton.getId()));
toolbarLine.addChild(copyButton);
 
// Remove
LightUIElement removeButton = createButton("remove", "Supprimer");
LightUIElement removeButton = new LightUIButtonUnmanaged("remove", "Supprimer");
panel.addControler(new ActivationOnSelectionControler(id, removeButton.getId()));
panel.addControler(new LightControler(LightControler.TYPE_REMOVE, id, removeButton.getId()));
toolbarLine.addChild(removeButton);
859,13 → 925,6
return panel;
}
 
LightUIElement createButton(String id, String label) {
final LightUIElement b1 = new LightUIElement(id);
b1.setType(LightUIElement.TYPE_BUTTON_UNMANAGED);
b1.setGridWidth(1);
b1.setLabel(label);
return b1;
}
});
return map;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/component/ReferenceArticleSQLComponent.java
426,8 → 426,20
panel.add(textTare, c);
addView(textTare, "TARE");
 
c.weightx = 0;
c.gridy++;
c.gridx = 0;
JLabel labelMasque = new JLabel(getLabelFor("MASQUE_CAISSE"));
c.fill = GridBagConstraints.BOTH;
panel.add(labelMasque, c);
c.weightx = 1;
c.gridx++;
JCheckBox boxMasqueCaisse = new JCheckBox();
panel.add(boxMasqueCaisse, c);
this.addSQLObject(boxMasqueCaisse, "MASQUE_CAISSE");
 
c.gridy++;
c.gridx = 0;
c.weightx = 0;
JLabel labelEco = new JLabel(getLabelFor("ID_ECO_CONTRIBUTION"));
c.fill = GridBagConstraints.BOTH;
1340,6 → 1352,7
}
 
private void setTextHT() {
if (!isFilling()) {
this.textPVHT.getDocument().removeDocumentListener(this.htDocListener);
final BigDecimal ttc = StringUtils.getBigDecimalFromUserText(this.textPVTTC.getText());
if (ttc != null) {
1353,8 → 1366,10
}
this.textPVHT.getDocument().addDocumentListener(this.htDocListener);
}
}
 
private void setTextTTC() {
if (!isFilling()) {
this.textPVTTC.getDocument().removeDocumentListener(this.ttcDocListener);
final BigDecimal ht = StringUtils.getBigDecimalFromUserText(this.textPVHT.getText());
if (ht != null) {
1368,6 → 1383,7
}
this.textPVTTC.getDocument().addDocumentListener(this.ttcDocListener);
}
}
 
/**
* calcul du prix achat et vente ainsi que le poids total pour la piece
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/StringStandardPrinter.java
New file
0,0 → 1,86
/*
* 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.pos.io;
 
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.XMLDateFormat;
 
import java.text.Format;
import java.util.Date;
import java.util.Locale;
 
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.standard.DocumentName;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.PrinterName;
 
/**
* A printer using {@link DocFlavor.STRING}
*
* @author sylvain
*/
public class StringStandardPrinter extends DefaultTicketPrinter {
 
private static final Format DATE_FMT = new XMLDateFormat();
 
static JobName createJobName(final String name) {
return new JobName(name + ' ' + DATE_FMT.format(new Date()), Locale.getDefault());
}
 
private final String printerName;
 
public StringStandardPrinter(String printerName) {
if (StringUtils.isEmpty(printerName, true))
throw new IllegalArgumentException("Missing printer name");
this.printerName = printerName;
}
 
public final String getPrinterName() {
return this.printerName;
}
 
@Override
public void printBuffer() throws Exception {
final AttributeSet attrSet = new HashPrintServiceAttributeSet(new PrinterName(this.printerName, null));
final PrintService[] lookupPrintServices = PrintServiceLookup.lookupPrintServices(null, attrSet);
if (lookupPrintServices.length <= 0) {
throw new PrintException("Printer " + this.printerName + " not found");
}
final DocPrintJob job = lookupPrintServices[0].createPrintJob();
 
final int size = this.strings.size();
final StringBuilder sb = new StringBuilder(size * 50);
for (int i = 0; i < size; i++) {
sb.append(this.strings.get(i));
sb.append('\n');
}
 
final Doc doc = new SimpleDoc(sb.toString(), DocFlavor.STRING.TEXT_PLAIN, new HashDocAttributeSet(new DocumentName(getDocName(), Locale.getDefault())));
job.print(doc, new HashPrintRequestAttributeSet(createJobName(getDocName())));
}
 
@Override
public void openDrawer() throws Exception {
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/SwingPrinter.java
New file
0,0 → 1,58
/*
* 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.pos.io;
 
import org.openconcerto.erp.core.sales.pos.ui.TextAreaTicketPrinter;
import org.openconcerto.utils.StringUtils;
 
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.swing.text.JTextComponent;
 
/**
* A printer using
* {@link JTextComponent#print(java.text.MessageFormat, java.text.MessageFormat, boolean, PrintService, javax.print.attribute.PrintRequestAttributeSet, boolean)}
*
* @author sylvain
*/
public class SwingPrinter extends TextAreaTicketPrinter {
 
private final String printerName;
 
public SwingPrinter(String printerName) {
if (StringUtils.isEmpty(printerName, true))
throw new IllegalArgumentException("Missing printer name");
this.printerName = printerName;
}
 
public final String getPrinterName() {
return this.printerName;
}
 
@Override
public void printBuffer() throws Exception {
super.printBuffer();
final AttributeSet attrSet = new HashPrintServiceAttributeSet(new PrinterName(this.printerName, null));
final PrintService[] lookupPrintServices = PrintServiceLookup.lookupPrintServices(null, attrSet);
if (lookupPrintServices.length <= 0) {
throw new PrintException("Printer " + this.printerName + " not found");
}
this.print(null, null, false, lookupPrintServices[0], new HashPrintRequestAttributeSet(StringStandardPrinter.createJobName(getDocName())), true);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/DefaultTicketPrinter.java
19,6 → 19,7
import java.util.List;
 
public abstract class DefaultTicketPrinter implements TicketPrinter {
private String docName = "unknown doc";
protected List<String> strings = new ArrayList<String>();
protected List<Integer> modes = new ArrayList<Integer>();
 
36,11 → 37,16
}
 
@Override
public void clearBuffer() {
public void clearBuffer(final String docName) {
this.docName = docName;
this.strings.clear();
this.modes.clear();
}
 
public final String getDocName() {
return this.docName;
}
 
public static String formatLeft(int l, String string) {
if (string.length() > l) {
string = string.substring(0, l);
55,13 → 61,21
}
 
public static String formatRight(int l, String string) {
return format(l, string, false);
}
 
public static String formatCenter(int l, String string) {
return format(l, string, true);
}
 
private static String format(int l, String string, final boolean center) {
if (string.length() > l) {
string = string.substring(0, l);
return string.substring(0, l);
}
 
StringBuffer str = new StringBuffer(l);
 
final int stop = l - string.length();
final int stop = center ? (l - string.length()) / 2 : (l - string.length());
for (int i = 0; i < stop; i++) {
str.append(' ');
}
69,6 → 83,20
return str.toString();
}
 
public static String formatSides(int l, String s1, String s2) {
if (s1.length() + s2.length() > l) {
return s1.substring(0, l / 2) + s2.substring(0, l / 2);
}
final int spaceCount = l - (s1.length() + s2.length());
final StringBuilder sb = new StringBuilder(l);
sb.append(s1);
for (int i = 0; i < spaceCount; i++) {
sb.append(' ');
}
sb.append(s2);
return sb.toString();
}
 
public void addToBuffer(TicketLine line) {
final String style = line.getStyle();
final int mode;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/Printable.java
New file
0,0 → 1,18
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.sales.pos.io;
 
public interface Printable {
public void print(final TicketPrinter prt, final int ticketWidth);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/io/TicketPrinter.java
32,6 → 32,6
 
public void addToBuffer(TicketLine line);
 
public void clearBuffer();
public void clearBuffer(String docName);
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/POSConfiguration.java
21,6 → 21,7
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Client;
40,7 → 41,6
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
298,7 → 298,6
}
 
public final int importReceipts(final List<Ticket> tickets, final List<ReceiptEntry> entries) throws SQLException {
 
if (entries != null && entries.size() != tickets.size())
throw new IllegalArgumentException("Size mismatch");
 
685,12 → 684,19
 
}
 
public void print(Ticket ticket) {
public void print(Printable ticket) {
print(ticket, this.ticketPrinterConf1);
print(ticket, this.ticketPrinterConf2);
}
 
public void print(Ticket ticket, TicketPrinterConfiguration conf) {
public void printOnceOnFirstPrinter(Printable ticket) {
if (this.ticketPrinterConf1.isValid()) {
final TicketPrinter prt = this.ticketPrinterConf1.createTicketPrinter();
ticket.print(prt, this.ticketPrinterConf1.getTicketWidth());
}
}
 
public void print(Printable ticket, TicketPrinterConfiguration conf) {
if (conf.isValid() && conf.getCopyCount() > 0) {
final TicketPrinter prt = conf.createTicketPrinter();
for (int i = 0; i < conf.getCopyCount(); i++) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TextAreaTicketPrinter.java
16,16 → 16,21
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.TicketLine;
 
import javax.swing.JTextArea;
import java.awt.Font;
 
public class TextAreaTicketPrinter extends JTextArea implements TicketPrinter {
import javax.swing.JEditorPane;
 
public class TextAreaTicketPrinter extends JEditorPane implements TicketPrinter {
 
private String docName = "unknown doc";
private StringBuffer text = new StringBuffer();
private String retour = "\n";
private final String retour = "<br/>";
 
public TextAreaTicketPrinter() {
super();
this.setContentType("text/html");
this.setEditable(false);
this.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
}
 
@Override
40,10 → 45,24
final boolean barCode = mode == TicketPrinter.BARCODE;
if (barCode) {
this.text.append("* ");
} else if (mode == TicketPrinter.BOLD) {
this.text.append("<b>");
} else if (mode == TicketPrinter.BOLD_LARGE) {
this.text.append("<big>");
this.text.append("<b>");
} else if (mode == TicketPrinter.UNDERLINE) {
this.text.append("<u>");
}
this.text.append(t);
if (barCode) {
this.text.append(" *");
} else if (mode == TicketPrinter.BOLD) {
this.text.append("</b>");
} else if (mode == TicketPrinter.BOLD_LARGE) {
this.text.append("</b>");
this.text.append("</big>");
} else if (mode == TicketPrinter.UNDERLINE) {
this.text.append("</u>");
}
 
this.text.append(this.retour);
51,7 → 70,7
 
@Override
public void printBuffer() throws Exception {
setText(this.text.toString());
setText("<pre>" + this.text.toString() + "</pre>");
}
 
public void clear() {
70,7 → 89,12
}
 
@Override
public void clearBuffer() {
public void clearBuffer(final String docName) {
this.clear();
this.docName = docName;
}
 
public final String getDocName() {
return this.docName;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSearchPanel.java
49,6 → 49,7
public class ArticleSearchPanel extends JPanel implements ListSelectionListener, CaisseListener {
private final ScrollableList list;
private final CaisseControler controler;
private final JTextField textField = new JTextField();
 
public ArticleSearchPanel(final CaisseControler controler) {
this.controler = controler;
72,6 → 73,10
if (object instanceof Article) {
Article article = (Article) object;
ArticleSelector.paintArticle(f1, g, article, isSelected, posY, this.getWidth(), this.getCellHeight(), 36, 10);
if (Categorie.getFavoriteProducts().contains(article)) {
g.setColor(Color.ORANGE);
g.fillRect(0, posY, 6, this.getCellHeight());
}
} else if (object instanceof Categorie) {
Categorie c = (Categorie) object;
paintCategorie(f1, f2, g, c, isSelected, posY, this.getWidth(), this.getCellHeight());
78,6 → 83,22
 
}
}
 
@Override
public void mouseReleased(MouseEvent event) {
if ((event.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) {
final Object obj = getSelectedValue();
if (obj != null && obj instanceof Article) {
Article product = (Article) obj;
Categorie.toggleFavoriteState(product);
controler.saveFavoriteProductsIds(Categorie.getFavoriteProducts());
model.setFilter(textField.getText());
list.scrollToOffset(0);
}
} else {
super.mouseReleased(event);
}
}
};
 
// Bar
100,6 → 121,13
});
 
bar.setTitle("Articles");
bar.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
list.scrollToOffset(0);
}
});
 
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 2;
this.add(bar, c);
121,7 → 149,7
c.gridwidth = 1;
c.weightx = 0;
this.add(label, c);
final JTextField textField = new JTextField();
 
textField.setBorder(BorderFactory.createLineBorder(CaissePanel.DARK_BLUE, 1));
textField.setFont(f1);
c.weightx = 1;
144,6 → 172,7
@Override
public void changedUpdate(DocumentEvent e) {
model.setFilter(textField.getText());
controler.setArticleSelected(null);
}
});
list.addListSelectionListener(this);
250,9 → 279,10
 
@Override
public void caisseStateChanged() {
 
final Article articleSelected = controler.getArticleSelected();
System.err.println("ArticleSearchPanel.caisseStateChanged() article selected : " + articleSelected);
if (articleSelected == null) {
list.clearSelection();
return;
}
Object selectedValue = null;
261,9 → 291,11
} catch (Exception e) {
e.printStackTrace();
}
if (articleSelected != null && !articleSelected.equals(selectedValue)) {
list.setSelectedValue(articleSelected, true);
if (selectedValue == null || !articleSelected.equals(selectedValue)) {
boolean found = list.setSelectedValue(articleSelected, true);
if (!found) {
list.clearSelection();
}
 
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PriceEditorPanel.java
205,11 → 205,7
if (this.rHT.isSelected()) {
r = this.htTextField.getValue();
} else if (this.rTTC.isSelected()) {
final BigDecimal value = this.ttcTextField.getValue();
if (value != null)
r = Article.computePriceWithoutTax(value, this.article.getIdTaxe());
else
r = BigDecimal.ZERO;
r = Article.computePriceWithoutTax(this.ttcTextField.getValue(), this.article.getIdTaxe());
} else if (this.rDiscountPercent.isSelected()) {
r = this.article.getPriceWithoutTax().subtract(this.article.getPriceWithoutTax().multiply(this.discountPercentTextField.getValue().divide(new BigDecimal(100))));
} else if (this.rDiscount.isSelected()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseControler.java
27,10 → 27,15
import org.openconcerto.erp.core.sales.pos.model.RegisterLogEntry.ReceiptEntry;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.preferences.TemplateNXProps;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.Pair;
import org.openconcerto.utils.StringUtils;
 
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
38,7 → 43,9
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
 
94,6 → 101,10
this.setLCDDefaultDisplay(0);
}
 
public final CaisseFrame getCaisseFrame() {
return this.caisseFrame;
}
 
public Article getArticleSelected() {
return this.articleSelected;
}
326,15 → 337,12
return s;
}
 
public void setTicketDate() {
public Ticket saveAndClearTicket(final RegisterFiles files, final SQLElementDirectory dir) throws IOException, SQLException {
if (!this.isTicketValid())
return null;
this.t.setCreationCal(Calendar.getInstance());
}
 
public void saveAndClearTicket(final RegisterFiles files, final SQLElementDirectory dir) throws IOException, SQLException {
if (this.t.getTotalInCents() > 0) {
if (this.getPaidTotal() >= this.getTotal()) {
 
final String fileHash = this.t.save(files, dir);
final Ticket res = this.t;
final int newIndex = this.t.getNumber() + 1;
t = new Ticket(POSConfiguration.getInstance().getPosID(), newIndex, fileHash);
p1 = new Paiement(Paiement.ESPECES);
346,26 → 354,13
this.setPaiementSelected(null);
this.setArticleSelected(null);
client = Client.NONE;
return res;
}
}
}
 
public int getTicketNumber() {
return this.t.getNumber();
}
 
public void printTicket() {
if (this.t.getTotalInCents() > 0) {
if (this.getPaidTotal() >= this.getTotal()) {
POSConfiguration.getInstance().print(this.t);
} else {
System.err.println("Ticket not printed because not paid");
}
} else {
System.err.println("Ticket not printed total <= 0");
}
}
 
public void openDrawer() {
try {
final TicketPrinter prt = POSConfiguration.getInstance().getTicketPrinterConfiguration1().createTicketPrinter();
476,6 → 471,43
}
 
public boolean isTicketValid() {
return (this.t.getTotalInCents() > 0) && (this.getPaidTotal() >= this.getTotal());
return (!this.t.getArticles().isEmpty()) && (this.getPaidTotal() >= this.getTotal());
}
 
public Set<Integer> loadFavoriteProductsIds() {
final TemplateNXProps nxprops = (TemplateNXProps) TemplateNXProps.getInstance();
final File f = new File(nxprops.getDefaultStringValue(), "favorites.txt");
System.out.println("CaisseControler.saveFavoriteProductsIds() loading favorites from " + f.getAbsolutePath());
final Set<Integer> result = new HashSet<>();
if (f.exists()) {
try {
String s = FileUtils.read(f);
List<String> sIds = StringUtils.fastSplit(s, ',');
for (String string : sIds) {
if (!string.isEmpty()) {
result.add(Integer.parseInt(string));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
 
public void saveFavoriteProductsIds(List<Article> products) {
final TemplateNXProps nxprops = (TemplateNXProps) TemplateNXProps.getInstance();
final File f = new File(nxprops.getDefaultStringValue(), "favorites.txt");
System.out.println("CaisseControler.saveFavoriteProductsIds() saving favorites to " + f.getAbsolutePath());
try (FileOutputStream fOut = new FileOutputStream(f);) {
for (Article product : products) {
fOut.write(String.valueOf(product.getId()).getBytes());
fOut.write(',');
}
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/RegisterSummary.java
New file
0,0 → 1,166
/*
* 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.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.DefaultTicketPrinter;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
 
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.logging.Level;
 
abstract class RegisterSummary implements Printable {
 
private final String name;
private final RegisterLog log;
 
protected RegisterSummary(final String name, final RegisterLog log) {
super();
this.name = name;
this.log = log;
}
 
public boolean isPrintingTicketsList() {
return true;
}
 
public final RegisterLog getLog() {
return this.log;
}
 
public abstract String getLabel();
 
protected abstract List<Ticket> getReceipts() throws ParseException;
 
@Override
public void print(TicketPrinter prt, int ticketWidth) {
final DateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY à HH:mm:ss");
final String title = this.name + " de la caisse " + getLog().getRegisterID();
prt.clearBuffer(title);
try {
final List<Ticket> receipts = this.getReceipts();
 
final Map<Ticket, Map<String, BigDecimal>> typesByReceipt = new LinkedHashMap<>();
final Map<Ticket, BigDecimal> paidByReceipt = new LinkedHashMap<>();
final Map<Ticket, BigDecimal> valueByReceipt = new LinkedHashMap<>();
 
final Map<String, BigDecimal> totalByType = new TreeMap<>();
BigDecimal total = BigDecimal.ZERO;
BigDecimal totalPaid = BigDecimal.ZERO;
 
for (final Ticket t : receipts) {
final int receiptInCents = t.getTotalInCents();
final BigDecimal receiptValue = BigDecimal.valueOf(receiptInCents).movePointLeft(2);
 
BigDecimal receiptPaid = BigDecimal.ZERO;
final Map<String, BigDecimal> byType = new TreeMap<>();
for (final Paiement p : t.getPaiements()) {
final BigDecimal paid = BigDecimal.valueOf(p.getMontantInCents()).movePointLeft(2);
receiptPaid = receiptPaid.add(paid);
addInMap(byType, p.getTypeAsString(), paid);
addInMap(totalByType, p.getTypeAsString(), paid);
}
typesByReceipt.put(t, byType);
valueByReceipt.put(t, receiptValue);
paidByReceipt.put(t, receiptPaid);
total = total.add(receiptValue);
totalPaid = totalPaid.add(receiptPaid);
}
 
prt.addToBuffer(title, TicketPrinter.BOLD_LARGE);
prt.addToBuffer("");
prt.addToBuffer("Edité le " + dateFormat.format(new Date()));
final RegisterState registerState = getLog().getRegisterState();
prt.addToBuffer((registerState.getStatus() == Status.OPEN ? "Ouvert" : "Fermé") + " le " + registerState.formatDate(dateFormat));
prt.addToBuffer("");
prt.addToBuffer("");
prt.addToBuffer("Tickets de caisse", TicketPrinter.BOLD_LARGE);
prt.addToBuffer("");
 
Paiement espece = new Paiement(Paiement.ESPECES);
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Total des ventes", totalPaid.toPlainString()), TicketPrinter.BOLD);
for (final Entry<String, BigDecimal> e2 : totalByType.entrySet()) {
final String typePayment = e2.getKey();
if (typePayment.equals(espece.getTypeAsString())) {
BigDecimal value = e2.getValue();
BigDecimal rendu = totalPaid.subtract(total);
value = value.subtract(rendu);
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, " " + typePayment, value.toPlainString()));
} else {
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, " " + typePayment, e2.getValue().toPlainString()));
}
}
 
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Total des paiements", totalPaid.toPlainString()), TicketPrinter.BOLD);
for (final Entry<String, BigDecimal> e2 : totalByType.entrySet()) {
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, " " + e2.getKey(), e2.getValue().toPlainString()));
}
prt.addToBuffer("");
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Total rendu", totalPaid.subtract(total).toPlainString()), TicketPrinter.BOLD);
prt.addToBuffer("");
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Total TTC (Euros)", total.toPlainString()), TicketPrinter.BOLD);
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Nombre de tickets", "" + receipts.size()));
final long avg = receipts.isEmpty() ? 0 : total.movePointRight(2).longValueExact() / receipts.size();
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, "Panier moyen (Euros)", BigDecimal.valueOf(avg).movePointLeft(2).toPlainString()));
prt.addToBuffer("");
if (isPrintingTicketsList()) {
prt.addToBuffer("");
prt.addToBuffer("Liste des tickets", TicketPrinter.BOLD_LARGE);
prt.addToBuffer("");
for (final Entry<Ticket, Map<String, BigDecimal>> e : typesByReceipt.entrySet()) {
final Ticket t = e.getKey();
final BigDecimal receiptValue = valueByReceipt.get(t);
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, t.getCode(), receiptValue.toPlainString()), TicketPrinter.BOLD);
for (final Entry<String, BigDecimal> e2 : e.getValue().entrySet()) {
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, " " + e2.getKey(), e2.getValue().toPlainString()));
}
// rendu
final BigDecimal receiptChange = paidByReceipt.get(t).subtract(receiptValue);
if (receiptChange.signum() != 0)
prt.addToBuffer(DefaultTicketPrinter.formatSides(ticketWidth, " rendu", receiptChange.toPlainString()));
 
prt.addToBuffer("");
}
}
} catch (Exception e) {
POSConfiguration.getLogger().log(Level.WARNING, "Couldn't fill " + this.name, e);
prt.addToBuffer("Erreur");
}
try {
prt.printBuffer();
} catch (Exception e) {
POSConfiguration.getLogger().log(Level.WARNING, "Couldn't print " + this.name, e);
}
}
 
static private final <K> void addInMap(final Map<K, BigDecimal> m, final K key, final BigDecimal val) {
final BigDecimal prev = m.get(key);
m.put(key, prev == null ? val : prev.add(val));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketPanel.java
13,7 → 13,10
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.Pair;
 
24,8 → 27,11
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
 
import javax.swing.ImageIcon;
import javax.swing.JLabel;
38,6 → 44,9
import javax.swing.event.ListSelectionListener;
 
public class TicketPanel extends JPanel implements CaisseListener {
 
static private final DateFormat DF = new SimpleDateFormat("' le' EEEE d MMMM à H:mm:ss");
 
private final Image bg;
 
private final ListModel dataModel;
127,6 → 136,14
protected void paintComponent(final Graphics g) {
g.drawImage(this.bg, 0, 0, null);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
try {
g.setColor(Color.LIGHT_GRAY);
g.setFont(getFont().deriveFont(18.0f));
final RegisterState registerState = this.controler.getCaisseFrame().getFiles().getLastLog().getRegisterState();
g.drawString("Caisse " + (registerState.getStatus() == Status.OPEN ? "ouverte" : "fermée") + registerState.formatDate(DF), 20, this.getHeight() - 25);
} catch (Exception e) {
POSConfiguration.getLogger().log(Level.WARNING, "Couldn't find register state", e);
}
super.paintComponent(g);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseMenuPanel.java
14,20 → 14,24
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.JImage;
import org.openconcerto.utils.StringUtils;
 
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;
import java.util.logging.Level;
import java.io.File;
import java.io.IOException;
import java.util.List;
 
import javax.swing.JPanel;
 
51,7 → 55,61
final JImage image = new JImage(ComptaBasePropsConfiguration.class.getResource("logo.png"));
this.add(image, c);
c.gridx++;
File testTicketDir = new File("test");
if (testTicketDir.exists() && testTicketDir.isDirectory()) {
File[] files = testTicketDir.listFiles();
for (int i = 0; i < files.length; i++) {
final File f = files[i];
if (f.getName().endsWith(".txt")) {
final POSButton b = new POSButton(f.getName().substring(0, f.getName().length() - 4));
this.add(b, c);
c.gridy++;
b.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
System.err.println("CaisseMenuPanel.CaisseMenuPanel(...).new ActionListener() {...}.actionPerformed()");
POSConfiguration.getInstance().printOnceOnFirstPrinter(new Printable() {
 
@Override
public void print(TicketPrinter prt, int ticketWidth) {
prt.clearBuffer(f.getName());
System.err.println("CaisseMenuPanel.CaisseMenuPanel(...)print()");
String content = f.getName();
try {
content = FileUtils.read(f);
List<String> lines = StringUtils.splitIntoLines(content);
for (String line : lines) {
line = line.trim();
System.err.println("CaisseMenuPanel.CaisseMenuPanel(...)print()" + line);
if (line.startsWith("[bl]")) {
prt.addToBuffer(line.substring(3), TicketPrinter.BOLD_LARGE);
} else if (line.startsWith("[b]")) {
prt.addToBuffer(line.substring(3), TicketPrinter.BOLD);
} else {
prt.addToBuffer(line);
}
}
} catch (IOException e1) {
prt.addToBuffer(content);
prt.addToBuffer(e1.getMessage());
e1.printStackTrace();
}
try {
prt.printBuffer();
} catch (final Exception e) {
e.printStackTrace();
}
}
});
 
}
});
}
 
}
}
 
final POSButton bTickets = new POSButton("Liste des tickets");
this.add(bTickets, c);
c.gridy++;
76,12 → 134,34
}
}
});
 
bCloture.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
JPanel p = new JPanel();
p.setOpaque(true);
p.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.WEST;
c.weightx = 0;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20, 20, 30, 20);
c.gridwidth = 2;
p.add(new POSLabel("Voulez vous clôturer la caisse ?"), c);
c.gridy++;
c.gridwidth = 1;
POSButton bOkCloture = new POSButton("Clôturer");
bOkCloture.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
try {
 
final boolean quit = caisseFrame.getDB().fetchRegisterState().checkIfMoved();
if (!quit) {
frame.getControler().setLCD("Cloture", "En cours...", 0);
final int userID = POSConfiguration.getInstance().getUserID();
final RegisterLog newLog = caisseFrame.getFiles().close(userID);
88,12 → 168,33
caisseFrame.getDB().close(userID, newLog);
frame.getControler().setLCD("Cloture", "Terminee", 0);
// TODO lock down the UI until open again
}
quit();
} catch (Exception ex) {
ExceptionHandler.handle("Erreur", ex);
}
System.err.println("CLOTURE");
frame.showCaisse();
}
});
p.add(bOkCloture, c);
c.gridx++;
POSButton bCancelCloture = new POSButton("Annuler");
bCancelCloture.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
p.setVisible(false);
System.err.println("CANCEL CLOTURE");
frame.showCaisse();
}
});
p.add(bCancelCloture, c);
 
frame.showPanel(p);
}
});
 
bQuit.addActionListener(new ActionListener() {
 
@Override
109,22 → 210,8
}
 
private void quit() {
POSConfiguration.getLogger().log(Level.INFO, "User exit");
POSConfiguration.getInstance().closeConnexion();
// Fermeture
frame.getControler().setLCD(" CAISSE FERMEE ", "", 0);
frame.dispose();
Frame[] l = Frame.getFrames();
for (int i = 0; i < l.length; i++) {
Frame f = l[i];
System.err.println(f.getName() + " " + f + " Displayable: " + f.isDisplayable() + " Valid: " + f.isValid() + " Active: " + f.isActive());
}
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
if (!thread.isDaemon()) {
System.err.println(thread.getName() + " " + thread.getId() + " not daemon");
}
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PaiementPanel.java
390,13 → 390,13
}
controller.autoFillPaiement(p);
this.calculatorValue = TicketCellRenderer.centsToString(p.getMontantInCents());
 
if (p.getType() == Paiement.ESPECES) {
try {
controller.openDrawer();
} catch (Throwable ex) {
JOptionPane.showMessageDialog(PaiementPanel.this, "Ouverture du tiroir caisse impossible");
}
if (p.getType() == Paiement.CB) {
} else if (p.getType() == Paiement.CB) {
controller.sendCBRequest(p);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseFrame.java
39,6 → 39,7
 
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
49,6 → 50,7
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
89,7 → 91,6
}
 
public static void main(String[] args) {
ComptaPropsConfiguration.checkJava();
System.setProperty(SQLRowAccessor.ACCESS_DB_IF_NEEDED_PROP, "true");
try {
System.out.println("Lancement du module de caisse");
126,6 → 127,14
final int userID = POSConfiguration.getInstance().getUserID();
final RegisterFiles registerFiles = new RegisterFiles(POSConfiguration.getInstance().getRootDir(), true, POSConfiguration.getInstance().getPosID());
final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), POSConfiguration.getInstance().getPosID());
 
// check before changing any state
final boolean quit = registerDB.fetchRegisterState().checkIfMoved();
if (quit) {
quit();
return;
}
 
final RegisterState reconciledState = registerFiles.doWithLock(new ExnTransformer<RegisterFiles, RegisterState, IOException>() {
@Override
public RegisterState transformChecked(RegisterFiles input) throws IOException {
334,12 → 343,43
return remoteState;
}
 
static public void quit() {
POSConfiguration.getLogger().log(Level.INFO, "User exit");
POSConfiguration.getInstance().closeConnexion();
Frame[] l = Frame.getFrames();
for (int i = 0; i < l.length; i++) {
Frame f = l[i];
System.err.println(f.getName() + " " + f + " Displayable: " + f.isDisplayable() + " Valid: " + f.isValid() + " Active: " + f.isActive());
}
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
if (!thread.isDaemon()) {
System.err.println(thread.getName() + " " + thread.getId() + " not daemon");
}
}
}
 
@Override
public void dispose() {
quit();
// Fermeture
this.getControler().setLCD(" CAISSE FERMEE ", "", 0);
super.dispose();
}
 
public void showMenu() {
System.out.println("CaisseFrame.showMenu()");
this.invalidate();
final CaisseMenuPanel panel = new CaisseMenuPanel(this);
showPanel(panel);
this.getControler().setLCD("OpenConcerto", "Menu", 0);
 
final POSGlassPane glassPane2 = new POSGlassPane(panel, (getWidth() - panel.getPreferredSize().width) / 2, 100) {
}
 
public void showPanel(JPanel panel) {
this.invalidate();
final int x = (getWidth() - panel.getPreferredSize().width) / 2;
final int y = 100;
final POSGlassPane glassPane2 = new POSGlassPane(panel, x, y) {
@Override
public void mousePressed(MouseEvent e) {
Point containerPoint = SwingUtilities.convertPoint(this, e.getPoint(), panel);
355,8 → 395,6
this.getGlassPane().setVisible(true);
this.validate();
this.repaint();
this.getControler().setLCD("OpenConcerto", "Menu", 0);
 
}
 
public void showPriceEditor(Article article, CaisseControler caisseControler) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ListeDesTicketsPanel.java
15,7 → 15,14
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.TicketPrinterConfiguration;
import org.openconcerto.erp.core.sales.pos.io.DefaultTicketPrinter;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.ui.DefaultListModel;
import org.openconcerto.ui.touch.ScrollableList;
34,6 → 41,19
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
 
import javax.swing.JLabel;
import javax.swing.JList;
44,9 → 64,74
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
import org.jdom2.JDOMException;
 
public class ListeDesTicketsPanel extends JPanel implements ListSelectionListener {
 
private static final String ARIAL_FONT = "Arial";
 
static private final class X extends RegisterSummary {
 
private final List<Ticket> receipts;
 
protected X(final RegisterLog log, final List<Ticket> receipts) {
super("X", log);
this.receipts = receipts;
}
 
@Override
protected final List<Ticket> getReceipts() {
return this.receipts;
}
 
@Override
public String getLabel() {
return "Synthèse actuelle (X)";
}
}
 
static private final class XLite extends RegisterSummary {
 
private final List<Ticket> receipts;
 
protected XLite(final RegisterLog log, final List<Ticket> receipts) {
super("X", log);
this.receipts = receipts;
}
 
@Override
public boolean isPrintingTicketsList() {
return false;
}
 
@Override
protected final List<Ticket> getReceipts() {
return this.receipts;
}
 
@Override
public String getLabel() {
return "Synthèse actuelle simplifiée (résumé du X)";
}
}
 
static private final class Z extends RegisterSummary {
 
protected Z(final RegisterFiles files, final Calendar day) throws IOException, JDOMException {
super("Z", new RegisterLog(files.getLogFile(day)).parse());
}
 
@Override
protected final List<Ticket> getReceipts() throws ParseException {
return this.getLog().parseReceipts();
}
 
@Override
public String getLabel() {
return "Synthèse précédente (Z)";
}
}
 
private JList l;
private CaisseFrame frame;
 
83,9 → 168,20
c.weighty = 1;
c.gridheight = 2;
 
try {
final RegisterLog lastLog = this.frame.getFiles().getLastLog();
final List<Ticket> receipts = lastLog.parseReceipts();
ticketLlistModel = new DefaultListModel();
try {
ticketLlistModel.addAll(this.frame.getFiles().getLastLog().parseReceipts());
ticketLlistModel.addElement(new X(lastLog, receipts));
ticketLlistModel.addElement(new XLite(lastLog, receipts));
final Date previousDate = lastLog.getFirstRegisterEvent().getPreviousDate();
if (previousDate != null) {
final Calendar cal = Calendar.getInstance();
cal.setTime(previousDate);
ticketLlistModel.addElement(new Z(this.frame.getFiles(), cal));
}
ticketLlistModel.addAll(receipts);
 
} catch (Exception exn) {
ExceptionHandler.handle(this.frame, "Impossible de charger les tickets", exn);
}
112,6 → 208,7
g.setColor(Color.GRAY);
}
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (object instanceof Ticket) {
Ticket article = (Ticket) object;
String label = "Ticket " + article.getCode();
 
120,8 → 217,10
int wEuro = (int) g.getFontMetrics().getStringBounds(euro, g).getWidth();
g.drawString(label, 10, posY + 39);
g.drawString(euro, getWidth() - 5 - wEuro, posY + 39);
 
} else {
g.drawString(((RegisterSummary) object).getLabel(), 10, posY + 39);
}
}
};
this.add(ticketList, c);
// Ticket
199,7 → 298,7
Object selectedValue = ticketList.getSelectedValue();
int selectedIndex = l.getSelectedIndex();
if (selectedIndex == 0 && selectedValue != null) {
POSConfiguration.getInstance().print(((Ticket) selectedValue));
POSConfiguration.getInstance().printOnceOnFirstPrinter(((Printable) selectedValue));
}
l.clearSelection();
}
207,7 → 306,7
public void setSelectedTicket(Object selectedValue) {
ticketP.clear();
if (selectedValue != null) {
POSConfiguration.getInstance().print(((Ticket) selectedValue), new TicketPrinterConfiguration() {
POSConfiguration.getInstance().print(((Printable) selectedValue), new TicketPrinterConfiguration() {
@Override
public TicketPrinter createTicketPrinter() {
return ticketP;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSelector.java
130,8 → 130,13
 
}
});
 
comp.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
list.scrollToOffset(0);
}
});
}
 
@Override
public void valueChanged(ListSelectionEvent e) {
162,7 → 167,7
} catch (Exception e) {
e.printStackTrace();
}
if (articleSelected != null && !articleSelected.equals(selectedValue)) {
if (!articleSelected.equals(selectedValue)) {
Categorie c = articleSelected.getCategorie();
model.setCategorie(c);
list.setSelectedValue(articleSelected, true);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
16,6 → 16,8
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Categorie;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles.DifferentDayException;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLRow;
39,9 → 41,12
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.JOptionPane;
import javax.swing.JPanel;
135,24 → 140,32
 
@Override
public void actionPerformed(ActionEvent e) {
if (CaissePanel.this.controler.isTicketValid()) {
final Ticket savedReceipt;
try {
savedReceipt = CaissePanel.this.controler.saveAndClearTicket(caisseFrame.getFiles(), caisseFrame.getConf().getDirectory());
} catch (DifferentDayException ex) {
JOptionPane.showMessageDialog(CaissePanel.this, "Impossible de laisser la caisse ouverte plusieurs jours. Veuillez la clôturer pour pouvoir faire de nouveaux tickets.", "Erreur",
JOptionPane.ERROR_MESSAGE);
return;
} catch (Throwable ex) {
ExceptionHandler.handle(CaissePanel.this, "Erreur de sauvegarde des informations du ticket", ex);
return;
}
if (savedReceipt != null) {
// Valider
CaissePanel.this.controler.setTicketDate();
CaissePanel.this.controler.setLCD("Impression de", "votre ticket...", 0);
try {
CaissePanel.this.controler.printTicket();
POSConfiguration.getInstance().print(savedReceipt);
} catch (UnsatisfiedLinkError ex) {
JOptionPane.showMessageDialog(CaissePanel.this, "Erreur de configuration de la liaison à l'imprimante");
} catch (Throwable ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(CaissePanel.this, "Erreur d'impression du ticket");
}
try {
CaissePanel.this.controler.saveAndClearTicket(caisseFrame.getFiles(), caisseFrame.getConf().getDirectory());
} catch (Throwable ex) {
ExceptionHandler.handle("Erreur de sauvegardes des informations du ticket", ex);
}
 
CaissePanel.this.controler.setLCDDefaultDisplay(2);
}
 
}
});
bClients.addActionListener(new ActionListener() {
188,6 → 201,9
 
private void loadArticles(final SQLElementDirectory dir) {
 
final Set<Integer> favoriteProductsIds = controler.loadFavoriteProductsIds();
final List<Article> favoriteProducts = new ArrayList<>();
 
final Map<Integer, Categorie> categoriesMap = new HashMap<Integer, Categorie>();
 
SQLElement eltFam = dir.getElement("FAMILLE_ARTICLE");
196,6 → 212,7
final SQLSelect selFamille = new SQLSelect();
selFamille.addSelectStar(eltFam.getTable());
selFamille.addFieldOrder(eltFam.getTable().getField("CODE"));
 
for (SQLRow row : SQLRowListRSH.execute(selFamille)) {
// Map id -> Category
final Categorie cP = categoriesMap.get(row.getInt("ID_FAMILLE_ARTICLE_PERE"));
214,9 → 231,10
final SQLTable tableArticle = eltArticle.getTable();
selArticle.addAllSelect(tableArticle.getFields(VirtualFields.PRIMARY_KEY.union(VirtualFields.ARCHIVE)));
selArticle.addAllSelect(tableArticle, Arrays.asList("ID_FAMILLE_ARTICLE", "NOM", "CODE", "CODE_BARRE", "ID_TAXE", "PV_HT", "PV_TTC"));
selArticle.setWhere(new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE));
selArticle.setWhere(new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE).and(new Where(tableArticle.getField("MASQUE_CAISSE"), "=", Boolean.FALSE)));
 
final Categorie cUnclassified = new Categorie("Non classés", true);
cUnclassified.setUnknown();
for (SQLRow row : SQLRowListRSH.execute(selArticle)) {
final int idFamilleArticle = row.getInt("ID_FAMILLE_ARTICLE");
Categorie s1 = categoriesMap.get(idFamilleArticle);
234,10 → 252,15
a.setIdTaxe(row.getInt("ID_TAXE"));
a.setPriceWithoutTax(row.getBigDecimal("PV_HT"));
a.setPriceWithTax(row.getBigDecimal("PV_TTC"));
final Integer idProduct = a.getId();
if (favoriteProductsIds.contains(idProduct)) {
favoriteProducts.add(a);
}
}
 
}
}
Categorie.setFavoriteProducts(favoriteProducts);
}
 
@Override
public void paint(Graphics g) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/FilteredListModel.java
27,11 → 27,12
import javax.swing.SwingUtilities;
 
public class FilteredListModel extends AbstractListModel {
private final List<Object> items = new ArrayList<Object>();
private final Stack<String> searches = new Stack<String>();
Thread t;
private final List<Object> items = new ArrayList<>();
private final Stack<String> searches = new Stack<>();
private final Thread t;
 
FilteredListModel() {
public FilteredListModel() {
items.addAll(Categorie.getFavoriteProducts());
final List<Categorie> l = new ArrayList<Categorie>(Categorie.getAllCategories());
Collections.sort(l, new Comparator<Categorie>() {
 
103,6 → 104,7
@Override
public void run() {
items.clear();
items.addAll(Categorie.getFavoriteProducts());
items.addAll(newitems);
fireContentsChanged(this, 0, items.size());
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/TicketPrinterConfiguration.java
16,10 → 16,14
import org.openconcerto.erp.core.sales.pos.io.ESCSerialPrinter;
import org.openconcerto.erp.core.sales.pos.io.ESCStandardPrinter;
import org.openconcerto.erp.core.sales.pos.io.JPOSTicketPrinter;
import org.openconcerto.erp.core.sales.pos.io.StringStandardPrinter;
import org.openconcerto.erp.core.sales.pos.io.SwingPrinter;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
 
public class TicketPrinterConfiguration {
public static final String STANDARD_PRINTER = "std";
public static final String STANDARD_STRING_PRINTER = "stdString";
public static final String SWING_PRINTER = "swing";
public static final String SERIAL_PRINTER = "serial";
public static final String JPOS_PRINTER = "jpos";
private String type = STANDARD_PRINTER;
38,7 → 42,7
}
 
public void setType(String type) {
if (STANDARD_PRINTER.equals(type) || SERIAL_PRINTER.equals(type) || JPOS_PRINTER.equals(type)) {
if (STANDARD_PRINTER.equals(type) || STANDARD_STRING_PRINTER.equals(type) || SWING_PRINTER.equals(type) || SERIAL_PRINTER.equals(type) || JPOS_PRINTER.equals(type)) {
this.type = type;
} else {
throw new IllegalArgumentException("Unknown type " + type);
87,6 → 91,10
final TicketPrinter prt;
if (STANDARD_PRINTER.equals(getType())) {
prt = new ESCStandardPrinter(getName());
} else if (STANDARD_STRING_PRINTER.equals(getType())) {
prt = new StringStandardPrinter(getName());
} else if (SWING_PRINTER.equals(getType())) {
prt = new SwingPrinter(getName());
} else if (SERIAL_PRINTER.equals(getType())) {
prt = new ESCSerialPrinter(getName());
} else if (JPOS_PRINTER.equals(getType())) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Categorie.java
21,6 → 21,7
public class Categorie {
private static List<Categorie> topLevelCategories = new ArrayList<>();
private static List<Categorie> allCategories = new ArrayList<>();
private static List<Article> favoriteProducts = new ArrayList<>();
private String name;
// Sous catégories
private List<Categorie> l = new ArrayList<>();
27,6 → 28,7
// Articles dans cette categorie
private List<Article> articles = new ArrayList<>();
private Categorie parent;
private boolean isUnknown = false;
 
public Categorie(String string) {
this(string, false);
40,6 → 42,14
allCategories.add(this);
}
 
public void setUnknown() {
this.isUnknown = true;
}
 
public boolean isUnknown() {
return isUnknown;
}
 
@Override
public String toString() {
return name;
94,4 → 104,21
});
return result;
}
 
public static void setFavoriteProducts(List<Article> products) {
favoriteProducts = products;
}
 
public static List<Article> getFavoriteProducts() {
return favoriteProducts;
}
 
public static void toggleFavoriteState(Article product) {
if (favoriteProducts.contains(product)) {
favoriteProducts.remove(product);
} else {
favoriteProducts.add(product);
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Ticket.java
21,6 → 21,7
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.DefaultTicketPrinter;
import org.openconcerto.erp.core.sales.pos.io.Printable;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles.HashMode;
import org.openconcerto.erp.core.sales.pos.ui.TicketCellRenderer;
49,6 → 50,8
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
58,7 → 61,7
import org.jdom2.Document;
import org.jdom2.Element;
 
public class Ticket {
public class Ticket implements Printable {
 
private static final XMLDateFormat DATE_FMT = new XMLDateFormat();
 
340,11 → 343,12
});
}
 
@Override
public void print(final TicketPrinter prt, final int ticketWidth) {
final int maxWidth = ticketWidth;
final int MAX_PRICE_WIDTH = 8;
final int MAX_QTE_WIDTH = 5;
prt.clearBuffer();
prt.clearBuffer("receipt " + this.getCode());
final List<TicketLine> headers = POSConfiguration.getInstance().getHeaderLines();
for (final TicketLine line : headers) {
prt.addToBuffer(line);
355,9 → 359,39
final SimpleDateFormat df = new SimpleDateFormat("EEEE d MMMM yyyy à HH:mm", Locale.FRENCH);
prt.addToBuffer(DefaultTicketPrinter.formatRight(maxWidth, "Le " + df.format(getCreationDate())));
prt.addToBuffer("");
List<Pair<Article, Integer>> itemsToPrint = new ArrayList<>(this.items);
Collections.sort(itemsToPrint, new Comparator<Pair<Article, Integer>>() {
 
@Override
public int compare(Pair<Article, Integer> o1, Pair<Article, Integer> o2) {
final Article p1 = o1.getFirst();
final Article p2 = o2.getFirst();
final Categorie c1 = p1.getCategorie();
final Categorie c2 = p2.getCategorie();
if (c1.equals(c2)) {
return p1.getName().compareTo(p2.getName());
}
// Unknown first
if (c1.isUnknown()) {
return -1;
}
if (c2.isUnknown()) {
return 1;
}
// Sort by name
return c1.getName().compareTo(c2.getName());
}
});
Categorie currentCategorie = null;
for (final Pair<Article, Integer> item : this.items) {
final Article article = item.getFirst();
if (currentCategorie == null || !currentCategorie.equals(article.getCategorie())) {
// Print category name, except for unknown
currentCategorie = article.getCategorie();
if (!currentCategorie.isUnknown()) {
prt.addToBuffer(currentCategorie.getName(), TicketPrinter.BOLD);
}
}
final Integer nb = item.getSecond();
final Float tauxFromId = TaxeCache.getCache().getTauxFromId(article.getIdTaxe());
final BigDecimal tauxTVA = new BigDecimal(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterState.java
15,6 → 15,7
 
import org.openconcerto.utils.CompareUtils;
 
import java.text.Format;
import java.util.Date;
 
import net.jcip.annotations.Immutable;
88,6 → 89,10
return this.date.compareTo(cal);
}
 
public final String formatDate(final Format f) {
return f.format(this.date);
}
 
@Override
public int hashCode() {
final int prime = 31;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/DBState.java
13,13 → 13,27
package org.openconcerto.erp.core.sales.pos.model;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.SwingThreadUtils;
import org.openconcerto.utils.CollectionUtils;
 
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
 
import javax.swing.JOptionPane;
 
import net.jcip.annotations.Immutable;
 
/**
30,11 → 44,20
@Immutable
public final class DBState {
 
private static final Status getStatus(final SQLRowAccessor entry) {
final Status res = Status.valueOf(entry.getString("EVT"));
if (res != Status.OPEN && res != Status.CLOSED)
throw new IllegalStateException("Invalid status : " + res);
return res;
}
 
// used not for requests but for tables and paths
private final RegisterDB registerDB;
private final SQLRowValues registerVals;
private final SQLRowValues lastReceiptVals;
private final RegisterState registerState;
// first is the latest
private final List<SQLRowValues> lastEntries;
 
protected DBState(final RegisterDB registerDB, final SQLRowValues registerR) {
super();
43,6 → 66,7
if (this.getPosID() != registerDB.getPosID())
throw new IllegalArgumentException("Not same register");
this.lastReceiptVals = CollectionUtils.getSole(this.registerVals.getReferentRows(this.registerDB.getReceiptElement().getTable().getField("ID_CAISSE")));
this.lastEntries = Collections.unmodifiableList(new ArrayList<>(this.registerVals.getReferentRows(this.registerDB.getLogElement().getTable().getField("ID_CAISSE"))));
 
final SQLRowAccessor lastEntry = getLastEntry();
if (lastEntry == null) {
50,9 → 74,7
} else {
if (lastEntry.getForeignID("ID_CAISSE") != this.getPosID())
throw new IllegalStateException("Incoherent register IDs");
final Status status = Status.valueOf(lastEntry.getString("EVT"));
if (status != Status.OPEN && status != Status.CLOSED)
throw new IllegalStateException("Invalid status : " + status);
final Status status = getStatus(lastEntry);
this.registerState = new RegisterState(status, lastEntry.getDate("DATE").getTime());
}
}
69,14 → 91,37
return this.registerVals;
}
 
public final SQLRowValues getLastClosure() {
return this.registerVals.followPath(this.registerDB.getRegisterToLastClosureEntry().minusLast());
}
 
public final SQLRowValues getLastClosureEntry() {
return this.registerVals.followPath(this.registerDB.getRegisterToLastClosureEntry());
}
 
public final SQLRowValues getLastOpeningEntry() {
final List<SQLRowValues> entries = this.getLastEntries();
if (entries.isEmpty()) {
// never opened
assert !this.getRegisterState().hasDate();
return null;
} else if (getStatus(entries.get(0)).equals(Status.OPEN)) {
return entries.get(0);
} else if (entries.size() > 1 && getStatus(entries.get(1)).equals(Status.OPEN)) {
return entries.get(1);
} else {
throw new IllegalStateException("Two consecutive non-open entries : " + entries);
}
}
 
public final SQLRowValues getLastEntry() {
return (SQLRowValues) this.registerVals.getNonEmptyForeign("ID_DERNIERE_ENTREE_JOURNAL");
return CollectionUtils.getFirst(this.getLastEntries());
}
 
public final List<SQLRowValues> getLastEntries() {
return this.lastEntries;
}
 
public final SQLRowValues getLastReceiptRow() {
return this.lastReceiptVals;
}
86,7 → 131,54
return lastReceiptRow == null ? null : new ReceiptCode(lastReceiptRow.getString("NUMERO"));
}
 
public final SQLRowValues fillHostValues(final SQLRowValues logVals) {
logVals.put("HOST_NAME", PropsConfiguration.getHostname());
logVals.put("HOST_USER", System.getProperty("user.name"));
return logVals;
}
 
// initial values for entries created before this version
private static final Map<String, ?> NULL_VALUES = CollectionUtils.createMap("HOST_NAME", null, "HOST_USER", null);
 
/**
* Check if the register installation has moved and ask the user about it if it did. This can be
* called from outside the EDT.
*
* @return <code>true</code> if the user wants to quit.
* @throws InterruptedException if this thread was interrupted while waiting on the EDT.
* @throws ExecutionException if there was an error while asking the user.
*/
public final boolean checkIfMoved() throws InterruptedException, ExecutionException {
final SQLRowValues lastEntry = this.getLastEntry();
if (lastEntry == null) {
return false;
}
 
final Map<String, Object> currentValues = fillHostValues(new SQLRowValues(lastEntry.getTable())).getAbsolutelyAll();
final Map<String, Object> dbValues = lastEntry.getValues(currentValues.keySet());
if (dbValues.equals(currentValues) || NULL_VALUES.equals(dbValues)) {
return false;
} else {
final String message = TM.tr("register.moved", getPosID());
final String[] options = new String[] { TM.tr("register.moved.ignore"), TM.tr("register.moved.quit") };
final FutureTask<Boolean> askUserCallable = new FutureTask<>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// quit by default
final int ans = JOptionPane.showOptionDialog(null, message, TM.tr("register.moved.title"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
// CLOSED_OPTION also means quit, only clicking "ignore" means don't quit
return ans != 0;
}
});
SwingThreadUtils.invoke(askUserCallable);
final boolean quit = askUserCallable.get();
if (!quit)
POSConfiguration.getLogger().log(Level.WARNING, "User choose to ignore changed host,\nDB values : {0}\ncurrent values : {1}", new Object[] { dbValues, currentValues });
return quit;
}
}
 
@Override
public String toString() {
return this.getClass().getSimpleName() + " for register " + this.getPosID() + " in state " + this.getRegisterState();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterLog.java
43,8 → 43,16
REGISTER_OPENING, RECEIPT_CREATION, REGISTER_CLOSURE;
}
 
static private final int VERSION = 2;
static private final String VERSION_ATTR_NAME = "version";
 
static final Element createRootElement() {
return new Element("registerLog").setAttribute(VERSION_ATTR_NAME, String.valueOf(VERSION));
}
 
private final Path logFile;
private Document parsed;
private int version;
private RegisterEntry opening;
 
public RegisterLog(Path logFile) {
71,6 → 79,7
throw new IllegalStateException("Do not begin with " + EventType.REGISTER_OPENING + " : " + firstEntry);
this.opening = (RegisterEntry) firstEntry;
this.parsed = doc;
this.version = Integer.parseInt(doc.getRootElement().getAttributeValue(VERSION_ATTR_NAME, "1"));
return this;
}
 
78,6 → 87,10
return this.parsed;
}
 
public final int getVersion() {
return this.version;
}
 
public final RegisterLogEntry getLastEvent() throws ParseException {
return this.getEvent(-1);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterFiles.java
21,6 → 21,7
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.MessageDigestUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.TimeUtils;
import org.openconcerto.utils.cc.ExnTransformer;
import org.openconcerto.utils.checks.ValidState;
 
230,6 → 231,15
return dayDirToUse == null ? null : dayDirToUse.resolve(code.getFileName());
}
 
public final Path getLogFile(final Calendar day) throws IOException {
return getLogFile(getDayDir(day, false));
}
 
private final Path getLogFile(final Path dayDir) throws IOException {
final Path dayDirToUse = getDayDirToUse(dayDir);
return dayDirToUse == null ? null : dayDirToUse.resolve(LOG_FILENAME);
}
 
public final int getPosID() {
return this.posID;
}
305,9 → 315,9
 
private Path getLogToUse(final SortedSet<Path> sortedDays) throws IOException {
for (final Path dayDir : sortedDays) {
final Path dayDirToUse = getDayDirToUse(dayDir);
if (dayDirToUse != null)
return dayDirToUse.resolve(LOG_FILENAME);
final Path logFile = getLogFile(dayDir);
if (logFile != null)
return logFile;
}
return null;
}
315,9 → 325,9
public final List<Path> findLogFiles() throws IOException {
final List<Path> res = new ArrayList<>();
for (final Path dayDir : getSortedDays(true)) {
final Path dayDirToUse = getDayDirToUse(dayDir);
if (dayDirToUse != null)
res.add(dayDirToUse.resolve(LOG_FILENAME));
final Path logFile = getLogFile(dayDir);
if (logFile != null)
res.add(logFile);
}
return res;
}
366,8 → 376,10
POSConfiguration.checkRegisterID(input.getPosID(), registerDB.getPosID());
final RegisterLog lastLog = input.checkStatus(true);
final String lastLocalHash;
final Date prevDate;
if (lastLog == null) {
lastLocalHash = null;
prevDate = null;
} else {
try {
lastLocalHash = lastLog.getLastReceiptHash();
374,6 → 386,9
} catch (ParseException e) {
throw new IOException("Couldn't parse last receipt of log", e);
}
prevDate = lastLog.getFirstRegisterEvent().getDate();
if (lastLocalHash != null && prevDate == null)
throw new IOException("There's a receipt, but no previous closure date");
}
 
final DBState dbState;
406,8 → 421,8
FileUtils.rm_R(prevDir);
Files.createDirectory(stagingDir);
 
final Element rootElem = new Element("registerLog");
rootElem.addContent(new RegisterLogEntry.RegisterEntry(EventType.REGISTER_OPENING, cal.getTime(), userID, input.getPosID(), lastLocalHash).toXML());
final Element rootElem = RegisterLog.createRootElement();
rootElem.addContent(new RegisterLogEntry.RegisterEntry(EventType.REGISTER_OPENING, cal.getTime(), userID, input.getPosID(), lastLocalHash, prevDate).toXML());
save(new Document(rootElem), stagingDir.resolve(LOG_FILENAME));
 
Files.move(stagingDir, currentDir, StandardCopyOption.ATOMIC_MOVE);
507,7 → 522,7
}
// TODO verify that receipts' files match the log's content
final Document doc = lastLog.getDocument().clone();
doc.getRootElement().addContent(new RegisterLogEntry.RegisterEntry(EventType.REGISTER_CLOSURE, new Date(), userID, getPosID(), lastHash).toXML());
doc.getRootElement().addContent(new RegisterLogEntry.RegisterEntry(EventType.REGISTER_CLOSURE, new Date(), userID, getPosID(), lastHash, null).toXML());
save(doc, stagingDir.resolve(LOG_FILENAME));
return null;
}
524,6 → 539,12
});
}
 
public static final class DifferentDayException extends IllegalStateException {
protected DifferentDayException(final RegisterLog lastLog) {
super("Cannot save a receipt for a different day than the register opening : " + lastLog.getFirstRegisterEvent());
}
}
 
public final String save(final Ticket t) throws IOException, SQLException {
return this.doWithLock(new UpdateDir<String, String>("saving receipt") {
@Override
533,6 → 554,8
 
@Override
protected String updateDir(final Path stagingDir, final RegisterLog lastLog) throws IOException {
if (!TimeUtils.isSameDay(t.getCreationCal(), lastLog.getFirstRegisterEvent().getDate()))
throw new DifferentDayException(lastLog);
try {
final ReceiptEntry lastReceipt = lastLog.getLastReceiptCreationEvent();
final int expectedIndex;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterLogEntry.java
29,16 → 29,20
static private final String USER_ATTR_NAME = "userID";
static private final String REGISTER_ATTR_NAME = "registerID";
static private final String LAST_HASH_ATTR_NAME = "lastReceiptHash";
static private final String PREVIOUS_DATE_ATTR_NAME = "previousDate";
 
static private final RegisterEntry _parseEntry(final Element elem, final EventType evtType, final Date date) {
static private final RegisterEntry _parseEntry(final Element elem, final EventType evtType, final Date date) throws ParseException {
final String lastDateAttr = elem.getAttributeValue(PREVIOUS_DATE_ATTR_NAME);
final Date prevDate = lastDateAttr == null ? null : (Date) DATE_FMT.parseObject(lastDateAttr);
return new RegisterEntry(evtType, date, Integer.parseInt(elem.getAttributeValue(USER_ATTR_NAME)), Integer.parseInt(elem.getAttributeValue(REGISTER_ATTR_NAME)),
elem.getAttributeValue(LAST_HASH_ATTR_NAME));
elem.getAttributeValue(LAST_HASH_ATTR_NAME), prevDate);
}
 
private final int userID, registerID;
private final String lastReceiptHash;
private final Date previousDate;
 
public RegisterEntry(final EventType type, final Date date, final int userID, final int registerID, final String lastReceiptHash) {
public RegisterEntry(final EventType type, final Date date, final int userID, final int registerID, final String lastReceiptHash, final Date previousDate) {
super(type, date);
if (type != EventType.REGISTER_OPENING && type != EventType.REGISTER_CLOSURE)
throw new IllegalArgumentException("Wrong type : " + type);
45,6 → 49,7
this.userID = userID;
this.registerID = registerID;
this.lastReceiptHash = lastReceiptHash;
this.previousDate = previousDate;
}
 
public final String getLastReceiptHash() {
59,6 → 64,19
return this.registerID;
}
 
/**
* If this is {@link EventType#REGISTER_OPENING}, date of the previous opening. Useful to
* find the previous {@link RegisterFiles#getLogFile(java.util.Calendar) log}. Also makes
* sure that a log without any receipts can't just be deleted.
*
* @return the date of the previous event, <code>null</code> if
* {@link EventType#REGISTER_CLOSURE} or if {@link RegisterLog#getVersion() format
* version} 1.
*/
public final Date getPreviousDate() {
return this.previousDate;
}
 
@Override
protected void fillXML(Element res) {
res.setAttribute(USER_ATTR_NAME, String.valueOf(this.userID));
65,6 → 83,8
res.setAttribute(REGISTER_ATTR_NAME, String.valueOf(this.registerID));
if (this.lastReceiptHash != null)
res.setAttribute(LAST_HASH_ATTR_NAME, this.lastReceiptHash);
if (this.previousDate != null)
res.setAttribute(PREVIOUS_DATE_ATTR_NAME, DATE_FMT.format(this.previousDate));
}
 
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/RegisterDB.java
36,6 → 36,7
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.ProductInfo;
import org.openconcerto.utils.TimeUtils;
96,10 → 97,19
return fetchRegisterState(LockStrength.SHARE);
}
 
private final SQLSelect createMostRecentSelect(final SQLTable t, final int limit) {
final SQLSelect res = new SQLSelect();
res.addSelectStar(t);
res.setWhere(new Where(t.getField("ID_CAISSE"), "=", this.getPosID()));
res.addFieldOrder(t.getField("DATE"), Order.desc());
res.setLimit(limit);
res.setLockStrength(LockStrength.SHARE);
return res;
}
 
private final DBState fetchRegisterState(final LockStrength lockStrength) throws SQLException {
final SQLRowValues registerVals = new SQLRowValues(getRegisterTable());
registerVals.setAllToNull();
registerVals.putRowValues("ID_DERNIERE_ENTREE_JOURNAL").setAllToNull();
registerVals.assurePath(getRegisterToLastClosureEntry()).setAllToNull();
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(registerVals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
111,11 → 121,8
}
});
 
final SQLSelect selLastReceipt = new SQLSelect();
selLastReceipt.addSelectStar(this.receiptElem.getTable());
selLastReceipt.setWhere(new Where(this.receiptElem.getTable().getField("ID_CAISSE"), "=", this.getPosID()));
selLastReceipt.addFieldOrder(this.receiptElem.getTable().getField("DATE"), Order.desc());
selLastReceipt.setLimit(1);
final SQLSelect selLastReceipt = createMostRecentSelect(this.receiptElem.getTable(), 1);
final SQLSelect selLastEntries = createMostRecentSelect(this.getLogElement().getTable(), 3);
 
final SQLRowValues registerR = SQLUtils.executeAtomic(getRegisterTable().getDBSystemRoot().getDataSource(), new SQLFactory<SQLRowValues>() {
@Override
124,6 → 131,12
if (res == null)
throw new IllegalStateException("Register not found : " + getPosID());
 
final List<SQLRow> lastEntries = SQLRowListRSH.execute(selLastEntries);
for (final SQLRow r : lastEntries) {
final SQLRowValues vals = r.asRowValues();
vals.put("ID_CAISSE", res);
}
 
final List<SQLRow> receipts = SQLRowListRSH.execute(selLastReceipt);
if (receipts.size() == 1)
receipts.get(0).asRowValues().put("ID_CAISSE", res);
150,6 → 163,11
// E.g. if a work day starts 25/01 at 15h, even if the register is opened 26/01 at
// 01h then openDay is 25/01
final Date openDay = new Date();
 
final SQLRowValues lastOpeningEntry = fetchedState.getLastOpeningEntry();
if (lastOpeningEntry != null && TimeUtils.isSameDay(lastOpeningEntry.getDate("DATE"), openDay))
throw new IllegalStateException("The state to be created would be in the same day as the previous : " + lastOpeningEntry + " ; " + openDay);
 
// verifications OK, proceed to actually open
createUpdateVals(fetchedState, userID, Status.OPEN, openDay).commit();
 
172,7 → 190,7
throw new IllegalStateException("last DB receipt (" + lastDBHash + ") doesn't match last local receipt (" + lastLocalHash + ")");
}
 
private final void checkDate(final DBState fetchedState, final Date date, final boolean sameDayAllowed) {
private final void checkDate(final DBState fetchedState, final Date date) {
final SQLRowValues lastEntry = fetchedState.getLastEntry();
if (lastEntry == null)
return;
180,30 → 198,21
final Date previousEntryDate = previousEntryCal.getTime();
if (previousEntryDate.compareTo(date) >= 0)
throw new IllegalStateException("Previous date is after state to be created : " + previousEntryDate + " >= " + date);
if (!sameDayAllowed) {
final Calendar previousEntryDay = (Calendar) previousEntryCal.clone();
final Calendar newEntryDay = (Calendar) previousEntryCal.clone();
newEntryDay.clear();
newEntryDay.setTime(date);
TimeUtils.clearTime(previousEntryDay);
TimeUtils.clearTime(newEntryDay);
if (previousEntryDay.compareTo(newEntryDay) == 0)
throw new IllegalStateException("The state to be created would be in the same day as the previous : " + previousEntryDate + " ; " + date);
}
}
 
private final SQLRowValues createUpdateVals(final DBState fetchedState, final int userID, final Status newStatus, final Date date) {
checkDate(fetchedState, date, newStatus != Status.OPEN);
checkDate(fetchedState, date);
 
final SQLRowValues registerVals = new SQLRowValues(getRegisterTable());
registerVals.setPrimaryKey(fetchedState.getRegisterRow());
final SQLRowValues logVals = registerVals.putRowValues("ID_DERNIERE_ENTREE_JOURNAL");
logVals.put("ID_CAISSE", getPosID());
final SQLRowValues logVals = new SQLRowValues(getLogElement().getTable());
logVals.put("ID_CAISSE", registerVals);
logVals.put("DATE", date);
logVals.put("ID_USER", userID);
logVals.put("EVT", newStatus.name());
logVals.put("CREATOR", this.productInfo.getFullID());
logVals.put("CREATOR_VERSION", this.productInfo.getVersion());
fetchedState.fillHostValues(logVals);
return registerVals;
}
 
231,7 → 240,7
 
// actually close
final SQLRowValues registerVals = createUpdateVals(fetchedState, userID, Status.CLOSED, ourDate);
final SQLRowValues newLogEntry = (SQLRowValues) registerVals.getObject("ID_DERNIERE_ENTREE_JOURNAL");
final SQLRowValues newLogEntry = CollectionUtils.getSole(registerVals.getReferentRows(getLogElement().getTable()));
if (newLogEntry == null)
throw new IllegalStateException("Missing log entry in " + registerVals);
final SQLRowValues closureVals = registerVals.putRowValues("ID_DERNIERE_CLOTURE");
253,7 → 262,7
static SQLRowValues fillRow(final SQLRowValues closureVals, final List<ReceiptEntry> receiptEvents, final List<Ticket> receipts) {
BigDecimal totalTTC = BigDecimal.ZERO;
for (final Ticket t : receipts) {
totalTTC.add(BigDecimal.valueOf(t.getPaidTotal()).movePointLeft(2));
totalTTC = totalTTC.add(BigDecimal.valueOf(t.getPaidTotal()).movePointLeft(2));
}
closureVals.put("TOTAL_TTC", totalTTC);
if (!receiptEvents.isEmpty()) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/CheckIntegrity.java
19,11 → 19,13
import org.openconcerto.erp.core.sales.pos.model.RegisterLogEntry.ReceiptEntry;
import org.openconcerto.erp.core.sales.pos.model.RegisterLogEntry.RegisterEntry;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.sql.model.Order;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.TableRef;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.Value;
30,6 → 32,7
 
import java.io.IOException;
import java.nio.file.Path;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
45,10 → 48,12
final ComptaPropsConfiguration conf = posConf.createConnexion();
try {
for (final RegisterFiles files : RegisterFiles.scan(posConf.getRootDir())) {
checkRegisterFiles(conf, files);
final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), files.getPosID());
checkRegisterFiles(registerDB, files);
checkRegisterRow(registerDB, files);
}
System.out.println("\n\nAll done");
} catch (Exception e) {
} catch (Throwable e) {
e.printStackTrace();
} finally {
posConf.closeConnexion();
55,24 → 60,58
}
}
 
private static void checkRegisterFiles(final ComptaPropsConfiguration conf, final RegisterFiles files) throws IOException, JDOMException, ParseException {
final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), files.getPosID());
Value<RegisterLogEntry> lastEntry = Value.getNone();
private static void checkRegisterRow(final RegisterDB registerDB, final RegisterFiles files) throws IOException, JDOMException, ParseException, SQLException {
final RegisterState localRegisterState = files.getLastLog().getRegisterState();
final DBState dbState = registerDB.fetchRegisterState();
final RegisterState remoteRegisterState = dbState.getRegisterState();
if (!localRegisterState.equals(remoteRegisterState))
System.out.println("WARNING FS and DB state not equal (this may be fixed by launching the application) :\n" + localRegisterState + "\n" + remoteRegisterState);
 
final SQLTable logT = registerDB.getLogElement().getTable();
final SQLSelect sel = new SQLSelect();
sel.addSelect(logT.getKey());
setWhereAndOrder(sel, registerDB, logT);
final Number lastLogID = (Number) logT.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
final SQLRowValues registerLastEntry = dbState.getLastEntry();
final Number registerLastEntryID = registerLastEntry == null ? null : registerLastEntry.getIDNumber();
if (!Objects.equals(registerLastEntryID, lastLogID))
throw new IllegalStateException("Last log entry referenced by the register " + registerLastEntryID + " isn't the last in the log table " + lastLogID);
 
final SQLTable closureT = registerDB.getClosureElement().getTable();
final SQLSelect selClosure = new SQLSelect();
selClosure.addSelect(closureT.getKey());
final TableRef entryRef = selClosure.addJoin("INNER", closureT.getField("ID_ENTREE_JOURNAL")).getJoinedTable();
setWhereAndOrder(selClosure, registerDB, entryRef);
final Number lastClosureID = (Number) logT.getDBSystemRoot().getDataSource().executeScalar(selClosure.asString());
final SQLRowValues registerLastClosure = dbState.getLastClosure();
final Number registerLastClosureID = registerLastClosure == null ? null : registerLastClosure.getIDNumber();
if (!Objects.equals(registerLastClosureID, lastClosureID))
throw new IllegalStateException("Last closure referenced by the register " + registerLastClosureID + " isn't the last in its table " + lastClosureID);
}
 
private static void setWhereAndOrder(final SQLSelect sel, final RegisterDB registerDB, final TableRef entryRef) {
sel.setWhere(new Where(entryRef.getField("ID_CAISSE"), "=", registerDB.getPosID()));
sel.addFieldOrder(entryRef.getField("DATE"), Order.desc());
sel.setLimit(1);
}
 
private static void checkRegisterFiles(final RegisterDB registerDB, final RegisterFiles files) throws IOException, JDOMException, ParseException {
Value<RegisterLog> lastLog = Value.getNone();
for (final Path logFile : files.findLogFiles()) {
System.out.println("Checking " + logFile);
final RegisterLog log = new RegisterLog(logFile).parse();
try {
checkOneLog(files, lastEntry, log, registerDB);
checkOneLog(files, lastLog, log, registerDB);
System.out.println("OK for " + logFile);
} catch (Exception e) {
// keep checking other files
e.printStackTrace();
}
lastEntry = Value.getSome(log.getLastEvent());
lastLog = Value.getSome(log);
}
}
 
private static void checkOneLog(final RegisterFiles files, final Value<RegisterLogEntry> previousEntry, final RegisterLog log, final RegisterDB registerDB)
private static void checkOneLog(final RegisterFiles files, final Value<RegisterLog> previousLog, final RegisterLog log, final RegisterDB registerDB)
throws IOException, JDOMException, ParseException {
if (log.getFirstRegisterEvent().getRegisterID() != files.getPosID())
throw new IllegalStateException("Opening register ID mismatch");
80,10 → 119,11
 
Date cal;
// this checks this log is chained to the previous
if (previousEntry.hasValue()) {
if (previousEntry.getValue().getType() != EventType.REGISTER_CLOSURE)
if (previousLog.hasValue()) {
final RegisterLogEntry lastEntry = previousLog.getValue().getLastEvent();
if (lastEntry.getType() != EventType.REGISTER_CLOSURE)
throw new IllegalStateException("Previous log isn't closed");
final RegisterEntry previousLogClosure = (RegisterEntry) previousEntry.getValue();
final RegisterEntry previousLogClosure = (RegisterEntry) lastEntry;
if (!Objects.equals(previousLogClosure.getLastReceiptHash(), log.getFirstRegisterEvent().getLastReceiptHash()))
throw new IllegalStateException("Register opening hash mismatch, chain broken");
if (log.getFirstRegisterEvent().getDate().compareTo(previousLogClosure.getDate()) < 0)
92,6 → 132,15
} else {
cal = null;
}
final Date expectedPreviousDate;
// getPreviousDate() was added in version 2
if (log.getVersion() < 2 || !previousLog.hasValue()) {
expectedPreviousDate = null;
} else {
expectedPreviousDate = previousLog.getValue().getFirstRegisterEvent().getDate();
}
if (!Objects.equals(expectedPreviousDate, log.getFirstRegisterEvent().getPreviousDate()))
throw new IllegalStateException("Previous opening date of this log (" + log.getFirstRegisterEvent() + ") doesn't match the previous log " + expectedPreviousDate);
 
final List<ReceiptEntry> receiptEvents = log.getReceiptEvents();
 
110,11 → 159,16
final List<Ticket> receipts = log.parseReceipts();
// this checks the closure
if (log.getRegisterState().getStatus() == Status.CLOSED) {
// parseReceipts() has already checked that lastReceiptHash matches the receipt
final String lastReceiptHash = receipts.isEmpty() ? null : log.getLastReceiptCreationEvent().getFileHash();
final ReceiptEntry lastReceiptCreationEvent = log.getLastReceiptCreationEvent();
assert receipts.isEmpty() == (lastReceiptCreationEvent == null);
// parseReceipts() has already checked that lastReceiptCreationEvent.getFileHash()
// matches the receipt
// if there's no receipt in this log, opening and closure should match
// the opening has already been checked above to match the previous log
final String lastReceiptHash = receipts.isEmpty() ? log.getFirstRegisterEvent().getLastReceiptHash() : lastReceiptCreationEvent.getFileHash();
final RegisterEntry lastRegisterEvent = log.getLastRegisterEvent();
if (!CompareUtils.equals(lastRegisterEvent.getLastReceiptHash(), lastReceiptHash))
throw new IllegalStateException("Closure hash mismatch, recorded " + lastRegisterEvent.getLastReceiptHash() + " but was " + lastReceiptHash);
throw new IllegalStateException("Closure receipt hash mismatch, recorded " + lastRegisterEvent.getLastReceiptHash() + " but was " + lastReceiptHash);
if (lastRegisterEvent.getRegisterID() != files.getPosID())
throw new IllegalStateException("Closure register ID mismatch");
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Client.java
137,7 → 137,7
}
 
public void printCredit(TicketPrinter prt, int ticketWidth, BigDecimal amount, int paymentType, BigDecimal nouveauSolde) {
prt.clearBuffer();
prt.clearBuffer(this.getFullName() + " crédit");
List<TicketLine> headers = POSConfiguration.getInstance().getHeaderLines();
for (TicketLine line : headers) {
prt.addToBuffer(line);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/DepartementSQLElement.java
42,6 → 42,7
 
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("NUMERO");
l.add("NOM");
return l;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/SocieteJoinSQLElement.java
New file
0,0 → 1,39
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.common.element;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.sql.element.JoinSQLElement;
import org.openconcerto.sql.model.SQLTable;
 
public abstract class SocieteJoinSQLElement extends JoinSQLElement {
 
{
this.setL18nLocation(Gestion.class);
}
 
public SocieteJoinSQLElement(SQLTable table, final String... fieldsToOwner) {
super(table, fieldsToOwner);
}
 
@Override
protected String createCode() {
return createCodeFromPackage();
}
 
protected final String createCodeFromPackage() {
return SocieteSQLConfElement.createCodeFromPackage(SocieteSQLConfElement.getLastNonAbstractClass(this.getClass(), SocieteJoinSQLElement.class));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/NumerotationAutoSQLElement.java
294,7 → 294,7
return getNextForMonth(clazz, d, rowNum);
} else {
final String numberLabel = getLabelNumberFor(clazz);
if (rowNum.getObject(numberLabel) == null) {
if (rowNum.getObject(numberLabel) == null || rowNum.getString(getLabelFormatFor(clazz)) == null || rowNum.getString(getLabelFormatFor(clazz)).trim().length() == 0) {
return "";
}
String format = rowNum.getString(getLabelFormatFor(clazz));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/SocieteSQLConfElement.java
130,22 → 130,27
return createCodeFromPackage(getLastNonAbstractClass());
}
 
private final Class<? extends ComptaSQLConfElement> getLastNonAbstractClass() {
private final Class<? extends SocieteSQLConfElement> getLastNonAbstractClass() {
return getLastNonAbstractClass(this.getClass(), SocieteSQLConfElement.class);
}
 
static protected final <T extends SQLElement> Class<? extends T> getLastNonAbstractClass(final Class<? extends T> clazz, final Class<T> superClass) {
Class<?> prev = null;
Class<?> cl = this.getClass();
Class<?> cl = clazz;
// test loop
assert !Modifier.isAbstract(cl.getModifiers()) && ComptaSQLConfElement.class.isAssignableFrom(cl) && Modifier.isAbstract(ComptaSQLConfElement.class.getModifiers());
assert superClass.isAssignableFrom(cl);
if (Modifier.isAbstract(cl.getModifiers()))
throw new IllegalArgumentException("Class is abstract : " + cl);
if (!Modifier.isAbstract(superClass.getModifiers()))
throw new IllegalArgumentException("Superclass isn't abstract : " + superClass);
while (!Modifier.isAbstract(cl.getModifiers())) {
prev = cl;
cl = cl.getSuperclass();
}
assert ComptaSQLConfElement.class.isAssignableFrom(prev);
@SuppressWarnings("unchecked")
final Class<? extends ComptaSQLConfElement> res = (Class<? extends ComptaSQLConfElement>) prev;
return res;
return prev.asSubclass(superClass);
}
 
static protected String createCodeFromPackage(final Class<? extends ComptaSQLConfElement> cl) {
static protected String createCodeFromPackage(final Class<? extends SQLElement> cl) {
String canonicalName = cl.getName();
if (canonicalName.contains("erp.core") && canonicalName.contains(".element")) {
int i = canonicalName.indexOf("erp.core") + 9;
349,7 → 354,7
* Primary actions on the element (add/modify/remove)
*/
public List<TableAction> getPrimaryRowActions() {
final List<TableAction> actions = new ArrayList<TableAction>();
final List<TableAction> actions = new ArrayList<>(3);
actions.add(new TableAction(getAddAction()));
actions.add(new TableAction(getModifyAction()));
actions.add(new TableAction(getRemoveAction()));
360,8 → 365,7
* Secondary actions on the element (send by email, ..)
*/
public List<TableAction> getSecondaryRowActions() {
final List<TableAction> actions = new ArrayList<TableAction>(0);
return actions;
return new ArrayList<>(0);
}
 
public RowAction getAddAction() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/PreviewFrame.java
13,31 → 13,106
package org.openconcerto.erp.core.common.ui;
 
import org.openconcerto.erp.generationDoc.A4;
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
import org.openconcerto.erp.generationDoc.DefaultNXDocumentPrinter;
import org.openconcerto.erp.generationDoc.ODTPrinterNX;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.util.Arrays;
import java.util.List;
 
import javax.print.PrintService;
import javax.print.attribute.Attribute;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.Size2DSyntax;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.MediaSizeName;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
import org.jopendocument.model.OpenDocument;
import org.jopendocument.panel.ODSViewerPanel;
import org.jopendocument.print.DefaultXMLDocumentPrinter;
import org.jopendocument.print.ODTPrinterXML;
 
public class PreviewFrame extends JFrame {
 
private PreviewFrame(OpenDocument doc, String title) {
super(title);
this.setContentPane(new ODSViewerPanel(doc, new DefaultXMLDocumentPrinter()));
this.setContentPane(new ODSViewerPanel(doc, createDocumentPrinter()));
init();
}
 
public PreviewFrame(String title, String url, String odspXml) {
this.setContentPane(new ODSViewerPanel(url, odspXml, new DefaultXMLDocumentPrinter(), true));
this.setContentPane(new ODSViewerPanel(url, odspXml, createDocumentPrinter(), true));
this.setTitle(title);
init();
}
 
public DefaultXMLDocumentPrinter createDocumentPrinter() {
return new DefaultXMLDocumentPrinter() {
public void print(List<OpenDocument> documents) {
 
final double POINTS_PER_INCH = 72.0;
// Printer configuration
final PrinterJob printJob = PrinterJob.getPrinterJob();
 
final HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
// L'impression est forcée en A4, sur OpenSuse le format est en
// Letter par défaut alors que l'imprimante est en A4 dans le système
final MediaSizeName media = MediaSizeName.ISO_A4;
attributes.add(media);
Paper paper = new A4(0, 0);
 
final MediaPrintableArea printableArea = new MediaPrintableArea((float) (paper.getImageableX() / POINTS_PER_INCH), (float) (paper.getImageableY() / POINTS_PER_INCH),
(float) (paper.getImageableWidth() / POINTS_PER_INCH), (float) (paper.getImageableHeight() / POINTS_PER_INCH), Size2DSyntax.INCH);
attributes.add(printableArea);
attributes.add(new Copies(2));
// Print dialog
boolean okToPrint = printJob.printDialog(attributes);
final Attribute attribute = attributes.get(Copies.class);
if (attribute != null) {
final Copies attributeCopies = (Copies) attribute;
final int value = attributeCopies.getValue();
printJob.setCopies(value);
} else {
printJob.setCopies(1);
}
if (okToPrint) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
 
DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
printer.print(documents, printJob);
 
} catch (Exception e) {
ExceptionHandler.handle("Print error", e);
}
 
}
});
t.setName("PreviewFrame Print Thread");
t.setDaemon(true);
t.start();
}
 
}
 
};
 
}
 
private void init() {
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
this.setMaximizedBounds(ge.getMaximumWindowBounds());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/TotalCalculator.java
15,6 → 15,7
 
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
21,6 → 22,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.Tuple2;
 
37,7 → 39,7
private static String FIELD_SERVICE = "SERVICE";
private static String FIELD_POIDS = "T_POIDS";
private final String fieldHT, fieldHA, fieldDevise;
 
private boolean imputEcart = true;
private SQLRowAccessor rowDefaultCptProduit, rowDefaultCptService, rowDefaultCptTVACollecte, rowDefaultCptTVADeductible, rowDefaultCptAchat;
 
private SQLRowAccessor rowDefaultCptProduitStandard;
92,6 → 94,9
this.fieldHT = fieldHT;
final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
SQLPreferences prefs = SQLPreferences.getMemCached(tablePrefCompte.getDBRoot());
this.imputEcart = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.IMPUT_ECART, true);
 
// FIXME faire un fetcher pour ne pas faire 5 requetes (1 par getForeign)
// Comptes par défaut
this.rowDefaultCptService = rowPrefsCompte.getForeign("ID_COMPTE_PCE_VENTE_SERVICE");
228,7 → 233,10
addHT(ht, ht, tva, this.rowDefaultCptProduit, false);
}
 
private Map<Integer, SQLRowAccessor> mapTVA;
// Cache de TVA
private static Map<Integer, SQLRowAccessor> mapTVA;
private static long lastTVAfetchedTime = 0;
 
final SQLTable tvaTable = Configuration.getInstance().getRoot().findTable("TAXE");
final SQLTable compteTable = Configuration.getInstance().getRoot().findTable("COMPTE_PCE");
 
275,6 → 283,7
for (SQLRowValues sqlRowValues : rowValsList) {
mapTVA.put(sqlRowValues.getID(), sqlRowValues);
}
lastTVAfetchedTime = System.currentTimeMillis();
}
 
private void addHT(BigDecimal ht, BigDecimal htSansFacturable, SQLRowAccessor tva, SQLRowAccessor cptArticle, boolean selection) {
424,8 → 433,8
}
}
 
// TODO Ne pas fetcher la TVA pour chaque instance de TotalCalculator utiliser un cache
if (mapTVA == null) {
// TODO : generaliser le cache
if (mapTVA == null || lastTVAfetchedTime + 30 * 1000 < System.currentTimeMillis()) {
fetchTVA();
}
final SQLRowAccessor foreignTVA = rowAccessorLine.getForeign("ID_TAXE");
550,11 → 559,22
System.err.print("Ecarts: " + reste + "(HT:" + ht);
System.err.print(" TVA:" + tva);
System.err.println(" TTC:" + totalTTC2);
 
// TODO Check if row already exist in MAP ??
if (!this.imputEcart) {
for (SQLRowAccessor rHT : this.mapHt.keySet()) {
BigDecimal input = this.mapHt.get(rHT);
if (input != null && input.signum() != 0) {
this.mapHt.put(rHT, input.add(reste));
break;
}
}
} else {
SQLRow row = ComptePCESQLElement.getRow("758", "Ecarts arrondis");
// TODO Check if row already exist in MAP ??
this.mapHt.put(row, reste);
}
}
}
 
public BigDecimal getTotalDevise() {
return totalDevise;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractAchatArticleItemTable.java
112,6 → 112,7
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
final boolean showDmdAchat = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_DEMANDE_ACHAT, false);
this.supplierCode = prefs.getBoolean(GestionArticleGlobalPreferencePanel.SUPPLIER_PRODUCT_CODE, false);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
126,6 → 127,12
list.add(eNiveau);
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
SQLTableElement dmdElt = null;
if (showDmdAchat && e.getTable().contains("ID_DEMANDE_ACHAT_ELEMENT")) {
dmdElt = new SQLTableElement(e.getTable().getField("ID_DEMANDE_ACHAT_ELEMENT"));
list.add(dmdElt);
}
 
SQLTableElement tableElementCodeFournisseur = null;
 
if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
280,6 → 287,12
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
if (e.getTable().getFieldsName().contains("QTE_ORIGINE")) {
final SQLTableElement tableQteO = new SQLTableElement(e.getTable().getField("QTE_ORIGINE"));
tableQteO.setEditable(false);
list.add(tableQteO);
}
 
// Quantité
final SQLTableElement qteElement = new SQLTableElement(e.getTable().getField("QTE"), Integer.class) {
protected Object getDefaultNullValue() {
403,6 → 416,11
});
 
// Autocompletion
if (dmdElt != null) {
AutoCompletionManager dmd = new AutoCompletionManager(dmdElt, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("DEMANDE_ACHAT_ELEMENT.ID"), this.table,
this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker());
dmd.fill("ID_FAMILLE_ARTICLE", "ID_FAMILLE_ARTICLE");
}
List<String> completionFields = new ArrayList<String>();
if (e.getTable().getFieldsName().contains("INCOTERM")) {
completionFields.add("INCOTERM");
890,7 → 908,7
return result;
}
 
private Object tarifCompletion(SQLRow row, String field) {
public Object tarifCompletion(SQLRow row, String field) {
final SQLTable tTarifFournisseur = this.getSQLElement().getTable().getDBRoot().getTable("ARTICLE_TARIF_FOURNISSEUR");
 
if (row != null && !row.isUndefined() && field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") && tTarifFournisseur != null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/TotalPanel.java
573,7 → 573,9
}
}
}
rowValsPort.putRowValues("ID_ARTICLE").put("ID_COMPTE_PCE", rowDefaultCptPort.getID());
final SQLRowValues putRowValues = rowValsPort.putRowValues("ID_ARTICLE");
putRowValues.put("ID_COMPTE_PCE", rowDefaultCptPort.getID());
putRowValues.put("ID_COMPTE_PCE_ACHAT", rowDefaultCptPort.getID());
} else {
rowValsPort = null;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractAchatArticleItemTable.java.r23577
New file
0,0 → 1,1165
package ilm.erp.core.common.ui;
 
import ilm.erp.config.ComptaPropsConfiguration;
import ilm.erp.core.finance.accounting.model.CurrencyConverter;
import ilm.erp.core.finance.tax.model.TaxeCache;
import ilm.erp.core.sales.pos.io.BarcodeReader;
import ilm.erp.core.sales.pos.ui.BarcodeListener;
import ilm.erp.core.sales.product.element.ReferenceArticleSQLElement;
import ilm.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import ilm.erp.core.sales.product.ui.CurrencyWithSymbolRenderer;
import ilm.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import ilm.erp.preferences.DefaultNXProps;
import ilm.erp.preferences.GestionArticleGlobalPreferencePanel;
import ilm.sql.Configuration;
import ilm.sql.element.SQLElement;
import ilm.sql.model.FieldPath;
import ilm.sql.model.SQLRow;
import ilm.sql.model.SQLRowAccessor;
import ilm.sql.model.SQLRowListRSH;
import ilm.sql.model.SQLRowValues;
import ilm.sql.model.SQLSelect;
import ilm.sql.model.SQLTable;
import ilm.sql.model.UndefinedRowValuesCache;
import ilm.sql.model.Where;
import ilm.sql.model.graph.Path;
import ilm.sql.preferences.SQLPreferences;
import ilm.sql.sqlobject.ITextArticleWithCompletionCellEditor;
import ilm.sql.sqlobject.ITextWithCompletion;
import ilm.sql.view.list.AutoCompletionManager;
import ilm.sql.view.list.CellDynamicModifier;
import ilm.sql.view.list.RowValuesTable;
import ilm.sql.view.list.RowValuesTableModel;
import ilm.sql.view.list.SQLTableElement;
import ilm.sql.view.list.ValidStateChecker;
import ilm.utils.DecimalUtils;
import ilm.utils.Tuple3;
import ilm.utils.i18n.TranslationManager;
 
import java.awt.event.ActionEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
 
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellRenderer;
 
public abstract class AbstractAchatArticleItemTable extends AbstractArticleItemTable {
 
private AutoCompletionManager m;
private AutoCompletionManager m2, m3;
private AutoCompletionManager m4;
private final SQLTable tableArticle = getSQLElement().getTable().getTable("ARTICLE");
private SQLRowAccessor rowDevise;
private boolean supplierCode;
 
public AbstractAchatArticleItemTable() {
super();
}
 
@Override
protected void setModel(RowValuesTableModel model) {
super.setModel(model);
model.addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
 
calculTarifNomenclature();
 
}
});
}
 
protected void init() {
 
final SQLElement e = getSQLElement();
final SQLPreferences prefs = SQLPreferences.getMemCached(getSQLElement().getTable().getDBRoot());
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
this.supplierCode = prefs.getBoolean(GestionArticleGlobalPreferencePanel.SUPPLIER_PRODUCT_CODE, false);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
final SQLTableElement eNiveau = new SQLTableElement(e.getTable().getField("NIVEAU")) {
@Override
public void setValueFrom(SQLRowValues row, Object value) {
super.setValueFrom(row, value);
}
};
eNiveau.setRenderer(new NiveauTableCellRender());
eNiveau.setEditor(new NiveauTableCellEditor());
list.add(eNiveau);
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
SQLTableElement tableElementCodeFournisseur = null;
 
if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
tableElementCodeFournisseur = new SQLTableElement(e.getTable().getField("ID_CODE_FOURNISSEUR"), true, true, true);
list.add(tableElementCodeFournisseur);
}
 
SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementArticle);
 
if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
list.add(tableFamille);
}
 
if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
this.tableElementEcoID = new SQLTableElement(e.getTable().getField("ID_ECO_CONTRIBUTION"));
list.add(this.tableElementEcoID);
}
 
if (e.getTable().getFieldsName().contains("INCOTERM")) {
final SQLTableElement tableElementInco = new SQLTableElement(e.getTable().getField("INCOTERM"));
tableElementInco.setEditable(false);
list.add(tableElementInco);
}
 
if (e.getTable().getFieldsName().contains("PREBILAN")) {
final SQLTableElement tableElementPre = new SQLTableElement(e.getTable().getField("PREBILAN"), BigDecimal.class);
tableElementPre.setRenderer(new DeviseTableCellRenderer());
list.add(tableElementPre);
}
 
// Code article
final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"), String.class,
new ITextArticleWithCompletionCellEditor(e.getTable().getTable("ARTICLE"), e.getTable().getTable("ARTICLE_FOURNISSEUR"))) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementCode);
// Désignation de l'article
final SQLTableElement tableElementNom = new SQLTableElement(e.getTable().getField("NOM")) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementNom);
 
SQLTableElement tableCmdElt = null;
if (e.getTable().contains("ID_COMMANDE_ELEMENT")) {
tableCmdElt = new SQLTableElement(e.getTable().getField("ID_COMMANDE_ELEMENT"));
list.add(tableCmdElt);
}
 
if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
final SQLTableElement tableElementDesc = new SQLTableElement(e.getTable().getField("DESCRIPTIF"));
list.add(tableElementDesc);
}
if (e.getTable().getFieldsName().contains("COLORIS")) {
final SQLTableElement tableElementColoris = new SQLTableElement(e.getTable().getField("COLORIS"));
list.add(tableElementColoris);
}
// Valeur des métriques
final SQLTableElement tableElement_ValeurMetrique2 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_2"), Float.class);
list.add(tableElement_ValeurMetrique2);
final SQLTableElement tableElement_ValeurMetrique3 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_3"), Float.class);
list.add(tableElement_ValeurMetrique3);
final SQLTableElement tableElement_ValeurMetrique1 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_1"), Float.class);
list.add(tableElement_ValeurMetrique1);
// Prix d'achat HT de la métrique 1
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class);
tableElement_PrixMetrique1_AchatHT.setRenderer(new CurrencyWithSymbolRenderer());
list.add(tableElement_PrixMetrique1_AchatHT);
 
if (e.getTable().getFieldsName().contains("ECO_CONTRIBUTION")) {
this.tableElementEco = new SQLTableElement(e.getTable().getField("ECO_CONTRIBUTION"));
list.add(this.tableElementEco);
}
 
final SQLTableElement tableElement_Devise = new SQLTableElement(e.getTable().getField("ID_DEVISE"));
tableElement_Devise.setEditable(false);
final SQLTableElement tableElement_PA_Devise = new SQLTableElement(e.getTable().getField("PA_DEVISE"), BigDecimal.class);
Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
tableElement_PA_Devise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
// Devise
list.add(tableElement_Devise);
 
// Prix d'achat HT devise
list.add(tableElement_PA_Devise);
}
// Mode de vente
final SQLTableElement tableElement_ModeVente = new SQLTableElement(e.getTable().getField("ID_MODE_VENTE_ARTICLE"));
list.add(tableElement_ModeVente);
 
// Prix d'achat unitaire HT
this.ha = new SQLTableElement(e.getTable().getField("PA_HT"), BigDecimal.class);
this.ha.setRenderer(new CurrencyWithSymbolRenderer());
list.add(this.ha);
 
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
 
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
return false;
} else {
return super.isCellEditable(vals, rowIndex, columnIndex);
}
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
}
 
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
};
list.add(qteU);
 
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
// Quantité
final SQLTableElement qteElement = new SQLTableElement(e.getTable().getField("QTE"), Integer.class) {
protected Object getDefaultNullValue() {
return Integer.valueOf(0);
}
};
list.add(qteElement);
// TVA
this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(this.tableElementTVA);
// Poids piece
SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class);
list.add(tableElementPoids);
 
// Poids total
this.tableElementPoidsTotal = new SQLTableElement(e.getTable().getField("T_POIDS"), Float.class);
list.add(this.tableElementPoidsTotal);
 
// Service
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean b = Boolean.valueOf(val);
if (b != null && b.booleanValue()) {
this.service = new SQLTableElement(e.getTable().getField("SERVICE"), Boolean.class);
list.add(this.service);
}
 
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
// Prix d'achat HT devise
this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PA_DEVISE_T"), BigDecimal.class);
this.tableElementTotalDevise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
list.add(tableElementTotalDevise);
}
 
SQLTableElement tableElementRemise = null;
if (e.getTable().contains("POURCENT_REMISE")) {
tableElementRemise = new SQLTableElement(e.getTable().getField("POURCENT_REMISE"));
list.add(tableElementRemise);
}
 
if (e.getTable().getFieldsName().contains("T_ECO_CONTRIBUTION")) {
this.tableElementEcoTotal = new SQLTableElement(e.getTable().getField("T_ECO_CONTRIBUTION"));
list.add(this.tableElementEcoTotal);
}
 
// Total HT
this.totalHT = new SQLTableElement(e.getTable().getField("T_PA_HT"), BigDecimal.class);
this.totalHT.setRenderer(new DeviseTableCellRenderer());
this.totalHT.setEditable(false);
if (e.getTable().contains("POURCENT_REMISE") && tableElementRemise != null) {
tableElementRemise.addModificationListener(this.totalHT);
}
list.add(this.totalHT);
this.totalHA = this.totalHT;
// Total TTC
this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PA_TTC"), BigDecimal.class);
this.tableElementTotalTTC.setRenderer(new DeviseTableCellRenderer());
list.add(this.tableElementTotalTTC);
 
this.defaultRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(e.getTable()));
this.defaultRowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
this.defaultRowVals.put("CODE", "");
this.defaultRowVals.put("NOM", "");
this.defaultRowVals.put("QTE", 1);
this.defaultRowVals.put("QTE_UNITAIRE", BigDecimal.ONE);
this.defaultRowVals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
this.defaultRowVals.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("NOM"), false, this.defaultRowVals);
setModel(model);
 
this.table = new RowValuesTable(model, getConfigurationFile());
ToolTipManager.sharedInstance().unregisterComponent(this.table);
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
 
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
handlePopup(e);
}
 
@Override
public void mousePressed(MouseEvent e) {
handlePopup(e);
}
 
public void handlePopup(MouseEvent e) {
final int rowindex = table.getSelectedRow();
if (rowindex < 0)
return;
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
JPopupMenu popup = new JPopupMenu();
if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.CAN_EXPAND_NOMENCLATURE_HA, true)) {
popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expand")) {
 
@Override
public void actionPerformed(ActionEvent arg0) {
expandNomenclature(rowindex, m, EXPAND_TYPE.EXPAND);
}
});
popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expose")) {
 
@Override
public void actionPerformed(ActionEvent arg0) {
expandNomenclature(rowindex, m, EXPAND_TYPE.VIEW_ONLY);
}
});
popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.flat")) {
 
@Override
public void actionPerformed(ActionEvent arg0) {
expandNomenclature(rowindex, m, EXPAND_TYPE.FLAT);
}
});
}
for (AbstractAction action : getAdditionnalMouseAction(rowindex)) {
popup.add(action);
}
 
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
 
// Autocompletion
List<String> completionFields = new ArrayList<String>();
if (e.getTable().getFieldsName().contains("INCOTERM")) {
completionFields.add("INCOTERM");
}
if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
completionFields.add("ID_ECO_CONTRIBUTION");
}
completionFields.add("ID_UNITE_VENTE");
completionFields.add("PA_HT");
completionFields.add("PV_HT");
completionFields.add("POIDS");
completionFields.add("ID_TAXE");
completionFields.add("PRIX_METRIQUE_HA_1");
completionFields.add("PRIX_METRIQUE_HA_2");
completionFields.add("PRIX_METRIQUE_HA_3");
completionFields.add("VALEUR_METRIQUE_1");
completionFields.add("VALEUR_METRIQUE_2");
completionFields.add("VALEUR_METRIQUE_3");
completionFields.add("ID_MODE_VENTE_ARTICLE");
completionFields.add("PRIX_METRIQUE_VT_1");
completionFields.add("PRIX_METRIQUE_VT_2");
completionFields.add("PRIX_METRIQUE_VT_3");
completionFields.add("SERVICE");
completionFields.add("ID_DEVISE");
completionFields.add("PA_DEVISE");
if (e.getTable().getFieldsName().contains("COLORIS")) {
completionFields.add("COLORIS");
}
 
if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
completionFields.add("DESCRIPTIF");
}
if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
completionFields.add("ID_FAMILLE_ARTICLE");
}
 
this.m = new AutoCompletionManager(tableElementCode, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.CODE"), this.table,
this.table.getRowValuesTableModel()) {
@Override
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
}
};
m.fill("NOM", "NOM");
m.fill("ID", "ID_ARTICLE");
for (String string : completionFields) {
m.fill(string, string);
}
final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
final Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
m.setWhere(w);
 
this.m2 = new AutoCompletionManager(tableElementNom, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
this.table.getRowValuesTableModel()) {
@Override
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
}
};
m2.fill("CODE", "CODE");
m2.fill("ID", "ID_ARTICLE");
for (String string : completionFields) {
m2.fill(string, string);
}
m2.setWhere(w);
 
this.m3 = new AutoCompletionManager(tableElementArticle, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker()) {
@Override
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
}
};
m3.fill("CODE", "CODE");
m3.fill("NOM", "NOM");
for (String string : completionFields) {
m3.fill(string, string);
}
m3.setWhere(w);
 
if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
this.m4 = new AutoCompletionManager(tableElementCodeFournisseur, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker()) {
@Override
protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
Object res = tarifCompletion(row, field);
if (res == null) {
return super.getValueFrom(row, field, rowDest);
} else {
return res;
}
}
};
m4.fill("CODE", "CODE");
m4.fill("NOM", "NOM");
for (String string : completionFields) {
m4.fill(string, string);
}
}
 
tableElementCode.addModificationListener(tableElementArticle);
tableElementArticle.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
try {
SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
return foreign.getID();
} else {
return tableArticle.getUndefinedID();
}
} catch (Exception e) {
return tableArticle.getUndefinedID();
}
}
});
 
// ECO Contribution
if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
qteElement.addModificationListener(this.tableElementEcoTotal);
this.tableElementEco.addModificationListener(this.tableElementEcoTotal);
this.tableElementEcoTotal.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
 
int qte = Integer.parseInt(row.getObject("QTE").toString());
BigDecimal f = (row.getObject("ECO_CONTRIBUTION") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("ECO_CONTRIBUTION");
return f.multiply(new BigDecimal(qte));
}
 
});
this.tableElementEcoID.addModificationListener(this.tableElementEco);
this.tableElementEco.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
 
if (source.equals(tableElementEcoID)) {
return row.getForeign("ID_ECO_CONTRIBUTION").getBigDecimal("TAUX");
} else {
return row.getObject("ECO_CONTRIBUTION");
}
}
});
}
 
// Calcul automatique du total HT
qteElement.addModificationListener(this.totalHT);
qteU.addModificationListener(this.totalHT);
this.ha.addModificationListener(this.totalHT);
this.totalHT.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
 
int qte = Integer.parseInt(row.getObject("QTE").toString());
BigDecimal f = (row.getObject("PA_HT") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PA_HT");
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte)), DecimalUtils.HIGH_PRECISION).setScale(totalHT.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
 
if (row.getTable().contains("POURCENT_REMISE")) {
final Object o2 = row.getObject("POURCENT_REMISE");
 
BigDecimal lremise = (o2 == null) ? BigDecimal.ZERO : ((BigDecimal) o2);
if (lremise.compareTo(BigDecimal.ZERO) >= 0 && lremise.compareTo(BigDecimal.valueOf(100)) < 0) {
 
r = r.multiply(new BigDecimal(100).subtract(lremise).movePointLeft(2)).setScale(totalHT.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
}
}
 
return r;
}
 
});
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
 
if (tableElement_PA_Devise != null) {
tableElement_PA_Devise.addModificationListener(tableElement_PrixMetrique1_AchatHT);
}
 
if (tableElement_PA_Devise != null) {
tableElement_PrixMetrique1_AchatHT.addModificationListener(tableElement_PA_Devise);
 
tableElement_PA_Devise.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
if (source != null && source.getField().getName().equals("PA_DEVISE")) {
return row.getObject("PA_DEVISE");
} else {
if (!row.isForeignEmpty("ID_DEVISE") && row.getForeign("ID_DEVISE") != null) {
String devCode = row.getForeign("ID_DEVISE").getString("CODE");
BigDecimal bigDecimal = (BigDecimal) row.getObject("PRIX_METRIQUE_HA_1");
 
CurrencyConverter c = new CurrencyConverter();
BigDecimal result = convert(bigDecimal, devCode, true);
if (result == null) {
JOptionPane.showMessageDialog(AbstractAchatArticleItemTable.this, "Unable to convert " + bigDecimal + " from " + c.getCompanyCurrencyCode() + " to " + devCode);
return BigDecimal.ZERO;
}
return result;
} else if (source != null && source.getField().getName().equalsIgnoreCase("PRIX_METRIQUE_HA_1")) {
return row.getObject("PRIX_METRIQUE_HA_1");
}
return row.getObject("PA_DEVISE");
}
}
 
});
}
 
qteElement.addModificationListener(this.tableElementTotalDevise);
qteU.addModificationListener(this.tableElementTotalDevise);
tableElement_PA_Devise.addModificationListener(this.tableElementTotalDevise);
if (e.getTable().contains("POURCENT_REMISE") && tableElementRemise != null) {
tableElementRemise.addModificationListener(this.tableElementTotalDevise);
}
this.tableElementTotalDevise.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
int qte = Integer.parseInt(row.getObject("QTE").toString());
BigDecimal f = (BigDecimal) row.getObject("PA_DEVISE");
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte)), DecimalUtils.HIGH_PRECISION).setScale(tableElementTotalDevise.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
 
if (row.getTable().contains("POURCENT_REMISE")) {
final Object o2 = row.getObject("POURCENT_REMISE");
BigDecimal lremise = (o2 == null) ? BigDecimal.ZERO : ((BigDecimal) o2);
if (lremise.compareTo(BigDecimal.ZERO) >= 0 && lremise.compareTo(BigDecimal.valueOf(100)) < 0) {
 
r = r.multiply(new BigDecimal(100).subtract(lremise).movePointLeft(2)).setScale(tableElementTotalDevise.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
}
}
return r;
}
 
});
}
// Calcul automatique du total TTC
qteElement.addModificationListener(this.tableElementTotalTTC);
qteU.addModificationListener(this.tableElementTotalTTC);
this.ha.addModificationListener(this.tableElementTotalTTC);
this.tableElementTVA.addModificationListener(this.tableElementTotalTTC);
this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
@Override
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
int qte = Integer.parseInt(row.getObject("QTE").toString());
BigDecimal f = (BigDecimal) row.getObject("PA_HT");
int idTaux = Integer.parseInt(row.getObject("ID_TAXE").toString());
if (idTaux < 0) {
System.out.println(row);
}
Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
 
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION).setScale(tableElementTotalTTC.getDecimalDigits(),
BigDecimal.ROUND_HALF_UP);
float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
 
BigDecimal total = r.multiply(BigDecimal.ONE.add(new BigDecimal(taux / 100f))).setScale(tableElementTotalTTC.getDecimalDigits(), RoundingMode.HALF_UP);
return total;
}
 
});
 
this.table.readState();
 
// Mode Gestion article avancé
String valModeAvanceVt = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
Boolean bModeAvance = Boolean.valueOf(valModeAvanceVt);
boolean view = !(bModeAvance != null && !bModeAvance.booleanValue());
setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_1"), view);
setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_2"), view);
setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_3"), view);
setColumnVisible(model.getColumnForField("PRIX_METRIQUE_VT_1"), view);
setColumnVisible(model.getColumnForField("ID_MODE_VENTE_ARTICLE"), view);
setColumnVisible(model.getColumnForField("PA_HT"), view);
 
if (e.getTable().contains("ID_COMMANDE_ELEMENT")) {
setColumnVisible(model.getColumnForField("ID_COMMANDE_ELEMENT"), false);
}
 
// Gestion des unités de vente
final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
setColumnVisible(model.getColumnForField("QTE_UNITAIRE"), gestionUV);
setColumnVisible(model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
 
setColumnVisible(model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", true));
 
if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
setColumnVisible(model.getColumnForField("ID_ECO_CONTRIBUTION"), showEco);
setColumnVisible(model.getColumnForField("ECO_CONTRIBUTION"), showEco);
setColumnVisible(model.getColumnForField("T_ECO_CONTRIBUTION"), showEco);
}
 
setColumnVisible(model.getColumnForField("ID_ARTICLE"), selectArticle);
setColumnVisible(model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
setColumnVisible(model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
 
// Calcul automatique du poids unitaire
tableElement_ValeurMetrique1.addModificationListener(tableElementPoids);
tableElement_ValeurMetrique2.addModificationListener(tableElementPoids);
tableElement_ValeurMetrique3.addModificationListener(tableElementPoids);
tableElementPoids.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
return new Float(ReferenceArticleSQLElement.getPoidsFromDetails(row));
}
 
});
// Calcul automatique du poids total
tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
qteElement.addModificationListener(this.tableElementPoidsTotal);
qteU.addModificationListener(this.tableElementPoidsTotal);
this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
 
Number f = (row.getObject("POIDS") == null) ? 0 : (Number) row.getObject("POIDS");
int qte = Integer.parseInt(row.getObject("QTE").toString());
 
BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
// FIXME convertir en float autrement pour éviter une valeur non transposable
// avec floatValue ou passer POIDS en bigDecimal
return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
}
 
});
 
tableElement_PrixMetrique1_AchatHT.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
if (source != null && source.getField().getName().equals("PRIX_METRIQUE_HA_1")) {
return row.getObject("PRIX_METRIQUE_HA_1");
} else {
if (source != null && source.getField().getName().equals("PA_DEVISE")) {
if (!row.isForeignEmpty("ID_DEVISE") && row.getForeign("ID_DEVISE") != null) {
String devCode = row.getForeign("ID_DEVISE").getString("CODE");
BigDecimal bigDecimal = (BigDecimal) row.getObject("PA_DEVISE");
 
return convert(bigDecimal, devCode, false);
} else {
return row.getObject("PRIX_METRIQUE_HA_1");
}
}
return row.getObject("PRIX_METRIQUE_HA_1");
}
}
 
});
 
// Calcul automatique du prix d'achat unitaire HT
tableElement_ValeurMetrique1.addModificationListener(this.ha);
tableElement_ValeurMetrique2.addModificationListener(this.ha);
tableElement_ValeurMetrique3.addModificationListener(this.ha);
tableElement_PrixMetrique1_AchatHT.addModificationListener(this.ha);
this.ha.setModifier(new CellDynamicModifier() {
public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
 
if (row.isForeignEmpty("ID_MODE_VENTE_ARTICLE") || row.getInt("ID_MODE_VENTE_ARTICLE") == ReferenceArticleSQLElement.A_LA_PIECE) {
return row.getObject("PRIX_METRIQUE_HA_1");
} else {
 
final BigDecimal prixHAFromDetails = ReferenceArticleSQLElement.getPrixHAFromDetails(row);
return prixHAFromDetails.setScale(ha.getDecimalDigits(), RoundingMode.HALF_UP);
}
 
}
 
});
 
uniteVente.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 {
return row.getObject("QTE_UNITAIRE");
}
}
 
});
// La devise est renseignée globalement dans la commande et est reportée automatiquement sur
// les lignes
setColumnVisible(model.getColumnIndexForElement(tableElement_Devise), false);
for (String string : visibilityMap.keySet()) {
setColumnVisible(model.getColumnForField(string), visibilityMap.get(string));
}
 
// Barcode reader
final BarcodeReader barcodeReader = ComptaPropsConfiguration.getInstanceCompta().getBarcodeReader();
if (barcodeReader != null) {
 
final BarcodeListener l = new BarcodeListener() {
 
@Override
public void keyReceived(KeyEvent ee) {
// TODO Auto-generated method stub
}
 
@Override
public void barcodeRead(String code) {
if (((JFrame) SwingUtilities.getRoot(getRowValuesTable())).isActive()) {
final SQLSelect selArticle = new SQLSelect();
final SQLTable tableArticle = getSQLElement().getForeignElement("ID_ARTICLE").getTable();
selArticle.addSelectStar(tableArticle);
Where w = new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
w = w.and(new Where(tableArticle.getField("CODE_BARRE"), "=", code));
selArticle.setWhere(w);
List<SQLRow> l2 = SQLRowListRSH.execute(selArticle);
if (l2.size() > 0) {
System.err.println("ARTICLE " + l2.get(0).getString("NOM"));
Tuple3<Double, String, String> art = Tuple3.create(1.0D, l2.get(0).getString("CODE"), l2.get(0).getString("NOM"));
List<Tuple3<Double, String, String>> l = new ArrayList<Tuple3<Double, String, String>>();
l.add(art);
insertFromDrop(l, m);
} else {
System.err.println("ARTICLE NOT FOUND !");
}
}
 
}
};
getRowValuesTable().addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0)
if (getRowValuesTable().isDisplayable()) {
barcodeReader.addBarcodeListener(l);
} else {
barcodeReader.removeBarcodeListener(l);
}
}
});
 
}
 
// On réécrit la configuration au cas ou les preferences aurait changé
this.table.writeState();
}
 
private static Map<String, Boolean> visibilityMap = new HashMap<String, Boolean>();
 
public static Map<String, Boolean> getVisibilityMap() {
return visibilityMap;
}
 
private String incoterm = "";
 
public void setIncoterms(String incoterm) {
if (incoterm == null) {
incoterm = "";
}
this.incoterm = incoterm;
}
 
private SQLRow rowFournisseur = null;
 
public void setFournisseur(SQLRow rowFournisseur) {
this.rowFournisseur = rowFournisseur;
if (getSQLElement().getTable().contains("ID_CODE_FOURNISSEUR") && this.supplierCode) {
 
if (rowFournisseur != null && !rowFournisseur.isUndefined()) {
Where w = new Where(getSQLElement().getTable().getTable("CODE_FOURNISSEUR").getField("ID_FOURNISSEUR"), "=", rowFournisseur.getID());
this.m4.setWhere(w);
} else {
this.m4.setWhere(null);
}
}
}
 
private BigDecimal getPrice(final SQLRowAccessor r, List<String> list) {
BigDecimal result = r.getBigDecimal(list.get(0));
 
for (int i = 1; i < list.size(); i++) {
BigDecimal m0 = r.getBigDecimal(list.get(i));
if (m0 != null && m0.floatValue() > 0) {
result = result.divide(m0, 2, RoundingMode.HALF_UP);
}
}
return result;
}
 
private Object tarifCompletion(SQLRow row, String field) {
final SQLTable tTarifFournisseur = this.getSQLElement().getTable().getDBRoot().getTable("ARTICLE_TARIF_FOURNISSEUR");
 
if (row != null && !row.isUndefined() && field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") && tTarifFournisseur != null) {
List<String> incoTerms;
 
if (this.incoterm != null && this.incoterm.equalsIgnoreCase("CPT")) {
incoTerms = Arrays.asList("PRIX_ACHAT", "COEF_TRANSPORT_PORT");
} else if (this.incoterm != null && this.incoterm.equalsIgnoreCase("DDP")) {
incoTerms = Arrays.asList("PRIX_ACHAT", "COEF_TRANSPORT_PORT", "COEF_TAXE_D");
} else {
incoTerms = Arrays.asList("PRIX_ACHAT");
}
List<SQLRow> rows = row.getReferentRows(tTarifFournisseur);
if (row.getBoolean("AUTO_PRIX_ACHAT_NOMENCLATURE")) {
 
List<SQLRow> rowsElt = row.getReferentRows(row.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
BigDecimal price = BigDecimal.ZERO;
final Set<String> tarifNotFound = new HashSet<String>();
for (SQLRow sqlRow : rowsElt) {
List<SQLRow> rowsT = sqlRow.getForeign("ID_ARTICLE").getReferentRows(tTarifFournisseur);
 
boolean priceFound = false;
boolean tarifFound = false;
if (rowsT.size() > 0) {
BigDecimal min = BigDecimal.ZERO;
 
BigDecimal defaultPrice = BigDecimal.ZERO;
Calendar c = null;
for (SQLRow sqlRowT : rowsT) {
if (this.rowFournisseur != null && this.rowFournisseur.getID() == sqlRowT.getForeignID("ID_FOURNISSEUR")) {
BigDecimal priceT = getPrice(sqlRowT, incoTerms);
defaultPrice = priceT;
final Calendar datePrice = sqlRowT.getDate("DATE_PRIX");
datePrice.set(Calendar.HOUR, 0);
datePrice.set(Calendar.MINUTE, 0);
datePrice.set(Calendar.SECOND, 0);
datePrice.set(Calendar.MILLISECOND, 0);
if (datePrice == null || (this.getDateDevise() != null && !this.getDateDevise().before(datePrice.getTime()))) {
if (c == null || c.before(datePrice)) {
 
min = priceT;
c = datePrice;
priceFound = true;
} else if (c != null) {
defaultPrice = priceT;
}
}
tarifFound = true;
}
}
 
if (priceFound) {
price = price.add(min.multiply(sqlRow.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRow.getInt("QTE"), DecimalUtils.HIGH_PRECISION))));
} else {
price = price.add(defaultPrice.multiply(sqlRow.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRow.getInt("QTE"), DecimalUtils.HIGH_PRECISION))));
}
}
if (!tarifFound) {
tarifNotFound.add(sqlRow.getForeign("ID_ARTICLE").getString("CODE"));
}
}
if (!tarifNotFound.isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
JOptionPane.showMessageDialog(AbstractAchatArticleItemTable.this.table,
"Attention, impossible de calculer le tarif.\nLes articles suivants n'ont pas de tarif associé :\n" + tarifNotFound);
}
});
}
return price;
} else if (!rows.isEmpty()) {
BigDecimal min = BigDecimal.ZERO;
Calendar c = null;
for (SQLRow sqlRow : rows) {
if (this.rowFournisseur != null && this.rowFournisseur.getID() == sqlRow.getForeignID("ID_FOURNISSEUR")) {
BigDecimal price = getPrice(sqlRow, incoTerms);
final Calendar datePrice = sqlRow.getDate("DATE_PRIX");
if (datePrice == null || (this.getDateDevise() != null && !this.getDateDevise().before(datePrice.getTime()))) {
if (c == null || c.before(datePrice)) {
min = price;
c = datePrice;
}
}
}
}
return min.setScale(2, RoundingMode.HALF_UP);
}
}
if (field.equalsIgnoreCase("INCOTERM")) {
// if (tTarifFournisseur != null) {
// List<SQLRow> rows = row.getReferentRows(tTarifFournisseur);
// if (!rows.isEmpty()) {
// final SQLRow sqlRow0 = rows.get(0);
// return sqlRow0.getString("CONDITIONS");
// }
// }
return this.incoterm;
}
 
if (getDevise() != null && !getDevise().isUndefined()) {
if ((field.equalsIgnoreCase("ID_DEVISE") || field.equalsIgnoreCase("ID_DEVISE_HA"))) {
return getDevise().getID();
} else if ((field.equalsIgnoreCase("PA_DEVISE"))) {
if (row.getBigDecimal("PA_DEVISE") != null && row.getBigDecimal("PA_DEVISE").signum() != 0 && this.incoterm.length() == 0) {
return row.getBigDecimal("PA_DEVISE");
} else {
String devCode = getDevise().getString("CODE");
 
BigDecimal tarifCompletion = (BigDecimal) tarifCompletion(row, "PRIX_METRIQUE_HA_1");
if (tarifCompletion == null) {
tarifCompletion = row.getBigDecimal("PRIX_METRIQUE_HA_1");
}
if (tarifCompletion == null) {
return null;
} else {
// Remove set scale 2 --> if scale ex : PA = 95.74MAD --> 0.76592€
// with Scale 0.77€ so put 96.25MAD in PA
return convert(tarifCompletion, devCode, true);
}
}
 
}
} else {
if ((field.equalsIgnoreCase("ID_DEVISE") || field.equalsIgnoreCase("ID_DEVISE_HA"))) {
return Configuration.getInstance().getDirectory().getElement("DEVISE").getTable().getUndefinedID();
} else if ((field.equalsIgnoreCase("PA_DEVISE"))) {
 
return BigDecimal.ZERO;
}
}
return null;
 
}
 
@Override
protected void refreshDeviseAmount() {
int count = getRowValuesTable().getRowCount();
final int columnForField = getRowValuesTable().getRowValuesTableModel().getColumnForField("PA_DEVISE");
if (columnForField >= 0) {
SQLTableElement eltDevise = getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(columnForField);
for (int i = 0; i < count; i++) {
SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
// getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getObject("PV_U_DEVISE"),
// i, "PV_U_DEVISE", true);
eltDevise.setValueFrom(rowVals, rowVals.getObject("PA_DEVISE"));
getRowValuesTable().getRowValuesTableModel().fireTableChanged(new TableModelEvent(getRowValuesTable().getRowValuesTableModel(), i, i, columnForField));
}
}
}
 
public SQLRowAccessor getDevise() {
return this.rowDevise;
}
 
public void setDevise(SQLRowAccessor deviseRow) {
this.rowDevise = deviseRow;
if (deviseRow == null) {
getDefaultRowValues().put("ID_DEVISE", null);
} else {
getDefaultRowValues().put("ID_DEVISE", this.rowDevise.getID());
}
}
 
private BigDecimal tauxConversion = null;
 
public void setTauxConversion(BigDecimal tauxConversion) {
if (tauxConversion != null && tauxConversion.signum() == 0) {
tauxConversion = null;
}
this.tauxConversion = tauxConversion;
refreshDeviseAmount();
}
 
public BigDecimal convert(BigDecimal val, String devCode, boolean fromCompanyCurrency) {
if (val == null) {
return val;
}
if (this.tauxConversion == null) {
CurrencyConverter c = new CurrencyConverter();
if (fromCompanyCurrency) {
return c.convert(val, c.getCompanyCurrencyCode(), devCode, getDateDevise(), isUsedBiasedDevise());
} else {
return c.convert(val, devCode, c.getCompanyCurrencyCode(), getDateDevise(), isUsedBiasedDevise());
}
} else {
if (fromCompanyCurrency) {
return val.divide(this.tauxConversion, DecimalUtils.HIGH_PRECISION).setScale(val.scale(), RoundingMode.HALF_UP);
} else {
return val.multiply(this.tauxConversion, DecimalUtils.HIGH_PRECISION).setScale(val.scale(), RoundingMode.HALF_UP);
}
}
}
 
public void setFournisseurFilterOnCompletion(SQLRow row) {
final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
if (row != null && !row.isUndefined()) {
w = w.and(new Where(this.tableArticle.getField("ID_FOURNISSEUR"), "=", row.getID()));
}
this.m.setWhere(w);
this.m2.setWhere(w);
this.m3.setWhere(w);
}
 
private void insertFromDrop(List<Tuple3<Double, String, String>> articles, AutoCompletionManager m) {
 
List<String> code = new ArrayList<String>(articles.size());
for (int i = articles.size() - 1; i >= 0; i--) {
 
Tuple3<Double, String, String> tuple = articles.get(i);
code.add(tuple.get1());
}
 
int rowCount = getRowValuesTable().getRowValuesTableModel().getRowCount();
Map<Integer, Integer> mapRows = new HashMap<Integer, Integer>();
for (int i = 0; i < rowCount; i++) {
SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
if (rowVals.getObject("ID_ARTICLE") != null && !rowVals.isForeignEmpty("ID_ARTICLE")) {
mapRows.put(rowVals.getForeignID("ID_ARTICLE"), i);
}
}
 
SQLSelect sel = new SQLSelect();
final SQLTable articleTable = getSQLElement().getTable().getForeignTable("ID_ARTICLE");
sel.addSelectStar(articleTable);
sel.setWhere(new Where(articleTable.getField("CODE"), code));
List<SQLRow> matchCode = SQLRowListRSH.execute(sel);
Map<String, SQLRow> mapCode = new HashMap<String, SQLRow>();
for (SQLRow sqlRow : matchCode) {
mapCode.put(sqlRow.getString("CODE"), sqlRow);
}
Set<String> fieldsFrom = m.getFieldsFrom();
fieldsFrom.remove("POURCENT_REMISE");
for (int i = articles.size() - 1; i >= 0; i--) {
 
Tuple3<Double, String, String> tuple = articles.get(i);
 
SQLRow article = mapCode.get(tuple.get1());
if (article != null && mapRows.containsKey(article.getID())) {
Integer index = mapRows.get(article.getID());
SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(index);
getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getInt("QTE") + 1, index, "QTE");
} else {
final SQLRowValues row2Insert = new SQLRowValues(getRowValuesTable().getRowValuesTableModel().getDefaultRowValues());
 
// Completion depuis l'article trouvé
if (article != null) {
m.fillRowValues(article, fieldsFrom, row2Insert);
// Fill prix total
row2Insert.put("ID_ARTICLE", article.getID());
row2Insert.put("CODE", article.getObject("CODE"));
row2Insert.put("NOM", article.getObject("NOM"));
} else {
row2Insert.put("CODE", tuple.get1());
row2Insert.put("NOM", tuple.get2());
}
 
row2Insert.put("QTE", Math.round(tuple.get0().floatValue()));
 
row2Insert.put("PA_HT", row2Insert.getObject("PRIX_METRIQUE_HA_1"));
//
final BigDecimal resultTotalHT = row2Insert.getBigDecimal("PA_HT").multiply(new BigDecimal(row2Insert.getInt("QTE")));
row2Insert.put("T_PA_HT", resultTotalHT);
 
Float resultTaux = TaxeCache.getCache().getTauxFromId(row2Insert.getForeignID("ID_TAXE"));
 
if (resultTaux == null) {
SQLRow rowTax = TaxeCache.getCache().getFirstTaxe();
resultTaux = rowTax.getFloat("TAUX");
}
 
float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
 
BigDecimal r = resultTotalHT.multiply(BigDecimal.valueOf(taux).movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
 
row2Insert.put("T_PA_TTC", r);
// row2Insert.put("ID_STYLE", allStyleByName.get("Composant"));
getRowValuesTable().getRowValuesTableModel().addRowAt(0, row2Insert);
}
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/AbstractAchatArticleItemTable.java.r23597
New file
0,0 → 1,1175
package ilm.erp.core.common.ui;
 
import ilm.erp.config.ComptaPropsConfiguration;
import ilm.erp.core.finance.accounting.model.CurrencyConverter;
import ilm.erp.core.finance.tax.model.TaxeCache;
import ilm.erp.core.sales.pos.io.BarcodeReader;
import ilm.erp.core.sales.pos.ui.BarcodeListener;
import ilm.erp.core.sales.product.element.ReferenceArticleSQLElement;
import ilm.erp.core.sales.product.element.UniteVenteArticleSQLElement;
import ilm.erp.core.sales.product.ui.CurrencyWithSymbolRenderer;
import ilm.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
import ilm.erp.preferences.DefaultNXProps;
import ilm.erp.preferences.GestionArticleGlobalPreferencePanel;
import ilm.sql.Configuration;
import ilm.sql.element.SQLElement;
import ilm.sql.model.FieldPath;
import ilm.sql.model.SQLRow;
import ilm.sql.model.SQLRowAccessor;
import ilm.sql.model.SQLRowListRSH;
import ilm.sql.model.SQLRowValues;
import ilm.sql.model.SQLSelect;
import ilm.sql.model.SQLTable;
import ilm.sql.model.UndefinedRowValuesCache;
import ilm.sql.model.Where;
import ilm.sql.model.graph.Path;
import ilm.sql.preferences.SQLPreferences;
import ilm.sql.sqlobject.ITextArticleWithCompletionCellEditor;
import ilm.sql.sqlobject.ITextWithCompletion;
import ilm.sql.view.list.AutoCompletionManager;
import ilm.sql.view.list.CellDynamicModifier;
import ilm.sql.view.list.RowValuesTable;
import ilm.sql.view.list.RowValuesTableModel;
import ilm.sql.view.list.SQLTableElement;
import ilm.sql.view.list.ValidStateChecker;
import ilm.utils.DecimalUtils;
import ilm.utils.Tuple3;
import ilm.utils.i18n.TranslationManager;
 
import java.awt.event.ActionEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
 
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellRenderer;
 
public abstract class AbstractAchatArticleItemTable extends AbstractArticleItemTable {
 
private AutoCompletionManager m;
private AutoCompletionManager m2, m3;
private AutoCompletionManager m4;
private final SQLTable tableArticle = getSQLElement().getTable().getTable("ARTICLE");
private SQLRowAccessor rowDevise;
private boolean supplierCode;
 
public AbstractAchatArticleItemTable() {
super();
}
 
@Override
protected void setModel(RowValuesTableModel model) {
super.setModel(model);
model.addTableModelListener(new TableModelListener() {
 
@Override
public void tableChanged(TableModelEvent e) {
 
calculTarifNomenclature();
 
}
});
}
 
protected void init() {
 
final SQLElement e = getSQLElement();
final SQLPreferences prefs = SQLPreferences.getMemCached(getSQLElement().getTable().getDBRoot());
final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
final boolean showDmdAchat = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_DEMANDE_ACHAT, false);
this.supplierCode = prefs.getBoolean(GestionArticleGlobalPreferencePanel.SUPPLIER_PRODUCT_CODE, false);
 
final List<SQLTableElement> list = new Vector<SQLTableElement>();
final SQLTableElement eNiveau = new SQLTableElement(e.getTable().getField("NIVEAU")) {
@Override
public void setValueFrom(SQLRowValues row, Object value) {
super.setValueFrom(row, value);
}
};
eNiveau.setRenderer(new NiveauTableCellRender());
eNiveau.setEditor(new NiveauTableCellEditor());
list.add(eNiveau);
list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
 
if (showDmdAchat && e.getTable().contains("ID_DEMANDE_ACHAT_ELEMENT")) {
list.add(new SQLTableElement(e.getTable().getField("ID_DEMANDE_ACHAT_ELEMENT")));
}
 
SQLTableElement tableElementCodeFournisseur = null;
 
if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
tableElementCodeFournisseur = new SQLTableElement(e.getTable().getField("ID_CODE_FOURNISSEUR"), true, true, true);
list.add(tableElementCodeFournisseur);
}
 
SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementArticle);
 
if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
list.add(tableFamille);
}
 
if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
this.tableElementEcoID = new SQLTableElement(e.getTable().getField("ID_ECO_CONTRIBUTION"));
list.add(this.tableElementEcoID);
}
 
if (e.getTable().getFieldsName().contains("INCOTERM")) {
final SQLTableElement tableElementInco = new SQLTableElement(e.getTable().getField("INCOTERM"));
tableElementInco.setEditable(false);
list.add(tableElementInco);
}
 
if (e.getTable().getFieldsName().contains("PREBILAN")) {
final SQLTableElement tableElementPre = new SQLTableElement(e.getTable().getField("PREBILAN"), BigDecimal.class);
tableElementPre.setRenderer(new DeviseTableCellRenderer());
list.add(tableElementPre);
}
 
// Code article
final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"), String.class,
new ITextArticleWithCompletionCellEditor(e.getTable().getTable("ARTICLE"), e.getTable().getTable("ARTICLE_FOURNISSEUR"))) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementCode);
// Désignation de l'article
final SQLTableElement tableElementNom = new SQLTableElement(e.getTable().getField("NOM")) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
return b && noCmdElt;
} else {
return b;
}
 
}
};
list.add(tableElementNom);
 
SQLTableElement tableCmdElt = null;
if (e.getTable().contains("ID_COMMANDE_ELEMENT")) {
tableCmdElt = new SQLTableElement(e.getTable().getField("ID_COMMANDE_ELEMENT"));
list.add(tableCmdElt);
}
 
if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
final SQLTableElement tableElementDesc = new SQLTableElement(e.getTable().getField("DESCRIPTIF"));
list.add(tableElementDesc);
}
if (e.getTable().getFieldsName().contains("COLORIS")) {
final SQLTableElement tableElementColoris = new SQLTableElement(e.getTable().getField("COLORIS"));
list.add(tableElementColoris);
}
// Valeur des métriques
final SQLTableElement tableElement_ValeurMetrique2 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_2"), Float.class);
list.add(tableElement_ValeurMetrique2);
final SQLTableElement tableElement_ValeurMetrique3 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_3"), Float.class);
list.add(tableElement_ValeurMetrique3);
final SQLTableElement tableElement_ValeurMetrique1 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_1"), Float.class);
list.add(tableElement_ValeurMetrique1);
// Prix d'achat HT de la métrique 1
final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class);
tableElement_PrixMetrique1_AchatHT.setRenderer(new CurrencyWithSymbolRenderer());
list.add(tableElement_PrixMetrique1_AchatHT);
 
if (e.getTable().getFieldsName().contains("ECO_CONTRIBUTION")) {
this.tableElementEco = new SQLTableElement(e.getTable().getField("ECO_CONTRIBUTION"));
list.add(this.tableElementEco);
}
 
final SQLTableElement tableElement_Devise = new SQLTableElement(e.getTable().getField("ID_DEVISE"));
tableElement_Devise.setEditable(false);
final SQLTableElement tableElement_PA_Devise = new SQLTableElement(e.getTable().getField("PA_DEVISE"), BigDecimal.class);
Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
tableElement_PA_Devise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
// Devise
list.add(tableElement_Devise);
 
// Prix d'achat HT devise
list.add(tableElement_PA_Devise);
}
// Mode de vente
final SQLTableElement tableElement_ModeVente = new SQLTableElement(e.getTable().getField("ID_MODE_VENTE_ARTICLE"));
list.add(tableElement_ModeVente);
 
// Prix d'achat unitaire HT
this.ha = new SQLTableElement(e.getTable().getField("PA_HT"), BigDecimal.class);
this.ha.setRenderer(new CurrencyWithSymbolRenderer());
list.add(this.ha);
 
SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
@Override
public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
 
SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
return false;
} else {
return super.isCellEditable(vals, rowIndex, columnIndex);
}
}
 
@Override
public TableCellRenderer getTableCellRenderer() {
return new QteUnitRowValuesRenderer();
}
 
protected Object getDefaultNullValue() {
return BigDecimal.ZERO;
}
};
list.add(qteU);
 
SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
list.add(uniteVente);
 
if (e.getTable().getFieldsName().contains("QTE_ORIGINE")) {
final SQLTableElement tableQteO = new SQLTableElement(e.getTable().getField("QTE_ORIGINE"));
tableQteO.setEditable(false);
list.add(tableQteO);
}
// Quantité
final SQLTableElement qteElement = new SQLTableElement(e.getTable().getField("QTE"), Integer.class) {
protected Object getDefaultNullValue() {
return Integer.valueOf(0);
}
};
list.add(qteElement);
// TVA
this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
list.add(this.tableElementTVA);
// Poids piece
SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class);
list.add(tableElementPoids);
 
// Poids total
this.tableElementPoidsTotal = new SQLTableElement(e.getTable().getField("T_POIDS"), Float.class);
list.add(this.tableElementPoidsTotal);
 
// Service
String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
Boolean b = Boolean.valueOf(val);
if (b != null && b.booleanValue()) {
this.service = new SQLTableElement(e.getTable().getField("SERVICE"), Boolean.class);
list.add(this.service);
}
 
if (DefaultNXProps.getInstance().getBooleanValue(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false)) {
// Prix d'achat HT devise
this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PA_DEVISE_T"), BigDecimal.class);
this.tableElementTotalDevise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
list.add(tableElementTotalDevise);
}
 
SQLTableElement tableElementRemise = null;
if (e.getTable().contains("POURCENT_REMISE")) {
tableElementRemise = new SQLTableElement(e.getTable().getField("POURCENT_REMISE"));
list.add(tableElementRemise);
}
 
if (e.getTable().getFieldsName().contains("T_ECO_CONTRIBUTION")) {
this.tableElementEcoTotal = new SQLTableElement(e.getTable().getField("T_ECO_CONTRIBUTION"));
list.add(this.tableElementEcoTotal);
}
 
// Total HT
this.totalHT = new SQLTableElement(e.getTable().getField("T_PA_HT"), BigDecimal.class);
this.totalHT.setRenderer(new DeviseTableCellRenderer());
this.totalHT.setEditable(false);
if (e.getTable().contains("POURCENT_REMISE") && tableElementRemise != null) {
tableElementRemise.addModificationListener(this.totalHT);
}
list.add(this.totalHT);
this.totalHA = this.totalHT;
// Total TTC
this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PA_TTC"), BigDecimal.class);
this.tableElementTotalTTC.setRenderer(new DeviseTableCellRenderer());
list.add(this.tableElementTotalTTC);
 
this.defaultRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(e.getTable()));
this.defaultRowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
this.defaultRowVals.put("CODE", "");
this.defaultRowVals.put("NOM", "");
this.defaultRowVals.put("QTE", 1);
this.defaultRowVals.put("QTE_UNITAIRE", BigDecimal.ONE);
this.defaultRowVals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
this.defaultRowVals.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("NOM"), false, this.defaultRowVals);
setModel(model);
 
this.table = new RowValuesTable(model, getConfigura