OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 184 → Rev 185

/trunk/OpenConcerto/lib/OGNL-3.3.2.ILM.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/lib/OGNL-3.3.2.ILM.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/Configuration/Template/Labels/50x50.zpl
New file
0,0 → 1,24
^XA
^CI28
 
^FX Designation
^CF0,24
^FO20,50^FB 380,3,0,L,0^FD${product.name}^FS
 
^FX Traitement
^CF0,22
^FO20,140^FDTraitement : ${product.treatment}^FS
 
^FX Origine
^CF0,22
^FO20,170^FDOrigine : ${product.origin}^FS
 
^FX Numero de lot
^CF0,22
^FO20,200^FDN° de lot : ${product.batch}^FS
^FX EAN
^BY3,2,90
^FO60,250^BEN,80,Y,N^FD${product.ean13}^FS
 
^XZ
/trunk/OpenConcerto/Configuration/Template/Labels/57x32.zpl
New file
0,0 → 1,36
^XA
^CI28
 
^FX HT
^CF0,24
^FO490,20,1^FD${product.price}^FS
^CF0,20
^FO490,45,1^FD€ HT^FS
 
^FX TTC
^CF0,24
^FO490,70,1^FD${product.pricewithtax}^FS
^CF0,20
^FO490,95,1^FD€ TTC^FS
 
^FX Code
^CF0,28
^FO20,126^FB 380,3,0,L,0^FD${product.code}^FS
 
^FX Designation
^CF0,24
^FO20,155^FB480,1,0,L,0^FD${product.name}^FS
 
^FX Couleur
^CF0,18
^FO20,185^FDCouleur : ${product.color}^FS
 
^FX Taille
^CF0,18
^FO310,185^FDTaille : ${product.size}^FS
 
^FX EAN
^BY3,2,75
^FO54,15^BEN,75,Y,N^FD${product.ean13}^FS
 
^XZ
/trunk/OpenConcerto/Configuration/Template/Default/EtatRapprochement.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatRapprochement.ods
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/OpenConcerto/Configuration/Template/Default/EtatStockInventaire.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatChargesPaye.odsp
New file
0,0 → 1,9
<odsp>
<spliteveryrow>
<sheet number="0">68</sheet>
</spliteveryrow>
<offset x="0" y ="0"/>
<resize percent="100"/>
 
 
</odsp>
/trunk/OpenConcerto/Configuration/Template/Default/FichePayeSimplifiee.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/RepartitionAnalytique.odsp
1,9 → 1,7
<odsp>
<spliteveryrow>
<sheet number="0">68</sheet>
<sheet number="0">69</sheet>
</spliteveryrow>
<offset x="40" y ="20"/>
<resize percent="85"/>
 
 
<offset x="0" y ="0"/>
<resize percent="100"/>
</odsp>
/trunk/OpenConcerto/Configuration/Template/Default/LivrePaye.odsp
2,8 → 2,8
<spliteveryrow>
<sheet number="0">67</sheet>
</spliteveryrow>
<offset x="40" y ="20"/>
<resize percent="85"/>
<offset x="0" y ="0"/>
<resize percent="100"/>
 
 
</odsp>
/trunk/OpenConcerto/Configuration/Template/Default/RepartitionAnalytique.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatRapprochement.xml
New file
0,0 → 1,45
<?xml version="1.0" encoding="UTF-8" ?>
 
<contentDocument>
<element0 location="A1" type="Value" ValueName="SOCIETE">
</element0>
 
<element0 location="F1" type="Value" ValueName="DATE_EDITION">
</element0>
 
<element0 location="A3" type="Value" ValueName="TITRE">
</element0>
 
<table0 firstLine="6" endLine="60" endPageLine="60" lastColumn="G" base="Societe" table="ECRITURE" pageRef="F3">
<element location="A" type="fill" >
<field base="Societe" name="DATE"/>
</element>
 
<element location="B" type="fill" >
<field base="Societe" name="CODE_JOURNAL"/>
</element>
 
 
<element location="C" type="fill" >
<field base="Societe" name="PIECE"/>
</element>
 
<element location="D" type="fill" maxChar="60" >
<field base="Societe" name="NOM"/>
</element>
 
<element location="E" type="fill">
<field base="Societe" name="DEBIT"/>
</element>
 
<element location="F" type="fill">
<field base="Societe" name="CREDIT"/>
</element>
<element location="G" type="fill">
<field base="Societe" name="SOLDE"/>
</element>
</table0>
 
</contentDocument>
/trunk/OpenConcerto/Configuration/Template/Default/EtatStockInventaire.xml
3,7 → 3,7
<!-- <element location="A3" type="Value" ValueName="DATE">
</element>
-->
<table firstLine="2" endLine="17000" endPageLine="25000" lastColumn="E" table="SAISIE_VENTE_FACTURE">
<table firstLine="2" endLine="-1" endPageLine="25000" lastColumn="E" table="SAISIE_VENTE_FACTURE">
<element location="A" type="fill">
<field name="FAMILLE" />
29,5 → 29,9
<field name="QTE" />
</element>
 
<element location="H" type="fill">
<field name="DEPOT" />
</element>
 
</table>
</contentDocument>
/trunk/OpenConcerto/Configuration/Template/Default/FichePayeSimplifiee.xml
13,11 → 13,11
</field>
</element>
 
<element location="D7" type="fill">
<element location="C7" type="fill">
<field base="Common" table="SOCIETE_COMMON" name="NUMERO_URSSAF" />
</element>
 
<element location="G7" type="fill">
<element location="F7" type="fill">
<field base="Common" table="SOCIETE_COMMON" name="NUM_SIRET" />
</element>
 
114,10 → 114,10
<field name="DETAILS_CONGES" />
</element>
 
<element location="H52" type="fill">
<element location="G52" type="fill">
<field name="COT_SAL" />
</element>
<element location="I52" type="fill">
<element location="H52" type="fill">
<field name="COT_PAT" />
</element>
 
/trunk/OpenConcerto/Configuration/Template/Default/RepartitionAnalytique.xml
28,7 → 28,11
<field name="POSTE_NOM" />
</element>
 
<element location="D" type="fill">
<field name="CLASSE" />
</element>
<element location="E" type="fill">
<field name="DEBIT" />
</element>
/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/LivrePaye.ods
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/OpenConcerto/Configuration/Template/Default/EtatRapprochement.odsp
New file
0,0 → 1,9
<odsp>
<spliteveryrow>
<sheet number="0">60</sheet>
</spliteveryrow>
<offset x="0" y ="0"/>
<resize percent="100"/>
 
 
</odsp>
/trunk/OpenConcerto/src/org/jopendocument/link/OOConnexion.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
27,6 → 27,7
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.PropertyPermission;
54,7 → 55,8
}
 
static private final URL[] getURLs(final OOInstallation ooInstall) {
final List<URL> res = ooInstall.getURLs(CollectionUtils.createSet("ridl.jar", "jurt.jar", "juh.jar", "unoil.jar"));
final List<URL> from_v7 = ooInstall.getURLs(Collections.singleton("libreoffice.jar"));
final List<URL> res = from_v7.isEmpty() ? ooInstall.getURLs(CollectionUtils.createSet("ridl.jar", "jurt.jar", "juh.jar", "unoil.jar")) : from_v7;
return res.toArray(new URL[res.size()]);
}
 
/trunk/OpenConcerto/src/org/jopendocument/link/OOInstallation.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
/trunk/OpenConcerto/src/org/jopendocument/link/Component.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/BonFactureSQLInjector.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
34,6 → 34,9
if (tableBon.getTable().contains("ID_POLE_PRODUIT")) {
map(tableBon.getField("ID_POLE_PRODUIT"), tableFacture.getField("ID_POLE_PRODUIT"));
}
if (tableBon.contains("T_ACOMPTE") && tableFacture.contains("T_ACOMPTE")) {
map(tableBon.getField("T_ACOMPTE"), tableFacture.getField("T_ACOMPTE"));
}
if (getSource().getTable().contains("ID_CONTACT")) {
map(getSource().getField("ID_CONTACT"), getDestination().getField("ID_CONTACT"));
}
70,7 → 73,10
if (getSource().getTable().contains("ACOMPTE_COMMANDE")) {
map(getSource().getField("ACOMPTE_COMMANDE"), getDestination().getField("ACOMPTE_COMMANDE"));
}
if (getSource().getTable().contains("ID_COMMERCIAL")) {
map(getSource().getField("ID_COMMERCIAL"), getDestination().getField("ID_COMMERCIAL"));
}
}
 
@Override
protected void merge(SQLRowAccessor srcRow, SQLRowValues rowVals) {
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/FactureAvoirSQLInjector.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
18,6 → 18,7
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
72,7 → 73,18
if (myListItem.size() != 0) {
final SQLInjector injector = SQLInjector.getInjector(tableElementSource, tableElementDestination);
for (SQLRowAccessor rowElt : myListItem) {
final SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(rowElt.asRow());
final SQLRow asRow = rowElt.asRow();
final SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(asRow);
 
if (asRow.getObject("MONTANT_FACTURABLE") != null) {
createRowValuesFrom.put("PV_HT", asRow.getObject("MONTANT_FACTURABLE"));
createRowValuesFrom.put("PRIX_METRIQUE_VT_1", asRow.getObject("MONTANT_FACTURABLE"));
} else if (asRow.getObject("POURCENT_FACTURABLE") != null && asRow.getObject("PRIX_METRIQUE_VT_1") != null) {
final BigDecimal pv = asRow.getBigDecimal("PRIX_METRIQUE_VT_1").multiply(asRow.getBigDecimal("POURCENT_FACTURABLE")).movePointLeft(2);
createRowValuesFrom.put("PV_HT", pv);
createRowValuesFrom.put("PRIX_METRIQUE_VT_1", pv);
}
 
if (createRowValuesFrom.getTable().getFieldsName().contains("POURCENT_ACOMPTE")) {
if (createRowValuesFrom.getObject("POURCENT_ACOMPTE") == null) {
createRowValuesFrom.put("POURCENT_ACOMPTE", new BigDecimal(100.0));
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/ArticleCommandeEltSQLInjector.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
31,4 → 31,5
remove(tableArticle.getField("ID_DEVISE"), tableCommandeElement.getField("ID_DEVISE"));
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeFactureClientSQLInjector.java
35,6 → 35,10
if (tableCommande.contains("T_ACOMPTE")) {
map(tableCommande.getField("T_ACOMPTE"), tableFacture.getField("T_ACOMPTE"));
}
if (tableCommande.contains("POURCENT_RG") && tableFacture.contains("POURCENT_RG")) {
map(tableCommande.getField("POURCENT_RG"), tableFacture.getField("POURCENT_RG"));
}
 
if (tableCommande.contains("PORT_HT")) {
map(tableCommande.getField("PORT_HT"), tableFacture.getField("PORT_HT"));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeBlSQLInjector.java
32,6 → 32,9
if (tableCmd.getTable().contains("ID_POLE_PRODUIT") && tableBl.contains("ID_POLE_PRODUIT")) {
map(tableCmd.getField("ID_POLE_PRODUIT"), tableBl.getField("ID_POLE_PRODUIT"));
}
if (tableCmd.contains("T_ACOMPTE") && tableBl.contains("T_ACOMPTE")) {
map(tableCmd.getField("T_ACOMPTE"), tableBl.getField("T_ACOMPTE"));
}
if (getSource().getTable().contains("ID_CONTACT")) {
map(getSource().getField("ID_CONTACT"), getDestination().getField("ID_CONTACT"));
}
/trunk/OpenConcerto/src/org/openconcerto/erp/injector/CommandeBlEltSQLInjector.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
20,6 → 20,7
public CommandeBlEltSQLInjector(final DBRoot root) {
super(root, "COMMANDE_CLIENT_ELEMENT", "BON_DE_LIVRAISON_ELEMENT", false);
createDefaultMap();
remove(getSource().getField("QTE_LIVREE"), getDestination().getField("QTE_LIVREE"));
mapDefaultValues(getDestination().getField("QTE_LIVREE"), Integer.valueOf(0));
if (getDestination().contains("ID_COMMANDE_CLIENT_ELEMENT")) {
map(getSource().getKey(), getDestination().getField("ID_COMMANDE_CLIENT_ELEMENT"));
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLElement.java
133,6 → 133,15
if (brk != null && brk.trim().length() > 0) {
res = (res == null ? res : res.toString().replaceAll(brk, "\n"));
}
 
String attributeValueMaxChar = this.elt.getAttributeValue("maxChar");
if (attributeValueMaxChar != null) {
int maxChar = Integer.valueOf(attributeValueMaxChar);
if (res != null && res.toString().length() > maxChar) {
res = res.toString().substring(0, maxChar);
}
}
 
return res;
}
 
141,6 → 150,7
sel.addSelect(field, function);
Where w = new Where(field.getTable().getField("ID_" + this.row.getTable().getName()), "=", this.row.getID());
sel.setWhere(w);
 
return Configuration.getInstance().getBase().getDataSource().executeScalar(sel.asString());
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/BatchListProvider.java
New file
0,0 → 1,80
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.sql.model.SQLRowAccessor;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
 
public class BatchListProvider extends UserInitialsValueProvider {
 
private final String refTable;
 
public BatchListProvider(String refTable) {
this.refTable = refTable;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
final SQLRowAccessor row = context.getRow();
 
final Collection<? extends SQLRowAccessor> cols = row.asRow().getReferentRows(row.getTable().getTable(this.refTable));
final StringBuilder res = new StringBuilder();
for (SQLRowAccessor sqlRowAccessor : cols) {
final Calendar dluo = sqlRowAccessor.getDate("DLUO");
final Calendar dlc = sqlRowAccessor.getDate("DLC");
final String lot = sqlRowAccessor.getString("NUMERO_LOT");
final String serie = sqlRowAccessor.getString("NUMERO_SERIE");
if (res.length() > 0) {
res.append("\n");
}
if (serie != null && serie.trim().length() > 0) {
res.append("N° Série : " + serie);
}
if (lot != null && lot.trim().length() > 0) {
if (res.length() > 0) {
res.append(", ");
}
res.append("N° Lot : " + lot);
}
if (dlc != null) {
if (res.length() > 0) {
res.append(", ");
}
res.append("DLC : " + format.format(dlc.getTime()));
}
if (dluo != null) {
if (res.length() > 0) {
res.append(", ");
}
res.append("DLUO : " + format.format(dluo.getTime()));
}
 
}
 
return res.toString();
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.batch.list", new BatchListProvider("LOT_LIVRAISON"));
SpreadSheetCellValueProviderManager.put("purchase.batch.list", new BatchListProvider("LOT_RECEPTION"));
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/FormatedGlobalQtyTotalProvider.java
43,10 → 43,13
this.pieceName = withPieceName;
}
 
private final BigDecimal cent = new BigDecimal(100);
 
public Object getValue(SpreadSheetCellValueContext context) {
final SQLRowAccessor row = context.getRow();
final BigDecimal pv = row.getBigDecimal("PV_HT");
if (!this.alwaysShowOnZeroQty && pv != null && pv.compareTo(BigDecimal.ZERO) == 0) {
final BigDecimal pR = row.getBigDecimal("POURCENT_REMISE");
if (!this.alwaysShowOnZeroQty && pv != null && pv.compareTo(BigDecimal.ZERO) == 0 && (pR == null || pR.compareTo(cent) != 0)) {
return null;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/TitleInvoiceProvider.java
New file
0,0 → 1,42
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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;
 
public class TitleInvoiceProvider implements SpreadSheetCellValueProvider {
 
public Object getValue(SpreadSheetCellValueContext context) {
final SQLRowAccessor row = context.getRow();
String result;
if (row.getBoolean("PARTIAL")) {
result = "Facture de situation";
} else {
result = "Facture de solde";
}
if (row.getBoolean("PREVISIONNELLE")) {
result += " Prévisionnelle";
}
 
return result;
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.account.title", new TitleInvoiceProvider());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/RecapFactureProvider.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
19,6 → 19,7
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.utils.GestionDevise;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
31,9 → 32,12
};
 
private final TypeRecapFactureProvider type;
private final boolean withDate, withAvoir;
 
public RecapFactureProvider(TypeRecapFactureProvider t) {
public RecapFactureProvider(TypeRecapFactureProvider t, boolean withDate, boolean withAvoir) {
this.type = t;
this.withDate = withDate;
this.withAvoir = withAvoir;
}
 
public Object getValue(SpreadSheetCellValueContext context) {
55,8 → 59,14
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.account.history", new RecapFactureProvider(TypeRecapFactureProvider.HT));
SpreadSheetCellValueProviderManager.put("sales.account.history.ttc", new RecapFactureProvider(TypeRecapFactureProvider.TTC));
SpreadSheetCellValueProviderManager.put("sales.account.history", new RecapFactureProvider(TypeRecapFactureProvider.HT, false, false));
SpreadSheetCellValueProviderManager.put("sales.account.history.ttc", new RecapFactureProvider(TypeRecapFactureProvider.TTC, false, false));
SpreadSheetCellValueProviderManager.put("sales.account.history.withdate", new RecapFactureProvider(TypeRecapFactureProvider.HT, true, false));
SpreadSheetCellValueProviderManager.put("sales.account.history.ttc.withdate", new RecapFactureProvider(TypeRecapFactureProvider.TTC, true, false));
SpreadSheetCellValueProviderManager.put("sales.account.history.with.credit", new RecapFactureProvider(TypeRecapFactureProvider.HT, false, true));
SpreadSheetCellValueProviderManager.put("sales.account.history.with.credit.ttc", new RecapFactureProvider(TypeRecapFactureProvider.TTC, false, true));
SpreadSheetCellValueProviderManager.put("sales.account.history.with.credit.withdate", new RecapFactureProvider(TypeRecapFactureProvider.HT, true, true));
SpreadSheetCellValueProviderManager.put("sales.account.history.with.credit.ttc.withdate", new RecapFactureProvider(TypeRecapFactureProvider.TTC, true, true));
}
 
public String getPreviousAcompte(SQLRowAccessor sqlRowAccessor, Set<SQLRowAccessor> alreadyAdded, Calendar c) {
65,15 → 75,25
}
Collection<? extends SQLRowAccessor> rows = sqlRowAccessor.getReferentRows(sqlRowAccessor.getTable().getTable("TR_COMMANDE_CLIENT"));
StringBuffer result = new StringBuffer();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
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)
&& (!this.withAvoir || (this.withAvoir && rowFact.isForeignEmpty("ID_AVOIR_CLIENT")))) {
alreadyAdded.add(rowFact);
final String fieldTotal = this.type == TypeRecapFactureProvider.HT ? "T_HT" : "T_TTC";
result.append(rowFact.getString("NUMERO") + " (" + GestionDevise.currencyToString(rowFact.getLong(fieldTotal)) + "€), ");
result.append(rowFact.getString("NUMERO"));
result.append(" (");
if (this.withDate) {
result.append(format.format(rowFact.getDate("DATE").getTime()) + " ");
}
result.append(GestionDevise.currencyToString(rowFact.getLong(fieldTotal)) + "€), ");
if (this.withDate) {
result.append("\n");
}
}
}
 
return result.toString();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/RestantAReglerProvider.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
35,18 → 35,18
public RestantAReglerProvider(TypeRestantAReglerProvider t) {
this.type = t;
if (this.type == TypeRestantAReglerProvider.HT) {
acompteProv = new TotalAcompteProvider(TypeTotalAcompteProvider.HT);
cmdProvider = new TotalCommandeClientProvider(TypeTotalCommandeClientProvider.HT);
this.acompteProv = new TotalAcompteProvider(TypeTotalAcompteProvider.HT, false);
this.cmdProvider = new TotalCommandeClientProvider(TypeTotalCommandeClientProvider.HT);
} else {
acompteProv = new TotalAcompteProvider(TypeTotalAcompteProvider.TTC);
cmdProvider = new TotalCommandeClientProvider(TypeTotalCommandeClientProvider.TTC);
this.acompteProv = new TotalAcompteProvider(TypeTotalAcompteProvider.TTC, false);
this.cmdProvider = new TotalCommandeClientProvider(TypeTotalCommandeClientProvider.TTC);
}
 
}
 
public Object getValue(SpreadSheetCellValueContext context) {
Object acompte = acompteProv.getValue(context);
Object cmd = cmdProvider.getValue(context);
Object acompte = this.acompteProv.getValue(context);
Object cmd = this.cmdProvider.getValue(context);
if (acompte != null && cmd != null) {
return ((BigDecimal) cmd).subtract((BigDecimal) acompte);
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/RecapLigneFactureProvider.java
New file
0,0 → 1,108
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationDoc.provider;
 
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProvider;
import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.DecimalUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.List;
 
public class RecapLigneFactureProvider implements SpreadSheetCellValueProvider {
 
private enum TypeLineRecapFactureProvider {
HT, TTC, PERCENT;
};
 
private final TypeLineRecapFactureProvider type;
private final boolean old, withAvoir;
 
public RecapLigneFactureProvider(TypeLineRecapFactureProvider t, boolean old) {
this(t, old, false);
}
 
public RecapLigneFactureProvider(TypeLineRecapFactureProvider t, boolean old, boolean withAvoir) {
this.type = t;
this.old = old;
this.withAvoir = withAvoir;
}
 
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor row = context.getRow();
final SQLRowAccessor factureOrigin = row.getNonEmptyForeign("ID_SAISIE_VENTE_FACTURE");
final Calendar date = factureOrigin.getDate("DATE");
 
final SQLRowAccessor foreignCmdItem = row.getNonEmptyForeign("ID_COMMANDE_CLIENT_ELEMENT");
if (foreignCmdItem != null && foreignCmdItem.getBigDecimal("T_PV_HT").signum() != 0) {
 
SQLRowValues rowValsFactItem2Fetch = new SQLRowValues(row.getTable());
rowValsFactItem2Fetch.putNulls("T_PV_HT", "T_PV_TTC");
 
rowValsFactItem2Fetch.putRowValues("ID_SAISIE_VENTE_FACTURE").putNulls("DATE", "ID_AVOIR_CLIENT");
 
final List<SQLRowValues> fetch = SQLRowValuesListFetcher.create(rowValsFactItem2Fetch).fetch(new Where(row.getTable().getField("ID_COMMANDE_CLIENT_ELEMENT"), "=", foreignCmdItem.getID()));
 
BigDecimal total = BigDecimal.ZERO;
BigDecimal totalTTC = BigDecimal.ZERO;
for (SQLRowAccessor sqlRowAccessor : fetch) {
final SQLRowAccessor nonEmptyForeign = sqlRowAccessor.getNonEmptyForeign("ID_SAISIE_VENTE_FACTURE");
if (nonEmptyForeign != null && (!withAvoir || (withAvoir && sqlRowAccessor.isForeignEmpty("ID_AVOIR_CLIENT")))) {
final Calendar date2 = nonEmptyForeign.getDate("DATE");
final boolean same = old && factureOrigin.getID() == nonEmptyForeign.getID();
if (same || date2.before(date) || (date2.equals(date) && nonEmptyForeign.getID() < factureOrigin.getID())) {
total = total.add(sqlRowAccessor.getBigDecimal("T_PV_HT"));
totalTTC = totalTTC.add(sqlRowAccessor.getBigDecimal("T_PV_TTC"));
}
}
}
if (this.type == TypeLineRecapFactureProvider.HT) {
return total;
} else if (this.type == TypeLineRecapFactureProvider.TTC) {
return totalTTC;
} else {
if (foreignCmdItem.getBigDecimal("T_PV_HT").signum() != 0) {
return total.divide(foreignCmdItem.getBigDecimal("T_PV_HT"), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP) + "%";
} else {
return "";
}
}
} else {
return "";
}
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.account.line.history", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.HT, false));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.ttc", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.TTC, false));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.percent", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.PERCENT, false));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.total", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.HT, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.total.ttc", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.TTC, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.total.percent", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.PERCENT, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.HT, false, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit.ttc", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.TTC, false, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit.percent", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.PERCENT, false, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit.total", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.HT, true, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit.total.ttc", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.TTC, true, true));
SpreadSheetCellValueProviderManager.put("sales.account.line.history.with.credit.total.percent", new RecapLigneFactureProvider(TypeLineRecapFactureProvider.PERCENT, true, true));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/QteLineDocProvider.java
47,16 → 47,17
}
 
final BigDecimal qteUV = sqlRowAccessor.getBigDecimal("QTE_UNITAIRE");
final BigDecimal qte = new BigDecimal(sqlRowAccessor.getInt("QTE"));
final BigDecimal qte = sqlRowAccessor.getTable().getName().equalsIgnoreCase("BON_DE_LIVRAISON_ELEMENT") ? new BigDecimal(sqlRowAccessor.getInt("QTE_LIVREE"))
: new BigDecimal(sqlRowAccessor.getInt("QTE"));
 
final BigDecimal tare;
if (sqlRowAccessor.getObject("TARE") != null) {
tare = new BigDecimal(sqlRowAccessor.getInt("NB_COLIS"));
tare = sqlRowAccessor.getBigDecimal("TARE");
} else {
tare = BigDecimal.ZERO;
}
 
BigDecimal pdsNet = nbColis.multiply(qte).multiply(qteUV);
BigDecimal pdsNet = new BigDecimal(sqlRowAccessor.getFloat("POIDS")).multiply(qte).multiply(qteUV);
if (this.type == TypePoidsDocProvider.POIDS_NET) {
return pdsNet;
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/TotalAcompteProvider.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
31,9 → 31,11
};
 
private final TypeTotalAcompteProvider type;
private boolean old;
 
public TotalAcompteProvider(TypeTotalAcompteProvider t) {
public TotalAcompteProvider(TypeTotalAcompteProvider t, boolean old) {
this.type = t;
this.old = old;
}
 
public Object getValue(SpreadSheetCellValueContext context) {
43,7 → 45,7
Collection<? extends SQLRowAccessor> rows = row.getReferentRows(row.getTable().getTable("TR_COMMANDE_CLIENT"));
long total = 0;
Set<SQLRowAccessor> facture = new HashSet<SQLRowAccessor>();
facture.add(row);
 
for (SQLRowAccessor sqlRowAccessor : rows) {
total += getPreviousAcompte(sqlRowAccessor.getForeign("ID_COMMANDE_CLIENT"), facture, c, row);
}
52,8 → 54,10
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.account.total", new TotalAcompteProvider(TypeTotalAcompteProvider.HT));
SpreadSheetCellValueProviderManager.put("sales.account.total.ttc", new TotalAcompteProvider(TypeTotalAcompteProvider.TTC));
SpreadSheetCellValueProviderManager.put("sales.account.total.cumul", new TotalAcompteProvider(TypeTotalAcompteProvider.HT, true));
SpreadSheetCellValueProviderManager.put("sales.account.total.cumul.ttc", new TotalAcompteProvider(TypeTotalAcompteProvider.TTC, true));
SpreadSheetCellValueProviderManager.put("sales.account.total", new TotalAcompteProvider(TypeTotalAcompteProvider.HT, false));
SpreadSheetCellValueProviderManager.put("sales.account.total.ttc", new TotalAcompteProvider(TypeTotalAcompteProvider.TTC, false));
}
 
public long getPreviousAcompte(SQLRowAccessor sqlRowAccessor, Set<SQLRowAccessor> alreadyAdded, Calendar c, SQLRowAccessor origin) {
65,8 → 69,9
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) || (rowFact.getDate("DATE").equals(c) && rowFact.getID() < origin.getID()))) {
final boolean sameFact = rowFact.getDate("DATE").equals(c) && rowFact.getID() < origin.getID();
final boolean oldFact = rowFact.getID() == origin.getID() && this.old;
if (rowFact != null && !rowFact.isUndefined() && !alreadyAdded.contains(rowFact) && (rowFact.getDate("DATE").before(c) || sameFact || oldFact)) {
alreadyAdded.add(rowFact);
l += this.type == TypeTotalAcompteProvider.HT ? rowFact.getLong("T_HT") : rowFact.getLong("T_TTC");
}
73,5 → 78,4
}
return l;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/ResteALivrerDocProvider.java
New file
0,0 → 1,95
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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 ResteALivrerDocProvider implements SpreadSheetCellValueProvider {
 
protected enum ResteProvider {
RESTE, LIVRE_TOTAL, RESTE_CMD, LIVRE_TOTAL_CMD
};
 
protected final ResteProvider type;
 
public ResteALivrerDocProvider(ResteProvider t) {
this.type = t;
}
 
@Override
public Object getValue(SpreadSheetCellValueContext context) {
SQLRowAccessor sqlRowAccessor = context.getRow();
return geTotalFromRow(sqlRowAccessor);
 
}
 
protected BigDecimal geTotalFromRow(SQLRowAccessor sqlRowAccessor) {
BigDecimal totalD;
BigDecimal total = sqlRowAccessor.getBigDecimal("QTE_UNITAIRE");
total = total.multiply(new BigDecimal(sqlRowAccessor.getInt("QTE")));
 
if (this.type == ResteProvider.RESTE_CMD || this.type == ResteProvider.LIVRE_TOTAL_CMD) {
totalD = new BigDecimal(sqlRowAccessor.getInt("QTE_LIVREE"));
final BigDecimal returnedValue;
if (this.type == ResteProvider.RESTE_CMD) {
returnedValue = total.subtract(totalD);
} else {
returnedValue = totalD;
}
if (!sqlRowAccessor.isForeignEmpty("ID_ARTICLE") && returnedValue.signum() > 0) {
return returnedValue;
} else {
return null;
}
} else {
 
final SQLRowAccessor nonEmptyForeignCmdItem = sqlRowAccessor.getNonEmptyForeign("ID_COMMANDE_CLIENT_ELEMENT");
if (nonEmptyForeignCmdItem == null) {
 
totalD = sqlRowAccessor.getBigDecimal("QTE_UNITAIRE");
totalD = totalD.multiply(new BigDecimal(sqlRowAccessor.getInt("QTE_LIVREE")));
 
return total.subtract(totalD);
} else {
totalD = nonEmptyForeignCmdItem.getBigDecimal("QTE_LIVREE");
}
if (this.type == ResteProvider.LIVRE_TOTAL) {
if (totalD.signum() > 0) {
return totalD;
} else {
return null;
}
} else {
BigDecimal r = total.subtract(totalD);
if (r.signum() > 0) {
return r;
} else {
return null;
}
}
}
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.qty.delivred.total", new ResteALivrerDocProvider(ResteProvider.LIVRE_TOTAL));
SpreadSheetCellValueProviderManager.put("sales.qty.delivred.remained", new ResteALivrerDocProvider(ResteProvider.RESTE));
SpreadSheetCellValueProviderManager.put("sales.qty.cmd.delivred.total", new ResteALivrerDocProvider(ResteProvider.LIVRE_TOTAL_CMD));
SpreadSheetCellValueProviderManager.put("sales.qty.cmd.delivred.remained", new ResteALivrerDocProvider(ResteProvider.RESTE_CMD));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/RGProvider.java
New file
0,0 → 1,76
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.utils.DecimalUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
 
public class RGProvider implements SpreadSheetCellValueProvider {
 
private enum TypeRGProvider {
HT_RESTANT(true, true), TTC_RESTANT(false, true), HT_RG(true, false), TTC_RG(false, false);
 
private final boolean restant, ht;
 
TypeRGProvider(boolean ht, boolean restant) {
this.restant = restant;
this.ht = ht;
}
 
public boolean isHt() {
return this.ht;
}
 
public boolean isRestant() {
return this.restant;
}
};
 
private final TypeRGProvider type;
 
public RGProvider(TypeRGProvider t) {
this.type = t;
}
 
public Object getValue(SpreadSheetCellValueContext context) {
final BigDecimal total;
if (this.type.isHt()) {
total = new BigDecimal(context.getRow().getLong("T_HT")).movePointLeft(2);
} else {
total = new BigDecimal(context.getRow().getLong("T_TTC")).movePointLeft(2);
}
 
final BigDecimal pourcentRG = context.getRow().getBigDecimal("POURCENT_RG");
final BigDecimal totalRG = total.multiply(pourcentRG.movePointLeft(2), DecimalUtils.HIGH_PRECISION).setScale(2, RoundingMode.HALF_UP);
if (this.type.isRestant()) {
return total.subtract(totalRG);
} else {
return totalRG;
}
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.rg.due", new RGProvider(TypeRGProvider.TTC_RG));
SpreadSheetCellValueProviderManager.put("sales.total.sub.rg", new RGProvider(TypeRGProvider.TTC_RESTANT));
 
SpreadSheetCellValueProviderManager.put("sales.rg.due.ht", new RGProvider(TypeRGProvider.HT_RG));
SpreadSheetCellValueProviderManager.put("sales.total.sub.rg.ht", new RGProvider(TypeRGProvider.HT_RESTANT));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/LabelAccountInvoiceProvider.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
22,12 → 22,18
 
public class LabelAccountInvoiceProvider implements SpreadSheetCellValueProvider {
 
private final String label;
 
public LabelAccountInvoiceProvider(String label) {
this.label = label;
}
 
public Object getValue(SpreadSheetCellValueContext context) {
final SQLRowAccessor row = context.getRow();
final Collection<? extends SQLRowAccessor> rows = row.getReferentRows(row.getTable().getTable("TR_COMMANDE_CLIENT"));
String result;
if (row.getBoolean("PARTIAL")) {
result = "Facturation intermédiaire, commande N°";
result = this.label + ", commande N°";
} else {
result = "Solde, commande N°";
}
41,7 → 47,8
}
 
public static void register() {
SpreadSheetCellValueProviderManager.put("sales.account.label", new LabelAccountInvoiceProvider());
SpreadSheetCellValueProviderManager.put("sales.account.label", new LabelAccountInvoiceProvider("Facturation intermédiaire"));
SpreadSheetCellValueProviderManager.put("sales.account.label.account", new LabelAccountInvoiceProvider("Facture d'acompte"));
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
166,10 → 166,11
int nbPage = fillTable(tableau, liste, sheet, mapStyle, true, style);
int firstLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
int endLine = Integer.valueOf(tableau.getAttributeValue("endLine"));
 
Object printRangeObj = sheet.getPrintRanges();
 
System.err.println("Nombre de page == " + nbPage);
if (nbPage == 1) {
if (nbPage == 1 || endLine == -1) {
fillTable(tableau, liste, sheet, mapStyle, false, style);
} else {
 
233,6 → 234,8
int currentLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
 
int endLine = Integer.valueOf(tableau.getAttributeValue("endLine"));
 
List listElts = tableau.getChildren("element");
 
Object o = null;
241,8 → 244,15
Map<String, Double> mapSousTotal = new HashMap<String, Double>();
Map<String, Double> mapTotal = new HashMap<String, Double>();
 
// agrandissement selon le nombre de ligne à insérer
if (endLine == -1) {
sheet.setRowCount(currentLine + 1);
sheet.setRowCount(currentLine + liste.size(), currentLine);
// sheet.duplicateRows(currentLine+1, liste.size(), 1);
endPageLine = currentLine + 1 + liste.size();
}
 
// on remplit chaque ligne à partir des rows recuperées
 
for (int i = 0; i < liste.size(); i++) {
Map<String, Object> mValues = liste.get(i);
// System.err.println(mValues);
402,6 → 412,15
 
private static Object resizeValue(Element elt, Object res) {
{
String digitSize = elt.getAttributeValue("digitsFormat");
if (digitSize != null) {
int size = Integer.valueOf(digitSize);
if (res != null && res.toString().length() > 0) {
res = String.format("%-" + size + "s", res).replace(' ', '0');
}
}
}
{
String attributeValueMaxChar = elt.getAttributeValue("maxChar");
if (attributeValueMaxChar != null) {
int maxChar = Integer.valueOf(attributeValueMaxChar);
439,7 → 458,6
private static Object getValueOfComposant(Element eltField, Map<String, Object> mValues) {
 
String field = eltField.getAttributeValue("name");
 
return mValues.get(field);
}
 
606,7 → 624,8
System.err.println("End column search : " + columnCount);
 
int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
 
// Limite pour éviter les breakrepeated
rowCount = Math.min(100, rowCount);
System.err.println("End row search : " + rowCount);
for (int i = 0; i < rowCount && (mapStyleDef.keySet().size() - 2) > mapStyleFounded.keySet().size(); i++) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetXml.java
185,7 → 185,7
 
@Override
public void run(Object source) {
EmailTemplate.askTemplate(null, table.getDBRoot(), new ValueListener() {
EmailTemplate.askTemplate(null, table.getDBRoot(), table.getName(), new ValueListener() {
 
@Override
public void valueSelected(Object value) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/gestcomm/OptionDocProcessor.java
61,14 → 61,20
 
BigDecimal totalHT = sqlRowValues.getBigDecimal("T_PV_HT");
final BigDecimal remisePercent = sqlRowValues.getBigDecimal("POURCENT_REMISE");
if (remisePercent != null && remisePercent.signum() > 0) {
if (remisePercent != null && remisePercent.signum() > 0 && remisePercent.movePointLeft(2).compareTo(BigDecimal.ONE) != 0) {
if (BigDecimal.ONE.subtract(remisePercent.movePointLeft(2)).signum() != 0) {
totalHT = totalHT.divide(BigDecimal.ONE.subtract(remisePercent.movePointLeft(2)), org.openconcerto.utils.DecimalUtils.HIGH_PRECISION);
}
}
// On ne recalcule pas le prix unitaire si la remise est de 100% sinon le prix
// unitaire est à 0 et les provider de quantité n'affiche plus rien
if (remisePercent == null || remisePercent.movePointLeft(2).compareTo(BigDecimal.ONE) != 0) {
BigDecimal unitPrice = totalHT.divide(qte, DecimalUtils.HIGH_PRECISION);
sqlRowValues.put("PV_HT", unitPrice);
sqlRowValues.put("PRIX_METRIQUE_VT_1", unitPrice);
}
}
}
result.add(sqlRowValues);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOXMLField.java
277,9 → 277,26
if (cellSize != null && cellSize.trim().length() != 0) {
result = splitStringCell(cellSize, result);
}
String attributeValueMaxChar = this.elt.getAttributeValue("maxChar");
if (attributeValueMaxChar != null) {
int maxChar = Integer.valueOf(attributeValueMaxChar);
if (result != null && result.length() > maxChar) {
result = result.substring(0, maxChar);
}
}
 
return result;
} else {
if (display == null || !display.equalsIgnoreCase("false")) {
 
String attributeValueMaxChar = this.elt.getAttributeValue("maxChar");
if (attributeValueMaxChar != null) {
int maxChar = Integer.valueOf(attributeValueMaxChar);
if (o != null && o.toString().length() > maxChar) {
o = o.toString().substring(0, maxChar);
}
}
 
if (cellSize != null && cellSize.trim().length() != 0 && o != null) {
return splitStringCell(cellSize, o.toString());
} else {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
208,7 → 208,7
}
 
// Sauvegarde du fichier
return saveSpreadSheet(spreadSheet, outputDirectory, expectedFileName, templateId, rowLanguage);
return saveSpreadSheet(spreadSheet, outputDirectory, expectedFileName, templateId, rowLanguage, typeTemplate);
 
} catch (final JDOMException e) {
 
991,7 → 991,7
* @throws IOException
*/
 
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage, String type) throws IOException {
final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
// Test des arguments
if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
1027,7 → 1027,7
 
// Copie de l'odsp
File odspOut = new File(pathDest, fileName + ".odsp");
try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, null);) {
try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, type);) {
if (odspIn != null) {
StreamUtils.copy(odspIn, odspOut);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SpreadSheetGenerator.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
29,6 → 29,7
 
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
56,7 → 57,7
private String printer;
private boolean exportPDF;
private Map mapReplaceText;
private String fODSP = null;
private InputStream fODSP = null;
 
protected static final String defaultLocationTemplate = "/Configuration/Template/Default/";
 
77,15 → 78,17
 
// on parcourt chaque ligne de la feuille pour recuperer les styles
int columnCount = (colEnd == -1) ? sheet.getColumnCount() : (colEnd + 1);
System.err.println("End column search : " + columnCount);
int endColumnSearch = Math.min(100, columnCount);
System.err.println("End column search : " + endColumnSearch);
 
int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
for (int i = 0; i < rowCount; i++) {
int endRowSearch = Math.min(100, rowCount);
for (int i = 0; i < endRowSearch; i++) {
int x = 0;
Map<Integer, String> mapCellStyle = new HashMap<Integer, String>();
String style = "";
 
for (int j = 0; j < columnCount; j++) {
for (int j = 0; j < endColumnSearch; j++) {
 
if (sheet.isCellValid(j, i)) {
 
183,11 → 186,14
}
 
protected SpreadSheet loadTemplate() throws IOException {
InputStream f = getStreamStatic(modelDir + File.separator + this.modele);
fODSP = modelDir + File.separator + this.modele + "p";
 
InputStream f = TemplateManager.getInstance().getTemplate(modele.replaceAll(".ods", ""));
if (f == null) {
f = getStreamStatic(modelDir + File.separator + this.modele);
fODSP = getStreamStatic(modelDir + File.separator + this.modele + "p");
if (f == null) {
f = getStreamStatic(defaultLocationTemplate + File.separator + this.modele);
fODSP = defaultLocationTemplate + File.separator + this.modele + "p";
fODSP = getStreamStatic(defaultLocationTemplate + File.separator + this.modele + "p");
if (f == null) {
ExceptionHandler.handle("Modele " + this.modele + " introuvable. Impossible de générer le document.");
System.err.println("Modele introuvable : " + (defaultLocationTemplate + File.separator + this.modele));
195,6 → 201,10
return null;
}
}
} else {
fODSP = TemplateManager.getInstance().getTemplatePrintConfiguration(modele.replaceAll(".ods", ""), null, null);
}
 
final SpreadSheet res = new ODPackage(f).getSpreadSheet();
f.close();
return res;
217,13 → 227,12
fTmp.renameTo(fDest);
 
fDest = new File(this.destDirOO, this.destFileName + ".ods");
try (final InputStream stream = getStreamStatic(fODSP)) {
if (stream != null) {
if (this.fODSP != null) {
// Copie de l'odsp
File odspOut = new File(this.destDirOO, this.destFileName + ".odsp");
StreamUtils.copy(stream, odspOut);
StreamUtils.copy(this.fODSP, odspOut);
}
}
 
try {
ssheet.saveAs(fDest);
} catch (FileNotFoundException e) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Ecriture.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
31,6 → 31,7
private BigDecimal credit;
private Mouvement mouvement;
private String nom;
private String nomPieceCommerciale;
private String compteNumero;
private String compteNom;
private Number compteID;
50,6 → 51,7
this.date = date;
this.debit = debit;
this.credit = credit;
this.nomPieceCommerciale = "";
}
 
public SQLInsert createInsert(DBRoot root, User user) {
79,7 → 81,7
insert.add(table.getField("ID_JOURNAL"), this.journalID);
insert.add(table.getField("JOURNAL_NOM"), this.journalNom);
insert.add(table.getField("JOURNAL_CODE"), this.journalCode);
insert.add(table.getField("NOM_PIECE"), this.mouvement.getPiece().getNom());
insert.add(table.getField("NOM_PIECE"), this.nomPieceCommerciale);
insert.add(table.getField("ID_USER_COMMON_CREATE"), user.getId());
insert.add(table.getField("ID_USER_COMMON_MODIFY"), user.getId());
insert.add(table.getField("CLOTURE"), this.cloture);
104,6 → 106,14
this.dateLettrage = dateLettrage;
}
 
public void setNomPieceCommerciale(String nomPieceCommerciale) {
this.nomPieceCommerciale = nomPieceCommerciale;
}
 
public String getNomPieceCommerciale() {
return this.nomPieceCommerciale;
}
 
public void setLettrage(String lettrage) {
this.lettrage = lettrage;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAvoirClient.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
19,6 → 19,7
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
52,6 → 53,7
}
 
public int genereMouvement() throws Exception {
boolean genEcrDisabled = DefaultNXProps.getInstance().getBooleanValue(GenerationMvtSaisieVenteFacture.NOT_GEN_ECRITURE, false);
 
SQLTable avoirClientTable = base.getTable("AVOIR_CLIENT");
 
120,7 → 122,9
this.putValue("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.putValue("CREDIT", Long.valueOf(0));
this.putValue("DEBIT", Long.valueOf(taxeC));
if (!genEcrDisabled) {
ajoutEcriture();
}
taxe += taxeC;
// this.putValue("ID_COMPTE_PCE",
// rowCompl.getForeignID("ID_COMPTE_PCE_PRODUITS"));
134,10 → 138,12
this.putValue("ID_COMPTE_PCE", row.getID());
this.putValue("DEBIT", Long.valueOf(b - taxe));
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
SQLRow rowEcr = ajoutEcriture();
// addAssocAnalytiqueFromProvider(rowEcr, avoirRow);
}
}
}
 
// compte TVA
Map<SQLRowAccessor, BigDecimal> tvaMap = calc.getMapHtTVA();
147,9 → 153,11
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("DEBIT", Long.valueOf(longValue));
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
ajoutEcriture();
}
}
}
 
// compte Clients
int idCompteClient = avoirRow.getForeignRow("ID_CLIENT").getInt("ID_COMPTE_PCE");
164,8 → 172,9
this.putValue("DEBIT", Long.valueOf(0));
long ttc = calc.getTotalTTC().movePointRight(2).longValue();
this.putValue("CREDIT", Long.valueOf(ttc));
if (!genEcrDisabled) {
ajoutEcriture();
 
}
// Mise à jour de mouvement associé à la facture d'avoir
SQLRowValues valAvoir = new SQLRowValues(avoirClientTable);
valAvoir.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
179,8 → 188,9
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteClient));
this.putValue("DEBIT", Long.valueOf(ttc));
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
ajoutEcriture();
 
}
// compte Factor
int idComptefactor = rowPrefsCompte.getInt("ID_COMPTE_PCE_FACTOR");
if (idComptefactor <= 1) {
197,8 → 207,10
this.putValue("ID_COMPTE_PCE", idComptefactor);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc));
if (!genEcrDisabled) {
ajoutEcriture();
}
}
 
if (avoirRow.getInt("ID_MODE_REGLEMENT") > 1) {
new GenerationMvtReglementAvoir(avoirRow, this.idMvt);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationReglementVenteNG.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
26,6 → 26,7
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
161,6 → 162,12
// Cheque
if (typeRegRow.getID() == TypeReglementSQLElement.CHEQUE) {
 
final SQLRowAccessor nonEmptyForeign = modeReglement.getNonEmptyForeign("ID_BANQUE");
if (nonEmptyForeign != null && nonEmptyForeign.getTable().contains("TYPE_CAISSE") && nonEmptyForeign.getBoolean("TYPE_CAISSE")) {
rowClient = null;
cptTiers = nonEmptyForeign.getForeign("ID_COMPTE_PCE");
}
 
Date dateTmp = this.date;
if (modeReglement.getObject("DATE") != null) {
dateTmp = modeReglement.getDate("DATE").getTime();
196,6 → 203,9
&& !this.rowPrefsCompte.isForeignEmpty("ID_JOURNAL_CB_ATTENTE")) {
this.putValue("ID_JOURNAL", this.rowPrefsCompte.getForeignID("ID_JOURNAL_CB_ATTENTE"));
}
if (typeRegRow.contains("ID_COMPTE_PCE_CAISSE") && (rowClient == null || rowClient.isUndefined()) && !typeRegRow.isForeignEmpty("ID_COMPTE_PCE_CAISSE")) {
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES);
}
 
int idCompteClient = cptTiers != null && !cptTiers.isUndefined() ? cptTiers.getID() : rowClient.getInt("ID_COMPTE_PCE");
if (avance) {
214,11 → 224,23
}
}
}
boolean genEcrDisabled = DefaultNXProps.getInstance().getBooleanValue(GenerationMvtSaisieVenteFacture.NOT_GEN_ECRITURE, false);
if (typeRegRow.contains("ID_COMPTE_PCE_CAISSE") && (rowClient == null || rowClient.isUndefined()) && !typeRegRow.isForeignEmpty("ID_COMPTE_PCE_CAISSE")) {
if (!modeReglement.isForeignEmpty("ID_BANQUE")) {
rowClient = null;
final SQLRow foreign = modeReglement.getForeign("ID_BANQUE");
if (foreign.getBoolean("TYPE_CAISSE")) {
idCompteClient = foreign.getForeignID("ID_COMPTE_PCE");
}
}
}
this.putValue("ID_COMPTE_PCE", idCompteClient);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc.getLongValue()));
 
if (!genEcrDisabled) {
this.ecrClient = ajoutEcriture();
}
 
// compte de reglement, caisse, cheque, ...
if (typeRegRow.getID() == TypeReglementSQLElement.ESPECE) {
235,6 → 257,11
throw new SQLException(e);
}
}
 
if (typeRegRow.contains("ID_COMPTE_PCE_CAISSE") && (rowClient == null || rowClient.isUndefined()) && !typeRegRow.isForeignEmpty("ID_COMPTE_PCE_CAISSE")) {
this.putValue("ID_COMPTE_PCE", typeRegRow.getForeignID("ID_COMPTE_PCE_CAISSE"));
}
 
if (typeRegRow.getID() == TypeReglementSQLElement.CB && this.rowPrefsCompte.getTable().contains("ID_COMPTE_PCE_CB_ATTENTE")
&& !this.rowPrefsCompte.isForeignEmpty("ID_COMPTE_PCE_CB_ATTENTE")) {
 
243,8 → 270,9
 
this.putValue("DEBIT", Long.valueOf(ttc.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
ajoutEcriture();
 
}
// FIXME remove getConf
SQLRow rowSoc = ComptaPropsConfiguration.getInstanceCompta().getRowSociete();
if (rowSoc.getTable().contains("TVA_ENCAISSEMENT") && rowSoc.getBoolean("TVA_ENCAISSEMENT")) {
259,12 → 287,16
this.putValue("ID_COMPTE_PCE", rowCompteTvaCol.getID());
this.putValue("DEBIT", Long.valueOf(tva));
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
ajoutEcriture();
}
 
this.putValue("ID_COMPTE_PCE", rowCompteTvaEnc.getID());
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(tva));
if (!genEcrDisabled) {
ajoutEcriture();
}
 
}
}
294,10 → 326,11
this.idMvt = getNewMouvement("ECHEANCE_CLIENT", 1, mvtSource.getID(), mvtSource.getInt("ID_PIECE"));
valEcheance.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
valEcheance.put("DATE", dateEch);
valEcheance.put("RG", modeReglement.getBoolean("RG"));
valEcheance.put("MONTANT", Long.valueOf(ttc.getLongValue()));
valEcheance.put("ID_CLIENT", rowClient == null ? null : rowClient.getID());
valEcheance.put("TIERS", tiers);
valEcheance.put("ID_COMPTE_PCE_TIERS", cptTiers == null || !cptTiers.isUndefined() ? null : cptTiers.getID());
valEcheance.put("ID_COMPTE_PCE_TIERS", cptTiers == null || cptTiers.isUndefined() ? mvtSource.getTable().getTable("COMPTE_PCE").getUndefinedIDNumber() : cptTiers.getID());
if (source.getTable().equals(tableSaisieVenteFacture)) {
valEcheance.put("ID_SAISIE_VENTE_FACTURE", source.getID());
}
370,6 → 403,9
}
 
public void doLettrageAuto(final SQLRowAccessor source, Date dateLettrage) {
 
if (this.ecrClient != null) {
 
// A. On lettre les critures client (facture ET reglement)
// A1. Recherche criture client de facturation
 
421,6 → 457,7
e.printStackTrace();
}
}
}
 
private void paiementCheque(Date dateEch, SQLRow source, PrixTTC ttc, SQLRow rowClient, SQLRow modeRegl, SQLRow mvtSource, boolean avance, String tiers, SQLRowAccessor cptTiers)
throws SQLException {
477,6 → 514,21
if (rowPrefsCompte.getObject("ID_JOURNAL_VALEUR_ENCAISSEMENT") != null && !rowPrefsCompte.isForeignEmpty("ID_JOURNAL_VALEUR_ENCAISSEMENT")) {
idJournal = rowPrefsCompte.getForeignID("ID_JOURNAL_VALEUR_ENCAISSEMENT");
}
// compte de reglement, caisse, cheque, ...
int idCompteRegl = rowPrefsCompte.getInt("ID_COMPTE_PCE_VALEUR_ENCAISSEMENT");
if (idCompteRegl <= 1) {
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("ValeurEncaissement");
}
if (modeRegl != null) {
final SQLRowAccessor nonEmptyForeign = modeRegl.getNonEmptyForeign("ID_BANQUE");
if (nonEmptyForeign != null && nonEmptyForeign.getTable().contains("TYPE_CAISSE") && nonEmptyForeign.getBoolean("TYPE_CAISSE")) {
final SQLRow rowTypeREgl = tableMouvement.getTable("TYPE_REGLEMENT").getRow(TypeReglementSQLElement.CHEQUE);
if (rowTypeREgl.contains("ID_COMPTE_PCE_CAISSE") && (rowClient == null || rowClient.isUndefined()) && !rowTypeREgl.isForeignEmpty("ID_COMPTE_PCE_CAISSE")) {
idCompteRegl = rowTypeREgl.getForeignID("ID_COMPTE_PCE_CAISSE");
idJournal = JournalSQLElement.CAISSES;
}
}
}
 
this.putValue("ID_JOURNAL", idJournal);
this.putValue("ID_COMPTE_PCE", idCompteClient);
483,13 → 535,10
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(ttc.getLongValue()));
 
boolean genEcrDisabled = DefaultNXProps.getInstance().getBooleanValue(GenerationMvtSaisieVenteFacture.NOT_GEN_ECRITURE, false);
if (!genEcrDisabled) {
this.ecrClient = ajoutEcriture();
 
// compte de reglement, caisse, cheque, ...
int idCompteRegl = rowPrefsCompte.getInt("ID_COMPTE_PCE_VALEUR_ENCAISSEMENT");
if (idCompteRegl <= 1) {
idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("ValeurEncaissement");
}
this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
this.putValue("DEBIT", Long.valueOf(ttc.getLongValue()));
this.putValue("CREDIT", Long.valueOf(0));
496,6 → 545,7
 
ajoutEcriture();
}
}
 
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieVenteFacture.java
16,15 → 16,20
import org.openconcerto.erp.core.common.ui.TotalCalculator;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.generationDoc.SheetXml;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
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.preferences.SQLPreferences;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
 
42,6 → 47,7
public class GenerationMvtSaisieVenteFacture extends GenerationEcritures implements Runnable {
 
public static final String ID = "accounting.records.invoice.sales";
public static final String NOT_GEN_ECRITURE = "accounting.invoice.generation.disable";
private static final String source = "SAISIE_VENTE_FACTURE";
public static final Integer journal = Integer.valueOf(JournalSQLElement.VENTES);
private int idSaisieVenteFacture;
99,13 → 105,10
 
SQLRow saisieRow = GenerationMvtSaisieVenteFacture.saisieVFTable.getRow(this.idSaisieVenteFacture);
setRowAnalytiqueSource(saisieRow);
boolean genEcrDisabled = DefaultNXProps.getInstance().getBooleanValue(GenerationMvtSaisieVenteFacture.NOT_GEN_ECRITURE, false);
 
this.putValue("ID_JOURNAL", GenerationMvtSaisieVenteFacture.journal);
SQLRow clientRow = saisieRow.getForeignRow("ID_CLIENT");
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue());
// Total des acomptes déjà versés sur la facture
long montantAcompteTTC = 0;
 
int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
 
Boolean acompte = saisieRow.getBoolean("ACOMPTE");
114,7 → 117,36
} else {
this.nom = "Fact. vente " + saisieRow.getObject("NUMERO").toString();
}
 
boolean typeCaisse = false;
SQLRow modeRegl = saisieRow.getForeignRow("ID_MODE_REGLEMENT");
final SQLRow typeRegRow = modeRegl.getForeignRow("ID_TYPE_REGLEMENT");
final SQLRowAccessor nonEmptyForeign = modeRegl.getNonEmptyForeign("ID_BANQUE");
if (nonEmptyForeign != null && nonEmptyForeign.getTable().contains("TYPE_CAISSE") && nonEmptyForeign.getBoolean("TYPE_CAISSE")) {
typeCaisse = true;
idCompteClient = nonEmptyForeign.getForeignID("ID_COMPTE_PCE");
Number idJournal = nonEmptyForeign.getNonEmptyForeignIDNumber("ID_JOURNAL");
if (idJournal != null) {
this.putValue("ID_JOURNAL", idJournal);
} else {
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES);
}
this.nom += " (" + typeRegRow.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
} else {
this.nom += " " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
}
 
if (SQLPreferences.getMemCached(saisieRow.getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.ECRITURE_FACTURE_REF_LIBELLE, false)) {
if (saisieRow.getString("NOM") != null && saisieRow.getString("NOM").trim().length() > 0)
this.nom += " " + StringUtils.limitLength(saisieRow.getString("NOM"), 30);
}
 
 
// Calcul des montants
PrixTTC prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue());
// Total des acomptes déjà versés sur la facture
long montantAcompteTTC = 0;
 
this.putValue("NOM", this.nom);
 
// iniatilisation des valeurs de la map
123,7 → 155,7
provider.putLabel(saisieRow, this.mEcritures);
 
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
176,7 → 208,9
this.putValue("ID_COMPTE_PCE", rowCompl.getForeignID("ID_COMPTE_PCE"));
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(taxeC));
if (!genEcrDisabled) {
ajoutEcriture();
}
taxe += taxeC;
// this.putValue("ID_COMPTE_PCE",
// rowCompl.getForeignID("ID_COMPTE_PCE_PRODUITS"));
197,9 → 231,11
this.putValue("ID_COMPTE_PCE", idComptePCE);
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", Long.valueOf(b - taxe));
if (!genEcrDisabled) {
ajoutEcriture();
}
}
}
 
Map<SQLRowAccessor, BigDecimal> tvaMap = calc.getMapHtTVA();
for (SQLRowAccessor rowAc : tvaMap.keySet()) {
208,9 → 244,11
this.putValue("ID_COMPTE_PCE", rowAc.getID());
this.putValue("DEBIT", Long.valueOf(0));
this.putValue("CREDIT", longValue);
if (!genEcrDisabled) {
ajoutEcriture();
}
}
}
 
// compte Clients
 
226,7 → 264,9
}
this.putValue("DEBIT", ttcLongValue);
this.putValue("CREDIT", Long.valueOf(0));
if (!genEcrDisabled) {
ajoutEcriture();
}
 
// TODO Gestion des factures d'acomptes
// Solde des acomptes
303,9 → 343,8
 
if (genereReglement) {
// 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") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
 
String label = this.nom + " (" + typeRegRow.getString("NOM") + ") ";
int idAvoir = saisieRow.getInt("ID_AVOIR_CLIENT");
if (idAvoir > 1) {
// SQLRow avoirRow = base.getTable("AVOIR_CLIENT").getRow(idAvoir);
312,11 → 351,46
long l = ((Number) saisieRow.getObject("T_AVOIR_TTC")).longValue();
prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue() - l);
}
prixTTC = new PrixTTC(saisieRow.getLong("NET_A_PAYER"));
final long totalNet = saisieRow.getLong("NET_A_PAYER");
final SQLRow rowClient;
final SQLRow rowCptTiers;
if (typeCaisse) {
rowClient = null;
rowCptTiers = modeRegl.getForeign("ID_BANQUE").getForeign("ID_COMPTE_PCE");
} else {
rowClient = clientRow;
rowCptTiers = null;
}
final String tiers = clientRow.getString("NOM");
 
if (saisieRow.contains("POURCENT_RG") && saisieRow.getBigDecimal("POURCENT_RG") != null && saisieRow.getBigDecimal("POURCENT_RG").signum() != 0) {
long totalRG = new BigDecimal(totalNet).multiply(saisieRow.getBigDecimal("POURCENT_RG"), DecimalUtils.HIGH_PRECISION).movePointLeft(2).setScale(0, RoundingMode.HALF_UP)
.longValue();
PrixTTC prixRG = new PrixTTC(totalRG);
prixTTC = new PrixTTC(totalNet - totalRG);
if (prixTTC.getLongValue() > 0) {
new GenerationReglementVenteNG(label.trim(), clientRow, prixTTC, this.date, modeRegl, saisieRow, mvtTable.getRow(idMvt));
new GenerationReglementVenteNG(label.trim(), rowClient, prixTTC, this.date, modeRegl, saisieRow, mvtTable.getRow(idMvt), true, false, tiers, rowCptTiers);
}
if (prixRG.getLongValue() > 0) {
SQLRowValues rowValsMdrRg = new SQLRowValues(modeRegl.getTable());
rowValsMdrRg.put("AJOURS", 365);
rowValsMdrRg.put("LENJOUR", 0);
rowValsMdrRg.put("COMPTANT", Boolean.FALSE);
rowValsMdrRg.put("FIN_MOIS", Boolean.FALSE);
rowValsMdrRg.put("DATE_FACTURE", Boolean.TRUE);
rowValsMdrRg.put("RG", Boolean.TRUE);
rowValsMdrRg.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.INDEFINI);
final SQLRow rowMdrRG = rowValsMdrRg.commit();
new GenerationReglementVenteNG(label.trim(), rowClient, prixRG, this.date, rowMdrRG, saisieRow, mvtTable.getRow(idMvt), true, false, tiers, rowCptTiers);
}
} else {
prixTTC = new PrixTTC(totalNet);
if (prixTTC.getLongValue() > 0) {
new GenerationReglementVenteNG(label.trim(), rowClient, prixTTC, this.date, modeRegl, saisieRow, mvtTable.getRow(idMvt), true, false, tiers, rowCptTiers);
}
}
 
}
// Mise à jour de mouvement associé à la facture
 
SQLRowValues valSasieVF = new SQLRowValues(GenerationMvtSaisieVenteFacture.saisieVFTable);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtDepotChequeClient.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
28,6 → 28,9
 
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
90,7 → 93,21
int idJrnl = this.banque.getForeignID("ID_JOURNAL");
this.putValue("ID_JOURNAL", idJrnl);
}
if (!depot.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
SQLRow rowBanque = depot.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
if (rowBanque.getTable().contains("TYPE_CAISSE") && rowBanque.getBoolean("TYPE_CAISSE")) {
final SQLRow row = rowBanque.getTable().getTable("TYPE_REGLEMENT").getRow(TypeReglementSQLElement.CHEQUE);
if (row.getTable().contains("ID_COMPTE_PCE_CAISSE")) {
Number n = row.getNonEmptyForeignIDNumber("ID_COMPTE_PCE_CAISSE");
if (n != null) {
this.putValue("ID_JOURNAL", JournalSQLElement.CAISSES);
}
}
}
}
 
boolean genEcrDisabled = DefaultNXProps.getInstance().getBooleanValue(GenerationMvtSaisieVenteFacture.NOT_GEN_ECRITURE, false);
 
List<Integer> pieceIDs = new ArrayList<Integer>();
SQLRowValues rowValsDepotElt = new SQLRowValues(depot.getTable().getTable("DEPOT_CHEQUE_ELEMENT"));
rowValsDepotElt.putNulls("MONTANT", "TIERS", "PIECE");
131,20 → 148,36
this.putValue("ID_COMPTE_PCE", new Integer(idCompteClient));
this.putValue("DEBIT", new Long(0));
this.putValue("CREDIT", new Long(sqlRowAccessor.getLong("MONTANT")));
if (!genEcrDisabled) {
SQLRow insertedRow = ajoutEcriture();
 
sqlRowAccessor.createEmptyUpdateRow().put("ID_ECRITURE", insertedRow.getID()).getGraph().store(StoreMode.COMMIT, false);
}
sqlRowAccessor.getForeign("ID_CHEQUE_A_ENCAISSER").createEmptyUpdateRow().put("ENCAISSE", Boolean.TRUE).getGraph().store(StoreMode.COMMIT, false);
}
// compte de reglement cheque, ...
fillCompteBanqueFromRow(depot, "VenteCheque", false);
if (!depot.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
SQLRow rowBanque = depot.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
if (rowBanque.getTable().contains("TYPE_CAISSE") && rowBanque.getBoolean("TYPE_CAISSE")) {
final SQLRow row = rowBanque.getTable().getTable("TYPE_REGLEMENT").getRow(TypeReglementSQLElement.CHEQUE);
if (row.getTable().contains("ID_COMPTE_PCE_CAISSE")) {
Number n = row.getNonEmptyForeignIDNumber("ID_COMPTE_PCE_CAISSE");
if (n != null) {
this.putValue("ID_COMPTE_PCE", n);
}
}
}
}
 
this.putValue("NOM", this.nom);
this.putValue("DEBIT", new Long(this.montant));
this.putValue("CREDIT", new Long(0));
if (!genEcrDisabled) {
SQLRow insertedRow = ajoutEcriture();
 
depot.createEmptyUpdateRow().put("ID_MOUVEMENT", idMvt).put("ID_ECRITURE", insertedRow.getID()).getGraph().store(StoreMode.COMMIT, false);
 
} else {
depot.createEmptyUpdateRow().put("ID_MOUVEMENT", idMvt).getGraph().store(StoreMode.COMMIT, false);
}
pieceIDs.add(mouvementTable.getRow(idMvt).getForeignID("ID_PIECE"));
lettrageAuto(pieceIDs, this.date);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtSaisieKm.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
61,7 → 61,7
getNewMouvement(GenerationMvtSaisieKm.source, this.idSaisieKm, 1, rowValsPiece);
 
// gnération des ecritures
SQLTable tableElt = Configuration.getInstance().getRoot().findTable("SAISIE_KM_ELEMENT");
SQLTable tableElt = table.getDBRoot().findTable("SAISIE_KM_ELEMENT");
List<SQLRow> set = saisieRow.getReferentRows(tableElt);
 
SQLTable tableAssoc = Configuration.getInstance().getRoot().findTable("ASSOCIATION_ANALYTIQUE");
70,6 → 70,9
 
int idCpt = ComptePCESQLElement.getId(rowElement.getString("NUMERO"), rowElement.getString("NOM"));
 
if (ecritureTable.contains("DATE_ECHEANCE") && table.getDBRoot().findTable("SAISIE_KM_ELEMENT").contains("DATE_ECHEANCE")) {
this.putValue("DATE_ECHEANCE", rowElement.getObject("DATE_ECHEANCE"));
}
// Ajout de l'écriture
this.putValue("ID_COMPTE_PCE", new Integer(idCpt));
this.putValue("NOM", rowElement.getString("NOM_ECRITURE"));
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/provider/SalesInvoiceAccountingRecordsProvider.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
15,9 → 15,11
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.StringUtils;
 
import java.util.Map;
40,7 → 42,21
} else {
nom = "Fact. vente " + rowSource.getObject("NUMERO").toString();
}
SQLRowAccessor modeRegl = rowSource.getForeign("ID_MODE_REGLEMENT");
final SQLRowAccessor typeRegRow = modeRegl.getForeign("ID_TYPE_REGLEMENT");
final SQLRowAccessor nonEmptyForeign = modeRegl.getNonEmptyForeign("ID_BANQUE");
if (nonEmptyForeign != null && nonEmptyForeign.getTable().contains("TYPE_CAISSE") && nonEmptyForeign.getBoolean("TYPE_CAISSE")) {
 
nom += " (" + typeRegRow.getString("NOM") + ") ";
}
 
nom += " " + StringUtils.limitLength(rowSource.getForeign("ID_CLIENT").getString("NOM"), 20);
 
if (SQLPreferences.getMemCached(rowSource.getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.ECRITURE_FACTURE_REF_LIBELLE, false)) {
if (rowSource.getString("NOM") != null && rowSource.getString("NOM").trim().length() > 0)
nom += " " + StringUtils.limitLength(rowSource.getString("NOM"), 30);
}
 
values.put("NOM", nom);
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Mouvement.java
25,6 → 25,7
public class Mouvement {
private String numero;
private List<Ecriture> ecritures = new ArrayList<>();
private List<MouvementGED> gedURLs;
private Number id;
private BigDecimal debit = BigDecimal.ZERO;
private BigDecimal credit = BigDecimal.ZERO;
62,6 → 63,22
return this.id;
}
 
public List<MouvementGED> getURLs() {
return this.gedURLs;
}
 
public void addURL(MouvementGED e) {
if (this.gedURLs == null) {
this.gedURLs = new ArrayList<>();
}
e.setEcriture(this);
this.gedURLs.add(e);
}
 
public boolean hasURLs() {
return this.gedURLs != null;
}
 
SQLInsert createInsert(DBRoot root, User user) {
final SQLInsert insert = new SQLInsert();
final SQLTable table = root.getTable("MOUVEMENT");
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationEcritures.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
482,7 → 482,28
final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
SQLRow rowDefaultCptPort;
if (achat) {
if (rowTVAPort.getFloat("TAUX") > 0) {
rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS_ACHAT"));
if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
try {
rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortAchatSoumisTVA");
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS_ACHAT"));
if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
try {
rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortAchatNonSoumisTVA");
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else {
if (rowTVAPort.getFloat("TAUX") > 0) {
rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS"));
if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
try {
501,6 → 522,7
}
}
}
}
final SQLRowValues rowValsArt = rowValsPort.putRowValues("ID_ARTICLE");
rowValsArt.put(achat ? "ID_COMPTE_PCE_ACHAT" : "ID_COMPTE_PCE", rowDefaultCptPort.getID());
rowValsArt.put("ID_TAXE_COMPLEMENTAIRE", null);
606,8 → 628,14
SQLRow rowJournal = rowBanque.getForeignRow("ID_JOURNAL");
this.mEcritures.put("ID_JOURNAL", rowJournal.getID());
}
} else if (sqlRow.getTable().contains("ID_TYPE_REGLEMENT") && !sqlRow.isForeignEmpty("ID_TYPE_REGLEMENT")) {
SQLRow rowType = sqlRow.getForeignRow("ID_TYPE_REGLEMENT");
if (rowType.getTable().contains("ID_JOURNAL") && !rowType.isForeignEmpty("ID_JOURNAL")) {
SQLRow rowJournal = rowType.getForeignRow("ID_JOURNAL");
this.mEcritures.put("ID_JOURNAL", rowJournal.getID());
}
}
}
 
/**
* Définit le compte en fonction de la banque sélectionnée
615,7 → 643,7
* @param sqlRow sqlRow contenant la foreignKey Banque
* @throws Exception
*/
protected void fillCompteBanqueFromRow(SQLRow sqlRow, String defaultProps, boolean achat) throws Exception {
protected void fillCompteBanqueFromRow(SQLRow sqlRow, String defaultProps, boolean achat) throws SQLException {
int idPce = -1;
if (sqlRow.getTable().contains("ID_TYPE_REGLEMENT")) {
idPce = sqlRow.getForeign("ID_TYPE_REGLEMENT").getInt("ID_COMPTE_PCE_" + (achat ? "FOURN" : "CLIENT"));
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementAchat.java
33,7 → 33,7
import java.util.Map;
 
// FIXME mettre toute les generations dans des threads à part
public final class GenerationMvtReglementAchat extends GenerationEcritures implements Runnable {
public final class GenerationMvtReglementAchat extends GenerationEcritures {
 
private int idSaisieAchat;
 
45,11 → 45,11
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
private int idPere = 1; // Id du mouvement pere
 
public GenerationMvtReglementAchat(SQLRow rowAchat, int idMvt) {
public GenerationMvtReglementAchat(SQLRow rowAchat, int idMvt) throws Exception {
setRowAnalytiqueSource(rowAchat);
this.idSaisieAchat = rowAchat.getID();
this.idPere = idMvt;
new Thread(GenerationMvtReglementAchat.this).start();
genereReglement();
}
 
private void genereReglement() throws Exception {
234,12 → 234,4
 
}
 
public void run() {
try {
genereReglement();
} catch (Exception e) {
ExceptionHandler.handle("Erreur pendant la générations des écritures comptables", e);
e.printStackTrace();
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/Exercice.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
380,10 → 380,27
 
SQLUpdate.executeMultipleWithBatch(sysRoot, mvtUpdate);
 
// Creation des inserts des écritures sans analytique
final List<SQLInsert> insertsEcrituresSansAnalytique = new ArrayList<>(insertsMouvement.size() * 2);
final List<SQLInsert> insertsEcrituresAvecAnalytique = new ArrayList<>(insertsMouvement.size() * 2);
final List<Ecriture> ecrituresAvecAnalytique = new ArrayList<>(insertsEcrituresAvecAnalytique.size());
final List<SQLInsert> insertsURL = new ArrayList<>(insertsMouvement.size());
for (int i = 0; i < pieces.size(); i++) {
Piece piece = pieces.get(i);
piece.setId(idsPieces.get(i));
for (Mouvement m : piece.getMouvements()) {
if (m.hasURLs()) {
List<MouvementGED> urLs = m.getURLs();
for (MouvementGED urls : urLs) {
insertsURL.add(urls.createInsert(root, user));
}
}
}
}
if (!insertsURL.isEmpty()) {
SQLInsert.executeSimilarInserts(sysRoot, insertsURL, false);
}
 
// Creation des inserts des écritures sans liens ( analytique)
final List<SQLInsert> insertsEcrituresSansLiens = new ArrayList<>(insertsMouvement.size() * 2);
final List<SQLInsert> insertsEcrituresAvecLiens = new ArrayList<>(insertsMouvement.size() * 2);
final List<Ecriture> ecrituresAvecLiens = new ArrayList<>(insertsEcrituresAvecLiens.size());
for (Piece p : pieces) {
final List<Mouvement> mouvements = p.getMouvements();
final int stop = mouvements.size();
391,32 → 408,43
final Mouvement m = mouvements.get(i);
for (Ecriture e : m.getEcritures()) {
if (e.hasAnalytique()) {
insertsEcrituresAvecAnalytique.add(e.createInsert(root, user));
ecrituresAvecAnalytique.add(e);
insertsEcrituresAvecLiens.add(e.createInsert(root, user));
ecrituresAvecLiens.add(e);
} else {
insertsEcrituresSansAnalytique.add(e.createInsert(root, user));
insertsEcrituresSansLiens.add(e.createInsert(root, user));
}
}
 
}
}
if (!insertsEcrituresSansLiens.isEmpty()) {
// Insertions des écritures des mouvements
SQLInsert.executeSimilarInserts(sysRoot, insertsEcrituresSansAnalytique, false);
SQLInsert.executeSimilarInserts(sysRoot, insertsEcrituresSansLiens, false);
}
// Insertions des écritures avec analytique
if (!ecrituresAvecAnalytique.isEmpty()) {
final List<Number> idsEcritues = SQLInsert.executeSimilarInserts(sysRoot, insertsEcrituresAvecAnalytique, true);
if (!ecrituresAvecLiens.isEmpty()) {
final List<Number> idsEcritues = SQLInsert.executeSimilarInserts(sysRoot, insertsEcrituresAvecLiens, true);
// Analytique
final List<SQLInsert> insertsAssociationAnalytique = new ArrayList<>(insertsEcrituresAvecAnalytique.size());
final int size = ecrituresAvecAnalytique.size();
final List<SQLInsert> insertsAssociationAnalytique = new ArrayList<>(insertsEcrituresAvecLiens.size());
final List<SQLInsert> insertsURLs = new ArrayList<>(insertsEcrituresAvecLiens.size());
final int size = ecrituresAvecLiens.size();
for (int i = 0; i < size; i++) {
final Ecriture e = ecrituresAvecAnalytique.get(i);
final Ecriture e = ecrituresAvecLiens.get(i);
e.setId(idsEcritues.get(i));
if (e.hasAnalytique()) {
for (AssociationAnalytique a : e.getAssociationsAnalytiques()) {
insertsAssociationAnalytique.add(a.createInsert(root, user));
}
}
 
}
if (!insertsAssociationAnalytique.isEmpty()) {
SQLInsert.executeSimilarInserts(sysRoot, insertsAssociationAnalytique, false);
}
if (!insertsURLs.isEmpty()) {
SQLInsert.executeSimilarInserts(sysRoot, insertsURLs, false);
}
}
for (Piece p : pieces) {
final List<Mouvement> mouvements = p.getMouvements();
for (Mouvement m : mouvements) {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtAcompte.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
18,13 → 18,12
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.GestionDevise;
 
import java.sql.SQLException;
import java.util.Date;
 
public final class GenerationMvtAcompte extends GenerationEcritures implements Runnable {
public final class GenerationMvtAcompte extends GenerationEcritures {
 
private int idSalarie;
private long montant;
44,10 → 43,10
this.montant = GestionDevise.parseLongCurrency(String.valueOf(rowAcompte.getFloat("MONTANT")));
SQLRow rowSal = tableSalarie.getRow(this.idSalarie);
this.idMvt = getNewMouvement("ACOMPTE", this.idAcompte, 1, "Acompte " + rowSal.getString("NOM"));
new Thread(GenerationMvtAcompte.this).start();
genereComptaAcompte();
}
 
private void genereComptaAcompte() throws Exception {
private void genereComptaAcompte() throws SQLException {
 
System.out.println("Génération des ecritures du mouvement " + this.idMvt);
 
99,12 → 98,4
 
}
 
public void run() {
 
try {
genereComptaAcompte();
} catch (Exception e) {
ExceptionHandler.handle("Erreur lors de la génération des mouvements", e);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/MouvementGED.java
New file
0,0 → 1,48
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.generationEcritures;
 
import org.openconcerto.erp.core.edm.Attachment;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLInsert;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.users.User;
 
public class MouvementGED {
private String url;
private Mouvement mvt;
 
public MouvementGED(String url) {
this.url = url;
}
 
public void setEcriture(Mouvement mvt) {
this.mvt = mvt;
}
 
public SQLInsert createInsert(DBRoot root, User user) {
final SQLInsert insert = new SQLInsert();
final SQLTable table = root.getTable("ATTACHMENT");
insert.add(table.getField("SOURCE_TABLE"), "MOUVEMENT");
insert.add(table.getField("SOURCE_ID"), this.mvt.getId().intValue());
insert.add(table.getField("NAME"), this.url);
insert.add(table.getField("FILENAME"), this.url);
insert.add(table.getField("MIMETYPE"), Attachment.MIMETYPE_URL);
insert.add(table.getField("FILESIZE"), 0);
insert.add(table.getField("STORAGE_PATH"), "");
insert.add(table.getField("STORAGE_FILENAME"), "");
return insert;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtFichePaye.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
57,7 → 57,7
 
private Map<String, SQLTable> mapTableSource = new HashMap<String, SQLTable>();
 
public GenerationMvtFichePaye(int[] idFichePaye, String mois, String annee) throws SQLException {
public GenerationMvtFichePaye(int[] idFichePaye, String mois, String annee, Date d) throws SQLException {
 
setRowAnalytiqueSource(null);
SQLTable tableNet = Configuration.getInstance().getBase().getTable("RUBRIQUE_NET");
73,6 → 73,7
this.idFichePaye = idFichePaye;
this.annee = annee;
this.mois = mois;
this.date = d;
this.idMvt = getNewMouvement("", 1, 1, "Paye " + this.mois + " " + this.annee);
new Thread(GenerationMvtFichePaye.this).start();
}
98,7 → 99,7
// SQLRow rowFiche =
// Configuration.getInstance().getBase().getTable("FICHE_PAYE").getRow(this.idFichePaye);
// iniatilisation des valeurs de la map
this.date = new Date();
// this.date = new Date();
 
// SQLRow rowMois = tableMois.getRow(rowFiche.getInt("ID_MOIS"));
// SQLRow rowSal = tableSalarie.getRow(rowFiche.getInt("ID_SALARIE"));
348,15 → 349,19
 
Tuple2<Integer, Integer> t = mapCaisse.get(idCaisse);
// on recupere les comptes tiers et charge de la caisse associée
int idCompteCharge = (t == null ? ComptePCESQLElement.getId("645") : t.get0());
// }
int idCompteCharge;
if (rowSource.getString("NUMERO_COMPTE_PCE_CHARGES") != null && rowSource.getString("NUMERO_COMPTE_PCE_CHARGES").trim().length() > 0) {
idCompteCharge = ComptePCESQLElement.getId(rowSource.getString("NUMERO_COMPTE_PCE_CHARGES"));
} else {
idCompteCharge = (t == null ? ComptePCESQLElement.getId("645") : t.get0());
}
int idCompteTiers;
if (rowSource.getString("NUMERO_COMPTE_PCE") != null && rowSource.getString("NUMERO_COMPTE_PCE").trim().length() > 0) {
idCompteTiers = ComptePCESQLElement.getId(rowSource.getString("NUMERO_COMPTE_PCE"));
} else {
idCompteTiers = (t == null ? ComptePCESQLElement.getId("437") : t.get1());
}
 
// int idCompteTiers = rowCaisse.getInt("ID_COMPTE_PCE_TIERS");
// if (idCompteTiers <= 1) {
int idCompteTiers = (t == null ? ComptePCESQLElement.getId("437") : t.get1());
// int idCompteTiers = ComptePCESQLElement.getId("437");
// }
 
// Cotisations sal.
if (row.getObject("MONTANT_SAL_DED") != null && row.getFloat("MONTANT_SAL_DED") != 0) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtFactureFournisseur.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
22,14 → 22,14
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
 
public class GenerationMvtFactureFournisseur extends GenerationEcritures implements Runnable {
public class GenerationMvtFactureFournisseur extends GenerationEcritures {
 
public static final String ID = "accounting.records.supplychain.order";
 
42,18 → 42,18
private static final SQLTable tableMvt = base.getTable("MOUVEMENT");
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
 
public GenerationMvtFactureFournisseur(SQLRow row, int idMvt) {
public GenerationMvtFactureFournisseur(SQLRow row, int idMvt) throws SQLException {
setRowAnalytiqueSource(row);
this.idFacture = row.getID();
this.idMvt = idMvt;
(new Thread(GenerationMvtFactureFournisseur.this)).start();
genereMouvement();
}
 
public GenerationMvtFactureFournisseur(SQLRow row) {
public GenerationMvtFactureFournisseur(SQLRow row) throws SQLException {
this(row, 1);
}
 
public void genereMouvement() throws Exception {
public void genereMouvement() throws SQLException {
 
SQLRow saisieRow = getRowAnalytiqueSource();
// SQLRow taxeRow = base.getTable("TAXE").getRow(saisieRow.getInt("ID_TAXE"));
203,11 → 203,4
 
}
 
public void run() {
try {
genereMouvement();
} catch (Exception e) {
ExceptionHandler.handle("Erreur pendant la générations des écritures comptables", e);
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/generationEcritures/GenerationMvtReglementFactureFournisseur.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
38,7 → 38,7
import java.util.Map;
 
// FIXME mettre toute les generations dans des threads à part
public final class GenerationMvtReglementFactureFournisseur extends GenerationEcritures implements Runnable {
public final class GenerationMvtReglementFactureFournisseur extends GenerationEcritures {
 
private int idfacture;
 
50,13 → 50,13
private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
private int idPere = 1; // Id du mouvement pere
 
public GenerationMvtReglementFactureFournisseur(int idFacture, int idMvt) {
public GenerationMvtReglementFactureFournisseur(int idFacture, int idMvt) throws SQLException {
this.idfacture = idFacture;
this.idPere = idMvt;
new Thread(GenerationMvtReglementFactureFournisseur.this).start();
genereReglement();
}
 
private void genereReglement() throws Exception {
private void genereReglement() throws SQLException {
 
System.out.println("Génération des ecritures du reglement du mouvement " + this.idMvt);
 
249,7 → 249,7
 
public void run() {
try {
genereReglement();
} catch (Exception e) {
ExceptionHandler.handle("Erreur pendant la générations des écritures comptables", e);
e.printStackTrace();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/purchase/importer/FacturXExporter.java
181,8 → 181,10
int lineID = 1;
for (SQLRowAccessor rowItem : factureItems) {
String productCode = rowItem.getString("CODE");
String productName = rowItem.getString("NOM").trim().length() == 0 ? "Ligne" : rowItem.getString("NOM");
 
String productName = rowItem.getString("NOM");
if (productName == null || rowItem.getString("NOM").trim().isEmpty()) {
productName = "Ligne " + lineID;
}
final BigDecimal pHT, pTTC, totalHTLigne, totalTTCLigne;
SQLRowAccessor taxeItem = rowItem.getForeign("ID_TAXE");
BigDecimal taxValue = new BigDecimal(taxeItem.getFloat("TAUX")).setScale(2, RoundingMode.HALF_UP);
193,7 → 195,7
totalTTCLigne = BigDecimal.ZERO;
} else {
pHT = rowItem.getBigDecimal("PV_HT");
pTTC = pHT.multiply(taxValue.add(BigDecimal.ONE));
pTTC = pHT.multiply(taxValue.movePointLeft(2).add(BigDecimal.ONE));
totalHTLigne = rowItem.getBigDecimal("T_PV_HT");
totalTTCLigne = rowItem.getBigDecimal("T_PV_TTC");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/FactureFournisseurSQLComponent.java
360,7 → 360,7
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
 
DefaultGridBagConstraints.lockMinimumSize(this.comptePCE);
this.add(this.comptePCE, c);
 
final SQLElement foreignElement = getElement().getForeignElement("ID_COMPTE_PCE");
367,6 → 367,7
final ComboSQLRequest comboRequest = foreignElement.getComboRequest(true);
comboRequest.setWhere(new Where(foreignElement.getTable().getField("NUMERO"), "LIKE", "6%"));
this.comptePCE.init(foreignElement, comboRequest);
 
this.addView(this.comptePCE, "ID_COMPTE_PCE");
 
// Reference
806,7 → 807,11
this.table.createArticle(idFacture, this.getElement());
 
final SQLRow row = getTable().getRow(idFacture);
try {
new GenerationMvtFactureFournisseur(row);
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la création des écritures", e);
}
 
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(row);
sheet.createDocumentAsynchronous();
842,12 → 847,16
// on supprime tout ce qui est lié à la facture
EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
eltEcr.archiveMouvementProfondeur(idMvt, false);
try {
if (idMvt > 1) {
new GenerationMvtFactureFournisseur(row, idMvt);
} else {
new GenerationMvtFactureFournisseur(row);
}
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la création des écritures", e);
}
}
final FactureFournisseurXmlSheet sheet = new FactureFournisseurXmlSheet(row);
sheet.createDocumentAsynchronous();
sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true, getElement(), row);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
26,6 → 26,9
import org.openconcerto.erp.core.supplychain.order.element.CommandeSQLElement;
import org.openconcerto.erp.core.supplychain.order.element.DemandeAchatItemSQLElement;
import org.openconcerto.erp.core.supplychain.order.ui.CommandeItemTable;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeFournisseur;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeFournisseurComboBox;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeFournisseurRowItemView;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
46,6 → 49,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.SQLRowItemView;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
205,8 → 209,11
table.setRowCatComptable(null);
}
if (getTable().contains("OFFRE_COM")) {
((SQLTextCombo) getView("OFFRE_COM").getComp()).setValue(rowF.getString("RESPONSABLE"));
final SQLRowItemView view = getView("OFFRE_COM");
if (view != null) {
((SQLTextCombo) view.getComp()).setValue(rowF.getString("RESPONSABLE"));
}
}
} else {
table.setRowCatComptable(null);
}
594,6 → 601,20
this.add(commSel, c);
addRequiredSQLObject(commSel, field);
 
// Etat
final JLabel labelEtat = new JLabel(getLabelFor("ETAT_COMMANDE"), SwingConstants.RIGHT);
c.gridy++;
c.gridx = 0;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(labelEtat, c);
final EtatCommandeFournisseurComboBox comboEtat = new EtatCommandeFournisseurComboBox();
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
this.add(comboEtat, c);
addView(new EtatCommandeFournisseurRowItemView(comboEtat), "ETAT_COMMANDE", REQ);
 
// Table d'élément
c.fill = GridBagConstraints.BOTH;
c.gridy++;
1099,6 → 1120,7
SQLRowValues rowVals = new SQLRowValues(getTable());
rowVals.put("T_POIDS", 0.0F);
rowVals.put("EN_COURS", Boolean.TRUE);
rowVals.put("ETAT_COMMANDE", EtatCommandeFournisseur.EN_ATTENTE.getId());
 
// User
// SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandePrixSQLComponent.java
127,6 → 127,7
this.add(dateButoire, c);
 
this.addView(dateButoire, "DATE_BUTOIRE");
 
//
// c.gridx++;
// c.weightx = 0;
547,7 → 548,7
SQLRowValues rowVals = new SQLRowValues(getTable());
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(DemandePrixSQLElement.class));
SQLElement eltComm = getElement().getForeignElement("ID_COMMERCIAL");
int idUser = UserManager.getInstance().getCurrentUserID();
int idUser = UserManager.getInstance().getCurrentUser().getId();
 
SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
 
580,14 → 581,16
*/
public void loadDemandeExistant(final int idDemande) {
 
final SQLElement demande = Configuration.getInstance().getDirectory().getElement("DEMANDE_PRIX");
final SQLElement demandeElt = Configuration.getInstance().getDirectory().getElement("DEMANDE_PRIX_ELEMENT");
final SQLElement demande = getElement();
final SQLElement demandeElt = getElement().getDirectory().getElement("DEMANDE_PRIX_ELEMENT");
 
// On duplique la demande
if (idDemande > 1) {
final SQLRow row = demande.getTable().getRow(idDemande);
final SQLRowValues rowVals = new SQLRowValues(demande.getTable());
rowVals.put("ID_AFFAIRE", row.getInt("ID_AFFAIRE"));
if (demande.getTable().contains("ID_AFFAIRE")) {
rowVals.put("ID_AFFAIRE", row.getForeignIDNumber("ID_AFFAIRE"));
}
// rowVals.put("DATE_BUTOIRE", row.getObject("DATE_BUTOIRE"));
// rowVals.put("DATE_DISPOSITION", row.getObject("DATE_DISPOSITION"));
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(DemandePrixSQLElement.class));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/DemandeAchatItemSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
72,6 → 72,7
// "ID_ETAT_DEMANDE_ACHAT_ELEMENT" integer DEFAULT 1,
// "REPRISE" boolean NOT NULL DEFAULT false,
for (String string : copyFields) {
if (getTable().contains(string)) {
if (string.startsWith("ID_")) {
rowDupl.put(string, row.getForeignID(string));
} else {
78,6 → 79,7
rowDupl.put(string, row.getObject(string));
}
}
}
rowDupl.put("DATE", new Date());
EditFrame frame = new EditFrame(getDirectory().getElement("DEMANDE_ACHAT_ELEMENT"));
frame.getSQLComponent().select(rowDupl);
103,7 → 105,9
final List<SQLRow> rows = SQLRowListRSH.fetch(IListe.get(e).getRequest().getPrimaryTable(), IListe.get(e).getSelection().getSelectedIDs());
 
for (SQLRow row : rows) {
if (getTable().contains("ID_AFFAIRE")) {
rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
}
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
rowValsCmdElt.put("ID_STYLE", idNormal);
rowValsCmdElt.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
114,9 → 118,11
BigDecimal ha = row.getForeign("ID_ARTICLE").getBigDecimal("PA_HT");
rowValsCmdElt.put("PA_HT", ha);
rowValsCmdElt.put("PRIX_METRIQUE_HA_1", ha);
rowValsCmdElt.put("PA_DEVISE", ha);
} else {
rowValsCmdElt.put("PA_HT", BigDecimal.ZERO);
rowValsCmdElt.put("PRIX_METRIQUE_HA_1", BigDecimal.ZERO);
rowValsCmdElt.put("PA_DEVISE", BigDecimal.ZERO);
}
}
 
161,7 → 167,9
SQLInjector inj = SQLInjector.getInjector(getTable(), getTable().getTable("COMMANDE_ELEMENT"));
final List<SQLRow> rows = SQLRowListRSH.fetch(IListe.get(e).getRequest().getPrimaryTable(), IListe.get(e).getSelection().getSelectedIDs());
for (SQLRow row : rows) {
if (getTable().contains("ID_AFFAIRE")) {
rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
}
SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
rowValsCmdElt.put("ID_STYLE", idNormal);
rowValsCmdElt.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
172,9 → 180,11
BigDecimal ha = row.getForeign("ID_ARTICLE").getBigDecimal("PA_HT");
rowValsCmdElt.put("PA_HT", ha);
rowValsCmdElt.put("PRIX_METRIQUE_HA_1", ha);
rowValsCmdElt.put("PA_DEVISE", ha);
} else {
rowValsCmdElt.put("PA_HT", BigDecimal.ZERO);
rowValsCmdElt.put("PRIX_METRIQUE_HA_1", BigDecimal.ZERO);
rowValsCmdElt.put("PA_DEVISE", BigDecimal.ZERO);
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeSQLElement.java
20,6 → 20,8
import org.openconcerto.erp.core.sales.order.ui.ReliquatCommandeTableModel;
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
import org.openconcerto.erp.core.supplychain.order.component.SaisieAchatSQLComponent;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeFournisseur;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeRenderer;
import org.openconcerto.erp.core.supplychain.receipt.component.BonReceptionSQLComponent;
import org.openconcerto.erp.generationDoc.gestcomm.CommandeXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
40,31 → 42,39
import org.openconcerto.sql.model.SQLTableModifiedListener;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel;
import org.openconcerto.sql.view.EditPanelListener;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.PanelFrame;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableCellRenderer;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
 
79,6 → 89,20
getRowActions().add(actionAttachment);
}
 
for (final EtatCommandeFournisseur etat : EtatCommandeFournisseur.values()) {
 
PredicateRowAction action = new PredicateRowAction(new AbstractAction(etat.getTranslation()) {
 
@Override
public void actionPerformed(ActionEvent e) {
changeStateOfRows(IListe.get(e).getSelectedRows(), etat);
}
}, false);
action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
action.setPath(Arrays.asList("Etat", "Etat", "Etat"));
getRowActions().add(action);
}
 
getRowActions().addAll(new MouseSheetXmlListeListener(this, CommandeXmlSheet.class).getRowActions());
 
// Transfert vers BR
207,6 → 231,7
if (useCommandeEnCours) {
l.add("EN_COURS");
}
l.add("ETAT_COMMANDE");
l.add("INFOS");
return l;
}
220,6 → 245,18
return l;
}
 
@Override
protected void _initTableSource(SQLTableModelSource res) {
// TODO Auto-generated method stub
super._initTableSource(res);
SQLTableModelColumn col = res.getColumn(getTable().getField("ETAT_COMMANDE"));
if (col != null) {
col.setRenderer(new EtatCommandeRenderer());
 
}
 
}
 
/*
* (non-Javadoc)
*
290,8 → 327,35
editFactureFrame.pack();
editFactureFrame.setState(JFrame.NORMAL);
editFactureFrame.setVisible(true);
editFactureFrame.addEditPanelListener(new EditPanelListener() {
 
@Override
public void modified() {
 
}
 
@Override
public void inserted(int id) {
try {
SQLRowValues rowValsTR = new SQLRowValues(getTable().getTable("TR_COMMANDE"));
rowValsTR.put("ID_COMMANDE", commandeID);
rowValsTR.put("ID_SAISIE_ACHAT", id);
rowValsTR.commit();
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de l'insertion de la ligne de transfert", e);
}
}
 
@Override
public void deleted() {
}
 
@Override
public void cancelled() {
}
});
}
 
public RowAction getCloneAction() {
return new RowAction(new AbstractAction() {
 
312,6 → 376,52
};
}
 
private void changeStateOfRows(List<SQLRowValues> l, EtatCommandeFournisseur etat) {
 
List<Integer> ids = new ArrayList<Integer>(l.size());
for (SQLRowValues sqlRowValues : l) {
ids.add(sqlRowValues.getID());
}
 
UpdateBuilder builder = new UpdateBuilder(getTable());
builder.setObject("ETAT_COMMANDE", etat.getId());
builder.setWhere(Where.inValues(getTable().getKey(), ids));
 
getTable().getDBSystemRoot().getDataSource().execute(builder.asString());
getTable().fireTableModified(-1);
 
if (etat == EtatCommandeFournisseur.ANNULEE) {
 
// Suppression des stocks si commande annulée
SQLElement eltMvtStock = getDirectory().getElement("MOUVEMENT_STOCK");
SQLSelect sel = new SQLSelect();
sel.addSelect(eltMvtStock.getTable().getField("ID"));
Where w = Where.inValues(eltMvtStock.getTable().getField("IDSOURCE"), ids);
Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
sel.setWhere(w.and(w2));
 
try {
@SuppressWarnings("rawtypes")
List res = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
if (res != null) {
for (int i = 0; i < res.size(); i++) {
Object[] tmp = (Object[]) res.get(i);
eltMvtStock.archive(((Number) tmp[0]).intValue());
}
}
 
final SQLTable tableCmdItem = getTable().getTable("COMMANDE_ELEMENT");
UpdateBuilder build = new UpdateBuilder(tableCmdItem);
build.setObject("RECU_FORCED", Boolean.TRUE);
build.setWhere(Where.inValues(tableCmdItem.getField("ID_COMMANDE"), ids));
getTable().getDBSystemRoot().getDataSource().execute(build.asString());
 
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la suppression des mouvements de stocks", e);
}
}
}
 
@Override
protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/action/ListeDesElementsACommanderAction.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
56,7 → 56,7
final String quoteQte = new SQLName(input.getAlias(eltCmd.getTable()).getAlias(), "QTE").quote();
final String quoteQteU = new SQLName(input.getAlias(eltCmd.getTable()).getAlias(), "QTE_UNITAIRE").quote();
Where w = Where.createRaw(quoteQteL + " < (" + quoteQte + "*" + quoteQteU + ")", eltCmd.getTable().getField("QTE_RECUE"), eltCmd.getTable().getField("QTE"),
eltCmd.getTable().getField("QTE_UNITAIRE"));
eltCmd.getTable().getField("QTE_UNITAIRE")).or(Where.isNull(input.getAlias(eltCmd.getTable()).getField("QTE_RECUE")));
w = w.and(new Where(eltCmd.getTable().getField("RECU_FORCED"), "=", Boolean.FALSE));
input.setWhere(w);
return input;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/ui/EtatCommandeFournisseur.java
New file
0,0 → 1,70
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.order.ui;
 
import org.openconcerto.utils.i18n.TranslationManager;
 
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
 
public enum EtatCommandeFournisseur {
 
BROUILLON(1, "supplychain.order.state.waiting", Color.RED), EN_ATTENTE(2, "supplychain.order.state.running", Color.WHITE), EN_RECEPTION(3, "supplychain.order.state.toReceipt",
Color.BLUE), RECEPTION_PARTIEL(4, "supplychain.supplychain.state.receipt.partial", Color.ORANGE), RECEPTIONNEE(5, "supplychain.order.state.receipt",
Color.GREEN), LITIGE(6, "supplychain.order.state.block", Color.RED), ANNULEE(7, "supplychain.order.state.cancelled", Color.GRAY);
 
private final int id;
private final String translationID;
private final Color color;
 
private EtatCommandeFournisseur(int id, String translationID, Color color) {
this.id = id;
this.translationID = translationID;
this.color = color;
}
 
public int getId() {
return id;
}
 
public String getTranslationID() {
return translationID;
}
 
public String getTranslation() {
final String translationForItem = TranslationManager.getInstance().getTranslationForItem(translationID);
 
return (translationForItem == null || translationForItem.trim().length() == 0) ? translationID : translationForItem;
}
 
private static final Map<Integer, EtatCommandeFournisseur> idToEnum = new HashMap<Integer, EtatCommandeFournisseur>();
static {
for (EtatCommandeFournisseur e : values())
idToEnum.put(e.getId(), e);
}
 
public static EtatCommandeFournisseur fromID(int id) {
return idToEnum.get(id);
}
 
@Override
public String toString() {
return getTranslation();
}
 
public Color getColor() {
return color;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/ui/EtatCommandeFournisseurRowItemView.java
New file
0,0 → 1,50
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.order.ui;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.sqlobject.itemview.VWRowItemView;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.ui.valuewrapper.ValueWrapper;
 
public class EtatCommandeFournisseurRowItemView extends VWRowItemView<EtatCommandeFournisseur> {
 
public EtatCommandeFournisseurRowItemView(ValueWrapper<EtatCommandeFournisseur> wrapper) {
super(wrapper);
}
 
@Override
public void setEditable(InteractionMode b) {
if (this.getComp() != null) {
this.getComp().setEnabled(b.isEnabled());
}
}
 
@Override
public void show(SQLRowAccessor r) {
 
if (r.getObject(getField().getName()) != null) {
this.getWrapper().setValue(EtatCommandeFournisseur.fromID(r.getInt(getField().getName())));
} else {
this.getWrapper().setValue(null);
}
}
 
@Override
public void update(SQLRowValues vals) {
vals.put(getField().getName(), this.isEmpty() ? SQLRowValues.SQL_DEFAULT : this.getWrapper().getValue().getId());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/ui/EtatCommandeRenderer.java
New file
0,0 → 1,49
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.order.ui;
 
import org.openconcerto.ui.table.TableCellRendererUtils;
 
import java.awt.Component;
 
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
 
public class EtatCommandeRenderer extends DefaultTableCellRenderer {
 
public EtatCommandeRenderer() {
 
}
 
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
TableCellRendererUtils.setColors(this, table, isSelected);
 
if (value != null) {
final EtatCommandeFournisseur fromID = EtatCommandeFournisseur.fromID((Integer) value);
if (fromID != null) {
this.setText(fromID.getTranslation());
this.setBackground(fromID.getColor());
} else {
this.setText("");
}
 
}
 
return this;
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/ui/EtatCommandeFournisseurComboBox.java
New file
0,0 → 1,123
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.order.ui;
 
import org.openconcerto.sql.request.SQLRowItemView;
import org.openconcerto.sql.sqlobject.itemview.RowItemViewComponent;
import org.openconcerto.ui.valuewrapper.ValueChangeSupport;
import org.openconcerto.ui.valuewrapper.ValueWrapper;
import org.openconcerto.utils.checks.ValidListener;
import org.openconcerto.utils.checks.ValidState;
import org.openconcerto.utils.doc.Documented;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
 
import javax.swing.JComboBox;
import javax.swing.JComponent;
 
public class EtatCommandeFournisseurComboBox extends JComboBox implements ValueWrapper<EtatCommandeFournisseur>, Documented, RowItemViewComponent {
private final ValueChangeSupport<EtatCommandeFournisseur> supp;
 
public EtatCommandeFournisseurComboBox() {
 
this.supp = new ValueChangeSupport<EtatCommandeFournisseur>(this);
this.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
supp.fireValueChange();
}
});
 
for (EtatCommandeFournisseur etat : EtatCommandeFournisseur.values()) {
addItem(etat);
}
}
 
@Override
public ValidState getValidState() {
return ValidState.getTrueInstance();
}
 
@Override
public void addValidListener(ValidListener l) {
this.supp.addValidListener(l);
}
 
@Override
public void removeValidListener(ValidListener l) {
this.supp.removeValidListener(l);
}
 
@Override
public void setValue(EtatCommandeFournisseur val) {
this.setSelectedItem(val);
}
 
@Override
public void resetValue() {
// TODO Auto-generated method stub
 
}
 
@Override
public EtatCommandeFournisseur getValue() {
return (EtatCommandeFournisseur) this.getSelectedItem();
}
 
@Override
public void addValueListener(PropertyChangeListener l) {
this.supp.addValueListener(l);
}
 
@Override
public void rmValueListener(PropertyChangeListener l) {
this.supp.addValueListener(l);
}
 
@Override
public void init(SQLRowItemView v) {
// TODO Auto-generated method stub
 
}
 
@Override
public String getGenericDoc() {
return "";
}
 
@Override
public String getDocId() {
 
return "EtatCommandeFournisseur";
}
 
@Override
public boolean onScreen() {
return true;
}
 
@Override
public boolean isDocTransversable() {
return false;
}
 
@Override
public JComponent getComp() {
return this;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
20,19 → 20,20
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.core.common.ui.TotalPanel;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.product.element.LotSQLElement;
import org.openconcerto.erp.core.sales.product.element.LotSQLElement.TypeLot;
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
import org.openconcerto.erp.core.supplychain.order.element.DemandeAchatItemSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionSQLElement;
import org.openconcerto.erp.core.supplychain.receipt.ui.BonReceptionItemTable;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.generationDoc.gestcomm.BonReceptionXmlSheet;
import org.openconcerto.erp.panel.PanelOOSQLComponent;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
39,6 → 40,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.ui.DefaultGridBagConstraints;
50,6 → 52,7
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.NumberUtils;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.Color;
import java.awt.GridBagConstraints;
57,8 → 60,10
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
117,6 → 122,20
return rowVals;
}
 
@Override
public synchronized ValidState getValidState() {
final ValidState validState = super.getValidState();
if (validState.isValid()) {
final LotSQLElement element = getDirectory().getElement(LotSQLElement.class);
ValidState lotState = element.getValidStateOfRowValuesTable(getRowValuesTable().getRowValuesTableModel(), TypeLot.RECEPTION);
if (lotState != ValidState.getTrueInstance()) {
return lotState;
}
}
return validState;
 
}
 
public void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
697,7 → 716,15
 
// Mise à jour de l'élément
super.update();
 
// FIXME check transaction
try {
getDirectory().getElement(LotSQLElement.class).removeLotQuantiteFromBR(Arrays.asList(getSelectedID()));
} catch (SQLException e1) {
ExceptionHandler.handle("Update Batch error", e1);
}
final List<Object> cmdFrom = ((BonReceptionSQLElement) getElement()).getCmdFrom(getSelectedID());
 
this.tableBonItem.updateField("ID_BON_RECEPTION", getSelectedID());
if (tableBonReliquatItem != null) {
this.tableBonReliquatItem.updateField("ID_BON_RECEPTION_ORIGINE", getSelectedID());
709,6 → 736,9
@Override
public void run() {
try {
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
 
// Mise à jour du stock
((BonReceptionSQLElement) getElement()).updateStock(id);
717,6 → 747,10
DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
 
return null;
}
});
 
} catch (Exception e) {
ExceptionHandler.handle("Update error", e);
}
723,9 → 757,6
}
});
 
DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
 
// generation du document
final SQLRow row = getTable().getRow(id);
final BonReceptionXmlSheet sheet = new BonReceptionXmlSheet(row);
789,6 → 820,7
 
@Override
public void select(SQLRowAccessor r) {
 
super.select(r);
if (this.tableBonReliquatItem != null) {
this.tableBonReliquatItem.getRowValuesTable().clear();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/CodeFournisseurSQLElement.java
31,6 → 31,7
protected List<String> getListFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
l.add("ID_ARTICLE");
return l;
}
 
37,6 → 38,7
protected List<String> getComboFields() {
final List<String> l = new ArrayList<String>();
l.add("CODE");
l.add("ID_ARTICLE");
return l;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionSQLElement.java
16,8 → 16,13
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.sales.product.element.LotSQLElement;
import org.openconcerto.erp.core.supplychain.order.component.SaisieAchatSQLComponent;
import org.openconcerto.erp.core.supplychain.order.ui.EtatCommandeFournisseur;
import org.openconcerto.erp.core.supplychain.receipt.component.BonReceptionSQLComponent;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.generationDoc.gestcomm.BonReceptionXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
27,7 → 32,9
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
51,10 → 58,6
import javax.swing.SwingWorker;
 
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class BonReceptionSQLElement extends ComptaSQLConfElement {
 
193,6 → 196,22
AliasedTable alias = new AliasedTable(tableCmdElement, "c");
build.setWhere(new Where(alias.getField("ID_COMMANDE"), cmds));
getTable().getDBSystemRoot().getDataSource().execute(build.asString().replaceAll(" SET", " c SET "));
 
// Update commande state
final SQLTable tableCmd = getTable().getTable("COMMANDE");
AliasedTable aliasCmd = new AliasedTable(tableCmd, "c");
Where wIN = Where.inValues(aliasCmd.getKey(), cmds);
String reqPartiel = "UPDATE " + tableCmd.getSQLName().quote() + " c SET \"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.RECEPTION_PARTIEL.getId() + " WHERE " + wIN.getClause()
+ "and (\"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.BROUILLON.getId() + " or \"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.EN_ATTENTE.getId() + ") "
+ "and (select SUM(i.\"QTE_RECUE\") from " + tableCmdElement.getSQLName().quote() + " i" + " where i.\"ID_COMMANDE\"=c.\"ID\" and i.\"ARCHIVE\"=0)>0";
getTable().getDBSystemRoot().getDataSource().execute(reqPartiel);
 
String req = "UPDATE " + tableCmd.getSQLName().quote() + " c SET \"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.RECEPTIONNEE.getId() + " WHERE " + wIN.getClause() + "and (\"ETAT_COMMANDE\"="
+ EtatCommandeFournisseur.BROUILLON.getId() + " or \"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.EN_ATTENTE.getId() + " or c.\"ETAT_COMMANDE\"="
+ EtatCommandeFournisseur.EN_RECEPTION.getId() + " or c.\"ETAT_COMMANDE\"=" + EtatCommandeFournisseur.RECEPTION_PARTIEL.getId() + ") "
+ "and (select SUM((i.\"QTE\"*i.\"QTE_UNITAIRE\")-i.\"QTE_RECUE\") from " + tableCmdElement.getSQLName().quote() + " i" + " where i.\"ID_COMMANDE\"=c.\"ID\" and i.\"ARCHIVE\"=0)<=0";
getTable().getDBSystemRoot().getDataSource().execute(req);
 
}
 
@Override
219,6 → 238,7
}
}
}
getDirectory().getElement(LotSQLElement.class).removeLotQuantiteFromBR(ids);
super.archive(trees, cutLinks);
for (Integer id : ids) {
 
239,6 → 259,13
public void updateStock(int id) throws SQLException {
 
SQLRow row = getTable().getRow(id);
 
final SQLTable tableBrItem = getTable().getTable("BON_RECEPTION_ELEMENT");
final SQLTable tableCmdItem = getTable().getTable("COMMANDE_ELEMENT");
SQLRowValues rowValsItem = new SQLRowValues(tableBrItem);
rowValsItem.setAllToNull();
final List<SQLRowValues> fetchLinkedWithCmdItem = SQLRowValuesListFetcher.create(rowValsItem)
.fetch(new Where(tableBrItem.getField("ID_BON_RECEPTION"), "=", id).and(new Where(tableBrItem.getField("ID_COMMANDE_ELEMENT"), "!=", tableCmdItem.getUndefinedIDNumber())));
StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
 
@Override
246,8 → 273,7
 
return getLibelleStock(rowOrigin, rowElt);
}
}, row, row.getReferentRows(getTable().getTable("BON_RECEPTION_ELEMENT")),
getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_RECEPT : TypeStockUpdate.REAL_RECEPT);
}, row, fetchLinkedWithCmdItem, TypeStockUpdate.REAL_RECEPT);
 
if (getTable().getDBRoot().contains("RELIQUAT_BR")) {
List<SQLRow> l = row.getReferentRows(getTable().getTable("RELIQUAT_BR").getField("ID_BON_RECEPTION_ORIGINE"));
255,11 → 281,23
stockUpdater.addReliquat(sqlRow.getForeign("ID_ARTICLE"), sqlRow.getInt("QTE"), sqlRow.getBigDecimal("QTE_UNITAIRE"));
}
}
 
stockUpdater.update();
 
final List<SQLRowValues> fetchNotLinkedWithCmdItem = SQLRowValuesListFetcher.create(rowValsItem)
.fetch(new Where(tableBrItem.getField("ID_BON_RECEPTION"), "=", id).and(new Where(tableBrItem.getField("ID_COMMANDE_ELEMENT"), "=", tableCmdItem.getUndefinedIDNumber())));
StockItemsUpdater stockUpdaterNewItem = new StockItemsUpdater(new StockLabel() {
 
@Override
public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
 
return getLibelleStock(rowOrigin, rowElt);
}
}, row, fetchNotLinkedWithCmdItem, TypeStockUpdate.REAL_VIRTUAL_RECEPT);
stockUpdaterNewItem.setClearMouvementStock(false);
stockUpdaterNewItem.update();
 
}
 
public String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
return "Bon de réception N°" + row.getString("NUMERO");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/BatchQuantityTableCellEditor.java
New file
0,0 → 1,56
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
 
import javax.swing.DefaultCellEditor;
import javax.swing.JTextField;
 
import java.math.BigDecimal;
 
public class BatchQuantityTableCellEditor extends DefaultCellEditor {
 
private final Number foreignIDNumberUnite;
 
public BatchQuantityTableCellEditor(Number foreignIDNumberUnite) {
super(new JTextField());
this.foreignIDNumberUnite = foreignIDNumberUnite;
}
 
@Override
public boolean stopCellEditing() {
BigDecimal value = null;
try {
value = (BigDecimal) getCellEditorValue();
} catch (Exception e) {
return false;
}
final boolean piece = this.foreignIDNumberUnite != null && this.foreignIDNumberUnite.intValue() == UniteVenteArticleSQLElement.A_LA_PIECE;
final boolean valueIsInteger = (value.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0);
 
if (piece && !valueIsInteger) {
return false;
}
return super.stopCellEditing();
 
}
 
@Override
public Object getCellEditorValue() {
 
return new BigDecimal((String) super.getCellEditorValue());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/SerialAreaEditor.java
New file
0,0 → 1,68
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import org.openconcerto.ui.EnhancedTable;
import org.openconcerto.ui.TextAreaTableCellEditor;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.Component;
import java.math.BigDecimal;
import java.util.List;
 
import javax.swing.JTable;
import javax.swing.event.DocumentEvent;
 
public class SerialAreaEditor extends TextAreaTableCellEditor {
 
public SerialAreaEditor(final EnhancedTable table) {
super(table);
this.getTextArea().getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
public void update(DocumentEvent e) {
String t = getTextArea().getText();
if (t.trim().length() > 0) {
final List<String> fastSplitTrimmed = StringUtils.fastSplitTrimmed(t, '\n');
int qte = 0;
for (String string : fastSplitTrimmed) {
if (string.length() > 0) {
qte++;
}
}
if (qte == 0) {
qte = 1;
}
table.setValueAt(new BigDecimal(qte), row, col);
}
}
});
}
 
// Selected rowValues in table
// SQLRowValues rowVals = null;
private int row = 0;
// Column qte
final int col = 0;
 
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
 
// this.rowVals = ((RowValuesTableModel) table.getModel()).getRowValuesAt(rowIndex);
this.row = rowIndex;
return super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/LotReceptionTableModel.java
New file
0,0 → 1,241
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.StringUtils;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.table.AbstractTableModel;
 
public class LotReceptionTableModel extends AbstractTableModel {
private final List<SQLRowValues> dataRowVals = new ArrayList<>();
private final List<SQLField> fields = new ArrayList<>();
private final SQLElement eltLotReception;
private final SQLRowValues rowRef;
 
public LotReceptionTableModel(final SQLElement eltLotReception, final SQLRowValues rowRef) {
 
this.eltLotReception = eltLotReception;
this.rowRef = rowRef;
fields.add(eltLotReception.getTable().getField("QUANTITE"));
fields.add(eltLotReception.getTable().getField("NUMERO_LOT"));
fields.add(eltLotReception.getTable().getField("DLC"));
fields.add(eltLotReception.getTable().getField("DLUO"));
fields.add(eltLotReception.getTable().getField("NUMERO_SERIE"));
load();
}
 
@Override
public int getRowCount() {
return dataRowVals.size();
}
 
// Qté; lot, dlc, dluo, N° série
@Override
public int getColumnCount() {
return 5;
}
 
public void addLine() {
 
this.dataRowVals.add(createDefaultRowValues());
fireTableDataChanged();
}
 
private SQLRowValues createDefaultRowValues() {
final SQLRowValues r = new SQLRowValues(this.eltLotReception.getTable());
r.put("QUANTITE", BigDecimal.ONE);
r.put("NUMERO_SERIE", "");
r.put("NUMERO_LOT", "");
r.put("DLC", null);
r.put("DLUO", null);
r.put("ID_BON_RECEPTION_ELEMENT", this.rowRef);
r.put("ID_ARTICLE", this.rowRef.getForeignID("ID_ARTICLE"));
return r;
}
 
@Override
public String getColumnName(int column) {
return this.eltLotReception.getDirectory().getTranslator().getTitleFor(fields.get(column));
}
 
private final Set<Number> delivredIdLot = new HashSet<>();
 
public void load() {
 
this.delivredIdLot.clear();
this.dataRowVals.clear();
this.rmLines.clear();
final Set<SQLRowValues> referentRows = rowRef.getReferentRows(this.eltLotReception.getTable().getField("ID_BON_RECEPTION_ELEMENT"));
Set<Number> idUsedLot = new HashSet<>();
for (SQLRowValues sqlRowValues : referentRows) {
// Les lignes referentes peuvent être taggées archive si on ouvre la popup, qu'on
// supprime des lignes et qu'on reouvre la popup
if (!sqlRowValues.contains("ARCHIVE") || !sqlRowValues.isArchived()) {
this.dataRowVals.add(sqlRowValues);
}
if (sqlRowValues.contains("ID_LOT")) {
final Number nonEmptyForeignIDNumberLot = sqlRowValues.getNonEmptyForeignIDNumber("ID_LOT");
if (nonEmptyForeignIDNumberLot != null) {
idUsedLot.add(nonEmptyForeignIDNumberLot);
}
}
}
 
if (!idUsedLot.isEmpty()) {
final SQLTable lotTable = this.eltLotReception.getTable().getTable("LOT_LIVRAISON");
SQLRowValues rowVals = new SQLRowValues(lotTable);
rowVals.putNulls("ID_LOT");
final List<SQLRowValues> fetch = SQLRowValuesListFetcher.create(rowVals).fetch(Where.inValues(lotTable.getField("ID_LOT"), idUsedLot));
for (SQLRowValues sqlRowValues : fetch) {
this.delivredIdLot.add(sqlRowValues.getForeignIDNumber("ID_LOT"));
}
}
 
if (this.dataRowVals.isEmpty()) {
addLine();
} else {
fireTableDataChanged();
}
}
 
private final List<Class<?>> colClass = Arrays.asList(BigDecimal.class, String.class, Date.class, Date.class, String.class);
 
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
final SQLRowValues sqlRowValues = this.dataRowVals.get(rowIndex);
if (sqlRowValues.contains("ID_LOT") && sqlRowValues.getNonEmptyForeignIDNumber("ID_LOT") != null && this.delivredIdLot.contains(sqlRowValues.getNonEmptyForeignIDNumber("ID_LOT"))) {
return false;
} else if (fields.indexOf(eltLotReception.getTable().getField("QUANTITE")) == columnIndex) {
return sqlRowValues.getString("NUMERO_SERIE") == null || sqlRowValues.getString("NUMERO_SERIE").isEmpty();
} else {
return true;
}
}
 
@Override
public Class<?> getColumnClass(int columnIndex) {
return colClass.get(columnIndex);
}
 
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
 
// test pour éviter les setValueAt recu d'un editor d'une ligne supprimée
if (rowIndex < getRowCount()) {
final SQLRowValues sqlRowValues = this.dataRowVals.get(rowIndex);
sqlRowValues.put(fields.get(columnIndex).getName(), aValue);
fireTableCellUpdated(rowIndex, columnIndex);
if (!isEmptyVals(sqlRowValues) && !isEmptyVals(this.dataRowVals.get(this.dataRowVals.size() - 1))) {
addLine();
}
}
}
 
private boolean isEmptyVals(SQLRowValues rowVals) {
return (rowVals.getDate("DLC") == null && rowVals.getDate("DLUO") == null && rowVals.getString("NUMERO_SERIE").trim().length() == 0 && rowVals.getString("NUMERO_LOT").trim().length() == 0);
 
}
 
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return this.dataRowVals.get(rowIndex).getObject(this.fields.get(columnIndex).getName());
}
 
private List<SQLRowAccessor> rmLines = new ArrayList<>();
 
public void removeLine(int selectedRow) {
final SQLRowValues remove = this.dataRowVals.remove(selectedRow);
this.rmLines.add(remove);
if (!remove.hasID()) {
remove.putEmptyLink("ID_BON_RECEPTION_ELEMENT");
} else {
remove.put("ARCHIVE", 1);
}
if (getRowCount() == 0) {
addLine();
}
fireTableDataChanged();
}
 
public void checkData() {
List<SQLRowValues> emptyRowVals = new ArrayList<>();
for (int indexInDataRows = this.dataRowVals.size() - 1; indexInDataRows >= 0; indexInDataRows--) {
SQLRowValues rowVals = this.dataRowVals.get(indexInDataRows);
 
// Trim values
trimValues(rowVals);
 
// On scinde en plusieurs lignes si le numéro de série contient des \n
final String serial = rowVals.getString("NUMERO_SERIE");
 
if (serial != null && serial.contains("\n")) {
final List<String> fastSplit = StringUtils.fastSplitTrimmed(serial, '\n');
for (int serialIndex = fastSplit.size() - 1; serialIndex > 0; serialIndex--) {
final String value = fastSplit.get(serialIndex);
if (value != null && value.length() > 0) {
final SQLRowValues createCopy = createDefaultRowValues();
createCopy.put("NUMERO_LOT", rowVals.getObject("NUMERO_LOT"));
createCopy.put("DLC", rowVals.getObject("DLC"));
createCopy.put("DLUO", rowVals.getObject("DLUO"));
createCopy.put("NUMERO_SERIE", value);
this.dataRowVals.add(indexInDataRows, createCopy);
}
}
rowVals.put("QUANTITE", 1);
if (!fastSplit.isEmpty()) {
final String value = fastSplit.get(0);
if (value != null && value.trim().length() > 0) {
rowVals.put("NUMERO_SERIE", value);
}
}
}
 
// Suppression des lignes sans valeurs
if (isEmptyVals(rowVals)) {
emptyRowVals.add(rowVals);
}
}
 
for (SQLRowValues r : emptyRowVals) {
if (r.hasID()) {
this.rmLines.add(r);
r.put("ARCHIVE", 1);
} else {
r.putEmptyLink("ID_BON_RECEPTION_ELEMENT");
}
this.dataRowVals.remove(r);
}
}
 
private void trimValues(SQLRowValues rowVals) {
 
rowVals.put("NUMERO_SERIE", rowVals.getString("NUMERO_SERIE").trim());
rowVals.put("NUMERO_LOT", rowVals.getString("NUMERO_LOT").trim());
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/LotReceptionUIPanel.java
New file
0,0 → 1,145
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.EnhancedTable;
import org.openconcerto.ui.TextAreaRenderer;
import org.openconcerto.ui.table.AlternateTableCellRenderer;
import org.openconcerto.ui.table.TimestampTableCellEditor;
 
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.sql.Date;
import java.sql.Timestamp;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellEditor;
 
public class LotReceptionUIPanel extends JPanel {
 
public LotReceptionUIPanel(SQLElement eltLotReception, SQLRowValues selRowElt) {
EnhancedTable table = new EnhancedTable();
final LotReceptionTableModel dataModel = new LotReceptionTableModel(eltLotReception, selRowElt);
table.setModel(dataModel);
final TimestampTableCellEditor editorPrec = new TimestampTableCellEditor(false) {
@Override
public Object getCellEditorValue() {
 
Object o = super.getCellEditorValue();
Date d = null;
if (o != null) {
d = new Date(((Timestamp) o).getTime());
}
return d;
}
};
editorPrec.setAllowNull(true);
 
final Number foreignIDNumberUnite = selRowElt.getForeignIDNumber("ID_UNITE_VENTE");
 
final BatchQuantityTableCellEditor editorQty = new BatchQuantityTableCellEditor(foreignIDNumberUnite);
table.getColumnModel().getColumn(0).setCellEditor(editorQty);
table.getColumnModel().getColumn(0).setCellRenderer(new BatchQuantityRenderer());
 
final SQLRowAccessor foreign = selRowElt.getForeign("ID_ARTICLE");
table.getColumnModel().getColumn(1).setCellRenderer(new BatchRequiredRenderer(table.getDefaultRenderer(String.class), foreign.getBoolean("NUMERO_LOT_REQUIS")));
 
// DLC
table.getColumnModel().getColumn(2).setCellEditor(editorPrec);
table.getColumnModel().getColumn(2).setCellRenderer(new BatchRequiredRenderer(table.getDefaultRenderer(Date.class), foreign.getBoolean("DLC_REQUIS")));
// DLUO
table.getColumnModel().getColumn(3).setCellEditor(editorPrec);
table.getColumnModel().getColumn(3).setCellRenderer(new BatchRequiredRenderer(table.getDefaultRenderer(Date.class), foreign.getBoolean("DLUO_REQUIS")));
 
table.getColumnModel().getColumn(4).setCellEditor(new SerialAreaEditor(table));
table.getColumnModel().getColumn(4).setCellRenderer(new BatchRequiredRenderer(new TextAreaRenderer(), foreign.getBoolean("NUMERO_SERIE_REQUIS")));
 
AlternateTableCellRenderer.UTILS.setAllColumns(table);
 
final JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.LEFT));
 
final JButton add = new JButton(new AbstractAction("Ajouter un lot/n° de série") {
 
@Override
public void actionPerformed(ActionEvent e) {
dataModel.addLine();
}
});
 
final JButton remove = new JButton(new AbstractAction("Supprimer") {
 
@Override
public void actionPerformed(ActionEvent e) {
dataModel.removeLine(table.getSelectedRow());
}
});
buttons.add(add);
buttons.add(remove);
remove.setEnabled(false);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
remove.setEnabled(table.getSelectedRows().length > 0);
}
});
 
final JButton close = new JButton(new AbstractAction("Fermer") {
 
@Override
public void actionPerformed(ActionEvent e) {
TableCellEditor cellEditor = table.getCellEditor();
if (cellEditor != null) {
cellEditor.stopCellEditing();
}
dataModel.checkData();
 
// TODO Checker si articles avec DLC, DLUO, ... requis non renseigné
((Window) SwingUtilities.getRoot(LotReceptionUIPanel.this)).dispose();
}
});
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Boutons
c.weightx = 1;
this.add(buttons, c);
// Table
c.gridy++;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
this.add(new JScrollPane(table), c);
// Fermer
c.gridy++;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.SOUTHEAST;
this.add(close, c);
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/BatchQuantityRenderer.java
New file
0,0 → 1,40
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import java.awt.Component;
import java.math.BigDecimal;
import java.text.DecimalFormat;
 
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
 
public class BatchQuantityRenderer extends DefaultTableCellRenderer {
 
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
 
setHorizontalAlignment(SwingConstants.RIGHT);
if (value != null) {
BigDecimal b = (BigDecimal) value;
DecimalFormat f = new DecimalFormat("0.######");
this.setText(f.format(b));
}
 
return this;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/BatchRequiredRenderer.java
New file
0,0 → 1,46
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import java.awt.Color;
import java.awt.Component;
 
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
 
public class BatchRequiredRenderer extends DefaultTableCellRenderer {
 
private final TableCellRenderer rendererOrigin;
private final boolean valueRequired;
 
public BatchRequiredRenderer(TableCellRenderer rendererOrigin, boolean req) {
this.rendererOrigin = rendererOrigin;
this.valueRequired = req;
}
 
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 
final Component tableCellRendererComponent = this.rendererOrigin.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
 
if (this.valueRequired && (value == null || value.toString().trim().length() == 0)) {
tableCellRendererComponent.setBackground(Color.ORANGE);
} else {
tableCellRendererComponent.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
}
 
return tableCellRendererComponent;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/ui/BonReceptionItemTable.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
13,6 → 13,13
package org.openconcerto.erp.core.supplychain.receipt.ui;
 
import org.openconcerto.erp.core.common.ui.AbstractAchatArticleItemTable;
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
 
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.util.ArrayList;
20,13 → 27,6
 
import javax.swing.AbstractAction;
 
import org.openconcerto.erp.core.common.ui.AbstractAchatArticleItemTable;
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
 
public class BonReceptionItemTable extends AbstractAchatArticleItemTable {
 
private ReliquatRowValuesTable reliquatTable;
72,6 → 72,7
}
}
});
 
return actions;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSQLElement.java
13,14 → 13,24
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.sales.invoice.report.EtatStockInventaireXmlSheet;
import org.openconcerto.erp.core.supplychain.stock.report.StockReportPDF;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
28,16 → 38,29
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.PanelFrame;
import org.openconcerto.ui.SwingThreadUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
 
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
 
public class EtatStockSQLElement extends ComptaSQLConfElement {
58,26 → 81,60
getRowActions().add(action);
}
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Voir les articles") {
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Import Inventaire") {
@Override
public void actionPerformed(ActionEvent e) {
// PanelFrame frame = new PanelFrame(new
// ImportInventairePanel(getDirectory().getElement(DepotStockSQLElement.class)),
// "Import inventaire");
// FrameUtil.showPacked(frame);
 
final Frame frame = SwingThreadUtils.getAncestorOrSelf(Frame.class, (Component) e.getSource());
final FileDialog fd = new FileDialog(frame, "Import Inventaire", FileDialog.LOAD);
fd.setVisible(true);
if (fd.getFile() != null) {
final File f = new File(fd.getDirectory(), fd.getFile());
if (!f.exists()) {
JOptionPane.showMessageDialog(null, "Le ficher selectionné n'existe pas", "Erreur", JOptionPane.ERROR_MESSAGE);
} else if (f.isDirectory()) {
JOptionPane.showMessageDialog(null, "Le fichier selectionné n'est pas valide", "Erreur", JOptionPane.ERROR_MESSAGE);
} else {
new Thread(new Runnable() {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLElement element = getDirectory().getElement("ETAT_STOCK_ELEMENT");
SQLTableModelSource source = element.createTableSource(new Where(element.getTable().getField("ID_ETAT_STOCK"), "=", IListe.get(e).getSelectedId()));
final ListeViewPanel panel = new ListeViewPanel(element, new IListe(source));
IListFrame frame = new IListFrame(panel);
FrameUtil.show(frame);
public void run() {
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter(getDirectory().getElement("ARTICLE"));
try {
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
public Object handle(final SQLDataSource ds) throws SQLException, IOException {
 
impoter.importArticles(f, getTable().getDBRoot());
return null;
}
});
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de l'importation", e1);
}
 
}
}).start();
}
}
 
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
action.setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE));
getRowActions().add(action);
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Export pour inventaire") {
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Export d'état pour inventaire") {
@Override
public void actionPerformed(ActionEvent e) {
EtatStockInventaireXmlSheet sheet = new EtatStockInventaireXmlSheet(IListe.get(e).getSelectedRow().asRow());
 
EtatStockInventaireXmlSheet sheet = new EtatStockInventaireXmlSheet(getDirectory(), SQLRow.getIDs(IListe.get(e).getSelectedRowAccessors()));
 
try {
sheet.createDocument();
sheet.showPrintAndExport(true, false, false, false, false, Collections.emptyList());
86,27 → 143,98
}
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
getRowActions().add(action);
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Import Inventaire") {
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Générer tous les états de stock") {
 
@Override
public void actionPerformed(ActionEvent e) {
PanelFrame frame = new PanelFrame(new ImportInventairePanel(getDirectory().getElement(DepotStockSQLElement.class)), "Import inventaire");
FrameUtil.showPacked(frame);
SQLSelect sel = new SQLSelect();
 
sel.addSelectStar(getTable().getForeignTable("ID_DEPOT_STOCK"));
final List<SQLRow> rowsDepot = SQLRowListRSH.execute(sel);
 
Set<Number> idsEtat = new HashSet<>();
for (SQLRow rowDepot : rowsDepot) {
Date d = new Date();
EtatStockSnapshotCreator creator = new EtatStockSnapshotCreator(rowDepot, d, getTable().getDBRoot(), false);
 
final int etat = creator.create();
if (etat != SQLRow.NONEXISTANT_ID) {
idsEtat.add(etat);
}
}
 
if (!idsEtat.isEmpty()) {
 
EtatStockInventaireXmlSheet sheet = new EtatStockInventaireXmlSheet(getDirectory(), idsEtat);
try {
sheet.createDocument();
sheet.showPrintAndExport(true, false, false, false, false, Collections.emptyList());
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de la création de l'inventaire", e1);
}
}
 
}
}, true);
action.setPredicate(IListeEvent.createSelectionCountPredicate(0, Integer.MAX_VALUE));
getRowActions().add(action);
}
 
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Voir les articles") {
 
@Override
public void actionPerformed(ActionEvent e) {
final SQLElement element = getDirectory().getElement("ETAT_STOCK_ELEMENT");
SQLTableModelSource source = element.createTableSource(new Where(element.getTable().getField("ID_ETAT_STOCK"), "=", IListe.get(e).getSelectedId()));
final ListeViewPanel panel = new ListeViewPanel(element, new IListe(source));
IListFrame frame = new IListFrame(panel);
FrameUtil.show(frame);
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
{
PredicateRowAction action = new PredicateRowAction(new AbstractAction("Inventaire chiffré") {
 
@Override
public void actionPerformed(ActionEvent e) {
SQLRow r = IListe.get(e).getSelectedRow().fetchNewRow();
try {
String companyName = ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getString("NOM");
final Calendar date = r.getDate("DATE");
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
StockReportPDF pdf = new StockReportPDF(companyName, df.format(date.getTime()));
pdf.addStockDepot(r);
final File f = new File("out.pdf");
pdf.savePDF(f);
FileUtils.openFile(f);
} catch (Exception ex) {
ExceptionHandler.handle("Erreur", ex);
}
}
}, true);
action.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(action);
}
}
 
@Override
protected List<String> getListFields() {
final List<String> l = new ArrayList<>(3);
l.add("DATE");
final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
final boolean hasDeclinaison = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false);
if (hasDeclinaison) {
l.add("ID_DEPOT_STOCK");
}
 
l.add("MONTANT_HA");
l.add("INVENTAIRE");
return l;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/InventaireFromEtatStockImporter.java
22,18 → 22,23
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLInsert;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLUpdate;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.Tuple3;
import org.openconcerto.utils.cc.ITransformer;
 
import java.io.File;
import java.io.IOException;
45,6 → 50,7
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
57,12 → 63,13
public class InventaireFromEtatStockImporter {
 
private Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>();
private Map<Integer, InventaireProductLine> kitsChildren = new HashMap<Integer, InventaireProductLine>();
private List<String> codeKits = new ArrayList<String>();
private SQLRowAccessor depot;
private static String FAMILLE = "Famille";
private static String CODE = "Code";
private static String NOM = "Nom";
private static String TAILLE = "Taille";
private static String DEPOT = "Dépôt";
private static String COULEUR = "Couleur";
private static String QTE = "Qté réelle relevée";
private static String QTE_OPENCONCERTO = "QTE OpenConcerto";
71,8 → 78,7
private final DBRoot root;
private final SQLElement artElt;
 
public InventaireFromEtatStockImporter(SQLElement articleElt, SQLRowAccessor depot) {
this.depot = depot;
public InventaireFromEtatStockImporter(SQLElement articleElt) {
this.root = articleElt.getTable().getDBRoot();
this.artElt = articleElt;
{
83,7 → 89,7
List<SQLRow> l = SQLRowListRSH.execute(sel);
 
for (SQLRow sqlRow : l) {
mapCouleur.put(sqlRow.getString("NOM").trim(), sqlRow.getID());
this.mapCouleur.put(sqlRow.getString("NOM").trim(), sqlRow.getID());
}
}
 
95,7 → 101,7
List<SQLRow> l = SQLRowListRSH.execute(sel);
 
for (SQLRow sqlRow : l) {
mapTaille.put(sqlRow.getString("NOM").trim(), sqlRow.getID());
this.mapTaille.put(sqlRow.getString("NOM").trim(), sqlRow.getID());
}
}
}
117,6 → 123,7
columnMapping.put(COULEUR, null);
columnMapping.put(QTE, null);
columnMapping.put(QTE_OPENCONCERTO, null);
columnMapping.put(DEPOT, null);
{
// Searching column index from column Header
final DataImporter importer = new DataImporter(table);
140,11 → 147,20
final boolean hasDeclinaison = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false);
List<String> required;
if (hasDeclinaison) {
 
required = Arrays.asList(CODE, QTE, QTE_OPENCONCERTO, TAILLE, COULEUR);
} else {
required = Arrays.asList(CODE, QTE, QTE_OPENCONCERTO);
}
 
SQLSelect selDepot = new SQLSelect();
selDepot.addSelectStar(tableArtElt.getTable("DEPOT_STOCK"));
final List<SQLRow> listDepot = SQLRowListRSH.execute(selDepot);
final Map<String, SQLRow> mapDepot = new HashMap<>();
for (SQLRow sqlRow : listDepot) {
mapDepot.put(sqlRow.getString("NOM"), sqlRow);
}
 
for (Entry<String, Integer> e : columnMapping.entrySet()) {
if (e.getValue() != null) {
msg += e.getKey() + " : " + getColumnName(e.getValue()) + "\n";
171,6 → 187,42
 
ArrayTableModel m = importer.createModelFrom(file);
 
// Check depot
boolean multiDepotPrefs = prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false);
SQLRowAccessor defaultDepotRow = null;
boolean multiDepotFile = columnMapping.containsKey(DEPOT);
if (!multiDepotFile) {
if (multiDepotPrefs) {
// TODO popup choix depot
} else {
defaultDepotRow = table.getTable("DEPOT_STOCK").getRow(DepotStockSQLElement.DEFAULT_ID);
}
} else {
Set<String> errors = new HashSet<>();
for (int i = 1; i < m.getRowCount(); i++) {
List<Object> o = m.getLineValuesAt(i);
if (o.size() >= 5) {
System.err.println(o);
String code = o.get(columnMapping.get(CODE)).toString();
if (code.trim().length() > 0) {
 
final String depotName = o.get(columnMapping.get(DEPOT)).toString().trim();
if (depotName.length() == 0) {
errors.add("Le Depôt n'est pas renseigné, ligne " + i + ". Import annulé!");
 
} else if (mapDepot.get(depotName) == null) {
errors.add("Impossible de trouver le dépôt " + depotName + ", ligne " + i + ". Import annulé!");
}
 
}
}
}
if (!errors.isEmpty()) {
JOptionPane.showMessageDialog(null, errors);
return;
}
}
 
Calendar c = Calendar.getInstance();
// c.set(Calendar.DAY_OF_MONTH, 1);
// c.set(Calendar.MONTH, Calendar.JANUARY);
179,12 → 231,10
 
// TODO ne pas vider les stocks des kits, recalculer les stocks des kits
 
SQLRowValues rowVals = new SQLRowValues(table.getTable("ETAT_STOCK"));
rowVals.put("DATE", today);
rowVals.put("INVENTAIRE", Boolean.TRUE);
rowVals.put("ID_DEPOT_STOCK", this.depot.getID());
SQLRow rowEtat = rowVals.commit();
Map<Integer, Integer> mapDepotEtat = new HashMap<>();
 
List<SQLInsert> inserts = new ArrayList<>();
List<SQLUpdate> updates = new ArrayList<>();
for (int i = 1; i < m.getRowCount(); i++) {
List<Object> o = m.getLineValuesAt(i);
if (o.size() >= 5) {
209,95 → 259,145
 
// SQLRowAccessor match = findArticle(code, couleur, taille);
 
Tuple2<SQLRowValues, SQLRowValues> match = findArticle(code, couleur, taille);
InventaireProductLine match = findArticle(code, couleur, taille);
if (match != null) {
 
SQLRowAccessor stockValues = match.get1();
SQLRowAccessor depotRow = defaultDepotRow;
 
if (multiDepotFile) {
final String depotName = o.get(columnMapping.get(DEPOT)).toString().trim();
depotRow = mapDepot.get(depotName);
}
 
if (!mapDepotEtat.containsKey(depotRow.getID())) {
mapDepotEtat.put(depotRow.getID(), createEtat(table.getTable("ETAT_STOCK"), depotRow.getID()).commit().getID());
}
 
int etatID = mapDepotEtat.get(depotRow.getID());
 
SQLRowAccessor stockValues = match.getOrCreateStockRowValues(depotRow);
 
final SQLTable tableMvt = table.getTable("MOUVEMENT_STOCK");
SQLRowValues rowValsMvtStockClotureFermeture = new SQLRowValues(tableMvt);
rowValsMvtStockClotureFermeture.put("QTE", -qtyOld);
rowValsMvtStockClotureFermeture.put("NOM", "Clôture stock avant inventaire");
rowValsMvtStockClotureFermeture.put("ID_ARTICLE", match.get0().getID());
rowValsMvtStockClotureFermeture.put("DATE", today);
rowValsMvtStockClotureFermeture.put("REEL", Boolean.TRUE);
rowValsMvtStockClotureFermeture.put("ID_STOCK", stockValues.getID());
SQLInsert insertMvtStockClotureFermeture = new SQLInsert();
insertMvtStockClotureFermeture.add(tableMvt.getField("QTE"), -qtyOld);
insertMvtStockClotureFermeture.add(tableMvt.getField("NOM"), "Clôture stock avant inventaire");
insertMvtStockClotureFermeture.add(tableMvt.getField("ID_ARTICLE"), match.getRowValsArt().getID());
insertMvtStockClotureFermeture.add(tableMvt.getField("DATE"), today);
insertMvtStockClotureFermeture.add(tableMvt.getField("REEL"), Boolean.TRUE);
insertMvtStockClotureFermeture.add(tableMvt.getField("ID_STOCK"), stockValues.getID());
 
BigDecimal prc = getPRC(match.get0(), Math.round(qtyOld), today);
BigDecimal prc = getPRC(match.getRowValsArt(), Math.round(qtyOld), today);
if (prc == null) {
prc = BigDecimal.ZERO;
}
if (tableMvt.contains("PRICE")) {
rowValsMvtStockClotureFermeture.put("PRICE", prc);
insertMvtStockClotureFermeture.add(tableMvt.getField("PRICE"), prc);
}
rowValsMvtStockClotureFermeture.put("CLOTURE", Boolean.TRUE);
rowValsMvtStockClotureFermeture.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsMvtStockClotureFermeture.getGraph().store(StoreMode.COMMIT, false);
insertMvtStockClotureFermeture.add(tableMvt.getField("CLOTURE"), Boolean.TRUE);
insertMvtStockClotureFermeture.add(tableMvt.getField("ID_ETAT_STOCK"), etatID);
// insertMvtStockClotureFermeture.getGraph().store(StoreMode.COMMIT,
// false);
 
SQLRowValues rowValsItem = new SQLRowValues(table.getTable("ETAT_STOCK_ELEMENT"));
rowValsItem.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsItem.put("PA", prc);
rowValsItem.put("PV", BigDecimal.ZERO);
rowValsItem.put("QTE", qtyOld);
rowValsItem.put("T_PA", prc.multiply(new BigDecimal(qtyOld)));
rowValsItem.put("T_PV", BigDecimal.ZERO);
rowValsItem.put("CODE", match.get0().getString("CODE"));
rowValsItem.put("NOM", match.get0().getString("NOM"));
rowValsItem.put("ID_ARTICLE", match.get0().getID());
rowValsItem.getGraph().store(StoreMode.COMMIT, false);
inserts.add(insertMvtStockClotureFermeture);
 
SQLRowValues rowValsMvtStockClotureOuverture = new SQLRowValues(tableMvt);
rowValsMvtStockClotureOuverture.put("QTE", qty);
rowValsMvtStockClotureOuverture.put("NOM", "Mise en stock inventaire");
rowValsMvtStockClotureOuverture.put("ID_ETAT_STOCK", rowEtat.getID());
rowValsMvtStockClotureOuverture.put("ID_ARTICLE", match.get0().getID());
rowValsMvtStockClotureOuverture.put("DATE", today);
rowValsMvtStockClotureOuverture.put("REEL", Boolean.TRUE);
rowValsMvtStockClotureOuverture.put("ID_STOCK", stockValues.getID());
rowValsMvtStockClotureOuverture.put("OUVERTURE", Boolean.TRUE);
final SQLTable tableEtatElt = table.getTable("ETAT_STOCK_ELEMENT");
SQLInsert insertItem = new SQLInsert();
insertItem.add(tableEtatElt.getField("ID_ETAT_STOCK"), etatID);
insertItem.add(tableEtatElt.getField("PA"), prc);
insertItem.add(tableEtatElt.getField("PV"), BigDecimal.ZERO);
insertItem.add(tableEtatElt.getField("QTE"), qtyOld);
insertItem.add(tableEtatElt.getField("T_PA"), prc.multiply(new BigDecimal(qtyOld)));
insertItem.add(tableEtatElt.getField("T_PV"), BigDecimal.ZERO);
insertItem.add(tableEtatElt.getField("CODE"), match.getRowValsArt().getString("CODE"));
insertItem.add(tableEtatElt.getField("NOM"), match.getRowValsArt().getString("NOM"));
insertItem.add(tableEtatElt.getField("ID_ARTICLE"), match.getRowValsArt().getID());
// insertItem.getGraph().store(StoreMode.COMMIT, false);
inserts.add(insertItem);
 
SQLInsert insertMvtStockClotureOuverture = new SQLInsert();
insertMvtStockClotureOuverture.add(tableMvt.getField("QTE"), qty);
insertMvtStockClotureOuverture.add(tableMvt.getField("NOM"), "Mise en stock inventaire");
insertMvtStockClotureOuverture.add(tableMvt.getField("ID_ETAT_STOCK"), etatID);
insertMvtStockClotureOuverture.add(tableMvt.getField("ID_ARTICLE"), match.getRowValsArt().getID());
insertMvtStockClotureOuverture.add(tableMvt.getField("DATE"), today);
insertMvtStockClotureOuverture.add(tableMvt.getField("REEL"), Boolean.TRUE);
insertMvtStockClotureOuverture.add(tableMvt.getField("ID_STOCK"), stockValues.getID());
insertMvtStockClotureOuverture.add(tableMvt.getField("OUVERTURE"), Boolean.TRUE);
if (tableMvt.contains("PRICE")) {
rowValsMvtStockClotureOuverture.put("PRICE", getPRC(match.get0(), qty.intValue(), today));
insertMvtStockClotureOuverture.add(tableMvt.getField("PRICE"), getPRC(match.getRowValsArt(), qty.intValue(), today));
}
rowValsMvtStockClotureOuverture.getGraph().store(StoreMode.COMMIT, false);
inserts.add(insertMvtStockClotureOuverture);
// insertMvtStockClotureOuverture.getGraph().store(StoreMode.COMMIT,
// false);
 
// if (!match.isForeignEmpty("ID_STOCK")) {
// match.getForeign("ID_STOCK").createEmptyUpdateRow().put("QTE_REEL",
// qty).commit();
// } else {
final SQLRowValues createEmptyUpdateRow = match.get1().createEmptyUpdateRow();
createEmptyUpdateRow.put("QTE_REEL", qty);
createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false);
 
// final SQLRowValues createEmptyUpdateRow =
// stockValues.createEmptyUpdateRow();
// createEmptyUpdateRow.put("QTE_REEL", qty);
// createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false);
SQLUpdate up = new SQLUpdate(new Where(stockValues.getTable().getKey(), "=", stockValues.getID()));
up.add(stockValues.getTable().getField("QTE_REEL"), qty);
updates.add(up);
// }
 
} else {
System.err.println("Aucun article correspondant au code " + code);
System.err.println("\t Aucun article correspondant au code " + code);
}
}
}
}
 
if (!inserts.isEmpty()) {
SQLInsert.executeMultipleWithBatch(table.getDBSystemRoot(), inserts);
}
if (!updates.isEmpty()) {
SQLUpdate.executeMultipleWithBatch(table.getDBSystemRoot(), updates);
System.err.println(CollectionUtils.join(updates, ";\n"));
}
 
/**
* Mise à jour des kits
*/
 
final List<? extends SQLRowAccessor> rowsDepot;
if (multiDepotFile) {
rowsDepot = listDepot;
} else {
rowsDepot = Arrays.asList(defaultDepotRow);
}
 
List<String> reqs = new ArrayList<String>();
for (String code : codeKits) {
// Recalcul des stocks pour chaque kit impacté
for (String code : this.codeKits) {
System.err.println(code);
SQLRowValues rowValsKit = kits.get(code);
StockItem item = new StockItem(rowValsKit, ProductComponent.findOrCreateStock(rowValsKit, depot));
SQLRowValues rowValsKit = this.kits.get(code);
 
// récupération des stocks initialisés pour ce kit
final Set<SQLRowValues> referentRowsStock = rowValsKit.getReferentRows(table.getTable("STOCK").getField("ID_ARTICLE"));
for (SQLRowAccessor d : referentRowsStock) {
StockItem item = new StockItem(rowValsKit, d);
Collection<SQLRowValues> elts = rowValsKit.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
 
// Recalcul du stock pour le dépot
for (SQLRowValues sqlRowValues : elts) {
if (sqlRowValues.getForeign("ID_ARTICLE") != null) {
item.addItemComponent(
new StockItemComponent(new StockItem(sqlRowValues.getForeign("ID_ARTICLE"), ProductComponent.findOrCreateStock(sqlRowValues.getForeign("ID_ARTICLE"), depot)),
sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
final InventaireProductLine inventaireProductLine = this.kitsChildren.get(sqlRowValues.getID());
 
if (inventaireProductLine != null && sqlRowValues.getForeign("ID_ARTICLE") != null) {
final SQLRowValues stockArticle = inventaireProductLine.getStockRowValues(d.getForeign("ID_DEPOT_STOCK"));
if (stockArticle != null)
item.addItemComponent(new StockItemComponent(new StockItem(sqlRowValues.getForeign("ID_ARTICLE"), stockArticle), sqlRowValues.getBigDecimal("QTE_UNITAIRE"),
sqlRowValues.getInt("QTE")));
}
}
item.updateQtyFromChildren();
reqs.add(item.getUpdateRequest());
}
}
 
if (!reqs.isEmpty()) {
List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(reqs.size());
for (String s : reqs) {
handlers.add(null);
304,6 → 404,12
}
// FIXME FIRE TABLE CHANGED TO UPDATE ILISTE ??
SQLUtils.executeMultiple(table.getDBSystemRoot(), reqs, handlers);
}
// Recalcul du stock théorique
final SQLTable tableStock = root.getTable("STOCK");
org.openconcerto.sql.request.UpdateBuilder req = new UpdateBuilder(tableStock);
req.set("QTE_TH", SQLBase.quoteIdentifier("QTE_REEL") + "-" + SQLBase.quoteIdentifier("QTE_LIV_ATTENTE") + "+" + SQLBase.quoteIdentifier("QTE_RECEPT_ATTENTE"));
table.getDBSystemRoot().getDataSource().execute(req.asString());
 
/**
* Mise à jour des prix mini
344,8 → 450,41
// }
// }
}
 
}
 
public static SQLInsert getCreateStock(SQLRowAccessor article, SQLRowAccessor depot) {
 
SQLTable stockTable = article.getTable().getTable("STOCK");
SQLRowValues putRowValuesStock = new SQLRowValues(stockTable);
putRowValuesStock.putNulls(stockTable.getTable().getFieldsName());
 
SQLRowValuesListFetcher fetch = SQLRowValuesListFetcher.create(putRowValuesStock);
Where w = new Where(putRowValuesStock.getTable().getField("ID_DEPOT_STOCK"), "=", depot.getID());
Where w2 = new Where(putRowValuesStock.getTable().getField("ID_ARTICLE"), "=", article.getID());
Collection<SQLRowValues> rowValsResult = fetch.fetch(w.and(w2));
if (rowValsResult.size() == 0) {
SQLInsert insert = new SQLInsert();
insert.add(stockTable.getField("ID_ARTICLE"), article.getID());
insert.add(stockTable.getField("ID_DEPOT_STOCK"), depot.getID());
insert.add(stockTable.getField("QTE_TH"), 0F);
insert.add(stockTable.getField("QTE_REEL"), 0F);
insert.add(stockTable.getField("QTE_RECEPT_ATTENTE"), 0F);
insert.add(stockTable.getField("QTE_LIV_ATTENTE"), 0F);
return insert;
}
return null;
 
}
 
private SQLRowValues createEtat(SQLTable tableEtat, int depotID) {
SQLRowValues rowVals = new SQLRowValues(tableEtat);
rowVals.put("DATE", new Date());
rowVals.put("INVENTAIRE", Boolean.TRUE);
rowVals.put("ID_DEPOT_STOCK", depotID);
return rowVals;
}
 
private void checkMinPrice(SQLRow rowValsSuplierLastValid, SQLRow lastValidRow) {
boolean update = false;
final ProductHelper helper = new ProductHelper(rowValsSuplierLastValid.getTable().getDBRoot());
421,12 → 560,13
// return result;
}
 
private final Map<String, Tuple2<SQLRowValues, SQLRowValues>> mapArticle = new HashMap<String, Tuple2<SQLRowValues, SQLRowValues>>();
private final Map<String, Tuple2<SQLRowValues, SQLRowValues>> mapArticleVirtuel = new HashMap<String, Tuple2<SQLRowValues, SQLRowValues>>();
private final Map<Tuple3<String, String, String>, Tuple2<SQLRowValues, SQLRowValues>> mapDeclArticle = new HashMap<Tuple3<String, String, String>, Tuple2<SQLRowValues, SQLRowValues>>();
private final Map<String, InventaireProductLine> mapDepotArticle = new HashMap();
private final Map<String, InventaireProductLine> mapDepotArticleVirtuel = new HashMap();
private final Map<Tuple3<String, String, String>, InventaireProductLine> mapDepotDeclArticle = new HashMap();
 
private void fillArticles() throws SQLException {
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
 
SQLRowValues graph = new SQLRowValues(table);
graph.put("ID", null);
graph.put("CODE", null);
437,11 → 577,11
 
final SQLTable foreignTableStock = table.getForeignTable("ID_STOCK");
SQLRowValues graphStock = new SQLRowValues(foreignTableStock);
graphStock.putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
graphStock.putNulls("ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE").putRowValues("ID_DEPOT_STOCK").putNulls("NOM");
graphStock.put("ID_ARTICLE", graph);
 
SQLRowValues graphStockArt = new SQLRowValues(foreignTableStock);
graphStockArt.putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
graphStockArt.putNulls("ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE").putRowValues("ID_DEPOT_STOCK").putNulls("NOM");
graph.put("ID_STOCK", graphStockArt);
 
final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT");
469,37 → 609,24
// c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.MONTH, -2);
c.set(Calendar.DAY_OF_MONTH, 31);
Date dEndYear = c.getTime();
 
for (SQLRowValues sqlRowValues : results) {
final String code = sqlRowValues.getString("CODE");
 
Collection<SQLRowValues> stocks = sqlRowValues.getReferentRows(foreignTableStock);
 
SQLRowValues rowValsStock = null;
for (SQLRowValues sqlRowValues2 : stocks) {
if (sqlRowValues2.getForeignID("ID_DEPOT_STOCK") == depot.getID()) {
rowValsStock = sqlRowValues2;
}
}
// if (rowValsStock == null) {
// rowValsStock = ProductComponent.findOrCreateStock(sqlRowValues, depot).asRowValues();
// }
 
if (sqlRowValues.getBoolean("VIRTUEL")) {
mapArticleVirtuel.put(sqlRowValues.getString("CODE"), Tuple2.create(sqlRowValues, rowValsStock));
this.mapDepotArticleVirtuel.put(sqlRowValues.getString("CODE"), new InventaireProductLine(sqlRowValues));
}
 
final SQLRowAccessor couleur = sqlRowValues.getObject("ID_ARTICLE_DECLINAISON_COULEUR") == null ? null : sqlRowValues.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_COULEUR");
final SQLRowAccessor taille = sqlRowValues.getObject("ID_ARTICLE_DECLINAISON_TAILLE") == null ? null : sqlRowValues.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_TAILLE");
if (couleur == null && taille == null) {
mapArticle.put(sqlRowValues.getString("CODE"), Tuple2.create(sqlRowValues, rowValsStock));
this.mapDepotArticle.put(sqlRowValues.getString("CODE"), new InventaireProductLine(sqlRowValues));
} else if (couleur == null) {
mapDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), null, taille.getString("NOM")), Tuple2.create(sqlRowValues, rowValsStock));
this.mapDepotDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), null, taille.getString("NOM")), new InventaireProductLine(sqlRowValues));
} else if (taille == null) {
mapDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), couleur.getString("NOM"), null), Tuple2.create(sqlRowValues, rowValsStock));
this.mapDepotDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), couleur.getString("NOM"), null), new InventaireProductLine(sqlRowValues));
} else {
mapDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), couleur.getString("NOM"), taille.getString("NOM")), Tuple2.create(sqlRowValues, rowValsStock));
this.mapDepotDeclArticle.put(Tuple3.create(sqlRowValues.getString("CODE"), couleur.getString("NOM"), taille.getString("NOM")), new InventaireProductLine(sqlRowValues));
}
 
final Set<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
528,7 → 655,7
boolean contains = false;
for (SQLRowValues sqlRowValues2 : referentRows) {
if (sqlRowValues2.getForeign("ID_ARTICLE") != null && !sqlRowValues2.isForeignEmpty("ID_ARTICLE") && sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE") != null) {
if (codeKits.contains(sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE"))) {
if (this.codeKits.contains(sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE"))) {
contains = true;
break;
}
535,72 → 662,110
}
}
if (!contains) {
codeKits.add(0, code);
this.codeKits.add(0, code);
} else {
codeKits.add(code);
this.codeKits.add(code);
}
kits.put(code, sqlRowValues);
this.kits.put(code, sqlRowValues);
// if (sqlRowValues.isForeignEmpty("ID_STOCK")) {
// sqlRowValues.putRowValues("ID_STOCK").commit();
// }
}
 
}
fillKitChildren();
}
 
private Tuple2<SQLRowValues, SQLRowValues> findArticle(String code, String couleur, String taille) throws SQLException {
if (!mapCouleur.containsKey(couleur)) {
SQLRowValues rowVals = new SQLRowValues(root.getTable("ARTICLE_DECLINAISON_COULEUR"));
private void fillKitChildren() {
final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
 
SQLRowValues graph = new SQLRowValues(table);
graph.put("ID", null);
graph.put("CODE", null);
graph.put("NOM", null);
graph.put("VIRTUEL", null);
graph.putRowValues("ID_ARTICLE_DECLINAISON_COULEUR").putNulls("ID", "NOM");
graph.putRowValues("ID_ARTICLE_DECLINAISON_TAILLE").putNulls("ID", "NOM");
 
final SQLTable foreignTableStock = table.getForeignTable("ID_STOCK");
SQLRowValues graphStock = new SQLRowValues(foreignTableStock);
graphStock.putNulls("ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE").putRowValues("ID_DEPOT_STOCK").putNulls("NOM");
graphStock.put("ID_ARTICLE", graph);
 
final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT");
SQLRowValues artElt = new SQLRowValues(tableArtElt);
artElt.put("ID", null);
artElt.put("QTE", null);
artElt.put("QTE_UNITAIRE", null);
artElt.put("ID_ARTICLE", graph);
 
SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(artElt);
fetcher.appendSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.setWhere(Where.inValues(tableArtElt.getField("ID_ARTICLE_PARENT"), SQLRow.getIDs(InventaireFromEtatStockImporter.this.kits.values())));
return input;
}
});
List<SQLRowValues> results = fetcher.fetch();
for (SQLRowValues sqlRowValues : results) {
final SQLRowAccessor foreign = sqlRowValues.getNonEmptyForeign("ID_ARTICLE");
if (foreign != null) {
this.kitsChildren.put(foreign.getID(), new InventaireProductLine(foreign.asRowValues()));
}
}
}
 
private InventaireProductLine findArticle(String code, String couleur, String taille) throws SQLException {
if (!this.mapCouleur.containsKey(couleur)) {
SQLRowValues rowVals = new SQLRowValues(this.root.getTable("ARTICLE_DECLINAISON_COULEUR"));
rowVals.put("NOM", couleur);
mapCouleur.put(couleur, rowVals.commit().getID());
this.mapCouleur.put(couleur, rowVals.commit().getID());
}
if (!mapTaille.containsKey(taille)) {
SQLRowValues rowVals = new SQLRowValues(root.getTable("ARTICLE_DECLINAISON_TAILLE"));
if (!this.mapTaille.containsKey(taille)) {
SQLRowValues rowVals = new SQLRowValues(this.root.getTable("ARTICLE_DECLINAISON_TAILLE"));
rowVals.put("NOM", taille);
mapTaille.put(taille, rowVals.commit().getID());
this.mapTaille.put(taille, rowVals.commit().getID());
}
 
Tuple2<SQLRowValues, SQLRowValues> t;
InventaireProductLine t;
if ((couleur == null || couleur.trim().length() == 0) && (taille == null || taille.trim().length() == 0)) {
 
t = mapArticle.get(code);
if (t.get1() == null) {
t = Tuple2.create(t.get0(), ProductComponent.findOrCreateStock(t.get0(), depot).asRowValues());
mapArticle.put(code, t);
}
t = this.mapDepotArticle.get(code);
} else if (couleur == null || couleur.trim().length() == 0) {
t = mapDeclArticle.get(Tuple3.create(code, null, taille.trim()));
t = this.mapDepotDeclArticle.get(Tuple3.create(code, null, taille.trim()));
if (t == null) {
SQLRowValues artRow = cloneFromArticle(mapArticleVirtuel.get(code).get0(), null, mapTaille.get(taille.trim())).asRowValues();
final SQLRowValues stockRow = ProductComponent.findOrCreateStock(artRow, depot).asRowValues();
t = Tuple2.create(artRow, stockRow);
mapDeclArticle.put(Tuple3.create(code, null, taille.trim()), t);
} else if (t.get1() == null) {
t = Tuple2.create(t.get0(), ProductComponent.findOrCreateStock(t.get0(), depot).asRowValues());
mapDeclArticle.put(Tuple3.create(code, null, taille.trim()), t);
t = this.mapDepotDeclArticle.get(Tuple3.create(code, "", taille.trim()));
}
if (t == null) {
System.err.println("\tCREATE ARTICLE " + code + " taille : " + taille);
SQLRowValues rARtVirt = this.mapDepotArticleVirtuel.get(code).getRowValsArt();
SQLRowValues artRow = cloneFromArticle(rARtVirt, null, this.mapTaille.get(taille.trim())).asRowValues();
t = new InventaireProductLine(artRow);
this.mapDepotDeclArticle.put(Tuple3.create(code, null, taille.trim()), t);
}
} else if (taille == null || taille.trim().length() == 0) {
t = mapDeclArticle.get(Tuple3.create(code, couleur.trim(), null));
t = this.mapDepotDeclArticle.get(Tuple3.create(code, couleur.trim(), null));
if (t == null) {
SQLRowValues artRow = cloneFromArticle(mapArticleVirtuel.get(code).get0(), mapCouleur.get(couleur.trim()), null).asRowValues();
final SQLRowValues stockRow = ProductComponent.findOrCreateStock(artRow, depot).asRowValues();
t = Tuple2.create(artRow, stockRow);
mapDeclArticle.put(Tuple3.create(code, couleur.trim(), null), t);
} else if (t.get1() == null) {
t = Tuple2.create(t.get0(), ProductComponent.findOrCreateStock(t.get0(), depot).asRowValues());
mapDeclArticle.put(Tuple3.create(code, couleur.trim(), null), t);
t = this.mapDepotDeclArticle.get(Tuple3.create(code, couleur.trim(), ""));
}
if (t == null) {
System.err.println("\tCREATE ARTICLE " + code + " couleur : " + couleur);
SQLRowValues rARtVirt = this.mapDepotArticleVirtuel.get(code).getRowValsArt();
SQLRowValues artRow = cloneFromArticle(rARtVirt, this.mapCouleur.get(couleur.trim()), null).asRowValues();
t = new InventaireProductLine(artRow);
this.mapDepotDeclArticle.put(Tuple3.create(code, couleur.trim(), null), t);
}
} else {
t = mapDeclArticle.get(Tuple3.create(code, couleur.trim(), taille.trim()));
t = this.mapDepotDeclArticle.get(Tuple3.create(code, couleur.trim(), taille.trim()));
if (t == null) {
if (mapArticle.get(code) != null) {
SQLRowValues artRow = cloneFromArticle(mapArticleVirtuel.get(code).get0(), mapCouleur.get(couleur.trim()), mapTaille.get(taille.trim())).asRowValues();
final SQLRowValues stockRow = ProductComponent.findOrCreateStock(artRow, depot).asRowValues();
t = Tuple2.create(artRow, stockRow);
mapDeclArticle.put(Tuple3.create(code, couleur.trim(), taille.trim()), t);
if (this.mapDepotArticleVirtuel.get(code) != null) {
System.err.println("\tCREATE ARTICLE " + code + " taille : " + taille + " couleur : " + couleur);
SQLRowValues rARtVirt = this.mapDepotArticleVirtuel.get(code).getRowValsArt();
SQLRowValues artRow = cloneFromArticle(rARtVirt, this.mapCouleur.get(couleur.trim()), this.mapTaille.get(taille.trim())).asRowValues();
t = new InventaireProductLine(artRow);
this.mapDepotDeclArticle.put(Tuple3.create(code, couleur.trim(), taille.trim()), t);
}
} else if (t.get1() == null) {
t = Tuple2.create(t.get0(), ProductComponent.findOrCreateStock(t.get0(), depot).asRowValues());
mapDeclArticle.put(Tuple3.create(code, couleur.trim(), taille.trim()), t);
}
}
return t;
610,7 → 775,7
if (rArt == null) {
return null;
}
SQLRowValues copy = artElt.createCopy(rArt.getID());
SQLRowValues copy = this.artElt.createCopy(rArt.getID());
copy.put("VIRTUEL", Boolean.FALSE);
copy.put("ID_ARTICLE_VIRTUEL_PERE", rArt.getID());
if (idCouleur != null) {
640,4 → 805,40
 
return columnName;
}
 
class InventaireProductLine {
private final SQLRowValues rowValsArt;
private final Map<String, SQLRowValues> stockMap = new HashMap<>();
 
public InventaireProductLine(SQLRowValues rowValsArt) {
this.rowValsArt = rowValsArt;
 
Collection<SQLRowValues> stocks = this.rowValsArt.getReferentRows(this.rowValsArt.getTable().getTable("STOCK"));
 
for (SQLRowValues rowValsStock : stocks) {
this.stockMap.put(rowValsStock.getForeign("ID_DEPOT_STOCK").getString("NOM"), rowValsStock);
}
}
 
public SQLRowValues getOrCreateStockRowValues(SQLRowAccessor depot) {
final String depotName = depot.getString("NOM");
if (!this.stockMap.containsKey(depotName)) {
this.stockMap.put(depotName, ProductComponent.findOrCreateStock(this.rowValsArt, depot).asRowValues());
}
return this.stockMap.get(depotName);
}
 
public SQLRowValues getStockRowValues(SQLRowAccessor depot) {
final String depotName = depot.getString("NOM");
if (!this.stockMap.containsKey(depotName)) {
return null;
}
return this.stockMap.get(depotName);
}
 
public SQLRowValues getRowValsArt() {
return this.rowValsArt;
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockRootNode.java
New file
0,0 → 1,111
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.erp.core.sales.product.element.LotSQLElement;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class StockRootNode {
private final List<StockNode> children = new ArrayList<>();
private final List<SQLRowValues> listRowValsStock = new ArrayList<>();
private final List<FieldPath> cols = new ArrayList<>();
private final SQLElement eltStock;
private boolean hasBatch = false;
 
public StockRootNode(SQLElement e) {
this.eltStock = e;
final SQLTable tableStock = this.eltStock.getTable();
final Path pStock = new Path(tableStock);
final Path pDepotStock = pStock.add(tableStock.getField("ID_DEPOT_STOCK"));
this.cols.add(new FieldPath(pDepotStock, "NOM"));
this.cols.add(new FieldPath(pStock, "QTE_TH"));
this.cols.add(new FieldPath(pStock, "QTE_RECEPT_ATTENTE"));
this.cols.add(new FieldPath(pStock, "QTE_LIV_ATTENTE"));
this.cols.add(new FieldPath(pStock, "QTE_REEL"));
 
}
 
public void load(SQLRowAccessor article) {
 
this.children.clear();
final SQLTable tableStock = this.eltStock.getTable();
final SQLRowValues rowValsStock = new SQLRowValues(tableStock);
rowValsStock.putNulls("QTE_TH", "QTE_RECEPT_ATTENTE", "QTE_LIV_ATTENTE", "QTE_REEL");
rowValsStock.putRowValues("ID_DEPOT_STOCK").putNulls("NOM");
 
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsStock);
final List<SQLRowValues> fetch = fetcher.fetch(
new Where(tableStock.getField("ID_ARTICLE"), "=", article.getID()).and(new Where(tableStock.getField("QTE_REEL"), "!=", 0).or(new Where(tableStock.getField("QTE_TH"), "!=", 0))));
this.listRowValsStock.clear();
this.listRowValsStock.addAll(fetch);
final List<Integer> idsStock = new ArrayList<>();
for (SQLRowValues r : this.listRowValsStock) {
idsStock.add(r.getID());
}
 
final SQLTable tableLot = this.eltStock.getDirectory().getElement(LotSQLElement.class).getTable();
SQLRowValues rLot = new SQLRowValues(tableLot);
rLot.putNulls("ID_STOCK", "QUANTITE", "NUMERO_LOT", "NUMERO_SERIE", "DLC", "DLUO");
final List<SQLRowValues> fetchLots = SQLRowValuesListFetcher.create(rLot).fetch(Where.inValues(tableLot.getField("ID_STOCK"), idsStock));
this.hasBatch = !fetchLots.isEmpty();
 
final Map<Integer, List<BatchNode>> stockLots = new HashMap<>();
for (SQLRowValues lot : fetchLots) {
int idStock = lot.getInt("ID_STOCK");
List<BatchNode> lots = stockLots.get(idStock);
if (lots == null) {
lots = new ArrayList<>();
stockLots.put(idStock, lots);
}
lots.add(new BatchNode(lot));
}
for (SQLRowValues r : this.listRowValsStock) {
this.children.add(new StockNode(r, stockLots.get(r.getID())));
}
}
 
public boolean hasBatch() {
return this.hasBatch;
}
 
public StockNode getChild(int i) {
return this.children.get(i);
}
 
public int getSize() {
return this.children.size();
}
 
public String getLabelFor(int column) {
return this.eltStock.getDirectory().getTranslator().getLabelFor(this.cols.get(column).getField()).replace("Quantité", "Quantité\n");
}
 
public FieldPath getFieldPath(int columnIndex) {
final FieldPath fieldPath = this.cols.get(columnIndex);
return fieldPath;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockSnapshotCreator.java
14,6 → 14,7
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLInsert;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
28,6 → 29,8
 
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
47,7 → 50,7
this.withAllProducts = withAllProducts;
}
 
public void create() {
public int create() {
// Récupération des inventaires
SQLTable tableEtatStock = this.root.getTable("ETAT_STOCK");
SQLSelect sel = new SQLSelect();
83,7 → 86,7
if (tableMvtStock.contains("PRICE")) {
vals.put("PRICE", null);
}
vals.put("ID_ARTICLE", null);
vals.putRowValues("ID_ARTICLE").putNulls("CODE", "NOM");
vals.putRowValues("ID_STOCK").putNulls("QTE_REEL").putRowValues("ID_DEPOT_STOCK").putNulls("ID", "NOM", "CODE");
 
// Calendar cal0116 = Calendar.getInstance();
211,27 → 214,37
 
}
 
SQLRowValues rowVals = new SQLRowValues(tableEtatStock);
rowVals.put("DATE", d);
rowVals.put("MONTANT_HA", totalHT);
rowVals.put("ID_DEPOT_STOCK", depot.getID());
SQLInsert insertEtat = new SQLInsert();
insertEtat.add(tableEtatStock.getField("DATE"), d);
insertEtat.add(tableEtatStock.getField("MONTANT_HA"), totalHT);
insertEtat.add(tableEtatStock.getField("ID_DEPOT_STOCK"), depot.getID());
 
try {
int idEtat = SQLInsert.executeSimilarInserts(tableEtatStock.getDBSystemRoot(), Arrays.asList(insertEtat), true).get(0).intValue();
 
List<SQLInsert> inserts = new ArrayList<SQLInsert>();
final SQLTable tableElt = tableEtatStock.getTable("ETAT_STOCK_ELEMENT");
for (EtatStock etatItem : mapStockSnap.values()) {
SQLRowValues rowValsItem = new SQLRowValues(tableEtatStock.getTable("ETAT_STOCK_ELEMENT"));
rowValsItem.put("ID_ETAT_STOCK", rowVals);
rowValsItem.put("PA", etatItem.getPa());
rowValsItem.put("PV", etatItem.getPv());
rowValsItem.put("QTE", etatItem.getQte());
rowValsItem.put("T_PA", etatItem.getTotalPA());
rowValsItem.put("T_PV", etatItem.getTotalPV());
rowValsItem.put("CODE", etatItem.getArticle().getString("CODE"));
rowValsItem.put("NOM", etatItem.getArticle().getString("NOM"));
rowValsItem.put("ID_ARTICLE", etatItem.getArticle().getID());
SQLInsert insertItem = new SQLInsert();
insertItem.add(tableElt.getField("ID_ETAT_STOCK"), idEtat);
insertItem.add(tableElt.getField("PA"), etatItem.getPa());
insertItem.add(tableElt.getField("PV"), etatItem.getPv());
insertItem.add(tableElt.getField("QTE"), etatItem.getQte());
insertItem.add(tableElt.getField("T_PA"), etatItem.getTotalPA());
insertItem.add(tableElt.getField("T_PV"), etatItem.getTotalPV());
insertItem.add(tableElt.getField("CODE"), etatItem.getArticle().getString("CODE"));
insertItem.add(tableElt.getField("NOM"), etatItem.getArticle().getString("NOM"));
insertItem.add(tableElt.getField("ID_ARTICLE"), etatItem.getArticle().getID());
inserts.add(insertItem);
}
try {
rowVals.commit();
if (!inserts.isEmpty()) {
// TODO voir avec Guillaume si il faut spliter par tranche de 1000
SQLInsert.executeSimilarInserts(tableElt.getDBSystemRoot(), inserts, false);
}
return idEtat;
} catch (SQLException e) {
ExceptionHandler.handle("Erreur lors de la création de l'état", e);
return SQLRow.NONEXISTANT_ID;
}
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItem.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
235,6 → 235,10
return this.stock != null && !this.stock.isUndefined();
}
 
public int getStockID() {
return this.stock.getID();
}
 
public void clearStockValues() {
this.realQty = 0;
this.deliverQty = 0;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/EtatStockCreationPanel.java
30,8 → 30,10
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
public class EtatStockCreationPanel extends JPanel {
 
75,6 → 77,7
 
EtatStockSnapshotCreator creator = new EtatStockSnapshotCreator(rowDepot, d, depotElt.getTable().getDBRoot(), !box.isSelected());
creator.create();
((JFrame) SwingUtilities.getRoot(EtatStockCreationPanel.this)).dispose();
}
 
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockItemsUpdater.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
25,8 → 25,6
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTableEvent;
import org.openconcerto.sql.model.SQLTableEvent.Mode;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.DecimalUtils;
59,6 → 57,7
private final List<? extends SQLRowAccessor> items;
private final TypeStockUpdate type;
private final boolean createMouvementStock;
private boolean clearMouvementStock;
private final SQLRowAccessor rowSource;
private boolean resetStockTH = false;
 
100,6 → 99,7
this.items = items;
this.type = t;
this.createMouvementStock = createMouvementStock;
this.clearMouvementStock = createMouvementStock;
this.rowSource = rowSource;
this.headless = GraphicsEnvironment.isHeadless();
}
116,10 → 116,14
 
List<String> requests = new ArrayList<String>();
 
public void setClearMouvementStock(boolean clearMouvementStock) {
this.clearMouvementStock = clearMouvementStock;
}
 
public void update() throws SQLException {
final SQLTable stockTable = this.rowSource.getTable().getTable("STOCK");
 
if (this.createMouvementStock) {
if (this.clearMouvementStock) {
clearExistingMvt(this.rowSource);
}
 
128,10 → 132,12
 
final ListMap<SQLRow, SQLRowValues> cmd = new ListMap<SQLRow, SQLRowValues>();
 
final List<Integer> updatedIDs = new ArrayList<>();
for (StockItem stockItem : stockItems) {
 
if (stockItem.isStockInit()) {
requests.add(stockItem.getUpdateRequest());
updatedIDs.add(stockItem.getStockID());
} else {
SQLRowValues rowVals = new SQLRowValues(stockTable);
rowVals.put("QTE_REEL", stockItem.getRealQty());
161,8 → 167,16
@Override
public Object handle(SQLDataSource ds) throws SQLException, IOException {
SQLUtils.executeMultiple(stockTable.getDBSystemRoot(), requests, handlers);
// FIXME FIRE ONLY CHANGED ROWS
stockTable.fire(new SQLTableEvent(stockTable, SQLRow.NONEXISTANT_ID, Mode.ROW_UPDATED));
 
if (!updatedIDs.isEmpty()) {
if (updatedIDs.size() <= 60) {
for (int idUpdated : updatedIDs) {
stockTable.fireTableModified(idUpdated);
}
} else {
stockTable.fireTableModified();
}
}
return null;
}
});
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockConsultPanel.java
New file
0,0 → 1,165
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.JTreeTable;
import org.openconcerto.ui.table.MultiLineHeaderRenderer;
 
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
 
public class StockConsultPanel extends JPanel {
 
private JTable tableStock;
private StockTreeModel stockModel;
private JLabel code = new JLabel();
private JLabel nom = new JLabel();
private JLabel taille = new JLabel();
private JLabel couleur = new JLabel();
private final boolean hasDeclinaison;
 
public StockConsultPanel(SQLElement eltArt, SQLRowAccessor sqlRowAccessor) {
super(new GridBagLayout());
final SQLPreferences prefs = SQLPreferences.getMemCached(eltArt.getTable().getDBRoot());
this.hasDeclinaison = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false);
 
final GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Code : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
this.add(this.code, c);
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Désignation : ", SwingConstants.RIGHT), c);
c.weightx = 0;
c.gridx++;
c.weightx = 1;
this.add(this.nom, c);
 
if (this.hasDeclinaison) {
// Taille
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Taille : ", SwingConstants.RIGHT), c);
c.weightx = 0;
c.gridx++;
c.weightx = 1;
this.add(this.taille, c);
// Couleur
c.gridy++;
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel("Couleur : ", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 0;
c.weightx = 1;
this.add(this.couleur, c);
}
c.gridy++;
c.gridx = 0;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 2;
c.weighty = 1;
this.stockModel = new StockTreeModel(new StockRootNode(eltArt.getForeignElement("ID_STOCK")));
load(sqlRowAccessor);
this.tableStock = new JTreeTable(this.stockModel);
 
MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
Enumeration e = this.tableStock.getColumnModel().getColumns();
while (e.hasMoreElements()) {
final TableColumn tableColumn = (TableColumn) e.nextElement();
tableColumn.setHeaderRenderer(renderer);
 
}
this.tableStock.getColumnModel().getColumn(0).setWidth(260);
this.tableStock.getColumnModel().getColumn(0).setMinWidth(200);
if (this.tableStock.getColumnModel().getColumnCount() > 5) {
this.tableStock.getColumnModel().getColumn(5).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
value = new SimpleDateFormat("dd/MM/yyyy").format((Date) value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
});
}
this.add(new JScrollPane(this.tableStock), c);
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.SOUTHEAST;
final JButton close = new JButton("Fermer");
close.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
((JFrame) SwingUtilities.getRoot(StockConsultPanel.this)).dispose();
}
});
this.add(close, c);
this.setMinimumSize(new Dimension(960, 400));
this.setPreferredSize(new Dimension(960, 400));
}
 
public void load(SQLRowAccessor article) {
this.code.setText(article.getString("CODE"));
this.nom.setText(article.getString("NOM"));
if (this.hasDeclinaison) {
final SQLRowAccessor nonEmptyForeignTaille = article.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_TAILLE");
if (nonEmptyForeignTaille != null) {
this.taille.setText(nonEmptyForeignTaille.getString("NOM"));
} else {
this.taille.setText("");
}
 
final SQLRowAccessor nonEmptyForeignCouleur = article.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_COULEUR");
if (nonEmptyForeignCouleur != null) {
this.couleur.setText(nonEmptyForeignCouleur.getString("NOM"));
} else {
this.couleur.setText("");
}
 
}
this.stockModel.load(article);
 
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
59,6 → 59,8
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
335,10 → 337,44
CommandeItemTable itemTable = cmp.getRowValuesTablePanel();
 
final RowValuesTableModel model = cmp.getRowValuesTable().getRowValuesTableModel();
for (SQLRowValues rowValsElt : e.getValue()) {
final List<SQLRowValues> articleToCmd = e.getValue();
// Tri des items par code, couleur et taille
Collections.sort(articleToCmd, new Comparator<SQLRowValues>() {
@Override
public int compare(SQLRowValues o1, SQLRowValues o2) {
SQLRowAccessor o1ArticleNumber = o1.contains("ID_ARTICLE") ? o1.getNonEmptyForeign("ID_ARTICLE") : null;
SQLRowAccessor o2ArticleNumber = o1.contains("ID_ARTICLE") ? o1.getNonEmptyForeign("ID_ARTICLE") : null;
if (o1ArticleNumber != null && o2ArticleNumber != null) {
int comparedCode = o1ArticleNumber.getString("CODE").compareTo(o1ArticleNumber.getString("CODE"));
if (comparedCode == 0) {
SQLRowAccessor o1CouleurNumber = o1ArticleNumber.contains("ID_ARTICLE_DECLINAISON_COULEUR")
? o1ArticleNumber.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_COULEUR")
: null;
SQLRowAccessor o2CouleurNumber = o2ArticleNumber.contains("ID_ARTICLE_DECLINAISON_COULEUR")
? o2ArticleNumber.getNonEmptyForeign("ID_ARTICLE_DECLINAISON_COULEUR")
: null;
if (o1CouleurNumber != null && o2CouleurNumber != null) {
int comparedCouleurCode = o1CouleurNumber.getBigDecimal("ORDRE").compareTo(o2CouleurNumber.getBigDecimal("ORDRE"));
if (comparedCouleurCode != 0) {
return comparedCouleurCode;
}
}
SQLRowAccessor o1TailleNumber = o1ArticleNumber.contains("ID_ARTICLE_TAILLE_COULEUR") ? o1ArticleNumber.getNonEmptyForeign("ID_ARTICLE_TAILLE_COULEUR") : null;
SQLRowAccessor o2TailleNumber = o2ArticleNumber.contains("ID_ARTICLE_TAILLE_COULEUR") ? o2ArticleNumber.getNonEmptyForeign("ID_ARTICLE_TAILLE_COULEUR") : null;
if (o1TailleNumber != null && o2TailleNumber != null) {
int comparedTailleCode = o1TailleNumber.getBigDecimal("ORDRE").compareTo(o2TailleNumber.getBigDecimal("ORDRE"));
return comparedTailleCode;
}
}
return comparedCode;
} else {
return o1.getString("CODE").compareTo(o2.getString("CODE"));
}
}
});
for (SQLRowValues rowValsElt : articleToCmd) {
SQLRowValues rowValsMatch = null;
int index = 0;
 
for (int i = 0; i < model.getRowCount(); i++) {
final SQLRowValues rowValsCmdElt = model.getRowValuesAt(i);
Number lineArticleNumber = rowValsCmdElt.contains("ID_ARTICLE") ? rowValsCmdElt.getNonEmptyForeignIDNumber("ID_ARTICLE") : null;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockSQLElement.java
31,9 → 31,12
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.request.ComboSQLRequest.KeepMode;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.ui.DefaultGridBagConstraints;
67,7 → 70,7
@Override
public void actionPerformed(ActionEvent e) {
if (UserRightsManager.getCurrentUserRights().canAdd(getTable().getDBRoot().getTable("STOCK"))) {
final PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), IListe.get(e).getSelectedRows()), "Mise à jour des stocks");
final PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), IListe.get(e).getSelectedRowAccessors()), "Mise à jour des stocks");
FrameUtil.show(p);
} else {
JOptionPane.showMessageDialog(null, "Vous n'avez les droits suffisants pour modifier manuellement les stocks!");
150,6 → 153,11
return rowStock;
}
 
@Override
protected SQLTableModelSourceOnline instantiateTableSourceOnline(ListSQLRequest req) {
return new SQLTableModelSourceOnline(req, this, KeepMode.ROW);
}
 
public static SQLRowAccessor getStock(SQLRowAccessor rowValsSource) throws SQLException {
 
SQLRowAccessor rowStock = null;
377,7 → 385,7
.and(new Where(rowValsCode.getTable().getField("ID_FOURNISSEUR"), "=", fournisseur.getID()));
final List<SQLRowValues> fetch = SQLRowValuesListFetcher.create(rowValsCode).fetch(w);
for (SQLRowValues sqlRowAccessor : fetch) {
rowValsElt.put("ID_CODE_FOURNISSEUR", sqlRowAccessor.getID());
rowValsElt.put("ID_CODE_FOURNISSEUR", sqlRowAccessor);
}
}
map.add(fournisseur, rowValsElt);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/ImportInventairePanel.java
93,7 → 93,7
@Override
public void run() {
// FIXME ajouter une barre de progression
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter(depotElt.getDirectory().getElement("ARTICLE"), rowDepot);
final InventaireFromEtatStockImporter impoter = new InventaireFromEtatStockImporter(depotElt.getDirectory().getElement("ARTICLE"));
try {
SQLUtils.executeAtomic(depotElt.getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
@Override
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/StockTreeModel.java
New file
0,0 → 1,228
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.element;
 
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.table.AbstractTreeTableModel;
import org.openconcerto.ui.table.TreeTableModel;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
 
public class StockTreeModel extends AbstractTreeTableModel {
static final SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
 
public StockTreeModel(Object root) {
super(root);
 
}
 
@Override
public Object getChild(Object parent, int index) {
if (parent instanceof StockRootNode) {
return ((StockRootNode) parent).getChild(index);
}
if (parent instanceof StockNode) {
return ((StockNode) parent).getLot(index);
}
return null;
}
 
@Override
public int getChildCount(Object parent) {
if (parent instanceof StockRootNode) {
final int size = ((StockRootNode) parent).getSize();
return size;
}
if (parent instanceof StockNode) {
final int size = ((StockNode) parent).getLotSize();
return size;
}
return 0;
}
 
@Override
public boolean isLeaf(Object node) {
if (node instanceof StockRootNode) {
return false;
}
if (node instanceof StockNode) {
return ((StockNode) node).getLotSize() == 0;
}
return true;
}
 
@Override
public int getColumnCount() {
if (((StockRootNode) getRoot()).hasBatch()) {
return 6;
}
return 5;
}
 
@Override
public String getColumnName(int column) {
if (column == 0) {
return "Dépôt";
}
if (column >= 1 && column < 5) {
return ((StockRootNode) getRoot()).getLabelFor(column);
}
if (column == 5) {
return "DLC/DLUO";
}
return "";
}
 
@SuppressWarnings("rawtypes")
@Override
public Class getColumnClass(int column) {
if (column == 0) {
return TreeTableModel.class;
}
if (column > 0 && column < 5) {
return Float.class;
}
if (column == 5) {
return Date.class;
}
return String.class;
}
 
@Override
public Object getValueAt(Object node, int column) {
if (node instanceof StockRootNode) {
return null;
}
if (node instanceof StockNode) {
final StockNode n = ((StockNode) node);
if (column >= 5) {
return null;
}
final StockRootNode root = ((StockRootNode) getRoot());
final FieldPath fieldPath = root.getFieldPath(column);
return n.getValueAt(fieldPath, column);
}
if (node instanceof BatchNode) {
final BatchNode rLot = (BatchNode) node;
if (column == 4) {
return rLot.getValues().getBigDecimal("QUANTITE").floatValue();
}
if (column == 5) {
final Calendar c1 = rLot.getValues().getDate("DLC");
final Calendar c2 = rLot.getValues().getDate("DUO");
if (c1 == null && c2 != null) {
return c2.getTime();
}
if (c2 == null && c1 != null) {
return c1.getTime();
}
if (c1 != null && c2 != null) {
if (c1.before(c2)) {
return c1.getTime();
} else {
return c2.getTime();
}
} else {
return null;
}
 
}
 
}
 
return null;
}
 
public void load(SQLRowAccessor article) {
((StockRootNode) getRoot()).load(article);
fireTreeStructureChanged(this, new Object[] { getRoot() }, new int[] { 0 }, new Object[] {});
}
 
}
 
class BatchNode {
private final SQLRowValues sqlRowValues;
private String str;
 
public BatchNode(SQLRowValues sqlRowValues) {
this.sqlRowValues = sqlRowValues;
final StringBuilder b = new StringBuilder();
if (!sqlRowValues.getString("NUMERO_LOT").isEmpty()) {
b.append(sqlRowValues.getString("NUMERO_LOT"));
 
}
if (!sqlRowValues.getString("NUMERO_SERIE").isEmpty()) {
b.append(sqlRowValues.getString("NUMERO_SERIE"));
b.append(" ");
}
 
if (sqlRowValues.getDate("DLC") != null) {
b.append(" DLC: ");
b.append(StockTreeModel.df.format(sqlRowValues.getDate("DLC").getTime()));
b.append(" ");
}
if (sqlRowValues.getDate("DLUO") != null) {
b.append(" DLUO: ");
b.append(StockTreeModel.df.format(sqlRowValues.getDate("DLUO").getTime()));
b.append(" ");
}
this.str = b.toString().trim();
}
 
@Override
public String toString() {
return this.str;
}
 
public SQLRowValues getValues() {
return this.sqlRowValues;
}
}
 
class StockNode {
private final SQLRowValues sqlRowValues;
private final List<BatchNode> lots;
 
public StockNode(SQLRowValues sqlRowValues, List<BatchNode> lots) {
this.sqlRowValues = sqlRowValues;
this.lots = lots;
}
 
public int getLotSize() {
if (this.lots == null)
return 0;
else
return this.lots.size();
}
 
public Object getValueAt(FieldPath fieldPath, int columnIndex) {
return this.sqlRowValues.followPath(fieldPath.getPath()).getObject(fieldPath.getFieldName());
}
 
public BatchNode getLot(int index) {
if (this.lots == null)
return null;
return this.lots.get(index);
}
 
@Override
public String toString() {
return this.sqlRowValues.getForeign("ID_DEPOT_STOCK").getString("NOM");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/report/SQLRowValuesTreeNode.java
New file
0,0 → 1,56
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.report;
 
import org.openconcerto.sql.model.SQLRowValues;
 
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
 
public class SQLRowValuesTreeNode {
private SQLRowValues r;
private List<SQLRowValuesTreeNode> children = new ArrayList<>();
 
public SQLRowValuesTreeNode(SQLRowValues r) {
this.r = r;
}
 
public SQLRowValues getSQLRowValues() {
return this.r;
}
 
public void addChild(SQLRowValuesTreeNode node) {
this.children.add(node);
}
 
public List<SQLRowValuesTreeNode> getChildren() {
return this.children;
}
 
public int getChildrenCount() {
return this.children.size();
}
 
public void dump(int space, PrintStream prt) {
for (int i = 0; i < space; i++) {
prt.println(" ");
}
prt.println(this.r);
for (SQLRowValuesTreeNode n : this.children) {
n.dump(space + 1, prt);
}
prt.flush();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/report/SQLRowValuesTree.java
New file
0,0 → 1,58
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.report;
 
import org.openconcerto.sql.model.SQLRowValues;
 
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class SQLRowValuesTree {
List<SQLRowValuesTreeNode> children = new ArrayList<>();
 
public SQLRowValuesTree(List<SQLRowValues> all, String fieldName) {
Map<Number, SQLRowValuesTreeNode> map = new HashMap<>(all.size());
for (SQLRowValues r : all) {
SQLRowValuesTreeNode node = new SQLRowValuesTreeNode(r);
map.put(r.getIDNumber(), node);
}
for (SQLRowValues r : all) {
final Number foreignIDNumber = r.getForeignIDNumber(fieldName);
SQLRowValuesTreeNode node = map.get(r.getIDNumber());
 
final SQLRowValuesTreeNode sqlRowValuesTreeNode = map.get(foreignIDNumber);
if (sqlRowValuesTreeNode != null) {
sqlRowValuesTreeNode.addChild(node);
} else {
this.children.add(node);
}
 
}
 
}
 
public List<SQLRowValuesTreeNode> getChildren() {
return this.children;
}
 
public void dump(PrintStream prt) {
for (SQLRowValuesTreeNode n : this.children) {
n.dump(0, prt);
}
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/report/StockReportPDF.java
New file
0,0 → 1,463
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.supplychain.stock.report;
 
import org.openconcerto.erp.core.finance.accounting.report.GrandLivrePDF;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
 
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
 
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
 
public class StockReportPDF {
 
private static final int LINE_HEIGHT = 10;
 
private static final float COL_1_SIZE = 80;
private static final float COL_2_SIZE = 300;
private static final float COL_3_SIZE = 30;
private static final float COL_4_SIZE = 40;
private static final float COL_5_SIZE = 50;
private static final float COL_1_X = 50;
 
private static final float COL_2_X = COL_1_X + COL_1_SIZE;
private static final float COL_3_X = COL_2_X + COL_2_SIZE;
private static final float COL_4_X = COL_3_X + COL_3_SIZE;
private static final float COL_5_X = COL_4_X + COL_4_SIZE;
 
private final PDDocument doc;
private final List<SQLRow> etatsStock = new ArrayList<>();
private final String companyName;
private final String title;
private int y = 0;
private PDPageContentStream content;
 
private final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(Locale.FRANCE));
private final DecimalFormat decimalFormatQuantity = new DecimalFormat("#,##0.##", DecimalFormatSymbols.getInstance(Locale.FRANCE));
 
private Map<SQLRow, BigDecimal> totaux = new HashMap<>();
 
public StockReportPDF(String companyName, String title) throws IOException {
this.companyName = companyName;
this.title = title;
 
this.doc = new PDDocument();
final PDPage page = new PDPage(PDRectangle.A4);
this.doc.addPage(page);
 
this.content = new PDPageContentStream(this.doc, page);
this.y = drawHeader(true, true);
 
}
 
private int drawHeader(boolean full, boolean columns) throws IOException {
this.y = 795;
this.content.beginText();
this.content.setFont(PDType1Font.HELVETICA_BOLD, 14);
this.content.newLineAtOffset(40, this.y);
this.content.showText("INVENTAIRE " + StringUtils.cleanPDFString(this.companyName.toUpperCase()));
this.content.endText();
this.y -= 17;
if (full) {
this.content.beginText();
this.content.setFont(PDType1Font.HELVETICA, 12);
this.content.newLineAtOffset(40, this.y);
this.content.showText(StringUtils.cleanPDFString(this.title));
this.content.endText();
 
this.y -= 20;
}
this.content.setFont(PDType1Font.HELVETICA_BOLD, 7);
if (columns) {
this.content.beginText();
this.content.newLineAtOffset(COL_1_X + 5, this.y);
this.content.showText("CODE");
this.content.endText();
 
this.content.beginText();
this.content.newLineAtOffset(COL_2_X, this.y);
this.content.showText("ARTICLE");
this.content.endText();
 
drawRightAlign(this.content, COL_3_X, this.y, COL_3_SIZE, "QUANTITE");
drawRightAlign(this.content, COL_4_X, this.y, COL_4_SIZE, "PRIX U.");
drawRightAlign(this.content, COL_5_X, this.y, COL_5_SIZE, "TOTAL");
}
this.y -= 4;
this.content.setStrokingColor(Color.BLACK);
this.content.setLineWidth(1f);
this.content.moveTo(COL_1_X - 4, this.y);
this.content.lineTo(COL_5_X + COL_5_SIZE + 4, this.y);
this.content.stroke();
 
return this.y;
}
 
private static void drawRightAlign(PDPageContentStream content, float x, float y, float width, String text) throws IOException {
content.beginText();
final float w = PDType1Font.HELVETICA.getStringWidth(StringUtils.cleanPDFString(text)) / 1000.0f * 7f;
content.newLineAtOffset(x + width - w, y);
content.showText(StringUtils.cleanPDFString(text));
content.endText();
}
 
private void drawFamilleName(String name) throws IOException {
this.y -= LINE_HEIGHT;
 
this.content.setFont(PDType1Font.HELVETICA_BOLD, 7);
 
this.content.beginText();
this.content.newLineAtOffset(COL_1_X, this.y);
this.content.showText(StringUtils.cleanPDFString(name));
this.content.endText();
 
}
 
/**
*
* @param root
* @param mapDeclinaison map de ID_ARTICLE_DECLINAISON_... vers Tuple2<Nom, Ordre>
*/
 
private void fillDeclinaisons(DBRoot root, Map<String, Map<Integer, Tuple2<String, BigDecimal>>> mapDeclinaisons) {
List<String> tablesDeclinaisons = new ArrayList<>();
List<String> declinaisonsFieldNames = new ArrayList<>();
SQLTable tableArticle = root.getTable("ARTICLE");
 
for (SQLField f : tableArticle.getFields()) {
if (f.getName().startsWith("ID_ARTICLE_DECLINAISON_")) {
declinaisonsFieldNames.add(f.getName());
tablesDeclinaisons.add(f.getName().substring("ID_".length()));
}
}
 
for (String table : tablesDeclinaisons) {
SQLTable t = tableArticle.getTable(table);
final SQLSelect selDecl = new SQLSelect();
selDecl.addSelect(t.getKey());
selDecl.addSelect(t.getField("NOM"));
selDecl.addSelect(t.getField("ORDRE"));
Map<Integer, Tuple2<String, BigDecimal>> m = new HashMap<>();
mapDeclinaisons.put("ID_" + table, m);
for (SQLRow row : SQLRowListRSH.execute(selDecl)) {
m.put(row.getID(), Tuple2.create(row.getString("NOM"), row.getBigDecimal("ORDRE")));
}
}
}
 
private void drawLine(String code, String article, BigDecimal qte, BigDecimal prixUnitaire, BigDecimal total) throws IOException {
String s = StringUtils.splitString(article, 70);
final List<String> parts = StringUtils.fastSplitTrimmed(s, '\n');
this.y -= LINE_HEIGHT;
 
if (this.y - LINE_HEIGHT * parts.size() < 50) {
final PDPage page = new PDPage(PDRectangle.A4);
this.doc.addPage(page);
if (this.content != null) {
this.content.close();
}
this.content = new PDPageContentStream(this.doc, page);
this.y = drawHeader(false, true);
this.y -= LINE_HEIGHT;
this.y -= LINE_HEIGHT;
}
 
this.content.setFont(PDType1Font.HELVETICA, 7);
if (code != null) {
this.content.beginText();
this.content.newLineAtOffset(COL_1_X, this.y);
this.content.showText(StringUtils.cleanPDFString(code));
this.content.endText();
}
 
drawRightAlign(this.content, COL_3_X, this.y, COL_3_SIZE, this.decimalFormatQuantity.format(qte));
drawRightAlign(this.content, COL_4_X, this.y, COL_4_SIZE, this.decimalFormat.format(prixUnitaire));
drawRightAlign(this.content, COL_5_X, this.y, COL_5_SIZE, this.decimalFormat.format(total));
 
for (String part : parts) {
this.content.beginText();
this.content.newLineAtOffset(COL_2_X, this.y);
this.content.showText(StringUtils.cleanPDFString(part));
this.content.endText();
this.y -= LINE_HEIGHT;
}
this.y += LINE_HEIGHT;
 
this.content.setLineWidth(0.5f);
this.content.setStrokingColor(Color.LIGHT_GRAY);
this.content.moveTo(COL_1_X - 4, this.y - 2f);
this.content.lineTo(COL_5_X + 4 + COL_5_SIZE, this.y - 2f);
this.content.stroke();
 
}
 
public void addStockDepot(SQLRow rowEtatStock) throws IOException {
 
this.etatsStock.add(rowEtatStock);
 
final DBRoot root = rowEtatStock.getTable().getDBRoot();
// Nouvelle page si besoin
if (this.etatsStock.size() > 1) {
final PDPage page = new PDPage(PDRectangle.A4);
this.doc.addPage(page);
if (this.content != null) {
this.content.close();
}
this.content = new PDPageContentStream(this.doc, page);
this.y = drawHeader(false, true);
}
final SQLTable tDepot = root.getTable("DEPOT_STOCK");
final SQLTable tFamilleArtice = root.getTable("FAMILLE_ARTICLE");
final SQLRow rDepot = tDepot.getRow(rowEtatStock.getInt("ID_DEPOT_STOCK"));
 
this.y -= LINE_HEIGHT * 2;
 
// Nom du déport
this.content.setFont(PDType1Font.HELVETICA, 10);
this.content.beginText();
this.content.newLineAtOffset(COL_1_X, this.y);
this.content.showText(StringUtils.cleanPDFString("DÉPÔT : " + rDepot.getString("NOM")));
this.content.endText();
this.y -= LINE_HEIGHT;
// Depot Element
final SQLTable tEtatStockElement = root.getTable("ETAT_STOCK_ELEMENT");
final SQLRowValues rElements = new SQLRowValues(tEtatStockElement);
final SQLRowValues putRowValues = rElements.putRowValues("ID_ARTICLE");
putRowValues.putNulls("ID_FAMILLE_ARTICLE");
for (SQLField field : putRowValues.getTable().getContentFields()) {
if (field.getName().startsWith("ID_ARTICLE_DECLINAISON_")) {
putRowValues.put(field.getName(), null);
}
}
rElements.putNulls("PA", "T_PA", "QTE", "CODE", "NOM");
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rElements);
final List<SQLRowValues> elements = fetcher
.fetch(new Where(tEtatStockElement.getField("ID_ETAT_STOCK"), "=", rowEtatStock.getID()).and(new Where(tEtatStockElement.getField("QTE"), ">", BigDecimal.ZERO)));
 
Collections.sort(elements, new Comparator<SQLRowValues>() {
 
@Override
public int compare(SQLRowValues o1, SQLRowValues o2) {
final BigDecimal qte1 = o1.getBigDecimal("PA");
final BigDecimal qte2 = o2.getBigDecimal("PA");
if (qte1.signum() == 0 && qte2.signum() == 0 || qte1.signum() != 0 && qte2.signum() != 0) {
return o1.getString("NOM").compareTo(o2.getString("NOM"));
} else if (qte1.signum() == 0) {
return 1;
} else {
return -1;
}
}
});
final Map<Number, List<SQLRowValues>> mapFamilleElement = new HashMap<>();
 
for (final SQLRowValues e : elements) {
final Number idFamille = e.getForeign("ID_ARTICLE").getForeignIDNumber("ID_FAMILLE_ARTICLE");
List<SQLRowValues> l = mapFamilleElement.get(idFamille);
if (l == null) {
l = new ArrayList<>();
mapFamilleElement.put(idFamille, l);
}
l.add(e);
}
 
// On recupere tous les familles
final SQLRowValues rFamille = new SQLRowValues(root.getTable("FAMILLE_ARTICLE"));
rFamille.putNulls("NOM", "ID_FAMILLE_ARTICLE_PERE");
List<SQLRowValues> familles = SQLRowValuesListFetcher.create(rFamille).fetch();
System.out.println("StockReportPDF.addStockDepot()" + familles.size() + " familles");
SQLRowValuesTree tree = new SQLRowValuesTree(familles, "ID_FAMILLE_ARTICLE_PERE");
tree.dump(System.out);
// On récupère les declinaisons
Map<String, Map<Integer, Tuple2<String, BigDecimal>>> mapDeclinaison = new HashMap<>();
fillDeclinaisons(tDepot.getDBRoot(), mapDeclinaison);
 
//// On groupe par Famille
 
// D'abord les articles sans familles
BigDecimal t = BigDecimal.ZERO;
for (final SQLRowValues e : elements) {
final Number idFamille = e.getForeign("ID_ARTICLE").getForeignIDNumber("ID_FAMILLE_ARTICLE");
if (idFamille.intValue() == tFamilleArtice.getUndefinedID()) {
drawEtatStockElement(e, mapDeclinaison);
t = t.add(e.getBigDecimal("T_PA"));
 
}
}
this.totaux.put(rowEtatStock, t);
 
// Les familles selons l'arbre
List<SQLRowValuesTreeNode> roots = tree.getChildren();
final Comparator<SQLRowValuesTreeNode> comparatorFamille = new Comparator<SQLRowValuesTreeNode>() {
 
@Override
public int compare(SQLRowValuesTreeNode o1, SQLRowValuesTreeNode o2) {
return o1.getSQLRowValues().getString("NOM").compareToIgnoreCase(o2.getSQLRowValues().getString("NOM"));
}
};
Collections.sort(roots, comparatorFamille);
for (SQLRowValuesTreeNode f : roots) {
drawFamilleNode(mapFamilleElement, f, mapDeclinaison);
}
 
}
 
private void drawFamilleNode(Map<Number, List<SQLRowValues>> mapFamilleElement, SQLRowValuesTreeNode f, Map<String, Map<Integer, Tuple2<String, BigDecimal>>> mapDeclinaison) throws IOException {
if (f.getChildrenCount() > 0) {
drawFamilleName(f.getSQLRowValues().getString("NOM").toUpperCase());
}
// EtatStockElement
List<SQLRowValues> list = mapFamilleElement.get(f.getSQLRowValues().getIDNumber());
if (list != null) {
for (SQLRowValues e : list) {
drawEtatStockElement(e, mapDeclinaison);
}
}
// Sous familles
for (SQLRowValuesTreeNode n : f.getChildren()) {
drawFamilleNode(mapFamilleElement, n, mapDeclinaison);
}
 
}
 
private void drawEtatStockElement(SQLRowValues e, Map<String, Map<Integer, Tuple2<String, BigDecimal>>> mapDeclinaison) throws IOException {
String code = e.getString("CODE");
String article = e.getString("NOM");
 
StringBuilder detailsDeclinaison = new StringBuilder();
final SQLRowAccessor nonEmptyForeignArticle = e.getNonEmptyForeign("ID_ARTICLE");
if (nonEmptyForeignArticle != null) {
for (String fieldDecl : mapDeclinaison.keySet()) {
if (nonEmptyForeignArticle.getObject(fieldDecl) != null) {
final Number nonEmptyForeignDecl = nonEmptyForeignArticle.getNonEmptyForeignIDNumber(fieldDecl);
if (nonEmptyForeignDecl != null) {
final String declinaisonName = mapDeclinaison.get(fieldDecl).get(nonEmptyForeignDecl).get0();
if (declinaisonName.trim().length() > 0) {
detailsDeclinaison.append(fieldDecl.substring("ID_ARTICLE_DECLINAISON_".length()));
detailsDeclinaison.append(" : ");
detailsDeclinaison.append(declinaisonName);
detailsDeclinaison.append(" ");
}
}
}
}
}
String detailsDeclString = detailsDeclinaison.toString().trim();
if (detailsDeclString.length() > 0) {
article += "\n" + detailsDeclString;
}
 
BigDecimal qte = e.getBigDecimal("QTE");
BigDecimal prixUnitaire = e.getBigDecimal("PA");
BigDecimal total = e.getBigDecimal("T_PA");
drawLine(code, article, qte, prixUnitaire, total);
}
 
public void savePDF(File f) throws IOException {
final PDPage page = new PDPage(PDRectangle.A4);
this.doc.addPage(page);
if (this.content != null) {
this.content.close();
}
this.content = new PDPageContentStream(this.doc, page);
// Totaux
drawHeader(false, false);
 
this.y -= LINE_HEIGHT;
 
this.content.setFont(PDType1Font.HELVETICA, 10);
 
for (SQLRow r : this.etatsStock) {
BigDecimal total = this.totaux.get(r);
final SQLTable tDepot = r.getTable().getTable("DEPOT_STOCK");
 
final SQLRow rDepot = tDepot.getRow(r.getInt("ID_DEPOT_STOCK"));
 
this.y -= LINE_HEIGHT * 2;
 
// Nom du déport
this.content.setFont(PDType1Font.HELVETICA, 10);
this.content.beginText();
this.content.newLineAtOffset(COL_1_X, this.y);
this.content.showText(StringUtils.cleanPDFString("TOTAL DÉPÔT : " + rDepot.getString("NOM") + " : " + this.decimalFormat.format(total) + " EUR"));
this.content.endText();
 
}
 
this.content.close();
// Header avec numéro de page
final InputStream sImage = GrandLivrePDF.class.getResourceAsStream("OpenConcerto_2000px.png");
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final byte[] buf = new byte[8192];
int length;
while ((length = sImage.read(buf)) > 0) {
bOut.write(buf, 0, length);
}
sImage.close();
bOut.close();
 
final float ratio = 20;
final int pageCount = this.doc.getNumberOfPages();
for (int index = 0; index < pageCount; index++) {
final PDPage currentPage = this.doc.getPage(index);
this.content = new PDPageContentStream(this.doc, currentPage, PDPageContentStream.AppendMode.APPEND, true, true);
if (index == 0 || index == pageCount - 1) {
// Logo sur 1ere page
final PDImageXObject pdImage = PDImageXObject.createFromByteArray(this.doc, bOut.toByteArray(), "openconcerto.png");
final float h = pdImage.getHeight() / ratio;
this.content.drawImage(pdImage, 40, 10, pdImage.getWidth() / ratio, h);
}
 
this.content.beginText();
this.content.setFont(PDType1Font.HELVETICA, 10);
this.content.newLineAtOffset(500, 20);
this.content.showText("Page " + (index + 1) + " / " + pageCount);
this.content.endText();
this.content.close();
}
 
this.doc.save(f);
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ClientNormalSQLElement.java
23,6 → 23,7
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
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.Where;
97,6 → 98,11
}
}
 
@Override
public String getDescription(SQLRow fromRow) {
return fromRow.getString("CODE") + " " + fromRow.getString("NOM");
}
 
public void printLabel(SQLRowAccessor row, String qlPrinterProperty) {
final LabelCreator c = new LabelCreator(720);
c.setLeftMargin(10);
192,7 → 198,7
@Override
protected void _initTableSource(SQLTableModelSource res) {
super._initTableSource(res);
 
addCommercialFilter(res, getTable().getField("ID_COMMERCIAL"));
res.getColumns().add(new BaseSQLTableModelColumn(getDirectory().getTranslator().getLabelFor(getTable().getField("CATEGORIES")), String.class) {
 
@Override
214,7 → 220,8
@Override
protected void _initComboRequest(ComboSQLRequest req) {
super._initComboRequest(req);
req.setWhere(new Where(getTable().getField("OBSOLETE"), "=", Boolean.FALSE));
addCommercialFilterCombo(req, getTable().getField("ID_COMMERCIAL"));
req.putWhere("Obsolete", new Where(getTable().getField("OBSOLETE"), "=", Boolean.FALSE));
}
 
/*
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ContactItemTable.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
31,8 → 31,11
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.function.Supplier;
 
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
109,6 → 112,12
list.add(tableElementNoMailing);
}
 
final Map<String, Supplier<? extends JComponent>> additionalFields = elt.getAdditionalFields();
for (String addField : additionalFields.keySet()) {
SQLTableElement eltAdd = new SQLTableElement(elt.getTable().getField(addField));
list.add(eltAdd);
}
 
if (elt.getTable().contains("DATE_NAISSANCE")) {
list.add(new SQLTableElement(elt.getTable().getField("DATE_NAISSANCE")) {
private final DateToSQLConvertor conv = new DateToSQLConvertor();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ComptaContactSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
13,11 → 13,23
package org.openconcerto.erp.core.customerrelationship.customer.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
 
import java.awt.event.ActionEvent;
import java.util.List;
 
import javax.swing.AbstractAction;
 
45,8 → 57,53
public ContactSQLElement() {
super("CONTACT");
}
 
@Override
protected void _initComboRequest(ComboSQLRequest req) {
super._initComboRequest(req);
final UserRights rights = UserRightsManager.getCurrentUserRights();
if (!rights.haveRight(ComptaSQLConfElement.NON_RESTREINT_PAR_COMMERCIAL_RIGHT)) {
req.putWhere(ComptaSQLConfElement.NON_RESTREINT_PAR_COMMERCIAL_RIGHT, getWhereCommercial());
}
}
 
@Override
protected synchronized void _initTableSource(SQLTableModelSource res) {
 
super._initTableSource(res);
final UserRights rights = UserRightsManager.getCurrentUserRights();
if (!rights.haveRight(ComptaSQLConfElement.NON_RESTREINT_PAR_COMMERCIAL_RIGHT)) {
res.getReq().putWhere(ComptaSQLConfElement.NON_RESTREINT_PAR_COMMERCIAL_RIGHT, getWhereCommercial());
}
}
 
private Where getWhereCommercial() {
SQLRow row = getTable().getDBRoot().findTable("USER_COMMON").getRow(UserManager.getInstance().getCurrentUser().getId());
final SQLTable tableCommercial = getTable().getTable("COMMERCIAL");
List<SQLRow> rows = row.getReferentRows(tableCommercial.getField("ID_USER_COMMON"));
 
Where w = null;
 
if (rows.isEmpty()) {
w = Where.FALSE;
} else {
for (SQLRow sqlRow : rows) {
 
// CLIENT.ID_COMMERCIAL in CONTACT
SQLField field = getTable().getField("ID_CLIENT");
SQLSelect selIDClient = new SQLSelect();
selIDClient.addSelect(field.getForeignTable().getKey());
selIDClient.setWhere(new Where(field.getForeignTable().getField("ID_COMMERCIAL"), "=", sqlRow.getID()));
 
Where wClient = Where.createRaw(field.getSQLName().quote() + " IN (" + selIDClient.asString() + ")", field);
w = Where.or(w, wClient);
 
}
}
return w;
}
}
 
protected ComptaContactSQLElement(String tableName) {
super(tableName);
PredicateRowAction action = new PredicateRowAction(new AbstractAction() {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplate.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
18,6 → 18,7
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
 
import java.awt.BorderLayout;
import java.awt.Component;
58,7 → 59,7
this.dateFormat = dateFormat;
}
 
public static List<EmailTemplate> getAll(DBRoot root) {
public static List<EmailTemplate> getAllForTable(DBRoot root, String tableName) {
final List<EmailTemplate> result = new ArrayList<>();
final SQLSelect selF = new SQLSelect();
final SQLTable tFamilleArticle = root.getTable(EmailTemplateSQLElement.TABLE_NAME);
68,6 → 69,7
selF.addSelect(tFamilleArticle.getField("TEXTE"));
selF.addSelect(tFamilleArticle.getField("PAR_DEFAUT"));
selF.addSelect(tFamilleArticle.getField("FORMAT_DATE"));
selF.setWhere(new Where(tFamilleArticle.getField("TABLE_NAME"), "=", tableName));
final List<SQLRow> lF = SQLRowListRSH.execute(selF);
for (SQLRow sqlRow : lF) {
result.add(new EmailTemplate(sqlRow.getString("NOM"), sqlRow.getString("TITRE"), sqlRow.getString("TEXTE"), sqlRow.getBoolean("PAR_DEFAUT"), sqlRow.getString("FORMAT_DATE")));
95,11 → 97,11
return this.dateFormat;
}
 
public static void askTemplate(JComponent parent, DBRoot root, ValueListener listener) {
public static void askTemplate(JComponent parent, DBRoot root, String tableName, ValueListener listener) {
if (!SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("must be called from EDT");
}
List<EmailTemplate> templates = getAll(root);
List<EmailTemplate> templates = getAllForTable(root, tableName);
if (templates.isEmpty()) {
listener.valueSelected(null);
return;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateTableComboBox.java
New file
0,0 → 1,143
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.customerrelationship.mail;
 
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.request.SQLRowItemView;
import org.openconcerto.sql.sqlobject.itemview.RowItemViewComponent;
import org.openconcerto.ui.valuewrapper.ValueChangeSupport;
import org.openconcerto.ui.valuewrapper.ValueWrapper;
import org.openconcerto.utils.checks.ValidListener;
import org.openconcerto.utils.checks.ValidState;
import org.openconcerto.utils.doc.Documented;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JComboBox;
import javax.swing.JComponent;
 
public class EmailTemplateTableComboBox extends JComboBox<EmailTemplateTableNameItem> implements ValueWrapper<EmailTemplateTableNameItem>, Documented, RowItemViewComponent {
private final ValueChangeSupport<EmailTemplateTableNameItem> supp;
public static final List<String> tablesCustomer = Arrays.asList("ECHEANCE_CLIENT", "RELANCE", "AVOIR_CLIENT", "DEVIS", "COMMANDE_CLIENT", "BON_DE_LIVRAISON", "SAISIE_VENTE_FACTURE");
public static final List<String> tablesSupplier = Arrays.asList("COMMANDE", "DEMANDE_PRIX", "BON_RECEPTION", "FACTURE_FOURNISSEUR", "AVOIR_FOURNISSEUR");
 
private Map<String, EmailTemplateTableNameItem> mapItem = new HashMap<>();
 
public EmailTemplateTableComboBox(SQLElementDirectory dir) {
 
this.supp = new ValueChangeSupport<EmailTemplateTableNameItem>(this);
this.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
supp.fireValueChange();
}
});
 
for (String name : tablesCustomer) {
final EmailTemplateTableNameItem item = new EmailTemplateTableNameItem(name, dir, true);
mapItem.put(name, item);
addItem(item);
}
for (String name : tablesSupplier) {
final EmailTemplateTableNameItem item = new EmailTemplateTableNameItem(name, dir, true);
mapItem.put(name, item);
addItem(item);
}
}
 
public EmailTemplateTableNameItem getItemFromTableName(String tableName) {
return mapItem.get(tableName);
}
 
@Override
public ValidState getValidState() {
return ValidState.getTrueInstance();
}
 
@Override
public void addValidListener(ValidListener l) {
this.supp.addValidListener(l);
}
 
@Override
public void removeValidListener(ValidListener l) {
this.supp.removeValidListener(l);
}
 
@Override
public void setValue(EmailTemplateTableNameItem val) {
this.setSelectedItem(val);
}
 
@Override
public void resetValue() {
// TODO Auto-generated method stub
 
}
 
@Override
public EmailTemplateTableNameItem getValue() {
return (EmailTemplateTableNameItem) this.getSelectedItem();
}
 
@Override
public void addValueListener(PropertyChangeListener l) {
this.supp.addValueListener(l);
}
 
@Override
public void rmValueListener(PropertyChangeListener l) {
this.supp.addValueListener(l);
}
 
@Override
public void init(SQLRowItemView v) {
// TODO Auto-generated method stub
 
}
 
@Override
public String getGenericDoc() {
return "";
}
 
@Override
public String getDocId() {
 
return "TableName";
}
 
@Override
public boolean onScreen() {
return true;
}
 
@Override
public boolean isDocTransversable() {
return false;
}
 
@Override
public JComponent getComp() {
return this;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateSQLComponent.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
17,6 → 17,8
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRowValues;
 
import javax.swing.JComponent;
 
public class EmailTemplateSQLComponent extends GroupSQLComponent {
 
public EmailTemplateSQLComponent(SQLElement element) {
24,6 → 26,22
}
 
@Override
protected void addViews() {
super.addViews();
 
}
 
@Override
public JComponent createEditor(String id) {
if (id.equals("TABLE_NAME")) {
EmailTemplateTableComboBox box = new EmailTemplateTableComboBox(getDirectory());
addView(new EmailTableTableNameRowItemView(box), "TABLE_NAME", REQ);
return box;
}
return super.createEditor(id);
}
 
@Override
protected SQLRowValues createDefaults() {
final SQLRowValues defaultValues = new SQLRowValues(getTable());
defaultValues.put("FORMAT_DATE", "dd/MM/yyyy");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailCreator.java
New file
0,0 → 1,204
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.customerrelationship.mail;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.GestionDevise;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class EmailCreator {
 
private final EmailTemplate template;
private final List<SQLRow> rows;
private final Map<String, String> map;
private final String files;
 
public EmailCreator(EmailTemplate template, List<SQLRow> row, String files) {
 
this.template = template;
this.rows = row;
this.files = files;
this.map = getMapValues();
}
 
private Map<String, String> getMapValues() {
String datePattern = this.template.getDateFormat();
if (datePattern == null || datePattern.trim().isEmpty()) {
datePattern = "dd/MM/yyyy";
}
 
final Map<String, String> map = new HashMap<>();
 
final SQLRow rowSoc = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
final SQLRow rowSocAdresse = rowSoc.getForeignRow("ID_ADRESSE_COMMON");
SQLRow rowUser = rowSoc.getTable().getDBRoot().findTable("USER_COMMON").getRow(UserManager.getUser().getId());
map.put("UserName", rowUser.getString("NOM"));
map.put("UserFirstName", rowUser.getString("PRENOM"));
if (rowUser.getTable().contains("MAIL")) {
map.put("UserMail", rowUser.getString("MAIL"));
}
if (rowUser.getTable().contains("TEL")) {
map.put("UserTel", rowUser.getString("TEL"));
}
// Infos societe
map.put("SocieteType", rowSoc.getString("TYPE"));
map.put("SocieteNom", rowSoc.getString("NOM"));
map.put("SocieteAdresse", rowSocAdresse.getString("RUE"));
map.put("SocieteCodePostal", rowSocAdresse.getString("CODE_POSTAL"));
 
String ville = rowSocAdresse.getString("VILLE");
final Object cedex = rowSocAdresse.getObject("CEDEX");
final boolean hasCedex = rowSocAdresse.getBoolean("HAS_CEDEX");
 
if (hasCedex) {
ville += " CEDEX";
if (cedex != null && cedex.toString().trim().length() > 0) {
ville += " " + cedex.toString().trim();
}
}
 
map.put("SocieteVille", ville);
 
map.put("PiècesJointes", this.files);
 
SQLRow rowTiers;
String fieldTiers = "ID_CLIENT";
if (EmailTemplateTableComboBox.tablesSupplier.contains(this.rows.get(0).getTable().getName())) {
fieldTiers = "ID_FOURNISSEUR";
}
 
final SQLRow tiersRowNX = this.rows.get(0).getForeignRow(fieldTiers);
rowTiers = tiersRowNX;
SQLRow rowAdresse = rowTiers.getForeignRow("ID_ADRESSE");
 
// Infos Client
if (fieldTiers.equals("ID_CLIENT")) {
map.put("TiersType", rowTiers.getString("FORME_JURIDIQUE"));
}
map.put("TiersNom", rowTiers.getString("NOM"));
map.put("TiersAdresse", rowAdresse.getString("RUE"));
map.put("TiersCodePostal", rowAdresse.getString("CODE_POSTAL"));
String villeCli = rowAdresse.getString("VILLE");
final Object cedexCli = rowAdresse.getObject("CEDEX");
final boolean hasCedexCli = rowAdresse.getBoolean("HAS_CEDEX");
 
if (hasCedexCli) {
villeCli += " CEDEX";
if (cedexCli != null && cedexCli.toString().trim().length() > 0) {
villeCli += " " + cedexCli.toString().trim();
}
}
 
map.put("TiersVille", villeCli);
 
// Date
Date d = new Date();
DateFormat dateFormat = new SimpleDateFormat(datePattern);
map.put("Date", dateFormat.format(d));
 
// Infos documents
Long lTotalTTC = 0L;
Long lTotalHT = 0L;
Long lTotalTVA = 0L;
 
Set<String> affairesNumero = new HashSet<>();
Set<String> affairesRef = new HashSet<>();
Set<String> documentsNumero = new HashSet<>();
Set<String> documentsRef = new HashSet<>();
Set<String> documentsDate = new HashSet<>();
Set<String> dateReception = new HashSet<>();
Set<String> documentsDateValid = new HashSet<>();
for (SQLRow sqlRow : rows) {
 
if (sqlRow.getTable().contains("DATE_RECEPTION_DEMANDEE")) {
Calendar dateRecpt = sqlRow.getDate("DATE_RECEPTION_DEMANDEE");
if (d != null) {
dateReception.add(dateFormat.format(dateRecpt.getTime()));
}
}
String fieldTotal = "T_";
if (!sqlRow.getTable().contains("T_TTC") && sqlRow.getTable().contains("MONTANT_TTC")) {
fieldTotal = "MONTANT_";
}
 
lTotalTTC += (Long) sqlRow.getObject(fieldTotal + "TTC");
lTotalHT += (Long) sqlRow.getObject(fieldTotal + "HT");
lTotalTVA += (Long) sqlRow.getObject(fieldTotal + "TVA");
 
documentsNumero.add(sqlRow.getString("NUMERO"));
if (sqlRow.getTable().contains("NOM")) {
documentsRef.add(sqlRow.getString("NOM"));
} else {
if (sqlRow.getTable().contains("OBJET")) {
documentsRef.add(sqlRow.getString("OBJET"));
}
}
documentsDate.add(dateFormat.format((Date) sqlRow.getObject("DATE")));
 
if (sqlRow.getTable().contains("ID_AFFAIRE")) {
SQLRow rowAffaire = sqlRow.getForeign("ID_AFFAIRE");
if (rowAffaire.getTable().contains("OBJET"))
affairesRef.add(rowAffaire.getString("OBJET"));
affairesNumero.add(rowAffaire.getString("NUMERO"));
 
}
if (sqlRow.getTable().contains("DATE_VALIDITE") && sqlRow.getObject("DATE_VALIDITE") != null) {
documentsDateValid.add(dateFormat.format((Date) sqlRow.getObject("DATE_VALIDITE")));
}
}
map.put("DocumentDateValidite", CollectionUtils.join(documentsDateValid, ","));
map.put("NomAffaire", CollectionUtils.join(affairesRef, ","));
map.put("NumeroAffaire", CollectionUtils.join(affairesNumero, ","));
map.put("DocumentNumero", CollectionUtils.join(documentsNumero, ","));
map.put("DocumentReference", CollectionUtils.join(documentsRef, ","));
map.put("DocumentDate", CollectionUtils.join(documentsDate, ","));
map.put("DocumentDateReception", CollectionUtils.join(dateReception, ","));
map.put("DocumentTotalTTC", GestionDevise.currencyToString(lTotalTTC.longValue(), true));
map.put("DocumentTotalHT", GestionDevise.currencyToString(lTotalHT.longValue(), true));
map.put("DocumentTotalTVA", GestionDevise.currencyToString(lTotalTVA.longValue(), true));
 
map.put("message", "");
return map;
}
 
public String getObject() {
return fill(this.template.getTitle());
}
 
public String getValue() {
return fill(this.template.getText());
}
 
private String fill(String string) {
String result = string;
for (String key : this.map.keySet()) {
result = result.replace("{" + key + "}", this.map.get(key));
}
return result;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTableTableNameRowItemView.java
New file
0,0 → 1,52
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.customerrelationship.mail;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.sqlobject.itemview.VWRowItemView;
import org.openconcerto.ui.component.InteractionMode;
import org.openconcerto.ui.valuewrapper.ValueWrapper;
 
public class EmailTableTableNameRowItemView extends VWRowItemView<EmailTemplateTableNameItem> {
 
public EmailTableTableNameRowItemView(ValueWrapper<EmailTemplateTableNameItem> wrapper) {
super(wrapper);
}
 
@Override
public void setEditable(InteractionMode b) {
if (this.getComp() != null) {
this.getComp().setEnabled(b.isEnabled());
}
}
 
@Override
public void show(SQLRowAccessor r) {
 
if (r.getObject(getField().getName()) != null) {
EmailTemplateTableComboBox box = (EmailTemplateTableComboBox) this.getWrapper().getComp();
 
this.getWrapper().setValue(box.getItemFromTableName(r.getString(getField().getName())));
} else {
this.getWrapper().setValue(null);
}
}
 
@Override
public void update(SQLRowValues vals) {
vals.put(getField().getName(), this.isEmpty() ? SQLRowValues.SQL_DEFAULT : this.getWrapper().getValue().getTableName());
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateTableNameItem.java
New file
0,0 → 1,44
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.customerrelationship.mail;
 
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.utils.StringUtils;
 
public class EmailTemplateTableNameItem {
 
private final String tableName, name;
private final boolean customer;
 
public EmailTemplateTableNameItem(String tableName, SQLElementDirectory dir, boolean customer) {
this.tableName = tableName;
this.name = StringUtils.firstUp(dir.getElement(tableName).getPluralName());
this.customer = customer;
}
 
public String getTableName() {
return tableName;
}
 
public boolean isCustomer() {
return customer;
}
 
@Override
public String toString() {
 
return this.name;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
16,9 → 16,18
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.sql.element.GlobalMapper;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.StringUtils;
 
import java.util.Arrays;
import java.util.List;
import java.util.Set;
 
public class EmailTemplateSQLElement extends ComptaSQLConfElement {
public static final String TABLE_NAME = "MODELE_EMAIL";
36,6 → 45,31
}
 
@Override
protected void _initTableSource(SQLTableModelSource res) {
 
super._initTableSource(res);
 
SQLTableModelColumn colTableName = new BaseSQLTableModelColumn("Table", String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
final String string = r.getString("TABLE_NAME");
return StringUtils.firstUp(getDirectory().getElement(string).getPluralName());
 
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
 
return CollectionUtils.createSet(new FieldPath(p, "TABLE_NAME"));
}
};
 
res.getColumns().add(colTableName);
}
 
@Override
protected List<String> getComboFields() {
return Arrays.asList("NOM");
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/mail/EmailTemplateGroup.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
25,6 → 25,10
addItem("TITRE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
addItem("TEXTE", new LayoutHints(true, true, true, true, true, true, true));
addItem("FORMAT_DATE", new LayoutHints(false, false, true, true, false, false));
addItem("TABLE_NAME");
addItem("PAR_DEFAUT");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivrePDF.java
16,7 → 16,6
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
26,6 → 25,7
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.Color;
80,32 → 80,43
 
private final List<Map<String, Object>> recapSousTotaux = new ArrayList<>();
 
private final SQLElementDirectory directory;
 
public static final String TEMPLATE_ID = "GrandLivre";
public static final String TEMPLATE_PROPERTY_NAME = "LocationGrandLivre";
private static final int LINE_HEIGHT = 10;
private static final float COL_1_SIZE = 34;
private static final float COL_2_SIZE = 35;
private static final float COL_3_SIZE = 35;
private static final float COL_4_SIZE = 246;
private static final float COL_5_SIZE = 50;
private static final float COL_6_SIZE = COL_5_SIZE;
private static final float COL_7_SIZE = 60;
// Date
private static final float COL_DATE_1_SIZE = 34;
// Jrnl
private static final float COL_JRNL_2_SIZE = 35;
// Mvt
private static final float COL_MVT_3_SIZE = 35;
// Lettrage
private static final float COL_LETTRAGE_4_SIZE = 25;
 
private static final float COL_1_X = 40;
private static final float COL_2_X = COL_1_X + COL_1_SIZE;
private static final float COL_3_X = COL_2_X + COL_2_SIZE;
private static final float COL_4_X = COL_3_X + COL_3_SIZE;
private static final float COL_5_X = COL_4_X + COL_4_SIZE;
private static final float COL_6_X = COL_5_X + COL_5_SIZE;
private static final float COL_7_X = COL_6_X + COL_6_SIZE;
// Libelle
private static final float COL_LIBELLE_5_SIZE = 221;
 
// Debit
private static final float COL_DEBIT_6_SIZE = 50;
 
// Credit
private static final float COL_CREDIT_7_SIZE = COL_DEBIT_6_SIZE;
 
// SOlde
private static final float COL_SOLDE_8_SIZE = 60;
 
private static final float COL_DATE_1_X = 40;
private static final float COL_JRNL_2_X = COL_DATE_1_X + COL_DATE_1_SIZE;
private static final float COL_MVT_3_X = COL_JRNL_2_X + COL_JRNL_2_SIZE;
private static final float COL_LET_4_X = COL_MVT_3_X + COL_MVT_3_SIZE;
private static final float COL_LIB_5_X = COL_LET_4_X + COL_LETTRAGE_4_SIZE;
private static final float COL_DEB_6_X = COL_LIB_5_X + COL_LIBELLE_5_SIZE;
private static final float COL_CRE_7_X = COL_DEB_6_X + COL_DEBIT_6_SIZE;
private static final float COL_SOL_8_X = COL_CRE_7_X + COL_CREDIT_7_SIZE;
 
private final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(Locale.FRANCE));
 
public GrandLivrePDF(ComptaPropsConfiguration conf, Date du, Date au, String compteDep, String compteEnd, int lettrage, boolean cumul, boolean excludeCptSolde, boolean centralClient,
boolean centralFourn, int idJrnlExclude) {
this.directory = conf.getDirectory();
this.rowSociete = conf.getRowSociete();
final DBRoot b = conf.getRootSociete();
this.tableEcriture = b.getTable("ECRITURE");
270,7 → 281,9
 
}
 
if (contents != null) {
contents.close();
}
 
// Recapitulatif
 
330,7 → 343,7
contents.beginText();
contents.setFont(PDType1Font.HELVETICA, 10);
contents.newLineAtOffset(250, 20);
contents.showText("Edition du " + this.dateFormatEcr.format(new Date()));
contents.showText("Edition du " + StringUtils.cleanPDFString(this.dateFormatEcr.format(new Date())));
contents.endText();
 
contents.beginText();
352,33 → 365,41
 
contents.setFont(PDType1Font.HELVETICA, 7);
if (dateEcriture != null) {
drawRightAlign(contents, COL_1_X, y, COL_1_SIZE - 5, this.dateFormatEcr.format(dateEcriture));
drawRightAlign(contents, COL_DATE_1_X, y, COL_DATE_1_SIZE - 5, this.dateFormatEcr.format(dateEcriture));
}
if (journal != null) {
contents.beginText();
contents.newLineAtOffset(COL_2_X, y);
contents.showText(cleanString(journal));
contents.newLineAtOffset(COL_JRNL_2_X, y);
contents.showText(StringUtils.cleanPDFString(journal));
contents.endText();
}
if (mouvement != null) {
contents.beginText();
contents.newLineAtOffset(COL_3_X, y);
contents.showText(cleanString(mouvement));
contents.newLineAtOffset(COL_MVT_3_X, y);
contents.showText(StringUtils.cleanPDFString(mouvement));
contents.endText();
}
 
if (codeLettrage != null) {
contents.beginText();
contents.newLineAtOffset(COL_4_X, y);
contents.showText(cleanString(libelle));
contents.newLineAtOffset(COL_LET_4_X, y);
contents.showText(StringUtils.cleanPDFString(codeLettrage));
contents.endText();
}
 
drawRightAlign(contents, COL_5_X, y, COL_5_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_6_X, y, COL_6_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_7_X, y, COL_7_SIZE, this.decimalFormat.format(solde));
contents.beginText();
contents.newLineAtOffset(COL_LIB_5_X, y);
contents.showText(StringUtils.limitLength(StringUtils.cleanPDFString(libelle), 60));
contents.endText();
 
drawRightAlign(contents, COL_DEB_6_X, y, COL_DEBIT_6_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_CRE_7_X, y, COL_CREDIT_7_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_SOL_8_X, y, COL_SOLDE_8_SIZE, this.decimalFormat.format(solde));
 
contents.setLineWidth(0.5f);
contents.setStrokingColor(Color.LIGHT_GRAY);
contents.moveTo(COL_1_X - 4, y - 2f);
contents.lineTo(COL_7_X + 4 + COL_7_SIZE, y - 2f);
contents.moveTo(COL_DATE_1_X - 4, y - 2f);
contents.lineTo(COL_SOL_8_X + 4 + COL_SOLDE_8_SIZE, y - 2f);
contents.stroke();
 
return y;
390,55 → 411,36
contents.setFont(PDType1Font.HELVETICA_BOLD, 7);
if (!total) {
contents.beginText();
contents.newLineAtOffset(COL_1_X, y);
contents.showText(num);
contents.newLineAtOffset(COL_DATE_1_X, y);
contents.showText(StringUtils.cleanPDFString(num));
contents.endText();
 
contents.setFont(PDType1Font.HELVETICA, 7);
 
contents.beginText();
contents.newLineAtOffset(COL_3_X, y);
contents.showText(cleanString(libelle));
contents.newLineAtOffset(COL_MVT_3_X, y);
contents.showText(StringUtils.cleanPDFString(libelle));
contents.endText();
}
drawRightAlign(contents, COL_5_X, y, COL_5_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_6_X, y, COL_6_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_7_X, y, COL_7_SIZE, this.decimalFormat.format(solde));
drawRightAlign(contents, COL_DEB_6_X, y, COL_DEBIT_6_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_CRE_7_X, y, COL_CREDIT_7_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_SOL_8_X, y, COL_SOLDE_8_SIZE, this.decimalFormat.format(solde));
 
if (!total) {
contents.setLineWidth(0.5f);
contents.setStrokingColor(Color.LIGHT_GRAY);
contents.moveTo(COL_1_X - 4, y - 2f);
contents.lineTo(COL_7_X + 4 + COL_7_SIZE, y - 2f);
contents.moveTo(COL_DATE_1_X - 4, y - 2f);
contents.lineTo(COL_SOL_8_X + 4 + COL_SOLDE_8_SIZE, y - 2f);
contents.stroke();
}
return y;
}
 
private String cleanString(String s) {
StringBuilder b = new StringBuilder(s.length());
 
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
b.append(c);
} else if (c == 'é' || c == 'è' || c == 'ê' || c == 'â' || c == 'à' || c == 'î' || c == 'ù' || c == 'û' || c == 'ô' || c == 'ç') {
b.append(c);
} else if (c >= 32 && c < 127) {
b.append(c);
} else {
b.append(' ');
}
}
 
return b.toString();
 
}
 
private void drawRightAlign(PDPageContentStream contents, float x, float y, float width, String text) throws IOException {
contents.beginText();
final float w = PDType1Font.HELVETICA.getStringWidth(text) / 1000.0f * 7f;
final float w = PDType1Font.HELVETICA.getStringWidth(StringUtils.cleanPDFString(text)) / 1000.0f * 7f;
contents.newLineAtOffset(x + width - w, y);
contents.showText(text);
contents.showText(StringUtils.cleanPDFString(text));
contents.endText();
}
 
446,9 → 448,9
y -= LINE_HEIGHT;
contents.beginText();
contents.setFont(PDType1Font.HELVETICA_BOLD, 7);
contents.newLineAtOffset(COL_1_X, y);
contents.newLineAtOffset(COL_DATE_1_X, y);
String string = numCpt + " " + nomCpt.toUpperCase();
contents.showText(cleanString(string));
contents.showText(StringUtils.cleanPDFString(string));
contents.endText();
 
return y;
458,13 → 460,13
y -= LINE_HEIGHT;
contents.setFont(PDType1Font.HELVETICA_BOLD, 7);
contents.beginText();
contents.newLineAtOffset(COL_4_X, y);
contents.showText("Cumuls antérieurs");
contents.newLineAtOffset(COL_LIB_5_X, y);
contents.showText(StringUtils.cleanPDFString("Cumuls antérieurs"));
contents.endText();
 
drawRightAlign(contents, COL_5_X, y, COL_5_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_6_X, y, COL_6_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_7_X, y, COL_7_SIZE, this.decimalFormat.format(solde));
drawRightAlign(contents, COL_DEB_6_X, y, COL_DEBIT_6_SIZE, this.decimalFormat.format(debit));
drawRightAlign(contents, COL_CRE_7_X, y, COL_CREDIT_7_SIZE, this.decimalFormat.format(credit));
drawRightAlign(contents, COL_SOL_8_X, y, COL_SOLDE_8_SIZE, this.decimalFormat.format(solde));
 
return y;
}
474,13 → 476,14
contents.beginText();
contents.setFont(PDType1Font.HELVETICA_BOLD, 14);
contents.newLineAtOffset(40, y);
contents.showText("GRAND LIVRE " + companyName.toUpperCase());
 
contents.showText("GRAND LIVRE " + StringUtils.cleanPDFString(companyName.toUpperCase()));
contents.endText();
y -= 17;
contents.beginText();
contents.setFont(PDType1Font.HELVETICA, 12);
contents.newLineAtOffset(40, y);
contents.showText(title);
contents.showText(StringUtils.cleanPDFString(title));
contents.endText();
 
y -= 20;
488,40 → 491,45
 
if (full) {
contents.beginText();
contents.newLineAtOffset(COL_1_X + 5, y);
contents.newLineAtOffset(COL_DATE_1_X + 5, y);
contents.showText("DATE");
contents.endText();
 
contents.beginText();
contents.newLineAtOffset(COL_2_X, y);
contents.newLineAtOffset(COL_JRNL_2_X, y);
contents.showText("JOURNAL");
contents.endText();
 
contents.beginText();
contents.newLineAtOffset(COL_3_X, y);
contents.newLineAtOffset(COL_MVT_3_X, y);
contents.showText(" MVT");
contents.endText();
 
contents.beginText();
contents.newLineAtOffset(COL_4_X, y);
contents.newLineAtOffset(COL_LET_4_X, y);
contents.showText("LET");
contents.endText();
 
contents.beginText();
contents.newLineAtOffset(COL_LIB_5_X, y);
contents.showText("LIBELLE");
contents.endText();
} else {
contents.beginText();
contents.newLineAtOffset(COL_1_X, y);
contents.newLineAtOffset(COL_DATE_1_X, y);
contents.showText("COMPTE");
contents.endText();
}
 
drawRightAlign(contents, COL_5_X, y, COL_5_SIZE, "DEBIT");
drawRightAlign(contents, COL_6_X, y, COL_6_SIZE, "CREDIT");
drawRightAlign(contents, COL_7_X, y, COL_7_SIZE, "SOLDE CUMULE");
drawRightAlign(contents, COL_DEB_6_X, y, COL_DEBIT_6_SIZE, "DEBIT");
drawRightAlign(contents, COL_CRE_7_X, y, COL_CREDIT_7_SIZE, "CREDIT");
drawRightAlign(contents, COL_SOL_8_X, y, COL_SOLDE_8_SIZE, "SOLDE CUMULE");
 
y -= 4;
contents.setStrokingColor(Color.BLACK);
contents.setLineWidth(1f);
contents.moveTo(COL_1_X - 4, y);
contents.lineTo(COL_7_X + COL_7_SIZE + 4, y);
contents.moveTo(COL_DATE_1_X - 4, y);
contents.lineTo(COL_SOL_8_X + COL_SOLDE_8_SIZE + 4, y);
contents.stroke();
 
return y;
541,13 → 549,13
y -= LINE_HEIGHT;
contents.beginText();
contents.setFont(PDType1Font.HELVETICA_BOLD, 7);
contents.newLineAtOffset(COL_4_X, y);
contents.newLineAtOffset(COL_LIB_5_X, y);
contents.showText("Sous-total");
contents.endText();
 
drawRightAlign(contents, COL_5_X, y, COL_5_SIZE, this.decimalFormat.format(debit / 100D));
drawRightAlign(contents, COL_6_X, y, COL_6_SIZE, this.decimalFormat.format(credit / 100D));
drawRightAlign(contents, COL_7_X, y, COL_7_SIZE, this.decimalFormat.format((debit - credit) / 100D));
drawRightAlign(contents, COL_DEB_6_X, y, COL_DEBIT_6_SIZE, this.decimalFormat.format(debit / 100D));
drawRightAlign(contents, COL_CRE_7_X, y, COL_CREDIT_7_SIZE, this.decimalFormat.format(credit / 100D));
drawRightAlign(contents, COL_SOL_8_X, y, COL_SOLDE_8_SIZE, this.decimalFormat.format((debit - credit) / 100D));
 
y -= LINE_HEIGHT;
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/Map2033B.java
435,14 → 435,17
******************************************************************************************/
// 312
// 374 SommeSoldeDebit( 4457, 4457* )
// 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));
// // TODO Prndre les ecritures des comptes 4457 uniquement issues des ventes, la case doit
// contenir toute la tva collectée de l'exercice (factures et avoirs)
// 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.soldeCompteDebiteur(4456, 4456, true, this.dateDeb,
// this.dateFin);
// this.m.put("T1.42", GestionDevise.currencyToString(v378, false));
 
// 378 SommeSoldeCredit( 44566 )
long v378 = this.sommeCompte.soldeCompteDebiteur(4456, 4456, true, this.dateDeb, this.dateFin);
this.m.put("T1.42", GestionDevise.currencyToString(v378, false));
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Map2033B.this.bar.setValue(95);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/VentilationAnalytiqueSheetXML.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
124,7 → 124,7
 
final SQLRowValues valsAnalytique = new SQLRowValues(tableAssoc);
valsAnalytique.put("ID_ECRITURE", vals);
valsAnalytique.putRowValues("ID_POSTE_ANALYTIQUE").put("NOM", null);
valsAnalytique.putRowValues("ID_POSTE_ANALYTIQUE").put("NOM", null).putRowValues("ID_AXE_ANALYTIQUE").putNulls("NOM");
valsAnalytique.put("POURCENT", null);
valsAnalytique.put("MONTANT", null);
valsAnalytique.put("ID_ECRITURE", vals);
263,6 → 263,7
setTitle = true;
setCumuls = true;
} else {
if (sqlRowValuesAnalytique.getObject("MONTANT") != null) {
long l = sqlRowValuesAnalytique.getLong("MONTANT");
long cred = (l >= 0 ? 0 : -l);
long deb = (l <= 0 ? 0 : l);
291,6 → 292,7
ooLine.put("SOLDE", (solde == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(solde, false)));
 
style.put(tableauVals.size() - 1, "Normal");
}
i++;
}
 
313,7 → 315,8
 
sheetVals.put("TITRE_1", "Ventilation analytique " + this.rowSociete.getString("TYPE") + " " + this.rowSociete.getString("NOM"));
sheetVals.put("DATE_EDITION", new Date());
sheetVals.put("TITRE_2", "Poste analytique : " + this.rowPoste.getString("NOM") + ". Période du " + dateFormatEcr.format(this.dateDu) + " au " + dateFormatEcr.format(this.dateAu) + ".");
sheetVals.put("TITRE_2", "Axe : " + this.rowPoste.getForeign("ID_AXE_ANALYTIQUE").getString("NOM") + " Poste : " + this.rowPoste.getString("NOM") + ". Période du "
+ dateFormatEcr.format(this.dateDu) + " au " + dateFormatEcr.format(this.dateAu) + ".");
 
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/RapprochementBancaireSheetXML.java
New file
0,0 → 1,316
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.report;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.cc.ITransformer;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class RapprochementBancaireSheetXML extends AbstractListeSheetXml {
 
private final static SQLTable tableEcriture = base.getTable("ECRITURE");
private final static SQLTable tableMvt = base.getTable("MOUVEMENT");
private final static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
private final static DateFormat dateFormatEcr = DateFormat.getDateInstance(DateFormat.SHORT);
private SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
 
private Date dateDu, dateAu;
private String compteDeb, numeroReleve;
private final boolean detail;
private final BigDecimal soldeDepart;
 
public static String TEMPLATE_ID = "EtatRapprochement";
public static String TEMPLATE_PROPERTY_NAME = "LocationEtatRapprochement";
 
@Override
public String getDefaultTemplateId() {
return TEMPLATE_ID;
}
 
Date date;
 
@Override
public String getName() {
if (this.date == null) {
this.date = new Date();
}
return "Rapprochement" + date.getTime();
}
 
@Override
protected String getStoragePathP() {
return "Rapprochement";
}
 
public RapprochementBancaireSheetXML(Date du, Date au, String compteDep, boolean detail, String numeroReleve, BigDecimal soldeDepart) {
super();
Calendar cal = Calendar.getInstance();
cal.setTime(au);
this.printer = PrinterNXProps.getInstance().getStringProperty("GrandLivrePrinter");
this.dateAu = au;
this.dateDu = du;
this.compteDeb = compteDep.trim();
this.numeroReleve = numeroReleve;
this.detail = detail;
this.soldeDepart = soldeDepart;
}
 
private String toDay = dateFormat.format(new Date());
private int size;
 
protected void createListeValues() {
Date d = new Date();
 
final SQLRowValues vals = new SQLRowValues(tableEcriture);
vals.put("ID_COMPTE_PCE", null);
vals.put("COMPTE_NUMERO", null);
vals.put("COMPTE_NOM", null);
if (tableEcriture.contains("NOM_PIECE")) {
vals.put("NOM_PIECE", null);
}
vals.put("ID_JOURNAL", null);
vals.put("JOURNAL_CODE", null);
vals.put("JOURNAL_NOM", null);
vals.putRowValues("ID_MOUVEMENT").put("NUMERO", null).putRowValues("ID_PIECE").put("NOM", null);
vals.put("CREDIT", null);
vals.put("DEBIT", null);
vals.put("DATE", null);
vals.put("NOM", null);
vals.put("NOM_PIECE", null);
vals.put("POINTEE", null);
vals.put("DATE_POINTEE", null);
 
final SQLRowValuesListFetcher fetcher = new SQLRowValuesListFetcher(vals);
fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect sel) {
 
Where w = (new Where(tableEcriture.getField("DATE"), RapprochementBancaireSheetXML.this.dateDu, RapprochementBancaireSheetXML.this.dateAu));
 
if (numeroReleve != null && numeroReleve.trim().length() > 0) {
// On prend toutes les écritures de la période + celle pointées
// avec le numéro de relevé sans filtre de période
// w = w.and(new Where(tableEcriture.getField("POINTEE"), "=", (Object)
// null).or(new Where(tableEcriture.getField("POINTEE"), "=", "")));
w = w.or(new Where(tableEcriture.getField("POINTEE"), "=", numeroReleve));
}
 
w = w.and(new Where(tableEcriture.getField("COMPTE_NUMERO"), "=", RapprochementBancaireSheetXML.this.compteDeb));
 
w = w.and(new Where(tableEcriture.getField("ID_MOUVEMENT"), "=", tableMvt.getField("ID")));
 
sel.setWhere(w);
sel.addFieldOrder(tableEcriture.getField("COMPTE_NUMERO"));
sel.addFieldOrder(tableEcriture.getField("DATE"));
sel.addFieldOrder(tableMvt.getField("NUMERO"));
System.err.println(sel.asString());
return sel;
}
});
 
List<SQLRowValues> list = fetcher.fetch();
size = list.size();
System.err.println("START CREATE Rapprochement, NB ecritures " + size);
 
// Valeur de la liste
// listAllSheetValues ;
 
// Style des lignes
// styleAllSheetValues;
 
// Valeur à l'extérieur de la liste
// mapAllSheetValues
 
List<Map<String, Object>> tableauVals = new ArrayList<Map<String, Object>>();
this.listAllSheetValues.put(0, tableauVals);
 
Map<Integer, String> style = new HashMap<Integer, String>();
this.styleAllSheetValues.put(0, style);
 
Line lineSoldePointe = new Line("Solde pointé du compte " + this.compteDeb + " au " + this.dateFormatEcr.format(dateAu));
Line lineSoldeAdjust = new Line("Solde réajusté du compte " + this.compteDeb + " au " + this.dateFormatEcr.format(dateAu));
 
Line lineSoldeNonPointe = new Line("Solde non pointé du compte " + this.compteDeb + " au " + this.dateFormatEcr.format(dateAu));
 
Line lineSoldeAutrePointe = new Line("Solde pointé autre relevé du compte " + this.compteDeb + " au " + this.dateFormatEcr.format(dateAu));
 
if (this.soldeDepart != null) {
Line lineSoldeDepart = new Line("Solde de départ du compte " + this.compteDeb + " au " + this.dateFormatEcr.format(dateAu));
final SQLRowValues rowSoldeDepart = new SQLRowValues(tableEcriture);
if (this.soldeDepart.signum() > 0) {
rowSoldeDepart.put("DEBIT", this.soldeDepart.movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue());
rowSoldeDepart.put("CREDIT", 0);
} else {
rowSoldeDepart.put("CREDIT", this.soldeDepart.movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue());
rowSoldeDepart.put("DEBIT", 0);
}
lineSoldePointe.cumulRow(rowSoldeDepart);
lineSoldeAdjust.cumulRow(rowSoldeDepart);
lineSoldeDepart.cumulRow(rowSoldeDepart);
tableauVals.add(lineSoldeDepart.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
 
}
 
List<Line> lineNonPointee = new ArrayList<>();
List<Line> linePointee = new ArrayList<>();
List<Line> linePointeeAutre = new ArrayList<>();
for (SQLRowValues ecrVals : list) {
final String codeP = ecrVals.getString("POINTEE");
if (codeP == null || codeP.trim().length() == 0) {
lineNonPointee.add(new Line(ecrVals));
lineSoldeNonPointe.cumulRow(ecrVals);
lineSoldeAdjust.cumulRow(ecrVals);
} else {
if (numeroReleve == null || numeroReleve.trim().length() == 0 || numeroReleve.trim().equals(codeP)) {
linePointee.add(new Line(ecrVals));
lineSoldePointe.cumulRow(ecrVals);
lineSoldeAdjust.cumulRow(ecrVals);
} else {
linePointeeAutre.add(new Line(ecrVals));
lineSoldeAutrePointe.cumulRow(ecrVals);
}
}
 
}
 
Collections.sort(lineNonPointee, new Comparator<Line>() {
@Override
public int compare(Line o1, Line o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
 
if (this.detail) {
for (Line line : linePointee) {
tableauVals.add(line.getMapValues());
style.put(tableauVals.size() - 1, "Normal");
}
}
 
tableauVals.add(lineSoldePointe.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
 
for (Line line : lineNonPointee) {
tableauVals.add(line.getMapValues());
style.put(tableauVals.size() - 1, "Normal");
}
if (linePointeeAutre.isEmpty()) {
tableauVals.add(lineSoldeAdjust.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
} else {
 
tableauVals.add(lineSoldeNonPointe.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
 
tableauVals.add(lineSoldeAdjust.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
 
for (Line line : linePointeeAutre) {
 
tableauVals.add(line.getMapValues());
style.put(tableauVals.size() - 1, "Normal");
}
 
tableauVals.add(lineSoldeAutrePointe.getMapValues());
style.put(tableauVals.size() - 1, "Titre 1");
 
}
Map<String, Object> sheetVals = new HashMap<String, Object>();
 
this.mapAllSheetValues.put(0, sheetVals);
 
sheetVals.put("SOCIETE", this.rowSociete.getString("TYPE") + " " + this.rowSociete.getString("NOM"));
sheetVals.put("DATE_EDITION", new Date());
sheetVals.put("TITRE", "Etat de rapprochement du " + dateFormatEcr.format(this.dateDu) + " au " + dateFormatEcr.format(this.dateAu) + " du compte " + this.compteDeb);
 
Date end = new Date();
System.err.println("///////// TAKE " + (end.getTime() - d.getTime()) + " millisecondes TO CREATE MAP");
}
 
private class Line {
private String journal, codeJournal, piece, nom;
private Date date;
private long debit, credit;
 
public Line(SQLRowAccessor rowEcr) {
this.journal = rowEcr.getString("JOURNAL_NOM");
this.codeJournal = rowEcr.getString("JOURNAL_CODE");
this.piece = rowEcr.getString("NOM_PIECE");
this.date = rowEcr.getDate("DATE").getTime();
this.debit = rowEcr.getLong("DEBIT");
this.credit = rowEcr.getLong("CREDIT");
this.nom = rowEcr.getString("NOM");
}
 
public Line(String nom) {
this.nom = nom;
this.debit = 0;
this.credit = 0;
}
 
public Date getDate() {
return date;
}
 
public void cumulRow(SQLRowAccessor rowEcr) {
this.debit += rowEcr.getLong("DEBIT");
this.credit += rowEcr.getLong("CREDIT");
}
 
public Map<String, Object> getMapValues() {
Map<String, Object> map = new HashMap<>();
map.put("CODE_JOURNAL", this.codeJournal);
map.put("NOM_JOURNAL", this.journal);
map.put("PIECE", this.piece);
map.put("DATE", this.date);
map.put("NOM", this.nom);
map.put("DEBIT", new BigDecimal(this.debit).movePointLeft(2));
map.put("CREDIT", new BigDecimal(this.credit).movePointLeft(2));
map.put("SOLDE", new BigDecimal(this.debit - credit).movePointLeft(2));
 
return map;
}
}
 
@Override
public String getTemplateId() {
return TEMPLATE_ID;
}
 
public int getSize() {
return size;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/GrandLivreSheetXML.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
306,9 → 306,9
idCpt = idCptFourn;
}
ooLine.put("DATE", numCpt);
ooLine.put("JOURNAL", nomCpt);
ooLine.put("JOURNAL", "");
ooLine.put("MOUVEMENT", "");
ooLine.put("LIBELLE", "");
ooLine.put("LIBELLE", nomCpt);
ooLine.put("DEBIT", "");
ooLine.put("CREDIT", "");
ooLine.put("SOLDE", "");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/report/RepartitionAnalytiqueSheetXML.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
17,12 → 17,9
import org.openconcerto.erp.generationDoc.AbstractListeSheetXml;
import org.openconcerto.erp.preferences.PrinterNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.FieldRef;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.TableRef;
import org.openconcerto.sql.model.Where;
import org.openconcerto.utils.GestionDevise;
 
92,9 → 89,10
protected void createListeValues() {
 
SQLSelect sel = new SQLSelect();
 
sel.addSelect(tablePoste.getField("NOM"));
sel.addSelect(tableAssoc.getField("MONTANT"), "SUM");
sel.addSelect(tableEcriture.getField("COMPTE_NUMERO"));
sel.addSelect(tableEcriture.getField("COMPTE_NOM"));
 
Where w = (new Where(tableEcriture.getField("DATE"), RepartitionAnalytiqueSheetXML.this.dateDu, RepartitionAnalytiqueSheetXML.this.dateAu));
 
104,42 → 102,20
w = w.and(new Where(tableAssoc.getField("ID_ECRITURE"), "=", tableEcriture.getKey()));
 
sel.setWhere(w);
sel.addRawSelect("subString(\"" + sel.getAlias(tableEcriture).getAlias() + "\".\"COMPTE_NUMERO\",1,1)", "classe");
// sel.addRawSelect("subString(\"" + sel.getAlias(tableEcriture).getAlias() +
// "\".\"COMPTE_NUMERO\",1,1)", "classe");
 
sel.addRawOrder("classe");
// sel.addRawOrder("classe");
sel.addFieldOrder(tablePoste.getField("NOM"));
sel.addFieldOrder(tableEcriture.getField("COMPTE_NUMERO"));
// sel.addFieldOrder(sel.getJoinFromField(tableAssoc.getField("ID_ECRITURE")).getJoinedTable().getField("COMPTE_NUMERO"));
// sel.addGroupBy(sel.getJoinFromField(tableAssoc.getField("ID_ECRITURE")).getJoinedTable().getField("COMPTE_NUMERO"));
// sel.addGroupBy(sel.getJoinFromField(tableAssoc.getField("ID_ECRITURE")).getJoinedTable().getField("COMPTE_NOM"));
// sel.addGroupBy(sel.getJoinFromField(tableAssoc.getField("ID_POSTE_ANALYTIQUE")).getJoinedTable().getField("CODE"));
sel.addGroupBy(tablePoste.getField("NOM"));
sel.addGroupBy(new FieldRef() {
sel.addGroupBy(tableEcriture.getField("COMPTE_NUMERO"));
sel.addGroupBy(tableEcriture.getField("COMPTE_NOM"));
 
@Override
public TableRef getTableRef() {
 
return tableEcriture;
}
 
@Override
public String getFieldRef() {
 
return "classe";
}
 
@Override
public SQLField getField() {
 
return tableEcriture.getField("COMPTE_NUMERO");
}
 
@Override
public String getAlias() {
 
return tableEcriture.getField("COMPTE_NUMERO").getName();
}
});
 
List<Object[]> list = tableAssoc.getDBSystemRoot().getDataSource().executeA(sel.asString());
size = list.size();
 
202,7 → 178,8
 
// String codePoste = line[0].toString();
String nomPoste = line[0].toString();
String classe = line[2].toString();
String compteNumero = line[2].toString();
String compteNom = line[3].toString();
 
Map<String, Object> ooLine = new HashMap<String, Object>();
 
209,37 → 186,37
// Titre
if (setTitle) {
if (!setLine) {
tableauVals.add(ooLine);
style.put(tableauVals.size() - 1, "Titre 1");
 
ooLine.put("CLASSE", "");
ooLine.put("POSTE_CODE", "");
ooLine.put("POSTE_NOM", "");
ooLine.put("POSTE_NOM", nomPoste);
ooLine.put("DEBIT", "");
ooLine.put("CREDIT", "");
ooLine.put("SOLDE", "");
setTitle = false;
setLine = true;
 
if (rowFirstEcr == null) {
rowFirstEcr = line;
numClasseFirst = line[2].toString();
numClasseFirst = nomPoste;
}
 
} else {
tableauVals.add(ooLine);
style.put(tableauVals.size() - 1, "Normal");
setLine = false;
}
} else {
 
// si on change de classe alors on applique le style Titre 1
if (rowFirstEcr != null && !classe.equals(numClasseFirst)) {
tableauVals.add(ooLine);
// si on change de poste
if (rowFirstEcr != null && !nomPoste.equals(numClasseFirst)) {
rowFirstEcr = line;
numClasseFirst = line[2].toString();
ooLine.put("CLASSE", classe);
// ooLine.put("POSTE_CODE", codePoste);
ooLine.put("POSTE_NOM", nomPoste);
ooLine.put("POSTE_CODE", "Total");
ooLine.put("POSTE_NOM", numClasseFirst);
numClasseFirst = nomPoste;
 
tableauVals.add(ooLine);
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sousTotalCredit = 0;
246,13 → 223,11
sousTotalDebit = 0;
setTitle = true;
} else {
long l = ((BigDecimal) line[1]).movePointRight(2).longValue();
long l = ((BigDecimal) line[1]).longValue();
long cred = (l >= 0 ? 0 : -l);
long deb = (l <= 0 ? 0 : l);
 
ooLine.put("POSTE_NOM", nomPoste);
// ooLine.put("POSTE_CODE", codePoste);
 
ooLine.put("POSTE_CODE", compteNumero);
ooLine.put("POSTE_NOM", compteNom);
totalCredit += cred;
totalDebit += deb;
 
263,7 → 238,7
ooLine.put("DEBIT", (deb == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(deb, false)));
ooLine.put("CREDIT", (cred == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(cred, false)));
ooLine.put("SOLDE", (solde == 0) ? doubleZero : Double.valueOf(GestionDevise.currencyToString(solde, false)));
 
tableauVals.add(ooLine);
style.put(tableauVals.size() - 1, "Normal");
i++;
}
278,6 → 253,8
if (size > 0) {
Map<String, Object> ooLine = new HashMap<String, Object>();
tableauVals.add(ooLine);
ooLine.put("POSTE_CODE", "Total");
ooLine.put("POSTE_NOM", numClasseFirst);
makeSousTotal(ooLine, style, tableauVals.size() - 1, sousTotalDebit, sousTotalCredit);
 
sheetVals.put("TOTAL_DEBIT", (totalDebit == 0) ? 0 : new Double(GestionDevise.currencyToString(totalDebit, false)));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/ListeDesEcrituresAction.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
17,11 → 17,8
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.erp.core.common.ui.IListTotalPanel.Type;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.finance.accounting.ui.AssociationAnalytiquePanel;
import org.openconcerto.erp.core.finance.accounting.ui.SuppressionEcrituresPanel;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.Configuration;
28,7 → 25,6
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
38,24 → 34,24
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.Tuple2;
 
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JLabel;
import javax.swing.JTable;
 
public class ListeDesEcrituresAction extends CreateFrameAbstractAction {
121,6 → 117,7
final IListFilterDatePanel comp = new IListFilterDatePanel(frame.getPanel().getListe(), element.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
comp.setDateDu((Date) rowExercice.getObject("DATE_DEB"));
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
frame.getPanel().add(comp, c);
 
List<SQLField> l = new ArrayList<SQLField>();
127,8 → 124,21
l.add(element.getTable().getField("DEBIT"));
l.add(element.getTable().getField("CREDIT"));
 
IListTotalPanel comp2 = new IListTotalPanel(frame.getPanel().getListe(), l);
final List<Tuple2<? extends SQLTableModelColumn, Type>> initListe = IListTotalPanel.initListe(frame.getPanel().getListe(),
Arrays.asList(element.getTable().getField("DEBIT"), element.getTable().getField("CREDIT")));
IListTotalPanel compSel = new IListTotalPanel(frame.getPanel().getListe(), initListe, null, null, "Sélection", true);
c.gridy++;
c.gridx = 0;
c.gridwidth = 1;
c.weightx = 1;
frame.getPanel().add(new JLabel(), c);
c.weightx = 0;
c.gridx++;
compSel.addSubtract(initListe.get(0).get0(), initListe.get(1).get0());
frame.getPanel().add(compSel, c);
 
IListTotalPanel comp2 = new IListTotalPanel(frame.getPanel().getListe(), l, "Total");
c.gridx++;
c.weightx = 0;
frame.getPanel().add(comp2, c);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/action/RelevesBancairesAction.java
New file
0,0 → 1,42
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.action;
 
import org.openconcerto.erp.core.finance.accounting.component.ReleveBancaireFrame;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.ui.FrameUtil;
 
import java.awt.Dimension;
import java.awt.event.ActionEvent;
 
import javax.swing.AbstractAction;
import javax.swing.Action;
 
public class RelevesBancairesAction extends AbstractAction {
SQLElementDirectory dir;
 
public RelevesBancairesAction(SQLElementDirectory dir) {
this.dir = dir;
this.putValue(Action.NAME, "Relevés bancaires");
}
 
@Override
public void actionPerformed(ActionEvent e) {
ReleveBancaireFrame f = new ReleveBancaireFrame(dir);
f.setPreferredSize(new Dimension(700, 500));
f.setSize(new Dimension(700, 500));
FrameUtil.show(f);
f.setLocationRelativeTo(null);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ListeGestCommEltPanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
13,10 → 13,13
package org.openconcerto.erp.core.finance.accounting.ui;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.sales.account.VenteFactureSituationSQLComponent;
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeSQLComponent;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
29,6 → 32,7
 
import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.List;
 
import javax.swing.JButton;
 
129,6 → 133,13
final SQLRowAccessor mvt = row.getForeign("ID_MOUVEMENT");
if (source == this.buttonEffacer) {
 
if (ComptaPropsConfiguration.getInstanceCompta().isExperimental()) {
final List<SQLRowAccessor> selectedRowAccessors = this.getListe().getSelectedRowAccessors();
for (SQLRowAccessor sqlRowAccessor : selectedRowAccessors) {
EcritureSQLElement elt = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
elt.archiveMouvement(sqlRowAccessor.getForeignID("ID_MOUVEMENT"));
}
} else {
if (mvt != null && !mvt.isUndefined()) {
PanelFrame frame = new PanelFrame(new SuppressionEcrituresPanel(mvt.getID()), "Suppression");
frame.pack();
138,6 → 149,7
} else {
super.handleAction(source, evt);
}
}
} else {
if (source == this.buttonModifier) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieKmItemTable.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
40,6 → 40,7
import org.openconcerto.sql.view.list.ValidStateChecker;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JComponentUtils;
import org.openconcerto.ui.table.TimestampTableCellEditor;
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.GridBagConstraints;
48,7 → 49,9
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
98,6 → 101,22
final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE"));
list.add(tableElementNomEcriture);
 
if (elt.getTable().contains("DATE_ECHEANCE")) {
final SQLTableElement tableElementDate = new SQLTableElement(tableElement.getField("DATE_ECHEANCE"), Date.class);
tableElementDate.setEditor(new TimestampTableCellEditor(false) {
@Override
public Object getCellEditorValue() {
 
Object o = super.getCellEditorValue();
Date d = null;
if (o != null) {
d = new Date(((Timestamp) o).getTime());
}
return d;
}
});
list.add(tableElementDate);
}
boolean kd = false;
this.debit = new SQLTableElement(tableElement.getField("DEBIT"), Long.class, this.deviseCellEditor);
list.add(this.debit);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImportEcriturePanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
67,7 → 67,7
 
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)");
JLabel label3 = new JLabel(" - Date dd/MM/yyyy");
JLabel label4 = new JLabel(" - Journal");
JLabel label5 = new JLabel(" - N° de compte");
JLabel label6 = new JLabel(" - Nom de la pièce");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/SaisieJournalItemTable.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
18,6 → 18,7
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.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
38,6 → 39,7
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JComponentUtils;
import org.openconcerto.ui.RangedIntegerTableCellEditor;
import org.openconcerto.ui.table.TimestampTableCellEditor;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
57,6 → 59,7
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
138,7 → 141,22
 
final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE"));
list.add(tableElementNomEcriture);
if (elt.getTable().contains("DATE_ECHEANCE")) {
final SQLTableElement tableElementDate = new SQLTableElement(tableElement.getField("DATE_ECHEANCE"), Date.class);
tableElementDate.setEditor(new TimestampTableCellEditor(false) {
@Override
public Object getCellEditorValue() {
 
Object o = super.getCellEditorValue();
Date d = null;
if (o != null) {
d = new Date(((Timestamp) o).getTime());
}
return d;
}
});
list.add(tableElementDate);
}
//
DeviseCellEditor deviseDebitEditor = new DeviseCellEditor();
DeviseCellEditor deviseCreditEditor = new DeviseCellEditor();
527,7 → 545,8
final String lib = pieceLabel == null || pieceLabel.trim().length() == 0 ? t.get1() : pieceLabel;
 
// Create saisieKM
SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
final SQLTable kmTable = SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM");
SQLRowValues rowVAlsKM = new SQLRowValues(kmTable);
 
rowVAlsKM.put("DATE", d);
rowVAlsKM.put("NOM", lib);
542,7 → 561,7
int idMvt = gen.genereMouvement();
 
// maj de l'id du mouvement correspondant
SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
SQLRowValues rowValsKMMvt = new SQLRowValues(kmTable);
rowValsKMMvt.put("ID_MOUVEMENT", Integer.valueOf(idMvt));
rowValsKMMvt.update(id);
 
550,6 → 569,24
defaultRowVals.put("NOM_ECRITURE", "");
this.table.getRowValuesTableModel().addNewRow();
pieceText.setText("");
 
boolean showPropoLettrage = Boolean.valueOf(DefaultNXProps.getInstance().getProperty(ComptabiliteWorkflowPreferencePanel.LETTRAGE_PROPO_KM));
if (showPropoLettrage) {
if (id > SQLRow.NONEXISTANT_ID) {
final SQLRow rowKM = kmTable.getRow(id);
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
PropoLettrage lettragePropo = new PropoLettrage(
SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getDirectory().getElement(EcritureSQLElement.class));
lettragePropo.transfert(rowKM);
}
});
 
}
}
 
} catch (SQLException e) {
e.printStackTrace();
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImpressionEtatRapprochementPanel.java
New file
0,0 → 1,193
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.DeviseField;
import org.openconcerto.erp.core.finance.accounting.report.RapprochementBancaireSheetXML;
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.sqlobject.SQLRequestComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.util.Date;
 
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
public class ImpressionEtatRapprochementPanel extends JPanel {
 
private final JDate dateEnd, dateStart;
private JButton valid;
private JButton annul;
 
private JTextField numeroReleve;
private SQLRequestComboBox compteDeb;
 
public ImpressionEtatRapprochementPanel(SQLElement eltCpt, int idCptSel) {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
SQLRow rowExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON").getRow(rowSociete.getInt("ID_EXERCICE_COMMON"));
 
this.dateEnd = new JDate();
this.dateStart = new JDate();
 
// Période
this.add(new JLabel("Ecritures du"), c);
c.gridx++;
c.weightx = 1;
this.add(this.dateStart, c);
c.gridx++;
this.add(new JLabel("au"), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 1;
this.add(this.dateEnd, c);
// Chargement des valeurs par défaut
String valueDateEnd = DefaultNXProps.getInstance().getStringProperty("EtatRapproDateEnd");
if (valueDateEnd.trim().length() > 0) {
Long l = new Long(valueDateEnd);
this.dateEnd.setValue(new Date(l.longValue()));
} else {
this.dateEnd.setValue((Date) rowExercice.getObject("DATE_FIN"));
}
 
// relevé
c.gridy++;
c.gridx = 0;
c.gridwidth = 1;
this.add(new JLabel("Filtré sur le relevé"), c);
c.gridx++;
c.weightx = 1;
this.numeroReleve = new JTextField(15);
this.add(this.numeroReleve, c);
 
JLabel labelSolde = new JLabel("Solde bancaire de départ");
c.gridx++;
this.add(labelSolde, c);
c.gridx++;
final DeviseField fieldSolde = new DeviseField(20);
c.weightx = 1;
this.add(fieldSolde, c);
 
// Compte
this.compteDeb = new SQLRequestComboBox(false);
this.compteDeb.uiInit(eltCpt.getComboRequest(true));
 
c.gridy++;
c.gridx = 0;
c.gridwidth = 1;
this.add(new JLabel("Du compte "), c);
c.gridx++;
c.weightx = 1;
this.add(this.compteDeb, c);
 
c.gridx += 2;
final JCheckBox box = new JCheckBox("Ne pas afficher le détail des lignes pointées");
this.add(box, c);
 
this.valid = new JButton("Valider");
this.annul = new JButton("Fermer");
 
c.gridy++;
c.gridx = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
this.add(this.valid, c);
c.gridx += 2;
this.add(this.annul, c);
checkValidity();
this.valid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valid.setEnabled(false);
final BigDecimal soldeDepart = fieldSolde.getValue() == null ? null : new BigDecimal(fieldSolde.getValue()).movePointLeft(2);
RapprochementBancaireSheetXML sheet = new RapprochementBancaireSheetXML(dateStart.getDate(), dateEnd.getDate(), eltCpt.getTable().getRow(compteDeb.getWantedID()).getString("NUMERO"),
!box.isSelected(), numeroReleve.getText(), soldeDepart);
try {
sheet.createDocument();
sheet.openDocument(false);
} catch (Exception e1) {
ExceptionHandler.handle("Erreur lors de la création du document", e1);
}
}
});
this.annul.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JFrame) SwingUtilities.getRoot(ImpressionEtatRapprochementPanel.this)).dispose();
}
});
 
this.dateEnd.addValueListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
checkValidity();
storeValue();
}
});
this.compteDeb.addModelListener("wantedID", new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
checkValidity();
}
});
if (idCptSel != SQLRow.NONEXISTANT_ID) {
this.compteDeb.setValue(idCptSel);
}
}
 
private void checkValidity() {
 
if (this.compteDeb.getWantedID() != SQLRow.NONEXISTANT_ID) {
Date endDate = this.dateEnd.getDate();
 
// System.err.println("Check validity between ");
if (endDate == null) {
this.valid.setEnabled(false);
} else {
this.valid.setEnabled(true);
}
} else {
this.valid.setEnabled(false);
}
}
 
private void storeValue() {
 
// Set date Fin
Date dFin = this.dateEnd.getDate();
if (dFin != null) {
DefaultNXProps.getInstance().setProperty("EtatRapproDateEnd", String.valueOf(dFin.getTime()));
}
 
DefaultNXProps.getInstance().store();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ClotureMensuellePayePanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
186,7 → 186,11
FichePayeSQLElement.clotureMensuelle(selMois.getSelectedId(), Integer.parseInt(textAnnee.getText()), rowFiche.getInt("ID_SALARIE"));
}
if (boxCompta.isSelected()) {
new GenerationMvtFichePaye(idS, rowMois.getString("NOM"), textAnnee.getText());
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, Integer.valueOf(textAnnee.getText()));
c.set(Calendar.MONTH, rowMois.getID() - 2);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
new GenerationMvtFichePaye(idS, rowMois.getString("NOM"), textAnnee.getText(), c.getTime());
}
}
System.err.println("ClotureMensuellePayePanel.ClotureMensuellePayePanel().new ActionListener() {...}.actionPerformed()");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteResultatBilanPanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
23,6 → 23,7
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
 
import java.awt.Desktop;
61,22 → 62,14
private JButton buttonRemplirResultat = new JButton("Remplir la déclaration");
 
public CompteResultatBilanPanel() {
 
super();
this.setLayout(new GridBagLayout());
// this.setOpaque(false);
TitleLabel labelBilan = new TitleLabel("Compte de Bilan");
TitleLabel labelResultat = new TitleLabel("Compte de Résultat");
labelBilan.setOpaque(true);
// labelBilan.setBackground(new Color(255, 255, 255));
labelResultat.setOpaque(true);
// labelResultat.setBackground(new Color(255, 255, 255));
 
final GridBagConstraints c = new DefaultGridBagConstraints();
 
this.textFieldResultat.setEditable(false);
this.textFieldBilan.setEditable(false);
 
// Période
JPanel panelPeriode = new JPanel();
panelPeriode.add(new JLabel("Période du "));
108,18 → 101,15
c.gridx++;
 
// Bouton remplir bilan
 
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
this.add(this.buttonRemplirBilan, c);
this.buttonRemplirBilan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
 
Map2033A map2033A = new Map2033A(progressBarBilan, CompteResultatBilanPanel.this.dateDebutPeriode.getDate(), CompteResultatBilanPanel.this.dateFinPeriode.getDate());
map2033A.generateMap2033A();
}
});
 
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
129,12 → 119,11
c.gridy++;
c.gridx = 0;
// Bouton ouvrir dossier bilan
JButton buttonOpenLocationBilan = new JButton(new ImageIcon(ElementComboBox.class.getResource("loupe.png")));
final JButton buttonOpenLocationBilan = new JButton(new ImageIcon(ElementComboBox.class.getResource("loupe.png")));
setIconJButton(buttonOpenLocationBilan);
buttonOpenLocationBilan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
openFolder("Location2033APDF");
openFolder(CompteResultatBilanPanel.this.textFieldBilan.getText());
}
});
 
198,9 → 187,7
 
SwingUtilities.invokeLater(new Runnable() {
public void run() {
 
// progressBarResultat.setValue(100);
Map2033B map2033B = new Map2033B(progressBarResultat, CompteResultatBilanPanel.this.dateDebutPeriode.getDate(), CompteResultatBilanPanel.this.dateFinPeriode.getDate());
final Map2033B map2033B = new Map2033B(progressBarResultat, CompteResultatBilanPanel.this.dateDebutPeriode.getDate(), CompteResultatBilanPanel.this.dateFinPeriode.getDate());
map2033B.generateMap();
}
});
218,7 → 205,7
setIconJButton(buttonOpenLocationResultat);
buttonOpenLocationResultat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFolder("Location2033BPDF");
openFolder(CompteResultatBilanPanel.this.textFieldResultat.getText());
}
});
 
267,7 → 254,6
this.dateDebutPeriode.addValueListener(new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
isDateValid();
}
});
274,7 → 260,6
this.dateFinPeriode.addValueListener(new PropertyChangeListener() {
 
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
isDateValid();
}
});
283,17 → 268,12
 
private void setIconJButton(JButton res) {
res.setMargin(new Insets(1, 1, 1, 1));
// res.setModel(new ContinuousButtonModel(300));
// res.setBorder(null);
// res.setOpaque(false);
// res.setFocusPainted(true);
// res.setContentAreaFilled(false);
}
 
private void setTextLocation() {
 
File f2033APDF = new File(TemplateNXProps.getInstance().getStringProperty("Location2033APDF") + "\\" + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
File f2033BPDF = new File(TemplateNXProps.getInstance().getStringProperty("Location2033BPDF") + "\\" + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
File f2033APDF = new File(TemplateNXProps.getInstance().getStringProperty("Location2033APDF") + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
File f2033BPDF = new File(TemplateNXProps.getInstance().getStringProperty("Location2033BPDF") + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
 
try {
this.textFieldBilan.setText(f2033APDF.getCanonicalPath());
303,10 → 283,8
}
}
 
private void openFolder(String locationProperty) {
String file = TemplateNXProps.getInstance().getStringProperty(locationProperty) + File.separator + String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
System.err.println(file);
File f = new File(file);
private void openFolder(String location) {
File f = new File(location);
f.mkdirs();
if (Desktop.isDesktopSupported()) {
Desktop d = Desktop.getDesktop();
315,7 → 293,6
try {
d.browse(f.getCanonicalFile().toURI());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
331,7 → 308,6
 
@Override
protected Tuple2<Date, Date> doInBackground() throws Exception {
 
SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
SQLRow rowExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON").getRow(rowSociete.getInt("ID_EXERCICE_COMMON"));
Date dateFin = (Date) rowExercice.getObject("DATE_FIN");
341,19 → 317,13
 
@Override
protected void done() {
 
Tuple2<Date, Date> t;
try {
t = get();
 
CompteResultatBilanPanel.this.dateDebutPeriode.setValue(t.get0());
CompteResultatBilanPanel.this.dateFinPeriode.setValue(t.get1());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException | ExecutionException e) {
ExceptionHandler.handle("erreur", e);
}
}
}.execute();
360,7 → 330,6
}
 
private void isDateValid() {
System.err.println("Check date");
Date dDeb = this.dateDebutPeriode.getDate();
Date dEnd = this.dateFinPeriode.getDate();
if (dDeb != null && dEnd != null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ImpressionGrandLivrePanel.java
256,7 → 256,9
this.checkValidity();
this.validPDF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
GrandLivreSheetXML sheet = new GrandLivreSheetXML(dateDeb.getDate(), dateEnd.getDate(), compteDeb.getText().trim(), compteEnd.getText().trim(), mode, boxCumulsAnts.isSelected(),
!boxCompteSolde.isSelected(), boxCentralClient.isSelected(), boxCentralFourn.isSelected(), comboJrnl.getSelectedId());
JFileChooser chooser = new JFileChooser(sheet.getDocumentOutputDirectory());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
chooser.setSelectedFile(new File("Grand livre " + df.format(new Date()) + ".pdf"));
int r = chooser.showSaveDialog(ImpressionGrandLivrePanel.this);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/PointagePanel.java
16,6 → 16,7
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.erp.core.common.ui.DeviseNiceTableCellRenderer;
import org.openconcerto.erp.core.common.ui.PanelFrame;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
36,6 → 37,7
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FontUtils;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.warning.JLabelWarning;
109,6 → 111,10
final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
this.modeSelect = allEcriture;
 
this.fieldEcart.setAuthorizedNegative(true);
this.fieldSoldeD.setAuthorizedNegative(true);
this.fieldSoldeA.setAuthorizedNegative(true);
 
// Selection du compte à pointer
// TODO Ajouter selection d'un Journal
 
117,7 → 123,7
this.add(labelPointageCompte, c);
 
this.selCompte = new ISQLCompteSelector();
SQLElement eltCpt = directory.getElement("COMPTE_PCE");
final SQLElement eltCpt = directory.getElement("COMPTE_PCE");
final ComboSQLRequest createComboRequest = eltCpt.createComboRequest();
String function = "REGEXP";
if (Configuration.getInstance().getBase().getServer().getSQLSystem() == SQLSystem.POSTGRESQL) {
322,6 → 328,18
c.gridwidth = 2;
this.add(panelPeriode, c);
 
c.gridx = 0;
c.gridy++;
JButton buttonPrint = new JButton(new AbstractAction("Imprimer un état") {
 
@Override
public void actionPerformed(ActionEvent e) {
PanelFrame frame = new PanelFrame(new ImpressionEtatRapprochementPanel(eltCpt, selCompte.getWantedID()), "Impression rapprochement bancaire");
FrameUtil.showPacked(frame);
}
});
this.add(buttonPrint, c);
 
// Liste des ecritures
final EcritureSQLElement ecritureElem = directory.getElement(EcritureSQLElement.class);
this.ecriturePanel = new ListPanelEcritures(ecritureElem, new IListe(ecritureElem.createPointageTableSource()));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/PropoLettrage.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
70,7 → 70,7
Set<Tuple2<String, String>> cpts = new HashSet();
for (SQLRow sqlRow : rowItems) {
final String cptNumero = sqlRow.getString("NUMERO");
if (cptNumero.startsWith("40") || cptNumero.startsWith("41")) {
if (cptNumero.startsWith("40") || cptNumero.startsWith("41") || cptNumero.startsWith("42") || cptNumero.startsWith("43") || cptNumero.startsWith("44") || cptNumero.startsWith("45")) {
cpts.add(Tuple2.create(cptNumero, sqlRow.getString("NOM")));
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/CompteGestCommPreferencePanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
43,7 → 43,8
public class CompteGestCommPreferencePanel extends DefaultPreferencePanel {
 
private ISQLCompteSelector selCompteCBAttente, selCompteTVAIntraComm, selCompteFourn, selCompteAchat, selCompteValeurEncaissement, selCompteAvanceClient, selCompteClient, selCompteVenteProduits,
selCompteVenteService, selCompteTVACol, selCompteTVADed, selCompteTVAImmo, selCompteAchatIntra, selCompteFactor, selComptePortSoumis, selComptePortNonSoumis;
selCompteVenteService, selCompteTVACol, selCompteTVADed, selCompteTVAImmo, selCompteAchatIntra, selCompteFactor, selComptePortSoumis, selComptePortNonSoumis, selComptePortNonSoumisAchat,
selComptePortSoumisAchat;
private ElementComboBox selJrnlFactor, selJrnlValEnc, selJrnlCB;
private final static SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
114,6 → 115,40
this.selCompteAchatIntra.init();
this.add(this.selCompteAchatIntra, c);
 
/**
* Frais de port sur achat
*/
 
c.gridy++;
c.gridx = 0;
TitledSeparator sepPortAchat = new TitledSeparator("Ports sur achat");
c.insets = separatorInsets;
c.gridwidth = GridBagConstraints.REMAINDER;
this.add(sepPortAchat, c);
c.insets = normalInsets;
c.gridwidth = 1;
 
// Compte TVA Collectee
c.gridy++;
c.weightx = 0;
this.add(new JLabel("Compte Port soumis à TVA"), c);
c.weightx = 1;
c.gridx++;
this.selComptePortSoumisAchat = new ISQLCompteSelector();
this.selComptePortSoumisAchat.init();
this.add(this.selComptePortSoumisAchat, c);
 
// Compte TVA Deductible
c.gridy++;
c.weightx = 0;
c.gridx = 0;
this.add(new JLabel("Compte Port non soumis à TVA"), c);
c.weightx = 1;
c.gridx++;
this.selComptePortNonSoumisAchat = new ISQLCompteSelector();
this.selComptePortNonSoumisAchat.init();
this.add(this.selComptePortNonSoumisAchat, c);
 
/*******************************************************************************************
* SAISIE DES VENTES
******************************************************************************************/
264,7 → 299,7
c.gridy++;
c.weightx = 0;
c.gridx = 0;
this.add(new JLabel("Compte Port non soumis à TVA)"), c);
this.add(new JLabel("Compte Port non soumis à TVA"), c);
c.weightx = 1;
c.gridx++;
this.selComptePortNonSoumis = new ISQLCompteSelector();
361,6 → 396,8
this.rowPrefCompteVals.put("ID_COMPTE_PCE_TVA_IMMO", this.selCompteTVAImmo.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_PORT_SOUMIS", this.selComptePortSoumis.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_PORT_NON_SOUMIS", this.selComptePortNonSoumis.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_PORT_SOUMIS_ACHAT", this.selComptePortSoumisAchat.getValue());
this.rowPrefCompteVals.put("ID_COMPTE_PCE_PORT_NON_SOUMIS_ACHAT", this.selComptePortNonSoumisAchat.getValue());
try {
final Object[] pb = this.rowPrefCompteVals.getInvalid();
if (pb != null) {
437,6 → 474,16
value = ComptePCESQLElement.getId(compte);
this.selComptePortNonSoumis.setValue(value);
 
// Port Achat
compte = ComptePCESQLElement.getComptePceDefault("PortAchatSoumisTVA");
value = ComptePCESQLElement.getId(compte);
this.selComptePortSoumisAchat.setValue(value);
 
// Port non soumis achat
compte = ComptePCESQLElement.getComptePceDefault("PortAchatNonSoumisTVA");
value = ComptePCESQLElement.getId(compte);
this.selComptePortNonSoumisAchat.setValue(value);
 
// TVA Coll
compte = ComptePCESQLElement.getComptePceDefault("TVACollectee");
value = ComptePCESQLElement.getId(compte);
510,6 → 557,8
setComboValues(this.selCompteValeurEncaissement, "ID_COMPTE_PCE_VALEUR_ENCAISSEMENT", "ValeurEncaissement");
setComboValues(this.selComptePortSoumis, "ID_COMPTE_PCE_PORT_SOUMIS", "PortVenteSoumisTVA");
setComboValues(this.selComptePortNonSoumis, "ID_COMPTE_PCE_PORT_NON_SOUMIS", "PortVenteNonSoumisTVA");
setComboValues(this.selComptePortSoumisAchat, "ID_COMPTE_PCE_PORT_SOUMIS_ACHAT", "PortAchatSoumisTVA");
setComboValues(this.selComptePortNonSoumisAchat, "ID_COMPTE_PCE_PORT_NON_SOUMIS_ACHAT", "PortAchatNonSoumisTVA");
setComboValues(this.selCompteTVACol, "ID_COMPTE_PCE_TVA_VENTE", "TVACollectee");
setComboValues(this.selCompteTVADed, "ID_COMPTE_PCE_TVA_ACHAT", "TVADeductible");
setComboValues(this.selCompteTVAIntraComm, "ID_COMPTE_PCE_TVA_INTRA", "TVAIntraComm");
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/importer/Transaction.java
New file
0,0 → 1,148
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.importer;
 
import java.math.BigDecimal;
import java.time.LocalDate;
 
public class Transaction {
 
public static final String TYPE_PRELEVEMENT = "directdebit";
public static final String TYPE_AUTRE = "other";
public static final String TYPE_VIREMENT = "transfer";
public static final String TYPE_CARTE = "card";
public static final String TYPE_CHEQUE = "check";
public static final String TYPE_ESPECES = "cash";
 
private String uuid;
private BigDecimal amount;
private String name;
private String memo;
private LocalDate date;
// Date à utiliser
private LocalDate dateValue;
// commentaire de l'utilisateur
private String comment;
 
public Transaction() {
//
}
 
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Transaction))
return false;
return uuid.equals(((Transaction) o).uuid);
 
}
 
@Override
public int hashCode() {
return uuid.hashCode();
}
 
public BigDecimal getAmount() {
return amount;
}
 
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public String getMemo() {
return memo;
}
 
public void setMemo(String memo) {
this.memo = memo;
}
 
public LocalDate getDate() {
return date;
}
 
public void setDate(LocalDate date) {
this.date = date;
}
 
public LocalDate getDateValue() {
return dateValue;
}
 
public void setDateValue(LocalDate date) {
this.dateValue = date;
}
 
public String getUUID() {
return uuid;
}
 
public void setUUID(String uuid) {
this.uuid = uuid;
}
 
public String getComment() {
return comment;
}
 
public void setComment(String comment) {
this.comment = comment;
}
 
@Override
public String toString() {
return this.date + " " + amount + " " + name + "|" + memo + "[" + uuid + "]";
}
 
public String getType() {
String rawname = this.getName().toUpperCase();
String type = TYPE_AUTRE;
if (getAmount().compareTo(BigDecimal.ZERO) < 0) {
// debit
if (rawname.contains("PRLV") || rawname.contains("PRELEV")) {
type = TYPE_PRELEVEMENT;
} else if (rawname.contains("VIREMENT") || rawname.contains("VIR CPTE")) {
type = TYPE_VIREMENT;
} else if (rawname.contains("CARTE")) {
type = TYPE_CARTE;
} else if (rawname.contains("CHEQUE")) {
type = TYPE_CHEQUE;
} else if (rawname.contains("ESPECES")) {
type = TYPE_ESPECES;
}
} else {
if (rawname.contains("VIR")) {
type = TYPE_VIREMENT;
} else if (rawname.contains("REM") && rawname.contains("CARTE")) {
type = TYPE_CARTE;
} else if (rawname.contains("REM") && rawname.contains("CHEQUE")) {
type = TYPE_CHEQUE;
} else if (rawname.contains("ESPECES")) {
type = TYPE_ESPECES;
}
}
return type;
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/importer/ReleveBancaire.java
New file
0,0 → 1,29
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.importer;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
 
public class ReleveBancaire {
String label;
int month;
int year;
BigDecimal debit;
BigDecimal credit;
BigDecimal balanceEndOfMonth;
List<Transaction> trs = new ArrayList<>();
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/importer/OFXParser.java
New file
0,0 → 1,205
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.importer;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
 
public class OFXParser {
 
private List<Transaction> transactions;
private LocalDate startDate;
private LocalDate endDate;
 
private String bankId = "";
private String branchId = "";
private String accId = "";
 
// For parsing
private List<String> openTags;
 
// RIB
public String getBasicBankAccountNumber() {
return bankId + branchId + accId;
}
 
public List<Transaction> getTransactions() {
return this.transactions;
}
 
public LocalDate getStartDate() {
return startDate;
}
 
public LocalDate getEndDate() {
return endDate;
}
 
public List<Month> getCompleteMonth() {
final List<Month> result = new ArrayList<>();
if (this.startDate != null && this.endDate != null) {
LocalDate d = startDate;
while (d.isBefore(this.endDate)) {
final LocalDate d1 = d.with(TemporalAdjusters.firstDayOfMonth());
final LocalDate d2 = d.with(TemporalAdjusters.lastDayOfMonth());
if ((d1.isEqual(this.startDate) || d1.isAfter(this.startDate)) && (d2.isEqual(this.endDate) || d2.isBefore(this.endDate))) {
result.add(d.getMonth());
}
d = d.plusMonths(1);
}
}
 
return result;
}
 
public void parse(File file) throws IOException {
parse(new FileInputStream(file));
}
 
public void parse(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
this.transactions = new ArrayList<>();
this.openTags = new LinkedList<>();
try {
while ((line = reader.readLine()) != null) {
parseLine(line.trim());
}
} finally {
reader.close();
}
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyy");
for (Transaction t : transactions) {
 
// Clean
if (t.getMemo().length() > 10) {
String d = t.getMemo().substring(0, 10);
if (d.startsWith("DU ") && d.endsWith(" ")) {
t.setMemo(t.getMemo().substring(10));
LocalDate date = LocalDate.parse(d.substring(3, 3 + 6), formatter);
t.setDate(date);
}
 
}
// Improve uuid resistance
t.setUUID(t.getUUID() + "-" + t.getDateValue().getYear() + "-" + t.getDateValue().getDayOfYear());
 
}
 
openTags = null;
}
 
private void openTag(String tag) {
openTags.add(tag);
if (tag.equals("STMTTRN")) {
transactions.add(new Transaction());
}
}
 
private void closeTag(String tag) {
// when we close a tag we could implicitly close a bunch of
// tags in between.
// For example consider: <a><b><c><d></a>
// when I encounter "</a>" it tells me that all the tags inside "a" should be considered
// to be closed
while (!lastOpenTag().equals(tag)) {
closeTag(lastOpenTag());
}
// remove the last one
openTags.remove(openTags.size() - 1);
}
 
private void text(String text) {
final String lastOpenTag = lastOpenTag();
final Transaction lastTransaction = lastTransaction();
if (lastOpenTag.equals("BANKID")) {
this.bankId = text;
} else if (lastOpenTag.equals("BRANCHID")) {
this.branchId = text;
} else if (lastOpenTag.equals("ACCTID")) {
this.accId = text;
} else if (lastTransaction != null) {
if (lastOpenTag.equals("TRNAMT")) {
lastTransaction.setAmount(new BigDecimal(text));
} else if (lastOpenTag.equals("NAME")) {
lastTransaction.setName(text);
} else if (lastOpenTag.equals("MEMO")) {
lastTransaction.setMemo(text.trim());
} else if (lastOpenTag.equals("DTPOSTED")) {
String t = text.substring(0, 8);
lastTransaction.setDate(LocalDate.parse(t, DateTimeFormatter.ofPattern("yyyyMMdd")));
lastTransaction.setDateValue(LocalDate.parse(t, DateTimeFormatter.ofPattern("yyyyMMdd")));
} else if (lastOpenTag.equals("FITID")) {
lastTransaction.setUUID(text);
} else if (lastOpenTag.equals("TRNTYPE")) {
// type : CREDIT or DEBIT
}
} else if (lastOpenTag.equals("DTSTART") && openTags.get(openTags.size() - 2).equals("BANKTRANLIST")) {
String t = text.substring(0, 8);
this.startDate = LocalDate.parse(t, DateTimeFormatter.ofPattern("yyyyMMdd"));
 
} else if (lastOpenTag.equals("DTEND") && openTags.get(openTags.size() - 2).equals("DTSTART")) {
String t = text.substring(0, 8);
this.endDate = LocalDate.parse(t, DateTimeFormatter.ofPattern("yyyyMMdd"));
}
}
 
private String lastOpenTag() {
if (openTags.isEmpty()) {
return "";
} else {
return openTags.get(openTags.size() - 1);
}
}
 
private Transaction lastTransaction() {
if (transactions.isEmpty()) {
return null;
} else {
return transactions.get(transactions.size() - 1);
}
}
 
private void parseLine(String line) {
if (line.startsWith("<")) {
int close = line.indexOf('>', 1);
openTag(line.substring(1, close));
int next = line.indexOf('<', close);
if (next == -1) {
next = line.length();
}
String text = line.substring(close + 1, next);
if (!text.isEmpty()) {
text(text);
}
 
} else if (line.startsWith("</")) {
int close = line.indexOf('>', 1);
closeTag(line.substring(2, close));
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/component/ReleveBancaireFrame.java
New file
0,0 → 1,147
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 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.component;
 
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.ReleveBancaireElementSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.ReleveBancaireSQLElement;
import org.openconcerto.erp.core.finance.accounting.importer.OFXParser;
import org.openconcerto.erp.core.finance.accounting.importer.Transaction;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.ui.WrapLayout;
 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
 
public class ReleveBancaireFrame extends JFrame {
public ReleveBancaireFrame(final SQLElementDirectory dir) {
final SQLRequestComboBox banqueSelect = new SQLRequestComboBox();
banqueSelect.uiInit(dir.getElement(BanqueSQLElement.class).getComboRequest());
 
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
JSpinner spinnerYear = new JSpinner(new SpinnerNumberModel(year, year - 20, year + 10, 1));
String[] months = new String[] { "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" };
JComboBox<String> comboMontsh = new JComboBox<>(months);
JPanel tools = new JPanel();
tools.setLayout(new WrapLayout());
tools.add(banqueSelect);
tools.add(comboMontsh);
tools.add(spinnerYear);
JButton importer = new JButton("Import OFX");
tools.add(importer);
 
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(tools, BorderLayout.NORTH);
final ReleveBancaireElementSQLElement element = dir.getElement(ReleveBancaireElementSQLElement.class);
 
ListeAddPanel add = new ListeAddPanel(element);
add.setAddVisible(false);
add.setModifyVisible(false);
add.setDeleteVisible(false);
p.add(add, BorderLayout.CENTER);
this.setContentPane(p);
 
importer.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
try {
OFXParser p = new OFXParser();
p.parse(new FileInputStream(new File("jan-aout2021.ofx")));
System.out.println("OFXTest.main() " + p.getStartDate() + " => " + p.getEndDate() + " : " + p.getCompleteMonth() + " : " + p.getBasicBankAccountNumber());
List<Transaction> transactions1 = p.getTransactions();
Collections.sort(transactions1, new Comparator<Transaction>() {
 
@Override
public int compare(Transaction o1, Transaction o2) {
return o1.getDateValue().compareTo(o2.getDateValue());
}
});
LocalDate min = transactions1.get(0).getDateValue();
LocalDate max = transactions1.get(transactions1.size() - 1).getDateValue();
p.parse(new FileInputStream(new File("avril-decembre-2021.ofx")));
System.out.println("OFXTest.main() " + p.getStartDate() + " => " + p.getEndDate() + " : " + p.getCompleteMonth() + " : " + p.getBasicBankAccountNumber());
List<Transaction> transactions2 = p.getTransactions();
 
for (Transaction t : transactions2) {
boolean alreadIn = !t.getDateValue().isBefore(min) && !t.getDateValue().isAfter(max);
if (alreadIn) {
System.out.println("alreadIn : " + t);
} else {
transactions1.add(t);
}
}
 
System.out.println("OFXTest.main() " + transactions1.size());
System.out.println("OFXTest.main()" + transactions1.get(0).getDate() + " : " + transactions1.get(0).getDateValue());
System.out.println("OFXTest.main()" + transactions1.get(transactions1.size() - 1).getDate() + " : " + transactions1.get(transactions1.size() - 1).getDateValue());
for (Transaction t : transactions1) {
 
System.out.println(t);
 
}
int year = 2021;
final ReleveBancaireSQLElement eReleve = dir.getElement(ReleveBancaireSQLElement.class);
for (int i = 0; i < 12; i++) {
List<Transaction> trs = new ArrayList<>();
BigDecimal total = BigDecimal.ZERO;
for (Transaction t : transactions1) {
if (t.getDateValue().getMonth().getValue() == (i + 1) && t.getDateValue().getYear() == year) {
trs.add(t);
total = total.add(t.getAmount());
}
}
System.out.println(total);
Collections.sort(trs, new Comparator<Transaction>() {
 
@Override
public int compare(Transaction o1, Transaction o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
int idBanque = banqueSelect.getSelectedId();
eReleve.importReleve(idBanque, (i + 1), year, trs);
 
}
 
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
});
 
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmSQLElement.java
27,6 → 27,7
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.AliasedTable;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLRow;
579,6 → 580,9
vals.put("DEBIT", rowKmElement.getObject("DEBIT"));
vals.put("CREDIT", rowKmElement.getObject("CREDIT"));
vals.put("DATE", rowSaisieKm.getObject("DATE"));
if (vals.getTable().contains("DATE_ECHEANCE") && rowSaisieKm.getTable().contains("DATE_ECHEANCE")) {
vals.put("DATE_ECHEANCE", rowSaisieKm.getObject("DATE_ECHEANCE"));
}
SQLRow rowJournal = rowSaisieKm.getForeignRow("ID_JOURNAL");
vals.put("ID_JOURNAL", rowJournal.getID());
vals.put("JOURNAL_NOM", rowJournal.getString("NOM"));
628,6 → 632,15
}
 
}
 
// Mise à jour de l'analytique
UpdateBuilder up = new UpdateBuilder(getTable().getTable("ASSOCIATION_ANALYTIQUE"));
final AliasedTable item = new AliasedTable(getTable().getTable("SAISIE_KM_ELEMENT"), "item");
up.addForwardVirtualJoin(item, "ID_SAISIE_KM_ELEMENT");
up.setFromVirtualJoin("MONTANT", "item", "(item.\"DEBIT\"-item.\"CREDIT\")/100.0*\"POURCENT\"");
up.setWhere(Where.inValues(getTable().getTable("ASSOCIATION_ANALYTIQUE").getField("ID_SAISIE_KM_ELEMENT"), SQLRow.getIDs(myListKmItem)));
getElement().getTable().getDBSystemRoot().getDataSource().executeCol(up.asString());
 
// Suppression des lettrages déséquilibré (ex : si on modifie un
// montant d'une écriture lettrée)
SQLSelect sel = new SQLSelect();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ReleveBancaireSQLElement.java
New file
0,0 → 1,212
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.element;
 
import org.openconcerto.erp.config.Log;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.accounting.importer.Transaction;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLInsert;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public class ReleveBancaireSQLElement extends ComptaSQLConfElement {
public static final String TABLE_NAME = "RELEVE_BANCAIRE";
 
public ReleveBancaireSQLElement(DBRoot root) {
super(root.getTable(TABLE_NAME));
}
 
@Override
protected List<String> getListFields() {
return Arrays.asList("LABEL", "ANNEE", "MOIS", "DEBIT", "CREDIT");
}
 
@Override
protected SQLComponent createComponent() {
return null;
}
 
/**
* Création d'un nouveau relevé
*
* @param month : 1 -12
* @throws IOException
*/
public void importReleve(int idBanque, int month, int year, List<Transaction> transactions) throws SQLException {
if (transactions.isEmpty())
return;
 
LocalDate min = transactions.get(0).getDateValue();
LocalDate max = min;
for (Transaction t : transactions) {
LocalDate d = t.getDateValue();
if (d.isBefore(min)) {
min = d;
} else if (d.isAfter(max)) {
max = d;
}
}
if (min.getYear() != year) {
throw new IllegalArgumentException("a transaction is not in the specified year (" + year + ") but is " + min.getYear());
}
if (max.getYear() != year) {
throw new IllegalArgumentException("a transaction is not in the specified year (" + year + ") but is " + max.getYear());
}
if (min.getMonthValue() != month) {
throw new IllegalArgumentException("a transaction is not in the specified month (" + month + ") but is " + min.getMonthValue());
}
if (max.getMonthValue() != month) {
throw new IllegalArgumentException("a transaction is not in the specified month (" + month + ") but is " + max.getMonthValue());
}
// Récupération des UUID ReleveBancaireElementSQLElement entre min et max
Set<String> existingUUIDs = getElementUUIDs(min, max);
if (!existingUUIDs.isEmpty()) {
throw new IllegalArgumentException("transaction already defined in month: " + month + " year:" + year);
}
 
final List<SQLInsert> releveInserts = new ArrayList<>(transactions.size());
SQLTable tReleve = getTable();
 
BigDecimal debit = BigDecimal.ZERO;
BigDecimal credit = BigDecimal.ZERO;
for (Transaction t : transactions) {
if (t.getAmount().signum() > 0) {
credit = credit.add(t.getAmount());
} else {
debit = debit.add(t.getAmount());
}
}
 
final SQLInsert rinsert = new SQLInsert();
rinsert.add(tReleve.getField("ID_BANQUE"), idBanque);
rinsert.add(tReleve.getField("ANNEE"), year);
rinsert.add(tReleve.getField("MOIS"), month);
rinsert.add(tReleve.getField("DEBIT"), debit);
rinsert.add(tReleve.getField("CREDIT"), credit);
releveInserts.add(rinsert);
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
@Override
public Object handle(SQLDataSource ds) throws SQLException {
// Insertion du relevé
int idReleve = ((Number) ds.executeScalar(rinsert.asString())).intValue();
 
// Insertion des lignes de relevés
SQLTable tReleveElement = getTable().getTable(ReleveBancaireElementSQLElement.TABLE_NAME);
List<SQLInsert> transactionsInserts = new ArrayList<>();
 
for (Transaction t : transactions) {
final SQLInsert insert = new SQLInsert();
insert.add(tReleveElement.getField("ID_RELEVE_BANCAIRE"), idReleve);
insert.add(tReleveElement.getField("UUID"), t.getUUID());
insert.add(tReleveElement.getField("TYPE"), t.getType());
insert.add(tReleveElement.getField("NAME"), t.getName());
insert.add(tReleveElement.getField("DESCRIPTION"), t.getMemo());
insert.add(tReleveElement.getField("COMMENT"), "");
insert.add(tReleveElement.getField("MONTANT"), t.getAmount());
insert.add(tReleveElement.getField("DATE"), toTimeStamp(t.getDate()));
insert.add(tReleveElement.getField("DATE_VALEUR"), toTimeStamp(t.getDateValue()));
transactionsInserts.add(insert);
}
Log.get().info("creating " + transactionsInserts + " lines for " + month + "/" + year);
 
SQLInsert.executeSimilarInserts(getTable().getDBSystemRoot(), transactionsInserts, false);
return null;
}
});
}
 
public Set<ReleveRef> getExistingReleve(int idBanque, LocalDate min, LocalDate max) {
final int minYear = min.getYear();
final int minMonth = min.getMonthValue();
final int maxYear = min.getYear();
final int maxMonth = min.getMonthValue();
final SQLTable tReleve = getTable();
final SQLSelect select = new SQLSelect();
select.addSelect(tReleve.getField("ANNE"));
select.addSelect(tReleve.getField("MOIS"));
Where w = new Where(tReleve.getField("ID_BANQUE"), "=", idBanque);
w = w.and(new Where(tReleve.getField("ANNE"), ">=", minYear)).and(new Where(tReleve.getField("ANNE"), "<=", maxYear));
w = w.and(new Where(tReleve.getField("MOIS"), ">=", minMonth)).and(new Where(tReleve.getField("MOIS"), "<=", maxMonth));
select.setWhere(w);
final List<SQLRow> rows = SQLRowListRSH.execute(select);
final Set<ReleveRef> result = new HashSet<>();
for (final SQLRow r : rows) {
final ReleveRef ref = new ReleveRef();
ref.id = r.getID();
ref.month = r.getInt("MOIS");
ref.year = r.getInt("ANNE");
result.add(ref);
}
return result;
}
 
private Set<String> getElementUUIDs(LocalDate min, LocalDate max) {
final SQLTable tReleveElement = getTable().getTable(ReleveBancaireElementSQLElement.TABLE_NAME);
final SQLSelect select = new SQLSelect();
select.addSelect(tReleveElement.getField("UUID"));
 
select.setWhere(new Where(tReleveElement.getField("DATE_VALEUR"), toTimeStamp(min), toTimeStamp(max)));
final List<SQLRow> rows = SQLRowListRSH.execute(select);
final Set<String> result = new HashSet<>();
for (SQLRow r : rows) {
result.add(r.getString("UUID"));
}
return result;
}
 
private Timestamp toTimeStamp(LocalDate d) {
Timestamp time = Timestamp.valueOf(d.atStartOfDay());
return time;
}
 
class ReleveRef {
Number id;
int year;
int month;
 
@Override
public boolean equals(Object obj) {
ReleveRef r = (ReleveRef) obj;
return r.year == year && r.month == month;
}
 
@Override
public int hashCode() {
return year * 100 + month;
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCESQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
129,6 → 129,8
mapCompteDefault.put("FACTOR", "467000");
mapCompteDefault.put("PORTVENTESOUMISTVA", "708510");
mapCompteDefault.put("PORTVENTENONSOUMISTVA", "708520");
mapCompteDefault.put("PORTACHATSOUMISTVA", "608510");
mapCompteDefault.put("PORTACHATNONSOUMISTVA", "608520");
mapCompteDefault.put("AVANCECLIENTS", "4191");
mapCompteDefault.put("VALEURENCAISSEMENT", "511");
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ReleveBancaireElementSQLElement.java
New file
0,0 → 1,195
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.finance.accounting.element;
 
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.supplychain.order.element.SaisieAchatSQLElement;
import org.openconcerto.erp.core.supplychain.supplier.element.FournisseurSQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieAchat;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.action.SQLRowValuesAction.PredicateRowAction;
 
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.swing.JOptionPane;
 
public class ReleveBancaireElementSQLElement extends ComptaSQLConfElement {
public static final String TABLE_NAME = "RELEVE_BANCAIRE_ELEMENT";
 
public ReleveBancaireElementSQLElement(DBRoot root) {
super(root.getTable(TABLE_NAME));
this.getRowValuesActions().add(getCreateAction());
}
 
@Override
protected List<String> getListFields() {
return Arrays.asList("DATE_VALEUR", "TYPE", "DESCRIPTION", "COMMENT", "MONTANT");
}
 
@Override
protected SQLComponent createComponent() {
return null;
}
 
public PredicateRowAction getCreateAction() {
PredicateRowAction action = new PredicateRowAction(true, true, "purchase.create", (a) -> {
try {
final List<? extends SQLRowAccessor> selectedRowAccessors = a.getSelectedRowAccessors();
create(selectedRowAccessors);
JOptionPane.showMessageDialog(null, selectedRowAccessors.size() + " lignes traitées");
} catch (Exception e) {
e.printStackTrace();
}
});
action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
return action;
}
 
void create(List<? extends SQLRowAccessor> rows) throws Exception {
Map<String, Integer> mapFournisseur = new HashMap<>();
Map<String, Integer> mapCompte = new HashMap<>();
for (SQLRowAccessor r : rows) {
SQLRow row = r.fetchNewRow(false);
String comptePCE = "607";
String toSearch = "";
String nom = "Matériel";
if (row.getBigDecimal("MONTANT").signum() < 0) {
String desc = row.getString("DESCRIPTION").toLowerCase();
 
if (desc.contains("amazon")) {
toSearch = "Amazon";
nom = "Matériel";
} else if (desc.contains("atelier porta")) {
toSearch = "L'atelier du portable";
nom = "Matériel";
} else if (desc.contains("google")) {
toSearch = "Google";
comptePCE = "604";
nom = "Publicité";
} else if (desc.contains("sendinblue")) {
toSearch = "SendInBlue";
comptePCE = "623";
nom = "Mailing";
} else if (desc.contains("united parcel s")) {
toSearch = "UPS";
comptePCE = "624";
nom = "Transport";
}
 
}
Integer idFournisseur = mapFournisseur.get(toSearch);
if (idFournisseur == null) {
idFournisseur = searchFournisseur(toSearch);
mapFournisseur.put(toSearch, idFournisseur);
}
 
Integer idComptePCE = mapCompte.get(comptePCE);
if (idComptePCE == null) {
idComptePCE = searchCompte(comptePCE);
mapCompte.put(toSearch, idComptePCE);
}
 
if (idFournisseur != null && idComptePCE != null) {
final String type = r.getString("TYPE");
 
if (type.equals("card")) {
try {
int idF = idFournisseur;
int idPCE = idComptePCE;
String n = nom;
SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, Exception>() {
@Override
public Object handle(SQLDataSource ds) throws Exception {
SQLRowValues modeReglement = new SQLRowValues(ReleveBancaireElementSQLElement.this.getDirectory().getElement(ModeDeReglementSQLElement.class).getTable());
modeReglement.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.CB);
modeReglement.put("COMPTANT", Boolean.TRUE);
modeReglement.put("DATE_FACTURE", Boolean.TRUE);
SQLRow taxe = TaxeCache.getCache().getFirstTaxe();
SQLRowValues rAchat = new SQLRowValues(ReleveBancaireElementSQLElement.this.getDirectory().getElement(SaisieAchatSQLElement.class).getTable());
int ttcCents = Math.abs(r.getBigDecimal("MONTANT").multiply(new BigDecimal("100")).intValue());
float ht = ttcCents / 1.2f;
int htCents = Math.round(ht);
int tvaCents = (ttcCents - htCents);
rAchat.put("ID_FOURNISSEUR", idF);
rAchat.put("MONTANT_TTC", ttcCents);
rAchat.put("SOURCE", "");
rAchat.put("NOM", n);
rAchat.put("ID_MODE_REGLEMENT", modeReglement);
rAchat.put("ID_COMPTE_PCE", idPCE);
rAchat.put("MONTANT_HT", htCents);
rAchat.put("ID_TAXE", taxe.getID());
rAchat.put("DATE", row.getDate("DATE").getTime());
rAchat.put("MONTANT_TVA", tvaCents);
SQLRow resutl = rAchat.commit();
new GenerationMvtSaisieAchat(resutl).genereMouvement();
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("ReleveBancaireSQLElement " + r.getString("TYPE") + " not supported");
}
}
}
 
}
 
protected Integer searchCompte(String comptePCE) {
SQLSelect select = new SQLSelect();
SQLTable tComptePCE = this.getDirectory().getElement(ComptePCESQLElement.class).getTable();
select.addSelect(tComptePCE.getKey());
select.addSelect(tComptePCE.getField("NUMERO"));
select.setWhere(new Where(tComptePCE.getField("NUMERO"), "=", comptePCE));
final List<SQLRow> rows = SQLRowListRSH.execute(select);
if (rows.isEmpty()) {
return null;
}
return rows.get(0).getID();
}
 
protected Integer searchFournisseur(String name) {
SQLSelect select = new SQLSelect();
SQLTable tFournisseur = this.getDirectory().getElement(FournisseurSQLElement.class).getTable();
select.addSelect(tFournisseur.getKey());
select.addSelect(tFournisseur.getField("NOM"));
select.setWhere(new Where(tFournisseur.getField("NOM"), "=", name));
final List<SQLRow> rows = SQLRowListRSH.execute(select);
if (rows.isEmpty()) {
return null;
}
return rows.get(0).getID();
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/EcritureSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
107,7 → 107,7
 
SQLRowAccessor row = IListe.get(event).getSelectedRow();
 
PanelFrame f = new PanelFrame(new LettragePanel(row.getForeignID("ID_COMPTE_PCE")), "Lettrage manuel par compte");
PanelFrame f = new PanelFrame(new LettragePanel(ComptePCESQLElement.getRow(row.getString("COMPTE_NUMERO"), row.getString("COMPTE_NOM")).getID()), "Lettrage manuel par compte");
f.setVisible(true);
}
}, false);
302,6 → 302,9
listEcriture.add("NOM");
listEcriture.add("DATE_LETTRAGE");
listEcriture.add("DATE");
if (getTable().contains("DATE_ECHEANCE")) {
listEcriture.add("DATE_ECHEANCE");
}
listEcriture.add("DEBIT");
listEcriture.add("CREDIT");
final SQLTableModelSourceOnline res = this.instantiateTableSourceOnline(this.createListRequest(listEcriture));
549,20 → 552,21
SQLTable tableEcriture = base.getTable("ECRITURE");
 
// on recupere l'ensemble des mouvements à valider
SQLSelect selEcriture = new SQLSelect(base);
SQLSelect selEcriture = new SQLSelect();
selEcriture.addSelect(tableEcriture.getField("ID_MOUVEMENT"));
selEcriture.setDistinct(true);
Where w1 = new Where(tableEcriture.getField("DATE"), "<=", d);
Where w2 = new Where(tableEcriture.getField("VALIDE"), "=", Boolean.FALSE);
selEcriture.setWhere(w1.and(w2));
List l = (List) base.getDataSource().execute(selEcriture.asString(), new ArrayListHandler());
List l = base.getDataSource().executeCol(selEcriture.asString());
 
// validation de tous les mouvements
for (int i = 0; i < l.size(); i++) {
Object[] tmp = (Object[]) l.get(i);
System.err.println("Validation du mouvement " + tmp[0]);
validationEcritures(Integer.parseInt(tmp[0].toString()));
}
UpdateBuilder builder = new UpdateBuilder(tableEcriture);
builder.setObject("VALIDE", Boolean.TRUE);
builder.setObject("DATE_VALIDE", new java.sql.Date(new Date().getTime()));
builder.setObject("IDUSER_VALIDE", UserManager.getInstance().getCurrentUserID());
builder.setWhere(Where.inValues(tableEcriture.getField("ID_MOUVEMENT"), l));
tableEcriture.getDBSystemRoot().getDataSource().execute(builder.asString());
 
if (cloture) {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/SEPAMandateSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
21,10 → 21,13
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.sqlobject.itemview.SimpleRowItemView;
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.ui.component.ITextCombo;
import org.openconcerto.ui.component.ImmutableITextComboCache;
import org.openconcerto.ui.valuewrapper.ValidatedValueWrapper;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.checks.ValidState;
 
import java.nio.ByteBuffer;
import java.util.ArrayList;
87,9 → 90,13
return l;
}
 
// Allow to add existing mandates when migrating to OpenConcerto
@Override
public Set<String> getReadOnlyFields() {
return CollectionUtils.createSet("ID_CLIENT", "MandateIdentification");
public Set<String> getInsertOnlyFields() {
return CollectionUtils.createSet("ID_CLIENT", "MandateIdentification"
// use SequenceType and SDDMessageSQLElement.generateXML() will update this field (MAYBE
// allow to change alongside SequenceType)
, "ACTIVE");
}
 
@Override
98,7 → 105,13
@Override
protected void addViews() {
this.addView("ID_CLIENT");
this.addView("MandateIdentification");
final SimpleRowItemView<? extends String> res = this.createSimpleRowItemView("MandateIdentification", String.class, (vw) -> {
return ValidatedValueWrapper.add(vw, (v) -> {
final int invalidIndex = getInvalidIdentifierChar(v);
return ValidState.createCached(invalidIndex < 0, "Le caractère " + (invalidIndex + 1) + " est invalide");
});
});
this.addInitedView(res, REQ);
this.addView("DateOfSignature");
final ITextCombo seqTypeCombo = new ITextCombo(true);
seqTypeCombo.initCache(new ImmutableITextComboCache(SEQ_VALUES));
105,6 → 118,15
this.addView(seqTypeCombo, "SequenceType");
this.addView("ACTIVE");
}
 
@Override
protected SQLRowValues createDefaults() {
 
SQLRowValues rowVals = new SQLRowValues(getTable());
rowVals.put("ACTIVE", Boolean.TRUE);
rowVals.put("SequenceType", SEQ_FIRST);
return rowVals;
}
};
}
 
128,6 → 150,44
return res;
}
 
public static boolean isValidIdentifier(String s) {
return getInvalidIdentifierChar(s) < 0;
}
 
public static int getInvalidIdentifierChar(String s) {
final int length = s.length();
for (int i = 0; i < length; i++) {
if (!isValidIdentifierChar(s.charAt(i)))
return i;
}
return -1;
}
 
public static boolean isValidIdentifierChar(char c) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
return true;
switch (c) {
// don't permit slash because there's additional restrictions :
// - must not start or end with a ‘/’
// - must not contain ‘//’s
// case '/':
 
case '-':
case '?':
case ':':
case '(':
case ')':
case '.':
case ',':
case '\'':
case '+':
case ' ':
return true;
default:
return false;
}
}
 
public String generateMandateIdentification(String label, final char pad, final boolean padStart, final boolean truncateStart) {
final UUID uuid = UUID.randomUUID();
final ByteBuffer byteBuffer = ByteBuffer.allocate(16);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ChequeAEncaisserSQLElement.java
25,6 → 25,7
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
64,6 → 65,13
}
 
@Override
protected void _initListRequest(ListSQLRequest req) {
 
super._initListRequest(req);
req.addToGraphToFetch("REG_COMPTA");
}
 
@Override
public String getDoneFieldName() {
return "ENCAISSE";
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/EncaisserMontantSQLElement.java
36,27 → 36,22
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;
 
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
 
65,43 → 60,12
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")) {
if (!selRow.isForeignEmpty("ID_DEVIS")) {
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);
}
} else if (!selRow.isForeignEmpty("ID_COMMANDE_CLIENT")) {
int idDevis = selRow.getForeignID("ID_COMMANDE_CLIENT");
try {
archive(selRow.getID());
String up = "UPDATE " + getTable().getTable("COMMANDE_CLIENT").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
+ getTable().getSQLName().quote() + " where \"ID_COMMANDE_CLIENT\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID\"=" + 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 void _initListRequest(ListSQLRequest req) {
super._initListRequest(req);
req.addToGraphToFetch("ACOMPTE", "ID_MOUVEMENT");
}
 
@Override
188,40 → 152,36
rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisseItems.getLong("MONTANT_REGLE"));
}
rowVals.update();
final Number nonEmptyForeignIDNumber = rowEch.getNonEmptyForeignIDNumber("ID_SAISIE_VENTE_FACTURE");
if (nonEmptyForeignIDNumber != null) {
final SQLTable foreignTableFact = rowEch.getTable().getForeignTable("ID_SAISIE_VENTE_FACTURE");
UpdateBuilder up = new UpdateBuilder(foreignTableFact);
up.setObject("DATE_REGLEMENT", null);
up.setWhere(new Where(foreignTableFact.getKey(), "=", nonEmptyForeignIDNumber));
getTable().getDBSystemRoot().getDataSource().execute(up.asString());
}
Configuration.getInstance().getDirectory().getElement(rowEncaisseItems.getTable()).archive(rowEncaisseItems);
}
getDirectory().getElement(rowEncaisseItems.getTable()).archive(rowEncaisseItems);
}
if (row.getBoolean("ACOMPTE")) {
if (!row.isForeignEmpty("ID_DEVIS")) {
int idDevis = row.getForeignID("ID_DEVIS");
try {
archive(row.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;
+ " where \"ID_DEVIS\"=" + idDevis + " AND \"ARCHIVE\"=0 AND \"ID\"!=" + row.getID() + ") 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);
}
} else if (!row.isForeignEmpty("ID_COMMANDE_CLIENT")) {
int idDevis = row.getForeignID("ID_COMMANDE_CLIENT");
try {
archive(row.getID());
String up = "UPDATE " + getTable().getTable("COMMANDE_CLIENT").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
+ getTable().getSQLName().quote() + " where \"ID_COMMANDE_CLIENT\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID\"=" + idDevis;
+ getTable().getSQLName().quote() + " where \"ID_COMMANDE_CLIENT\"=" + idDevis + " AND \"ARCHIVE\"=0 AND \"ID\"!=" + row.getID() + ") where \"ID\"=" + idDevis;
getTable().getDBSystemRoot().getDataSource().execute(up);
} catch (SQLException e1) {
e1.printStackTrace();
ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
}
}
}
 
// On supprime les mouvements
SQLSelect sel = new SQLSelect(getTable().getBase());
SQLSelect sel = new SQLSelect();
 
SQLTable tableMvt = getTable().getTable("MOUVEMENT");
EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(tableMvt.getTable("ECRITURE"));
EcritureSQLElement eltEcr = (EcritureSQLElement) getDirectory().getElement(tableMvt.getTable("ECRITURE"));
sel.addSelectStar(tableMvt);
Where w = new Where(tableMvt.getField("SOURCE"), "=", getTable().getName());
w = w.and(new Where(tableMvt.getField("IDSOURCE"), "=", row.getID()));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/ui/ChequeListPanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
16,10 → 16,15
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.ChequeType;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.model.GestionChequesModel;
import org.openconcerto.erp.rights.ComptaUserRight;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.IListe;
103,6 → 108,13
c.gridx++;
banqueSelect.uiInit(element.getDirectory().getElement(BanqueSQLElement.class).getComboRequest());
res.add(banqueSelect, c);
final SQLTable tableTypeReglement = element.getDirectory().getElement(TypeReglementSQLElement.class).getTable();
if (tableTypeReglement.contains("ID_BANQUE")) {
final SQLRow rowCheque = tableTypeReglement.getRow(TypeReglementSQLElement.CHEQUE);
if (!rowCheque.isForeignEmpty("ID_BANQUE")) {
banqueSelect.setValue(rowCheque.getForeignID("ID_BANQUE"));
}
}
} else {
banqueSelect = null;
}
169,6 → 181,28
c.gridwidth = 1;
res.add(this.boutonValide, c);
 
final SQLTable table = getElement().getTable();
if (table.contains("REG_COMPTA")) {
c.gridy += 3;
c.weightx = 0;
c.gridx = 0;
c.anchor = GridBagConstraints.WEST;
final JCheckBox checkRegCompta = new JCheckBox("Voir les régularisations");
this.add(checkRegCompta, c);
 
checkRegCompta.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (checkRegCompta.isSelected()) {
getListe().getRequest().setWhere(new Where(table.getField(((ChequeType) getElement()).getDoneFieldName()), "=", Boolean.FALSE));
} else {
getListe().getRequest().setWhere(
new Where(table.getField(((ChequeType) getElement()).getDoneFieldName()), "=", Boolean.FALSE).and(new Where(table.getField("REG_COMPTA"), "=", Boolean.FALSE)));
}
}
});
}
 
return res;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/ui/ListeDesChequesAEncaisserPanel.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
18,6 → 18,7
import org.openconcerto.erp.rights.ComptaTotalUserRight;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
25,6 → 26,8
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.action.ListEvent;
import org.openconcerto.sql.view.list.action.SQLRowValuesAction;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.GestionDevise;
 
138,9 → 141,35
}
});
}
 
SQLRowValuesAction actionCancel = new SQLRowValuesAction(false, "cancel.regulation.cheque", (ev) -> {
int answer = JOptionPane.showConfirmDialog(null, "Etes vous sûr de vouloir annuler la régularisation ?");
if (answer == JOptionPane.YES_OPTION) {
SQLRowAccessor row = ev.getSelectedRow();
SQLRowValues rowVals = row.createEmptyUpdateRow();
rowVals.put("REG_COMPTA", Boolean.FALSE);
try {
rowVals.commit();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}) {
 
@Override
public boolean enabledFor(ListEvent evt) {
if (evt.getSelectedRows().size() == 1) {
SQLRowAccessor row = evt.getSelectedRow();
return row.getBoolean("REG_COMPTA");
} else {
return true;
}
}
};
getListe().addRowValuesAction(actionCancel);
}
 
@Override
protected String getDepositLabel() {
return "Sélectionner les chéques à déposer, en date du ";
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueCotisationSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
52,6 → 52,7
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.tree.TreePath;
 
358,6 → 359,28
JCheckBox checkBrut = new JCheckBox(getLabelFor("BRUT"));
panelProp.add(checkBrut, cPanel);
 
// Compte tiers
JLabel labelTiers = new JLabel(getLabelFor("NUMERO_COMPTE_PCE"));
cPanel.gridx = 1;
cPanel.gridy++;
JTextField fieldCompte = new JTextField();
this.addView(fieldCompte, "NUMERO_COMPTE_PCE");
panelProp.add(labelTiers, cPanel);
cPanel.gridx++;
cPanel.weightx = 1;
panelProp.add(fieldCompte, cPanel);
cPanel.weightx = 0;
// Compte charge
JLabel labelCharge = new JLabel(getLabelFor("NUMERO_COMPTE_PCE_CHARGES"));
cPanel.gridy++;
cPanel.gridx = 1;
panelProp.add(labelCharge, cPanel);
cPanel.gridx++;
cPanel.weightx = 1;
JTextField fieldCompteCharge = new JTextField();
panelProp.add(fieldCompteCharge, cPanel);
this.addView(fieldCompteCharge, "NUMERO_COMPTE_PCE_CHARGES");
 
// Tabbed Pane
JTabbedPane tab = new JTabbedPane();
tab.add("Calcul", new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, paneTree, panelCalcul));
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueBrutSQLElement.java
1,7 → 1,7
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
* Copyright 2011-2019 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
359,9 → 359,18
JCheckBox checkCSGR = new JCheckBox(getLabelFor("CSG_REDUIT"));
panelProp.add(checkCSGR, cPanel);
 
cPanel.gridx = 1;
cPanel.weightx = 1;
cPanel.gridy++;
c.fill = GridBagConstraints.HORIZONTAL;
cPanel.gridwidth = GridBagConstraints.REMAINDER;
JCheckBox checkCSGSansAbattement = new JCheckBox(getLabelFor("PART_CSG_SANS_ABATTEMENT"));
panelProp.add(checkCSGSansAbattement, cPanel);
 
NoneSelectedButtonGroup groupCSG = new NoneSelectedButtonGroup();
groupCSG.add(checkCSGN);
groupCSG.add(checkCSGR);
groupCSG.add(checkCSGSansAbattement);
 
// Type
JLabel labelSelCodeRubrique = new JLabel("Code DSN (S21.G00.51.011)");
403,6 → 412,7
this.addSQLObject(checkImpo, "TAXABLE_CM");
this.addSQLObject(checkCSGN, "CSG_NORMAL");
this.addSQLObject(checkCSGR, "CSG_REDUIT");
this.addSQLObject(checkCSGSansAbattement, "PART_CSG_SANS_ABATTEMENT");
 
selSalarie.addValueListener(new PropertyChangeListener() {
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeIdccSQLElement.java
14,7 → 14,10
package org.openconcerto.erp.core.humanresources.payroll.element;
 
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.utils.ListMap;
 
import java.util.Arrays;
 
public class CodeIdccSQLElement extends AbstractCodeCommonSQLElement {
 
public CodeIdccSQLElement(final DBRoot root) {
25,4 → 28,11
protected String createCode() {
return createCodeOfPackage() + ".conventions.code";
}
 
@Override
public ListMap<String, String> getShowAs() {
ListMap<String, String> l = new ListMap<>();
l.put(null, Arrays.asList("CODE", "NOM"));
return l;
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CaisseCotisationSQLElement.java
286,16 → 286,22
 
@Override
public void update() {
 
super.update();
try {
this.table.getModel().updateField("ID_CAISSE_COTISATION", getSelectedID());
 
} catch (Exception e) {
throw new RuntimeException(e);
}
}
 
@Override
public int insert(SQLRow order) {
final int insertID = super.insert(order);
try {
this.table.getModel().updateField("ID_CAISSE_COTISATION", insertID);
} catch (Exception e) {
throw new RuntimeException(e);
}
return insertID;
}
};
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentPanel.java
33,8 → 33,10
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
42,6 → 44,7
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
55,6 → 58,7
import java.util.List;
import java.util.Set;
 
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
68,7 → 72,7
 
public class AttachmentPanel extends JPanel {
 
private final SQLRowAccessor rowSource;
private SQLRowAccessor rowSource;
private final Collection<SQLRowAccessor> rowSecondaires;
private List<ListDataListener> listeners = new ArrayList<>();
 
94,6 → 98,11
setFocusable(true);
}
 
public void setRowSource(SQLRowAccessor rowSource) {
this.rowSource = rowSource;
initUI();
}
 
public void addListener(ListDataListener l) {
this.listeners.add(l);
}
116,6 → 125,7
this.filePanels.clear();
this.invalidate();
this.removeAll();
if (rowSource != null) {
GridBagConstraints c = new DefaultGridBagConstraints();
 
// Recupération de la liste des fichiers
217,6 → 227,8
toolbar.add(addFileButton);
final JButton addURLButton = new JButton("Ajouter une URL");
toolbar.add(addURLButton);
final JButton copyClipboard = new JButton("Coller l'image");
toolbar.add(copyClipboard);
 
final JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(100);
283,6 → 295,36
}
});
 
copyClipboard.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
 
Transferable content = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (content == null) {
System.err.println("error: nothing found in clipboard");
return;
}
if (!content.isDataFlavorSupported(DataFlavor.imageFlavor)) {
System.err.println("error: no image found in clipbaord");
return;
}
 
try {
final BufferedImage img = (BufferedImage) content.getTransferData(DataFlavor.imageFlavor);
final File tmp = File.createTempFile("Image", ".png");
ImageIO.write(img, "png", tmp);
final AttachmentUtils utils = new AttachmentUtils();
utils.uploadFile(tmp, AttachmentPanel.this.rowSource, AttachmentPanel.this.idParent);
initUI();
tmp.delete();
} catch (UnsupportedFlavorException | IOException | SQLException e1) {
ExceptionHandler.handle(AttachmentPanel.this, "Erreur lors de la récupération de l'image", e1);
}
}
 
});
 
ScrollablePanel files = new ScrollablePanel() {
@Override
public Dimension getPreferredSize() {
405,7 → 447,8
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
@SuppressWarnings("unchecked")
List<File> fileList = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
// TODO faire en arriere plan, mettre une jauge à droite du bouton ajouter
// TODO faire en arriere plan, mettre une jauge à droite du bouton
// ajouter
// et mettre un bouton d'annulation
AttachmentUtils utils = new AttachmentUtils();
boolean cancelledByUser = false;
433,6 → 476,7
scroll.getViewport().setDropTarget(dt);
fireDataChanged();
}
}
 
public Set<Attachment> getSelectedAttachments() {
return this.selectedAttachments;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/AttachmentUtils.java
355,7 → 355,7
config.getDirectory().getElement(AttachmentSQLElement.class).archive(rowAttachment.getId());
updateAttachmentsCountFromAttachment(rowAttachment);
 
if (!rowAttachment.isFolder()) {
if (!rowAttachment.isFolder() && !rowAttachment.isURL()) {
boolean isOnCloud = config.isOnCloud();
// Delete File
String subDir = rowAttachment.getStoragePath();
/trunk/OpenConcerto/src/org/openconcerto/erp/core/edm/Attachment.java
95,6 → 95,10
return this.mimeType.equals(MIMETYPE_FOLDER);
}
 
public boolean isURL() {
return this.mimeType.equals(MIMETYPE_URL);
}
 
public boolean isEncrypted() {
return this.encrypted;
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/BarcodeListener.java
File deleted
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/StockErrorPanel.java
35,6 → 35,7
import java.util.Map;
 
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
public class StockErrorPanel extends JPanel {
private final CaisseControler controller;
80,24 → 81,25
final SQLSelect select = new SQLSelect();
select.addSelect(tDepot.getField("ID"));
select.addSelect(tDepot.getField("NOM"));
for (final SQLRow rowDepotArrivee : SQLRowListRSH.execute(select)) {
final int idDepotSource = rowDepotArrivee.getInt("ID");
final String nomDepot = rowDepotArrivee.getString("NOM");
int nbChoice = 0;
for (final SQLRow rowDepotDepart : SQLRowListRSH.execute(select)) {
final int idDepotDepart = rowDepotDepart.getInt("ID");
final String nomDepotDepart = rowDepotDepart.getString("NOM");
final int idDepotIDestination = caisseFrame.getPOSConf().getDepotID();
if (idDepotSource != idDepotIDestination) {
POSButton b = new POSButton("Créer un mouvement de stock depuis le dépôt " + nomDepot);
if (idDepotDepart != idDepotIDestination) {
POSButton b = new POSButton("Créer un mouvement de stock depuis le dépôt " + nomDepotDepart);
b.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent ev) {
System.err.println("StockErrorPanel.StockErrorPanel(...) mouvement de stock");
final SQLRow selectedRowDepotDepart = tDepot.getRow(idDepotSource);
final SQLRow selectedRowDepotArrivee = tDepot.getRow(idDepotIDestination);
final Date date = new Date();
for (Map.Entry<TicketItem, Integer> e : missingQty.entrySet()) {
final int idArticle = e.getKey().getArticle().getId();
final BigDecimal qteReel = new BigDecimal(e.getValue());
final SQLRow selectedRowArticle = tArticle.getRow(idArticle);
dir.getElement(MouvementStockSQLElement.class).transfertStock(qteReel, date, selectedRowArticle, selectedRowDepotDepart, rowDepotArrivee, "transfert depuis caisse");
dir.getElement(MouvementStockSQLElement.class).transfertStock(qteReel, date, selectedRowArticle, rowDepotDepart, selectedRowDepotArrivee, "transfert depuis caisse");
}
caisseFrame.showCaisse();
runnable.run();
105,21 → 107,21
});
c.gridy++;
this.add(b, c);
nbChoice++;
}
}
POSButton b = new POSButton("Ignorer le problème de stock");
b.addActionListener(new ActionListener() {
if (nbChoice == 0) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void actionPerformed(ActionEvent e) {
System.err.println("StockErrorPanel.StockErrorPanel(...) ignore stock");
public void run() {
caisseFrame.showCaisse();
runnable.run();
 
}
});
c.gridy++;
this.add(b, c);
 
} else {
 
POSButton b2 = new POSButton("Annuler la validation du ticket");
b2.addActionListener(new ActionListener() {
 
133,5 → 135,6
c.gridy++;
this.add(b2, c);
}
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaisseControler.java
14,6 → 14,8
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.io.Barcode;
import org.openconcerto.erp.core.sales.pos.io.BarcodeListener;
import org.openconcerto.erp.core.sales.pos.io.BarcodeReader;
import org.openconcerto.erp.core.sales.pos.io.ESCSerialDisplay;
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
251,7 → 253,8
}
 
@Override
public void barcodeRead(String code) {
public void barcodeRead(Barcode barcode) {
String code = barcode.getData();
System.err.println("CaisseControler.barcodeRead() barcode : " + code);
if (code.equalsIgnoreCase("especes")) {
autoFillPaiement(this.p1);
468,8 → 471,6
return (!this.t.getItems().isEmpty()) && ((this.getTotal() >= 0 && this.getPaidTotal() >= this.getTotal()) || (this.getTotal() < 0 && this.getPaidTotal() == this.getTotal()));
}
 
 
public void setTicketItemSelected(TicketItem item) {
this.ticketItemSelected = item;
if (item == null) {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketClientNamePanel.java
25,6 → 25,7
import java.awt.event.ActionListener;
import java.util.Collections;
 
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
67,9 → 68,11
tAdresse.setText(ticket.getClient().getAddr());
this.add(new JScrollPane(tAdresse), c);
c.gridy++;
final JButton b;
c.fill = GridBagConstraints.NONE;
// Textfield
POSButton b = new POSButton("Imprimer");
c.fill = GridBagConstraints.NONE;
if (caisseFrame != null) {
b = new POSButton("Imprimer");
b.addActionListener(new ActionListener() {
 
@Override
78,9 → 81,23
ticket.getClient().setAdresse(tAdresse.getText());
printInvoice(ticket);
caisseFrame.showCaisse();
}
});
} else {
b = new JButton("Imprimer");
c.fill = GridBagConstraints.NONE;
b.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
ticket.getClient().setFullName(text.getText());
ticket.getClient().setAdresse(tAdresse.getText());
printInvoice(ticket);
SwingUtilities.getWindowAncestor(TicketClientNamePanel.this).dispose();
 
}
});
}
c.gridy++;
this.add(b, c);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/TicketCellRenderer.java
17,6 → 17,7
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.QuickOrderedMap;
import org.openconcerto.utils.Tuple2;
 
import java.awt.Color;
import java.awt.Component;
112,12 → 113,12
if (s2.length() > maxLength) {
s2 = s2.substring(0, maxLength + 1) + '…';
}
QuickOrderedMap<String, String> decls = article.getDeclinaisons();
QuickOrderedMap<String, Tuple2<String, BigDecimal>> decls = article.getDeclinaisons();
String textDeclinaisons = null;
if (decls != null && !decls.isEmpty()) {
StringBuilder declinaisons = new StringBuilder();
for (int i = 0; i < decls.size(); i++) {
declinaisons.append(decls.getValue(i));
declinaisons.append(decls.getValue(i).get0());
declinaisons.append(" ");
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/PaiementPanel.java
13,6 → 13,8
package org.openconcerto.erp.core.sales.pos.ui;
 
import org.openconcerto.erp.core.sales.pos.io.Barcode;
import org.openconcerto.erp.core.sales.pos.io.BarcodeListener;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
547,7 → 549,7
}
 
@Override
public void barcodeRead(String code) {
public void barcodeRead(Barcode code) {
// Nothing to do here
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/ArticleSelector.java
18,6 → 18,7
import org.openconcerto.ui.touch.ScrollableList;
import org.openconcerto.utils.QuickOrderedMap;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
 
import java.awt.Color;
import java.awt.FlowLayout;
214,13 → 215,14
label += " [" + article.getCode() + "]";
}
StringBuilder declinaisons = null;
QuickOrderedMap<String, String> decls = article.getDeclinaisons();
QuickOrderedMap<String, Tuple2<String, BigDecimal>> decls = article.getDeclinaisons();
if (decls != null && !decls.isEmpty()) {
declinaisons = new StringBuilder();
for (int i = 0; i < decls.size(); i++) {
declinaisons.append(StringUtils.firstUpThenLow(decls.getKey(i)));
declinaisons.append(": ");
declinaisons.append(decls.getValue(i));
final Tuple2<String, BigDecimal> value = decls.getValue(i);
declinaisons.append(value.get0());
declinaisons.append(" ");
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/ui/CaissePanel.java
36,6 → 36,7
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
 
import java.awt.Color;
222,7 → 223,8
Map<TicketItem, Integer> missingQty = new HashMap<>();
for (SQLRow row : SQLRowListRSH.execute(selStock)) {
int idArticle = row.getInt("ID_ARTICLE");
int qte = (int) Math.round(row.getFloat("QTE_REEL"));
// Limite pour ne pas fixer les stock négatif et corrompre le stock principal
int qte = Math.max(0, (int) Math.round(row.getFloat("QTE_REEL")));
TicketItem item = mapTicketItem.get(idArticle);
if (item == null) {
System.err.println("Pas d'entrée dans STOCK pour l'article " + idArticle);
318,8 → 320,8
final SQLSelect selArticle = new SQLSelect();
final SQLTable tableArticle = eltArticle.getTable();
selArticle.addAllSelect(tableArticle.getFields(VirtualFields.PRIMARY_KEY.union(VirtualFields.ARCHIVE)));
selArticle.addAllSelect(tableArticle,
Arrays.asList("ID_FAMILLE_ARTICLE", "NOM", "CODE", "CODE_BARRE", "ID_TAXE", "PV_HT", "PV_TTC", "ADDITIONAL_TICKET_COPY", "ID_UNITE_VENTE", "ID_ECO_CONTRIBUTION"));
selArticle.addAllSelect(tableArticle, Arrays.asList("ID_ARTICLE_VIRTUEL_PERE", "ID_FAMILLE_ARTICLE", "NOM", "CODE", "CODE_BARRE", "ID_TAXE", "PV_HT", "PV_TTC", "ADDITIONAL_TICKET_COPY",
"ID_UNITE_VENTE", "ID_ECO_CONTRIBUTION"));
selArticle.setWhere(new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE).and(new Where(tableArticle.getField("MASQUE_CAISSE"), "=", Boolean.FALSE)));
selArticle.andWhere(new Where(tableArticle.getField("VIRTUEL"), "=", Boolean.FALSE));
 
333,6 → 335,15
}
}
 
final SQLSelect selArtVirt = new SQLSelect();
selArtVirt.addSelect(tableArticle.getKey());
selArtVirt.addSelect(tableArticle.getField("NOM"));
 
Map<Integer, String> mapVirtuel = new HashMap<>();
for (SQLRow row : SQLRowListRSH.execute(selArtVirt)) {
mapVirtuel.put(row.getID(), row.getString("NOM"));
}
 
final Categorie cUnclassified = new Categorie("Non classés", true);
cUnclassified.setUnknown();
 
339,16 → 350,17
// Fetch des declinaisons :
// "ID_ARTICLE_DECLINAISON_COULEUR" : { {3 , "noir"] } ,
// "ID_ARTICLE_DECLINAISON_TAILLE" : { {2 ,"XL"},{3,"XXL"}};
Map<String, Map<Integer, String>> mapDeclinaisons = new HashMap<>();
Map<String, Map<Integer, Tuple2<String, BigDecimal>>> mapDeclinaisons = new HashMap<>();
for (String table : tablesDeclinaisons) {
SQLTable t = eltArticle.getTable().getTable(table);
final SQLSelect selDecl = new SQLSelect();
selDecl.addSelect(t.getKey());
selDecl.addSelect(t.getField("NOM"));
Map<Integer, String> m = new HashMap<>();
selDecl.addSelect(t.getField("ORDRE"));
Map<Integer, Tuple2<String, BigDecimal>> m = new HashMap<>();
mapDeclinaisons.put("ID_" + table, m);
for (SQLRow row : SQLRowListRSH.execute(selDecl)) {
m.put(row.getID(), row.getString("NOM"));
m.put(row.getID(), Tuple2.create(row.getString("NOM"), row.getBigDecimal("ORDRE")));
}
}
// Fetch des articles
384,7 → 396,7
Map<Integer, List<TarifQuantite>> mapTarif = new HashMap<>();
System.err.println("CaissePanel.loadArticles()" + rPromotions.size() + " promotions");
for (SQLRowValues r : rPromotions) {
final Integer foreignID = ((Integer) r.getObjectNoCheck("ID_ARTICLE"));
final Integer foreignID = r.getForeignID("ID_ARTICLE");
List<TarifQuantite> list = mapTarif.get(foreignID);
if (list == null) {
list = new ArrayList<>();
442,11 → 454,15
for (String f : declinaisonsFieldNames) {
Integer idArtDeclinaison = (Integer) row.getObjectNoCheck(f);
if (idArtDeclinaison != null && idArtDeclinaison > 1) {
Map<Integer, String> mm = mapDeclinaisons.get(f);
Map<Integer, Tuple2<String, BigDecimal>> mm = mapDeclinaisons.get(f);
if (mm != null) {
String v = mm.get(idArtDeclinaison);
a.addDeclinaison(f.substring("ID_ARTICLE_DECLINAISON_".length()), v);
Tuple2<String, BigDecimal> v = mm.get(idArtDeclinaison);
a.addDeclinaison(f.substring("ID_ARTICLE_DECLINAISON_".length()), v.get0(), v.get1());
}
// Integer pere = (Integer) row.getObjectNoCheck("ID_ARTICLE_VIRTUEL_PERE");
// if (pere != null && mapVirtuel.containsKey(pere)) {
// a.setArticlePereNom(mapVirtuel.get(pere));
// }
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Categorie.java
13,6 → 13,10
package org.openconcerto.erp.core.sales.pos.model;
 
import org.openconcerto.utils.QuickOrderedMap;
import org.openconcerto.utils.Tuple2;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
103,9 → 107,29
Collections.sort(result, new Comparator<Article>() {
@Override
public int compare(Article o1, Article o2) {
final boolean isChild = o1.getArticlePereNom() != null && o2.getArticlePereNom() != null && o1.getArticlePereNom().trim().length() > 0
&& o1.getArticlePereNom().equals(o2.getArticlePereNom());
final QuickOrderedMap<String, Tuple2<String, BigDecimal>> declinaisons1 = o1.getDeclinaisons();
final QuickOrderedMap<String, Tuple2<String, BigDecimal>> declinaisons2 = o2.getDeclinaisons();
final boolean hasDecl = isChild && declinaisons1 != null && !declinaisons1.isEmpty() && declinaisons2 != null && !declinaisons2.isEmpty();
if (o1.getName().compareTo(o2.getName()) == 0 && hasDecl) {
for (int i = 0; i < declinaisons1.size(); i++) {
final String key = declinaisons1.getKey(i);
final Tuple2<String, BigDecimal> tuple1 = declinaisons1.get(key);
final Tuple2<String, BigDecimal> tuple2 = declinaisons2.get(key);
if (tuple1 != null && tuple2 != null) {
BigDecimal order1 = tuple1.get1();
BigDecimal order2 = tuple2.get1();
if (order1.compareTo(order2) != 0) {
return order1.compareTo(order2);
}
}
}
}
return o1.getName().compareTo(o2.getName());
}
});
 
return result;
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/model/Article.java
16,6 → 16,7
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.QuickOrderedMap;
import org.openconcerto.utils.Tuple2;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
42,10 → 43,13
private String salesUnit;
private static Map<String, List<Article>> codes = new HashMap<>();
 
// declinaison (ex "taille":"45", "couleur","rouge"), null si pas de declinaison
private QuickOrderedMap<String, String> declinaisons;
// type de declinaison : nom de la déclinaison et ordre (ex "taille":"45 / 5.5",
// "couleur","rouge / 2.05"), null si pas de declinaison
private QuickOrderedMap<String, Tuple2<String, BigDecimal>> declinaisons;
 
List<TarifQuantite> tarifs;
private String declinaison;
private String articlePereNom = null;
 
public Article(Categorie s1, String string, int id) {
this.s = s1;
68,7 → 72,7
this.ecotaxe = a.ecotaxe;
 
this.s.addArticle(this);
final QuickOrderedMap<String, String> decl = a.getDeclinaisons();
final QuickOrderedMap<String, Tuple2<String, BigDecimal>> decl = a.getDeclinaisons();
if (decl != null) {
final int size = decl.size();
this.declinaisons = new QuickOrderedMap<>(size);
109,17 → 113,25
return result;
}
 
public void addDeclinaison(String key, String value) {
public void addDeclinaison(String key, String value, BigDecimal ordreDeclinaison) {
if (this.declinaisons == null) {
this.declinaisons = new QuickOrderedMap<>(5);
}
this.declinaisons.put(key, value);
this.declinaisons.put(key, Tuple2.create(value, ordreDeclinaison));
}
 
public QuickOrderedMap<String, String> getDeclinaisons() {
public QuickOrderedMap<String, Tuple2<String, BigDecimal>> getDeclinaisons() {
return this.declinaisons;
}
 
public void setArticlePereNom(String articlePereNom) {
this.articlePereNom = articlePereNom;
}
 
public String getArticlePereNom() {
return this.articlePereNom;
}
 
public boolean isPromotion() {
return this.tarifs != null && !this.tarifs.isEmpty();
}
238,7 → 250,8
if (this.declinaisons != null) {
return "Article:" + this.code + " | " + this.name + " " + this.priceTTC + " cents" + "(HT:" + this.priceHT + ") " + getSalesUnit() + " discount:" + getDiscountPct();
}
return "Article:" + this.code + " | " + this.name + " [" + this.declinaisons + "] : " + this.priceTTC + " cents" + "(HT:" + this.priceHT + ") " + getSalesUnit() + " discount:" + getDiscountPct();
return "Article:" + this.code + " | " + this.name + " [" + this.declinaisons + "] : " + this.priceTTC + " cents" + "(HT:" + this.priceHT + ") " + getSalesUnit() + " discount:"
+ getDiscountPct();
}
 
public static List<Article> getArticleFromBarcode(String code) {
307,9 → 320,12
if (this.declinaison == null && this.declinaisons != null && !this.declinaisons.isEmpty()) {
StringBuilder b = new StringBuilder();
for (int i =