OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 182 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
177 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
177 ilm 5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.supplychain.purchase.importer;
15
 
182 ilm 16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
180 ilm 17
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
182 ilm 18
import org.openconcerto.sql.Configuration;
177 ilm 19
import org.openconcerto.sql.model.DBRoot;
180 ilm 20
import org.openconcerto.sql.model.SQLRow;
21
import org.openconcerto.sql.model.SQLRowAccessor;
22
import org.openconcerto.sql.model.SQLRowValues;
23
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
24
import org.openconcerto.sql.model.SQLTable;
25
import org.openconcerto.sql.model.Where;
177 ilm 26
 
27
import java.math.BigDecimal;
182 ilm 28
import java.math.RoundingMode;
177 ilm 29
import java.text.DecimalFormat;
30
import java.text.DecimalFormatSymbols;
31
import java.text.SimpleDateFormat;
180 ilm 32
import java.util.Collection;
177 ilm 33
import java.util.Date;
180 ilm 34
import java.util.HashMap;
177 ilm 35
import java.util.List;
36
import java.util.Locale;
180 ilm 37
import java.util.Map;
177 ilm 38
 
39
import org.jdom2.Document;
40
import org.jdom2.Element;
41
import org.jdom2.Namespace;
42
import org.jdom2.output.Format;
43
import org.jdom2.output.XMLOutputter;
44
 
45
/**
46
 * FacturX export (EN 16931 format)
47
 */
48
public class FacturXExporter {
49
    private class Tax {
50
        // Taux, ex pour 20% : 20.00
180 ilm 51
        final BigDecimal rate;
177 ilm 52
        // Montant de la TVA
180 ilm 53
        BigDecimal amount = BigDecimal.ZERO;
177 ilm 54
 
55
        // montant HT sur lequel s'applique la TVA
180 ilm 56
        BigDecimal basisAmount = BigDecimal.ZERO;
177 ilm 57
 
180 ilm 58
        public Tax(BigDecimal rate) {
59
            this.rate = rate;
60
        }
61
 
62
        public void add(BigDecimal taxAmount,
63
 
64
                BigDecimal basisAmount) {
65
            this.amount = this.amount.add(taxAmount);
66
            this.basisAmount = this.basisAmount.add(basisAmount);
67
        }
177 ilm 68
    }
69
 
70
    public static Namespace QDT_NS = Namespace.getNamespace("qdt", "urn:un:unece:uncefact:data:standard:QualifiedDataType:100");
71
    public static Namespace RAM_NS = Namespace.getNamespace("ram", "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100");
72
    public static Namespace RSM_NS = Namespace.getNamespace("rsm", "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100");
73
    public static Namespace UDT_NS = Namespace.getNamespace("udt", "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100");
74
    public static Namespace XSI_NS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
75
 
76
    public static void main(String[] args) {
77
 
78
        FacturXExporter ex = new FacturXExporter();
79
        System.err.println("FacturXExporter.main() " + ex.checkEAN13("5987854125989"));
180 ilm 80
        // String xml = ex.createXMLFrom(null, 1);
81
        // System.out.println(xml);
177 ilm 82
    }
83
 
180 ilm 84
    DecimalFormat formatAmount = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
177 ilm 85
 
180 ilm 86
    private boolean useCommonClient = false;
177 ilm 87
 
180 ilm 88
    public String createXMLFrom(DBRoot dbRoot, int invoiceId, SQLRow societeRow) {
89
 
90
        SQLTable factureTable = dbRoot.getTable("SAISIE_VENTE_FACTURE");
91
        SQLRowValues rowValsToFetch = new SQLRowValues(factureTable);
92
        rowValsToFetch.putNulls("NUMERO", "DATE", "NOM", "T_TVA", "T_HT", "T_TTC", "NET_A_PAYER");
93
        rowValsToFetch.putRowValues("ID_MODE_REGLEMENT").putNulls("COMPTANT", "AJOURS", "LENJOUR", "DATE_FACTURE", "FIN_MOIS").putRowValues("ID_TYPE_REGLEMENT").putNulls("NOM");
94
        SQLRowValues putRowValuesClient = rowValsToFetch.putRowValues("ID_CLIENT");
95
        putRowValuesClient.putNulls("NOM", "RESPONSABLE", "SIRET", "NUMERO_TVA", "MAIL", "TEL");
182 ilm 96
 
180 ilm 97
        putRowValuesClient.putRowValues("ID_ADRESSE").putNulls("RUE", "VILLE", "CODE_POSTAL", "PAYS");
98
        putRowValuesClient.putRowValues("ID_ADRESSE_F").putNulls("RUE", "VILLE", "CODE_POSTAL", "PAYS");
99
        rowValsToFetch.putRowValues("ID_ADRESSE").putNulls("RUE", "VILLE", "CODE_POSTAL", "PAYS");
100
 
101
        SQLTable factureItemtable = dbRoot.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
102
        SQLRowValues rowValsItemsToFetch = new SQLRowValues(factureItemtable);
103
 
104
        rowValsItemsToFetch.putNulls("NIVEAU", "CODE", "NOM", "QTE", "QTE_UNITAIRE", "PV_HT", "T_PV_HT", "T_PV_TTC").putRowValues("ID_TAXE").put("TAUX", null);
105
        rowValsItemsToFetch.put("ID_SAISIE_VENTE_FACTURE", rowValsToFetch);
106
        List<SQLRowValues> factures = SQLRowValuesListFetcher.create(rowValsToFetch).fetch(new Where(factureTable.getKey(), "=", invoiceId));
107
        SQLRowValues facture = factures.get(0);
108
 
109
        Collection<? extends SQLRowAccessor> factureItems = facture.getReferentRows(factureItemtable.getField("ID_SAISIE_VENTE_FACTURE"));
110
 
111
        Map<Integer, Tax> taxes = new HashMap<>();
112
 
113
        // Tax t1 = new Tax();
114
        // t1.rate = new BigDecimal("20.0");
115
        // t1.amount = new BigDecimal("40.0");
116
        // t1.basisAmount = new BigDecimal("200.0");
117
        // taxes.add(t1);
118
 
177 ilm 119
        DecimalFormat fQty = new DecimalFormat("#0.########", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
180 ilm 120
        String invoiceNumber = facture.getString("NUMERO");
121
        Date invoiceDate = facture.getDate("DATE").getTime();
122
        String regNote = societeRow.getString("TYPE") + " au capital de " + societeRow.getObject("CAPITAL") + " €";
123
        String legNote = societeRow.getString("RCS");
124
        int nbLines = factureItems.size();
177 ilm 125
 
126
        final Document doc = new Document();
127
        Element root = new Element("CrossIndustryInvoice", RSM_NS);
128
        root.addNamespaceDeclaration(QDT_NS);
129
        root.addNamespaceDeclaration(RAM_NS);
130
        root.addNamespaceDeclaration(RSM_NS);
131
        root.addNamespaceDeclaration(UDT_NS);
132
        root.addNamespaceDeclaration(XSI_NS);
133
 
134
        doc.setRootElement(root);
135
 
136
        // ExchangedDocumentContext : Le truc qui s'ecrirait en une ligne si les génies, grands
137
        // créateurs de cette norme, connaissaient la notion d'attributs...
138
        Element eDC = new Element("ExchangedDocumentContext", RSM_NS);
139
        Element bPSDCP = new Element("BusinessProcessSpecifiedDocumentContextParameter", RAM_NS);
140
        final Element bPSDCP_ID = new Element("ID", RAM_NS);
141
        // CHORUSPRO specifications: A1 (invoice deposit), A2 (prepaid invoice deposit)...
142
        bPSDCP_ID.setText("A1");
143
        bPSDCP.addContent(bPSDCP_ID);
144
        eDC.addContent(bPSDCP);
145
        Element bGSDCP = new Element("GuidelineSpecifiedDocumentContextParameter", RAM_NS);
146
        final Element bGSDCP_ID = new Element("ID", RAM_NS);
147
        // For Profile EN 16931 (Comfort):
148
        bGSDCP_ID.setText("urn:cen.eu:en16931:2017");
149
        bGSDCP.addContent(bGSDCP_ID);
150
        eDC.addContent(bGSDCP);
151
        root.addContent(eDC);
152
 
153
        // ExchangedDocument
154
        Element ed = new Element("ExchangedDocument", RSM_NS);
155
        Element edID = new Element("ID", RAM_NS);
156
        if (invoiceNumber.length() > 20) {
157
            // CHORUSPRO: the invoice number is limited to 20 characters (lol)
158
            invoiceNumber = invoiceNumber.substring(0, 20);
159
        }
160
        edID.setText(invoiceNumber);
161
        ed.addContent(edID);
162
        Element edTypeCode = new Element("TypeCode", RAM_NS);
163
        // The types of documents used are:
164
        // 380: Commercial Invoice
165
        // 381: Credit note
166
        // 384: Corrected invoice
167
        // 389: Self-billied invoice (created by the buyer on behalf of the supplier)
168
        // 261: Self billed credit note (not accepted by CHORUSPRO)
169
        // 386: Prepayment invoice
170
        // 751: Invoice information for accounting purposes (not accepted by CHORUSPRO)
171
        edTypeCode.setText("380");
172
        ed.addContent(edTypeCode);
173
        Element edIssueDateTime = new Element("IssueDateTime", RAM_NS);
174
        addDateTime(invoiceDate, edIssueDateTime);
175
        ed.addContent(edIssueDateTime);
176
        addIncludedNote(regNote, "REG", ed);
177
        addIncludedNote(legNote, "ABL", ed);
178
 
179
        // SupplyChainTradeTransaction
180
        Element eSupplyChainTradeTransaction = new Element("SupplyChainTradeTransaction", RSM_NS);
180 ilm 181
        int lineID = 1;
182
        for (SQLRowAccessor rowItem : factureItems) {
183
            String productCode = rowItem.getString("CODE");
185 ilm 184
            String productName = rowItem.getString("NOM");
185
            if (productName == null || rowItem.getString("NOM").trim().isEmpty()) {
186
                productName = "Ligne " + lineID;
187
            }
180 ilm 188
            final BigDecimal pHT, pTTC, totalHTLigne, totalTTCLigne;
189
            SQLRowAccessor taxeItem = rowItem.getForeign("ID_TAXE");
182 ilm 190
            BigDecimal taxValue = new BigDecimal(taxeItem.getFloat("TAUX")).setScale(2, RoundingMode.HALF_UP);
180 ilm 191
            if (rowItem.getInt("NIVEAU") != 1) {
192
                pHT = BigDecimal.ZERO;
193
                pTTC = BigDecimal.ZERO;
194
                totalHTLigne = BigDecimal.ZERO;
195
                totalTTCLigne = BigDecimal.ZERO;
196
            } else {
197
                pHT = rowItem.getBigDecimal("PV_HT");
185 ilm 198
                pTTC = pHT.multiply(taxValue.movePointLeft(2).add(BigDecimal.ONE));
180 ilm 199
                totalHTLigne = rowItem.getBigDecimal("T_PV_HT");
200
                totalTTCLigne = rowItem.getBigDecimal("T_PV_TTC");
201
            }
177 ilm 202
 
180 ilm 203
            int idTaxe = taxeItem.getID();
204
            if (!taxes.containsKey(idTaxe)) {
205
                Tax t = new Tax(taxValue);
206
                taxes.put(idTaxe, t);
207
            }
208
            taxes.get(idTaxe).add(totalTTCLigne.subtract(totalHTLigne), totalHTLigne);
209
            BigDecimal qte = new BigDecimal(rowItem.getInt("QTE")).multiply(rowItem.getBigDecimal("QTE_UNITAIRE"));
210
 
177 ilm 211
            Element eLineItem = new Element("IncludedSupplyChainTradeLineItem", RAM_NS);
180 ilm 212
 
177 ilm 213
            // AssociatedDocumentLineDocument
214
            Element eAssociatedDocumentLineDocument = new Element("AssociatedDocumentLineDocument", RAM_NS);
215
            Element eLineID = new Element("LineID", RAM_NS);
180 ilm 216
            eLineID.setText(String.valueOf(lineID++));
177 ilm 217
            eAssociatedDocumentLineDocument.addContent(eLineID);
218
            eLineItem.addContent(eAssociatedDocumentLineDocument);
219
            // SpecifiedTradeProduct
220
            Element eSpecifiedTradeProduct = new Element("SpecifiedTradeProduct", RAM_NS);
221
            if (!productCode.isEmpty()) {
222
                Element eGlobalID = new Element("GlobalID", RAM_NS);
223
                if (productCode.length() > 40) {
224
                    // CHORUSPRO: this field is limited to 40 characters
225
                    productCode = productCode.substring(0, 40);
226
                }
227
                if (checkEAN13(productCode)) {
228
                    // 0088 : EAN
229
                    eGlobalID.setAttribute("schemeID", "0088");
230
                } else {
231
                    // 0197 : Not Known
232
                    eGlobalID.setAttribute("schemeID", "0197");
233
                }
234
                eGlobalID.setText(productCode);
235
                eSpecifiedTradeProduct.addContent(eGlobalID);
236
            }
237
            Element eName = new Element("Name", RAM_NS);
238
            eName.setText(productName);
239
            eSpecifiedTradeProduct.addContent(eName);
240
            eLineItem.addContent(eSpecifiedTradeProduct);
241
            //
242
            Element eSpecifiedLineTradeAgreement = new Element("SpecifiedLineTradeAgreement", RAM_NS);
243
            // Prix unitaire TTC
244
            Element eGrossPriceProductTradePrice = new Element("GrossPriceProductTradePrice", RAM_NS);
245
            Element eChargeAmount = new Element("ChargeAmount", RAM_NS);
180 ilm 246
            eChargeAmount.setText(formatAmount.format(pTTC));
177 ilm 247
            eGrossPriceProductTradePrice.addContent(eChargeAmount);
248
            Element eAppliedTradeAllowanceCharge = new Element("AppliedTradeAllowanceCharge", RAM_NS);
249
            Element eChargeIndicator = new Element("ChargeIndicator", RAM_NS);
180 ilm 250
            Element eIndicator = new Element("Indicator", UDT_NS);
177 ilm 251
            // pas de remise
252
            eIndicator.setText("false");
253
            eChargeIndicator.addContent(eIndicator);
254
            eAppliedTradeAllowanceCharge.addContent(eChargeIndicator);
255
 
256
            Element eActualAmount = new Element("ActualAmount", RAM_NS);
257
            // Montant de TVA (unitaire)
180 ilm 258
            eActualAmount.setText(formatAmount.format(pTTC.subtract(pHT)));
177 ilm 259
 
260
            eAppliedTradeAllowanceCharge.addContent(eActualAmount);
261
 
180 ilm 262
            // eGrossPriceProductTradePrice.addContent(eAppliedTradeAllowanceCharge);
177 ilm 263
 
264
            eSpecifiedLineTradeAgreement.addContent(eGrossPriceProductTradePrice);
265
            // Prix unitaire HT
266
            Element eNetPriceProductTradePrice = new Element("NetPriceProductTradePrice", RAM_NS);
267
            Element eChargeAmountHT = new Element("ChargeAmount", RAM_NS);
180 ilm 268
            eChargeAmountHT.setText(formatAmount.format(pHT));
177 ilm 269
 
270
            eNetPriceProductTradePrice.addContent(eChargeAmountHT);
271
            eSpecifiedLineTradeAgreement.addContent(eNetPriceProductTradePrice);
272
            eLineItem.addContent(eSpecifiedLineTradeAgreement);
273
 
274
            // Quantité
275
 
276
            Element eSpecifiedLineTradeDelivery = new Element("SpecifiedLineTradeDelivery", RAM_NS);
277
 
278
            // LTR = Liter (1 dm3), MTQ = cubic meter , KGM = Kilogram , MTR = Meter , C62 = Unit ,
279
            // TNE = Tonne
280
            // TODO : gerer les unités
281
            Element eBilledQuantity = new Element("BilledQuantity", RAM_NS);
282
            eBilledQuantity.setAttribute("unitCode", "C62");
283
            eBilledQuantity.setText(fQty.format(qte));
284
 
285
            eSpecifiedLineTradeDelivery.addContent(eBilledQuantity);
286
            eLineItem.addContent(eSpecifiedLineTradeDelivery);
287
 
288
            Element eSpecifiedLineTradeSettlement = new Element("SpecifiedLineTradeSettlement", RAM_NS);
289
            Element eApplicableTradeTaxt = new Element("ApplicableTradeTax", RAM_NS);
290
 
291
            Element eTypeCode = new Element("TypeCode", RAM_NS);
292
            eTypeCode.setText("VAT");
293
            eApplicableTradeTaxt.addContent(eTypeCode);
294
 
295
            // S = Taux de TVA standard
296
            // E = Exempté de TVA
297
            // AE = Autoliquidation de TVA
298
            // K = Autoliquidation pour cause de livraison intracommunautaire
299
            // G = Exempté de TVA pour Export hors UE
300
            // O = Hors du périmètre d'application de la TVA
301
            // L = Iles Canaries
302
            // M = Ceuta et Mellila
303
            // TODO : TVA 0
304
            Element eCategoryCode = new Element("CategoryCode", RAM_NS);
305
            eCategoryCode.setText("S");
306
            eApplicableTradeTaxt.addContent(eCategoryCode);
307
 
308
            Element eRateApplicablePercent = new Element("RateApplicablePercent", RAM_NS);
309
            // 20% -> 20.0
180 ilm 310
            eRateApplicablePercent.setText(formatAmount.format(taxValue));
177 ilm 311
            eApplicableTradeTaxt.addContent(eRateApplicablePercent);
312
 
313
            eSpecifiedLineTradeSettlement.addContent(eApplicableTradeTaxt);
314
 
315
            Element eSpecifiedTradeSettlementLineMonetarySummation = new Element("SpecifiedTradeSettlementLineMonetarySummation", RAM_NS);
316
            // Total HT
317
            Element eLineTotalAmount = new Element("LineTotalAmount", RAM_NS);
180 ilm 318
            eLineTotalAmount.setText(formatAmount.format(totalHTLigne));
177 ilm 319
            eSpecifiedTradeSettlementLineMonetarySummation.addContent(eLineTotalAmount);
320
            eSpecifiedLineTradeSettlement.addContent(eSpecifiedTradeSettlementLineMonetarySummation);
321
 
322
            eLineItem.addContent(eSpecifiedLineTradeSettlement);
323
            //
324
            eSupplyChainTradeTransaction.addContent(eLineItem);
325
        }
326
 
180 ilm 327
        root.addContent(ed);
328
        addApplicableHeader(societeRow, facture, eSupplyChainTradeTransaction, taxes.values());
177 ilm 329
 
180 ilm 330
        root.addContent(eSupplyChainTradeTransaction);
177 ilm 331
 
332
        final XMLOutputter xmlOutput = new XMLOutputter();
333
        xmlOutput.setFormat(Format.getPrettyFormat());
334
        return xmlOutput.outputString(doc);
335
    }
336
 
337
    public void addValue(Element parent, Element element, String value) {
338
        element.setText(value);
339
        parent.addContent(element);
340
    }
341
 
180 ilm 342
    private void addApplicableHeader(SQLRowAccessor rowSociete, SQLRowAccessor rowFacture, Element eSupplyChainTradeTransaction, Collection<Tax> taxes) {
177 ilm 343
        //
344
        // ApplicableHeaderTradeAgreement
345
        //
346
        final Element eApplicableHeaderTradeAgreement = new Element("ApplicableHeaderTradeAgreement", RAM_NS);
180 ilm 347
        addSupplierInfo(eApplicableHeaderTradeAgreement, rowSociete);
348
        addBuyerInfo(eApplicableHeaderTradeAgreement, rowFacture);
177 ilm 349
 
350
        String orderRef = "";
351
        String contractRef = "";
352
        // Date de livraison, facultative
180 ilm 353
        Date effectiveDeliveryDate = rowFacture.getDate("DATE").getTime();
354
        String invoiceNumber = rowFacture.getString("NUMERO");
177 ilm 355
        String currencyCode = "EUR";
180 ilm 356
        SQLRowAccessor foreignMdr = rowFacture.getForeign("ID_MODE_REGLEMENT");
357
        int ajours = foreignMdr.getInt("AJOURS");
358
        int lenjour = foreignMdr.getInt("LENJOUR");
359
        String dueDescription = (ajours > 0 ? "A " + ajours : "") + (lenjour > 0 ? " le " + lenjour : "");
360
        Date dueDate = ModeDeReglementSQLElement.calculDate(foreignMdr, rowFacture.getDate("DATE").getTime());
177 ilm 361
 
362
        final Element eBuyerOrderReferencedDocument = new Element("BuyerOrderReferencedDocument", RAM_NS);
363
        addValue(eBuyerOrderReferencedDocument, new Element("IssuerAssignedID", RAM_NS), orderRef);
364
        eApplicableHeaderTradeAgreement.addContent(eBuyerOrderReferencedDocument);
365
 
366
        final Element eContractReferencedDocument = new Element("ContractReferencedDocument", RAM_NS);
367
        addValue(eContractReferencedDocument, new Element("IssuerAssignedID", RAM_NS), contractRef);
368
 
369
        eApplicableHeaderTradeAgreement.addContent(eContractReferencedDocument);
370
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeAgreement);
371
 
372
        //
373
        // ApplicableHeaderTradeDelivery
374
        //
375
        final Element eApplicableHeaderTradeDelivery = new Element("ApplicableHeaderTradeDelivery", RAM_NS);
376
 
377
        // <ram:ShipToTradeParty>
378
        // <ram:PostalTradeAddress>
379
        // <ram:PostcodeCode>69001</ram:PostcodeCode>
380
        // <ram:LineOne>35 rue de la République</ram:LineOne>
381
        // <ram:CityName>Lyon</ram:CityName>
382
        // <ram:CountryID>FR</ram:CountryID>
383
        // </ram:PostalTradeAddress>
384
        // </ram:ShipToTradeParty>
385
        if (effectiveDeliveryDate != null) {
386
            // Date de livraison effective (facultative)
387
            final Element eActualDeliverySupplyChainEvent = new Element("ActualDeliverySupplyChainEvent", RAM_NS);
388
            final Element eOccurrenceDateTime = new Element("OccurrenceDateTime", RAM_NS);
389
            addDateTime(effectiveDeliveryDate, eOccurrenceDateTime);
390
            eActualDeliverySupplyChainEvent.addContent(eOccurrenceDateTime);
391
            eApplicableHeaderTradeDelivery.addContent(eActualDeliverySupplyChainEvent);
392
        }
393
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeDelivery);
394
 
395
        //
396
        // ApplicableHeaderTradeSettlement
397
        //
398
        final Element eApplicableHeaderTradeSettlement = new Element("ApplicableHeaderTradeSettlement", RAM_NS);
399
        addValue(eApplicableHeaderTradeSettlement, new Element("PaymentReference", RAM_NS), invoiceNumber);
400
        addValue(eApplicableHeaderTradeSettlement, new Element("InvoiceCurrencyCode", RAM_NS), currencyCode);
401
        final Element aSpecifiedTradeSettlementPaymentMeans = new Element("SpecifiedTradeSettlementPaymentMeans", RAM_NS);
180 ilm 402
        addValue(aSpecifiedTradeSettlementPaymentMeans, new Element("TypeCode", RAM_NS), "57");
177 ilm 403
 
404
        // <ram:TypeCode>30</ram:TypeCode>
405
        // <ram:Information>Virement sur compte Banque Fiducial</ram:Information>
406
        // <ram:PayeePartyCreditorFinancialAccount>
407
        // <ram:IBANID>FR2012421242124212421242124</ram:IBANID>
408
        // </ram:PayeePartyCreditorFinancialAccount>
409
        // <ram:PayeeSpecifiedCreditorFinancialInstitution>
410
        // <ram:BICID>FIDCFR21XXX</ram:BICID>
411
        // </ram:PayeeSpecifiedCreditorFinancialInstitution>
412
 
413
        eApplicableHeaderTradeSettlement.addContent(aSpecifiedTradeSettlementPaymentMeans);
414
        DecimalFormat format = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
415
        for (Tax t : taxes) {
416
            final Element aApplicableTradeTax = new Element("ApplicableTradeTax", RAM_NS);
417
            // Montant de la TVA
418
            addValue(aApplicableTradeTax, new Element("CalculatedAmount", RAM_NS), format.format(t.amount));
419
            // LOL
420
            addValue(aApplicableTradeTax, new Element("TypeCode", RAM_NS), "VAT");
421
            // montant HT sur lequel s'applique la TVA
422
            addValue(aApplicableTradeTax, new Element("BasisAmount", RAM_NS), format.format(t.basisAmount));
423
            // S = Taux de TVA standard
424
            // E = Exempté de TVA
425
            // AE = Autoliquidation de TVA
426
            // K = Autoliquidation pour cause de livraison intracommunautaire
427
            // G = Exempté de TVA pour Export hors UE
428
            // O = Hors du périmètre d'application de la TVA
429
            // L = Iles Canaries
430
            // M = Ceuta et Mellila
431
            // TODO : TVA 0
432
            addValue(aApplicableTradeTax, new Element("CategoryCode", RAM_NS), "S");
433
 
434
            // TODO : type de TVA :
435
            // 5 : Date de la facture (TVA sur DEBITS)
436
            // 29 : Date de livraison (TVA sur DEBITS)
437
            // 72 : Date de paiement (TVA sur ENCAISSEMENTS)
438
            addValue(aApplicableTradeTax, new Element("DueDateTypeCode", RAM_NS), "5");
439
 
440
            addValue(aApplicableTradeTax, new Element("RateApplicablePercent", RAM_NS), format.format(t.rate));
441
            eApplicableHeaderTradeSettlement.addContent(aApplicableTradeTax);
442
        }
443
 
444
        final Element eSpecifiedTradePaymentTerms = new Element("SpecifiedTradePaymentTerms", RAM_NS);
445
        addValue(eSpecifiedTradePaymentTerms, new Element("Description", RAM_NS), dueDescription);
446
 
447
        final Element eDueDateDateTime = new Element("DueDateDateTime", RAM_NS);
448
        addDateTime(dueDate, eDueDateDateTime);
449
        eSpecifiedTradePaymentTerms.addContent(eDueDateDateTime);
450
        eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradePaymentTerms);
451
 
452
        final Element eSpecifiedTradeSettlementHeaderMonetarySummation = new Element("SpecifiedTradeSettlementHeaderMonetarySummation", RAM_NS);
180 ilm 453
        final Element eTotalHT = new Element("LineTotalAmount", RAM_NS);
454
        eTotalHT.setText(this.formatAmount.format(new BigDecimal(rowFacture.getLong("T_HT")).movePointLeft(2)));
455
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalHT);
177 ilm 456
 
180 ilm 457
        final Element eTotalBaseTVA = new Element("TaxBasisTotalAmount", RAM_NS);
458
 
459
        BigDecimal totalBaseTVA = BigDecimal.ZERO;
460
        for (Tax tax : taxes) {
461
            totalBaseTVA = totalBaseTVA.add(tax.basisAmount);
462
        }
463
        eTotalBaseTVA.setText(this.formatAmount.format(totalBaseTVA));
464
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalBaseTVA);
465
 
466
        final Element eTotalTVA = new Element("TaxTotalAmount", RAM_NS);
467
        eTotalTVA.setAttribute("currencyID", "EUR");
468
        eTotalTVA.setText(this.formatAmount.format(new BigDecimal(rowFacture.getLong("T_TVA")).movePointLeft(2)));
469
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalTVA);
470
 
471
        final Element eTotalTTC = new Element("GrandTotalAmount", RAM_NS);
472
        BigDecimal totalTTC = new BigDecimal(rowFacture.getLong("T_TTC")).movePointLeft(2);
473
        eTotalTTC.setText(this.formatAmount.format(totalTTC));
474
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalTTC);
475
 
476
        final Element eTotalPrepaid = new Element("TotalPrepaidAmount", RAM_NS);
477
        BigDecimal netApayer = new BigDecimal(rowFacture.getLong("NET_A_PAYER")).movePointLeft(2);
478
        eTotalPrepaid.setText(this.formatAmount.format(totalTTC.subtract(netApayer)));
479
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalPrepaid);
480
 
481
        final Element eTotalDue = new Element("DuePayableAmount", RAM_NS);
482
        eTotalDue.setText(this.formatAmount.format(netApayer));
483
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalDue);
484
 
177 ilm 485
        // Total HT
486
        // <ram:LineTotalAmount>624.90</ram:LineTotalAmount>
487
        // Total HT sur leque est appliqué la TVA
488
        // <ram:TaxBasisTotalAmount>624.90</ram:TaxBasisTotalAmount>
489
        // Total des TVA
490
        // <ram:TaxTotalAmount currencyID="EUR">46.25</ram:TaxTotalAmount>
491
        // Total TTC
492
        // <ram:GrandTotalAmount>671.15</ram:GrandTotalAmount>
493
        // Montant déjà payé
494
        // <ram:TotalPrepaidAmount>201.00</ram:TotalPrepaidAmount>
495
        // Reste à payer
496
        // <ram:DuePayableAmount>470.15</ram:DuePayableAmount>
497
 
498
        eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradeSettlementHeaderMonetarySummation);
499
 
500
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeSettlement);
501
 
502
    }
503
 
180 ilm 504
    private void addBuyerInfo(final Element eApplicableHeaderTradeAgreement, final SQLRowAccessor rowFacture) {
505
 
506
        SQLRowAccessor client = rowFacture.getForeign("ID_CLIENT");
507
        SQLRowAccessor clientGestion = client;
508
        if (this.useCommonClient) {
509
            client = client.getForeign("ID_CLIENT");
510
        }
511
        final SQLRowAccessor adr;
512
        if (!rowFacture.isForeignEmpty("ID_ADRESSE")) {
513
            adr = rowFacture.getForeign("ID_ADRESSE");
514
        } else if (!clientGestion.isForeignEmpty("ID_ADRESSE_F")) {
515
            adr = clientGestion.getForeign("ID_ADRESSE_F");
516
        } else {
517
            adr = client.getForeign("ID_ADRESSE");
518
        }
519
 
177 ilm 520
        // Acheteur
180 ilm 521
        String buyerName = client.getString("NOM");
522
        String buyerSIRET = client.getString("SIRET");
523
        String buyerVAT = client.getString("NUMERO_TVA");
524
        String buyerContactName = client.getString("RESPONSABLE");
525
        String buyerPhone = client.getString("TEL");
526
        String buyerEmail = client.getString("MAIL");
527
        String buyerAddrL1 = adr.getString("RUE");
177 ilm 528
        String buyerAddrL2 = "";
529
        String buyerAddrL3 = "";
180 ilm 530
        String buyerPostalCode = adr.getString("CODE_POSTAL");
531
        String buyerCity = adr.getString("VILLE");
532
        String buyerCountryCode = resolveCountryCode(adr.getString("PAYS"));
177 ilm 533
 
534
        final Element eBuyerTradeParty = new Element("BuyerTradeParty", RAM_NS);
535
        this.addValue(eBuyerTradeParty, new Element("Name", RAM_NS), buyerName);
536
 
537
        final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS);
538
        Element eSpecifiedLegalOrganizationId = new Element("ID", RAM_NS);
539
        eSpecifiedLegalOrganizationId.setAttribute("schemeID", "0002");
540
        eSpecifiedLegalOrganizationId.setText(buyerSIRET);
541
        eSpecifiedLegalOrganization.addContent(eSpecifiedLegalOrganizationId);
542
        eBuyerTradeParty.addContent(eSpecifiedLegalOrganization);
543
        // Contact
544
        final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS);
545
        addValue(eDefinedTradeContact, new Element("PersonName", RAM_NS), buyerContactName);
546
        final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS);
547
        addValue(eTelephoneUniversalCommunication, new Element("CompleteNumber", RAM_NS), buyerPhone);
548
        eDefinedTradeContact.addContent(eTelephoneUniversalCommunication);
549
        final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS);
550
        final Element eURIID = new Element("URIID", RAM_NS);
551
        eURIID.setAttribute("schemeID", "SMTP");
552
        eURIID.setText(buyerEmail);
553
        eEmailURIUniversalCommunication.addContent(eURIID);
554
        eDefinedTradeContact.addContent(eEmailURIUniversalCommunication);
555
        eBuyerTradeParty.addContent(eDefinedTradeContact);
556
        // Adresse postale
557
        final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS);
180 ilm 558
        addValue(ePostalTradeAddress, new Element("PostcodeCode", RAM_NS), buyerPostalCode);
559
        addValue(ePostalTradeAddress, new Element("LineOne", RAM_NS), buyerAddrL1);
177 ilm 560
        if (buyerAddrL2 != null && !buyerAddrL2.trim().isEmpty()) {
180 ilm 561
            addValue(ePostalTradeAddress, new Element("LineTwo", RAM_NS), buyerAddrL2);
177 ilm 562
        }
563
        if (buyerAddrL3 != null && !buyerAddrL3.trim().isEmpty()) {
180 ilm 564
            addValue(ePostalTradeAddress, new Element("LineThree", RAM_NS), buyerAddrL3);
177 ilm 565
        }
180 ilm 566
        addValue(ePostalTradeAddress, new Element("CityName", RAM_NS), buyerCity);
567
        addValue(ePostalTradeAddress, new Element("CountryID", RAM_NS), buyerCountryCode);
177 ilm 568
 
569
        eBuyerTradeParty.addContent(ePostalTradeAddress);
570
 
180 ilm 571
        if (buyerVAT != null && buyerVAT.trim().length() > 0) {
572
            // TVA
573
            final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS);
574
            final Element eSpecifiedTaxRegistrationId = new Element("ID", RAM_NS);
575
            eSpecifiedTaxRegistrationId.setAttribute("schemeID", "VA");
576
            eSpecifiedTaxRegistrationId.setText(buyerVAT);
577
            eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationId);
578
            eBuyerTradeParty.addContent(eSpecifiedTaxRegistration);
579
        }
177 ilm 580
        eApplicableHeaderTradeAgreement.addContent(eBuyerTradeParty);
581
    }
582
 
180 ilm 583
    private void addSupplierInfo(final Element eApplicableHeaderTradeAgreement, SQLRowAccessor rowSociete) {
584
        String supplierName = rowSociete.getString("NOM");
585
        String supplierSIRET = rowSociete.getString("NUM_SIRET");
586
        String supplierContactName = "";
587
        String supplierContactPhone = rowSociete.getString("NUM_TEL");
588
        String supplierContactEmail = rowSociete.getString("MAIL");
589
        SQLRowAccessor adr = rowSociete.getForeign("ID_ADRESSE_COMMON");
590
        String supplierAddrL1 = adr.getString("RUE");
177 ilm 591
        String supplierAddrL2 = "";
592
        String supplierAddrL3 = "";
180 ilm 593
        String supplierAddrPostalCode = adr.getString("CODE_POSTAL");
594
        String supplierAddrCityName = adr.getString("VILLE");
595
        String supplierAddrCountryID = resolveCountryCode(adr.getString("PAYS"));
596
        String supplierNumTVA = rowSociete.getString("NUM_NII");
177 ilm 597
        // Vendeur
598
        final Element eSellerTradeParty = new Element("SellerTradeParty", RAM_NS);
599
        addValue(eSellerTradeParty, new Element("Name", RAM_NS), supplierName);
600
 
601
        final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS);
602
        final Element eID = new Element("ID", RAM_NS);
603
        eID.setAttribute("schemeID", "0002");
604
        eID.setText(supplierSIRET);
605
        eSpecifiedLegalOrganization.addContent(eID);
606
        eSellerTradeParty.addContent(eSpecifiedLegalOrganization);
607
 
608
        final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS);
609
        final Element ePersonName = new Element("PersonName", RAM_NS);
610
        ePersonName.setText(supplierContactName);
611
        eDefinedTradeContact.addContent(ePersonName);
612
 
613
        final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS);
614
        final Element eCompleteNumber = new Element("CompleteNumber", RAM_NS);
615
        eCompleteNumber.setText(supplierContactPhone);
616
        eTelephoneUniversalCommunication.addContent(eCompleteNumber);
617
        eDefinedTradeContact.addContent(eTelephoneUniversalCommunication);
618
 
619
        final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS);
620
        final Element eURIID = new Element("URIID", RAM_NS);
621
        eURIID.setAttribute("schemeID", "SMTP");
622
        eURIID.setText(supplierContactEmail);
623
        eEmailURIUniversalCommunication.addContent(eURIID);
624
        eDefinedTradeContact.addContent(eEmailURIUniversalCommunication);
625
        eSellerTradeParty.addContent(eDefinedTradeContact);
626
 
627
        final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS);
180 ilm 628
        addValue(ePostalTradeAddress, new Element("PostcodeCode", RAM_NS), supplierAddrPostalCode);
177 ilm 629
        addValue(ePostalTradeAddress, new Element("LineOne", RAM_NS), supplierAddrL1);
630
        if (supplierAddrL2 != null && !supplierAddrL2.trim().isEmpty()) {
631
            addValue(ePostalTradeAddress, new Element("LineTwo", RAM_NS), supplierAddrL2);
632
        }
633
        if (supplierAddrL3 != null && !supplierAddrL3.trim().isEmpty()) {
634
            addValue(ePostalTradeAddress, new Element("LineThree", RAM_NS), supplierAddrL3);
635
        }
636
        addValue(ePostalTradeAddress, new Element("CityName", RAM_NS), supplierAddrCityName);
637
        addValue(ePostalTradeAddress, new Element("CountryID", RAM_NS), supplierAddrCountryID);
638
 
639
        eSellerTradeParty.addContent(ePostalTradeAddress);
640
 
641
        final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS);
642
        final Element eSpecifiedTaxRegistrationID = new Element("ID", RAM_NS);
643
        eSpecifiedTaxRegistrationID.setAttribute("schemeID", "VA");
644
        eSpecifiedTaxRegistrationID.setText(supplierNumTVA);
645
        eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationID);
646
        eSellerTradeParty.addContent(eSpecifiedTaxRegistration);
647
 
648
        eApplicableHeaderTradeAgreement.addContent(eSellerTradeParty);
649
    }
650
 
651
    private void addIncludedNote(String content, String code, Element ed) {
652
        final Element e = new Element("IncludedNote", RAM_NS);
653
        final Element eContent = new Element("Content", RAM_NS);
654
        eContent.setText(content);
655
        e.addContent(eContent);
656
        final Element eCode = new Element("SubjectCode", RAM_NS);
657
        eCode.setText(code);
658
        e.addContent(eCode);
659
        ed.addContent(e);
660
    }
661
 
662
    private void addDateTime(Date date, Element eTime) {
663
        final Element e = new Element("DateTimeString", UDT_NS);
664
        // From the doc : Only value "102" ...
665
        e.setAttribute("format", "102");
666
        SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
667
        e.setText(s.format(date));
668
        eTime.addContent(e);
669
    }
670
 
671
    boolean checkEAN13(String code) {
672
        if (code == null || code.length() != 13) {
673
            return false;
674
        }
182 ilm 675
        try {
676
            int checkdigit = 0;
677
            for (int i = 1; i < 12; i += 2) {
678
                checkdigit += Integer.valueOf(code.substring(i, i + 1));
679
            }
680
            checkdigit *= 3;
681
            for (int i = 0; i < 11; i += 2) {
682
                checkdigit += Integer.valueOf(code.substring(i, i + 1));
683
            }
684
            checkdigit %= 10;
685
            if (checkdigit != 0) {
686
                checkdigit = 10 - checkdigit;
687
            }
688
            return Integer.valueOf(code.substring(12, 13)).intValue() == checkdigit;
689
        } catch (Exception e) {
690
            // if not digits, parse error
691
            return false;
177 ilm 692
        }
693
    }
180 ilm 694
 
695
    private String resolveCountryCode(String pays) {
696
        if (pays == null || pays.trim().length() == 0) {
697
            return "FR";
698
        } else if (pays.toLowerCase().equals("france")) {
699
            return "FR";
700
        } else if (pays.toLowerCase().equals("fr")) {
701
            return "FR";
702
        } else if (pays.toLowerCase().equals("polska")) {
703
            return "PL";
704
        } else if (pays.toLowerCase().equals("pologne")) {
705
            return "PL";
706
        } else if (pays.toLowerCase().equals("pl")) {
707
            return "PL";
708
        } else if (pays.toLowerCase().equals("allemagne")) {
709
            return "DE";
710
        } else if (pays.toLowerCase().equals("de")) {
711
            return "DE";
712
        } else if (pays.toLowerCase().equals("deutschland")) {
713
            return "DE";
714
        } else if (pays.toLowerCase().equals("italie")) {
715
            return "IT";
716
        } else if (pays.toLowerCase().equals("italy")) {
717
            return "IT";
718
        } else if (pays.toLowerCase().equals("italia")) {
719
            return "IT";
720
        } else if (pays.toLowerCase().equals("it")) {
721
            return "IT";
722
        } else if (pays.toLowerCase().equals("espagne")) {
723
            return "SP";
724
        } else if (pays.toLowerCase().equals("spain")) {
725
            return "SP";
726
        } else if (pays.toLowerCase().equals("sp")) {
727
            return "SP";
728
        } else if (pays.toLowerCase().equals("luxembourg")) {
729
            return "LU";
730
        } else if (pays.toLowerCase().equals("lu")) {
731
            return "LU";
732
        } else if (pays.toLowerCase().equals("portugal")) {
733
            return "PT";
734
        } else if (pays.toLowerCase().equals("pt")) {
735
            return "PT";
736
        } else if (pays.toLowerCase().equals("belgique")) {
737
            return "BE";
738
        } else if (pays.toLowerCase().equals("belgium")) {
739
            return "BE";
740
        } else if (pays.toLowerCase().equals("be")) {
741
            return "BE";
742
        } else {
743
            return "";
744
        }
745
    }
177 ilm 746
}